<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
> <channel><title>Ex nihilo nihil fit &#187; .NET Framework</title> <atom:link href="http://victorhurdugaci.com/category/microsoft/net-framework/feed/" rel="self" type="application/rss+xml" /><link>http://victorhurdugaci.com</link> <description>Victor Hurdugaci&#039;s playground</description> <lastBuildDate>Wed, 18 Apr 2012 16:29:21 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=</generator> <item><title>Modifying .NET binaries – Part 2</title><link>http://victorhurdugaci.com/modifying-net-binaries-part-2/</link> <comments>http://victorhurdugaci.com/modifying-net-binaries-part-2/#comments</comments> <pubDate>Wed, 21 Jul 2010 11:16:39 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Expert]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[.NET]]></category> <category><![CDATA[Advanced]]></category> <category><![CDATA[CFF Explorer]]></category> <category><![CDATA[Cracking]]></category> <category><![CDATA[IL]]></category> <category><![CDATA[WinDbg]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=2122</guid> <description><![CDATA[Description Objective Remove the &#8216;Trial protection&#8217; from an obfuscated .NET application Tools WinDbg CFF Explorer Target audience Advanced users The second part of the article discusses how to modify binaries that are obfuscated. For simplicity and clarity, I will not use obfuscated binaries. Doing this, allows the reader to understand what is actually happening. In [...]]]></description> <content:encoded><![CDATA[<table
class="tutorial-description" border="1" cellspacing="0"><tbody><tr><th
colspan="2">Description</th></tr><tr><td
class="header-column">Objective</td><td>Remove the &#8216;Trial protection&#8217; from an obfuscated .NET application</td></tr><tr><td
class="header-column">Tools</td><td><ul><li>WinDbg</li><li>CFF Explorer</li></ul></td></tr><tr><td
class="header-column">Target audience</td><td>Advanced users</td></tr></tbody></table><p
style="text-align: justify;">The second part of the article discusses how to modify binaries that are obfuscated. For simplicity and clarity, I will not use obfuscated binaries. Doing this, allows the reader to understand what is actually happening. In the demo I will completely ignore the name of the methods or the actual, non-obfuscated, code.</p><p
style="text-align: justify;">I recommend reading the <a
href="http://victorhurdugaci.com/modifiying-net-binaries-part-1/" target="_blank">first part</a>, if you didn&#8217;t already. It provides some information that might be needed to understand theis second part.</p><p
style="text-align: justify;">The same &#8216;TrialApp.exe&#8217; binary is used. The current approach, as opposed the the former one, is:</p><ol
style="text-align: justify;"><li>Load the application in debugger and break the execution when the trial message is displayed.</li><li>Get the call stack</li><li>Find the address of the trial check method</li><li>Remove the call</li></ol><h4 style="text-align: justify;">1. Load the application in debugger and break the execution when the trial message is displayed</h4><p
style="text-align: justify;">WinDbg can be obtained for free from Windows SDK (see the Microsoft Downloads website). If you are running a 64 bit OS, make sure you start the 32bit version of WinDbg (should be in Program Files (x86)).</p><p
style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg01.jpg"><img
class="alignright size-thumbnail wp-image-2130" title="WinDbg01" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg01-150x101.jpg" alt="" width="150" height="101" /></a>Load &#8216;TrialApp.exe&#8217; in WinDbg by clicking File -&gt; Load Executable. In order to run it you have 3 options:</p><ol
style="text-align: justify;"><li>Type &#8216;g&#8217; and press ENTER</li><li>Press F5</li><li>Click Debug -&gt; Go</li></ol><p
style="text-align: justify;">The application will start and the execution will stop when the message box is displayed. Is actually waiting for the user to click OK. At this point break the execution by pressing Debug -&gt; Break.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg02.jpg"><img
class="aligncenter size-large wp-image-2131" title="WinDbg02" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg02-1024x689.jpg" alt="" width="717" height="482" /></a></p><p
style="text-align: justify;">Before being able to debug the .NET application, 2 DLLs needs to be loaded. They help the debugger &#8216;understand&#8217; the .NET internals. The actual paths might differ on your configuration. Anyway, make sure you load the 32 bit version of these files (the 64 bit version are in the <em>Framework64 </em>folder). The <em>.load</em> command loads external libraries.</p><pre class="brush: plain; light: true; title: ; notranslate">.load c:\Windows\Microsoft.NET\Framework\v4.0.30319\SOS.dll
.load c:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll</pre><h4><span
id="more-2122"></span>2. Get the call stack</h4><p
style="text-align: justify;">A call stack is associated with a thread. Before getting the stack we need to figure out which is the thread for which we want it. Execute the following command and inspect the output&#8230;</p><pre class="brush: plain; light: true; title: ; notranslate">!threads</pre><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg03.jpg"><img
class="size-large wp-image-2132  aligncenter" title="WinDbg03" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg03-1024x689.jpg" alt="" width="717" height="482" /></a></p><p
style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg03.jpg"></a>There are two thread having IDs 0 and 2. Is quite easy to decide which is the main thread since just one of them is Single Thread Apartment (STA). Switch to the main thread and display the CLR stack using the following commands:</p><pre class="brush: plain; light: true; title: ; notranslate">~0s
!clrstack</pre><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg04.jpg"><img
class="aligncenter size-large wp-image-2133" title="WinDbg04" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg04-1024x689.jpg" alt="" width="717" height="482" /></a></p><h4>3. Find the address of the trial check method</h4><p
style="text-align: justify;">OK! You&#8217;re still with me? If yes, then take a look at the result of the last command. It displays the call stack of the main thread. Notice that OnCreateControl calls OnLoad, OnLoad calls From1_Load, etc. In the case of obfuscated code, the name would probably be strange and you would have to analyze each method in depth. Because the code was JIT compiled the call to the trial check was inlined.</p><p
style="text-align: justify;">Let&#8217;s take a look at the IL code for Form1_Load. To do this, first we need the address description of the MethodDesc structure of method. The <em>ip2md</em> command returns the structure. The argument is the IP address of the method. After this, just dump the IL for the address specified in MethodDesc. I want to make on observation here: if you look at the MethodDesc structure you can see the <em>mdToken</em> field. This field specified the table and the row in the table for the this method (the row corresponding to this method is the 6<sup>th</sup>, because the index starts at 0).</p><pre class="brush: plain; light: true; title: ; notranslate">!ip2md 003f01f9
!dumpil 00176304</pre><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg05_details.jpg"><img
class="aligncenter size-large wp-image-2135" title="WinDbg05_details" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg05_details-1024x689.jpg" alt="" width="717" height="482" /></a></p><p
style="text-align: justify;">In case of obfuscated code, you would probably see just a call instruction to some cryptic method. It makes no difference. We can see that at IL_0001 (relative to the start of the method) we have a call and this instruction uses 5 bytes in the file (0006-0001 = 0005; in hex)).</p><p
style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF01.jpg"><img
class="alignright size-thumbnail wp-image-2126" title="CFF01" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF01-150x101.jpg" alt="" width="150" height="101" /></a>Having the size of the instruction, its position and the row of the method in the <a
href="http://msdn.microsoft.com/en-us/magazine/cc163791.aspx#S8" target="blank">methods table</a> we can proceed further. Open CFF Explorer and load the assembly.</p><p
style="text-align: justify;">Navigate to .NET Directory -&gt; MetaData Streams -&gt; #~ -&gt; Tables. Look for the Method table in the new tree and select the entry with number 5. Copy its RVA value.</p><h4>4. Remove the call</h4><p
style="text-align: justify;">With the RVA in hand (on clipboard :-) ), remove the call just like in the first part of the article. Replace the call bytes with zeros. One observation: we must also remove the instruction before the call (ldarg_0; opcode 02; no arguments). So, zero 6 bytes starting at the first in the method.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF02.jpg"><img
class="aligncenter size-large wp-image-2127" title="CFF02" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF02-1024x692.jpg" alt="" width="717" height="484" /></a></p><p
style="text-align: justify;">In other words, replace:</p><pre class="brush: plain; light: true; title: ; notranslate">00 00 0A 02 28 08 00 00 06 2A 1E 02 28 06 00 00
06 2A 66 02 7B 02 00 00 04 2C 10 72 01 00 00 00</pre><p>with</p><pre class="brush: plain; light: true; title: ; notranslate">00 00 0A 02 28 08 00 00 06 2A 1E 00 00 00 00 00
00 2A 66 02 7B 02 00 00 04 2C 10 72 01 00 00 00</pre><p
style="text-align: justify;">Run the application. The trial check is gone.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/modifying-net-binaries-part-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Modifying .NET binaries &#8211; Part 1</title><link>http://victorhurdugaci.com/modifiying-net-binaries-part-1/</link> <comments>http://victorhurdugaci.com/modifiying-net-binaries-part-1/#comments</comments> <pubDate>Sun, 30 May 2010 17:11:00 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Expert]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[.NET]]></category> <category><![CDATA[Advanced]]></category> <category><![CDATA[CFF Explorer]]></category> <category><![CDATA[Cracking]]></category> <category><![CDATA[IL]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=2076</guid> <description><![CDATA[The content of this post can be used for good and bad purposes. Modifying the source code to bypass trial/license checks is what crackers do in order to get paid software for free. Be advised that the purpose of this article is not to teach you how to steal. My target for this article are [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">The content of this post can be used for good and bad purposes. Modifying the source code to bypass trial/license checks is what crackers do in order to get paid software for free. Be advised that the purpose of this article is not to teach you how to steal. My target for this article are the .NET developers who should understand what a cracker will (try to) do in order to get access to paid features.</p><p
style="text-align: justify;">Before reading any further you should understand that each protection measure (as long as the cracker can access the source code) is useless. Is just a matter of time, for a motivated person, before she will bypass any protection.</p><p
style="text-align: justify;">For the demo, we are going to use a very simple Windows Forms Application that will display a message box with a trial message and will exit after that. The goal is to show a few techniques that will prevent the application from exiting (and will remove the trial message).</p><p
style="text-align: justify;">The code for the &#8216;trial&#8217; application is kept in just one class. There is just one variable for checking the trial and we&#8217;ll consider that is always true &#8211; it makes no difference if there was a function call to determine if the trial has expired.</p><pre class="brush: csharp; title: ; notranslate">
public partial class Form1 : Form
{
    bool hasExpired = true;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        CheckTrialApp();
    }
    private void CheckTrialApp()
    {
        if (hasExpired)
        {
            MessageBox.Show(&quot;Trial has expired&quot;);
            Application.Exit();
        }
    }
}
</pre><p
style="text-align: justify;">The binary used was compiled on the x86 Release configuration with VS2010 having .NET 4.0 as target framework. The IL Disassembler from VS2010 and a free application called <a
href="http://www.ntcore.com/exsuite.php" target="blank">CFF Explorer</a> are used to view and edit the binary.</p><p
style="text-align: justify;"><span
id="more-2076"></span></p><p
style="text-align: justify;">Opening the &#8216;TrialApp.exe&#8217; file (the target binary) in IL Dissasembler will reveal all the statements from each method. This is important but, more important is the <a
href="http://stackoverflow.com/questions/2170843/va-virutual-adress-rva-relative-virtual-address" target="blank">RVA</a> of the method containing the trial check, the bytes for each statement and their position relative to the RVA.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/05/BytesExplained.jpg"><img
class="aligncenter size-full wp-image-2087" title="BytesExplained" src="http://victorhurdugaci.com/wp-content/uploads/2010/05/BytesExplained.jpg" alt="" width="708" height="408" /></a></p><p
style="text-align: justify;">By knowing the RVA you are able to navigate to that address using CFF explorer and locate the bytes for the calls. Even without seeing the actual bytes, one is able to locate the calls (and their length) by looking at the offsets (ie: the byte 2C is located 0006 bytes from the beginning of the implementation) &#8211; more on this in Part2.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/05/ILMapping.jpg"><img
class="aligncenter size-large wp-image-2090" title="ILMapping" src="http://victorhurdugaci.com/wp-content/uploads/2010/05/ILMapping-1024x433.jpg" alt="" width="717" height="303" /></a></p><p
style="text-align: justify;">Having access to all this information gives not one but many possibilities of bypassing the trial check:</p><ol
style="text-align: justify;"><li>Remove the two calls to <em>Application.Exit</em> and <em>MessageBox.Show.</em></li><li>Change the <em>if</em> check.</li><li>Remove the &#8216;CheckTrialApp&#8217; call from &#8216;Form1_Load&#8217;.</li></ol><p
style="text-align: justify;">This post will cover just the first two possibilities, since the third is similar to the first.</p><h3>1. Remove the calls to <em>Exit </em>and <em>Show</em></h3><p
style="text-align: justify;">The bytes from the method implementation:</p><pre class="brush: csharp; light: true; title: ; notranslate">
         02 7B 02 00 00 04 2C 10 72 01 00 00 70
28 16 00 00 0A 26 28 17 00 00 0A 2A
</pre><p
style="text-align: justify;">A call to a method has the opcode 28. The next 4 bytes following the opcode represent the location of the method in the methods table (you can see this table using CFF explorer).</p><p
style="text-align: justify;">Now here comes the magic: in order to remove the calls to <em>Exit </em>and <em>Show, </em>one must  replace with NOP, all the bytes associated with these methods. Basically we are going the introduce a NOP byte (00) for each byte in the call.</p><pre class="brush: csharp; light: true; title: ; notranslate">
         02 7B 02 00 00 04 2C 10 72 01 00 00 70
00 00 00 00 00 26 00 00 00 00 00 2A
</pre><p>That&#8217;s all. Save the file and the trial is bypassed.</p><h3>2. Change the <em>if</em> check</h3><p
style="text-align: justify;">If you look in the disassembled IL you can see that at offset 0&#215;6 we have a <em>brfalse.s</em> opcode. This is a branch instruction that will branch to offset 0&#215;18 (IL_0018) if false. However, in the case of &#8216;TrialApp&#8217;, since <em>hasExpired</em> is always true, the branch will never take place and the code following it will be executed.</p><p
style="text-align: justify;">In order to change the meaning of the code &#8211; in other words &#8220;give the trial message if the application has NOT expired&#8221; &#8211; the check will be changed. Currently, is checking against <em>false</em> using the instruction <em>brfalse.s</em>, having the opcode 2C. By looking on MSDN, the opcode for <em>brtrue.s</em> can be found: 2D. Replacing 2C with 2D will make the branch happen always.</p><p
style="text-align: justify;">The method inside the binary, after replacing the <em>brfalse.s</em> opcode:</p><pre class="brush: csharp; light: true; title: ; notranslate">
         02 7B 02 00 00 04 2D 10 72 01 00 00 70
