<?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; Intermediate</title>
	<atom:link href="http://www.dijksterhuis.org/category/csharp/intermediate/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>Show all assemblies loaded by your C# program</title>
		<link>http://www.dijksterhuis.org/show-assemblies-loaded-program/</link>
		<comments>http://www.dijksterhuis.org/show-assemblies-loaded-program/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 07:29:15 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=721</guid>
		<description><![CDATA[Sometimes it is handy to have a quick overview of all the assemblies that your C# program has loaded. Maybe because you are trying to debug a version conflict, or because you want to distribute your application and want to get an idea of its dependencies.

To find the loaded assemblies we first need to determine [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>Sometimes it is handy to have a quick overview of all the assemblies that your C# program has loaded. Maybe because you are trying to debug a version conflict, or because you want to distribute your application and want to get an idea of its dependencies.</em></p>
<p><span id="more-721"></span></p>
<p>To find the loaded assemblies we first need to determine the current AppDomain (it is possible for your application to have more than one AppDomain, but in that case you have created the second one yourself). Each AppDomain keeps a list of Assemblies it is using and in the following example code we query it using the GetAssemblies() method.</p>
<p>By calling FullName we obtain the name, version, culture and public key ID for each assembly. </p>
<pre class="brush: c#">
using System;
using System.Text;
using System.Reflection;

namespace AssemblyListing
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain MyDomain = AppDomain.CurrentDomain;
            Assembly[] AssembliesLoaded = MyDomain.GetAssemblies();

            foreach (Assembly MyAssembly in AssembliesLoaded)
            {
                Console.WriteLine(&quot;Loaded: {0}&quot;, MyAssembly.FullName);
            }
        }
    }
}
</pre>
<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/show-assemblies-loaded-program/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Measuring memory usage of object creation in C#</title>
		<link>http://www.dijksterhuis.org/measuring-memory-usage-object-creation/</link>
		<comments>http://www.dijksterhuis.org/measuring-memory-usage-object-creation/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 05:49:03 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[garbage collector]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[memory usage]]></category>
		<category><![CDATA[object creation]]></category>
		<category><![CDATA[process]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=467</guid>
		<description><![CDATA[As your application grows it can be useful to get an idea of how much memory a particular data structure is using in memory. Measuring memory in a garbage collected environment is a somewhat of a moving target as the Garbage collector is able to move things around in the background.The .NET libraries offer two [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>As your application grows it can be useful to get an idea of how much memory a particular data structure is using in memory. Measuring memory in a garbage collected environment is a somewhat of a moving target as the Garbage collector is able to move things around in the background.The .NET libraries offer two ways of measuring your applications memory. The total amount of memory allocated to the process (which includes code, unique libraries) and the amount of memory used that the Garbage collector is aware off (which is only your applications variables). This second set is of course a subset of the total amount of memory. </em></p>
<p><span id="more-467"></span></p>
<p><strong>Measuring your process memory usage</strong></p>
<p>The .NET API allows you to retrieve the total amount of memory allocated to a process through the <em>System.Diagnostics.Process</em> class. This variable is useful is you are interested in the total memory footprint of your process, but it is too coarse to measure how much memory a single object takes.</p>
<pre class="brush: c#">
long Process_MemoryStart = 0;
Process MyProcess = System.Diagnostics.Process.GetCurrentProcess();
Process_MemoryStart = MyProcess.PrivateMemorySize64;
</pre>
<p>This will return the total amount of memory uniquely allocated to your process in bytes (not shared with other processes).This measure of memory includes everything from code, libraries, the execution environment, stack, variables etc. If you try to measure the creation of a new object in memory using this variable it is likely to show no change.  It is very likely that the difference shown is zero as some memory for new objects is pre-allocated.</p>
<p><strong>Using the garbage collector to gain insights into memory allocation</strong></p>
<p>If you are building a multi threaded application the following code won&#8217;t work as expected, other threads might be too busy creating new objects and destroying to gain a clear insight into how much memory an object uses.We make use of the fact that the Garbage collector can report how much allocated memory it is aware off. As the Garbage collector manages just the objects we create for our application &#8212; we can use it to measure an objects size.</p>
<p>By calling <em>System.GC.GetTotalMemory()</em> we can obtain a measure of how much memory the Garbage collector is managing. If we call this function again after we allocated our object, we can calculate the difference.</p>
<pre class="brush: c#">
// Measure starting point memory use
GC_MemoryStart = System.GC.GetTotalMemory(true);

// Allocate a new byte array of 20000 elements (about 20000 bytes)
MyByteArray = new byte[20000];

// Obtain measurements after creating the new byte[]
GC_MemoryEnd = System.GC.GetTotalMemory(true);

// Ensure that the Array stays in memory and doesn&#039;t get optimized away
MyByteArray[1] = 20;
</pre>
<p>By calling System.GC.GetTotalMemory with &#8220;true&#8221; as a parameter we ensure that the Garbage collector makes at least an efford to clean up before reporting the amount of memory under its management.<em> </em>To avoid any compiler optimizations that would shift code around, we need to make sure that our newly created byte array is accessed again after we make the second GetTotalMemory() call.</p>
<p>The code listed at the end of this post reports something similar to the following when run:</p>
<pre class="brush: c#">
Memory Use reported by GC: 20480
Memory Use reported by Process: 65536
Memory allocated by the Garbage collector: 135168 bytes
Memory allocated by the process: 2641920 bytes
</pre>
<p>As you can see, allocating a 20,000 element byte array takes up about 20Kb (with some additional overhead). Apparently the garbage collector decided to increase the applications total memory by 64Kb as the total process size increased by that much.You mileage may vary depending on your run. The final two figures show how much memory is under management by the Garbage collector for our simple application (about 135Kb) and the how much the Operating system needed to allocate it the whole application (2 Megabyte).</p>
<pre class="brush: c#">
using System;
using System.Diagnostics;

namespace ProfileTest
{
	class MainClass
	{
		public static void Main(string[] args)
		{
	      long GC_MemoryStart = 0;
    	  long GC_MemoryEnd = 0;
		  long Process_MemoryStart = 0;
		  long Process_MemoryEnd = 0;
		  byte[] MyByteArray;

		  Process MyProcess = System.Diagnostics.Process.GetCurrentProcess();

		  // Measure starting point memory use
      	  GC_MemoryStart = System.GC.GetTotalMemory(true);
		  Process_MemoryStart = MyProcess.PrivateMemorySize64;

		  // Allocate a new byte array of 20000 elements (about 20000 bytes)
		  MyByteArray = new byte[20000];

		  // Obtain measurements after creating the new byte[]
		  GC_MemoryEnd = System.GC.GetTotalMemory(true);
		  Process_MemoryEnd = MyProcess.PrivateMemorySize64;

		  // Ensure that the Array stays in memory and doesn&#039;t get optimized away
		  MyByteArray[1] = 20;

		  // Show the difference after allocating the memory
		  Console.WriteLine(&quot;Memory Use reported by GC: {0}&quot; , GC_MemoryEnd - GC_MemoryStart );
		  Console.WriteLine(&quot;Memory Use reported by Process: {0}&quot; , Process_MemoryEnd - Process_MemoryStart );

		  // Show how much memory was allocated by the process, and how much by the GC
		  Console.WriteLine(&quot;Memory allocated by the Garbage collector: {0} bytes&quot;, GC_MemoryEnd);
		  Console.WriteLine(&quot;Memory allocated by the process: {0} bytes&quot;, Process_MemoryEnd);
		}
	}
}
</pre>
<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/measuring-memory-usage-object-creation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Encrypting and Decrypting a C# string</title>
		<link>http://www.dijksterhuis.org/encrypting-decrypting-string/</link>
		<comments>http://www.dijksterhuis.org/encrypting-decrypting-string/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 06:31:27 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[decryption]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=453</guid>
		<description><![CDATA[The .NET C# library provides all the basic elements for encrypting a string with a passphrase and decrypting it later. Doing this however requires a few steps in between. This post show a simple set of routines to help you do just that. We use the TripleDES encryption suite to do the actual encryption, with [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>The .NET C# library provides all the basic elements for encrypting a string with a passphrase and decrypting it later. Doing this however requires a few steps in between. This post show a simple set of routines to help you do just that. We use the TripleDES encryption suite to do the actual encryption, with a little help from the MD5 hash sum generator.<br />
</em></p>
<p>The complete source code is listed below, but lets have a little look at how it works first.</p>
<p><span id="more-453"></span></p>
<p><strong>The problem</strong></p>
<p>I want to take a string, and then encrypt it using a password. The result should be a Base64 encoded string that I can store somewhere relatively safe.</p>
<pre class="brush: c#">
            // The message to encrypt.
            string Msg = &quot;This world is round, not flat, don&#039;t believe them!&quot;;
            string Password = &quot;secret&quot;;

            string EncryptedString = EncryptString(Msg, Password);
            string DecryptedString = DecryptString(EncryptedString, Password);

            Console.WriteLine(&quot;Message: {0}&quot;,Msg);
            Console.WriteLine(&quot;Password: {0}&quot;,Password);
            Console.WriteLine(&quot;Encrypted string: {0}&quot;,EncryptedString);
            Console.WriteLine(&quot;Decrypted string: {0}&quot;,DecryptedString);
</pre>
<p>In the EncryptString function we apply the TripleDES algorithm with a 128 bit key. But first we need to turn the above passphrase (&#8217;secret&#8217;) into a 128 bit key.  One useful coincidence is that the MD5 hash algorithm accepts a set of bytes of any length and turns them into a 128 bit hash. So by running the password through the MD5 hashing algorithm we create our key.</p>
<pre class="brush: c#">
            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
</pre>
<p>The TripleDES algorithm itself turns a byte array into an encrypted  byte array. So we first need to convert our C# message string (which is Unicode encoded) into a byte array  through the System.Text.UTF8Encoding encoder.</p>
<p>The key is used to initialize the TripleDES algorithm. In addition we need to specify that we will only encode something once (CipherMode.ECB) and because its unlikely that our source string fits into a single TripleDES block we need to specify how we want to pad any remaining bytes (PaddingMode.PKCS7).</p>
<pre class="brush: c#">
            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
</pre>
<p>The encrypted byte array is finally converted into a Base64 encoded string for easy storage. The <em>DecryptString</em> function is very similar to the encryption function, except that it turns the Base64 encoded encrypted message back into the original UTF8 string.</p>
<p><strong>Drawbacks to the above method</strong></p>
<p>To keep the code above straightforward we made use of the fact that an MD5 hash is exactly 128 bits in length. The C# TripleDES code accepts three possible key lengths: 64 bit, 128 bit and 192 bit. Only 192 bit keys are truly TripleDES, the 128 bit key length we obtain from the MD5 hash is only sufficient for Double DES. According to Wikipedia, that would make its real key strength only equivalent to 80 bits.</p>
<p><strong>The Source code</strong></p>
<pre class="brush: c#">
using System;
using System.Text;
using System.Security.Cryptography;

namespace EncryptStringSample
{
    class MainClass
    {

        public static string EncryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToEncrypt = UTF8.GetBytes(Message);

            // Step 5. Attempt to encrypt the string
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return Convert.ToBase64String(Results);
        }

        public static string DecryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the decoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            // Step 5. Attempt to decrypt the string
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the decrypted string in UTF8 format
            return UTF8.GetString( Results );
        }

        public static void Main(string[] args)
        {
            // The message to encrypt.
            string Msg = &quot;This world is round, not flat, don&#039;t believe them!&quot;;
            string Password = &quot;secret&quot;;

            string EncryptedString = EncryptString(Msg, Password);
            string DecryptedString = DecryptString(EncryptedString, Password);

            Console.WriteLine(&quot;Message: {0}&quot;,Msg);
            Console.WriteLine(&quot;Password: {0}&quot;,Password);
            Console.WriteLine(&quot;Encrypted string: {0}&quot;,EncryptedString);
            Console.WriteLine(&quot;Decrypted string: {0}&quot;,DecryptedString);
        }
    }
}
</pre>
<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/encrypting-decrypting-string/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Debugging C# in Monodevelop on Ubuntu</title>
		<link>http://www.dijksterhuis.org/debugging-c-in-monodevelop-on-ubuntu/</link>
		<comments>http://www.dijksterhuis.org/debugging-c-in-monodevelop-on-ubuntu/#comments</comments>
		<pubDate>Mon, 29 Dec 2008 06:26:22 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[monodevelop]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=387</guid>
		<description><![CDATA[As soon as I heard that the  MonoDevelop Subversion code included support for actually debugging my C# code I tried installing it to give it a go. Optimistically I kept notes, figuring that it would be useful to write a post about the install process later. As my notes started to turn into a book, [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>As soon as I heard that the  MonoDevelop Subversion code included support for actually debugging my C# code I tried installing it to give it a go. Optimistically I kept notes, figuring that it would be useful to write a post about the install process later. As my notes started to turn into a book, and the arrows back and forth and <span style="text-decoration: line-through;">crossed out scribbles </span>increased I gave up on writing the ultimate &#8220;ten step guide to installing Monodevelop on Ubuntu&#8221;.</p>
<p>When I finally had MonoDevelop compiled and installed &#8212; the promised debugging didn&#8217;t actually work. Bummer. I gave up, and went back to coding the old way (with ticker tape). This morning I checked out the latest SVN, installed it and ran it, just for laughs.</p>
<p>And behold as shown below &#8212; debugging actually worked. I can step and trace through the code, and set watches making MonoDevelop suddenly that much more useful to me.</p>
<p>The best thing? The Mono C# libraries are not black boxes but open source &#8212; you can step and trace directly into the Mono libraries themselves and find out what Mono is doing as you call library functions.</p>
<p><a href="http://www.dijksterhuis.org/wp-content/uploads/2008/12/monodevelop1.png"><img class="alignnone size-medium wp-image-389" title="MonoDevelop on Ubuntu" src="http://www.dijksterhuis.org/wp-content/uploads/2008/12/monodevelop1-500x404.png" alt="MonoDevelop on Ubuntu" width="500" height="404" /></a></p>
<p>The problem with installing MonoDevelop 2.0alpha 2 is that<a href="http://monodevelop.com/Download_-_Unstable"> the guides online</a> don&#8217;t actually produce a working MonoDevelop installation. If you run MonoDevelop under Ubuntu like I do, the number of dependencies and sub-dependencies you need to resolve is large and I ended up compiling, re-compiling and changing version numbers of modules multiple times to find combinations that worked. In addition I had to change, add and resolve many missing library conflicts within Ubuntu as well.</p>
<p>Concluding: Yes, it is possible. Just do not expect a quick and easy install of MonoDevelop 2.0 alpha 2 on your Ubuntu installation.</p>
<p>This is fun only if you have plenty of spare time.</p>
<p><strong>Some hints &#8212; <em>this does not produce a working Mono Develop installation<br />
</em></strong></p>
<ul>
<li>Remove Mono 1.9, MonoDevelop 1.0, and any and all other mono related things from your ubuntu installation before attempting to compile MonoDevelop 2.0 Alpha 2 to avoid conflicts down the road.</li>
<li>Install mono 2.3, the debugger and mono develop from SVN, not from the packages provided on the website (they do not work)</li>
<li>$ svn co svn://anonsvn.mono-project.com/source/trunk/mono<br />
$ svn co svn://anonsvn.mono-project.com/source/trunk/mcs<br />
$ svn co svn://anonsvn.mono-project.com/source/trunk/debugger<br />
$ svn co svn://anonsvn.mono-project.com/source/trunk/mono-addins<br />
$ svn co svn://anonsvn.mono-project.com/source/trunk/olive<br />
$ svn co svn://anonsvn.mono-project.com/source/trunk/monodevelop</li>
<li>I installed gtk-sharp-2.12.5, gnome-sharp-2.20.0 and libglade-2.0.1 as support libraries</li>
<li>Compile and install monodevelop last of all</li>
</ul>
<p><em>Mono JIT compiler version 2.3 (/trunk/mono r121276 Thu Dec 11 13:04:53 CST 2008)<br />
Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com</em></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/debugging-c-in-monodevelop-on-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating salted hash passwords in C#</title>
		<link>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/</link>
		<comments>http://www.dijksterhuis.org/creating-salted-hash-values-in-c/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 04:59:11 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[crc]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[salted]]></category>
		<category><![CDATA[sha-1]]></category>
		<category><![CDATA[sha-256]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=336</guid>
		<description><![CDATA[
Hash values have many uses in computing: for storing password tokens, securing that a file hasn&#8217;t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set &#8212; such as a string &#8212; and turns it into a numeric value of a certain length. [...]<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/12/salt.jpg" alt="" title="Salted Hash Passwords in C#" width="500" height="288" class="alignnone size-full wp-image-340" /><br />
<em>Hash values have many uses in computing: for storing password tokens, securing that a file hasn&#8217;t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set &#8212; such as a string &#8212; and turns it into a numeric value of a certain length.  </p>
<p>This article will go into how to create a hash of your passwords and how salting them makes them more secure.</em></p>
<p><span id="more-336"></span></p>
<p><strong>What is a hash?</strong></p>
<p>A hash function turns &#8220;Hello World&#8221; into &#8220;3964322768&#8243;. And it does that every time you run that same string through the hash function. How it does that depends on the hash algorithm, and so does the &#8220;3964322768&#8243; result. </p>
<p>Different hash function return different results, but given the same data the same function always returns the same result. </p>
<p>Now imagine transferring a block of 2Kb of data across the Internet &#8212; at the end of it you include an extra hash. The receiver can check if the data received was all transferred correctly, if a bit had fallen over the data block would have generated a different hash. </p>
<p><strong>On collisions</strong></p>
<p>In the &#8220;old days&#8221; CRC16 was used to ensure that data was being transmitted correctly over telephone and serial lines. As modems became faster and the data send increased collisions became more frequent, leading to corrupted transfers. The CRC-16 was a 16-bit value, so it could only generate 2^16 = 65535 unique values.  </p>
<p>By making the hash longer the chance that two sets of data share the same hash value (a collision) decreases. It is important to realize that this chance will never reach zero! It is entirely (though often unlikely) possible that your program will have two strings that generate the same hash.</p>
<p><strong>Using hashes to store passwords</strong></p>
<p>Hashes are useful as a one-way method to store passwords. In a typical scenario a user types his password and the system generates the hash and compares this with a hash stored on file. </p>
<p>It is not possible to reverse the password from a hash. Thus if someone gets hold of the password file they cannot reverse the original passwords. </p>
<p><strong>Salting the hash</strong></p>
<p>Hashes however are still open to one of the oldest attacks: the dictionary attack. Your system will likely lock out a users after several failed password attempts. If however through a security breach an attacker obtains your hashed password file (or part thereof) it is possible to apply one of many standard dictionaries against the found hashes:</p>
<ol>
<li>Obtain hashed passwords (through online snooping, hacking)</li>
<li>Use dictionary software which contains pre-computed hash values for common passwords</li>
<li>See if the result matches , if so : password found</li>
<li>The hacker can now login and impersonate the user</li>
</ol>
<p>The dictionary attack can be blunted. By adding a unique salt to each hash the attacker needs to re-calculate the dictionary for each users password, greatly increasing the attack time.</p>
<p><em>A salt is a random set of bytes which are added to the data set before calculating the hash. </em></p>
<ol>
<li>User enters password for the first time
<li>The system adds a salt to the password (for example 4 bytes of random data)
<li>The system generates and stores the hash together with the salt
</ol>
<p>When the user returns for another login the system does the following:</p>
<ol>
<li>The users enters the password
<li>The system looks up the stored hash + salt
<li>The system tries if a new hash of the given password + salt matches the stored hash
<li>If they match the user can login
</ol>
<p><strong>A Salted Hash implementation in C#</strong></p>
<p>The following implementation demonstrates how you can implement a Salted Hash in C#. The class defaults to using SHA256Managed hash algorithm, and a salt size of 32 bits. You can however call the class with any other <em>HashAlgorithm</em> derived class (such as for example: <em>SHA1Managed</em>,<em>SHA256Managed</em>, <em>SHA384Managed</em>, <em>SHA512Managed</em> and <em>MD5CryptoServiceProvider</em>) and specify a salt size of any length.</p>
<p>The <em>SaltedHash</em> class provides two routines that do all the leg work:</p>
<p><em>void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)</em></p>
<p>This routine generates the hash and a random salt for a given set of bytes.</p>
<p><em>bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)</em></p>
<p>This routine checks if the data passed, together with the stored salt will generate the same hash as we had earlier calculated.</p>
<p>For convenience two more functions allow us to work with strings directly instead of byte arrays:</p>
<p><em>public void GetHashAndSaltString(string Data, out string Hash, out string Salt)</em></p>
<p>This routine takes a C# hash string and returns both the Hash and Salt as Base-64 encoded string. </p>
<p><em>public bool VerifyHashString(string Data, string Hash, string Salt)</em></p>
<p>The counterpart to the GetHashAndSaltString function, this routine allows us to use verify whether a string returns the same hash with the given salt. </p>
<pre class="brush: c#">
using System;
using System.Security.Cryptography;
using System.Text;

namespace SaltedHash
{
    class SaltedHash
    {
        HashAlgorithm HashProvider;
        int SalthLength;

        /// &lt;summary&gt;
        /// The constructor takes a HashAlgorithm as a parameter.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;HashAlgorithm&quot;&gt;
        /// A &lt;see cref=&quot;HashAlgorithm&quot;/&gt; HashAlgorihm which is derived from HashAlgorithm. C# provides
        /// the following classes: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider
        /// &lt;/param&gt;

        public SaltedHash(HashAlgorithm HashAlgorithm, int theSaltLength)
        {
            HashProvider = HashAlgorithm;
            SalthLength = theSaltLength;
        }

        /// &lt;summary&gt;
        /// Default constructor which initialises the SaltedHash with the SHA256Managed algorithm
        /// and a Salt of 4 bytes ( or 4*8 = 32 bits)
        /// &lt;/summary&gt;

        public SaltedHash() : this(new SHA256Managed(), 4)
        {
        }

        /// &lt;summary&gt;
        /// The actual hash calculation is shared by both GetHashAndSalt and the VerifyHash functions
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A byte array of the Data to Hash&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;A byte array of the Salt to add to the Hash&lt;/param&gt;
        /// &lt;returns&gt;A byte array with the calculated hash&lt;/returns&gt;

        private byte[] ComputeHash(byte[] Data, byte[] Salt)
        {
            // Allocate memory to store both the Data and Salt together
            byte[] DataAndSalt = new byte[Data.Length + SalthLength];

            // Copy both the data and salt into the new array
            Array.Copy(Data, DataAndSalt, Data.Length);
            Array.Copy(Salt, 0, DataAndSalt, Data.Length, SalthLength);

            // Calculate the hash
            // Compute hash value of our plain text with appended salt.
            return HashProvider.ComputeHash(DataAndSalt);
        }

        /// &lt;summary&gt;
        /// Given a data block this routine returns both a Hash and a Salt
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array containing the data from which to derive the salt
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array which will contain the hash calculated
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;
        /// A &lt;see cref=&quot;System.Byte&quot;/&gt;byte array which will contain the salt generated
        /// &lt;/param&gt;

        public void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)
        {
            // Allocate memory for the salt
            Salt = new byte[SalthLength];

            // Strong runtime pseudo-random number generator, on Windows uses CryptAPI
            // on Unix /dev/urandom
            RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

            // Create a random salt
            random.GetNonZeroBytes(Salt);

            // Compute hash value of our data with the salt.
            Hash = ComputeHash(Data, Salt);
        }

        /// &lt;summary&gt;
        /// The routine provides a wrapper around the GetHashAndSalt function providing conversion
        /// from the required byte arrays to strings. Both the Hash and Salt are returned as Base-64 encoded strings.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; string containing the data to hash
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; base64 encoded string containing the generated hash
        /// &lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; base64 encoded string containing the generated salt
        /// &lt;/param&gt;

        public void GetHashAndSaltString(string Data, out string Hash, out string Salt)
        {
            byte[] HashOut;
            byte[] SaltOut;

            // Obtain the Hash and Salt for the given string
            GetHashAndSalt(Encoding.UTF8.GetBytes(Data), out HashOut, out SaltOut);

            // Transform the byte[] to Base-64 encoded strings
            Hash = Convert.ToBase64String(HashOut);
            Salt = Convert.ToBase64String(SaltOut);
        }

        /// &lt;summary&gt;
        /// This routine verifies whether the data generates the same hash as we had stored previously
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;The data to verify &lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;The hash we had stored previously&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;The salt we had stored previously&lt;/param&gt;
        /// &lt;returns&gt;True on a succesfull match&lt;/returns&gt;

        public bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)
        {
            byte[] NewHash = ComputeHash(Data, Salt);

            //  No easy array comparison in C# -- we do the legwork
            if (NewHash.Length != Hash.Length) return false;

            for (int Lp = 0; Lp &lt; Hash.Length; Lp++ )
                if (!Hash[Lp].Equals(NewHash[Lp]))
                    return false;

            return true;
        }

        /// &lt;summary&gt;
        /// This routine provides a wrapper around VerifyHash converting the strings containing the
        /// data, hash and salt into byte arrays before calling VerifyHash.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A UTF-8 encoded string containing the data to verify&lt;/param&gt;
        /// &lt;param name=&quot;Hash&quot;&gt;A base-64 encoded string containing the previously stored hash&lt;/param&gt;
        /// &lt;param name=&quot;Salt&quot;&gt;A base-64 encoded string containing the previously stored salt&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        public bool VerifyHashString(string Data, string Hash, string Salt)
        {
            byte[] HashToVerify = Convert.FromBase64String(Hash);
            byte[] SaltToVerify = Convert.FromBase64String(Salt);
            byte[] DataToVerify = Encoding.UTF8.GetBytes(Data);
            return VerifyHash(DataToVerify, HashToVerify, SaltToVerify);
        }

    }

    /// &lt;summary&gt;
    /// This little demo code shows how to encode a users password.
    /// &lt;/summary&gt;

    class SaltedHashDemo
    {
        public static void Main(string[] args)
        {
            // We use the default SHA-256 &amp; 4 byte length
            SaltedHash demo = new SaltedHash();

            // We have a password, which will generate a Hash and Salt
            string Password = &quot;MyGlook234&quot;;
            string Hash;
            string Salt;

            demo.GetHashAndSaltString(Password, out Hash, out Salt);
            Console.WriteLine(&quot;Password = {0} , Hash = {1} , Salt = {2}&quot;, Password, Hash, Salt);

            // Password validation
            //
            // We need to pass both the earlier calculated Hash and Salt (we need to store this somewhere safe between sessions)

            // First check if a wrong password passes
            string WrongPassword = &quot;OopsOops&quot;;
            Console.WriteLine(&quot;Verifying {0} = {1}&quot;, WrongPassword, demo.VerifyHashString(WrongPassword, Hash, Salt));

            // Check if the correct password passes
            Console.WriteLine(&quot;Verifying {0} = {1}&quot;, Password, demo.VerifyHashString(Password, Hash, Salt));

        }
    }

}
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/fernando/">Looking Glass</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/creating-salted-hash-values-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up NUnit for C# Unit Testing with Visual Studio C# Express 2008</title>
		<link>http://www.dijksterhuis.org/setting-up-nunit-for-c-unit-testing-with-visual-studio-c-express-2008/</link>
		<comments>http://www.dijksterhuis.org/setting-up-nunit-for-c-unit-testing-with-visual-studio-c-express-2008/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 04:50:43 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[visual studio express C# 2008]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=292</guid>
		<description><![CDATA[
Unit testing helps you verify that each individual part of your code is working as expected and keeps doing that as you change your software. You do this by adding small bits of testing code and have the unit testing frame work execute them in order.  I am currently writing some code that needs [...]<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/unittesting.gif" alt="" title="Unit Testing with Visual Studio Express 2008" width="500" height="278" class="alignnone size-full wp-image-302" /></p>
<p><em>Unit testing helps you verify that each individual part of your code is working as expected and keeps doing that as you change your software. You do this by adding small bits of testing code and have the unit testing frame work execute them in order.  I am currently writing some code that needs to have a basic unit testing framework and wanted to install the NUnit framework. This post is about how you can install NUnit, use it and run it with / install it for Visual Studio C# 2008 Express. I will leave the nuts and bolts of unit testing to a future post but this post should get you up and running.<br />
</em></p>
<p><span id="more-292"></span></p>
<p>Installing NUnit itself is straightforward and only requires a few steps:</p>
<ul>
<li>Download the NUnit framework from the <a href="http://www.nunit.org/index.php?p=download">NUnit website</a> (download <a href="http://prdownloads.sourceforge.net/nunit/NUnit-2.4.8-net-2.0.msi?download">NUnit-2.4.8-net-2.0.msi</a>)
<li>Install the software on your Windows XP / Vista machine
</ul>
<p><strong>Creating your first NUnit test</strong></p>
<p>Now we need to create a new project to test if this works, and we need to add a reference to NUnit to be able to use the code.</p>
<p>Click &#8220;Project > Add Reference&#8230;&#8221;</p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/nunit1.jpg" alt="" title="Adding NUnit To Visual Studio Express 2008" width="400" height="291" class="alignnone size-full wp-image-293" /></p>
<p>Select &#8220;Browse&#8221; and navigate to &#8220;C:\Program Files\NUnit 2.4.8\bin&#8221; and select the <strong>nunit.framework.dll</strong>.</p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/nunit2.gif" alt="" title="Adding the NUnit Framework DLL to Visual Studio C# Express 2008" width="400" height="300" class="alignnone size-full wp-image-294" /></p>
<p>This allows you to use NUnit.Framework in your programs. </p>
<p><strong>Testing the NUnit Demo code</strong></p>
<p>Below I have included a little bit of demo code that tests if this works properly. The code is mostly borrowed from the NUnit website demo, I have just for the sake of it included a class containing &#8220;Main&#8221; so that the code actually compiles and runs.</p>
<pre class="brush: c#">
using System;
using NUnit.Framework;

namespace bank
{
    public class Account
    {
        private float balance;
        public void Deposit(float amount)
        {
            balance += amount;
        }

        public void Withdraw(float amount)
        {
            balance -= amount;
        }

        public void TransferFunds(Account destination, float amount)
        {
        }

        public float Balance
        {
            get { return balance; }
        }
    }
}

namespace bank
{
    [TestFixture]
    public class AccountTest
    {
        [Test]
        public void TransferFunds()
        {
            Account source = new Account();
            source.Deposit(200.00F);
            Account destination = new Account();
            destination.Deposit(150.00F);

            source.TransferFunds(destination, 100.00F);
            Assert.AreEqual(250.00F, destination.Balance);
            Assert.AreEqual(100.00F, source.Balance);

        }

        [Test]
        public void DepositFunds()
        {
            Account source = new Account();
            source.Deposit(200.00F);
            Assert.AreEqual(200.00F, source.Balance);
        }

    }
}

namespace UnitTestDemo
{
    public class MyAccountingSoftware
    {

        public static void Main()
        {
            bank.Account DemoAccount = new bank.Account();
            DemoAccount.Deposit(1000.00F);
            DemoAccount.Withdraw(500.50F);
            Console.WriteLine(&quot;Our account balance is {0}&quot;, DemoAccount.Balance);
        }

    }
}
</pre>
<p>In the above code the actual unit testing is done by the &#8220;AccountTest&#8221; class, for simplicity we keep this in the same file but usually you would keep a separate directory with all of your unit tests, separate from the actual code. </p>
<p>Note that because the &#8220;<strong>WithDraw</strong>&#8221; function in the code above is poorly implemented (eg. its empty) the Unit test will hopefully (!!) fail. The second unit test in <strong>DepositFunds</strong> should succeed.</p>
<p><strong>How to run the NUnit GUI runner from within Visual Studio C# Express 2008</strong></p>
<p>We can run NUnit from the Menu option it installed under [Start/Programs/NUnit] but it is more convenient to do so from Visual Studio Express itself. </p>
<p>Visual Studio C# Express allows you to define outside &#8220;Tools&#8221; which can be run from the menu. This is exactly what we would like to do with the NUnit GUI Runner. The GUI Runner is a tool which loads our program and executes all the unit tests it finds and reports the results in a seperate window.</p>
<p>Click on &#8220;Tools > External Tools&#8230;&#8221; to add NUnit&#8217;s GUI Runner.</p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/nunit3.gif" alt="" title="Adding NUnit to the VisuaL Studio Express Tools Menu" width="500" height="191" class="alignnone size-full wp-image-296" /></p>
<p>The following definition allows us to run the tests in our current project:</p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/nunit4.gif" alt="" title="Starting NUnit from the Visual Studio Tools Menu" width="460" height="486" class="alignnone size-full wp-image-299" /></p>
<p>To run the unit test, simply click &#8220;NUnit&#8221; from the Tools Menu.</p>
<p><a href="http://www.dijksterhuis.org/wp-content/uploads/2008/11/nunit5.gif"><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/nunit5-300x243.gif" alt="" title="Running NUnit with our Visual Studio C# project" width="300" height="243" class="alignnone size-medium wp-image-300" /></a></p>
<p>[Click the picture for a larger image] </p>
<p>If everything went correctly you should see NUnit run 2 tests, one of which will fail. </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/setting-up-nunit-for-c-unit-testing-with-visual-studio-c-express-2008/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Creating and synchronizing Threads with C#</title>
		<link>http://www.dijksterhuis.org/creating-and-synchronizing-threads-with-c/</link>
		<comments>http://www.dijksterhuis.org/creating-and-synchronizing-threads-with-c/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 06:59:37 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c-sharp]]></category>
		<category><![CDATA[multi threading]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=182</guid>
		<description><![CDATA[
Multi-tasking / multi-threaded applications have always been a bit of a nightmare to create. Different operating systems and sometimes even different compilers and class libraries tends to have their own implementations. Fortunately the .NET /  C# implementation of threading is extremely straightforward and makes it simple to create a multi threaded application. In this [...]<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/threads.jpg" alt="" title="Creating Threads with C#" width="500" height="274" class="alignnone size-full wp-image-186" /></p>
<p><em>Multi-tasking / multi-threaded applications have always been a bit of a nightmare to create. Different operating systems and sometimes even different compilers and class libraries tends to have their own implementations. Fortunately the .NET /  C# implementation of threading is extremely straightforward and makes it simple to create a multi threaded application. In this article we look at building some very simple threaded applications. We go into how to create them, synchronize them and how we can ensure that things such as shared variables are properly protected.</em></p>
<p><span id="more-182"></span></p>
<p>But what are threads anyway? Threading provides the ability for a program to split itself into smaller segments. For example, one thread takes care of the user interface while another task re-calculates data in the background. Because each thread has access to all the variables and memory of the running program there is a need to ensure that they play together nicely. This is solved by adding inter thread communication and synchronization.</p>
<p>To create a new thread, we need to include System.Threading which provides the Thread class. From there on creating a new thread involves only a few steps:</p>
<ol>
<li>Create a new instance of Thread   <em>[new Thread()]</em>
<li>Pass the code starting point point of the thread in its creation <em>[myThread = new Thread( new ThreadStart( myObj.EntryPoint ) )]</em>
<li>Start the Thread <em>[myThread.Start()]</em>
</ol>
<p>The <em>ThreadStart</em> object mentioned in the Thread constructor <a href="http://www.dijksterhuis.org/using-delegates-in-c/">is actually a delegate</a>. It defines the format that the entry point function should follow : a function returning &#8220;void&#8221; that takes no parameters. (Alternatively there is also <em>ParameterizedThreadStart</em> which allows you pass a parameter).</p>
<p>C# makes it possible to name every Thread Object and we use this to give a name to each of the Threads we create.</p>
<p>Each thread is then started and asked to print its name.  In total there will be three messages printed: by the main thread and the two threads we create in the example. Also notice that <i>Thread.CurrentThread</i> provides a reference to the currently executing thread.</p>
<pre class="brush: c#">
using System;
using System.Threading;

namespace TheadingDemo1
{

    class ThreadExample
    {

        static void ShowThreadName()
        {
            Console.WriteLine(&quot;Current Thread: {0}&quot;,Thread.CurrentThread.Name);
        }

        public void ThreadStartPoint()
        {
            ShowThreadName();
        }

        public static void Main()
        {
            // As we enter the program with this thread -- lets call it &quot;main&quot;
            Thread.CurrentThread.Name = &quot;Main&quot;;

            // Create two new instances of the current class
            ThreadExample instance1 = new ThreadExample();
            ThreadExample instance2 = new ThreadExample();

            // We need to setup their starting points, which is the same for both
            Thread thread1 = new Thread( new ThreadStart( instance1.ThreadStartPoint ));
            Thread thread2 = new Thread( new ThreadStart( instance2.ThreadStartPoint ));

            // Name each thread
            thread1.Name = &quot;Instance1&quot;;
            thread2.Name = &quot;Instance2&quot;;

            // Start both threads
            thread1.Start();
            thread2.Start();

            // Display the name of the current (main) thread
            ShowThreadName();           

            Console.WriteLine(&quot;Ending Main Tread&quot;);
        }

    }

}
</pre>
<p>The above example will print something similar to the following:</p>
<pre class="brush: c#">
Current Thread: Main
Current Thread: Instance2
Ending Main Tread
Current Thread: Instance1
</pre>
<p>Note that in this case Instance1 kept on running although the program had already ended. That is because C# makes a distinction between two different kinds of tasks: background tasks and foreground tasks. Foreground threads (the default) will keep the main thread from ending as long as there is still at least one other thread active. Background tasks  die when the programs main thread ends.</p>
<p>To see this effect , modify the above code by adding below line 35:</p>
<pre class="brush: c#">
thread1.IsBackground = true;
thread2.IsBackground = true;
</pre>
<p><strong>Many hands make light work</strong></p>
<p>In the above example we needed to create every task separately, but that becomes tedious if we need to create many. Using the <em>ThreadPool</em> class we only have to queue the actual work, which it will then allocate this to available tasks as required.</p>
<p>A simple example: we have a busy web server and as requests come in we need to serve them. But each request will probably take some time to complete as each thread will need to wait for disk IO and calculations to complete. The <em>ThreadPool</em> class will find an idle task for each new request and if it runs out of idle tasks the <em>ThreadPool</em> will simply create more threads.</p>
<p>Broken down in steps:</p>
<ol>
<li>We create 1000 instances of WebRequest
<li>Each is passed to the ReceiveRequest method
<li>The main thread starts waiting until everything has completed
<li>ReceiveRequest uses <em>ThreadPool.QueueUserWorkItem</em> to queue each request
<li>ThreadPool goes over each queue item, allocates it to a task which then calls &#8220;HandleRequest&#8221; for each
<li>The main thread is woken up
</ol>
<p>We do some more things to smooth communication but first have a look at the code example:</p>
<pre class="brush: c#">
namespace TheadingPool1
{
    // WebRequest
    //
    // This is a simple class that pretends to be a request received from the internet
    // Here it only need to carry a unique number so that we can identify it.

    class WebRequest
    {
        public int id;
        public WebRequest(int id)
        {
            this.id = id;
        }
    }

    // WebServer
    //
    // Our little webserver &quot;receives&quot; requests from the internet, and then queues them
    // The ThreadPool mechanism will allocate a new thread to

    class WebServer
    {
        public int QueueLength;
        ManualResetEvent WaitEvent;
        bool       WaitForComplete;

        public WebServer()
        {
            this.QueueLength = 0;
            this.WaitForComplete = false;
        }

        public void WaitForCompleted()
        {
            // We lock the class to ensure that nobody modifies the QueueLength
            // while we are inspecting it.
            lock(this)
            {
                if (this.QueueLength==0) return;
                WaitEvent = new ManualResetEvent(false);
                WaitForComplete = true;
            }
            // Outside the lock block as we need to free the lock!
            WaitEvent.WaitOne();
        }

        // ReceiveRequest
        //
        // Our webserver has received a request, we use the ThreadPool.QueueWorkItem
        // to find / create a thread that will handle this request.
        //
        // Actual handling of the request is done by the &quot;HandleRequest&quot; function

        public void ReceiveRequest(WebRequest req)
        {
            // This is very simple, there is no need to define the thread pool.
            // We just add work
            ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), req);
            this.QueueLength++;
        }

        public void HandleRequest(Object obj)
        {
            // Notes:
            //
            // 1. Thread.CurrentThread.GetHasCode provides a unique identifies for each thread
            // 2. We need to cast the generic object parameter to our web request

            Console.WriteLine(&quot;Thread {0} handles request {1}&quot;,
                              Thread.CurrentThread.GetHashCode(),
                              ((WebRequest) obj).id);

            // 3. We add sleep to simulate a task taking some time, otherwise its likely that
            //    a single task is able to handle all our requests in order.

            Thread.Sleep(100);

            // 4. Finished, we reduce one item from the queue. If the queue is empty we need
            //    to free the main program

            lock(this)
            {
                this.QueueLength--;
                if (this.QueueLength == 0 &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; this.WaitForComplete)
                {
                    this.WaitEvent.Set();
                }
            }
        }

        public static void Main()
        {
            WebServer server = new WebServer();

            // &quot;Receive&quot; 1000 requests from the internet and queue them
            for (int Lp = 0; Lp &lt; 1000; Lp ++)
                server.ReceiveRequest( new WebRequest( Lp ));

            // We wait until the queue has emptied
            server.WaitForCompleted();

            Console.WriteLine(&quot;Main Thread has completed&quot;);
        }
    }
}
</pre>
<p><strong>So how do we know if the work has been completed?</strong></p>
<p>The Webserver class keeps track of the number of outstanding tasks and as soon as this reaches zero the task completing the last work item frees the main task from its wait.</p>
<p>This is done by using a <em>ManualResetEvent</em>.</p>
<p>Any task which calls <em>WaitOne()</em> on a <em>ManualResetEvent</em> will be suspended until another task frees it by calling <em>Set()</em>. It is possible for more tasks to wait for the same <em>ManualResetEvent</em>, but in our example only the main task needs to wait.</p>
<p>When our <em>HandleRequest</em> method discovers that it has handled the last outstanding request it calls <em>Set()</em> freeing the main task to end the program.</p>
<p><strong>We need to avoid interruption</strong></p>
<p>As multiple tasks are executing the code at the same time several critical sections might be updated by more than one task at the same time.</p>
<p>In our example the critical code is the code which maintains the <em>QueueLength</em> variable. Every time a task is completed it reduces <em>QueueLength</em> by one, and every time a task is added <em>QueueLength</em> is increased. But what happens if a task reduces the <em>QueueLength</em> while another one is checking if its zero?</p>
<p>There are several things that could go unexpectedly wrong, which is something called a &#8220;race condition&#8221;.</p>
<p>We would like to ensure that these statements are executed in order and without interruption &#8212; as an essentially atomic operation.</p>
<p>C# allows you to synchronize tasks by exclusively locking a code segment with the lock() statement. Only one task can enter this segment of the code. All others tasks reaching it will be suspended until the first task has completed it.</p>
<pre class="brush: c#">
lock(this)
{
   // The code between these brackets can only be entered by one task modifying this instance
   // of the class
}
</pre>
<p>In the example above we have protected each critical section that modifies <em>QueueLength</em> by placing it in an exclusive block.</p>
<p>This is the ABC of building a threaded application in C#. In another article I hope to go further into the details of inter thread and inter process communication.</p>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/chefranden/">chefranden</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/creating-and-synchronizing-threads-with-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generics in C#</title>
		<link>http://www.dijksterhuis.org/generics-in-c/</link>
		<comments>http://www.dijksterhuis.org/generics-in-c/#comments</comments>
		<pubDate>Sat, 15 Nov 2008 08:29:22 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=116</guid>
		<description><![CDATA[
You heard might have heard about generics, but how do they work in C# ? And what is that &#60;T&#62; doing in the class definition? This article shows you the benefits of using generics, and how to implement them yourself.


Version 2 of C# introduced something called a &#8220;generic&#8221;. In this article we will look into [...]<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/codereuse.jpg" alt="" title="Code Re-Use in C# through Generics" width="500" height="311" class="alignnone size-full wp-image-123" /><br />
<em>You heard might have heard about generics, but how do they work in C# ? And what is that &lt;T&gt; doing in the class definition? This article shows you the benefits of using generics, and how to implement them yourself.<br />
</em><br />
<span id="more-116"></span></p>
<p>Version 2 of C# introduced something called a &#8220;generic&#8221;. In this article we will look into what a generic is, and why you would want to use them. Generics are similar to a concept frequently used in C++ Templates. They allow you to better re-use your code while at the same time providing more information to the compiler on what should be allowed, and what shouldn&#8217;t.</p>
<p>The code below give an example on how  generics can improve the compilers knowledge of what it should accept. A very basic vector array class is defined to accept only strings.</p>
<p><em>This code is just for illustration of the Generics concept. Normally you would just use the build in C# Array type to obtain the same Array functionality. </em></p>
<pre class="brush: c#">
    class Vector
    {
        string[] elements;

        public Vector(int maximum_elements)
        {
            elements = new string[maximum_elements];
        }

        public string this[int i]
        {
            get {return elements[i];}
            set {elements[i] = value;}
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            Vector test = new Vector(20);

            test[1] = &quot;42&quot;;
            // The compiler catches this, we cannot convert an integer to string
            // test[2] = 123;
            string theAnswer = test[1];
            Console.WriteLine(&quot;The answer is {0}&quot; , theAnswer );
        }
    }
</pre>
<p>The above vector array code can only be used for storing strings,limiting our re-use of the code. What to do if we would like to store integers instead?</p>
<p>We can improve the code by making it more abstract by replacing the <em>int</em> definitions with the more general <em>object</em> tag. </p>
<p> It is now possible to store all kinds of elements (not just integers) in the Vector. But because the compiler no longer knows what type is stored in the Vector, it allows all kinds. Worse, we now need to cast all return values to our main type (<em>string</em>) as the compiler cannot implicitly convert objects to strings. </p>
<pre class="brush: c#">
    class Vector
    {
        object[] elements;

        public Vector(int maximum_elements)
        {
            elements = new object[maximum_elements];
        }

        public object this[int i]
        {
            get {return elements[i];}
            set {elements[i] = value;}
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            Vector test = new Vector(20);

            test[1] = &quot;42&quot;; // The Vector doesn&#039;t know about our type
            test[2] = 123;// So both strings and numbers are OK, allowing for mistakes
            string theAnswer = (string) test[1];// We are also forced to cast (object) to (string)
            Console.WriteLine(&quot;The answer is {0}&quot; , theAnswer );
        }
    }
</pre>
<p>Generics help out by allowing us to define our Vector as an abstract type. Note the &lt;T&gt; given in the class definition of the Vector. It replaces all instances where we would have said &#8220;string&#8221;, &#8220;int&#8221; or &#8220;object&#8221; previously.</p>
<pre class="brush: c#">
    class Vector&lt;T&gt;
    {
        T[] elements;

        public Vector(int maximum_elements)
        {
            elements = new T[maximum_elements];
        }

        public T this[int i]
        {
            get {return elements[i];}
            set {elements[i] = value;}
        }
    }

    class MainClass

    {
        public static void Main(string[] args)
        {
            Vector&lt;string&gt; test= new Vector&lt;string&gt;(20);

            test[1] = &quot;42&quot;;
            // The compiler catches this, we cannot convert an integer to string
            // test[2] = 123;
            string theAnswer = test[1];
            Console.WriteLine(&quot;The answer is {0}&quot; , theAnswer );
        }
    }
</pre>
<p>The above example removes the need to typecast any returned value, the compiler is already aware of the correct type (&#8221;string&#8221; in our example). The code is also type-safe as it is no longer possible to assign the wrong type to an element in the Vector and finally, the above Vector code can be re-used to hold any kind of variable.</p>
<p>We could re-use the final code to create any kind of container; suitable for holding only a single type.</p>
<pre class="brush: c#">
Vector&lt;int&gt;    test1 = new Vector&lt;int&gt;(20);
Vector&lt;string&gt; test2 = new Vector&lt;string&gt;(20);
Vector&lt;float&gt;  test3 = new Vector&lt;float&gt;(20);
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/9229859@N02/">bucklava</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/generics-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
