<?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; Tutorial</title> <atom:link href="http://victorhurdugaci.com/category/tutorial/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>Dynamic tests with mstest and T4</title><link>http://victorhurdugaci.com/dynamic-tests-with-mstest-and-t4/</link> <comments>http://victorhurdugaci.com/dynamic-tests-with-mstest-and-t4/#comments</comments> <pubDate>Sat, 05 Mar 2011 12:41:14 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[mstest]]></category> <category><![CDATA[t4]]></category> <category><![CDATA[text template]]></category> <category><![CDATA[Visual Studio]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=2256</guid> <description><![CDATA[If you used mstest and NUnit you might be aware of the fact that the former doesn&#8217;t support dynamic, data driven test cases. For example, the following scenario cannot be achieved with the out-of-box mstest: given a dataset, create distinct test cases for each entry in it, using a predefined generic test case. The best [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">If you used <em>mstest </em>and <em>NUnit </em>you might be aware of the fact that the former doesn&#8217;t support dynamic, data driven test cases. For example, the following scenario cannot be achieved with the out-of-box mstest: given a dataset, create <strong>distinct </strong>test cases for each entry in it, using a predefined generic test case.</p><p
style="text-align: justify;">The best result that can be achieved using mstest is a <strong>single </strong>testcase that will iterate through the dataset. There is one disadvantage: if the test fails for one entry in the dataset, the whole test case fails.</p><p
style="text-align: justify;">So, in order to overcome the previously mentioned limitation, I decided to create a text template that will generate the test cases for me. As an example, I will write some tests for an integer multiplication function that has 2 bugs in it:</p><pre class="brush: csharp; title: ; notranslate">
public int Multiply(int a, int b)
{
    //This conditions are simulating the 2 bugs
    if (a == 0 &amp;&amp; b == 1)
        return 100;
    if (a == 1 &amp;&amp; b == 0)
        return -100;
    return a * b;
}</pre><h3>The classical approach (no dynamic test)</h3><p
style="text-align: justify;">Without using any &#8216;hacks&#8217;, one could write the tests for the <em>Multiply</em> function in the following way:</p><pre class="brush: csharp; title: ; notranslate">
//Tuple description &lt;value of param a, value of param b, expected result&gt;
private static readonly Tuple&lt;int, int, int&gt;[] TestData = new Tuple&lt;int, int, int&gt;[]{
    new Tuple&lt;int, int, int&gt;(0,0,0),
    new Tuple&lt;int, int, int&gt;(2,3,6),
    new Tuple&lt;int, int, int&gt;(1,0,0), //These will trigger one of the bugs
    new Tuple&lt;int, int, int&gt;(-2,-3,6),
    new Tuple&lt;int, int, int&gt;(0,1,0) //These will trigger one of the bugs
};
[TestMethod]
public void TestMultiply()
{
    foreach (var data in TestData)
    {
        Assert.AreEqual(data.Item3, Multiply(data.Item1, data.Item2),
                        &quot;Failed for input ({0}, {1})&quot;, data.Item1, data.Item2);
    }
}
</pre><p
style="text-align: justify;">Running the test will surface only one of the bugs, the one triggered by the input (1,0):</p><p
style="text-align: center;"><img
class="size-full wp-image-2267" title="Restult_Classic" src="http://victorhurdugaci.com/wp-content/uploads/2011/03/Restult_Classic.png" alt="" width="600" height="160" /></p><p
style="text-align: justify;">This is not only bad because it doesn&#8217;t give a complete overview of the bugs but it also violates the principle of <a
href="http://techblog.daveastels.com/2006/08/27/one-expectation-per-example-a-remake-of-one-assertion-per-test/" target="_blank">one assertion per test</a> because more than one assertion could be triggered in the test case above.</p><h3>The T4 approach (dynamic test)</h3><p><span
id="more-2256"></span>A text templates, from MSDN:</p><blockquote><p>&#8230; is a  mixture of text blocks and control logic that can generate a text file.  The control logic is written as fragments of program code in Visual C#  or Visual Basic. The generated file can be text of any kind, such as a  Web page, or a resource file, or program source code in any language.  Text templates can be used at run time to produce part of the output of  an application. They can also be used for code generation, in which the templates help build part of the source code of an application.</p></blockquote><p
style="text-align: justify;"><a
href="http://msdn.microsoft.com/en-us/library/bb126445.aspx" target="_blank">Text templates</a> are invoked before compilation in order to generate some code that will be used in the compilation process. <a
href="http://msdn.microsoft.com/en-us/library/ee844259.aspx" target="_blank">Preprocessed text templates</a> are used to generate templates that can be invoked at runtime in order to generate new files. I am going to use the former one.</p><p
style="text-align: justify;">So, the goal is to have one assertion per test and show all bugs. For this, different test cases, for each input, are needed. A possible approach would be to write manually each test:</p><pre class="brush: csharp; title: ; notranslate">
[TestMethod]
public void TestMultiply_Input_0_0()
{
    TestMultiply(0, 0, 0);
}
[TestMethod]
public void TestMultiply_Input_2_3()
{
    TestMultiply(2,3,6);
}
[TestMethod]
public void TestMultiply_Input_1_0()
{
    TestMultiply(1, 0, 0);
}
[TestMethod]
public void TestMultiply_Input_Minus2_Minus3()
{
    TestMultiply(-2, -3, 6);
}
[TestMethod]
public void TestMultiply_Input_0_1()
{
    TestMultiply(0, 1, 0);
}
public void TestMultiply(int a, int b, int expected)
{
    Assert.AreEqual(expected, Multiply(a, b), &quot;Failed for input ({0}, {1})&quot;, a, b);
}</pre><p
style="text-align: justify;">While this approach doesn&#8217;t violate the two principles above, it creates a code that is hard to maintain and is a pain to write it for many inputs. Just imagine having 100 tuples in the dataset. The result is the expected one:</p><p
style="text-align: center;"><img
class="size-full wp-image-2268" title="Restult_Dynamic" src="http://victorhurdugaci.com/wp-content/uploads/2011/03/Restult_Dynamic.png" alt="" width="600" height="220" /></p><p
style="text-align: justify;">A smarter approach is to generate all those test methods. Can you see the pattern they follow?</p><ul
style="text-align: justify;"><li>The title of the method is composed of the string &#8220;TestMultiply_Input_&#8221; followed by the first input value, followed by the string &#8220;_&#8221; and then followed by the second input value</li><li>The body of the method is made by a call to a generic test method (TestMultiply) using the two input values and the expected result</li><li>For negative values, the minus sign is replaced by the literal &#8220;Minus&#8221;</li></ul><p
style="text-align: justify;">So, a text template (not a preprocessed text template!) can be written to the test cases. It can be added to a Visual Studio 2010 project by adding a new item of type &#8220;Visual C# Items\General\Text Template&#8221;. I will name the file &#8220;GeneratedTestCases.tt&#8221; and the generated code file will be &#8220;GeneratedTestCases.generated.cs&#8221;.</p><pre class="brush: csharp; title: ; notranslate">
&lt;#@ template debug=&quot;false&quot; hostspecific=&quot;true&quot; language=&quot;C#&quot; #&gt;
&lt;#@ output extension=&quot;.generated.cs&quot; #&gt;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
    [TestClass]
    public class MultiplicationTests
    {
&lt;#
//Tuple description &lt;value of param a, value of param b, expected result&gt;
Tuple&lt;int, int, int&gt;[] TestData = new Tuple&lt;int, int, int&gt;[]{
    new Tuple&lt;int, int, int&gt;(0,0,0),
    new Tuple&lt;int, int, int&gt;(2,3,6),
    new Tuple&lt;int, int, int&gt;(1,0,0), //These will trigger one of the bugs
    new Tuple&lt;int, int, int&gt;(-2,-3,6),
    new Tuple&lt;int, int, int&gt;(0,1,0) //These will trigger one of the bugs
};
foreach (var data in TestData)
{
#&gt;
		[TestMethod]
		public void TestMultiply_Input_&lt;#= data.Item1.ToString().Replace(&quot;-&quot;, &quot;Minus&quot;) #&gt;_&lt;#= data.Item2.ToString().Replace(&quot;-&quot;, &quot;Minus&quot;) #&gt;()
		{
			TestMultiply(&lt;#= data.Item1 #&gt;, &lt;#= data.Item2 #&gt;, &lt;#= data.Item3 #&gt;);
		}
&lt;#
}
#&gt;
		public void TestMultiply(int a, int b, int expected)
        {
            Assert.AreEqual(expected, Multiply(a, b), &quot;Failed for input ({0}, {1})&quot;, a, b);
        }
	//Just write this method here. In reality, this method will be somewhere else
	public int Multiply(int a, int b)
        {
            //This conditions are simulating the 2 bugs
            if (a == 0 &amp;&amp; b == 1)
                return 100;
            if (a == 1 &amp;&amp; b == 0)
                return -100;
            return a * b;
        }
    }
}
</pre><p
style="text-align: justify;">This text template will generate the test class. It looks quite ugly and writing it is not trivial because there is not intellisense or syntax coloring in Visual Studio.</p><p
style="text-align: justify;">Let me explain what it does:</p><ol
style="text-align: justify;"><li>All the text that is not between &lt;# #&gt;, &lt;#@ #&gt; or &lt;#= #&gt; is just copied to the output file (ex: lines 3-12)</li><li>Line 2 specifies the extension of the output file</li><li>Code between &lt;# #&gt; is C# code and will be executed at generation time</li><li>Code between &lt;#= #&gt; is C# code, will be executed at generation time and it&#8217;s output will be written to the generated file. It must be a single statement returning a non void value.</li><li>For each tuple in the data set, a test method is written to the output file.</li></ol><p
style="text-align: justify;">It can be improved a little by working with partial classes. Instead of writing all the code in the tt file, the C# code can be placed in a cs file. So, I&#8217;ll do some changes to the tt file by removing the last methods and making the class partial:</p><pre class="brush: csharp; title: ; notranslate">
&lt;#@ template debug=&quot;false&quot; hostspecific=&quot;true&quot; language=&quot;C#&quot; #&gt;
&lt;#@ output extension=&quot;.generated.cs&quot; #&gt;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
    [TestClass]
    public partial class MultiplicationTests
    {
&lt;#
//Tuple description &lt;value of param a, value of param b, expected result&gt;
Tuple&lt;int, int, int&gt;[] TestData = new Tuple&lt;int, int, int&gt;[]{
    new Tuple&lt;int, int, int&gt;(0,0,0),
    new Tuple&lt;int, int, int&gt;(2,3,6),
    new Tuple&lt;int, int, int&gt;(1,0,0), //These will trigger one of the bugs
    new Tuple&lt;int, int, int&gt;(-2,-3,6),
    new Tuple&lt;int, int, int&gt;(0,1,0) //These will trigger one of the bugs
};
foreach (var data in TestData)
{
#&gt;
		[TestMethod]
		public void TestMultiply_Input_&lt;#= data.Item1.ToString().Replace(&quot;-&quot;, &quot;Minus&quot;) #&gt;_&lt;#= data.Item2.ToString().Replace(&quot;-&quot;, &quot;Minus&quot;) #&gt;()
		{
			TestMultiply(&lt;#= data.Item1 #&gt;, &lt;#= data.Item2 #&gt;, &lt;#= data.Item3 #&gt;);
		}
&lt;#
}
#&gt;
    }
}
</pre><p
style="text-align: justify;">Then, create a class called &#8220;MultiplicationTests&#8221; that is also partial and contains the methods removed from the tt file:</p><pre class="brush: csharp; title: ; notranslate">
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
    partial class MultiplicationTests
    {
        public void TestMultiply(int a, int b, int expected)
        {
            Assert.AreEqual(expected, Multiply(a, b), &quot;Failed for input ({0}, {1})&quot;, a, b);
        }
        //Just write this method here. In reality, this method will be somewhere else
        public int Multiply(int a, int b)
        {
            //This conditions are simulating the 2 bugs
            if (a == 0 &amp;&amp; b == 1)
                return 100;
            if (a == 1 &amp;&amp; b == 0)
                return -100;
            return a * b;
        }
    }
}
</pre><p
style="text-align: justify;">Now regenerate the template and compile.</p><h3 style="text-align: justify;">Conclusion</h3><p
style="text-align: justify;">The presented approach is good and definetely has some advantages but is not perfect. Here are some dissadvantages:</p><ul
style="text-align: justify;"><li>Text Template editor, in VS, is just plain text with not syntax coloring or intellisense</li><li>The compilation errors are sometime ambiguous</li><li><a
href="http://msdn.microsoft.com/en-us/library/bb126338.aspx" target="_blank">Debugging a text template</a> is something you would like to avoid :)</li><li>For a few test cases, more code is written</li><li>In case of new test cases, the code must be recompiled</li></ul><p
style="text-align: justify;">Advantages:</p><ul
style="text-align: justify;"><li>Shows more bugs earlier</li><li>Allows one assertion per test even for large data sets</li><li>The code is compiled and not evaluated at runtime (maybe there is a performance gain)</li><li>Less manual code duplication</li></ul><p
style="text-align: justify;">Advice: try to write as less code as possible in the tt file. Move as much as possible to cs files. Any assembly, except the one in which the tt file is, can be referenced at generation time.</p><p
style="text-align: justify;">If you have troubles going through this tutorial, download the complete C# project: <a
href="http://victorhurdugaci.com/download/TTSample.zip"><img
src="http://victorhurdugaci.com/img/download-icon.jpg" alt="Download Icon" width="24" height="24" />T4_mstest (3.56 kB)</a></p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/dynamic-tests-with-mstest-and-t4/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <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>Fancy windows previewer</title><link>http://victorhurdugaci.com/fancy-windows-previewer/</link> <comments>http://victorhurdugaci.com/fancy-windows-previewer/#comments</comments> <pubDate>Wed, 05 May 2010 09:45:55 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Beginner]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[DWM]]></category> <category><![CDATA[Win32]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1961</guid> <description><![CDATA[Tutorial description Objective Create a fancy-looking application that displays the preview of the open applications. Covered topics Enumerating windows and getting various information about them Creating the Aero glass effect Using the DWM windows preview feature Requirements Windows Vista/7 with the Aero theme active Visual Studio 2010 (or 2008 but requires some changes in code [...]]]></description> <content:encoded><![CDATA[<table
cellspacing="0" border="1" class="tutorial-description"><tr><th
colspan="2">Tutorial description</th></tr><tr><td
class="header-column">Objective</td><td><p>Create a fancy-looking application that displays the preview of the open applications.</p><p
style="text-align: center"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/05/finalresult.jpg"><img
src="http://victorhurdugaci.com/wp-content/uploads/2010/05/finalresult.jpg" alt="" title="finalresult" width="550" height="242" class="alignnone size-full wp-image-1982" /></a></p></td></tr><tr><td
class="header-column">Covered topics</td><td><ul><li>Enumerating windows and getting various information about them</li><li>Creating the Aero glass effect</li><li>Using the DWM windows preview feature</li></ul></td></tr><tr><td
class="header-column">Requirements</td><td><ul><li>Windows Vista/7 with the Aero theme active</li><li>Visual Studio 2010 (or 2008 but requires some changes in code which are not covered by this tutorial)</li></ul></td></tr><tr><td
class="header-column">Target audience</td><td>Intermediate users</td></tr><tr><td
class="header-column">Download</td><td><a
href="http://victorhurdugaci.com/download/taskswitcher.zip"><img
src="http://victorhurdugaci.com/img/download-icon.jpg" alt="Download Icon" width="24" height="24" />TaskSwitcher (13.07 KB)</a></td></tr></table><p
style="text-align: justify">The basic idea behind this application is the following: upon start, we create snapshot (a list) of all the available windows and we use it to decide what previews to display. Once the list is created, a preview is drawn for each item. There is a drawback for this approach: if new windows are created or some existing are closed the interface will not display them (actually for closed windows will replace the preview with an icon). The advantage: is a simple implementation.</p><p
style="text-align: justify">There are three parts for this project.</p><ol><li>Enumerating only the open applications&#8217; windows</li><li>Make a glass window</li><li>Generate a live preview for each window</li></ol><h2>Enumerating windows</h2><p
style="text-align: justify">Enumerating all windows can be done with the <em>EnumWindows</em> function from <em>user32.dll</em> which can be easily imported in C#.</p><pre class="brush: csharp; title: ; toolbar: false; notranslate">
[DllImport(&quot;user32.dll&quot;)]
private static extern int EnumWindows(EnumWindowsCallbackDelegate callback, int lParam = 0);
private delegate bool EnumWindowsCallbackDelegate(IntPtr hWnd, int lParam);
</pre><p
style="text-align: justify">However, the result of a pure enumeration will return hundreds of windows. The most powerful filtration is to keep just the windows that are visible. Again, a function from <em>user32.dll</em> called <em>IsWindowVisible</em> is used to check whether a hWnd belongs to a visible window. Probably, after this step you will have just 30-40 windows left in the list.</p><pre class="brush: csharp; title: ; toolbar: false; notranslate">
[DllImport(&quot;user32.dll&quot;)]
private static extern bool IsWindowVisible(IntPtr hWnd);
</pre><p
style="text-align: justify">The next step is to decide which is the most meaningful representative window from each cluster of windows related by ownership. The Old New Thing blog presents <a
href="http://blogs.msdn.com/oldnewthing/archive/2007/10/08/5351207.aspx" target="blank">an algorithm</a> for this problem. The logic behind this algorithm is: &#8220;For each visible window, walk up its owner chain until you find the root owner. Then walk back down the visible last active popup chain until you find a visible window. If you&#8217;re back to where you&#8217;re started, then put the window in the Alt+Tab list.&#8221; A few Dll imports and the translation of the pseudocode to C# gives the following code.</p><p><span
id="more-1961"></span></p><pre class="brush: csharp; title: ; notranslate">
private static bool IsWindowChainVisible(IntPtr hWnd)
{
    // Start at the root owner
    IntPtr hwndWalk = GetAncestor(hWnd);
    // Basically we try get from the parent back to that window
    IntPtr hwndTry;
    while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry)
    {
        if (IsWindowVisible(hwndTry)) break;
        hwndWalk = hwndTry;
    }
    return (hwndWalk == hWnd);
}
</pre><p
style="text-align: justify">At this point you probably filtered most windows. However, there are still a few that refuse to be filtered out:</p><ol><li>The desktop window</li><li>Our application window</li><li>The taskbar</li></ol><h3>Removing the desktop window</h3><p
style="text-align: justify">Depending on what you want to do, you may decide to keep this window. The task switcher in Windows 7 provides also the preview for the desktop. However, if you decide to to remove it, you have the check each handle against the desktop handle (which can be obtained using the <em>GetShellWindow</em> from <em>user32.dll</em>).</p><pre class="brush: csharp; title: ; toolbar: false; notranslate">
[DllImport(&quot;user32.dll&quot;)]
private static extern IntPtr GetShellWindow();
</pre><h3>Removing our application window</h3><p
style="text-align: justify">One naive approach would be to ignore the windows with a specific title. This is bad because many windows can have the same title. The correct approach is to filter based on the window handle. I created a list of ignored handled and, after the main window was created, I added its handle in this list. Because WPF is used, the handle of a window can be obtained using <a
href="http://msdn.microsoft.com/en-us/library/system.windows.interop.windowinterophelper.aspx" target="blank">WindowInteropHelper</a> class.</p><h3>Removing the taskbar</h3><p
style="text-align: justify">This was tricky and I&#8217;m still not sure is the correct approach. There is one window in the list that is not filtered by the previous filters. Even more, is not visible with Spy++ (!!!) and it&#8217;s preview is the taskbar. The only solution I found and seems to remove just that window, is to filter out all windows that don&#8217;t have the <em>WS_EX_APPWINDOW</em> style. If you find any window that is not displayed because of this, let me know.</p><p
style="text-align: justify">Finally, the method that decides which window goes into the snapshot is presented below:</p><pre class="brush: csharp; title: ; notranslate">
//This function will be called for each available window
private bool EnumWindowsCallback(IntPtr hWnd, int lParam)
{
    bool IsDesktopWindow = (hWnd == GetShellWindow());
    bool IsVisible = IsWindowVisible(hWnd);
    bool IsChainVisible = IsWindowChainVisible(hWnd);
    bool IsInIgnoreList = (WindowHandlesToIgnore.Contains(hWnd));
    //Filters the taskbar
    bool IsApplicationWindow = ((GetWindowLong(hWnd) &amp; WS_EX_APPWINDOW) == WS_EX_APPWINDOW);
    if (!IsDesktopWindow &amp;&amp; IsVisible &amp;&amp; IsChainVisible &amp;&amp; !IsInIgnoreList &amp;&amp; IsApplicationWindow)
    {
        windowsSnapshot.Add(new WindowInfo(hWnd));
    }
    return true;
}
</pre><p
style="text-align: justify">Once we have a snapshot of the visible windows we plan to display them. As seen in the objective screenshot, the main window is transparent and has a glass effect.</p><h2>The glass window</h2><p
style="text-align: justify">It is very important to understand that the glass effect is available only on Windows Vista and 7 and works as long as you have the Aero theme enabled!</p><p
style="text-align: justify">The glass effect functions are part of the <a
href="http://msdn.microsoft.com/en-us/library/aa969540%28VS.85%29.aspx" target="blank">Desktop Window Manager API</a> represented by the library <em>dwmapi.dll</em>. All the functions were imported from that DLL.</p><p
style="text-align: justify">In order to make (a part of) a window transparent you need to:</p><ol><li>Make the windows background transparent (paint it with a transparent brush)</li><li>Call the <em>DwmExtendFrameIntoClientArea</em> function specifying the window handle and the inner region of the window that will have the glass effect (you specify the margins from the inner border). If you want the whole window to be transparent specify a negative (-1) margin for all sides.</li></ol><pre class="brush: csharp; title: ; notranslate">
private void MakeGlassEffect()
{
    if (DwmIsCompositionEnabled())
    {
        IntPtr mainWindowPtr = new WindowInteropHelper(this).Handle;
        HwndSource mainWindowSrc = HwndSource.FromHwnd(mainWindowHandle);
        mainWindowSrc.CompositionTarget.BackgroundColor = Colors.Transparent;
        this.Background = Brushes.Transparent;
        MARGINS margins = new MARGINS();
        margins.ExtendToWholeClientArea(); //Sets all values to -1
        int result = DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
        if (result &lt; 0)
        {
            MessageBox.Show(&quot;An error occured while extending the glass unit.&quot;);
            Application.Current.Shutdown();
        }
    }
}
</pre><h2>Live windows preview</h2><p
style="text-align: justify">As  you might already know, when you press Alt+Tab in Windows Vista/7 (and Aero is active!) you see a live preview of the running applications. In the past, the only method of generating a preview for a window was to copy whatever was visible from it to a bitmap. This approach works as long as the windows is completely visible (no other window is on top, the windows is not out of the screen and the window is not minimized). Trying to save a screenshot with this method will fail, unless you take every window, restore it&#8217;s state, bring it to front, take a screenshot and move it back &#8211; by the way, this action takes too much time and is messy.</p><p
style="text-align: justify">In <em>dwmapi.dll</em> we have a set of functions that will generate thumbnails for any opened window. The interesting part is that the preview is not static! It will modify as the window changes. The function <em>DwmRegisterThumbnail</em> defines a region on which the Desktop Window Manager is allowed to draw the preview for a specific window. So, instead of you drawing the picture, you just specify a region and the DWM will do it for you. One important aspect is that DWM will draw the preview as the top layer &#8211; everything on the window will be behind the preview. There are some parameters that you can specify for how the drawing is made (transparency, visibility, etc.) but these are out of the scope of this tutorial.</p><p
style="text-align: justify">To &#8216;translate&#8217; the drawing into code we are first going to check if the window has already registered a preview (if so, unregister it), the register a new preview, set the region of the drawing and center the image and finally draw (update) the preview &#8211; which will continue to be updated until is unregistered.</p><pre class="brush: csharp; title: ; notranslate">
private void DrawThumbnail(WindowInfo win, int thumbnailIndex)
{
    IntPtr thumbnail = win.Thumbnail;
    if (thumbnail != IntPtr.Zero)
        DwmUnregisterThumbnail(thumbnail);
    int hResult = DwmRegisterThumbnail(mainWindowHandle, win.HWnd, out thumbnail);
    if (hResult == 0)
    {
        PSIZE size;
        DwmQueryThumbnailSourceSize(thumbnail, out size);
        DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES();
        props.dwFlags = DWM_TNP_VISIBLE | DWM_TNP_RECTDESTINATION | DWM_TNP_SOURCECLIENTAREAONLY;
        props.fVisible = true;
        props.fSourceClientAreaOnly = true;
        //Set the region where the live preview will be drawn
        int left = (thumbnailIndex % MaxThumbnails) * (ThumbnailSize + ThumbnailSpacing);
        int top = (int)(thumbnailIndex / MaxThumbnails) * (ThumbnailSize + ThumbnailSpacing) + WindowTopOffset;
        int right = left + ThumbnailSize;
        int bottom = top + ThumbnailSize;
        props.rcDestination = new RECT(left, top, right, bottom);
        //Center the live preview
        if (size.x &lt; size.y)
        {
            double ScaleFactor = ThumbnailSize / (double)size.y;
            int scaledX = (int)(size.x * ScaleFactor);
            int xOffset = (ThumbnailSize - scaledX) / 2;
            props.rcDestination.Left += xOffset;
            props.rcDestination.Right -= xOffset;
        }
        if (size.y &lt; size.x)
        {
            double ScaleFactor = ThumbnailSize / (double)size.x;
            int scaledY = (int)(size.y * ScaleFactor);
            int yOffset = (ThumbnailSize - scaledY) / 2;
            props.rcDestination.Top += yOffset;
            props.rcDestination.Bottom -= yOffset;
        }
        DwmUpdateThumbnailProperties(thumbnail, ref props);
    }
}
</pre><p
style="text-align: justify">For each available window we are going to choose a region in which its preview can be displayed. Basically, the preview region is a grid (filled from left to right, top to bottom) where each cell is a preview.</p><h2>Known Issues</h2><p
style="text-align: justify">The application offered as download is not perfect and has a series of inconveniences. They are not big problems but I couldn&#8217;t find the time to fix them.</p><ul><li>If the list of available windows is modified, the update is not reflected in the application.</li><li>Previews are no longer centered if you change the size of the window they represent.</li><li>There should be a &#8220;glow&#8221; effect behind the text on glass in order to be visible on any surface. Just like in the Alt-Tab window.</li><li>If clicking an application in the preview list, the focus is not transferred to it.</li></ul> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/fancy-windows-previewer/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Tutorials questionnaire results</title><link>http://victorhurdugaci.com/tutorials-questionnaire-results/</link> <comments>http://victorhurdugaci.com/tutorials-questionnaire-results/#comments</comments> <pubDate>Mon, 03 May 2010 19:43:19 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Personal/Blog]]></category> <category><![CDATA[Tutorial]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1957</guid> <description><![CDATA[After having the results from the tutorials questionnaire, I concluded the following: The opinions around focused vs. complete tutorials are split almost even (56% vs. 44%). However, someone uggested that he prefers focused tutorials (as text) and a download link with the full project. In my opinion this idea is great. Most people prefer tutorials [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">After having the results from the tutorials questionnaire, I concluded the following:</p><ul
style="text-align: justify;"><li>The opinions around focused vs. complete tutorials are split almost even (56% vs. 44%). However, someone uggested that he prefers focused tutorials (as text) and a download link with the full project. In my opinion this idea is great.</li><li>Most people prefer tutorials of a difficulty level above or equal to their proficiency level. However, there were a few anomalies  in the results: some that ranked themselves as &#8216;Advanced&#8217; or &#8216;Intermediate&#8217; prefer beginner tutorials. This might have two explanations: they prefer beginner tutorials for the other programming fields or they just overestimated themselves.</li><li>The result for the tutorial format is conclusive: almost everyone wants text + images. Just a few prefer video tutorials.</li></ul><p
style="text-align: justify;">So, the final result is: intermediate or advanced tutorials, presenting just the essentials parts as text but allowing the download of full source.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/tutorials-questionnaire-results/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Using UAC with C# – Part 3</title><link>http://victorhurdugaci.com/using-uac-with-c-part-3/</link> <comments>http://victorhurdugaci.com/using-uac-with-c-part-3/#comments</comments> <pubDate>Wed, 06 Jan 2010 22:02:28 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[Programming]]></category> <category><![CDATA[UAC]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1716</guid> <description><![CDATA[After a long period since I wrote part 2 of this article I decided to add some extra information. There is one thing that was missed by the previous two articles: the design of UAC enabled applications. If you use Windows Vista/7 then you know that buttons and links which elevate privileges are preceded by [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">After a long period since I wrote <a
href="http://victorhurdugaci.com/using-uac-with-c-part-2/" target="_blank">part 2</a> of this article I decided to add some extra information. There is one thing that was missed by the previous two articles: the design of UAC enabled applications.</p><p
style="text-align: justify;">If you use Windows Vista/7 then you know that buttons and links which elevate privileges are preceded by a shield icon. This is the way Microsoft decided to inform the user about the effect of clicking that control.</p><p
style="text-align: justify;">The first idea that might pop up is the reinvention of the wheel (or shield). In other words you could draw the shield on a button. This is OK except that:</p><ol
style="text-align: justify;"><li>Is not easy</li><li>Will require you to recompile the interface if Microsoft decides to change the icon</li><li>You need the icon in many sizes 16&#215;16, 24&#215;24, 32&#215;32, etc. (extract it from MS&#8217; DLLs)</li><li>Will create a lot of overhead with layout (position icon relative to text size/position)</li></ol><p
style="text-align: justify;">The second method is easier, safer and recommended by MS. All you need to do is send a specific message (<em>BCM_SETSHIELD</em>) to the button if the user has limited privileges and pressing that button will trigger the UAC window. Actually there is a second, tricky, thing that must be done: the style of the button must be &#8220;System&#8221; (in C# &#8220;<a
href="http://msdn.microsoft.com/en-us/library/system.windows.forms.flatstyle.aspx" target="_blank">System.Windows.FlatStyle</a>.System&#8221;). Without this you will not be able to see the shield.</p><p
style="text-align: justify;">The code provided in <a
href="http://victorhurdugaci.com/using-uac-with-c-part-1/" target="_blank">part 1</a> of this article will be modified in order to display the shield on the two buttons. Moreover, the shield will be displayed only when the user runs under an account with limited privileges or non-elevated administrator.</p><p
style="text-align: center;"><img
title="UACShield" src="http://victorhurdugaci.com/wp-content/uploads/2010/01/UACShield.png" alt="" width="700" height="280" /></p><p
style="text-align: justify;">In order to display the shield one needs to send the <em>BCM_SETSHIELD </em>(=<em>0x0000160C)</em> message to the button. This can be done by using the <a
href="http://msdn.microsoft.com/en-us/library/ms644950%28VS.85%29.aspx">SendMessage function from user32.dll</a>. This article will not cover what is and how to use SendMessage, if you need more information about it follow the previous link.</p><p
style="text-align: justify;">To set the shield of the &#8220;Elevate this application&#8221; button one needs to send the message in the following way:</p><div
class="wp_codebox"><table><tr
id="p17164"><td
class="code" id="p1716code4"><pre class="csharp" style="font-family:monospace;">SendMessage<span style="color: #008000;">&#40;</span>btnElevate<span style="color: #008000;">.</span><span style="color: #0000FF;">Handle</span>, BCM_SETSHIELD, <span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">The first parameter is the handle of the button, the second one is the message, the third one is not used and must be &#8217;0&#8242; and the last argument must be non-zero in order to draw the shield, zero otherwise.</p><p
style="text-align: justify;">If you try this it will not work :) Remember the &#8216;tricky&#8217; thing told before? This is the full code to display the shield for <em>btnElevate</em>:</p><div
class="wp_codebox"><table><tr
id="p17165"><td
class="code" id="p1716code5"><pre class="csharp" style="font-family:monospace;">btnElevate<span style="color: #008000;">.</span><span style="color: #0000FF;">FlatStyle</span> <span style="color: #008000;">=</span> FlatStyle<span style="color: #008000;">.</span><span style="color: #000000;">System</span><span style="color: #008000;">;</span>
SendMessage<span style="color: #008000;">&#40;</span>btnElevate<span style="color: #008000;">.</span><span style="color: #0000FF;">Handle</span>, BCM_SETSHIELD, <span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">There is only one thing that must be done in order to work properly. Remove the shield if the user has elevated privileges. I don&#8217;t know if this is against MS&#8217; recommendation but in my opinion one must not be shown information that cannot be used in that context; in our case don&#8217;t show the elevate shield if there is nothing to elevate.</p><p
style="text-align: justify;">Part 1 described how to check if a user has full rights. Now we are just using that boolean variable:</p><div
class="wp_codebox"><table><tr
id="p17166"><td
class="code" id="p1716code6"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>hasAdministrativeRight<span style="color: #008000;">&#41;</span>
    SetUACShields<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;">Where <em>SetUACShields</em> will send the message to all buttons that require the shield drawn.</p><p
style="text-align: justify;">The full updated code from Part 1: <a
href="http://victorhurdugaci.com/download/uacapp3.zip"><img
src="http://victorhurdugaci.com/img/download-icon.jpg" alt="Download Icon" width="24" height="24" />UAC Code 3 (10.13 KB)</a></p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/using-uac-with-c-part-3/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Tip #8: Make Firefox Better</title><link>http://victorhurdugaci.com/tip-8-make-firefox-better/</link> <comments>http://victorhurdugaci.com/tip-8-make-firefox-better/#comments</comments> <pubDate>Thu, 24 Dec 2009 10:21:45 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Tips]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[extension]]></category> <category><![CDATA[Firefox]]></category> <category><![CDATA[Mozilla]]></category> <category><![CDATA[tweak]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1681</guid> <description><![CDATA[What I want from a browser To show the pages correctly To show as much as possible from a page (to remove the need of scrolling) To provide me with an easy way of accessing pages. What I don&#8217;t like at Firefox The search bar is superfluous. I really like what Chrome is doing (and [...]]]></description> <content:encoded><![CDATA[<h3 style="text-align: justify;">What I want from a browser</h3><ol
style="text-align: justify;"><li>To show the pages correctly</li><li>To show as much as possible from a page (to remove the need of scrolling)</li><li>To provide me with an easy way of accessing pages.</li></ol><h3 style="text-align: justify;">What I don&#8217;t like at Firefox</h3><ul
style="text-align: justify;"><li>The search bar is superfluous. I really like what Chrome is doing (and the latest version of Opera?): use the address bar as search bar.</li><li>There is no ad blocker</li><li>There is a lot of wasted space: bookmarks toolbar, menu bar (just think how often you use the top menu), big icons</li></ul><p
style="text-align: justify;">After a few tweaks I got a browser looking like the one in the picture below that satisfies almost all my needs.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/12/firefox-details.jpg"><img
class="aligncenter size-large wp-image-1688" title="firefox" src="http://victorhurdugaci.com/wp-content/uploads/2009/12/firefox-1024x574.jpg" alt="" width="717" height="402" /></a></p><h3 style="text-align: justify;">Tweaks applied and how/why to use them</h3><p><span
id="more-1681"></span></p><ol
style="text-align: justify;"><li><strong>Remove the bookmark toolbar. </strong>You just don&#8217;t need that bar! How often do you click a bookmark? If you need a page opened all the time you just don&#8217;t close it. Why do you minimize the working are just to see some buttons that you click them in an infinite small amount of the time you spend in browser? <strong>How to apply:</strong> right click the menu bar -&gt; Uncheck Bookmarks Toolbar.</li><li><strong>Remove the menu bar. </strong>Just like the bookmark toolbar, you don&#8217;t use it to often. If you want to see it just press Alt+F. <strong>How to apply: </strong>Install the <a
href="https://addons.mozilla.org/en-US/firefox/addon/4762" target="_blank">Hide Menubar extension</a>.</li><li><strong>Merge address bar and search bar. </strong>Is not practical to need to think if you want to search or you want to enter an a priori known address. There should be just on input field and the browser should be able to decide if you want to search or go to some specific place. <strong>How to apply: </strong>First remove the search bar by right clicking the menubar -&gt; Customize and drag the search bar out of the menu. Second navigate to &#8220;about:config&#8221; and search for &#8220;keywork.url&#8221;. Replace its value with &#8220;http://google.com/search?q=&#8221;. This will make Firefox search on Google when it cannot resolve a name.</li><li><strong>Remove ads.</strong> Most of the time you just don&#8217;t want to see &#8220;Super/Extra/Mega/Ultra discount for X&#8221;. Also you don&#8217;t want to see links that are on top of the search list just because they paid. <strong>How to apply: </strong>Install the <a
href="https://addons.mozilla.org/en-US/firefox/addon/1865" target="_blank">Adblock Plus extension</a>.</li><li><strong>Move icons and make them smaller. </strong>This is just a personal preference. I want the bookmarks button in the left corner. And in order to maximize working area I want small icons. <strong>How to apply: </strong>Right click a toolbar -&gt; Customize. Drag/drop the icons you want. For small icons check the appropriate box.</li><li><strong>Mouse gestures. </strong>I like the back button on the toolbar because of the drop down menu but usually I go back by holding the right mouse button and dragging left. The gesture functionality saves a lot of time and movement. <strong>How to apply: </strong>Install the <a
href="https://addons.mozilla.org/en-US/firefox/addon/6366" target="_blank">FireGesture extension</a>.</li><li
style="text-align: justify;"><strong>Protect/sync bookmarks. </strong>Sometimes one might accidentally delete an important bookmark or, even worse, the entire bookmark collection. Is a good idea to backup bookmarks online. This also gives you the possibility of synchronizing bookmarks across multiple machines. <strong>How to apply: </strong>Install the <a
href="https://addons.mozilla.org/en-US/firefox/addon/2410" target="_blank">Xmarks extension</a>.</li></ol><h3>Future work</h3><ol><li><strong>Remove the status bar. </strong>Currently this cannot be done because there is no other way of knowing where a link is sending. Any suggestion?</li><li><strong>Remove the tabs bar. </strong>The tabs bar should be removed in order to get more space but I have no idea where it could go&#8230;</li></ol> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/tip-8-make-firefox-better/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Tip #3: Shared OneNote notebooks with Live Mesh</title><link>http://victorhurdugaci.com/tip-3-shared-onenote-notebooks-with-live-mesh/</link> <comments>http://victorhurdugaci.com/tip-3-shared-onenote-notebooks-with-live-mesh/#comments</comments> <pubDate>Tue, 04 Aug 2009 12:06:47 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Beginner]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tips]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[Live Mesh]]></category> <category><![CDATA[OneNote]]></category> <category><![CDATA[Sync]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1292</guid> <description><![CDATA[OneNote allows users to create shared notebooks by using a shared folder or a SharePoint repository. When two persons who want to share a notebook are in different countries then a shared folder is not a too feasible solution. A SharePoint repository can be created for free on Office Small Business but you have only [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">OneNote allows users to create shared notebooks by using a shared folder or a SharePoint repository. When two persons who want to share a notebook are in different countries then a shared folder is not a too feasible solution. A SharePoint repository can be created for free on Office Small Business but you have only 50 MB for storage and you need at least basic SharePoint knowledge.</p><p
style="text-align: justify;">As you might already know, Live Mesh allows one to sync files across multiple computers. A big advantage is the Live Desktop -  a 5000 MB online storage location that can be used for storage. When computers involved in the sync are not simultaneously online, the files are synced with the Live Desktop and, when the computers are back online, the files will be synced.</p><p
style="text-align: justify;">The sharing with Live Mesh works like this: add notebooks&#8217; files on Mesh and they can sync across computers. When a notebook is updated, if you are online the change will be sent/received to/from the Live Desktop.</p><p
style="text-align: justify;"><span
id="more-1292"></span></p><p
style="text-align: justify;">Advantages of this method:<a
href="http://victorhurdugaci.com/wp-content/uploads/2009/08/AddToLiveMesh.jpg"><img
class="alignright size-medium wp-image-1294" title="AddToLiveMesh" src="http://victorhurdugaci.com/wp-content/uploads/2009/08/AddToLiveMesh-281x300.jpg" alt="AddToLiveMesh" width="281" height="300" /></a></p><ul
style="text-align: justify;"><li>No SharePoint knowledge are necessarily.</li><li>Works on Windows Mobile because Live Mesh has a mobile version.</li><li>Instant sync if you are online.</li><li>More storage space.</li><li>Full control over permissions directly from Explorer.</li><li
style="text-align: justify;">No user interaction for sync.</li><li
style="text-align: justify;">Files are kept offline and can be accessed even with no Internet connection.</li><li
style="text-align: justify;">You can store notebooks wherever you want.</li></ul><p
style="text-align: justify;">Disadvantages:</p><ul
style="text-align: justify;"><li>Need to install Live Mesh (requires administrative rights).</li><li>You can set sharing permissions only on the top folder (depending on how you sync you can share also individual notebooks).</li><li>Live Mesh has many other functionalities that you might not need if you only want to sync notebooks.</li><li>While online you cannot control when to sync.</li><li>All persons involved must have Live Mesh installed.</li></ul><p
style="text-align: justify;">To put your notebooks on Mesh (assuming that you have OneNote installed):</p><ol
style="text-align: justify;"><li>Register for Mesh.</li><li>Install the mesh client by adding your PC to the mesh.</li><li>Select the folder(s) that contain(s):<ol><li>All your notebooks if you want to just backup or share all notebooks.</li><li>Individual notebooks if you want to be able to share selected notebooks.</li></ol></li><li>Right click it/them select &#8220;Add folder to Live Mesh&#8221; (see the image on right). The folder is added to the Live Desktop and you can check it by opening the mesh in a browser.</li><li>That&#8217;s it. The folder is also online and you can share it with whoever you want.</li></ol><p><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/08/Invite.jpg"><img
class="size-medium wp-image-1298 alignright" title="Invite" src="http://victorhurdugaci.com/wp-content/uploads/2009/08/Invite-300x170.jpg" alt="Invite" width="300" height="170" /></a>To share notebooks:</p><ol><li>Select on your local disk a folder that is shared with Mesh.</li><li>In the right sidebar select &#8220;Members&#8221;</li><li>Click &#8220;Invite&#8221;.</li><li>Enter the e-mail addresses of the ones you want to share with and choose their permission level (Owner = full control; Contributor = can read/write but cannot perform special tasks; reader = can get files from Mesh but their updates are not synced).</li><li>Click OK.</li></ol><p
style="text-align: center"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/08/Permission.jpg"><img
class="aligncenter size-medium wp-image-1299" title="Permission" src="http://victorhurdugaci.com/wp-content/uploads/2009/08/Permission-300x173.jpg" alt="Permission" width="300" height="173" /></a></p><p
style="text-align: justify;">Even if you are the only user of a notebook you can use the Live Desktop for backup &#8211; this is how I use it.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/tip-3-shared-onenote-notebooks-with-live-mesh/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Tip 2: #if</title><link>http://victorhurdugaci.com/tip-2-if/</link> <comments>http://victorhurdugaci.com/tip-2-if/#comments</comments> <pubDate>Thu, 23 Jul 2009 19:34:59 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tips]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[#if]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1262</guid> <description><![CDATA[This is a C# tip When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol; the #if statement in C# is Boolean and [...]]]></description> <content:encoded><![CDATA[<h2>This is a C# tip</h2><p
style="text-align: justify;">When the C# compiler encounters an<span><span> #if</span></span> directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol; the #if statement in C# is Boolean and only tests whether the symbol has been defined or not.</p><p
style="text-align: justify;">A predefined (by default) symbol on the &#8220;Debug&#8221; build configuration is <em>DEBUG</em>. Using this symbol you can define code that will be compiled only in Debug; for example, a debug window will be shown only when needed.</p><div
class="wp_codebox"><table><tr
id="p12628"><td
class="code" id="p1262code8"><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.Text</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ConsoleApplication1
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">class</span> Program
    <span style="color: #008000;">&#123;</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>
<span style="color: #008080;">#if DEBUG</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Debugging information&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080;">#endif</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Code that always executes&quot;</span><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></pre></td></tr></table></div><p
style="text-align: justify;">The code above will print<em> &#8220;Debugging information&#8221;</em> and <em>&#8220;Code that always executes&#8221;</em> when build on Debug and will display only <em>&#8220;Code that always executes&#8221;</em> when build on another configuration.</p><p
style="text-align: justify;">You can suppress the definition of the <em>DEBUG</em> symbol from the project properties or by removing the DEBUG from the build argument <em>&#8220;/define:DEBUG&#8221;. </em>Also, you can define your own symbols in order to accommodate your needs.</p><p
style="text-align: justify;">Define as many build configurations and symbols you need but don&#8217;t abuse this feature!</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/tip-2-if/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Tip #1: Backup Outlook 2007 Accounts&#8217; Information</title><link>http://victorhurdugaci.com/tip-1-backup-outlook-2007-accounts-information/</link> <comments>http://victorhurdugaci.com/tip-1-backup-outlook-2007-accounts-information/#comments</comments> <pubDate>Mon, 20 Jul 2009 17:47:28 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Beginner]]></category> <category><![CDATA[Tips]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[Backup]]></category> <category><![CDATA[Export]]></category> <category><![CDATA[Outlook]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1235</guid> <description><![CDATA[This is a series of different tips and tricks for computer users. It will include: software usage tip, hacks, development tips, hardware tips, etc. I will try to post tips every day but I don&#8217;t know if my schedule will allow me. &#8212; When you need to reinstall Windows and/or Outlook you might backup the [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">This is a series of different tips and tricks for computer users. It will include: software usage tip, hacks, development tips, hardware tips, etc.</p><p
style="text-align: justify;">I will try to post tips every day but I don&#8217;t know if my schedule will allow me.</p><p
style="text-align: justify;">&#8212;</p><p
style="text-align: justify;">When you need to reinstall Windows and/or Outlook you might backup the .pst files (Outlook data files). Unfortunately these files do not contain account information. After reinstall and restore of backup files you need to reenter all information about each account which is a boring process &#8211; at least for me because I have 5 e-mail accounts.</p><p
style="text-align: justify;">If you want to backup accounts information you have to export the<em> &#8220;HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook&#8221; </em>key from Registry.</p><p
style="text-align: justify;"><strong>Export accounts&#8217; information:</strong></p><ol
style="text-align: justify;"><li><strong><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/07/Tip_01_01.jpg"><img
class="size-medium wp-image-1239 alignright" title="Tip_01_01" src="http://victorhurdugaci.com/wp-content/uploads/2009/07/Tip_01_01-300x185.jpg" alt="Tip_01_01" width="219" height="135" /></a></strong>Start the Registry Editor (Start -&gt; Run -&gt; &#8220;regedit&#8221;) &#8211; in Windows Vista/7 you need administrative rights to start it.</li><li>Navigate to the previously mentioned branch (HKEY_CURRENT_USER\Software\ &#8230; ).</li><li>Right click the &#8220;Outlook&#8221; tree node.</li><li>Choose export.</li><li>Name the file accordingly.</li><li>Click &#8220;Save&#8221;</li></ol><p
style="text-align: justify;">After reinstalling Outlook, you have to import the accounts. Follow the steps below for this:</p><p
style="text-align: justify;"><strong>Import accounts&#8217; information:</strong></p><ol
style="text-align: justify;"><li>Double click the exported file.</li><li>Choose &#8220;Yes&#8221; when asked if you really want to import.</li></ol> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/tip-1-backup-outlook-2007-accounts-information/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> </channel> </rss>