28 16 00 00 0A 26 28 17 00 00 0A 2A
</pre><p
style="text-align: justify;">That&#8217;s all. The message box will not be displayed since the body of the <em>if</em> statement is no longer executed.</p><p
style="text-align: justify;">There are some techniques that will make cracking difficult. Obfuscating the code is one of them. However, part 2 of this article will cover the modification of obfuscated binaries.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/modifiying-net-binaries-part-1/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>I.R. Certified</title><link>http://victorhurdugaci.com/i-r-certified/</link> <comments>http://victorhurdugaci.com/i-r-certified/#comments</comments> <pubDate>Fri, 24 Apr 2009 07:28:23 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Personal/Blog]]></category> <category><![CDATA[Brasov]]></category> <category><![CDATA[Bucharest]]></category> <category><![CDATA[Certification]]></category> <category><![CDATA[Exam]]></category> <category><![CDATA[MCP]]></category> <category><![CDATA[Pictures]]></category> <category><![CDATA[Train]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=846</guid> <description><![CDATA[I finally got it, my first Microsoft certification. Yesterday I went to Bucharest, Romania to take the 70-536 Microsoft .NET Framework &#8211; Application Development Foundation exam. It was an interesting experience because of the train which was 30 late. Got to Bucharest later than expected and I had to (almost) run to the exam center [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;"><img
class="alignleft" title="MCP Logo" src="http://victorhurdugaci.com/img/mcplogo.png" alt="" width="160" height="80" />I finally got it, my first Microsoft certification. Yesterday I went to Bucharest, Romania to take the <em>70-536 Microsoft .NET Framework &#8211; Application Development Foundation</em> exam.</p><p
style="text-align: justify;">It was an interesting experience because of the train which was 30 late. Got to Bucharest later than expected and I had to (almost) run to the exam center -  got there 1-2 minutes before the exam start.</p><p
style="text-align: justify;">The exam itself was a little different than what I was expecting (from the practice tests). I had 40 questions instead on 45 (why?) and there were a lot of .NET globalization questions. I would rate it as medium to hard but the time was more than enough and I was able to recheck my questions 3 times and still got out of the room with 50 minutes before deadline.</p><p
style="text-align: justify;">After the exam I took a walk through Bucharest and took some pictures. That city is so green (compared to Brasov)&#8230;</p><div
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3184.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-850" title="img_3184" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3184-150x112.jpg" alt="img_3184" width="150" height="112" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3187.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-851" title="img_3187" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3187-150x112.jpg" alt="img_3187" width="150" height="112" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3192.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-852" title="img_3192" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3192-150x112.jpg" alt="img_3192" width="150" height="112" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3198.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-854" title="img_3198" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3198-150x112.jpg" alt="img_3198" width="150" height="112" /></a></div><p
style="text-align: justify;">Guess what? When returning the train, again, was late. Just this time there was almost an hour.</p><p
style="text-align: justify;"><strong>NOTE:</strong> I.R. stands for &#8220;I are&#8221; (see the animated TV series &#8220;I Am Weasel&#8221;).</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/i-r-certified/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Using UAC with C# &#8211; Part 2</title><link>http://victorhurdugaci.com/using-uac-with-c-part-2/</link> <comments>http://victorhurdugaci.com/using-uac-with-c-part-2/#comments</comments> <pubDate>Fri, 03 Apr 2009 18:15:06 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[UAC]]></category> <category><![CDATA[User Account Control]]></category> <category><![CDATA[Vista]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=683</guid> <description><![CDATA[In part 1 of this tutorial I have presented how to run an application with and without elevation by specifying this from another process. However there are some situations when an application cannot be run without administrative rights. For example a system configuration utility requires administrative rights to change some global policies. In order to [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">In <a
href="http://victorhurdugaci.com/using-uac-with-c-part-1/">part 1</a> of this tutorial I have presented how to run an application with and without elevation by specifying this from another process.</p><p
style="text-align: justify;">However there are some situations when an application cannot be run without administrative rights. For example a system configuration utility requires administrative rights to change some global policies.</p><p
style="text-align: justify;">In order to force an application to run only if the current user is administrator or can provide administrative credentials you must add a manifest to the C# project.</p><p
style="text-align: justify;">The manifest is an XML file named &lt;application_name&gt;.exe.manifest with the following content:</p><div
class="wp_codebox"><table><tr
id="p6832"><td
class="code" id="p683code2"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span> <span style="color: #000066;">standalone</span>=<span style="color: #ff0000;">&quot;yes&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;assembly</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;urn:schemas-microsoft-com:asm.v1&quot;</span> <span style="color: #000066;">manifestVersion</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;assemblyIdentity</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0.0.0&quot;</span> <span style="color: #000066;">processorArchitecture</span>=<span style="color: #ff0000;">&quot;X86&quot;</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;UACApp&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;win32&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;trustInfo</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;urn:schemas-microsoft-com:asm.v3&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;requestedPrivileges<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;requestedExecutionLevel</span> <span style="color: #000066;">level</span>=<span style="color: #ff0000;">&quot;requireAdministrator&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/requestedPrivileges<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/trustInfo<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/assembly<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div><p
style="text-align: justify;">What is important is the <em>requestedExecutionLevel </em>element. It specifies what permissions (execution level) the application needs in order to start. If the current user does not have the required level then an elevation window is displayed (see part one of the tutorial that describes the elevation window).</p><p
style="text-align: justify;">The default value of <em>requestedExecutionLevel</em> if it is not specified in the manifest or the manifest does not exist is <em>asInvoker. </em>Except <em>asInvoker</em> and <em>requireAdministrator</em> there is another execution level. All three are described below:</p><table
border="0" cellspacing="0" cellpadding="2" width="100%"><tbody><tr><td
style="border:solid 1px black; text-align: center;"><strong>Value</strong></td><td
style="border:solid 1px black; border-left: 0px; text-align: center;"><strong>Description</strong></td><td
style="border:solid 1px black; border-left: 0px; text-align: center;"><strong>Comment</strong></td></tr><tr><td
style="border:solid 1px black; border-top: 0px; text-align: center;">asInvoker</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">The application runs with the same access token as the parent process.</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.</td></tr><tr><td
style="border:solid 1px black; border-top: 0px; text-align: center;">highestAvailable</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">The application runs with the highest privileges the current user can obtain.</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">Recommended for mixed-mode applications. Plan to refractor the application in a future release.</td></tr><tr><td
style="border:solid 1px black; border-top: 0px; text-align: center;">requireAdministrator</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">The application runs only for administrators and requires that the application be launched with the full access token of an administrator.</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">Recommended for administrator only applications. Internal elevation points are not needed. The application is already running elevated.</td></tr></tbody></table><p
style="text-align: justify;">In order to embed the manifest in the aplication&#8217;s executable you can choose one of the following options:</p><p><span
id="more-683"></span></p><p
style="text-align: justify;"><strong>1. The hard way &#8211; mt.exe</strong></p><p
style="text-align: justify;">The Mt.exe file is a tool that generates signed files and catalogs. It is available in the Microsoft Windows Software Development Kit (SDK). Mt.exe requires that the file referenced in the manifest be present in the same directory as the manifest.</p><p
style="text-align: justify;">The manifest will be embedded after a successful build so we need to add this the call of Mt.exe in the post-build event. In order to do this right click the project -&gt; Properties -&gt; Choose &#8220;Build Events&#8221; from the vertical left tabs.</p><p>Mt.exe is found in many places on disk so the path to it might be different on your configuration. The post build command is:</p><p><em>&#8220;C:Program FilesMicrosoft.NETSDKv2.0 64bitBinmt.exe&#8221; -manifest &#8220;$(ProjectDir)$(TargetName).exe.manifest&#8221; –outputresource:&#8221;$(TargetDir)$(TargetFileName)&#8221;;#1</em></p><p
style="text-align: justify;">Make sure the paths to mt.exe and the .manifest file are correct. You should get something like this:</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-hardway.png"><img
class="aligncenter size-full wp-image-713" title="uac-hardway" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-hardway.png" alt="uac-hardway" width="657" height="347" /></a></p><p
style="text-align: justify;">This method has a drawback. If you start the application with debugging from Visual Studio it will start with limited privileges. Running without debugging will ask you to elevate the parent process (in our case Visual Studio).</p><p
style="text-align: justify;"><strong>2. The easy way &#8211; designer</strong></p><p
style="text-align: justify;">Just create the manifest file, include it in visual studio, go to the &#8220;Application&#8221; tab in project&#8217;s properties and choose the manifest file from the Manifest combo box.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-easyway.png"><img
class="aligncenter size-full wp-image-712" title="uac-easyway" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-easyway.png" alt="uac-easyway" width="597" height="394" /></a></p><p>Build.</p><p>This method that has another advantage. Even if running with Debug you will still be prompted to elevate Visual Studio.</p><p
style="text-align: center;"><img
class="aligncenter size-full wp-image-714" title="uac-vsmsg" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-vsmsg.png" alt="uac-vsmsg" width="509" height="248" /></p><p>The source code can be downloaded below (it is the application from part 1 but includes the manifest file):</p><h3><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/uacapp_manifest.zip">Download source</a></h3><p><strong>IMPORTANT:</strong> This tutorial is useless if you disabled UAC because all you processes (considering you are the administrator) run elevated.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/using-uac-with-c-part-2/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Using UAC with C# &#8211; Part 1</title><link>http://victorhurdugaci.com/using-uac-with-c-part-1/</link> <comments>http://victorhurdugaci.com/using-uac-with-c-part-1/#comments</comments> <pubDate>Wed, 01 Apr 2009 05:13:32 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[UAC]]></category> <category><![CDATA[User Account Control]]></category> <category><![CDATA[Vista]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=638</guid> <description><![CDATA[User Account Control (UAC) is a new technology introduced by Microsoft in Windows Vista and most of the time it is misunderstood by users and developers. It&#8217;s main purpose is to protect the operating system by running applications with reduced privileges. Why should we use this? Most applications DO NOT require full privileges. Think to [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;"><img
class="size-full wp-image-650 alignright" title="user_account_control_administrator_dialog" src="http://victorhurdugaci.com/wp-content/uploads/2009/03/user_account_control_administrator_dialog.png" alt="user_account_control_administrator_dialog" width="307" height="169" />User Account Control (UAC) is a new technology introduced by Microsoft in Windows Vista and most of the time it is misunderstood by users and developers. It&#8217;s main purpose is to protect the operating system by running applications with reduced privileges.</p><p
style="text-align: justify;">Why should we use this? Most applications DO NOT require full privileges. Think to the applications you have written and ask yourself if most of the job can be done without full writes (if you write to disk think if you could write in the user&#8217;s folder or an isolated storage, if writing in registry to HKLM think if you could write to HKLU, etc). The answer is mostly sure &#8220;Yes&#8221;.</p><p
style="text-align: justify;">So why run applications with full privileges when they can be run with limited? Running with more privileges than required is just a security vulnerability -  If an attacker exploits a vulnerability in your application he will gain more control.</p><p
style="text-align: justify;">There are two mistakes developers tend to do:<img
class="size-full wp-image-649 alignright" title="unidentified_uac" src="http://victorhurdugaci.com/wp-content/uploads/2009/03/unidentified_uac.png" alt="unidentified_uac" width="322" height="258" /></p><ol
style="text-align: justify;"><li>Request the end-user to run an application with full rights even though this is not necessarily (most of the time because of bad design practices)</li><li>Do not request to user to run the application elevated but try to perform operations that require more rights</li></ol><p
style="text-align: justify;">By design UAC can only elevate code at process level and only at process&#8217; startup (means that a running process cannot be elevated). In the .NET world this also means that you cannot elevate code running in another app domain because the app domain is part of a running process. In order to elevate an existing application this must be closed and reopen with more privileges.</p><p
style="text-align: justify;">There are two types on UAC dialogs: blue and yellow. When you see a blue dialog you can be sure that the application requesting privileges is signed and trusted. The yellow dialog shows for any application that is not digitally signed and is not fully trusted.</p><p
style="text-align: justify;">User Account Control also prevents a lower privilege process to do the following (list below taken from MSDN):</p><ul
style="text-align: justify;"><li>Perform a window handle validation of higher process privilege.</li><li><em>SendMessage </em>or <em>PostMessage </em>to higher privilege application windows. These Application Programming Interfaces (APIs) return success but silently drop the window message.</li><li>Use thread hooks to attach to a higher privilege process.</li><li>Use Journal hooks to monitor a higher privilege process.</li><li>Perform DLL injection to a higher privilege process.</li></ul><p
style="text-align: justify;">Let&#8217;s see how an UAC aware application should look.</p><p
style="text-align: justify;"><span
id="more-638"></span>It should be composed of two executables (one that will be run with limited privileges and another one that will be started only with needed and with full rights) or two working modes (a mode for limited rights and another one for full rights). Either way you must remember that once you elevated the application and finalized the administrative tasks, the process should be destroyed in order to reduce an attacker&#8217;s privileges.</p><p
style="text-align: justify;">In order to launch an elevated process in Windows Vista the process must be started with the &#8220;<em>runas</em>&#8221; verb. The <em>Verb </em>property is part of System.Diagnostics.Process.StartInfo class. The code snippet that launches &#8220;notepad.exe&#8221; with full rights is showed below:</p><div
class="wp_codebox"><table><tr
id="p6386"><td
class="code" id="p638code6"><pre class="csharp" style="font-family:monospace;">    ProcessStartInfo processInfo <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ProcessStartInfo<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    processInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">Verb</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;runas&quot;</span><span style="color: #008000;">;</span>
    processInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">FileName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;notepad.exe&quot;</span><span style="color: #008000;">;</span>
    Process<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span>processInfo<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">If you choose to have only one executable file that acts differently based on permissions you should check if the user is part of the administrative group. In Vista even if your user is part of the Administrators group it runs with reduced privileges by default and gains his full rights on demand. The code below stores <em>true</em> in the <em>hasAdministrativeRight</em> boolean variable if the user&#8217;s privileges are administrative and <em>false</em> otherwise.</p><div
class="wp_codebox"><table><tr
id="p6387"><td
class="code" id="p638code7"><pre class="csharp" style="font-family:monospace;">    WindowsPrincipal pricipal <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> WindowsPrincipal<span style="color: #008000;">&#40;</span>WindowsIdentity<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrent</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">bool</span> hasAdministrativeRight <span style="color: #008000;">=</span> pricipal<span style="color: #008000;">.</span><span style="color: #0000FF;">IsInRole</span><span style="color: #008000;">&#40;</span>WindowsBuiltInRole<span style="color: #008000;">.</span><span style="color: #0000FF;">Administrator</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">To elevate the current application you must create a process with elevated rights and close the existing instance. However you cannot start a process with limited privileges &#8211; I couldn&#8217;t find a solution. Anyone knows how to start a less privilege process from a higher privilege one? The sample creates an elevated instance of the current executable and closes the existing one.</p><div
class="wp_codebox"><table><tr
id="p6388"><td
class="code" id="p638code8"><pre class="csharp" style="font-family:monospace;">    RunElevated<span style="color: #008000;">&#40;</span>Application<span style="color: #008000;">.</span><span style="color: #0000FF;">ExecutablePath</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;"><em>RunElevated</em> is a method that takes the name of an executable and spawns it in a new elevated process (see the attached code).</p><p
style="text-align: justify;">I have created a sample application that illustrates all the things written so far: it displays the user&#8217;s rights, elevates the current application and starts a process with more privileges. In order to see all features of the application you must have UAC enabled. You can download the code from <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/03/uacapp.zip">this link</a>.</p><p
style="text-align: justify;">Please note that here I recommend to run applications with limited privileges but there are situations when applications need to run unrestricted &#8211; this is the case of system configuration utilities or other special applications. What I want to say is that you should run applications in an unprivileged environment when possible.</p><p
style="text-align: justify;">This is part one of the tutorial. Part 2 will explain how to use the manifest file to specify that an executable must be always run with full privleges.</p><h3 style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/03/uacapp.zip" target="_self">Download Source Code</a></h3> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/using-uac-with-c-part-1/feed/</wfw:commentRss> <slash:comments>24</slash:comments> </item> <item><title>Access private data with Reflection</title><link>http://victorhurdugaci.com/access-private-data-with-reflection/</link> <comments>http://victorhurdugaci.com/access-private-data-with-reflection/#comments</comments> <pubDate>Sun, 15 Feb 2009 20:01:35 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[How To]]></category> <category><![CDATA[Private Data]]></category> <category><![CDATA[Reflection]]></category> <category><![CDATA[Tutorial]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=471</guid> <description><![CDATA[This article shows how one of the basic OOP principles &#8211; encapsulation &#8211; can be violated using reflection. Let&#8217;s assume that we have a simple class with a private field called &#8220;someHiddenValue&#8221;. class ClassThatHidesSomething &#123; private int someHiddenValue = 5; &#125; We want to modify that field from outside the class. This can be done [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">This article shows how one of the basic OOP principles &#8211; encapsulation &#8211; can be violated using reflection.</p><p
style="text-align: justify;">Let&#8217;s assume that we have a simple class with a private field called &#8220;someHiddenValue&#8221;.</p><div
class="wp_codebox"><table><tr
id="p47115"><td
class="code" id="p471code15"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> ClassThatHidesSomething
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> someHiddenValue <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p
style="text-align: justify;">We want to modify that field from outside the class. This can be done extremely easy through Reflection. First of all we need to get the <em>Type </em>of the <em>ClassThatHidesSomething </em>and get some information about the <em>someHiddenValue </em>field.</p><div
class="wp_codebox"><table><tr
id="p47116"><td
class="code" id="p471code16"><pre class="csharp" style="font-family:monospace;">Type classThatHidesSomethingType <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color: #008000;">typeof</span></a><span style="color: #008000;">&#40;</span>ClassThatHidesSomething<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
FieldInfo field <span style="color: #008000;">=</span> classThatHidesSomethingType<span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
                         <span style="color: #666666;">&quot;someHiddenValue&quot;</span>,
                         BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><ul><li>BindingFlags.NonPublic specifies that we want to search in all fields; by default it searches only the public fields &#8211; <strong>actually here is the trick that violates encapsulation. </strong></li><li>BindingFlags.Instance specified that we want to search in instance fields also; by default it searches only in static ones.</li></ul><p
style="text-align: justify;">Now that we have the <em>FieldInfo </em>of that specific field we can do whatever we want with it. Let&#8217;s display its value. But first, because the field is an instance field we need an instance of <em>ClassThatHidesSomething.</em></p><div
class="wp_codebox"><table><tr
id="p47117"><td
class="code" id="p471code17"><pre class="csharp" style="font-family:monospace;">ClassThatHidesSomething c <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ClassThatHidesSomething<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #6666cc; font-weight: bold;">int</span> hiddenFieldValue <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>field<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>c<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Hidden field value: {0}&quot;</span>, hiddenFieldValue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p>Using the same instance <em>c</em> we can set the private field&#8217;s value.</p><div
class="wp_codebox"><table><tr
id="p47118"><td
class="code" id="p471code18"><pre class="csharp" style="font-family:monospace;">field<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValue</span><span style="color: #008000;">&#40;</span>c, <span style="color: #FF0000;">6</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p>Below you can see the entire code (it is a console application):</p><p><span
id="more-471"></span></p><div
class="wp_codebox"><table><tr
id="p47119"><td
class="code" id="p471code19"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> Reflection
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">class</span> ClassThatHidesSomething
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> someHiddenValue <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #6666cc; font-weight: bold;">class</span> Reflection
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">int</span> ANumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Type classThatHidesSomethingType <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color: #008000;">typeof</span></a><span style="color: #008000;">&#40;</span>ClassThatHidesSomething<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            FieldInfo field <span style="color: #008000;">=</span> classThatHidesSomethingType<span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
                                     <span style="color: #666666;">&quot;someHiddenValue&quot;</span>,
                                     BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//It is good to check this because</span>
            <span style="color: #008080; font-style: italic;">//we don't want a NullReferenceException</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>field <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
                Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Field not found&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">else</span>
            <span style="color: #008000;">&#123;</span>
                ClassThatHidesSomething c <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ClassThatHidesSomething<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #6666cc; font-weight: bold;">int</span> hiddenFieldValue <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>field<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>c<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Hidden field value: {0}&quot;</span>, hiddenFieldValue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                field<span style="color: #008000;">.</span><span style="color: #0000FF;">SetValue</span><span style="color: #008000;">&#40;</span>c, <span style="color: #FF0000;">6</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #6666cc; font-weight: bold;">int</span> newHiddenFiledValue <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>field<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>c<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;New hidden field value: {0}&quot;</span>, newHiddenFiledValue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>The code outputs:</p><div
class="wp_codebox"><table><tr
id="p47120"><td
class="code" id="p471code20"><pre class="php" style="font-family:monospace;">Hidden field value<span style="color: #339933;">:</span> <span style="color: #cc66cc;">5</span>
<span style="color: #000000; font-weight: bold;">New</span> hidden field value<span style="color: #339933;">:</span> <span style="color: #cc66cc;">6</span></pre></td></tr></table></div> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/access-private-data-with-reflection/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Binding in WinForms like in WPF Part 1</title><link>http://victorhurdugaci.com/binding-in-winforms-like-in-wpf-1/</link> <comments>http://victorhurdugaci.com/binding-in-winforms-like-in-wpf-1/#comments</comments> <pubDate>Sun, 06 Jul 2008 14:44:43 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Data Binding]]></category> <category><![CDATA[Visual Studio]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=88</guid> <description><![CDATA[If you have ever used Windows Presentation Foundation (WPF) then you might have been impressed by the binding features of it. Part one of this tutorial will show how to bind properties of the same type while the second one will also anlyse type conversion. Using data binding you can synchronize object properties. The source [...]]]></description> <content:encoded><![CDATA[<p>If you have ever used Windows Presentation Foundation (WPF) then you might have been impressed by the binding features of it.</p><p>Part one of this tutorial will show how to bind properties of the same type while the second one will also anlyse type conversion.</p><p>Using data binding you can synchronize object properties. The source of the binding is the object or property that is changing the value and the destination is the one who receives it (the new value).</p><p>There are two types of binding:</p><ul><li>one way binding &#8211; there is only one source that updates the information and as many destinations who receive the update.</li><li>two way binding &#8211; every binding element can update and can receive updates so there is no distinction between source and destination.</li></ul><p><span
id="more-88"></span></p><p>The central element of binding is the Observer. It manages the process &#8211; chooses whether to send or not the notifications, performs type conversions and keeps the list of subscribers.</p><p>The diagrams below illustrate the two binding situations (one way and two way) when the source and destination have the same data type.</p><p><a
href="http://victorhurdugaci.com/wp-content/uploads/onewaysametype.jpg"><img
class="alignnone size-medium wp-image-89" title="onewaysametype" src="http://victorhurdugaci.com/wp-content/uploads/onewaysametype-300x230.jpg" alt="One Way Same Type" width="300" height="230" /></a><a
href="http://victorhurdugaci.com/wp-content/uploads/twowaysametype.jpg"><img
class="alignnone size-medium wp-image-92" title="twowaysametype" src="http://victorhurdugaci.com/wp-content/uploads/twowaysametype-300x184.jpg" alt="Two Way Same Type" width="300" height="184" /></a></p><p>In the first diagram, the arrows suggest that the information comes from the source object and the Observer distributes is to all subscribers. In the second one every subscriber is also a source. &#8220;Update&#8221; is the process of informing the Observer that one source changed its value and &#8220;notify&#8221; is the process of sending, to all subscribers, the new value. Even though in the first diagram is not suggested, the source performs an update and the observers performs three notifications.</p><p>All we need to do is to create the observer. As seen in the diagrams this will have an Update method and a mechanism of notifying the subscribers about the new value. The notification can be implemented as an event and the update like a method.</p><p>Because we don&#8217;t know what data type will be used for binding and we want type safety, the observer will be generic.</p><div
class="wp_codebox"><table><tr
id="p8825"><td
class="code" id="p88code25"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> Observer<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
<span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>The event sends the new value and the source (class) of it. The source is needed because if the one who sent the information is also a subscriber it should not react to notification.</p><div
class="wp_codebox"><table><tr
id="p8826"><td
class="code" id="p88code26"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">delegate</span> <span style="color: #6666cc; font-weight: bold;">void</span> ValueChangeDelegate<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, T value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> ValueChangeDelegate ValueChangeNotification<span style="color: #008000;">;</span></pre></td></tr></table></div><p>The Observer holds the current value (last value sent) and if an update contains it there is no need of notification because no changes take place. The update method compares the new value with the current one and checks for subscribers. If the values are different and subscribers exist it raises the event.</p><div
class="wp_codebox"><table><tr
id="p8827"><td
class="code" id="p88code27"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Update<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> source, T value<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>currentValue <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>currentValue<span style="color: #008000;">.</span><span style="color: #0000FF;">Equals</span><span style="color: #008000;">&#40;</span>value<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> ValueChangeNotification <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
            ValueChangeNotification<span style="color: #008000;">&#40;</span>source, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">else</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>value <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span> ValueChangeNotification <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
            ValueChangeNotification<span style="color: #008000;">&#40;</span>source, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    currentValue <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>Combining the code above and adding constructors we obtain the Observer.</p><div
class="wp_codebox"><table><tr
id="p8828"><td
class="code" id="p88code28"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> Observer<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">delegate</span> <span style="color: #6666cc; font-weight: bold;">void</span> ValueChangeDelegate<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> sender, T value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> ValueChangeDelegate ValueChangeNotification<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> T currentValue<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> Observer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        currentValue <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">default</span><span style="color: #008000;">&#40;</span>T<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> Observer<span style="color: #008000;">&#40;</span>T initValue<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        currentValue <span style="color: #008000;">=</span> initValue<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Update<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> source, T value<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>currentValue <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>currentValue<span style="color: #008000;">.</span><span style="color: #0000FF;">Equals</span><span style="color: #008000;">&#40;</span>value<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> ValueChangeNotification <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
                ValueChangeNotification<span style="color: #008000;">&#40;</span>source, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">else</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>value <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span> ValueChangeNotification <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
                ValueChangeNotification<span style="color: #008000;">&#40;</span>source, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        currentValue <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p>Let&#8217;s create a small test application that has two text boxes and syncronizes their texts.</p><ol><li>Create a new Windows Forms Application in Visual Studio and add two text boxes on the main form.</li><li>Create events for text change (double click each text box).</li><li>Now add the Binding class to your project and create a new Observer object for string as a member the form&#8217;s class. Let&#8217;s call it textObserver.</li><li>Now create a method for the update event &#8211; a method with two parameter: an object and a string &#8211; and subscribe to the event.</li><li>Update the observer when the text changes in one text box.</li></ol><p>If you are having problems in creating the application you can download the final version from <a
href="http://victorhurdugaci.com/wp-content/uploads/binding1.zip">here</a>. Change the text in one text box and it should also update the other one.</p><p>Part 2 of this tutorial will explain how to synchronize properties that have different values and need conversion. It will be posted soon.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/binding-in-winforms-like-in-wpf-1/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How expensive are cross-domain operations?</title><link>http://victorhurdugaci.com/cross-domain-operations/</link> <comments>http://victorhurdugaci.com/cross-domain-operations/#comments</comments> <pubDate>Sun, 27 Apr 2008 22:41:30 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[AppDomain]]></category> <category><![CDATA[Cross domain]]></category> <category><![CDATA[Programming]]></category> <category><![CDATA[Visual Studio]]></category> <guid
isPermaLink="false">http://victorhurdugaci.wordpress.com/?p=44</guid> <description><![CDATA[I was curios how expensive is a cross domain operation so I have made a test. The test procedure is simple. Perform a number of cross-domain and non cross-domain operations (get the value of NextNumber() from same domain and from another domain) and measure the time elapsed. For each value I have runned the application [...]]]></description> <content:encoded><![CDATA[<p>I was curios how expensive is a cross domain operation so I have made a test.</p><p>The test procedure is simple. Perform a number of cross-domain and non cross-domain operations (get the value of NextNumber() from same domain and from another domain) and measure the time elapsed. For each value I have runned the application 3 times, recorded the time (in milliseconds) and created the mean of this three.</p><p>For this I&#8217;ve created a Console Application containing two classes, the main class and &#8220;NumberClass&#8221; which has a method that returns the next long. The code for this two is below:</p><p>NumberClass:</p><pre><span style="color: #008000;">//MarshalByRefObject is used because this object will cross domain boundary</span>
<span style="color: #0000ff;">class </span><span style="color: #33cccc;">NumberClass</span>:<span style="color: #33cccc;">MarshalByRefObject</span>
{
    <span style="color: #0000ff;">public ulong </span>number = 0;
    <span style="color: #0000ff;">public ulong </span>NextNumber()
    {
        <span style="color: #0000ff;">return </span>number++;
    }
}</pre><p>The Main method from the main class:</p><p><span
id="more-17"></span></p><pre><span style="color: #0000ff;">static void</span> Main(<span style="color: #0000ff;">string</span>[] args)
{
    <span style="color: #008000;">//Uncomment this two lines to load the class in another app domain
    //System.AppDomain appDom = System.AppDomain.CreateDomain("TestAppDomain");
    //NumberClass n = (NumberClass)appDom.CreateInstanceAndUnwrap("AppDomain", "AppDomain.NumberClass");</span>
    <span style="color: #33cccc;">NumberClass</span> n = new <span style="color: #33cccc;">NumberClass</span>(); <span style="color: #008000;">//Comment this line if uncomment the two above</span>
    <span style="color: #33cccc;">DateTime </span>start = <span style="color: #33cccc;">DateTime</span>.Now;
    <span style="color: #008000;">//We are going to change the value of i </span>
    <span style="color: #0000ff;">for </span>(<span style="color: #0000ff;">ulong </span>i = 0; i &lt; 10; i++)
    {
        n.NextNumber();
    }
    <span style="color: #33cccc;">DateTime </span>end = <span style="color: #33cccc;">DateTime</span>.Now;
    <span style="color: #33cccc;">TimeSpan </span>elapsedTime = end - start;
    <span style="color: #33cccc;">Console</span>.WriteLine("Elapsed time: {0} ms", elapsedTime.TotalMilliseconds);
    <span style="color: #33cccc;">Console</span>.ReadLine();
}</pre><p>The values of <strong>i </strong>are: 1, 10, 100, 1.000,  10.000, 100.000, 1.000.000 so a total of 42 measurements were performed. The test system is a Core2Duo 2Ghz, 2GB Ram 667 running Windows Vista Business x32 and Visual Studio 2008 Professional.</p><p>Let&#8217;s see the results:</p><p
style="text-align:center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2008/04/resulttable.jpg"><img
class="aligncenter size-medium wp-image-45" src="http://victorhurdugaci.com/wp-content/uploads/2008/04/resulttable.jpg?w=300" alt="Results Table" width="300" height="98" /></a></p><p>Please note that the tallest bar from the left graph is almost the smallest from the right one :)</p><p
style="text-align:center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2008/04/resultgraph.jpg"><img
class="aligncenter size-medium wp-image-46" src="http://victorhurdugaci.com/wp-content/uploads/2008/04/resultgraph.jpg?w=300" alt="Results Graph" width="300" height="150" /></a></p><p><strong>Conclusion</strong>: using AppDomains is cool, is useful but use them wisely because a large number of cross domain operations drastically affect performances.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/cross-domain-operations/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>EventInfo.AddEventHandler &#8211; bug or not?</title><link>http://victorhurdugaci.com/eventinfoaddeventhandler-bug-or-not/</link> <comments>http://victorhurdugaci.com/eventinfoaddeventhandler-bug-or-not/#comments</comments> <pubDate>Wed, 16 Apr 2008 20:49:29 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Bug]]></category> <category><![CDATA[EventInfo.AddEventHandler]]></category> <category><![CDATA[Programming]]></category> <category><![CDATA[Visual Studio]]></category> <guid
isPermaLink="false">http://victorhurdugaci.wordpress.com/?p=19</guid> <description><![CDATA[Reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming. [Wikipedia] Working a few days ago on a plugin architecture on .NET Framework I&#8217;ve found something very interesting. The method System.Reflection.EventInfo.AddEventHandler does late-binding. You&#8217;ll probably say &#8220;so [...]]]></description> <content:encoded><![CDATA[<blockquote><p>Reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming. [Wikipedia]</p></blockquote><p>Working a few days ago on a plugin architecture on .NET Framework I&#8217;ve found something very interesting. The method System.Reflection.EventInfo.AddEventHandler does late-binding. You&#8217;ll probably say &#8220;so what?&#8221;. Let&#8217;s see the problem with an example:</p><p>Using Visual Studio 2005/2008, create two C# projects (a windows forms application project and a class library one). Rename the class from the class library project to &#8220;TestClass.cs&#8221;.</p><p
style="text-align:center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2008/04/projectstart.jpg"><img
class="aligncenter size-medium wp-image-27" src="http://victorhurdugaci.com/wp-content/uploads/2008/04/projectstart.jpg?w=400" alt="" width="400" height="231" /></a></p><p><span
id="more-12"></span>We are going to dynamically load the dll and add his public methods that begin with &#8220;Method&#8221; to respond to some menu item clicks.</p><p>First we need the dll code. Let&#8217;s add three methods (don&#8217;t forget to add a reference to System.Windows.Forms because we&#8217;ll show some message boxes):</p><pre><span style="color: #0000ff;">public class</span> TestClass
{
<span><span style="color: #0000ff;">    </span></span><span style="color: #0000ff;">public static void</span> Method1()
<span style="color: #0000ff;">    </span>{
MessageBox.Show(<span style="color: #ff0000;">"Method1"</span>);
}
<span style="color: #0000ff;">    public static void</span> Method2()
<span><span style="color: #0000ff;">    </span></span>{
<span><span style="color: #0000ff;">    </span></span><span><span style="color: #0000ff;">    </span></span>MessageBox.Show(<span style="color: #ff0000;">"Method2"</span>);
<span><span style="color: #0000ff;">    </span></span>}
<span><span style="color: #0000ff;">    </span></span><span style="color: #0000ff;">public static void</span> Method3()
<span><span style="color: #0000ff;">    </span></span>{
<span><span style="color: #0000ff;">    </span></span><span><span style="color: #0000ff;">    </span></span>MessageBox.Show(<span style="color: #ff0000;">"Method3"</span>);
<span><span style="color: #0000ff;">    </span></span>}
}</pre><p>That&#8217;s it, we have finished with the class library :-)</p><p>Now go the the windows forms project, in Form1.cs and add a MenuStrip (name it &#8220;menuStrip&#8221;) and on this add one MenuItem (named &#8220;menu1&#8243;).</p><p
style="text-align:center;"><img
class="aligncenter size-medium wp-image-28" src="http://victorhurdugaci.com/wp-content/uploads/2008/04/form1.jpg?w=400" alt="" width="400" height="231" /></p><p>It&#8217;s time to write some code that loads the dll. First add the needed using, &#8220;using System.Reflection&#8221;, and then, on the Load event of Form1 write:<a
href="../2008/04/16/eventinfoaddeventhandler-is-it-a-bug-or-not/" target="_blank"></a></p><pre><span style="color: #33cccc;">Assembly </span>classLib = <span style="color: #33cccc;">Assembly.</span>LoadFrom<span style="color: #33cccc;">(</span><span style="color: #33cccc;">AppDomain.</span>CurrentDomain.BaseDirectory + <span style="color: #ff0000;">"ClassLibrary.dll"</span>);
<span style="color: #33cccc;">Type </span>t = classLib.GetType(<span style="color: #ff0000;">"ClassLibrary.TestClass"</span>);</pre><p>Ok, now we have the assembly loaded and we want to subscribe with each of it&#8217;s methods that begin with &#8220;Method&#8221; to a menu item click. Let&#8217;s find the methods that begin with &#8220;Method&#8221;, create a menu item and subscribe to the event, using AddEventHandler, with a delegate that invokes the method from dll.</p><pre>foreach (<span style="color: #33cccc;">MethodInfo </span>method in t.GetMethods())
{
    if (method.Name.IndexOf(<span style="color: #ff0000;">"Method"</span>) == 0)
    {
<span style="color: #33cccc;">        ToolStripItem</span> newMenuItem = menu1.DropDownItems.Add(method.Name)<span style="color: #339966;">       </span>
<span style="color: #33cccc;">        EventInfo</span> e = newMenuItem .GetType().GetEvent(<span style="color: #ff0000;">"Click"</span>);
        e.AddEventHandler(newMenuItem, <span style="color: #0000ff;">new </span><span style="color: #33cccc;">EventHandler</span>(<span style="color: #0000ff;">delegate</span>(<span style="color: #0000ff;">object </span>sender, <span style="color: #33cccc;">EventArgs </span>ev)
            {
                method.Invoke(<span style="color: #0000ff;">null</span>, <span style="color: #0000ff;">null</span>);
            }
        ));
    }
}</pre><p>The code compiles, and our form shows with the menu we wanted :D (<em>oh yeah!!</em>).</p><p><a
href="http://victorhurdugaci.com/wp-content/uploads/2008/04/firstrun.jpg"></a><a
href="http://victorhurdugaci.files.wordpress.com/2008/04/FirstRun.jpg"> </a></p><p
style="text-align:center;"><img
class="aligncenter size-medium wp-image-29" src="http://victorhurdugaci.com/wp-content/uploads/2008/04/firstrun.jpg?w=400" alt="" width="400" height="315" /></p><p>Let&#8217;s click a Method1 item&#8230; Huh? Exception&#8230; Something is strange. I&#8217;ve subscribed with static methods and I receive &#8220;Non-static method requires a target.&#8221;.</p><p>Just adding a watch on &#8220;method&#8221; reveals the truth&#8230; I&#8217;ve subscribed with &#8220;GetHashCode()&#8221; which is not a static method. <em>Probably my fault &#8211; bad code. </em>Add a break point where the method is added to the delegate and surprise: &#8220;Method1()&#8221;. When I first saw this I was so confused. I didn&#8217;t knew if this is a bug, my fault or something normal. Searching on MSDN revealed the <a
href="http://msdn2.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx">&#8220;supreme&#8221; truth</a>:</p><blockquote><p>All actions are performed using late binding.</p></blockquote><p>This way I&#8217;ve found out that you cannot subscribe directly to an event with a set of methods and get the right result. If you watch every delegate from the event above you&#8217;ll see that all of them are pointing to &#8220;GetHashCode()&#8221; even though you subscribed with something else.</p><p>Is it a bug or not?</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/eventinfoaddeventhandler-bug-or-not/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> </channel> </rss>
