Search Results

Search found 11001 results on 441 pages for 'native drag drop'.

Page 94/441 | < Previous Page | 90 91 92 93 94 95 96 97 98 99 100 101  | Next Page >

  • JOGL: cannot run java on compiled class file

    - by John Goche
    I am running ubuntu Linux 11.10. I have followed the instructions on the site http://jogamp.org/jogl/www/ and downloaded everything with git to $HOME/jogamp and built everything with ant (although I would have prefered the files installed somewhere under /usr/local). I am trying to run a simple application with JOGL found on the Wikipedia site: http://en.wikipedia.org/wiki/Java_OpenGL In order to compile the file I had to add: export CLASSPATH.:$HOME/jogamp/jogl/build/jogl/classes in order to compile the code. When I run java I get the following: $ java JOGLQuad Exception in thread "main" java.lang.NoClassDefFoundError: javax/media/nativewindow /WindowClosingProtocol at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631) at java.lang.ClassLoader.defineClass(ClassLoader.java:615) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) Caused by: java.lang.ClassNotFoundException: javax.media.nativewindow.WindowClosingProtocol at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) ... 12 more Could not find the main class: JOGLQuad. Program will exit. How do I fix this and where can I find more JOGL code samples that I can compile and run? Thanks, John Goche

    Read the article

  • Single intent to let user take picture OR pick image from gallery in Android

    - by Damian
    I'm developing an app for Android 2.1 upwards. I want to enable my users to select a profile picture within my app (I'm not using the contacts framework). The ideal solution would be to fire an intent that enables the user to select an image from the gallery, but if an appropriate image is not available then use the camera to take a picture (or vice-versa i.e. allow user to take picture but if they know they already have a suitable image already, let them drop into the gallery and pick said image). Currently I can do one or the other but not both. If I go directly into camera mode using MediaStore.ACTION_IMAGE_CAPTURE then there is no option to drop into the gallery. If I go directly to the gallery using Intent.ACTION_PICK then I can pick an image but if I click the camera button (in top right hand corner of gallery) then a new camera intent is fired. So, any picture that is taken is not returned directly to my application. (Sure you can press the back button to drop back into the gallery and select image from there but this is an extra unnecessary step and is not at all intuitive). So is there a way to combine both or am I going to have to offer a menu to do one or the other from within my application? Seems like it would be a common use case...surely I'm missing something?

    Read the article

  • Case Insensitive Ternary Search Tree

    - by Yan Cheng CHEOK
    I had been using Ternary Search Tree for a while, as the data structure to implement a auto complete drop down combo box. Which means, when user type "fo", the drop down combo box will display foo food football The problem is, my current used of Ternary Search Tree is case sensitive. My implementation is as follow. It had been used by real world for around 1++ yeas. Hence, I consider it as quite reliable. My Ternary Search Tree code However, I am looking for a case insensitive Ternary Search Tree, which means, when I type "fo", the drop down combo box will show me foO Food fooTBall Here are some key interface for TST, where I hope the new case insentive TST may have similar interface too. /** * Stores value in the TernarySearchTree. The value may be retrieved using key. * @param key A string that indexes the object to be stored. * @param value The object to be stored in the tree. */ public void put(String key, E value) { getOrCreateNode(key).data = value; } /** * Retrieve the object indexed by key. * @param key A String index. * @return Object The object retrieved from the TernarySearchTree. */ public E get(String key) { TSTNode<E> node = getNode(key); if(node==null) return null; return node.data; } An example of usage is as follow. TSTSearchEngine is using TernarySearchTree as the core backbone. Example usage of Ternary Search Tree // There is stock named microsoft and MICROChip inside stocks ArrayList. TSTSearchEngine<Stock> engine = TSTSearchEngine<Stock>(stocks); // I wish it would return microsoft and MICROCHIP. Currently, it just return microsoft. List<Stock> results = engine.searchAll("micro");

    Read the article

  • Stored procedure using cursor in mySql.

    - by RAVI
    I wrote a stored procedure using cursor in mysql but that procedure is taking 10 second to fetch the result while that result set have only 450 records so, I want to know that why that proedure is taking that much time to fetch tha record. procedure as below: DELIMITER // DROP PROCEDURE IF EXISTS curdemo123// CREATE PROCEDURE curdemo123(IN Branchcode int,IN vYear int,IN vMonth int) BEGIN DECLARE EndOfData,tempamount INT DEFAULT 0; DECLARE tempagent_code,tempplantype,tempsaledate CHAR(12); DECLARE tempspot_rate DOUBLE; DECLARE var1,totalrow INT DEFAULT 1; DECLARE cur1 CURSOR FOR select SQL_CALC_FOUND_ROWS ad.agentCode,ad.planType,ad.amount,ad.date from adplan_detailstbl ad where ad.branchCode=Branchcode and (ad.date between '2009-12-1' and '2009-12-31')order by ad.NUM_ID asc; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET EndOfData = 1; DROP TEMPORARY TABLE IF EXISTS temptable; CREATE TEMPORARY TABLE temptable (agent_code varchar(15), plan_type char(12),sale double,spot_rate double default '0.0', dATE DATE); OPEN cur1; SET totalrow=FOUND_ROWS(); while var1 <= totalrow DO fetch cur1 into tempagent_code,tempplantype,tempamount,tempsaledate; IF((tempplantype='Unit Plan' OR tempplantype='MIP') OR tempplantype='STUP') then select spotRate into tempspot_rate from spot_amount where ((monthCode=vMonth and year=vYear) and ((agentCode=tempagent_code and branchCode=Branchcode) and (planType=tempplantype))); INSERT INTO temptable VALUES(tempagent_code,tempplantype,tempamount,tempspot_rate,tempsaledate); else INSERT INTO temptable(agent_code,plan_type,sale,dATE) VALUES(tempagent_code,tempplantype,tempamount,tempsaledate); END IF; SET var1=var1+1; END WHILE; CLOSE cur1; select * from temptable; DROP TABLE temptable; END // DELIMITER ;

    Read the article

  • Ordering by formula fields in NHibernate

    - by Darin Dimitrov
    Suppose that I have the following mapping with a formula property: <class name="Planet" table="planets"> <id name="Id" column="id"> <generator class="native" /> </id> <!-- somefunc() is a native SQL function --> <property name="Distance" formula="somefunc()" /> </class> I would like to get all planets and order them by the Distance calculated property: var planets = session .CreateCriteria<Planet>() .AddOrder(Order.Asc("Distance")) .List<Planet>(); This is translated to the following query: SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY somefunc() Desired query: SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY formula0 If I set a projection with an alias it works fine: var planets = session .CreateCriteria<Planet>() .SetProjection(Projections.Alias(Projections.Property("Distance"), "dist")) .AddOrder(Order.Asc("dist")) .List<Planet>(); SQL: SELECT somefunc() as formula0 FROM planets ORDER BY formula0 but it populates only the Distance property in the result and I really like to avoid projecting manually over all the other properties of my object (there could be many other properties). Is this achievable with NHibernate? As a bonus I would like to pass parameters to the native somefunc() SQL function. Anything producing the desired SQL is acceptable (replacing the formula field with subselects, etc...), the important thing is to have the calculated Distance property in the resulting object and order by this distance inside SQL.

    Read the article

  • how to fix error in bitmap size exceeds VM budget

    - by narasimha
    hi folks i am working one application image uploading to sdcard i am scaling that sdcard saved into database some times one error is occurs bitmap size exceeds vm budget ouput : 01-11 15:39:51.809: ERROR/AndroidRuntime(6214): Uncaught handler: thread main exiting due to uncaught exception 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): java.lang.OutOfMemoryError: bitmap size exceeds VM budget 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.graphics.BitmapFactory.nativeDecodeByteArray(Native Method) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:384) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:397) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at com.fitzgeraldsoftware.shout.presentationLayer.Shout.onActivityResult(Shout.java:1653) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.app.Activity.dispatchActivityResult(Activity.java:3624) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.app.ActivityThread.deliverResults(ActivityThread.java:3220) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3266) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.app.ActivityThread.access$2600(ActivityThread.java:116) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.os.Handler.dispatchMessage(Handler.java:99) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.os.Looper.loop(Looper.java:123) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at android.app.ActivityThread.main(ActivityThread.java:4203) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at java.lang.reflect.Method.invokeNative(Native Method) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at java.lang.reflect.Method.invoke(Method.java:521) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 01-11 15:39:51.979: ERROR/AndroidRuntime(6214): at dalvik.system.NativeStart.main(Native Method) how can fix the error please forward some solution thanks in advance

    Read the article

  • unique items from an observableArray of object properties

    - by Joe
    I'm trying to extract unique properties from a knockout.js observableArray of objects, to populate a drop menu. Being new to knockout, I'm really struggling with this! I want to iterate over a contacts list, and populate a drop menu with a unique value from each person object within the observableArray. So in my code example below, I wish to populate my drop menu with a list of people 'type' - family, friend etc. Looking on Google, I found a similar function, but it does not return any values, even if I console.log the results? //dummy data more rows in actual code... var people = [ { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "[email protected]", type: "family" }, { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "[email protected]", type: "friend" } ]; function ContactsViewModel(people) { var self = this; self.contacts = ko.observableArray(people); self.uniqueSelect = ko.dependentObservable(function() { return( ko.utils.arrayGetDistinctValues(self.contacts().type).sort()); }, self); }; ko.applyBindings(new ContactsViewModel()); And HTML template <p>Show me: <select data-bind="options: ContactsViewModel.uniqueSelect"></select></p> Any help appreciated, as a noob I'm lost! Thanks

    Read the article

  • How do I do MongoDB console-style queries in PHP?

    - by Zoe Boles
    I'm trying to get a MongoDB query from the javascript console into my PHP app. What I'm trying to avoid is having to translate the query into the PHP "native driver"'s format... I don't want to hand build arrays and hand-chain functions any more than I want to manually build an array of MySQL's internal query structure just to get data. I already have a string producing the exact content I want in the Mongo console: db.intake.find({"processed": {"$exists": "false"}}).sort({"insert_date": "1"}).limit(10); The question is, is there a way for me to hand this string, as is, to MongoDB and have it return a cursor with the dataset I request? Right now I'm at the "write your own parser because it's not valid json to kinda turn a subset of valid Mongo queries into the format the PHP native driver wants" state, which isn't very fun. I don't want an ORM or a massive wrapper library; I just want to give a function my query string as it exists in the console and get an Iterator back that I can work with. I know there are a couple of PHP-based Mongo manager applications that apparently take console-style queries and handle them, but initial browsing through their code, I'm not sure how they handle the translation. I absolutely love working with mongo in the console, but I'm rapidly starting to loathe the thought of converting every query into the format the native writer wants...

    Read the article

  • Javascript code works only when the page loads

    - by victor
    I have a page with a dropdown and two textboxes. The javascript code checks to make sure that if the dropdown says Appointment Made or Patient Scheduled, the appropriate text boxes will have dates in them. When the page loads and the drop down shows either of the two above, all works fine but when I change the drop down the script does not work. I have put an alert statament after the third line and do see that when I make a change to patient_status, the variable a gets updated but for some reason the script fails and does not prompt. For example if the page loads and Appointment Made is selected, the script will prompt, but if I change the drop down to Patient Scheduled, it will not prompt. Thank You. function calculate() { a= document.getElementById("EditRecordpatient_status").value; b= document.getElementById("EditRecordSurgery_Date").value; c= document.getElementById("EditRecordConsult_Date").value; alert(a); alert(b); alert(c); if (a=="Appointment Made" && c=="") { alert('You have scheduled a patient for consultation but the consult date is missing!'); return false; } else if (a=="Patient Scheduled" && b=="") { alert('You have scheduled a patient for surgery but the surgery date is missing!'); return false; } else { return true; } } document.getElementById("Mod0EditRecord").onclick=calculate;

    Read the article

  • How do I install websocket module for Node.js on Debian VPS?

    - by Ollie Shaw
    I currently am renting a VPS from Dreamhost which runs Debian. I am still learning command line on this OS, but fast! I have successfully installed Node.js, now I want to install the websocket module found here: https://github.com/Worlize/WebSocket-Node From the root user, I have run the following command: npm install websocket The error thrown is: [websocket v1.0.7] Native code compile failed!! On Windows, native extensions require Visual Studio and Python. On Unix, native extensions require Python, make and a C++ compiler. Start npm with --websocket:verbose to show compilation output (if any). What commands should I issue to install this websocket module and its requirements? Thanks very much! Edit: When I run sudo apt-get install gcc make I get this message: Reading package lists... Done Building dependency tree Reading state information... Done gcc is already the newest version. gcc set to manually installed. make is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 44 not upgraded. And the same error when trying to install WebSocket.

    Read the article

  • Turning on multiple result sets in an ODBC connection to SQL Server

    - by David Griffiths
    I have an application that originally needed to connect to Sybase (via ODBC), but I've needed to add the ability to connect to SQL Server as well. As ODBC should be able to handle both, I thought I was in a good position. Unfort, SQL Server will not let me, by default, nest ODBC commands and ODBCDataReaders - it complains the connection is busy. I know that I had to specify that multiple active result sets (MARS) were allowed in similar circumstances when connecting to SQL Server via a native driver, so I thought it wouldn't be an issue. The DSN wizard has no entr y when creating a SystemDSN. Some people have provided registry hacks to get around this, but this did not work (add a MARS_Connection with a value of Yes to HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\system-dsn-name). Another suggestion was to create a file-dsn, and add "MARS_Connection=YES" to that. Didn't work. Finally, a DSN-less connection string. I've tried this one (using MultipleActiveResultSets - same variable as a Sql Server connection would use), "Driver={SQL Native Client};Server=xxx.xxx.xxx.xxx;Database=someDB;Uid=u;Pwd=p;MultipleActiveResultSets=True;" and this one: "Driver={SQL Native Client};Server=192.168.75.33\\ARIA;Database=Aria;Uid=sa;Pwd=service;MARS_Connection=YES;" I have checked the various connection-string sites - they all suggest what I've already tried.

    Read the article

  • jquery draggable/droppable issue

    - by Scarface
    Hey guys I have a drag and drop function that does not fully work. What I want to do is be able to drag and drop a picture into a div and have that picture pop up in the div. I have a list of 2 pictures right now, so I have the following function echoed for each picture. Both pictures are draggable and droppable, but the first one is the only one that appears in the div, regardless of which picture gets dragged in. I am not sure what is wrong because the jquery function seems to be unique to each picture. If any one has any suggestions I would appreciate it greatly. while ($row = mysql_fetch_assoc($query)) { $image=htmlentities($row['image']); //image name $uniqid=uniqid(); //unique id for jquery functions $dirname = "usercontent/$user/images/$image"; echo "<img id=\"$uniqid\" src=\"$dirname\" width=\"75\" height=\"75\"/>"; echo "<script> $(function() { $(\"#$uniqid\").draggable({ scroll: true, scrollSensitivity: 10, scrollSpeed: 10, revert: true, helper: 'clone', cursorAt: { cursor: 'move', top: 27, left: 27 } }); $(\"#droppable2, #droppable-background , #droppable2-innerer\").droppable({ greedy: true, activeClass: 'ui-state-hover', hoverClass: 'ui-state-active', drop: function(event, ui) { $(this).addClass('ui-state-highlight').find('> p').html('Dropped!'); $('#droppable-background').css(\"background-image\",\"url($dirname)\"); } }); }); </script>"; }

    Read the article

  • temporary tables within stored procedures on slave servers with readonly set

    - by lau
    Hi, We have set up a replication scheme master/slave and we've had problems lately because some users wrote directly on the slave instead of the master, making the whole setup inconsistent. To prevent these problems from happening again, we've decided to remove the insert, delete, update, etc... rights from the users accessing the slave. Problems is that some stored procedure (for reading) require temporary tables. I read that changing the global variable read_only to true would do what I want and allow the stored procedures to work correctly ( http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_read_only ) but I keep getting the error : The MySQL server is running with the --read-only option so it cannot execute this statement (1290) The stored procedure that I used (for testing purpose) is this one : DELIMITER $$ DROP PROCEDURE IF EXISTS test_readonly $$ CREATE DEFINER=dbuser@% PROCEDURE test_readonly() BEGIN CREATE TEMPORARY TABLE IF NOT EXISTS temp ( BT_INDEX int(11), BT_DESC VARCHAR(10) ); INSERT INTO temp (BT_INDEX, BT_DESC) VALUES (222,'walou'), (111,'bidouille'); DROP TABLE temp; END $$ DELIMITER ; The create temporary table and the drop table work fine with the readonly flag - if I comment the INSERT line, it runs fine- but whenever I want to insert or delete from that temporary table, I get the error message. I use Mysql 5.1.29-rc. My default storage engine is InnoDB. Thanks in advance, this problem is really driving me crazy.

    Read the article

  • java , eclipse jar problem

    - by Raxvan
    Hello , i'm kind of new to java. I use eclipse and i imported some jar files with some classes by going to properties - Add External Jars; The problem is that when i try to use a class from the jar i get the following exception: Exception in thread "main" java.lang.NoClassDefFoundError: nextapp/echo2/app/event/ActionListener at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) at Program.main(Program.java:12) Caused by: java.lang.ClassNotFoundException: nextapp.echo2.app.event.ActionListener at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 13 more The class is supposed to create a window, i guess that the jar has to import somehow other stuff or something like that, How can i fix this? PS. Sorry for the bad code , i don't know tags here. thansk, Raxvan

    Read the article

  • passing string to a AJAX/JSON function

    - by Mikey1980
    I’m having trouble getting a AJAX/JSON function to work correctly. I had this function grabbing value from a drop down box but now I want to use an anchor tag to set it's value. I thought it would be easy to just use the onClick event to pass string to the function I was using for the drop down box but it doesn’t do anything. I’m stumped! Here how I set it up: 1st I add an onClick event… <a href="<?php echo Settings::get('app.webroot'); ?>?view=schedule&action=questions" onmouseout="MM_swapImgRestore();" onmouseover="MM_swapImage('bre','','template/images/schedule/bre_f2.gif',1) onclick="assignCallType('testing')";> 2nd I check main.js.php function assignCallType(type) { alert(type); //just for debugging new Request.JSON({ url: "ajax.php", onSuccess: function(rtndata,txt){ if (rtndata['STATUS'] != 'OK') alert('Error assigning call type to call'); }, onFailure: function (xhr) { alert('Error assigning call type to call'); } }).get({ 'action': 'assignCallType', 'call_type': type }); } 3rd Ajax.php: the variable is back in PHP and values don’t get added to the db, but I also didn’t get the alert from main.js.php if ($_GET['action'] == "assignCallType") { if ($USER->isInsideSales()) { $call_type = $_GET['call_type']; $_SESSION['callinfo']->setCallType($call_type); $_SESSION['callinfo']->save($callid); echo json_encode(array('STATUS'=>'OK')); } else { echo json_encode(array('STATUS'=>'DENIED')); } } Any idea where I am going wrong. The only difference between this and the working drop down is how the function was called, I used onchange="assignCallType(this.value)".

    Read the article

  • How do I refer to a windows form control by name (C# / VB)

    - by Alex
    Suppose I have a label control on a windows form called "UserName". How can I refer to that label programmatically using the label name? For example I can do: For each ctrl as Control in TabPage.Controls If ctrl.Name = "UserName" Then ' Do something End If Next This seems quite inefficient. I would like to do something like: TabPage.Controls("UserName").Text = "Something" I did some googling but couldn't find a satisfactory answer. Most suggested looping, some said .NET 2005 doesn't support direct refenece using string name, and FindControl method was asp.net only... EDIT Thanks for the response so far. Here is a bit more detail. I have a windows form with three tabpages, all of which a very similar in design and function i.e. same drop down menus, labels, react in simlar way to events etc. Rather than write code for each event per tabpage I have built a class that controls the events etc. per tabpage. For example, on each tabpage there is a Label called "RecordCounter" that simply shows the number of rows in the datagridview when it is populated by selection of a variable in a drop down menu. So what I want to be able to do is, upon selection of a variable in the drop down menu, the datagridview populates itself with data, and then I simply want to display the number of rows in a label ("RecordCounter"). This is exactly the same process on each tabpage so what I am doing is passing the tabpage to the class and then I want to be able to refer to the "RecordCounter" and then update it. In my class I set the ActivePage property to be the TabPage that the user has selected and then want to be able to do something like: ActivePage.RecordCounter.Text = GetNumberOfRows()

    Read the article

  • The same C# code produces different output in Visio Professional and Premium

    - by user615993
    I have built a simple conversion Add In, but its behavior is unfortunately different with the different Visio Editions (Visio 2010 Professional and Visio 2010 Premium). The Add In takes a Process-Diagram created with Shapes from Stencil_1.vss and creates a new slightly different Process-Diagram with Shapes from Stencil_2.vsd. It loops through a Visio page and for each shape founded creates a new shapes from new master shape (from Stencil_2.vsd) and drop it into the new page. Geometry, captions etc. are the same, only the shape-appearance is changed. Below is the source diagram: When I run the code into Visio 2010 Professional the swimlane shapes are drawn correctly. When I run the same code from Visio Premium the swimlane appearance and layout are mismatched: Both times i drop the SAME Shape("Swimlane" from the same stencil) into the Page with the SAME Code fragment: Visio.Master vm = swimlane_stencil.Masters.get_ItemU(@"Swimlane"); Visio.Shape TargetShape = targetPage.Drop(vm, shape_x, shape_y); How could I ensure, that the code produces any time the same (correct) output? Must I disable any (premium)features in the swimlane-shapesheet?

    Read the article

  • Jython & Mysql - what is the current practice for connection?

    - by Sector7B
    Just trying jython for the first time, because something came up at work that would fit for this perfect for it. I assume jython can make mysql jdbc connection using the mysql jdbc driver. After googling and reading, however I am having problems and it seems jython specific and probably simple. so i do jython: Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54) [Java HotSpot(TM) 64-Bit Server VM (Apple Inc.)] on java1.6.0_17 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.path ['', '/JYTHONPATH/mysql-connector-java-5.1.10-bin.jar', '/WorkArea/Apps/jython/jython2.5.1/Lib', '__classpath__', '__pyclasspath__/', '/WorkArea/Apps/jython/jython2.5.1/Lib/site-packages'] >>> code i'm running from java.lang import * from java.sql import * driverName="com.mysql.jdbc.Driver" Class.forName(driverName) url = "jdbc:mysql://localhost/test?user=jgreenaw&password=" con = DriverManager.getConnection(url) stmt = con.createStatement() output riux:Desktop$ jython pymysql.py Traceback (most recent call last): File "pymysql.py", line 7, in <module> Class.forName(driverName) at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:315) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:330) at java.lang.ClassLoader.loadClass(ClassLoader.java:250) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:398) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) java.lang.ClassNotFoundException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver any advice? thanks

    Read the article

  • Why does VS2005 skip execution of lines when debugging managed C++ without optimizations?

    - by Sakin
    I ran into a rather odd behavior that I don't even know how to start describing. I wrote a piece of managed C++ code that makes calls to native methods. A (very) simplified version of the code would look like this (I know it looks like a full native function, just assume there is managed stuff being done all over the place): int somefunction(ptrHolder x) { // the accessptr method returns a native pointer if (x.accessptr() != nullptr) // I tried this with nullptr, NULL, 0) { try { x->doSomeNativeVeryImportantStuff(); // or whatever, doesn't matter } catch (SomeCustomExceptionClass &) { return 0; } } SomeOtherNativeClass::doStaticMagic(); return 1; } I compiled this code without optimizations using the /clr flag (VS.NET 2005, SP2) and when running it in the debugger I get to the if statement, since the pointer is actually null, I don't enter the if, but surprisingly, the cursor jumps directly to the return 1 statement, ignoring the doStaticMagic() method completely!!! When looking at the assembly code, I see that it really jumps directly to that line. If I force the debugger to enter the if block, I also jump to the return 1 statement after I press F10. Any ideas why this is happening? Thanks, Ariel

    Read the article

  • Performance Problems with Django's F() Object

    - by JayhawksFan93
    Has anyone else noticed performance issues using Django's F() object? I am running Windows XP SP3 and developing against the Django trunk. A snippet of the models I'm using and the query I'm building are below. When I have the F() object in place, each call to a QuerySet method (e.g. filter, exclude, order_by, distinct, etc.) takes approximately 2 seconds, but when I comment out the F() clause the calls are sub-second. I had a co-worker test it on his Ubuntu machine, and he is not experiencing the same performance issues I am with the F() clause. Anyone else seeing this behavior? class Move (models.Model): state_meaning = models.CharField( max_length=16, db_index=True, blank=True, default='' ) drop = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_move_drop' ) class Split(models.Model): state_meaning = models.CharField( max_length=16, db_index=True, blank=True, default='' ) move = models.ForeignKey( Move, related_name='splits' ) pickup = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_split_pickup' ) pickup_date = models.DateField( null=True, default=None ) drop = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_split_drop' ) drop_date = models.DateField( null=True, default=None, db_index=True ) def get_splits(begin_date, end_date): qs = Split.objects \ .filter(state_meaning__in=['INPROGRESS','FULFILLED'], drop=F('move__drop'), # <<< the line in question pickup_date__lte=end_date) elapsed = timer.clock() - start print 'qs1 took %.3f' % elapsed start = timer.clock() qs = qs.filter(Q(drop_date__gte=begin_date) | Q(drop_date__isnull=True)) elapsed = timer.clock() - start print 'qs2 took %.3f' % elapsed start = timer.clock() qs = qs.exclude(move__state_meaning='UNFULFILLED') elapsed = timer.clock() - start print 'qs3 took %.3f' % elapsed start = timer.clock() qs = qs.order_by('pickup_date', 'drop_date') elapsed = timer.clock() - start print 'qs7 took %.3f' % elapsed start = timer.clock() qs = qs.distinct() elapsed = timer.clock() - start print 'qs8 took %.3f' % elapsed

    Read the article

  • Tiny MCE (jquery plugin version) not showing toolbar in IE (works fine in other browsers)

    - by I am Wonder
    I had an implementation working well but for some reason IE decided it was tired of playing nice. I have an advanced implementation of TinyMCE (the jquery plugin version - see http://tinymce.moxiecode.com/examples/example_23.php for details). It still works great in all browsers but IE. In IE it shows the drop-down options for Format, Font family, and Font size, but only as text.. not as a drop down normally looks. All other buttons on the toolbar are missing. (I've tried IE8 and IE8 Compatibility Mode) I get a javascript error: Syntax error Line 36 Char 1. Unfortunately the javascript is being loaded dynamically so this doesn't help me. Here is my implementation code for the TinyMCE editor: $(function () { $('#InputStuffHere').tinymce({ // General options theme: "advanced", plugins: "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,inlinepopups,preview,media,searchreplace,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,template", // Theme options theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,hr,removeformat", theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,|,forecolor,backcolor,|,spellchecker", theme_advanced_buttons3 : "", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom", theme_advanced_resizing: true, // Drop lists for link/image/media/template dialogs template_external_list_url: "lists/template_list.js", external_link_list_url: "lists/link_list.js", external_image_list_url: "lists/image_list.js", media_external_list_url: "lists/media_list.js", //initialization callback init_instance_callback: "TinyMCEReady", add_form_submit_trigger : false }); }); So... anyone seen anything like this or have any ideas for me? Thank you so much everyone!

    Read the article

  • jQuery ajax response not operating correctly

    - by mmarceau
    Ok this is frustrating... The code below works "correctly" as far as sending the email address to the SaveEmail URL and it gets saved correctly each time I change the drop down. However it only outputs the "Successful" message once, no matter how many times I change the value in the drop down. The "data" that is returned is "Successful". I would like to show the message for a couple seconds, then fade it out. It works correctly the first time I change the drop down, after that the change happens and the value gets saved, but the "Successful" message doesn't display. jQuery code: $('#AgentEmails').change(function() { var NewAddress = $('#AgentEmails').val(); $.post('SaveEmail.aspx', { email: NewAddress }, function(data) { $('#SelectMsg').html("<b>" + data + "</b>").fadeOut(); }); }); HTML code: <select ID='AgentEmails' runat='server'> <option value="[email protected]">TEST</option> </select><span id='SelectMsg'></span> What needs to be changed in my code to make this operate correctly? Thanks for the help.

    Read the article

  • Have a clickable button on top of a combobox in WPF

    - by Travyguy9
    I can get a button to appear and be clickable in the drop down list of a combo box, but I cannot get the selected combo box item (the drop list is closed) to have the button be clickable. It always skips the button click and just opens the drop down list. I basically want the Button_Click event handler that I setup to be called once it is clicked. Here is my sample combo box that shows the button but is not clickable once it is in the selected item: <ComboBox x:Name="MyCombo" Width="200" Height="30" ItemsSource="{Binding ListCombo}"> <ComboBox.Resources> <DataTemplate DataType="{x:Type local:ComboItemClass}"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=SampleText}" Width="120" /> <Button Width="20" Content="..." Click="Button_Click"/> </StackPanel> </DataTemplate> </ComboBox.Resources> </ComboBox>

    Read the article

  • Using placeholders/variables in a sed command

    - by jesse_galley
    I want to store a specific part of a matched result as a variable to be used for replacement later. I would like to keep this in a one liner instead of finding the variable I need before hand. when configuring apache, and use mod_rewrite, you can specificy specific parts of patterns to be used as variables,like this: RewriteRule ^www.example.com/page/(.*)$ http://www.example.com/page.php?page=$1 [R=301,L] the part of the pattern match that's contained inside the parenthesis is stored as $1 for use later. So if the url was www.example.com/page/home, it would be replaced with www.example.com/page.php?page=home. So the "home" part of the match was saved in $1 because it was the part of the pattern inside the parenthesis. I want something like this functionality with a sed command, I need to automatically replace many strings in a SQL dump file, to add drop table if exist commands before each create table, but I need to know the table name to do this, so if the dump file contains something like: ... CREATE TABLE `orders` ... I need to run something like: cat dump.sql | sed "s/CREATE TABLE `(.*)`/DROP TABLE IF EXISTS $1\N CREATE TABLE `$1`/g" to get the result of: ... DROP TABLE IF EXISTS `orders` CREATE TABLE `orders` ... I'm using the mod_rewrite syntax in the sed command as a logical example of what I'm trying to do. Any suggestions?

    Read the article

  • Creating a dynamic, extensible C# Expando Object

    - by Rick Strahl
    I love dynamic functionality in a strongly typed language because it offers us the best of both worlds. In C# (or any of the main .NET languages) we now have the dynamic type that provides a host of dynamic features for the static C# language. One place where I've found dynamic to be incredibly useful is in building extensible types or types that expose traditionally non-object data (like dictionaries) in easier to use and more readable syntax. I wrote about a couple of these for accessing old school ADO.NET DataRows and DataReaders more easily for example. These classes are dynamic wrappers that provide easier syntax and auto-type conversions which greatly simplifies code clutter and increases clarity in existing code. ExpandoObject in .NET 4.0 Another great use case for dynamic objects is the ability to create extensible objects - objects that start out with a set of static members and then can add additional properties and even methods dynamically. The .NET 4.0 framework actually includes an ExpandoObject class which provides a very dynamic object that allows you to add properties and methods on the fly and then access them again. For example with ExpandoObject you can do stuff like this:dynamic expand = new ExpandoObject(); expand.Name = "Rick"; expand.HelloWorld = (Func<string, string>) ((string name) => { return "Hello " + name; }); Console.WriteLine(expand.Name); Console.WriteLine(expand.HelloWorld("Dufus")); Internally ExpandoObject uses a Dictionary like structure and interface to store properties and methods and then allows you to add and access properties and methods easily. As cool as ExpandoObject is it has a few shortcomings too: It's a sealed type so you can't use it as a base class It only works off 'properties' in the internal Dictionary - you can't expose existing type data It doesn't serialize to XML or with DataContractSerializer/DataContractJsonSerializer Expando - A truly extensible Object ExpandoObject is nice if you just need a dynamic container for a dictionary like structure. However, if you want to build an extensible object that starts out with a set of strongly typed properties and then allows you to extend it, ExpandoObject does not work because it's a sealed class that can't be inherited. I started thinking about this very scenario for one of my applications I'm building for a customer. In this system we are connecting to various different user stores. Each user store has the same basic requirements for username, password, name etc. But then each store also has a number of extended properties that is available to each application. In the real world scenario the data is loaded from the database in a data reader and the known properties are assigned from the known fields in the database. All unknown fields are then 'added' to the expando object dynamically. In the past I've done this very thing with a separate property - Properties - just like I do for this class. But the property and dictionary syntax is not ideal and tedious to work with. I started thinking about how to represent these extra property structures. One way certainly would be to add a Dictionary, or an ExpandoObject to hold all those extra properties. But wouldn't it be nice if the application could actually extend an existing object that looks something like this as you can with the Expando object:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } } and then simply start extending the properties of this object dynamically? Using the Expando object I describe later you can now do the following:[TestMethod] public void UserExampleTest() { var user = new User(); // Set strongly typed properties user.Email = "[email protected]"; user.Password = "nonya123"; user.Name = "Rickochet"; user.Active = true; // Now add dynamic properties dynamic duser = user; duser.Entered = DateTime.Now; duser.Accesses = 1; // you can also add dynamic props via indexer user["NickName"] = "AntiSocialX"; duser["WebSite"] = "http://www.west-wind.com/weblog"; // Access strong type through dynamic ref Assert.AreEqual(user.Name,duser.Name); // Access strong type through indexer Assert.AreEqual(user.Password,user["Password"]); // access dyanmically added value through indexer Assert.AreEqual(duser.Entered,user["Entered"]); // access index added value through dynamic Assert.AreEqual(user["NickName"],duser.NickName); // loop through all properties dynamic AND strong type properties (true) foreach (var prop in user.GetProperties(true)) { object val = prop.Value; if (val == null) val = "null"; Console.WriteLine(prop.Key + ": " + val.ToString()); } } As you can see this code somewhat blurs the line between a static and dynamic type. You start with a strongly typed object that has a fixed set of properties. You can then cast the object to dynamic (as I discussed in my last post) and add additional properties to the object. You can also use an indexer to add dynamic properties to the object. To access the strongly typed properties you can use either the strongly typed instance, the indexer or the dynamic cast of the object. Personally I think it's kinda cool to have an easy way to access strongly typed properties by string which can make some data scenarios much easier. To access the 'dynamically added' properties you can use either the indexer on the strongly typed object, or property syntax on the dynamic cast. Using the dynamic type allows all three modes to work on both strongly typed and dynamic properties. Finally you can iterate over all properties, both dynamic and strongly typed if you chose. Lots of flexibility. Note also that by default the Expando object works against the (this) instance meaning it extends the current object. You can also pass in a separate instance to the constructor in which case that object will be used to iterate over to find properties rather than this. Using this approach provides some really interesting functionality when use the dynamic type. To use this we have to add an explicit constructor to the Expando subclass:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } public User() : base() { } // only required if you want to mix in seperate instance public User(object instance) : base(instance) { } } to allow the instance to be passed. When you do you can now do:[TestMethod] public void ExpandoMixinTest() { // have Expando work on Addresses var user = new User( new Address() ); // cast to dynamicAccessToPropertyTest dynamic duser = user; // Set strongly typed properties duser.Email = "[email protected]"; user.Password = "nonya123"; // Set properties on address object duser.Address = "32 Kaiea"; //duser.Phone = "808-123-2131"; // set dynamic properties duser.NonExistantProperty = "This works too"; // shows default value Address.Phone value Console.WriteLine(duser.Phone); } Using the dynamic cast in this case allows you to access *three* different 'objects': The strong type properties, the dynamically added properties in the dictionary and the properties of the instance passed in! Effectively this gives you a way to simulate multiple inheritance (which is scary - so be very careful with this, but you can do it). How Expando works Behind the scenes Expando is a DynamicObject subclass as I discussed in my last post. By implementing a few of DynamicObject's methods you can basically create a type that can trap 'property missing' and 'method missing' operations. When you access a non-existant property a known method is fired that our code can intercept and provide a value for. Internally Expando uses a custom dictionary implementation to hold the dynamic properties you might add to your expandable object. Let's look at code first. The code for the Expando type is straight forward and given what it provides relatively short. Here it is.using System; using System.Collections.Generic; using System.Linq; using System.Dynamic; using System.Reflection; namespace Westwind.Utilities.Dynamic { /// <summary> /// Class that provides extensible properties and methods. This /// dynamic object stores 'extra' properties in a dictionary or /// checks the actual properties of the instance. /// /// This means you can subclass this expando and retrieve either /// native properties or properties from values in the dictionary. /// /// This type allows you three ways to access its properties: /// /// Directly: any explicitly declared properties are accessible /// Dynamic: dynamic cast allows access to dictionary and native properties/methods /// Dictionary: Any of the extended properties are accessible via IDictionary interface /// </summary> [Serializable] public class Expando : DynamicObject, IDynamicMetaObjectProvider { /// <summary> /// Instance of object passed in /// </summary> object Instance; /// <summary> /// Cached type of the instance /// </summary> Type InstanceType; PropertyInfo[] InstancePropertyInfo { get { if (_InstancePropertyInfo == null && Instance != null) _InstancePropertyInfo = Instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); return _InstancePropertyInfo; } } PropertyInfo[] _InstancePropertyInfo; /// <summary> /// String Dictionary that contains the extra dynamic values /// stored on this object/instance /// </summary> /// <remarks>Using PropertyBag to support XML Serialization of the dictionary</remarks> public PropertyBag Properties = new PropertyBag(); //public Dictionary<string,object> Properties = new Dictionary<string, object>(); /// <summary> /// This constructor just works off the internal dictionary and any /// public properties of this object. /// /// Note you can subclass Expando. /// </summary> public Expando() { Initialize(this); } /// <summary> /// Allows passing in an existing instance variable to 'extend'. /// </summary> /// <remarks> /// You can pass in null here if you don't want to /// check native properties and only check the Dictionary! /// </remarks> /// <param name="instance"></param> public Expando(object instance) { Initialize(instance); } protected virtual void Initialize(object instance) { Instance = instance; if (instance != null) InstanceType = instance.GetType(); } /// <summary> /// Try to retrieve a member by name first from instance properties /// followed by the collection entries. /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; // first check the Properties collection for member if (Properties.Keys.Contains(binder.Name)) { result = Properties[binder.Name]; return true; } // Next check for Public properties via Reflection if (Instance != null) { try { return GetProperty(Instance, binder.Name, out result); } catch { } } // failed to retrieve a property result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { // first check to see if there's a native property to set if (Instance != null) { try { bool result = SetProperty(Instance, binder.Name, value); if (result) return true; } catch { } } // no match - set or add to dictionary Properties[binder.Name] = value; return true; } /// <summary> /// Dynamic invocation method. Currently allows only for Reflection based /// operation (no ability to add methods dynamically). /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (Instance != null) { try { // check instance passed in for methods to invoke if (InvokeMethod(Instance, binder.Name, args, out result)) return true; } catch { } } result = null; return false; } /// <summary> /// Reflection Helper method to retrieve a property /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="result"></param> /// <returns></returns> protected bool GetProperty(object instance, string name, out object result) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { result = ((PropertyInfo)mi).GetValue(instance,null); return true; } } result = null; return false; } /// <summary> /// Reflection helper method to set a property value /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected bool SetProperty(object instance, string name, object value) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { ((PropertyInfo)mi).SetValue(Instance, value, null); return true; } } return false; } /// <summary> /// Reflection helper method to invoke a method /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> protected bool InvokeMethod(object instance, string name, object[] args, out object result) { if (instance == null) instance = this; // Look at the instanceType var miArray = InstanceType.GetMember(name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0] as MethodInfo; result = mi.Invoke(Instance, args); return true; } result = null; return false; } /// <summary> /// Convenience method that provides a string Indexer /// to the Properties collection AND the strongly typed /// properties of the object by name. /// /// // dynamic /// exp["Address"] = "112 nowhere lane"; /// // strong /// var name = exp["StronglyTypedProperty"] as string; /// </summary> /// <remarks> /// The getter checks the Properties dictionary first /// then looks in PropertyInfo for properties. /// The setter checks the instance properties before /// checking the Properties dictionary. /// </remarks> /// <param name="key"></param> /// /// <returns></returns> public object this[string key] { get { try { // try to get from properties collection first return Properties[key]; } catch (KeyNotFoundException ex) { // try reflection on instanceType object result = null; if (GetProperty(Instance, key, out result)) return result; // nope doesn't exist throw; } } set { if (Properties.ContainsKey(key)) { Properties[key] = value; return; } // check instance for existance of type first var miArray = InstanceType.GetMember(key, BindingFlags.Public | BindingFlags.GetProperty); if (miArray != null && miArray.Length > 0) SetProperty(Instance, key, value); else Properties[key] = value; } } /// <summary> /// Returns and the properties of /// </summary> /// <param name="includeProperties"></param> /// <returns></returns> public IEnumerable<KeyValuePair<string,object>> GetProperties(bool includeInstanceProperties = false) { if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) yield return new KeyValuePair<string, object>(prop.Name, prop.GetValue(Instance, null)); } foreach (var key in this.Properties.Keys) yield return new KeyValuePair<string, object>(key, this.Properties[key]); } /// <summary> /// Checks whether a property exists in the Property collection /// or as a property on the instance /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(KeyValuePair<string, object> item, bool includeInstanceProperties = false) { bool res = Properties.ContainsKey(item.Key); if (res) return true; if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) { if (prop.Name == item.Key) return true; } } return false; } } } Although the Expando class supports an indexer, it doesn't actually implement IDictionary or even IEnumerable. It only provides the indexer and Contains() and GetProperties() methods, that work against the Properties dictionary AND the internal instance. The reason for not implementing IDictionary is that a) it doesn't add much value since you can access the Properties dictionary directly and that b) I wanted to keep the interface to class very lean so that it can serve as an entity type if desired. Implementing these IDictionary (or even IEnumerable) causes LINQ extension methods to pop up on the type which obscures the property interface and would only confuse the purpose of the type. IDictionary and IEnumerable are also problematic for XML and JSON Serialization - the XML Serializer doesn't serialize IDictionary<string,object>, nor does the DataContractSerializer. The JavaScriptSerializer does serialize, but it treats the entire object like a dictionary and doesn't serialize the strongly typed properties of the type, only the dictionary values which is also not desirable. Hence the decision to stick with only implementing the indexer to support the user["CustomProperty"] functionality and leaving iteration functions to the publicly exposed Properties dictionary. Note that the Dictionary used here is a custom PropertyBag class I created to allow for serialization to work. One important aspect for my apps is that whatever custom properties get added they have to be accessible to AJAX clients since the particular app I'm working on is a SIngle Page Web app where most of the Web access is through JSON AJAX calls. PropertyBag can serialize to XML and one way serialize to JSON using the JavaScript serializer (not the DCS serializers though). The key components that make Expando work in this code are the Properties Dictionary and the TryGetMember() and TrySetMember() methods. The Properties collection is public so if you choose you can explicitly access the collection to get better performance or to manipulate the members in internal code (like loading up dynamic values form a database). Notice that TryGetMember() and TrySetMember() both work against the dictionary AND the internal instance to retrieve and set properties. This means that user["Name"] works against native properties of the object as does user["Name"] = "RogaDugDog". What's your Use Case? This is still an early prototype but I've plugged it into one of my customer's applications and so far it's working very well. The key features for me were the ability to easily extend the type with values coming from a database and exposing those values in a nice and easy to use manner. I'm also finding that using this type of object for ViewModels works very well to add custom properties to view models. I suspect there will be lots of uses for this - I've been using the extra dictionary approach to extensibility for years - using a dynamic type to make the syntax cleaner is just a bonus here. What can you think of to use this for? Resources Source Code and Tests (GitHub) Also integrated in Westwind.Utilities of the West Wind Web Toolkit West Wind Utilities NuGet© Rick Strahl, West Wind Technologies, 2005-2012Posted in CSharp  .NET  Dynamic Types   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

< Previous Page | 90 91 92 93 94 95 96 97 98 99 100 101  | Next Page >