<?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; Intermediate</title> <atom:link href="http://victorhurdugaci.com/category/tutorial/tut-intermediate/feed/" rel="self" type="application/rss+xml" /><link>http://victorhurdugaci.com</link> <description>Victor Hurdugaci&#039;s playground</description> <lastBuildDate>Tue, 29 Nov 2011 07:38:40 +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>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>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>1</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 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>Windows Mobile 6.5 on Toshiba G900</title><link>http://victorhurdugaci.com/windows-mobile-65-on-toshiba-g900/</link> <comments>http://victorhurdugaci.com/windows-mobile-65-on-toshiba-g900/#comments</comments> <pubDate>Wed, 03 Jun 2009 18:47:49 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Mobile]]></category> <category><![CDATA[Review]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[PDA]]></category> <category><![CDATA[ROM]]></category> <category><![CDATA[Toshiba Portege G900]]></category> <category><![CDATA[Upgrade]]></category> <category><![CDATA[Windows Mobile]]></category> <category><![CDATA[Windows Mobile 6.5]]></category> <category><![CDATA[WM]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1054</guid> <description><![CDATA[Before writing anything else I must warn all readers that changing the operating systems on your mobile will void the warranty. If the upgrade process fails the phone might be damaged and no service will fix that for free. Do it on your own risk and make sure the following list is satisfied: Ask people [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/about.jpg"><img
class="alignright size-medium wp-image-1077" title="about" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/about-180x300.jpg" alt="about" width="104" height="173" /></a>Before writing anything else I must warn all readers that changing the operating systems on your mobile will void the warranty. If the upgrade process fails the phone might be damaged and no service will fix that for free. Do it on your own risk and make sure the following list is satisfied:</p><ul
style="text-align: justify;"><li>Ask people about the ROM you want to install. Make sure it did not brake any phone.</li><li>The phone&#8217;s battery must be at least 50% charged (better 100%)</li><li>Make sure you have and UPS. Or a laptop with good battery because if you cancel the process after it started the results might be unexpected.</li><li>Make sure the USB cable is firmly connect and is not broken!</li></ul><p>I cannot be made responsible for any damages caused directly or indirectly by this article.</p><p><span
id="more-1054"></span></p><p
style="text-align: justify;">On PortegeClub.com there is a WM 6.5 ROM Release Candidate for the G900. Because PortegeClub is not always working I uploaded the ROM on my server  and you can download it from <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/WM65AllmostOfficial2RC1.rar">this link</a>. It is not the kitchen version (clean version) and it includes some software but it is reasonable and it is not bloated.</p><p
style="text-align: justify;">The upgrade process is simple:<a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/superruu.jpg" target="_blank"><img
class="alignright size-medium wp-image-1057" title="superruu" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/superruu-300x175.jpg" alt="superruu" width="300" height="175" /></a></p><ol
style="text-align: justify;"><li>Get the ROM</li><li>Get SuperRUU</li><li>Run SuperRUU on a 32 bit Windows machine</li><li>Select the ROM image and check the &#8220;OS&#8221; radio button</li><li>Click &#8220;Upgrade target&#8221;.</li><li>Turn off the phone and start it while pressing the left softkey. A red screen should appear informing you that you need USB connection.</li><li>Connect the phone to the PC running SuperRUU and the upgrade process should start. Do not interrupt it!!! It takes about two minutes.</li></ol><p
style="text-align: center"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/update_1.jpg" target="_blank"><img
class="alignnone size-medium wp-image-1058" title="update_1" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/update_1-227x300.jpg" alt="update_1" width="227" height="300" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/update_2.jpg" target="_blank"><img
class="alignnone size-medium wp-image-1059" title="update_2" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/update_2-260x300.jpg" alt="update_2" width="260" height="300" /></a></p><p>WM6.5 brings a new startup logo and animation and a lot of other visual changes.</p><p
style="text-align: center"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/wm65_start.jpg"><img
class="alignnone size-medium wp-image-1071" title="wm65_start" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/wm65_start-300x225.jpg" alt="wm65_start" width="300" height="225" /></a><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/wm65_logo.jpg"><img
class="alignnone size-medium wp-image-1070" title="wm65_logo" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/wm65_logo-300x225.jpg" alt="wm65_logo" width="300" height="225" /></a></p><p
style="text-align: justify;">The first thing you will notice after startup is the new redesigned Today screen which supports widgets just like the HTC home screen. It&#8217;s aspect is nice but you will find out soon that it cannot be customized. The only item supporting customization is the favorites widget :( Like usual there are widgets for time, messages, calls, pictures and music. Also you can use the classical Today screen items but you will use the eye-candy widgets. What I really enjoyed is that you can scroll through items by moving your finger over the screen in any region not just on the right side &#8211; this is a nice addition and also works for menus.</p><p
style="text-align: center"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_01.jpg" target="_blank"><img
class="alignnone size-medium wp-image-1061" title="today_01" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_01-180x300.jpg" alt="today_01" width="162" height="270" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_02.jpg" target="_blank"><img
class="alignnone size-medium wp-image-1062" title="today_02" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_02-180x300.jpg" alt="today_02" width="162" height="270" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_03.jpg" target="_blank"><img
class="alignnone size-medium wp-image-1063" title="today_03" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_03-180x300.jpg" alt="today_03" width="162" height="270" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_04.jpg" target="_blank"><img
class="alignnone size-medium wp-image-1064" title="today_04" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/today_04-180x300.jpg" alt="today_04" width="162" height="270" /></a></p><p
style="text-align: justify;">Another major interface change is the start menu. Well it is no longer MENU, it&#8217;s a start screen that displays shortcuts to applications and phone settings. They are all arranged in the well-known WM6.5 combs and have a nice aspect. You can also scroll through items with your finger and when you get to the top/bottom of the menu there is a visual bounce effect that creates a realistic sensation. What is hard here is to navigate with the hardware DPad through items because pressing right many times cycles through a &#8220;row&#8221; of the comb and is not going the lower items. You must use all directions to navigate.</p><p
style="text-align: center"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/start_1.jpg"><img
class="alignnone size-medium wp-image-1067" title="start_1" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/start_1-180x300.jpg" alt="start_1" width="180" height="300" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/start_2.jpg"><img
class="alignnone size-medium wp-image-1068" title="start_2" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/start_2-180x300.jpg" alt="start_2" width="180" height="300" /></a></p><p
style="text-align: justify;">There are some other major visual changes but I don&#8217;t have screenshots for them. The first thing is the unlock screen which has an object that must be slide in order to unlock the phone just like on iPhone. The second are the menus that are larger and more &#8220;finger-friendly&#8221; &#8211; you can navigate easily with the finger through them.</p><p
style="text-align: justify;">On my G900 screen rotation took almost 10 seconds (from portrait to landscape). While using the PDA in landscape the icons seemed crowded, hard to follow and the Today screen was not so good looking.</p><p
style="text-align: center"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/todayl_1.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-1073" title="todayl_1" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/todayl_1-150x90.jpg" alt="todayl_1" width="150" height="90" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/todayl_2.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-1074" title="todayl_2" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/todayl_2-150x90.jpg" alt="todayl_2" width="150" height="90" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/06/todayl_3.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-1075" title="todayl_3" src="http://victorhurdugaci.com/wp-content/uploads/2009/06/todayl_3-150x90.jpg" alt="todayl_3" width="150" height="90" /></a></p><p
style="text-align: justify;">Because it is not an official release I cannot say it works bad. There could be &#8220;unofficial&#8221; reasons why this is not working properly. Anyhow, I haven&#8217;t seen other major changes except the interface. The problem with interface changes is that you get used to them quickly and then you start to see what is not working. The ringtones are corrupted in this ROM and the SD card is disconnecting after a few hours so I reverted the ROM to a kitchen version of Windows Mobile 6.1 &#8211; you should try the 6.5, it&#8217;s a nice experience!</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/windows-mobile-65-on-toshiba-g900/feed/</wfw:commentRss> <slash:comments>22</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="p68310"><td
class="code" id="p683code10"><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="p63814"><td
class="code" id="p638code14"><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="p63815"><td
class="code" id="p638code15"><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="p63816"><td
class="code" id="p638code16"><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>22</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="p47123"><td
class="code" id="p471code23"><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="p47124"><td
class="code" id="p471code24"><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="p47125"><td
class="code" id="p471code25"><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="p47126"><td
class="code" id="p471code26"><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="p47127"><td
class="code" id="p471code27"><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="p47128"><td
class="code" id="p471code28"><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>First CodeProject article &#8211; WPFDesigner</title><link>http://victorhurdugaci.com/first-codeproject-article-wpfdesigner/</link> <comments>http://victorhurdugaci.com/first-codeproject-article-wpfdesigner/#comments</comments> <pubDate>Sat, 30 Aug 2008 14:38:09 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Codeproject]]></category> <category><![CDATA[Programming]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[WPF]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=191</guid> <description><![CDATA[Today I&#8217;ve posted my first article on CodeProject. The article describes how to create a custom control in which you add elements and you can move/resize them. The article can be found here.]]></description> <content:encoded><![CDATA[<p>Today I&#8217;ve posted my first article on <a
href="http://codeproject.com" target="_blank">CodeProject</a>.</p><p>The article describes how to create a custom control in which you add elements and you can move/resize them.</p><p>The article can be found <a
href="http://www.codeproject.com/KB/WPF/WPFDesigner.aspx" target="_blank">here</a>.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/first-codeproject-article-wpfdesigner/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> </channel> </rss>
