Search Results

Search found 7799 results on 312 pages for 'changing'.

Page 82/312 | < Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >

  • SQL to insert latest version of a group of items

    - by Garett
    I’m trying to determine a good way to handle the scenario below. I have the following two database tables, along with sample data. Table1 contains distributions that are grouped per project. A project can have one or more distributions. A distribution can have one of more accounts. An account has a percentage allocated to it. The distributions can be modified by adding or removing account, as well as changing percentages. Table2 tracks distributions, assigning a version number to each distribution. I need to be able to copy new distributions from Table1 to Table2, but only under two conditions: 1. the entire distribution does not already exist 2. the distribution has been modified (accounts added/removed or percentages changed). Note: When copying a distribution from Table1 to Table2 I need to compare all accounts and percentages within the distribution to determine if it already exists. When inserting the new distribution then I need to increment the VersionID (max(VersionID) + 1). So, in the example provided the distribution (12345, 1) has been modified, adding account number 7, as well as changing percentages allocated. The entire distribution should be copied to the second table, incrementing the VersionID to 3 in the process. The database in question is SQL Server 2005. Table1 ------ ProjectID AccountDistributionID AccountID Percent 12345 1 1 25.0 12345 1 2 25.0 12345 1 7 50.0 56789 2 3 25.0 56789 2 4 25.0 56789 2 5 25.0 56789 2 6 25.0 Table2 ------ ID VersionID Project ID AccountDistributionID AccountID Percent 1 1 12345 1 1 50.0 2 1 12345 1 2 50.0 3 2 56789 2 3 25.0 4 2 56789 2 4 25.0 5 2 56789 2 5 25.0 6 2 56789 2 6 25.0

    Read the article

  • Casting pointer to object to void * in C++

    - by JB
    I've been reading StackOverflow too much and started doubting all the code I've ever written, I keep thinking "Is that undefined behavour?" even in code that has been working for ages. So my question - Is it safe and well defined behavour to cast a pointer to an object (In this case abstract interface classes) to a void* and then later on cast them back to the original class and call method using them? I'm fully aware that the code that does this is probably awful. I wouldn't even consider writing it like this now (this is old code which I don't really want to change), so I'm not looking for a discussion of better ways to do this. I already know how to write it better if I ever did this again. But if it's actually broken to rely on this in C++ then I'll have to look at changing the code, if it's merely awful code then changing it won't be a priority. I would have had no doubts about something this simple a year or two ago but as my understanding of C++ increases I actually find I have more and more worries about code being safe under the standards even if it works perfectly well. Perhaps reading too much stack overflow is a bad thing for productivity sometimes :P

    Read the article

  • Making a visual bar timer for iPhone

    - by Ohmnastrum
    I've looked up all results for progress bars and changing the width of an image but it only refers to scaling, and the progress bars aren't customizable so that they fit other functions or design schemes... unless I missed that part. I'm trying to make a bar timer that crops off of the right over a period of time. I tried using an NStimer so that it would subtract from a value each time its function is called. the Timerbar function gets called as a result of another timer invalidating and it works. What doesn't work is that the width isn't changing just the position. further more I keep getting values like Inf and 0 for power and pwrBarWidth I was sure that the changes would occur when Mult was plugged into the equation. it seems like casting mult as an int is causing problems but i'm not sure exactly how. int pwrBarMaxWidth = 137; int pwrBarWidth 0; int limit = 1; float mult; float power = 0; -(void) Timerbar:(NSTimer *)barTimer { if(!waitForPlayer) { [barTimer invalidate]; } if(mult > 0.0) { mult -= 0.001 * [colorChoices count]; if(mult < 0.0) { mult = 0.0; } } power = (mult * 10) / pwrBarMaxWidth; pwrBarWidth = (int)power % limit; // causes the bar to repeat after it reaches a certain point //At this point however the variable Power is always "inf" and PwrBarWidth is always 0. [powerBar setBounds:CGRectMake(powerBar.frame.origin.x, powerBar.frame.origin.y,pwrBarWidth,20)]; //supposed to change the crop of the bar } Any reason why I'm getting inf as a value for power, 0 as a value for pwrBarWidth, and the bar itself isn't cropping? if this question is a bit vague i'll provide more information as needed.

    Read the article

  • How to map keys in vim differently for different kinds of buffers

    - by Yogesh Arora
    The problem i am facing is that i have mapped some keys and mouse events for seraching in vim while editing a file. But those mappings impact the functionality if the quickfix buffer. I was wondering if it is possible to map keys depending on the buffer in which they are used. EDIT - I am adding more info for this question Let us consider a scenario. I want to map <C-F4> to close a buffer/window. Now this behavior could depend on a number of things. If i am editing a buffer it should just close that buffer without changing the layout of the windows. I am using buffkil plugin for this. It does not depend on extension of file but on the type of buffer. I saw in vim documentation that there are unlisted and listed buffer. So if it is listed buffer it should close using bufkill commands. If it is not a listed buffer it should use <c-w>c command to close buffer and changing the window layout. I am new at writing vim functions/scripts, can someone help me getting started on this

    Read the article

  • How to change database connection without compiling, using JBoss Seam?

    - by MLB
    Hi there: I am developing a web site in Eclipse using JBoss Seam 1.2. My site uses a database (named ALregcli) hosted in a MySQL server. That database has only one table named trazasfallos. The server I am using is local (localhost). When I deploy the site in an "X HOST", the MySQL server it is not in the same computer... the server is in an "Y HOST", so, the connection will not be stablished to the database. I was changing the Context.xml, but it didn't work. The only way it worked was changing the host to connect to in the Context.xml and "recompiling" all the project. Then, it generates the new version of the compiled class trazasfallos.class, and this is the file I have to overwrite for connecting to a new database server. The point is that I want to make the change without "recompiling" anything... Maybe there is a way to make only a "text change" and it will work (maybe in a .xml file)... but I don't know how to do it!! The question is: how to change the connection to the database without recompiling anything in the site?? I am sorry about my English, I am from Cuba.

    Read the article

  • change postgres date format

    - by Jay
    Is there a way to change the default format of a date in Postgres? Normally when I query a Postgres database, dates come out as yyyy-mm-dd hh:mm:ss+tz, like 2011-02-21 11:30:00-05. But one particular program the dates come out yyyy-mm-dd hh:mm:ss.s, that is, there is no time zone and it shows tenths of a second. Apparently something is changing the default date format, but I don't know what or where. I don't think it's a server-side configuration parameter, because I can access the same database with a different program and I get the format with the timezone. I care because it appears to be ignoring my "set timezone" calls in addition to changing the format. All times come out EST. Additional info: If I write "select somedate from sometable" I get the "no timezone" format. But if I write "select to_char(somedate::timestamptz, 'yyyy-mm-dd hh24:mi:ss-tz')" then timezones work as I would expect. This really sounds to me like something is setting all timestamps to implicitly be "to_char(date::timestamp, 'yyyy-mm-dd hh24:mi:ss.m')". But I can't find anything in the documentation about how I would do this if I wanted to, nor can I find anything in the code that appears to do this. Though as I don't know what to look for, that doesn't prove much.

    Read the article

  • C function prototype: void f(). Is it recommended?

    - by ycalleecharan
    Hi, I'm learning C and I saw in a book that a function prototype has the form void f() and in the function declaration or in the calling function, the f function takes arguments. Thus In the function declaration we have something like void f(long double y[], long double A) and in the calling function is f(y, A). The function is doing operations on the array y i.e. when the function is called, some elements in the array y are changing. A is just a constant numerical value that doesn't change. I have two questions: If defining the function prototype at the top in the program as void f() a good practice? Or is it better to put it as void f(long double y[], long double A) as in the function declaration? The called function f is changing elements in the array y. Is void the right return type? The program is working fine as such with the void as described. Or should I change all my "voids" to "long double". I'm working with long double as I need as much precision as possible though on my machine both double and long double gives me 15 precision digits. Thanks a lot

    Read the article

  • Events fired when you change the contents of a control in Silverlight

    - by nyxtom
    Assuming I change the contents of a control using a XamlReader and add the UIElement to the container of a control, what events are supposed to fire? There are times where the SizeChanged will fire, LayoutUpdated changing.. though there are other times where neither of these occur despite having changing the contents of a control. In my case, I am generating a thumbnail view of what's currently in view on a page. The user can change the content of the page and thus the thumbnail should update accordingly. Though, wiring to the LayoutUpdated, Loaded, SizeChanged aren't always reliable for when the contents have changed. I would just call my InvalidateThumbnail which uses a writeablebitmap, but it's too quick after setting the content and as a result I will get a blank thumbnail. At the moment, my hack (cringes) was to wait a few milliseconds before the UI is done rendering the actual new content and I can reliably create the thumbnail. I'd rather just trigger on an event every time though. Possible? What events should I look at? I've seen CompositeTarget.Rendering but that's not what I want.

    Read the article

  • Is there any well-known paradigm for iterating enum values?

    - by SadSido
    I have some C++ code, in which the following enum is declared: enum Some { Some_Alpha = 0, Some_Beta, Some_Gamma, Some_Total }; int array[Some_Total]; The values of Alpha, Beta and Gamma are sequential, and I gladly use the following cycle to iterate through them: for ( int someNo = (int)Some_Alpha; someNo < (int)Some_Total; ++someNo ) {} This cycle is ok, until I decide to change the order of the declarations in the enum, say, making Beta the first value and Alpha - the second one. That invalidates the cycle header, because now I have to iterate from Beta to Total. So, what are the best practices of iterating through enum? I want to iterate through all the values without changing the cycle headers every time. I can think of one solution: enum Some { Some_Start = -1, Some_Alpha, ... Some_Total }; int array[Some_Total]; and iterate from (Start + 1) to Total, but it seems ugly and I have never seen someone doing it in the code. Is there any well-known paradigm for iterating through the enum, or I just have to fix the order of the enum values? (let's pretend, I really have some awesome reasons for changing the order of the enum values)...

    Read the article

  • Overriding CSS style 'display:none' in javascript

    - by jsarma
    I'm trying to add a checkbox toggle that hides and shows list elements by changing their style display attribute from "none" to "inline", but it's not working. I'm setting the attribute's style to "display:none" in the CSS file. Then I set it to "display:inline" in javascript when someone checks a box. The javascript is successfully changing the element's property to inline, but for some reason the element remains invisible. If I do the opposite, by setting the display to inline in the CSS and overriding it to none in the javascript, it works fine. I don't see why this would work one way but not the other. I'm using chrome. Here is the code. Any feedback is appreciated. CSS file: #tabmenu li[status='disabled'] a, a.active, #disabled { color: #777777; background: #DDDDDD; font: normal 1em Arial; border: 1px solid black; border-radius: inherit; padding: 0px 5px 0px 5px; margin: 0px; text-decoration: none; cursor:hand; display:none; } HTML: <ul id="tabmenu"> <li name='tab' id='tab1' selected='no' status='disabled'></li> </ul> JAVASCRIPT (from command line, or onchange of a checkbox) tab = document.getElementById('tab1'); tab.style.display = 'inline';

    Read the article

  • Extending the CI_DB_active_record class in codeigniter 2.0

    - by ctrane
    I am writing my first program with Codeigniter, and have run into a problem. I will start with a focused description of the problem and can broaden it if I need to: I need to write a multi-dimensional array to the DB and want to use the insert_batch function from the CI_DB_active_record class to do so. The problem is that I need to write empty values as NULL for some fields while other fields need to be empty strings. The current function wraps all values with single quotes, and I cannot find a way to write null values to the database for specified fields. I would also like to increase the number of records per batch. I see how to extend models, libraries, etc., but is there a way to extend the CI_DB_active_record class without modifying core classes? The minimal amount of core class modification to make this work that I have found is modifying the following lines in the DB.php file (changing the require_once file to the new file that extends the CI_DB_active_record class and changing the CI_DB_active_record class name to the new class name): require_once(BASEPATH.'database/DB_active_rec'.EXT); if ( ! class_exists('CI_DB')) { eval('class CI_DB extends CI_DB_active_record { }'); } Can I do better?

    Read the article

  • Lost in Nodester Installation

    - by jslamka
    I am trying to install my own version of Nodester. I have tried on Ubuntu 12.04 LTS and now with CentOS. I am not the most skilled Linux user (~2 months use) so I am at a loss at this point. The instructions are located at https://github.com/nodester/nodester/wiki/Install-nodester#wiki-a. They ask you to "export paths (to make npm work)" with the lines necessary to accomplish this. cd ~ echo -e "root = ~/.node_libraries\nmanroot = ~/local/share/man\nbinroot = ~/bin" > ~/.npmrc echo -e "export PATH=3d9c7cfd35d3628e0aa233dec9ce9a44d2231afcquot;\${PATH}:~/bin3d9c7cfd35d3628e0aa233dec9ce9a44d2231afcquot;;" >> ~/.bashrc source ~/.bashrc I can accomplish all of this until I get to the source ~/.bashrc line. When I run that, I get the following: [root@MYSERVER ~]# source ~/.bashrc -bash: /root/.bashrc: line 13: syntax error near unexpected token ';;' -bash: /root/.bashrc: line 13: 'export PATH=3d9c7cfd35d3628e0aa233dec9ce9a44d2231afcquot;${PATH}:~/bin3d9c7cfd35d3628e0aa233dec9ce9a44d2231afcquot;; I have tried changing the quot; to " and that didn't help. I tried changing quot; to colons and that didn't help. I also removed that and it didn't help (I am sure many of you at this point are probably wondering why I would even try those things). Does anyone have any insight as to what I need to do to get this to run properly?

    Read the article

  • Write a completely fluid HTML page (using '%' instead of 'px' for EVERY element height/width)

    - by barak manos
    I am designing my HTML pages to be completely fluid: For every element in the mark-up (HTML), I am using 'style="height:%;width:%"' (instead of 'style="height:*px;width:*px"'). This approach seems to work pretty well, except for when changing the window measurements, in which case, the web page elements change their position and end up "on top of each other". I have come up with a pretty good run-time (java-script) solution to that: var elements = document.getElementsByTagName("*"); for (var i=0; i < elements.length; i++) { if (elements[i].style.height) elements[i].style.height = elements[i].offsetHeight+"px"; if (elements[i].style.width ) elements[i].style.width = elements[i].offsetWidth +"px"; } The only problem remaining is, that if the user opens up the website by entering the URL into a non-maximized window, then the page fits that portion of the window. Then, when maximizing the window, the page remains in its previous measurements. So in essence, I have solved the initial problem (when changing the window measurements), but only when the window is initially in its maximum size. Any ideas on how to tackle this problem? (given that I would like to keep my "% page-design" as is).

    Read the article

  • MERGE Bug with Filtered Indexes

    - by Paul White
    A MERGE statement can fail, and incorrectly report a unique key violation when: The target table uses a unique filtered index; and No key column of the filtered index is updated; and A column from the filtering condition is updated; and Transient key violations are possible Example Tables Say we have two tables, one that is the target of a MERGE statement, and another that contains updates to be applied to the target.  The target table contains three columns, an integer primary key, a single character alternate key, and a status code column.  A filtered unique index exists on the alternate key, but is only enforced where the status code is ‘a’: CREATE TABLE #Target ( pk integer NOT NULL, ak character(1) NOT NULL, status_code character(1) NOT NULL,   PRIMARY KEY (pk) );   CREATE UNIQUE INDEX uq1 ON #Target (ak) INCLUDE (status_code) WHERE status_code = 'a'; The changes table contains just an integer primary key (to identify the target row to change) and the new status code: CREATE TABLE #Changes ( pk integer NOT NULL, status_code character(1) NOT NULL,   PRIMARY KEY (pk) ); Sample Data The sample data for the example is: INSERT #Target (pk, ak, status_code) VALUES (1, 'A', 'a'), (2, 'B', 'a'), (3, 'C', 'a'), (4, 'A', 'd');   INSERT #Changes (pk, status_code) VALUES (1, 'd'), (4, 'a');          Target                     Changes +-----------------------+    +------------------+ ¦ pk ¦ ak ¦ status_code ¦    ¦ pk ¦ status_code ¦ ¦----+----+-------------¦    ¦----+-------------¦ ¦  1 ¦ A  ¦ a           ¦    ¦  1 ¦ d           ¦ ¦  2 ¦ B  ¦ a           ¦    ¦  4 ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦    +------------------+ ¦  4 ¦ A  ¦ d           ¦ +-----------------------+ The target table’s alternate key (ak) column is unique, for rows where status_code = ‘a’.  Applying the changes to the target will change row 1 from status ‘a’ to status ‘d’, and row 4 from status ‘d’ to status ‘a’.  The result of applying all the changes will still satisfy the filtered unique index, because the ‘A’ in row 1 will be deleted from the index and the ‘A’ in row 4 will be added. Merge Test One Let’s now execute a MERGE statement to apply the changes: MERGE #Target AS t USING #Changes AS c ON c.pk = t.pk WHEN MATCHED AND c.status_code <> t.status_code THEN UPDATE SET status_code = c.status_code; The MERGE changes the two target rows as expected.  The updated target table now contains: +-----------------------+ ¦ pk ¦ ak ¦ status_code ¦ ¦----+----+-------------¦ ¦  1 ¦ A  ¦ d           ¦ <—changed from ‘a’ ¦  2 ¦ B  ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦ ¦  4 ¦ A  ¦ a           ¦ <—changed from ‘d’ +-----------------------+ Merge Test Two Now let’s repopulate the changes table to reverse the updates we just performed: TRUNCATE TABLE #Changes;   INSERT #Changes (pk, status_code) VALUES (1, 'a'), (4, 'd'); This will change row 1 back to status ‘a’ and row 4 back to status ‘d’.  As a reminder, the current state of the tables is:          Target                        Changes +-----------------------+    +------------------+ ¦ pk ¦ ak ¦ status_code ¦    ¦ pk ¦ status_code ¦ ¦----+----+-------------¦    ¦----+-------------¦ ¦  1 ¦ A  ¦ d           ¦    ¦  1 ¦ a           ¦ ¦  2 ¦ B  ¦ a           ¦    ¦  4 ¦ d           ¦ ¦  3 ¦ C  ¦ a           ¦    +------------------+ ¦  4 ¦ A  ¦ a           ¦ +-----------------------+ We execute the same MERGE statement: MERGE #Target AS t USING #Changes AS c ON c.pk = t.pk WHEN MATCHED AND c.status_code <> t.status_code THEN UPDATE SET status_code = c.status_code; However this time we receive the following message: Msg 2601, Level 14, State 1, Line 1 Cannot insert duplicate key row in object 'dbo.#Target' with unique index 'uq1'. The duplicate key value is (A). The statement has been terminated. Applying the changes using UPDATE Let’s now rewrite the MERGE to use UPDATE instead: UPDATE t SET status_code = c.status_code FROM #Target AS t JOIN #Changes AS c ON t.pk = c.pk WHERE c.status_code <> t.status_code; This query succeeds where the MERGE failed.  The two rows are updated as expected: +-----------------------+ ¦ pk ¦ ak ¦ status_code ¦ ¦----+----+-------------¦ ¦  1 ¦ A  ¦ a           ¦ <—changed back to ‘a’ ¦  2 ¦ B  ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦ ¦  4 ¦ A  ¦ d           ¦ <—changed back to ‘d’ +-----------------------+ What went wrong with the MERGE? In this test, the MERGE query execution happens to apply the changes in the order of the ‘pk’ column. In test one, this was not a problem: row 1 is removed from the unique filtered index by changing status_code from ‘a’ to ‘d’ before row 4 is added.  At no point does the table contain two rows where ak = ‘A’ and status_code = ‘a’. In test two, however, the first change was to change row 1 from status ‘d’ to status ‘a’.  This change means there would be two rows in the filtered unique index where ak = ‘A’ (both row 1 and row 4 meet the index filtering criteria ‘status_code = a’). The storage engine does not allow the query processor to violate a unique key (unless IGNORE_DUP_KEY is ON, but that is a different story, and doesn’t apply to MERGE in any case).  This strict rule applies regardless of the fact that if all changes were applied, there would be no unique key violation (row 4 would eventually be changed from ‘a’ to ‘d’, removing it from the filtered unique index, and resolving the key violation). Why it went wrong The query optimizer usually detects when this sort of temporary uniqueness violation could occur, and builds a plan that avoids the issue.  I wrote about this a couple of years ago in my post Beware Sneaky Reads with Unique Indexes (you can read more about the details on pages 495-497 of Microsoft SQL Server 2008 Internals or in Craig Freedman’s blog post on maintaining unique indexes).  To summarize though, the optimizer introduces Split, Filter, Sort, and Collapse operators into the query plan to: Split each row update into delete followed by an inserts Filter out rows that would not change the index (due to the filter on the index, or a non-updating update) Sort the resulting stream by index key, with deletes before inserts Collapse delete/insert pairs on the same index key back into an update The effect of all this is that only net changes are applied to an index (as one or more insert, update, and/or delete operations).  In this case, the net effect is a single update of the filtered unique index: changing the row for ak = ‘A’ from pk = 4 to pk = 1.  In case that is less than 100% clear, let’s look at the operation in test two again:          Target                     Changes                   Result +-----------------------+    +------------------+    +-----------------------+ ¦ pk ¦ ak ¦ status_code ¦    ¦ pk ¦ status_code ¦    ¦ pk ¦ ak ¦ status_code ¦ ¦----+----+-------------¦    ¦----+-------------¦    ¦----+----+-------------¦ ¦  1 ¦ A  ¦ d           ¦    ¦  1 ¦ d           ¦    ¦  1 ¦ A  ¦ a           ¦ ¦  2 ¦ B  ¦ a           ¦    ¦  4 ¦ a           ¦    ¦  2 ¦ B  ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦    +------------------+    ¦  3 ¦ C  ¦ a           ¦ ¦  4 ¦ A  ¦ a           ¦                            ¦  4 ¦ A  ¦ d           ¦ +-----------------------+                            +-----------------------+ From the filtered index’s point of view (filtered for status_code = ‘a’ and shown in nonclustered index key order) the overall effect of the query is:   Before           After +---------+    +---------+ ¦ pk ¦ ak ¦    ¦ pk ¦ ak ¦ ¦----+----¦    ¦----+----¦ ¦  4 ¦ A  ¦    ¦  1 ¦ A  ¦ ¦  2 ¦ B  ¦    ¦  2 ¦ B  ¦ ¦  3 ¦ C  ¦    ¦  3 ¦ C  ¦ +---------+    +---------+ The single net change there is a change of pk from 4 to 1 for the nonclustered index entry ak = ‘A’.  This is the magic performed by the split, sort, and collapse.  Notice in particular how the original changes to the index key (on the ‘ak’ column) have been transformed into an update of a non-key column (pk is included in the nonclustered index).  By not updating any nonclustered index keys, we are guaranteed to avoid transient key violations. The Execution Plans The estimated MERGE execution plan that produces the incorrect key-violation error looks like this (click to enlarge in a new window): The successful UPDATE execution plan is (click to enlarge in a new window): The MERGE execution plan is a narrow (per-row) update.  The single Clustered Index Merge operator maintains both the clustered index and the filtered nonclustered index.  The UPDATE plan is a wide (per-index) update.  The clustered index is maintained first, then the Split, Filter, Sort, Collapse sequence is applied before the nonclustered index is separately maintained. There is always a wide update plan for any query that modifies the database. The narrow form is a performance optimization where the number of rows is expected to be relatively small, and is not available for all operations.  One of the operations that should disallow a narrow plan is maintaining a unique index where intermediate key violations could occur. Workarounds The MERGE can be made to work (producing a wide update plan with split, sort, and collapse) by: Adding all columns referenced in the filtered index’s WHERE clause to the index key (INCLUDE is not sufficient); or Executing the query with trace flag 8790 set e.g. OPTION (QUERYTRACEON 8790). Undocumented trace flag 8790 forces a wide update plan for any data-changing query (remember that a wide update plan is always possible).  Either change will produce a successfully-executing wide update plan for the MERGE that failed previously. Conclusion The optimizer fails to spot the possibility of transient unique key violations with MERGE under the conditions listed at the start of this post.  It incorrectly chooses a narrow plan for the MERGE, which cannot provide the protection of a split/sort/collapse sequence for the nonclustered index maintenance. The MERGE plan may fail at execution time depending on the order in which rows are processed, and the distribution of data in the database.  Worse, a previously solid MERGE query may suddenly start to fail unpredictably if a filtered unique index is added to the merge target table at any point. Connect bug filed here Tests performed on SQL Server 2012 SP1 CUI (build 11.0.3321) x64 Developer Edition © 2012 Paul White – All Rights Reserved Twitter: @SQL_Kiwi Email: [email protected]

    Read the article

  • A ToDynamic() Extension Method For Fluent Reflection

    - by Dixin
    Recently I needed to demonstrate some code with reflection, but I felt it inconvenient and tedious. To simplify the reflection coding, I created a ToDynamic() extension method. The source code can be downloaded from here. Problem One example for complex reflection is in LINQ to SQL. The DataContext class has a property Privider, and this Provider has an Execute() method, which executes the query expression and returns the result. Assume this Execute() needs to be invoked to query SQL Server database, then the following code will be expected: using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // Executes the query. Here reflection is required, // because Provider, Execute(), and ReturnValue are not public members. IEnumerable<Product> results = database.Provider.Execute(query.Expression).ReturnValue; // Processes the results. foreach (Product product in results) { Console.WriteLine("{0}, {1}", product.ProductID, product.ProductName); } } Of course, this code cannot compile. And, no one wants to write code like this. Again, this is just an example of complex reflection. using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // database.Provider PropertyInfo providerProperty = database.GetType().GetProperty( "Provider", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance); object provider = providerProperty.GetValue(database, null); // database.Provider.Execute(query.Expression) // Here GetMethod() cannot be directly used, // because Execute() is a explicitly implemented interface method. Assembly assembly = Assembly.Load("System.Data.Linq"); Type providerType = assembly.GetTypes().SingleOrDefault( type => type.FullName == "System.Data.Linq.Provider.IProvider"); InterfaceMapping mapping = provider.GetType().GetInterfaceMap(providerType); MethodInfo executeMethod = mapping.InterfaceMethods.Single(method => method.Name == "Execute"); IExecuteResult executeResult = executeMethod.Invoke(provider, new object[] { query.Expression }) as IExecuteResult; // database.Provider.Execute(query.Expression).ReturnValue IEnumerable<Product> results = executeResult.ReturnValue as IEnumerable<Product>; // Processes the results. foreach (Product product in results) { Console.WriteLine("{0}, {1}", product.ProductID, product.ProductName); } } This may be not straight forward enough. So here a solution will implement fluent reflection with a ToDynamic() extension method: IEnumerable<Product> results = database.ToDynamic() // Starts fluent reflection. .Provider.Execute(query.Expression).ReturnValue; C# 4.0 dynamic In this kind of scenarios, it is easy to have dynamic in mind, which enables developer to write whatever code after a dot: using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // database.Provider dynamic dynamicDatabase = database; dynamic results = dynamicDatabase.Provider.Execute(query).ReturnValue; } This throws a RuntimeBinderException at runtime: 'System.Data.Linq.DataContext.Provider' is inaccessible due to its protection level. Here dynamic is able find the specified member. So the next thing is just writing some custom code to access the found member. .NET 4.0 DynamicObject, and DynamicWrapper<T> Where to put the custom code for dynamic? The answer is DynamicObject’s derived class. I first heard of DynamicObject from Anders Hejlsberg's video in PDC2008. It is very powerful, providing useful virtual methods to be overridden, like: TryGetMember() TrySetMember() TryInvokeMember() etc.  (In 2008 they are called GetMember, SetMember, etc., with different signature.) For example, if dynamicDatabase is a DynamicObject, then the following code: dynamicDatabase.Provider will invoke dynamicDatabase.TryGetMember() to do the actual work, where custom code can be put into. Now create a type to inherit DynamicObject: public class DynamicWrapper<T> : DynamicObject { private readonly bool _isValueType; private readonly Type _type; private T _value; // Not readonly, for value type scenarios. public DynamicWrapper(ref T value) // Uses ref in case of value type. { if (value == null) { throw new ArgumentNullException("value"); } this._value = value; this._type = value.GetType(); this._isValueType = this._type.IsValueType; } public override bool TryGetMember(GetMemberBinder binder, out object result) { // Searches in current type's public and non-public properties. PropertyInfo property = this._type.GetTypeProperty(binder.Name); if (property != null) { result = property.GetValue(this._value, null).ToDynamic(); return true; } // Searches in explicitly implemented properties for interface. MethodInfo method = this._type.GetInterfaceMethod(string.Concat("get_", binder.Name), null); if (method != null) { result = method.Invoke(this._value, null).ToDynamic(); return true; } // Searches in current type's public and non-public fields. FieldInfo field = this._type.GetTypeField(binder.Name); if (field != null) { result = field.GetValue(this._value).ToDynamic(); return true; } // Searches in base type's public and non-public properties. property = this._type.GetBaseProperty(binder.Name); if (property != null) { result = property.GetValue(this._value, null).ToDynamic(); return true; } // Searches in base type's public and non-public fields. field = this._type.GetBaseField(binder.Name); if (field != null) { result = field.GetValue(this._value).ToDynamic(); return true; } // The specified member is not found. result = null; return false; } // Other overridden methods are not listed. } In the above code, GetTypeProperty(), GetInterfaceMethod(), GetTypeField(), GetBaseProperty(), and GetBaseField() are extension methods for Type class. For example: internal static class TypeExtensions { internal static FieldInfo GetBaseField(this Type type, string name) { Type @base = type.BaseType; if (@base == null) { return null; } return @base.GetTypeField(name) ?? @base.GetBaseField(name); } internal static PropertyInfo GetBaseProperty(this Type type, string name) { Type @base = type.BaseType; if (@base == null) { return null; } return @base.GetTypeProperty(name) ?? @base.GetBaseProperty(name); } internal static MethodInfo GetInterfaceMethod(this Type type, string name, params object[] args) { return type.GetInterfaces().Select(type.GetInterfaceMap).SelectMany(mapping => mapping.TargetMethods) .FirstOrDefault( method => method.Name.Split('.').Last().Equals(name, StringComparison.Ordinal) && method.GetParameters().Count() == args.Length && method.GetParameters().Select( (parameter, index) => parameter.ParameterType.IsAssignableFrom(args[index].GetType())).Aggregate( true, (a, b) => a && b)); } internal static FieldInfo GetTypeField(this Type type, string name) { return type.GetFields( BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault( field => field.Name.Equals(name, StringComparison.Ordinal)); } internal static PropertyInfo GetTypeProperty(this Type type, string name) { return type.GetProperties( BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault( property => property.Name.Equals(name, StringComparison.Ordinal)); } // Other extension methods are not listed. } So now, when invoked, TryGetMember() searches the specified member and invoke it. The code can be written like this: dynamic dynamicDatabase = new DynamicWrapper<NorthwindDataContext>(ref database); dynamic dynamicReturnValue = dynamicDatabase.Provider.Execute(query.Expression).ReturnValue; This greatly simplified reflection. ToDynamic() and fluent reflection To make it even more straight forward, A ToDynamic() method is provided: public static class DynamicWrapperExtensions { public static dynamic ToDynamic<T>(this T value) { return new DynamicWrapper<T>(ref value); } } and a ToStatic() method is provided to unwrap the value: public class DynamicWrapper<T> : DynamicObject { public T ToStatic() { return this._value; } } In the above TryGetMember() method, please notice it does not output the member’s value, but output a wrapped member value (that is, memberValue.ToDynamic()). This is very important to make the reflection fluent. Now the code becomes: IEnumerable<Product> results = database.ToDynamic() // Here starts fluent reflection. .Provider.Execute(query.Expression).ReturnValue .ToStatic(); // Unwraps to get the static value. With the help of TryConvert(): public class DynamicWrapper<T> : DynamicObject { public override bool TryConvert(ConvertBinder binder, out object result) { result = this._value; return true; } } ToStatic() can be omitted: IEnumerable<Product> results = database.ToDynamic() .Provider.Execute(query.Expression).ReturnValue; // Automatically converts to expected static value. Take a look at the reflection code at the beginning of this post again. Now it is much much simplified! Special scenarios In 90% of the scenarios ToDynamic() is enough. But there are some special scenarios. Access static members Using extension method ToDynamic() for accessing static members does not make sense. Instead, DynamicWrapper<T> has a parameterless constructor to handle these scenarios: public class DynamicWrapper<T> : DynamicObject { public DynamicWrapper() // For static. { this._type = typeof(T); this._isValueType = this._type.IsValueType; } } The reflection code should be like this: dynamic wrapper = new DynamicWrapper<StaticClass>(); int value = wrapper._value; int result = wrapper.PrivateMethod(); So accessing static member is also simple, and fluent of course. Change instances of value types Value type is much more complex. The main problem is, value type is copied when passing to a method as a parameter. This is why ref keyword is used for the constructor. That is, if a value type instance is passed to DynamicWrapper<T>, the instance itself will be stored in this._value of DynamicWrapper<T>. Without the ref keyword, when this._value is changed, the value type instance itself does not change. Consider FieldInfo.SetValue(). In the value type scenarios, invoking FieldInfo.SetValue(this._value, value) does not change this._value, because it changes the copy of this._value. I searched the Web and found a solution for setting the value of field: internal static class FieldInfoExtensions { internal static void SetValue<T>(this FieldInfo field, ref T obj, object value) { if (typeof(T).IsValueType) { field.SetValueDirect(__makeref(obj), value); // For value type. } else { field.SetValue(obj, value); // For reference type. } } } Here __makeref is a undocumented keyword of C#. But method invocation has problem. This is the source code of TryInvokeMember(): public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder == null) { throw new ArgumentNullException("binder"); } MethodInfo method = this._type.GetTypeMethod(binder.Name, args) ?? this._type.GetInterfaceMethod(binder.Name, args) ?? this._type.GetBaseMethod(binder.Name, args); if (method != null) { // Oops! // If the returnValue is a struct, it is copied to heap. object resultValue = method.Invoke(this._value, args); // And result is a wrapper of that copied struct. result = new DynamicWrapper<object>(ref resultValue); return true; } result = null; return false; } If the returned value is of value type, it will definitely copied, because MethodInfo.Invoke() does return object. If changing the value of the result, the copied struct is changed instead of the original struct. And so is the property and index accessing. They are both actually method invocation. For less confusion, setting property and index are not allowed on struct. Conclusions The DynamicWrapper<T> provides a simplified solution for reflection programming. It works for normal classes (reference types), accessing both instance and static members. In most of the scenarios, just remember to invoke ToDynamic() method, and access whatever you want: StaticType result = someValue.ToDynamic()._field.Method().Property[index]; In some special scenarios which requires changing the value of a struct (value type), this DynamicWrapper<T> does not work perfectly. Only changing struct’s field value is supported. The source code can be downloaded from here, including a few unit test code.

    Read the article

  • Intel Extreme Tuning utility options are greyed

    - by Abhishek Sha
    I'm having a ASUS K55VM with Intel Core i7 3610QM (IvyBridge) with a NVIDIA GT630M. I'm trying to operate the Intel XTU, but as you can see in the screenshot, all the options are greyed out. Can you please help with this situation. Another are is the CPU Throttling (Intel SpeedStep) which is always shown as 0%. But in the Intel Turbo Monitor, the Speed keeps dynamically changing. Then why is the CPU Throttling always at 0%?:

    Read the article

  • ESXi 5.0 GP Exception 13 World 2157

    - by rihatum
    1st time with Esxi 5.0, I have read the whitebox hcl and it states my box as compatible (Dell 960 Optiplex), I burnt Esxi install onto a cd and booted off it (without changing anything in bios) I only had a sata ssd connected, a usb flash 4gb (which i would have installed esxi on), It started loading fine and half way through it dumped a purple / pink screen with : GP Exception 13 World 2157 This system have 5GB RAM (2x2GB and 1x1GB), Intel VT is active in bios, Any suggestions or thoughts ? Will be grateful for your support Kind regards

    Read the article

  • Firefox/Google Chrome extension to darken pages & reduce eye strain

    - by megafish
    Is there an extension or add-on like Stylish which lets you easily toggle back and forth between affected (Stylish) and standard (or untainted) view? I've tried changing colors in Firefox (Settings Content Colors) but there is no quick toggle between the states. Firefox or Google Chrome, whichever one has the extension. Doesn't matter since I'll switch to using that as my primary development browser.

    Read the article

  • Port forward to different port number

    - by ThatGuyYouKnow
    I have a router that sets up rules like so: TCP Any -> 5800 Any -> 5900 UDP Any -> 5800 Any -> 5900 Computer: ip-address This would allow someone 'outside' to connect to my router's port 5800 and 5900 and forward that to the same port on my computer. My issue is that I want the 'outside' port to be different without changing the port on my computer.

    Read the article

  • Change default font in MS word 2010?

    - by Nano8Blazex
    I don't believe this has been asked before, and I'm curious, Is there any way to change the default font in MS Word 2010 beta? Or MS Word 2007? I'm getting really tired of changing fonts every time I write a document. I simply don't like the Calibri font and change it every time... and it's getting annoying. Thanks.

    Read the article

  • Disable header/footer printing from Chrome

    - by Toby
    The Chrome browser doesn't have any settings for changing or disabling header and footer data that gets printed when you go File Print. Apparently this is being developed but until it is does anyone know how to disable this in Windows XP. Chrome on the Mac and Ubuntu doesn't do it so I assume it is down to a system setting that by default doesn't print header/footer information unless software over-rides this?

    Read the article

  • Vim: change the quick fix title

    - by romeovs
    I'm using following makeprg to get my tex files compiled in vim: setlocal makeprg=pdflatex\ \-file\-line\-error\ \-shell\-escape\ \-interaction=nonstopmode\ $*\\\|\ tee\ \/dev\/tty\ \\\|\ grep\ \-P\ ':\\d{1,5}:\ ' which yields great results (errors displayed properly, tex compilation shown while busy,...) Yet, when there are errors and the quickfix window pops up, its status bar is cluttered up with the makeprg string: pdflatex\ \-file\-line\-error\ \-shell\-escape\ \-interaction=nonstopmode\ $*\\\|\ tee\ \/dev\/tty\ \\\|\ grep\ \-P\ ':\\d{1,5}:\ ' Is there a way of changing the quickfix title/statusbar?

    Read the article

< Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >