Search Results

Search found 5586 results on 224 pages for 'global illumination'.

Page 39/224 | < Previous Page | 35 36 37 38 39 40 41 42 43 44 45 46  | Next Page >

  • MySQL Syslog Audit Plugin

    - by jonathonc
    This post shows the construction process of the Syslog Audit plugin that was presented at MySQL Connect 2012. It is based on an environment that has the appropriate development tools enabled including gcc,g++ and cmake. It also assumes you have downloaded the MySQL source code (5.5.16 or higher) and have compiled and installed the system into the /usr/local/mysql directory ready for use.  The information provided below is designed to show the different components that make up a plugin, and specifically an audit type plugin, and how it comes together to be used within the MySQL service. The MySQL Reference Manual contains information regarding the plugin API and how it can be used, so please refer there for more detailed information. The code in this post is designed to give the simplest information necessary, so handling every return code, managing race conditions etc is not part of this example code. Let's start by looking at the most basic implementation of our plugin code as seen below: /*    Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.    Author:  Jonathon Coombes    Licence: GPL    Description: An auditing plugin that logs to syslog and                 can adjust the loglevel via the system variables. */ #include <stdio.h> #include <string.h> #include <mysql/plugin_audit.h> #include <syslog.h> There is a commented header detailing copyright/licencing and meta-data information and then the include headers. The two important include statements for our plugin are the syslog.h plugin, which gives us the structures for syslog, and the plugin_audit.h include which has details regarding the audit specific plugin api. Note that we do not need to include the general plugin header plugin.h, as this is done within the plugin_audit.h file already. To implement our plugin within the current implementation we need to add it into our source code and compile. > cd /usr/local/src/mysql-5.5.28/plugin > mkdir audit_syslog > cd audit_syslog A simple CMakeLists.txt file is created to manage the plugin compilation: MYSQL_ADD_PLUGIN(audit_syslog audit_syslog.cc MODULE_ONLY) Run the cmake  command at the top level of the source and then you can compile the plugin using the 'make' command. This results in a compiled audit_syslog.so library, but currently it is not much use to MySQL as there is no level of api defined to communicate with the MySQL service. Now we need to define the general plugin structure that enables MySQL to recognise the library as a plugin and be able to install/uninstall it and have it show up in the system. The structure is defined in the plugin.h file in the MySQL source code.  /*   Plugin library descriptor */ mysql_declare_plugin(audit_syslog) {   MYSQL_AUDIT_PLUGIN,           /* plugin type                    */   &audit_syslog_descriptor,     /* descriptor handle               */   "audit_syslog",               /* plugin name                     */   "Author Name",                /* author                          */   "Simple Syslog Audit",        /* description                     */   PLUGIN_LICENSE_GPL,           /* licence                         */   audit_syslog_init,            /* init function     */   audit_syslog_deinit,          /* deinit function */   0x0001,                       /* plugin version                  */   NULL,                         /* status variables        */   NULL,                         /* system variables                */   NULL,                         /* no reserves                     */   0,                            /* no flags                        */ } mysql_declare_plugin_end; The general plugin descriptor above is standard for all plugin types in MySQL. The plugin type is defined along with the init/deinit functions and interface methods into the system for sharing information, and various other metadata information. The descriptors have an internally recognised version number so that plugins can be matched against the api on the running server. The other details are usually related to the type-specific methods and structures to implement the plugin. Each plugin has a type-specific descriptor as well which details how the plugin is implemented for the specific purpose of that plugin type. /*   Plugin type-specific descriptor */ static struct st_mysql_audit audit_syslog_descriptor= {   MYSQL_AUDIT_INTERFACE_VERSION,                        /* interface version    */   NULL,                                                 /* release_thd function */   audit_syslog_notify,                                  /* notify function      */   { (unsigned long) MYSQL_AUDIT_GENERAL_CLASSMASK |                     MYSQL_AUDIT_CONNECTION_CLASSMASK }  /* class mask           */ }; In this particular case, the release_thd function has not been defined as it is not required. The important method for auditing is the notify function which is activated when an event occurs on the system. The notify function is designed to activate on an event and the implementation will determine how it is handled. For the audit_syslog plugin, the use of the syslog feature sends all events to the syslog for recording. The class mask allows us to determine what type of events are being seen by the notify function. There are currently two major types of event: 1. General Events: This includes general logging, errors, status and result type events. This is the main one for tracking the queries and operations on the database. 2. Connection Events: This group is based around user logins. It monitors connections and disconnections, but also if somebody changes user while connected. With most audit plugins, the principle behind the plugin is to track changes to the system over time and counters can be an important part of this process. The next step is to define and initialise the counters that are used to track the events in the service. There are 3 counters defined in total for our plugin - the # of general events, the # of connection events and the total number of events.  static volatile int total_number_of_calls; /* Count MYSQL_AUDIT_GENERAL_CLASS event instances */ static volatile int number_of_calls_general; /* Count MYSQL_AUDIT_CONNECTION_CLASS event instances */ static volatile int number_of_calls_connection; The init and deinit functions for the plugin are there to be called when the plugin is activated and when it is terminated. These offer the best option to initialise the counters for our plugin: /*  Initialize the plugin at server start or plugin installation. */ static int audit_syslog_init(void *arg __attribute__((unused))) {     openlog("mysql_audit:",LOG_PID|LOG_PERROR|LOG_CONS,LOG_USER);     total_number_of_calls= 0;     number_of_calls_general= 0;     number_of_calls_connection= 0;     return(0); } The init function does a call to openlog to initialise the syslog functionality. The parameters are the service to log under ("mysql_audit" in this case), the syslog flags and the facility for the logging. Then each of the counters are initialised to zero and a success is returned. If the init function is not defined, it will return success by default. /*  Terminate the plugin at server shutdown or plugin deinstallation. */ static int audit_syslog_deinit(void *arg __attribute__((unused))) {     closelog();     return(0); } The deinit function will simply close our syslog connection and return success. Note that the syslog functionality is part of the glibc libraries and does not require any external factors.  The function names are what we define in the general plugin structure, so these have to match otherwise there will be errors. The next step is to implement the event notifier function that was defined in the type specific descriptor (audit_syslog_descriptor) which is audit_syslog_notify. /* Event notifier function */ static void audit_syslog_notify(MYSQL_THD thd __attribute__((unused)), unsigned int event_class, const void *event) { total_number_of_calls++; if (event_class == MYSQL_AUDIT_GENERAL_CLASS) { const struct mysql_event_general *event_general= (const struct mysql_event_general *) event; number_of_calls_general++; syslog(audit_loglevel,"%lu: User: %s Command: %s Query: %s\n", event_general->general_thread_id, event_general->general_user, event_general->general_command, event_general->general_query ); } else if (event_class == MYSQL_AUDIT_CONNECTION_CLASS) { const struct mysql_event_connection *event_connection= (const struct mysql_event_connection *) event; number_of_calls_connection++; syslog(audit_loglevel,"%lu: User: %s@%s[%s] Event: %d Status: %d\n", event_connection->thread_id, event_connection->user, event_connection->host, event_connection->ip, event_connection->event_subclass, event_connection->status ); } }   In the case of an event, the notifier function is called. The first step is to increment the total number of events that have occurred in our database.The event argument is then cast into the appropriate event structure depending on the class type, of general event or connection event. The event type counters are incremented and details are sent via the syslog() function out to the system log. There are going to be different line formats and information returned since the general events have different data compared to the connection events, even though some of the details overlap, for example, user, thread id, host etc. On compiling the code now, there should be no errors and the resulting audit_syslog.so can be loaded into the server and ready to use. Log into the server and type: mysql> INSTALL PLUGIN audit_syslog SONAME 'audit_syslog.so'; This will install the plugin and will start updating the syslog immediately. Note that the audit plugin attaches to the immediate thread and cannot be uninstalled while that thread is active. This means that you cannot run the UNISTALL command until you log into a different connection (thread) on the server. Once the plugin is loaded, the system log will show output such as the following: Oct  8 15:33:21 machine mysql_audit:[8337]: 87: User: root[root] @ localhost []  Command: (null)  Query: INSTALL PLUGIN audit_syslog SONAME 'audit_syslog.so' Oct  8 15:33:21 machine mysql_audit:[8337]: 87: User: root[root] @ localhost []  Command: Query  Query: INSTALL PLUGIN audit_syslog SONAME 'audit_syslog.so' Oct  8 15:33:40 machine mysql_audit:[8337]: 87: User: root[root] @ localhost []  Command: (null)  Query: show tables Oct  8 15:33:40 machine mysql_audit:[8337]: 87: User: root[root] @ localhost []  Command: Query  Query: show tables Oct  8 15:33:43 machine mysql_audit:[8337]: 87: User: root[root] @ localhost []  Command: (null)  Query: select * from t1 Oct  8 15:33:43 machine mysql_audit:[8337]: 87: User: root[root] @ localhost []  Command: Query  Query: select * from t1 It appears that two of each event is being shown, but in actuality, these are two separate event types - the result event and the status event. This could be refined further by changing the audit_syslog_notify function to handle the different event sub-types in a different manner.  So far, it seems that the logging is working with events showing up in the syslog output. The issue now is that the counters created earlier to track the number of events by type are not accessible when the plugin is being run. Instead there needs to be a way to expose the plugin specific information to the service and vice versa. This could be done via the information_schema plugin api, but for something as simple as counters, the obvious choice is the system status variables. This is done using the standard structure and the declaration: /*  Plugin status variables for SHOW STATUS */ static struct st_mysql_show_var audit_syslog_status[]= {   { "Audit_syslog_total_calls",     (char *) &total_number_of_calls,     SHOW_INT },   { "Audit_syslog_general_events",     (char *) &number_of_calls_general,     SHOW_INT },   { "Audit_syslog_connection_events",     (char *) &number_of_calls_connection,     SHOW_INT },   { 0, 0, SHOW_INT } };   The structure is simply the name that will be displaying in the mysql service, the address of the associated variables, and the data type being used for the counter. It is finished with a blank structure to show that there are no more variables. Remember that status variables may have the same name for variables from other plugin, so it is considered appropriate to add the plugin name at the start of the status variable name to avoid confusion. Looking at the status variables in the mysql client shows something like the following: mysql> show global status like "audit%"; +--------------------------------+-------+ | Variable_name                  | Value | +--------------------------------+-------+ | Audit_syslog_connection_events | 1     | | Audit_syslog_general_events    | 2     | | Audit_syslog_total_calls       | 3     | +--------------------------------+-------+ 3 rows in set (0.00 sec) The final connectivity piece for the plugin is to allow the interactive change of the logging level between the plugin and the system. This requires the ability to send changes via the mysql service through to the plugin. This is done using the system variables interface and defining a single variable to keep track of the active logging level for the facility. /* Plugin system variables for SHOW VARIABLES */ static MYSQL_SYSVAR_STR(loglevel, audit_loglevel,                         PLUGIN_VAR_RQCMDARG,                         "User can specify the log level for auditing",                         audit_loglevel_check, audit_loglevel_update, "LOG_NOTICE"); static struct st_mysql_sys_var* audit_syslog_sysvars[] = {     MYSQL_SYSVAR(loglevel),     NULL }; So now the system variable 'loglevel' is defined for the plugin and associated to the global variable 'audit_loglevel'. The check or validation function is defined to make sure that no garbage values are attempted in the update of the variable. The update function is used to save the new value to the variable. Note that the audit_syslog_sysvars structure is defined in the general plugin descriptor to associate the link between the plugin and the system and how much they interact. Next comes the implementation of the validation function and the update function for the system variable. It is worth noting that if you have a simple numeric such as integers for the variable types, the validate function is often not required as MySQL will handle the automatic check and validation of simple types. /* longest valid value */ #define MAX_LOGLEVEL_SIZE 100 /* hold the valid values */ static const char *possible_modes[]= { "LOG_ERROR", "LOG_WARNING", "LOG_NOTICE", NULL };  static int audit_loglevel_check(     THD*                        thd,    /*!< in: thread handle */     struct st_mysql_sys_var*    var,    /*!< in: pointer to system                                         variable */     void*                       save,   /*!< out: immediate result                                         for update function */     struct st_mysql_value*      value)  /*!< in: incoming string */ {     char buff[MAX_LOGLEVEL_SIZE];     const char *str;     const char **found;     int length;     length= sizeof(buff);     if (!(str= value->val_str(value, buff, &length)))         return 1;     /*         We need to return a pointer to a locally allocated value in "save".         Here we pick to search for the supplied value in an global array of         constant strings and return a pointer to one of them.         The other possiblity is to use the thd_alloc() function to allocate         a thread local buffer instead of the global constants.     */     for (found= possible_modes; *found; found++)     {         if (!strcmp(*found, str))         {             *(const char**)save= *found;             return 0;         }     }     return 1; } The validation function is simply to take the value being passed in via the SET GLOBAL VARIABLE command and check if it is one of the pre-defined values allowed  in our possible_values array. If it is found to be valid, then the value is assigned to the save variable ready for passing through to the update function. static void audit_loglevel_update(     THD*                        thd,        /*!< in: thread handle */     struct st_mysql_sys_var*    var,        /*!< in: system variable                                             being altered */     void*                       var_ptr,    /*!< out: pointer to                                             dynamic variable */     const void*                 save)       /*!< in: pointer to                                             temporary storage */ {     /* assign the new value so that the server can read it */     *(char **) var_ptr= *(char **) save;     /* assign the new value to the internal variable */     audit_loglevel= *(char **) save; } Since all the validation has been done already, the update function is quite simple for this plugin. The first part is to update the system variable pointer so that the server can read the value. The second part is to update our own global plugin variable for tracking the value. Notice that the save variable is passed in as a void type to allow handling of various data types, so it must be cast to the appropriate data type when assigning it to the variables. Looking at how the latest changes affect the usage of the plugin and the interaction within the server shows: mysql> show global variables like "audit%"; +-----------------------+------------+ | Variable_name         | Value      | +-----------------------+------------+ | audit_syslog_loglevel | LOG_NOTICE | +-----------------------+------------+ 1 row in set (0.00 sec) mysql> set global audit_syslog_loglevel="LOG_ERROR"; Query OK, 0 rows affected (0.00 sec) mysql> show global status like "audit%"; +--------------------------------+-------+ | Variable_name                  | Value | +--------------------------------+-------+ | Audit_syslog_connection_events | 1     | | Audit_syslog_general_events    | 11    | | Audit_syslog_total_calls       | 12    | +--------------------------------+-------+ 3 rows in set (0.00 sec) mysql> show global variables like "audit%"; +-----------------------+-----------+ | Variable_name         | Value     | +-----------------------+-----------+ | audit_syslog_loglevel | LOG_ERROR | +-----------------------+-----------+ 1 row in set (0.00 sec)   So now we have a plugin that will audit the events on the system and log the details to the system log. It allows for interaction to see the number of different events within the server details and provides a mechanism to change the logging level interactively via the standard system methods of the SET command. A more complex auditing plugin may have more detailed code, but each of the above areas is what will be involved and simply expanded on to add more functionality. With the above skeleton code, it is now possible to create your own audit plugins to implement your own auditing requirements. If, however, you are not of the coding persuasion, then you could always consider the option of the MySQL Enterprise Audit plugin that is available to purchase.

    Read the article

  • Universities 2030: Learning from the Past to Anticipate the Future

    - by Mohit Phogat
    What will the landscape of international higher education look like a generation from now? What challenges and opportunities lie ahead for universities, especially “global” research universities? And what can university leaders do to prepare for the major social, economic, and political changes—both foreseen and unforeseen—that may be on the horizon? The nine essays in this collection proceed on the premise that one way to envision “the global university” of the future is to explore how earlier generations of university leaders prepared for “global” change—or at least responded to change—in the past. As the essays in this collection attest, many of the patterns associated with contemporary “globalization” or “internationalization” are not new; similar processes have been underway for a long time (some would say for centuries).[1] A comparative-historical look at universities’ responses to global change can help today’s higher-education leaders prepare for the future. Written by leading historians of higher education from around the world, these nine essays identify “key moments” in the internationalization of higher education: moments when universities and university leaders responded to new historical circumstances by reorienting their relationship with the broader world. Covering more than a century of change—from the late nineteenth century to the early twenty-first—they explore different approaches to internationalization across Europe, Asia, Australia, North America, and South America. Notably, while the choice of historical eras was left entirely open, the essays converged around four periods: the 1880s and the international extension of the “modern research university” model; the 1930s and universities’ attempts to cope with international financial and political crises; the 1960s and universities’ role in an emerging postcolonial international development apparatus; and the 2000s and the rise of neoliberal efforts to reform universities in the name of international economic “competitiveness.” Each of these four periods saw universities adopt new approaches to internationalization in response to major historical-structural changes, and each has clear parallels to today. Among the most important historical-structural challenges that universities confronted were: (1) fluctuating enrollments and funding resources associated with global economic booms and busts; (2) new modes of transportation and communication that facilitated mobility (among students, scholars, and knowledge itself); (3) increasing demands for applied science, technical expertise, and commercial innovation; and (4) ideological reconfigurations accompanying regime changes (e.g., from one internal regime to another, from colonialism to postcolonialism, from the cold war to globalized capitalism, etc.). Like universities today, universities in the past responded to major historical-structural changes by internationalizing: by joining forces across space to meet new expectations and solve problems on an ever-widening scale. Approaches to internationalization have typically built on prior cultural or institutional ties. In general, only when the benefits of existing ties had been exhausted did universities reach out to foreign (or less familiar) partners. As one might expect, this process of “reaching out” has stretched universities’ traditional cultural, political, and/or intellectual bonds and has invariably presented challenges, particularly when national priorities have differed—for example, with respect to curricular programs, governance structures, norms of academic freedom, etc. Strategies of university internationalization that either ignore or downplay cultural, political, or intellectual differences often fail, especially when the pursuit of new international connections is perceived to weaken national ties. If the essays in this collection agree on anything, they agree that approaches to internationalization that seem to “de-nationalize” the university usually do not succeed (at least not for long). Please continue reading the other essays at http://globalhighered.wordpress.com/

    Read the article

  • Entity Framework 4 POCO entities in separate assembly, Dynamic Data Website?

    - by steve.macdonald
    Basically I want to use a dynamic data website to maintain data in an EF4 model where the entities are in their own assembly. Model and context are in another assembly. I tried this http://stackoverflow.com/questions/2282916/entity-framework-4-self-tracking-entities-asp-net-dynamic-data-error but get an "ambiguous match" error from reflection: System.Reflection.AmbiguousMatchException was unhandled by user code Message=Ambiguous match found. Source=mscorlib StackTrace: at System.RuntimeType.GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) at System.Type.GetProperty(String name) at System.Web.DynamicData.ModelProviders.EFTableProvider..ctor(EFDataModelProvider dataModel, EntitySet entitySet, EntityType entityType, Type entityClrType, Type parentEntityClrType, Type rootEntityClrType, String name) at System.Web.DynamicData.ModelProviders.EFDataModelProvider.CreateTableProvider(EntitySet entitySet, EntityType entityType) at System.Web.DynamicData.ModelProviders.EFDataModelProvider..ctor(Object contextInstance, Func1 contextFactory) at System.Web.DynamicData.ModelProviders.SchemaCreator.CreateDataModel(Object contextInstance, Func1 contextFactory) at System.Web.DynamicData.MetaModel.RegisterContext(Func`1 contextFactory, ContextConfiguration configuration) at WebApplication1.Global.RegisterRoutes(RouteCollection routes) in C:\dev\Puffin\Puffin.Prototype.Web\Global.asax.cs:line 42 at WebApplication1.Global.Application_Start(Object sender, EventArgs e) in C:\dev\Puffin\Puffin.Prototype.Web\Global.asax.cs:line 78 InnerException:

    Read the article

  • Glassfish v3 / JNDI entry cannot be found problems!

    - by REMP
    I've been having problems trying to call an EJB's method from a Java Application Client. Here is the code. EJB Remote Interface package com.test; import javax.ejb.Remote; @Remote public interface HelloBeanRemote { public String sayHello(); } EJB package com.test; import javax.ejb.Stateless; @Stateless (name="HelloBeanExample" , mappedName="ejb/HelloBean") public class HelloBean implements HelloBeanRemote { @Override public String sayHello(){ return "hola"; } } Main class (another project) import com.test.HelloBeanRemote; import javax.naming.Context; import javax.naming.InitialContext; public class Main { public void runTest()throws Exception{ Context ctx = new InitialContext(); HelloBeanRemote bean = (HelloBeanRemote)ctx.lookup("java:global/Test/HelloBeanExample!com.test.HelloBeanRemote"); System.out.println(bean.sayHello()); } public static void main(String[] args)throws Exception { Main main = new Main(); main.runTest(); } } Well, what is my problem? JNDI entry for this EJB cannot be found! java.lang.NullPointerException at com.sun.enterprise.naming.impl.SerialContext.getRemoteProvider(SerialContext.java:297) at com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:271) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:430) at javax.naming.InitialContext.lookup(InitialContext.java:392) at testdesktop.Main.runTest(Main.java:22) at testdesktop.Main.main(Main.java:31) Exception in thread "main" javax.naming.NamingException: Lookup failed for 'java:global/Test/HelloBeanExample!com.test.HelloBeanRemote' in SerialContext [Root exception is javax.naming.NamingException: Unable to acquire SerialContextProvider for SerialContext [Root exception is java.lang.NullPointerException]] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:442) at javax.naming.InitialContext.lookup(InitialContext.java:392) at testdesktop.Main.runTest(Main.java:22) at testdesktop.Main.main(Main.java:31) Caused by: javax.naming.NamingException: Unable to acquire SerialContextProvider for SerialContext [Root exception is java.lang.NullPointerException] at com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:276) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:430) ... 3 more Caused by: java.lang.NullPointerException at com.sun.enterprise.naming.impl.SerialContext.getRemoteProvider(SerialContext.java:297) at com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:271) ... 4 more Java Result: 1 I've trying with different JNDI entries but nothing works (I got this entries from NetBeans console): INFO: Portable JNDI names for EJB HelloBeanExample : [java:global/Test/HelloBeanExample, java:global/Test/HelloBeanExample!com.test.HelloBeanRemote] INFO: Glassfish-specific (Non-portable) JNDI names for EJB HelloBeanExample : [ejb/HelloBean, ejb/HelloBean#com.test.HelloBeanRemote] So I tried with the following entries but I got the same exception : java:global/Test/HelloBeanExample java:global/Test/HelloBeanExample!com.test.HelloBeanRemote ejb/HelloBean ejb/HelloBean#com.test.HelloBeanRemote I'm using Netbeans 6.8 and Glassfish v3!

    Read the article

  • Property being immediately reset by ApplicationSetting Property Binding

    - by Slider345
    I have a .net 2.0 windows application written in c#, which currently uses several project settings to store user configurations. The forms in the application are made up of lots of user controls, each of which have properties that need to be set to these project settings. Right now these settings are manually assigned to the user control properties. I was hoping to simplify the code by replacing the manual implementation with ApplicationSettings Property Bindings. However, my first property is not behaving properly at all. The setting is an integer, used to record a port number typed into a text box. The setting is bound to an integer property on a user control, and that property sets the Text property on a TextBox control. When I type a new value into the textbox at runtime, as soon as the textbox loses focus, it is immediately replaced by the original value. A breakpoint on the property shows that it is immediately setting the property to the setting from the properties collection after I set it. Can anyone see what I'm doing wrong? Here's some code: The setting: [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("1000")] public int Port { get{ return ((int)(this["Port"])); } set{ this["Port"] = value; } } The binding: this.ctrlNetworkConfig.DataBindings.Add(new System.Windows.Forms.Binding("PortNumber", global::TestProject.Properties.Settings.Default, "Port", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.ctrlNetworkConfig.PortNumber = global::TestProject.Properties.Settings.Default.Port; And lastly, the property on the user control: public int PortNumber { get{ int port; if(int.TryParse(this.txtPortNumber.Text, out port)) return port; else return 0; } set{ txtPortNumber.Text = value.ToString(); } } Any thoughts? Thanks in advance for your help. EDIT: Sorry about the formatting, trying to correct.

    Read the article

  • Building ARM assembler vorbis decoder lib 'Tremolo' for iPhone

    - by Joachim Bengtsson
    I'm trying to compile Tremolo for iPhone. I've pulled in the files bitwise.c bitwiseARM.s codebook.c dpen.s dsp.c floor0.c floor1.c floor1ARM.s floor_lookup.c framing.c info.c mapping0.c mdct.c mdctARM.s misc.c res012.c into a new target, added the following custom settings: GCC_PREPROCESSOR_DEFINITIONS = _ARM_ASSEM_ GCC_C_LANGUAGE_STANDARD = gnu99 GCC_THUMB_SUPPORT = YES ... but as soon as xcode reaches the first assembler file, bitwiseARM.s, I get errors like these: /tremolo/bitwiseARM.s:3:Unknown pseudo-op: .global /tremolo/bitwiseARM.s:3:Rest of line ignored. 1st junk character valued 111 (o). /tremolo/bitwiseARM.s:4:Unknown pseudo-op: .global /tremolo/bitwiseARM.s:4:Rest of line ignored. 1st junk character valued 111 (o). /tremolo/bitwiseARM.s:5:Unknown pseudo-op: .global /tremolo/bitwiseARM.s:5:Rest of line ignored. 1st junk character valued 111 (o). /tremolo/bitwiseARM.s:6:Unknown pseudo-op: .global /tremolo/bitwiseARM.s:6:Rest of line ignored. 1st junk character valued 111 (o). /tremolo/bitwiseARM.s:11:bad instruction `STMFD r13!,{r10,r11,r14}' /tremolo/bitwiseARM.s:12:bad instruction `LDMIA r0,{r2,r3,r12}' /tremolo/bitwiseARM.s:16:bad instruction `SUBS r2,r2,r1' /tremolo/bitwiseARM.s:17:bad instruction `BLT look_slow' /tremolo/bitwiseARM.s:19:bad instruction `LDR r10,[r3]' The first error I could google, and changing .global to .globl fixed the first errors, but I still get the bad instructions, and I don't get why. Googling for the ARM instruction set, the above instructions look valid to me. I've tried toggling thumb support, and building for just armv7 instead of armv6, but neither helped.

    Read the article

  • LINQ to SQL - Save an entity without creating a new DataContext?

    - by aximili
    I get this error Cannot add an entity with a key that is already in use when I try to save an Item [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Item item) { Global.DataContext.Items.Attach(item); Global.DataContext.SubmitChanges(); return View(item); } That's because I cannot attach the item to the static global DataContext. Is it possible to save an item without creating a new DataContext? (I am very new to LINQ)

    Read the article

  • Why is ExecuteFunction method only available through base.ExecuteFunction in a child class of Object

    - by Matt
    I'm trying to call ObjectContext.ExecuteFunction from my objectcontext object in the repository of my site. The repository is generic, so all I have is an ObjectContext object, rather than one that actually represents my specific one from the Entity Framework. Here's an example of code that was generated that uses the ExecuteFunction method: [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")] public global::System.Data.Objects.ObjectResult<ArtistSearchVariation> FindSearchVariation(string source) { global::System.Data.Objects.ObjectParameter sourceParameter; if ((source != null)) { sourceParameter = new global::System.Data.Objects.ObjectParameter("Source", source); } else { sourceParameter = new global::System.Data.Objects.ObjectParameter("Source", typeof(string)); } return base.ExecuteFunction<ArtistSearchVariation>("FindSearchVariation", sourceParameter); } But what I would like to do is something like this... public class Repository<E, C> : IRepository<E, C>, IDisposable where E : EntityObject where C : ObjectContext { private readonly C _ctx; // ... public ObjectResult<E> ExecuteFunction(string functionName, params[]) { // Create object parameters return _ctx.ExecuteFunction<E>(functionName, /* parameters */) } } Anyone know why I have to call ExecuteFunction from base instead of _ctx? Also, is there any way to do something like I've written out? I would really like to keep my repository generic, but with having to execute stored procedures it's looking more and more difficult... Thanks, Matt

    Read the article

  • Globals are bad! But should I use them in this context?

    - by Matt
    Would setting the $link to my database be one thing that I should use a GLOBAL scope for? In my setting of (lots of functions)...it seems as though having only one variable that is in the global scope would be wise. I am currently using the functions to transfer it back and forth so that way I do not have it in the global scope. But it is a bit of a hindrance to my script. Please advise.

    Read the article

  • How do I store an array of a particular type into my settings file?

    - by joebeazelman
    For some reason, I can't seem to store an array of my class into the settings. Here's the code: var newLink = new Link(); Properties.Settings.Default.Links = new ArrayList(); Properties.Settings.Default.Links.Add(newLink); Properties.Settings.Default.Save(); In my Settings.Designer.cs I specified the field to be an array list: [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.ArrayList Links { get { return ((global::System.Collections.ArrayList)(this["Links"])); } set { this["Links"] = value; } } For some reason, it won't save any of the data even though the Link class is serializable and I've tested it.

    Read the article

  • Strange behavior with Powershell scriptblock variable scope and modules, any suggestions?

    - by DanMan
    NOTE: I'm using PowerShell 2.0 on Windows Vista. I'm trying to add support for specifying build arguments to psake, but I've run into some strange PowerShell variable scoping behavior dealing specifically with calling functions that have been exported using Export-ModuleMember (which is how psake exposes it's main method). Following is a simple PowerShell module to illustrate (named repoCase.psm1): function Test { param( [Parameter(Position=0,Mandatory=0)] [scriptblock]$properties = {} ) $defaults = {$message = "Hello, world!"} Write-Host "Before running defaults, message is: $message" . $defaults #At this point, $message is correctly set to "Hellow, world!" Write-Host "Aftering running defaults, message is: $message" . $properties #At this point, I would expect $message to be set to whatever is passed in, #which in this case is "Hello from poperties!", but it isn't. Write-Host "Aftering running properties, message is: $message" } Export-ModuleMember -Function "Test" To test the module, run the following sequence of commands (be sure you're in the same directory as the repoCase.psm1): Import-Module .\repoCase.psm1 #Note that $message should be null Write-Host "Before execution - In global scope, message is: $message" Test -properties { "Executing properties, message is $message"; $message = "Hello from properties!"; } #Now $message is set to the value from the script block. The script block affected only the global scope. Write-Host "After execution - In global scope, message is: $message" Remove-Module repoCase The behavior I expected was for the script block I passed to Test to affect the local scope of Test. It is being 'dotsourced' in, so any changes it makes should be within the scope of the caller. However, that's not what's happening, it seems to be affecting the scope of where it was declared. Here's the output: Before execution - In global scope, message is: Before running defaults, message is: Aftering running defaults, message is: Hello, world! Executing properties, message is Aftering running properties, message is: Hello, world! After execution - In global scope, message is: Hello from properties! Interestingly, if I don't export Test as a module and instead just declare the function and invoke it, everything works just like I would expect it to. The script block affects only Test's scope, and does not modify the global scope. I'm not a PowerShell guru, but can someone explain this behavior to me?

    Read the article

  • ObjectDataSource typename of a singleton Business object

    - by luppi
    My singleton business object is defined in Global: public class Global : HttpApplication { public static BusinessForm BusinessFormLayer; void Application_Start(object sender, EventArgs e) { FormDalProvider concreteProvider = FormDalProvider.Instance; BusinessForumLayer = new BusinessForum(concreteProvider); } } My page: <asp:ObjectDataSource ID="objThreads" runat="server" SelectMethod="GetForms" SelectCountMethod="GetFormsCount" TypeName="Global.BusinessFormLayer" EnablePaging="true" SortParameterName="sortExpression">

    Read the article

  • Difference between 'scope' and 'namespace'?

    - by katriel
    What is the difference, in general, between the concepts of namespaces and scope? To my understanding, both describe the parts of a program in which a variable/object/method/function will be accessible. I understand that 'scope' tends to be a property of the variable (e.g., "This variable has global scope"), while a 'namespace' is a property of the program (e.g., "A Python function creates a local namespace"). Are there other differences? Global scope vs global namespace addresses a slightly narrower question: global namespaces in C++. http://www.alan-g.me.uk/tutor/tutname.htm states, There are a few very subtle differences between the terms but only a Computer Scientist pedant would argue with you, and for our purposes namespace and scope are identical. What are those subtle differences? Under what circumstances or with which kinds of languages do people use each concept?

    Read the article

  • GLOBALS ARE BAAAAAAADDDD!!!!!

    - by Matt
    HOWEVER! would setting the $link to my database be one thing that I prolly should use a GLOBAL scope for? In my setting of (lots of functions)...it seems as though having only one variable that is on the global scope would be wise. I am currently using the functions to transfer it back and forth so that way I do not have it on global...but it is a bit of a hinder to my script. Please Advise, Thank you. Matt

    Read the article

  • Search for content in functions with regex

    - by Marlun
    Hello, How would I with regular expression search for functions which contains the use of a global variable without running "global $var" first? The files looks like this: class TestClass { function correctFunc() { global $var; $name = $var->name; } function invalidFuncIWantToFind() { $age = $var->user->age; } } I want to find the function names of all the invalidFuncIWantToFind. At work this would have really speeded up our work but I didn't get how to do it.

    Read the article

  • questions about name mangling in C++

    - by Tim
    I am trying to learn and understand name mangling in C++. Here are some questions: (1) From devx When a global function is overloaded, the generated mangled name for each overloaded version is unique. Name mangling is also applied to variables. Thus, a local variable and a global variable with the same user-given name still get distinct mangled names. Are there other examples that are using name mangling, besides overloading functions and same-name global and local variables ? (2) From Wiki The need arises where the language allows different entities to be named with the same identifier as long as they occupy a different namespace (where a namespace is typically defined by a module, class, or explicit namespace directive). I don't quite understand why name mangling is only applied to the cases when the identifiers belong to different namespaces, since overloading functions can be in the same namespace and same-name global and local variables can also be in the same space. How to understand this? Do variables with same name but in different scopes also use name mangling? (3) Does C have name mangling? If it does not, how can it deal with the case when some global and local variables have the same name? C does not have overloading functions, right? Thanks and regards!

    Read the article

  • uneven illuminated images

    - by coul
    How to get rid of uneven illumination from images, that contain text data, usually printed but may be handwritten? It can have some spots of lights because the light reflected while making picture. I've seen the Halcon program's segment_characters function that is doing this work perfectly, but it is not open source. I wish to convert an image to the image that has a constant illumination at background and more dark colored regions of text. So that binarization will be easy and without noise. The text is assumed to be dark colored than it's background. Any ideas?

    Read the article

  • Python 3.3 Webserver restarting problems

    - by IPDGino
    I have made a simple webserver in python, and had some problems with it before as described here: Python (3.3) Webserver script with an interesting error In that question, the answer was to use a While True: loop so that any crashes or errors would be resolved instantly, because it would just start itself again. I've used this for a while, and still want to make the server restart itself every few minutes, but on Linux for some reason it won't work for me. On windows the code below works fine, but on linux it keeps saying Handler class up here ... ... class Server: def __init__(self): self.server_class = HTTPServer self.server_adress = ('MY IP GOES HERE, or localhost', 8080) global httpd httpd = self.server_class(self.server_adress, Handler) self.main() def main(self): if count > 1: global SERVER_UP_SINCE HOUR_CHECK = int(((count - 1) * RESTART_INTERVAL) / 60) SERVER_UPTIME = str(HOUR_CHECK) + " MINUTES" if HOUR_CHECK > 60: minutes = int(HOUR_CHECK % 60) hours = int(HOUR_CHECK // 60) SERVER_UPTIME = ("%s HOURS, %s MINUTES" % (str(hours), str(minutes))) SERVING_ON_ADDR = self.server_adress SERVER_UP_SINCE = str(SERVER_UP_SINCE) SERVER_RESTART_NUMBER = count - 1 print(""" SERVER INFO ------------------------------------- SERVER_UPTIME: %s SERVER_UP_SINCE: %s TOTAL_FILES_SERVED: %d SERVING_ON_ADDR: %s SERVER_RESTART_NUMBER: %s \n\nSERVER HAS RESTARTED """ % (SERVER_UPTIME, SERVER_UP_SINCE, TOTAL_FILES, SERVING_ON_ADDR, SERVER_RESTART_NUMBER)) else: print("SERVER_BOOT=1\nSERVER_ONLINE=TRUE\nRESTART_LOOP=TRUE\nSERVING_ON_ADDR:%s" % str(self.server_adress)) while True: try: httpd.serve_forever() except KeyboardInterrupt: print("Shutting down...") break httpd.shutdown() httpd.socket.close() raise(SystemExit) return def server_restart(): """If you want the restart timer to be longer, replace the number after the RESTART_INTERVAL variable""" global RESTART_INTERVAL RESTART_INTERVAL = 10 threading.Timer(RESTART_INTERVAL, server_restart).start() global count count = count + 1 instance = Server() if __name__ == "__main__": global SERVER_UP_SINCE SERVER_UP_SINCE = strftime("%d-%m-%Y %H:%M:%S", gmtime()) server_restart() Basically, I make a thread to restart it every 10 seconds (For testing purposes) and start the server. After ten seconds it will say File "/home/username/Desktop/Webserver/server.py", line 199, in __init__ httpd = self.server_class(self.server_adress, Handler) File "/usr/lib/python3.3/socketserver.py", line 430, in __init__ self.server_bind() File "/usr/lib/python3.3/http/server.py", line 135, in server_bind socketserver.TCPServer.server_bind(self) File "/usr/lib/python3.3/socketserver.py", line 441, in server_bind self.socket.bind(self.server_address) OSError: [Errno 98] Address already in use As you can see in the except KeyboardInterruption line, I tried everything to make the server stop, and the program stop, but it will NOT stop. But the thing I really want to know is how to make this server able to restart, without giving some wonky errors.

    Read the article

  • Multi-tier applications using L2S, WCF and Base Class

    - by Gena Verdel
    Hi all. One day I decided to build this nice multi-tier application using L2S and WCF. The simplified model is : DataBase-L2S-Wrapper(DTO)-Client Application. The communication between Client and Database is achieved by using Data Transfer Objects which contain entity objects as their properties. abstract public class BaseObject { public virtual IccSystem.iccObjectTypes ObjectICC_Type { get { return IccSystem.iccObjectTypes.unknownType; } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_ID", AutoSync = AutoSync.OnInsert, DbType = "BigInt NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)] [global::System.Runtime.Serialization.DataMemberAttribute(Order = 1)] public virtual long ID { //get; //set; get { return _ID; } set { _ID = value; } } } [DataContract] public class BaseObjectWrapper<T> where T : BaseObject { #region Fields private T _DBObject; #endregion #region Properties [DataMember] public T Entity { get { return _DBObject; } set { _DBObject = value; } } #endregion } Pretty simple, isn't it?. Here's the catch. Each one of the mapped classes contains ID property itself so I decided to override it like this [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Divisions")] [global::System.Runtime.Serialization.DataContractAttribute()] public partial class Division : INotifyPropertyChanging, INotifyPropertyChanged { [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)] [global::System.Runtime.Serialization.DataMemberAttribute(Order=1)] public override long ID { get { return this._ID; } set { if ((this._ID != value)) { this.OnIDChanging(value); this.SendPropertyChanging(); this._ID = value; this.SendPropertyChanged("ID"); this.OnIDChanged(); } } } } Wrapper for division is pretty straightforward as well: public class DivisionWrapper : BaseObjectWrapper<Division> { } It worked pretty well as long as I kept ID values at mapped class and its BaseObject class the same(that's not very good approach, I know, but still) but then this happened: private CentralDC _dc; public bool UpdateDivision(ref DivisionWrapper division) { DivisionWrapper tempWrapper = division; if (division.Entity == null) { return false; } try { Table<Division> table = _dc.Divisions; var q = table.Where(o => o.ID == tempWrapper.Entity.ID); if (q.Count() == 0) { division.Entity._errorMessage = "Unable to locate entity with id " + division.Entity.ID.ToString(); return false; } var realEntity = q.First(); realEntity = division.Entity; _dc.SubmitChanges(); return true; } catch (Exception ex) { division.Entity._errorMessage = ex.Message; return false; } } When trying to enumerate over the in-memory query the following exception occurred: Class member BaseObject.ID is unmapped. Although I'm stating the type and overriding the ID property L2S fails to work. Any suggestions?

    Read the article

  • python: strange behavior about exec statement

    - by ifocus
    exec statement: exec code [ in globals[, locals]] When I execute the following code in python, the result really confused me. Some of the variables were setup into the globals, some were setup into the locals. s = """ # test var define int_v1 = 1 list_v1 = [1, 2, 3] dict_v1 = {1: 'hello', 2:'world', 3:'!'} # test built-in function list_v2 = [float(x) for x in list_v1] len_list_v1 = len(list_v1) # test function define def func(): global g_var, list_v1, dict_v1 print 'access var in globals:' print g_var print 'access var in locals:' for x in list_v1: print dict_v1[x] """ g = {'__builtins__': __builtins__, 'g_var': 'global'} l = {} exec s in g, l print 'globals:', g print 'locals:', l exec 'func()' in g, l the result in python2.6.5: globals: {'__builtins__': <module '__builtin__' (built-in)>, 'dict_v1': {1: 'hello', 2: 'world', 3: '!'}, 'g_var': 'global', 'list_v1': [1, 2, 3]} locals: {'int_v1': 1, 'func': <function func at 0x00ACA270>, 'x': 3, 'len_list_v1': 3, 'list_v2': [1.0, 2.0, 3.0]} access var in globals: global access var in locals: hello world ! And if I want to setup all variables and functions into the locals, and keep the rights of accessing the globals. How to do ?

    Read the article

  • Globals across modules

    - by Coder1
    Wow, this seems so basic, but I can't get it to work. All I need to do is store a global dict which can be accessed and modified from other modules & threads. What's the "best practices" way of achieving this? test.py import testmodule class MyClassA(): def __init__(self, id): self.id = id if __name__ == '__main__': global classa_dict classa_dict = {} classa_dict[1] = MyClassA(1) classa_dict[2] = MyClassA(2) testing = testmodule.TestModule() testmodule.py class TestModule(): def __init__(self): global classa_dict print classa_dict[2] output $ python test.py Traceback (most recent call last): File "test.py", line 13, in <module> testing = testmodule.TestModule() File "/path/to/project/testmodule.py", line 4, in __init__ print classa_dict[2] NameError: global name 'classa_dict' is not defined

    Read the article

  • OSGi bundle imports packages from non-bundle jars: create bundles for them?

    - by John Simmons
    I am new to OSGi, and am using Equinox. I have done several searches and can find no answer to this. The discussion at OSGI - handling 3rd party JARs required by a bundle helps somewhat, but does not fully answer my question. I have obtained a jar file, rabbitmq-client.jar, that is already packaged as an OSGi bundle (with Bundle-Name and other such properties in its MANIFEST.MF), that I would like to install as a bundle. This jar imports packages org.apache.commons.io and org.apache.commons.io.input from commons-io-1.2.jar. The RabbitMQ client 2.7.1 distribution also includes commons-cli-1.1.jar, so I presume that it is required as well. I examined the manifests of these commons jars and found that they do not appear to be packaged as bundles. That is, their manifests have none of the standard bundle properties. My specific question is: if I install rabbitmq-client.jar as a bundle, what is the proper way to get access to the packages that it needs to import from the commons jars? There are only three alternatives that I can think of, without rebuilding rabbitmq-client.jar. The packages from the commons jars are already included in the Equinox global classpath, and rabbitmq-client.jar will get them automatically from there. I must make another bundle with the two commons jars, export the needed packages, and install that bundle in Equinox. I must put these two commons jars in the global classpath when I start Equinox, and they will be available to rabbitmq-client.jar from there. I have read that one normally does not use the global classpath in an OSGi container. I am not clear on whether items from the global classpath are even available when building individual bundle classpaths. However, I note that rabbitmq-client.jar also imports other packages such as javax.net, which I presume come from the global classpath. Or is there some other bundle that exports them? Thanks for any assistance!

    Read the article

  • Trying to add data to sql from link click and return results via jquery or ajax

    - by Jay Schires
    I am not familiar with jquery or ajax, but i do know it is whats needed to perform the action I want. I have created a wordpress plugin that updates a database table based on the users click. Right now it refreshes the page to return the results, but I want to stop the page refresh and return data via ajax I believe. If anyone is interested in helping me figure this out I would be very appreciative or even willing to pay. Thanks! Here is the plugin code: function BoardLikeItGetDelim($postid) { global $wp_rewrite; if($wp_rewrite->using_permalinks()) { if(isset($_GET['mbpost'])) return "?mbpost=".$postid."&"; return "?"; } else { if(isset($_GET['mbpost'])) return "&mbpost=".$postid."&"; return "&"; } } function AddBoardLikeItButton($postid) { global $user_ID; if(isset($_GET['board-like-it-action']) && $_GET['board-like-it-action'] == "like" && $_GET['bpid'] == $postid) BoardLikeItLike($user_ID, $_GET['bpid']); if(isset($_GET['board-like-it-action']) && $_GET['board-like-it-action'] == "unlike" && $_GET['bpid'] == $postid) BoardLikeItUnLike($user_ID, $_GET['bpid']); $num_likes = BoardLikeItGetNumLikes($postid); if(!BoardLikeItIsLiked($user_ID, $postid)) echo "<HREF LINK='".BoardLikeItGetDelim($postid)."board-like-it-action=like&bpid=".$postid."#mngl-board-post-message-".$postid."'>Like</a> ".$num_likes."" . "<br/>"; else echo "<HREF LINK ='".BoardLikeItGetDelim($postid)."board-like-it-action=unlike&bpid=".$postid."#mngl-board-post-message-".$postid."'>Un-Like</a> " . "<br/><span style='display: inline-block; padding: 0px; bottom: -5px; position: relative; border: 0px;'><IMAGE='". get_bloginfo('wpurl')."/wp-content/plugins/board-like-it/top-up.png' /></span><div style='-moz-border-radius: 4px; -khtml-border-radius: 4px; -webkit-border-radius: 4px; font-family: Verdana, Geneva, sans-serif; font-size: 10px; color: #000; background-color: #B8C9DB; width: 90%; margin: 0px; display: block; padding-top: 4px; padding-right: 5px; padding-bottom: 4px; padding-left: 6px;'>" . "<IMAGE='". get_bloginfo('wpurl')."/wp-content/plugins/board-like-it/thumb_up.png'/> " .BoardLikeItShowLikers($postid). "like this." . "</div>"; } function BoardLikeItShowLikers($postid) { global $wpdb; $result = $wpdb->get_var($wpdb->prepare("SELECT `likers` FROM ".BoardLikeItGetDBName()." WHERE `mngl_id` = {$postid}")); $results = explode(',', $result); $names = ""; if($results[0] != "") foreach($results as $r) { $userinfo = get_usermeta($r, 'user_login'); $names .= $userinfo.", "; } return $names; } function BoardLikeItGetNumLikes($postid) { global $wpdb; $result = $wpdb->get_var($wpdb->prepare("SELECT `likers` FROM ".BoardLikeItGetDBName()." WHERE `mngl_id` = {$postid}")); $results = explode(',', $result); if($results[0] != '') return count($results)."<br/><span style='display: inline-block; padding: 0px; bottom: -5px; position: relative; border: 0px;'><IMAGE='". get_bloginfo('wpurl')."/wp-content/plugins/board-like-it/top-up.png' /></span><div style='-moz-border-radius: 4px; -khtml-border-radius: 4px; -webkit-border-radius: 4px; font-family: Verdana, Geneva, sans-serif; font-size: 10px; color: #000; background-color: #B8C9DB; width: 90%; margin: 0px; display: inline-block; border: 0px; padding-top: 0px; padding-right: 5px; padding-bottom: 1px; padding-left: 6px;'>" . "<IMAGE='". get_bloginfo('wpurl')."/wp-content/plugins/board-like-it/thumb_up.png'/> " .BoardLikeItShowLikers($postid). "likes this." . "</div>"; else return ""; } function BoardLikeItLike($user_ID, $postid) { global $wpdb; $likers = array(); $likersnew = array(); $result = $wpdb->get_var($wpdb->prepare("SELECT `likers` FROM ".BoardLikeItGetDBName()." WHERE `mngl_id` = {$postid}")); $results = explode(',',$result); if($results[0] != "") { if(!in_array($user_ID, $results)) $results[] = $user_ID; $likers = implode(',',$results); $wpdb->query($wpdb->prepare("UPDATE ".BoardLikeItGetDBName()." SET `likers` = '{$likers}' WHERE `mngl_id` = {$postid}")); } else { $likersnew[] = $user_ID; $likersnew = implode(',',$likersnew); $wpdb->query($wpdb->prepare("INSERT INTO ".BoardLikeItGetDBName()." (`mngl_id`, `likers`) VALUES ('{$postid}', '{$likersnew}')")); } } function BoardLikeItUnLike($user_ID, $postid) { global $wpdb; $likers = array(); $result = $wpdb->get_var($wpdb->prepare("SELECT `likers` FROM ".BoardLikeItGetDBName()." WHERE `mngl_id` = {$postid}")); $results = explode(',', $result); if(in_array($user_ID, $results)) { $results = BoardLikeItRemoveFromArray($results, $user_ID); if(!empty($results)) { $likers = implode(',', $results); $wpdb->query($wpdb->prepare("UPDATE ".BoardLikeItGetDBName()." SET `likers` = '{$likers}' WHERE `mngl_id` = {$postid}")); } else { $wpdb->query($wpdb->prepare("DELETE FROM ".BoardLikeItGetDBName()." WHERE `mngl_id` = {$postid}")); } } } function BoardLikeItIsLiked($user_ID, $postid) { global $wpdb; $result = $wpdb->get_var($wpdb->prepare("SELECT `likers` FROM ".BoardLikeItGetDBName()." WHERE `mngl_id` = {$postid}")); $results = explode(',', $result); if(in_array($user_ID, $results)) return true; else return false; } function BoardLikeItActivate() { global $wpdb; $charset_collate = ''; if($wpdb->has_cap('collation')) { if(!empty($wpdb->charset)) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; if(!empty($wpdb->collate)) $charset_collate .= " COLLATE $wpdb->collate"; } $table_sql = "CREATE TABLE ".BoardLikeItGetDBName()."( `mngl_id` int(11) NOT NULL, `likers` longtext NOT NULL, PRIMARY KEY (`mngl_id`)) {$charset_collate};"; require_once(ABSPATH.'wp-admin/includes/upgrade.php'); dbDelta($table_sql); } function BoardLikeItGetDBName() { global $wpdb; return $wpdb->prefix."board_like_it"; } function BoardLikeItRemoveFromArray($arr, $key) { $new = array(); foreach($arr as $j => $i) { if($i != $key) $new[] = $i; } return $new; }

    Read the article

  • LINQ to SQL and missing Many to Many EntityRefs

    - by Rick Strahl
    Ran into an odd behavior today with a many to many mapping of one of my tables in LINQ to SQL. Many to many mappings aren’t transparent in LINQ to SQL and it maps the link table the same way the SQL schema has it when creating one. In other words LINQ to SQL isn’t smart about many to many mappings and just treats it like the 3 underlying tables that make up the many to many relationship. Iain Galloway has a nice blog entry about Many to Many relationships in LINQ to SQL. I can live with that – it’s not really difficult to deal with this arrangement once mapped, especially when reading data back. Writing is a little more difficult as you do have to insert into two entities for new records, but nothing that can’t be handled in a small business object method with a few lines of code. When I created a database I’ve been using to experiment around with various different OR/Ms recently I found that for some reason LINQ to SQL was completely failing to map even to the linking table. As it turns out there’s a good reason why it fails, can you spot it below? (read on :-}) Here is the original database layout: There’s an items table, a category table and a link table that holds only the foreign keys to the Items and Category tables for a typical M->M relationship. When these three tables are imported into the model the *look* correct – I do get the relationships added (after modifying the entity names to strip the prefix): The relationship looks perfectly fine, both in the designer as well as in the XML document: <Table Name="dbo.wws_Item_Categories" Member="ItemCategories"> <Type Name="ItemCategory"> <Column Name="ItemId" Type="System.Guid" DbType="uniqueidentifier NOT NULL" CanBeNull="false" /> <Column Name="CategoryId" Type="System.Guid" DbType="uniqueidentifier NOT NULL" CanBeNull="false" /> <Association Name="ItemCategory_Category" Member="Categories" ThisKey="CategoryId" OtherKey="Id" Type="Category" /> <Association Name="Item_ItemCategory" Member="Item" ThisKey="ItemId" OtherKey="Id" Type="Item" IsForeignKey="true" /> </Type> </Table> <Table Name="dbo.wws_Categories" Member="Categories"> <Type Name="Category"> <Column Name="Id" Type="System.Guid" DbType="UniqueIdentifier NOT NULL" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" /> <Column Name="ParentId" Type="System.Guid" DbType="UniqueIdentifier" CanBeNull="true" /> <Column Name="CategoryName" Type="System.String" DbType="NVarChar(150)" CanBeNull="true" /> <Column Name="CategoryDescription" Type="System.String" DbType="NVarChar(MAX)" CanBeNull="true" /> <Column Name="tstamp" AccessModifier="Internal" Type="System.Data.Linq.Binary" DbType="rowversion" CanBeNull="true" IsVersion="true" /> <Association Name="ItemCategory_Category" Member="ItemCategory" ThisKey="Id" OtherKey="CategoryId" Type="ItemCategory" IsForeignKey="true" /> </Type> </Table> However when looking at the code generated these navigation properties (also on Item) are completely missing: [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.wws_Item_Categories")] [global::System.Runtime.Serialization.DataContractAttribute()] public partial class ItemCategory : Westwind.BusinessFramework.EntityBase { private System.Guid _ItemId; private System.Guid _CategoryId; public ItemCategory() { } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ItemId", DbType="uniqueidentifier NOT NULL")] [global::System.Runtime.Serialization.DataMemberAttribute(Order=1)] public System.Guid ItemId { get { return this._ItemId; } set { if ((this._ItemId != value)) { this._ItemId = value; } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CategoryId", DbType="uniqueidentifier NOT NULL")] [global::System.Runtime.Serialization.DataMemberAttribute(Order=2)] public System.Guid CategoryId { get { return this._CategoryId; } set { if ((this._CategoryId != value)) { this._CategoryId = value; } } } } Notice that the Item and Category association properties which should be EntityRef properties are completely missing. They’re there in the model, but the generated code – not so much. So what’s the problem here? The problem – it appears – is that LINQ to SQL requires primary keys on all entities it tracks. In order to support tracking – even of the link table entity – the link table requires a primary key. Real obvious ain’t it, especially since the designer happily lets you import the table and even shows the relationship and implicitly the related properties. Adding an Id field as a Pk to the database and then importing results in this model layout: which properly generates the Item and Category properties into the link entity. It’s ironic that LINQ to SQL *requires* the PK in the middle – the Entity Framework requires that a link table have *only* the two foreign key fields in a table in order to recognize a many to many relation. EF actually handles the M->M relation directly without the intermediate link entity unlike LINQ to SQL. [updated from comments – 12/24/2009] Another approach is to set up both ItemId and CategoryId in the database which shows up in LINQ to SQL like this: This also work in creating the Category and Item fields in the ItemCategory entity. Ultimately this is probably the best approach as it also guarantees uniqueness of the keys and so helps in database integrity. It took me a while to figure out WTF was going on here – lulled by the designer to think that the properties should be when they were not. It’s actually a well documented feature of L2S that each entity in the model requires a Pk but of course that’s easy to miss when the model viewer shows it to you and even the underlying XML model shows the Associations properly. This is one of the issue with L2S of course – you have to play by its rules and once you hit one of those rules there’s no way around them – you’re stuck with what it requires which in this case meant changing the database.© Rick Strahl, West Wind Technologies, 2005-2010Posted in ADO.NET  LINQ  

    Read the article

< Previous Page | 35 36 37 38 39 40 41 42 43 44 45 46  | Next Page >