<?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>Martijn's C# Programming Blog &#187; windows</title>
	<atom:link href="http://www.dijksterhuis.org/tag/windows/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Modifying the Windows Registry in C#</title>
		<link>http://www.dijksterhuis.org/modifying-the-windows-registry-in-c/</link>
		<comments>http://www.dijksterhuis.org/modifying-the-windows-registry-in-c/#comments</comments>
		<pubDate>Mon, 24 Nov 2008 05:19:27 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[registry]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=245</guid>
		<description><![CDATA[
One wrong move and your dead, or at least your computer. Nothing is more nerve wracking than manipulating the Windows Registry. In the following example we show how you can (safely!) create your own little part of the registry and store and retrieve your applications configuration. Which is a nice way to store user names, [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/registry.jpg" alt="" title="Modifying the Windows Registry in c#" width="500" height="300" class="alignnone size-full wp-image-259" /></p>
<p><em>One wrong move and your dead, or at least your computer. Nothing is more nerve wracking than manipulating the Windows Registry. In the following example we show how you can (safely!) create your own little part of the registry and store and retrieve your applications configuration. Which is a nice way to store user names, passwords and anything else that you fancy. </em></p>
<p><span id="more-245"></span></p>
<p>The registry is Windows central database of information on all its settings, stored there by applications, drivers and system software. If you have never worked with the registry before then start the &#8220;regedit&#8221; program on your computer &#8212; just be careful not to change anything!</p>
<p><a href="http://www.dijksterhuis.org/wp-content/uploads/2008/11/registry.gif"><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/registry-300x242.gif" alt="" title="Using the Windows Registry in C#" width="300" height="242" class="alignnone size-medium wp-image-252" /></a></p>
<p>As you can see from the image above, the registry is a tree structure. There are nodes, and each can have sets of names/values and further sub-nodes.</p>
<p><strong>Why would you want to access the registry?</strong></p>
<ol>
<li>To look up system configuration information stored by Windows (there are thousands of these)
<li>To store your applications configuration
</ol>
<p>In this example we will only be looking at the second reason, storing your applications information. The example will shows you how to create your own sub tree. As one computer can have more than one user using it your application will typically store its settings separately for each user.</p>
<p>The registry is accessed in C# through the <em>Microsoft.Win32</em> namespace. The most important classes are:</p>
<ul>
<li>Microsoft.Win32.Registry &#8211; this class provides access to the registry
<li>Microsoft.Win32.RegistryKey &#8211; this class represents a key in the registry
</ul>
<p><strong>Creating our own keys</strong></p>
<p>We are looking to store our applications data for the current user only.  <em>Microsoft.Win32.Registry.CurrentUser</em> provides us with a <em>RegistryKey</em> to the root of the <em>CurrentUser</em> tree in the Registry. As can be seen in the above graphic, the &#8220;Software&#8221; section of <em>CurrentUser</em> is where programs store their information:</p>
<p>To create our own little section (called &#8220;ourapp&#8221;) we need to create a sub-key here:</p>
<p><small><br />
string OurAppKeyStr = @&#8221;SOFTWARE\OurApp&#8221;;<br />
RegistryKey OurAppRootKey = CurrentUserKey.CreateSubKey (OurAppKeyStr);<br />
</small></p>
<p>To keep it interesting we create the following structure:</p>
<p><small><br />
[HKEY_CURRENT_USER\software\ourapp]<br />
[HKEY_CURRENT_USER\software\ourapp\config]:X<br />
[HKEY_CURRENT_USER\software\ourapp\config]:Y<br />
[HKEY_CURRENT_USER\software\ourapp\users]:Name<br />
[HKEY_CURRENT_USER\software\ourapp\users]:Password<br />
</small></p>
<p>So below our Applications key, we need two more sub-keys: config &#038; users. These are created in the same fashion as our applications key:</p>
<p><small><br />
RegistryKey ConfigKey = OurAppRootKey.CreateSubKey(&#8221;config&#8221;);<br />
RegistryKey UsersKey = OurAppRootKey.CreateSubKey(&#8221;users&#8221;);<br />
</small></p>
<p>To add values to the registry, we simply add them to the keys we have created. The <em>SetValue()</em> function takes a name/value pair. It defaults to &#8220;String&#8221; , but for the example we are a little more explicit. The <em>RegistryValueKind</em> enum provides us with the types possible:</p>
<table>
<tr>
<td>RegistryValueKind.Binary</td>
<td>Binary data</td>
</tr>
<tr>
<td>RegistryValueKind.DWord</td>
<td>32-bit number</td>
</tr>
<tr>
<td>RegistryValueKind.QWord</td>
<td>64-bit number</td>
</tr>
<tr>
<td>RegistryValueKind.ExpandString</td>
<td>&#8220;This is a string with %PATH%&#8221; in it, the %PATH% is expanded on query</td>
</tr>
<tr>
<td>RegistryValueKind.MultiString</td>
<td>An Array of String[]</td>
</tr>
<tr>
<td>RegistryValueKind.String</td>
<td>A regular string</td>
</tr>
</table>
<p>To set a value we simple call:</p>
<p><small><br />
ConfigKey.SetValue(&#8221;X&#8221;,12,RegistryValueKind.DWord);<br />
UsersKey.SetValue(&#8221;Password&#8221;,&#8221;35a6a$&#8221;,RegistryValueKind.String);<br />
</small></p>
<p>We need to ensure that the data is writing to the registry:</p>
<p><small><br />
ConfigKey.Flush();<br />
UsersKey.Flush();<br />
</small></p>
<p>The <em>PrintTree()</em> function in the example shows how we can travel through and explore through the tree recursively. For a given key, we can query <em>GetSubKeynames</em> which returns an string array of names. Using the name a call to <em>OpenSubKey</em> returns a new <em>RegistryKey</em>. In turn we can then call <em>GetSubKeyNames</em> on that key again.</p>
<p><small><br />
foreach (string SubKeyName in Root.GetSubKeyNames())<br />
  PrintTree(Root.OpenSubKey(SubKeyName));<br />
</small></p>
<p>Because your windows registry is probably already crowded with information we will clean up at the end of the example by removing our created tree. We do not have to step through the tree and delete each sub-tree individually. Instead <em>DeleteSubKeyTree</em> removes an entire sub tree (and as  this function is quite dangerous, use it with care!)</p>
<p><small><br />
// Remove the &#8220;OurApp&#8221; subtree from the Registry<br />
CurrentUserKey.DeleteSubKeyTree(OurAppKeyStr);<br />
</small></p>
<p><strong>The Example Code</strong></p>
<pre class="brush: c#">
using System;
using Microsoft.Win32;

namespace RegistryTest
{
    class MainClass
    {

        // PrintTree
        //
        // This routine recursively steps through the registry
        // and prints each sub tree and its values

        public static void PrintTree(RegistryKey Root)
        {
            // Print the name of the current key
            Console.WriteLine(&quot;{0}&quot;,Root.Name);

            // Check if this key has any other subkeys
            // If so, travel deeper into the tree
            foreach (string SubKeyName in Root.GetSubKeyNames())
             PrintTree(Root.OpenSubKey(SubKeyName));

            // Print each of the values for this key
            foreach(string RootName in Root.GetValueNames())
                Console.WriteLine(&quot;{0}={1}&quot;,RootName,
                                            Root.GetValue(RootName) );
        }

        public static void Main(string[] args)
        {
            // Obtain a link to the current users registry entries
            RegistryKey CurrentUserKey = Microsoft.Win32.Registry.CurrentUser;
            RegistryKey OurAppRootKey = null;
            RegistryKey ConfigKey = null;
            RegistryKey UsersKey = null;

            // Create a section for our application
            // Note: The @ in front of the string ensures that the compiler ignores the slash
            string OurAppKeyStr = @&quot;SOFTWARE\OurApp&quot;;
            OurAppRootKey = CurrentUserKey.CreateSubKey (OurAppKeyStr);

            // Save the X,Y values
            ConfigKey = OurAppRootKey.CreateSubKey(&quot;config&quot;);
            ConfigKey.SetValue(&quot;X&quot;,12,RegistryValueKind.DWord);
            ConfigKey.SetValue(&quot;Y&quot;,20,RegistryValueKind.DWord);

            // Save the username , password values
            UsersKey = OurAppRootKey.CreateSubKey(&quot;users&quot;);
            UsersKey.SetValue(&quot;Name&quot;,&quot;Martijn&quot;,RegistryValueKind.String);
            UsersKey.SetValue(&quot;Password&quot;,&quot;35a6a$&quot;,RegistryValueKind.String);           

            // Flush all the changes
            ConfigKey.Flush();
            UsersKey.Flush();

            // Print a tree of our applications keys
            PrintTree(OurAppRootKey);

            // Remove the &quot;OurApp&quot; subtree from the Registry
            CurrentUserKey.DeleteSubKeyTree(OurAppKeyStr);

        }
    }
}
</pre>
<p><strong>Using the Registry with Mono</strong></p>
<p>Although Unix does not have a registry as such it is still possible to use the above code under Mono. If you are looking in the registry for Windows specific configuration values &#8212; or those stored by other Windows only applications &#8212; you will  come up empty. This registry is just a shell. It however provides a good cross-platform method of storing your own configuration values. </p>
<p>Mono will create a tree of small XML files under the users home directory. So for example, in our example we created the key &#8220;HKEY_CURRENT_USER\software\ourapp\config&#8221; which is stored in  an XML file.  This XML file  is located in the following directory:</p>
<p>~/.mono/registry/CurrentUser/software/ourapp/config</p>
<p>The values we stored are kept in a file called values.xml:</p>
<pre class="brush: xml">
&lt;values&gt;
&lt;value name=&quot;X&quot; type=&quot;int&quot;&gt;12&lt;/value&gt;
&lt;value name=&quot;Y&quot; type=&quot;int&quot;&gt;20&lt;/value&gt;
&lt;/values&gt;
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/fboyd/">Florian</a></small></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/modifying-the-windows-registry-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Named Pipes in C# / Windows</title>
		<link>http://www.dijksterhuis.org/using-named-pipes-in-c-windows/</link>
		<comments>http://www.dijksterhuis.org/using-named-pipes-in-c-windows/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 09:30:57 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[named pipes]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=221</guid>
		<description><![CDATA[
Communication between different threads in a process is trivial as they share the same objects in memory. But what if you would like to communicate with a different process (program) on the same computer? You could open a TCP/IP port to share data but the added overhead of this would slow down your program if [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/pipes.jpg" alt="" title="Using named pipes in C# / Windows" width="500" height="279" class="alignnone size-full wp-image-224" /></p>
<p><em>Communication between different threads in a process is trivial as they share the same objects in memory. But what if you would like to communicate with a different process (program) on the same computer? You could open a TCP/IP port to share data but the added overhead of this would slow down your program if you send a lot of data.</em></p>
<p><span id="more-221"></span></p>
<p>Traditionally you would use a pipe: a pseudo file that allows one process to write and another to process to read. This is very similar to reading and writing from a file. This is more efficient as the information is passed straight through the kernel between processes and avoids the network stack overhead.</p>
<p>There are two kinds of pipes:</p>
<p><strong>Anonymous pipes</strong></p>
<p>These are typically used for communication between a parent and child process. As the pipe does not have a name we need to be able to pass a handle to it from one process to another. Typically this is done by passing this handle as an argument when starting the child process.</p>
<p><strong>Named pipes</strong></p>
<p>Named pipes are more generally useful. If a process is aware of the name of a pipe it can connect to it. There is no need for an immediate parent / child relationship. As long as the parent process makes the pipe available, other processes can connect to it.</p>
<p><strong>Pipes and Windows</strong></p>
<p>The Windows OS offers a solid set of named and unnamed pipe function calls in the kernel. But for some reason Microsoft didn&#8217;t actually include pipes in C# until .NET 3.5. The support for pipes is now included in the <em>System.IO.Pipes</em> class. In the intervening years enterprising programmers created their own set of non-portable bindings to the Kernel32 calls and on Linux the Mono teambuild their own set of calls to support Unix sockets in the <em>Mono.Unix.UnixPipes</em> class.</p>
<p>As a result there is currently no portable way to implement pipes under both .NET/Windows and Linux/Mono. In the following example I show you how to create a named pipe for Windows.</p>
<p>Because of the nature of a named pipe &#8212; we are going to need two programs: one that establishes the pipe, and another one that reads from the pipe.</p>
<p><strong>Example: Named Pipes in Visual C# / .NET 3.5</strong></p>
<p>With the introduction of <em>System.IO.Pipes</em> in .NET 3.5 creating and connecting to a pipe has become very straightforward.</p>
<ul>
<li>NamedPipeServerStream creates a pipe
<li>NamedPipeClientStream connects to an existing pipe
</ul>
<p>In the below example we simulate the communication between two processes by creating two threads instead. This makes debugging this example easier but in reality this could also have been an example of communication between two separate processes on the same computer.</p>
<p>We also make implicity use of the fact that <em>NamedPipeClientStream.Connect()</em> will wait for the pipe to be created if it can&#8217;t find it on its first try.  If this is not acceptable it is also possible to call <em>Connect</em> with a time-out in milliseconds &#8212; if the pipe is not created in the time specified the function will fail. </p>
<pre class="brush: c#">
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;

namespace PipeApplication1
{
    class ProgramPipeTest
    {

        public void ThreadStartServer()
        {
            // Create a name pipe
            using (NamedPipeServerStream pipeStream = new NamedPipeServerStream(&quot;mytestpipe&quot;))
            {
                Console.WriteLine(&quot;[Server] Pipe created {0}&quot;, pipeStream.GetHashCode());

                // Wait for a connection
                pipeStream.WaitForConnection();
                Console.WriteLine(&quot;[Server] Pipe connection established&quot;);

                using (StreamReader sr = new StreamReader(pipeStream))
                {
                    string temp;
                    // We read a line from the pipe and print it together with the current time
                    while ((temp = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(&quot;{0}: {1}&quot;, DateTime.Now, temp);
                    }
                }
            }

            Console.WriteLine(&quot;Connection lost&quot;);
        }

        public void ThreadStartClient(object obj)
        {
            // Ensure that we only start the client after the server has created the pipe
            ManualResetEvent SyncClientServer = (ManualResetEvent)obj;

            // Only continue after the server was created -- otherwise we just fail badly
            // SyncClientServer.WaitOne();

            using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(&quot;mytestpipe&quot;))
            {
                // The connect function will indefinately wait for the pipe to become available
                // If that is not acceptable specify a maximum waiting time (in ms)
                pipeStream.Connect();

                Console.WriteLine(&quot;[Client] Pipe connection established&quot;);
                using (StreamWriter sw = new StreamWriter(pipeStream))
                {
                    sw.AutoFlush = true;
                    string temp;
                    Console.WriteLine(&quot;Please type a message and press [Enter], or type &#039;quit&#039; to exit the program&quot;);
                    while ((temp = Console.ReadLine()) != null)
                    {
                        if (temp == &quot;quit&quot;) break;
                        sw.WriteLine(temp);
                    }
                }
            }
        }

        static void Main(string[] args)
        {

            // To simplify debugging we are going to create just one process, and have two tasks
            // talk to each other. (Which is a bit like me sending an e-mail to my co-workers)

            ProgramPipeTest Server = new ProgramPipeTest();
            ProgramPipeTest Client = new ProgramPipeTest();

            Thread ServerThread = new Thread( Server.ThreadStartServer );
            Thread ClientThread = new Thread(Client.ThreadStartClient);

            ServerThread.Start();
            ClientThread.Start();
        }
    }
}
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/28481088@N00/">TanakaWho</a></small></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/using-named-pipes-in-c-windows/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
