<?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; Learn C#</title>
	<atom:link href="http://www.dijksterhuis.org/tag/csharp/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>Formatting Strings in C# with String.Format</title>
		<link>http://www.dijksterhuis.org/formatting-strings-stringformat/</link>
		<comments>http://www.dijksterhuis.org/formatting-strings-stringformat/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 09:21:58 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[string.format]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=541</guid>
		<description><![CDATA[
String.Format is a very powerful method but the documentation at MSDN is quite wordy and spreads the details over many pages. For this post I have made quick reference to its many specifiers and for good measure added some examples to help get you started.If you would like to format a date, currency, number or [...]<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/2009/02/stringformat.jpg" alt="A String.Format Reference for C#" title="A String.Format Reference for C#" width="500" height="222" class="alignnone size-full wp-image-559" /></p>
<p><em>String.Format is a very powerful method but the documentation at MSDN is quite wordy and spreads the details over many pages. For this post I have made quick reference to its many specifiers and for good measure added some examples to help get you started.If you would like to format a date, currency, number or just the time, String.Format is your friend.</em><br />
<span id="more-541"></span><br />
For a trip down memory lane a little example how we did things in C. The C <em>sprintf</em> function takes a buffer, a formatting string, a couple of parameters and munches them together:</p>
<pre class="brush: c">
#include &lt;stdio.h&gt;
int main()
{
char buffer[255];
sprintf(buffer,&quot;Customer %d lives is %d years old and owns us %2.2f dollars&quot;, 1024, 96, 125.6f);
printf(&quot;%s&quot;,buffer);
}
</pre>
<p>This results in the following output:</p>
<blockquote><p>Customer 1024 is 96 years old and owns us 125.50</p></blockquote>
<p>Of course, if we made the buffer too small and the string expanded too much we might have created a buffer overrun once of C&#8217;s pesky little annoyances. And of course for each parameter we need to specify how to format them (%d for integers, %s for strings and %f for floats). Get the type wrong and things will go funny fast.</p>
<p><strong>Enter String.Format and Console.WriteLine</strong></p>
<p>So how do things work in C#? The String.Format method takes care of all our needs and a little more. Similar to the relationships between <em>sprintf</em> and <em>printf</em> the methods <em>String.Format</em> and <em>Console.WriteLine</em> work similary. String.Format returns a string whereas Console.WriteLine sends the resulting string to the console output. </p>
<p>The following should be a familiar example:</p>
<blockquote><p>int ResultValue = 123;<br />
string myString = String.Format(&#8221;The value is {0}&#8221;,ResultValue);<br />
Console.WriteLine(&#8221;The value is {0}&#8221;,ResultValue);</p></blockquote>
<p><strong>The Index </strong></p>
<p>The {0} is an index and refers to the first parameter given following the formatting string. {1},{2} to the second, third etc. You can also refer to a parameter more than once. The following is perfectly acceptable:</p>
<blockquote><p>Console.WriteLine(&#8221;First {0}, Second {1}, Third {2}, And again the First {0}&#8221;,Value1,Value2,Value2);</p></blockquote>
<p><strong>Aligning the output</strong></p>
<p>C# provides an alignment value that allows you to left or right align the output. Handy for screen or print formatting.</p>
<p>If you specify an alignment of 10 characters the resulting string will always be 10 characters even if the number only took up 4 places. The remainder is padded with spaces. If the value we want to display is longer than our given alignment size the alignment value is ignored.</p>
<blockquote><p>Console.WriteLine(&#8221;The value is {0,10} &#8211; continue from here&#8221;,9999);</p></blockquote>
<p>The above will output the value &#8220;9999&#8243;, and allocate 10 spaces for it. The output is right-aligned, the format method will simply add sufficient spaces to make sure the total length adds up to 10 characters.</p>
<p>To make the output left-aligned we need to make the number negative:</p>
<blockquote><p>Console.WriteLine(&#8221;The value is {0,-10} &#8211; continue from here&#8221;,9999);</p></blockquote>
<p><strong>Displaying enumerated types</strong></p>
<p>One very interesting feature of C# is the ability to display enumerated types.If you make your own enumeration wouldn&#8217;t it be nice if you could just print the values as a string literals? In fact you can as shown by the following example:</p>
<pre class="brush: c#">
class MainClass
{
public enum Transport {Car = 1, Plane = 2, Motorcycle = 3}

public static void Main(string[] args)
{
Transport peopleMover = Transport.Plane;

Console.WriteLine(&quot;{0:G}&quot;,peopleMover);  // string literal
Console.WriteLine(&quot;{0:f}&quot;,peopleMover);   // flag -- not clear
Console.WriteLine(&quot;{0:d}&quot;,peopleMover);  // decimal
Console.WriteLine(&quot;{0:x}&quot;,peopleMover);   // hexadecimal
}
}
</pre>
<p>This outputs:</p>
<blockquote><p>Plane</p>
<p>Plane</p>
<p>2<br />
00000002</p></blockquote>
<p><strong>Basic number formatting</strong></p>
<p>When no format is specified the String.Format method applies the &#8220;g&#8221; (General) type, which results in any value passed being rendered into a standard string. The following table shows what is possible:</p>
<p>If the table lists (error) it means that the <em>String.Format</em> method threw a <em>String.Formatting</em> exception. This happens if the number cannot be converted properly.</p>
<div>
<table border="1" cellspacing="0" cellpadding="2" width="100%">
<tbody>
<tr valign="top">
<td><strong>Format specifier</strong></td>
<td><strong>Name</strong></td>
<td><strong>1234.56 (double)</strong></td>
<td><strong>-100000 (int)</strong></td>
<td><strong>Description</strong></td>
</tr>
<tr valign="top">
<td>{0:c}</td>
<td>Currency</td>
<td>$123.45</td>
<td>($-100,000.00)</td>
<td>The number is converted to a string that represents a currency amount.</td>
</tr>
<tr valign="top">
<td>{0:d}</td>
<td>Decimal</td>
<td>(error)</td>
<td>-100000</td>
<td>Display a decimal amount, but throws an exception on non-decimal values (floats).</td>
</tr>
<tr valign="top">
<td>{0:e}</td>
<td>Scientific</td>
<td>1.234500e+002</td>
<td>-1.000000e+005</td>
<td>The number is converted to a string of the form &#8220;-d.ddd&#8230;E+ddd&#8221; or &#8220;-d.ddd&#8230;e+ddd&#8221;, where each &#8216;d&#8217; indicates a digit (0-9).</td>
</tr>
<tr valign="top">
<td>{0:f}</td>
<td>Fixed-point</td>
<td>123.45</td>
<td>-100000.00</td>
<td>The number is converted to a string of the form &#8220;-ddd.ddd&#8230;&#8221; where each &#8216;d&#8217; indicates a digit (0-9). The string starts with a minus sign if the number is negative.</td>
</tr>
<tr valign="top">
<td>{0:g}</td>
<td>General</td>
<td>123.45</td>
<td>-100000</td>
<td>The default format</td>
</tr>
<tr valign="top">
<td>{0:n}</td>
<td>Number</td>
<td>123.45</td>
<td>-100,000.00</td>
<td>Thousand separators are inserted between each group of three digits to the left of the decimal point.</td>
</tr>
<tr valign="top">
<td>{0:p}</td>
<td>Percent</td>
<td>12,345.00%</td>
<td>-10,000,000.00 %</td>
<td>The number is converted to a percentage.</td>
</tr>
<tr valign="top">
<td>{0:r}</td>
<td>Round-Trip</td>
<td>123.45</td>
<td>(error)</td>
<td>Guarantees that the number can be returned to its original value on conversion from string to number.</td>
</tr>
<tr valign="top">
<td>{0:x} or {0:X}</td>
<td>Hexadecimal</td>
<td>(error)</td>
<td>FFFE7960</td>
<td>Use &#8216;X&#8217; to produce &#8220;ABCDEF&#8221;, and &#8216;x&#8217; to produce &#8220;abcdef&#8221;.</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Custom number formatting</strong></p>
<p><strong></strong>Of course, your preferred format is not listed above and you need a few modifications made. Not a problem. Custom formatting allows for any kind of number-to-string conversion you might need:</p>
<div>
<table id="s4ei" class="zeroBorder" border="1" cellspacing="0" cellpadding="2" width="100%">
<tbody>
<tr>
<td><strong>Name</strong></td>
<td><strong>Format</strong></td>
<td><strong>Example</strong></td>
<td>Input</td>
<td><strong>Output</strong></td>
</tr>
<tr>
<td>Zero placeholder</td>
<td>0</td>
<td>{0:000.00}</td>
<td>45.5</td>
<td>045.50</td>
</tr>
<tr>
<td>Digit placeholder</td>
<td>#</td>
<td>{0:###.##}</td>
<td>45.5</td>
<td>45.5</td>
</tr>
<tr>
<td>Decimal point</td>
<td>.</td>
<td>{0:00.00}</td>
<td>45.5</td>
<td>45.50</td>
</tr>
<tr>
<td>Thousand separator (requires 0)</td>
<td>,</td>
<td><span style="font-family: Courier New; font-size: x-small;">{0:0,0</span>}</td>
<td>1000000</td>
<td>1,000,000</td>
</tr>
<tr>
<td>Percent (multiplies by 100)</td>
<td><span style="font-size: x-small;">%</span></td>
<td>{0:0%}</td>
<td>45.5</td>
<td>4550%</td>
</tr>
<tr>
<td>Scientific notation (multiple formats)</td>
<td>E0,E+0,E-0,e0,e+0,e-0</td>
<td>{0:E0}</td>
<td>1000000</td>
<td>1E+006</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Date formats</strong></p>
<p><strong></strong>The following table show the basic date formats obtained from calling DateTime.Now and then formatting the result. Note that different systems might produce different results depending on how the operating system is configured (think Chinese/Japanese/etc systems).<strong></strong></p>
<div>
<table id="s8:k" class="zeroBorder" border="1" cellspacing="0" cellpadding="2" width="100%">
<tbody>
<tr>
<td><strong>Specifier</strong></td>
<td><strong>Description</strong></td>
<td><strong>Example</strong></td>
</tr>
<tr>
<td>{0:d}</td>
<td><span>Short date</span></td>
<td><span>2/4/2009</span></td>
</tr>
<tr>
<td>{0:D}</td>
<td><span>Long date</span></td>
<td><span>Wednesday, February 04, 2009</span></td>
</tr>
<tr>
<td>{0:t}</td>
<td><span>Short time</span></td>
<td><span>2:59 PM</span></td>
</tr>
<tr>
<td>{0:T}</td>
<td><span>Long time</span></td>
<td><span>2:59:14 PM</span></td>
</tr>
<tr>
<td>{0:f}</td>
<td>Full date/time (short time)</td>
<td><span>Wednesday, February 04, 2009 2:59 PM</span></td>
</tr>
<tr>
<td>{0:F}</td>
<td>Full date/time  (long time)</td>
<td><span>Wednesday, February 04, 2009 2:59:40 PM</span></td>
</tr>
<tr>
<td>{0:g}</td>
<td>General date/time  (short time)</td>
<td><span>2/4/2009 2:59 PM</span></td>
</tr>
<tr>
<td><span>{0:G}</span></td>
<td>General date/time  (long time)</td>
<td><span>2/4/2009 3:01:12 PM</span></td>
</tr>
<tr>
<td><span>{0:M}</span></td>
<td>Month day</td>
<td><span>February 4</span></td>
</tr>
<tr>
<td>{0:R}</td>
<td>RFC1123</td>
<td><span>Wed, 04 Feb 2009 15:01:55 GMT</span></td>
</tr>
<tr>
<td>{0:s}</td>
<td>Sortable date/time ; conforms to ISO 8601</td>
<td><span>2009-02-04T15:02:10</span></td>
</tr>
<tr>
<td>{0:u}</td>
<td>Universal sortable date/time</td>
<td><span>2009-02-04 15:02:28Z</span></td>
</tr>
<tr>
<td>{0:U}</td>
<td>Universal sortable date/time</td>
<td><span>Wednesday, February 04, 2009 7:03:11 AM</span></td>
</tr>
<tr>
<td>{0:Y}</td>
<td>Year month</td>
<td><span>February, 2009</span></td>
</tr>
</tbody>
</table>
</div>
<p><strong></strong><strong><br />
Custom Date formatting</strong></p>
<p><strong></strong>The custom format strings allow DateTime objects to be formatted when the standard formatting strings are not useful and you need some special.</p>
<div>
<table class="zeroBorder" border="1" cellspacing="0" cellpadding="2" width="100%">
<tbody>
<tr>
<td><strong>Specifier<br />
</strong></td>
<td><strong>Description<br />
</strong></td>
<td><strong>Example<br />
</strong></td>
<td><strong>Output<br />
</strong></td>
</tr>
<tr>
<td>d</td>
<td>Day of the month as a number</td>
<td>{0:d}</td>
<td>4</td>
</tr>
<tr>
<td>dd</td>
<td>Day of the month as a number, with leading zero</td>
<td>{0:dd}</td>
<td>04</td>
</tr>
<tr>
<td>ddd</td>
<td>Abbriviated day of the month name</td>
<td>{0:ddd}</td>
<td>Wed</td>
</tr>
<tr>
<td>dddd</td>
<td>Full day of the month name</td>
<td>{0:dddd}</td>
<td><span>Wednesday</span></td>
</tr>
<tr>
<td>f,ff,fff</td>
<td>Fraction of a second (repeat &#8220;f&#8221; for more precision)</td>
<td>{0:fff}</td>
<td><span>405</span></td>
</tr>
<tr>
<td>gg,ggg</td>
<td>The era</td>
<td>{0:gg}</td>
<td>A.D.</td>
</tr>
<tr>
<td>h</td>
<td>Hour (1-12 range)</td>
<td>{0:h}</td>
<td>3</td>
</tr>
<tr>
<td>hh</td>
<td>Hour (1-12 range, with leading zero for 0-9)</td>
<td>{0:hh}</td>
<td><span>03</span></td>
</tr>
<tr>
<td>H</td>
<td>Hour (0-23 range)</td>
<td>{0:H}</td>
<td>15</td>
</tr>
<tr>
<td>HH</td>
<td>Hour (0-23 range with leading zero for 0-9)</td>
<td>{0:HH}</td>
<td>03</td>
</tr>
<tr>
<td>m</td>
<td>Minutes (0-59)</td>
<td>{0:m}</td>
<td>9</td>
</tr>
<tr>
<td>mm</td>
<td>Minutes (0-59 range with leading zero for 0-9)</td>
<td>{0:mm}</td>
<td>09</td>
</tr>
<tr>
<td>M</td>
<td>Number of the month (0-12)</td>
<td>{0:M}</td>
<td>2</td>
</tr>
<tr>
<td>MM</td>
<td>Number of the month (0-12 with leading zero for 0-9)</td>
<td>{0:MM}</td>
<td>02</td>
</tr>
<tr>
<td>MMM</td>
<td>Abbreviated name of the month</td>
<td>{0:MMM}</td>
<td>Feb</td>
</tr>
<tr>
<td>MMMM</td>
<td>Specifies the full name of the month</td>
<td>{0:MMMM}</td>
<td><span>February</span></td>
</tr>
<tr>
<td>s</td>
<td>Seconds (0-59 range)</td>
<td>{0:s}</td>
<td>23</td>
</tr>
<tr>
<td>ss</td>
<td>Seconds (0-59 range with leading zero for 0-9)</td>
<td>{0:ss}</td>
<td>23</td>
</tr>
<tr>
<td>tt</td>
<td>Both characters of the AM/PM range</td>
<td>{0:tt}</td>
<td>PM</td>
</tr>
<tr>
<td>y</td>
<td>The first two digits of the year (0-99)</td>
<td>{0:y}</td>
<td>9</td>
</tr>
<tr>
<td>yy</td>
<td>The first two digits of the year (0-99) with leading zero for 0-9</td>
<td>{0:yy}</td>
<td>09</td>
</tr>
<tr>
<td>yyyy</td>
<td>Four digit year number, if the year is less than 1000 it has 0&#8217;s prepended</td>
<td>{0:yyyy}</td>
<td></td>
</tr>
<tr>
<td>zz</td>
<td>The timezone offset in whole hours</td>
<td>{0:zz}</td>
<td>+08</td>
</tr>
<tr>
<td>zzz</td>
<td>The timezone offset in hours and minutes</td>
<td>{0:zzz}</td>
<td>+08:00</td>
</tr>
<tr>
<td>:</td>
<td>Time seperator</td>
<td>{0:hh:mm}</td>
<td><span>03:33</span></td>
</tr>
<tr>
<td>/</td>
<td>Date seperator</td>
<td>{0:MM/yyyy}</td>
<td><span>02/2009</span></td>
</tr>
</tbody>
</table>
</div>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/easement/">easement</a></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/formatting-strings-stringformat/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Timing C# function performance with the Stopwatch class</title>
		<link>http://www.dijksterhuis.org/timing-function-performance-stopwatch-class/</link>
		<comments>http://www.dijksterhuis.org/timing-function-performance-stopwatch-class/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 03:55:18 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[function execution]]></category>
		<category><![CDATA[stopwatch]]></category>
		<category><![CDATA[timing]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=458</guid>
		<description><![CDATA[
Occasionally you need to time the performance of a C# function to see if its as fast, or as slow, as you think it is. You could of course run your code through a profiler. But in situations that that would be overkill there exists a quick solution. Originally I looked at the standard DateTime [...]<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><img class="alignnone size-full wp-image-460" title="Timing C# function execution time with a stopwatch" src="http://www.dijksterhuis.org/wp-content/uploads/2009/01/stopwatch1.jpg" alt="Timing C# function execution time with a stopwatch" width="499" height="258" /><br />
Occasionally you need to time the performance of a C# function to see if its as fast, or as slow, as you think it is. You could of course run your code through a profiler. But in situations that that would be overkill there exists a quick solution. Originally I looked at the standard DateTime class, but NET 2.0 introduced the  Stopwatch class which is much more suitable. In this post I look at how you can measure your functions performance down to the last fraction of a millisecond. </em></p>
<p><span id="more-458"></span></p>
<p><strong>How not to measure your C# functions execution time</strong></p>
<p>The DateTime.Now function returns the current time on your computer, down to the millisecond. A simple approach to measuring the time of a function would thus be:</p>
<pre class="brush: c#">
DateTime Start = DateTime.Now;

for (int Lp = 0; Lp &lt; 100; Lp++)
Console.WriteLine(&quot;Hello World!&quot;);

TimeSpan Elapsed = DateTime.Now - Start;
Console.WriteLine(&quot;Time Elapsed: {0} ms&quot;,Elapsed.Milliseconds);
</pre>
<p>The problem is that <a rel="nofollow" href="http://msdn.microsoft.com/en-us/library/system.datetime.now.aspx">according to MSDN</a> the resolution of the DateTime.Now function is 10+ milliseconds, and we need to call it twice! So that would introduce a 20+ ms swing in your runtime measurement. As our function calls are often likely to be a lot quicker to return than this 20ms window this isn&#8217;t good enough.</p>
<p>Another approach would be to use the system tickcount as kept by the Environment.TickCount variable, which is also kept in milliseconds. This keeps the number of milliseconds since the computer was started. Unfortunately it is kept in a signed int, so that every 49 days (how often do you reset your computer?) it is actually counting backwards. We can compensate for this by just taking off the most siginificant bit.</p>
<pre class="brush: c#">
int Start = Environment.TickCount &amp;amp;amp;amp; Int32.MaxValue;

for (int Lp = 0; Lp &lt; 100; Lp++)
Console.WriteLine(&quot;Hello World!&quot;);

int Elapsed = (Environment.TickCount &amp;amp;amp;amp; Int32.MaxValue) - Start;
Console.WriteLine(&quot;Time Elapsed: {0} ms&quot;,Elapsed);
</pre>
<p><strong>Using the Stopwatch class</strong></p>
<p>The .NET 2.0 libraries introduced the Stopwatch class in <em>System.Diagnostics</em> which is much better suited for what we intend to do.  The class depends on the hardware available in your computer, if a high resolution timer is available is will use this, otherwise it will fall back to DateTime.Now.</p>
<p>You can check if the Stopwatch is using a high resolution timer by calling <em>Stopwatch.IsHighResolution</em>, and inquiry about the resolution in ticks per second by querying <em>Stopwatch.Frequency</em>.</p>
<pre class="brush: c#">
// If we don&#039;t have a high resolution timer then Stopwatch will fall back
// to DateTime, which is much less reliable
if (Stopwatch.IsHighResolution)
Console.WriteLine(&quot;We have a high resolution timer available&quot;);

long frequency = Stopwatch.Frequency;
Console.WriteLine(&quot; Timer frequency in ticks per second = {0}&quot;,frequency);
</pre>
<p>To start a Stopwatch simply call &#8220;Stopwatch.StartNew()&#8221; as shown below:</p>
<pre class="brush: c#">
// Start the stopwatch
Stopwatch sw = Stopwatch.StartNew();

for (int Lp = 0; Lp &lt; 100; Lp++)
Console.WriteLine(&quot;Hello World!&quot;);

// Stop the stopwatch
sw.Stop();

// Report the results
Console.WriteLine(&quot;Time used (float): {0} ms&quot;,sw.Elapsed.TotalMilliseconds);
Console.WriteLine(&quot;Time used (rounded): {0} ms&quot;,sw.ElapsedMilliseconds);
</pre>
<p>The <em>ElapsedMilliseconds</em> property returns a rounded number to the nearest full millisecond, the <em>Elapsed.TotalMilliseconds</em> property is a float that can return execution times to the partial millisecond.</p>
<p><em>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/27383466@N02/">Stopwatch by Duy</a></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/timing-function-performance-stopwatch-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a GTK notification area icon using Mono and C#</title>
		<link>http://www.dijksterhuis.org/creating-gtk-notification-area-icon-mono/</link>
		<comments>http://www.dijksterhuis.org/creating-gtk-notification-area-icon-mono/#comments</comments>
		<pubDate>Fri, 02 Jan 2009 08:14:59 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[GTK]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[mono]]></category>
		<category><![CDATA[StatusIcon]]></category>
		<category><![CDATA[Tooltip]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=435</guid>
		<description><![CDATA[
Cool (Linux) applications have their own icon in the notification area. To add my own icon in the Gnome notification area using Mono only took a few lines of code. In the post below I show how you can add your icon and associate a tooltip and right click menu to it.

GTK provides the StatusIcon [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dijksterhuis.org/wp-content/uploads/2009/01/tooltip.png"><img src="http://www.dijksterhuis.org/wp-content/uploads/2009/01/tooltip.png" alt="Adding a Gnome tooltip to your application with C# and Mono" title="Adding a Gnome tooltip to your application with C# and Mono" width="500" height="57" class="alignnone size-full wp-image-436" /></a></p>
<p><em>Cool (Linux) applications have their own icon in the notification area. To add my own icon in the Gnome notification area using Mono only took a few lines of code. In the post below I show how you can add your icon and associate a tooltip and right click menu to it.</em></p>
<p><span id="more-435"></span></p>
<p>GTK provides the <em>StatusIcon</em> class to register your own icon in the notification area.</p>
<pre class="brush: c#">
    StatusIcon  myStatusIcon;
</pre>
<p>You can provide and load your own icon, but for this example I used one of the GTK stock icons.</p>
<pre class="brush: c#">
     myStatusIcon = StatusIcon.NewFromStock(Stock.Harddisk);  // I use a stock icon from Stock.*
                                                                                          // to avoid having to include an icon file
     myStatusIcon.Visible = true;                                             // Make sure we are displayed
</pre>
<p>Adding or changing a tooltip is as straighforward as assigning it:</p>
<pre class="brush: c#">
      myStatusIcon.Tooltip = &quot;Hello World ToolTip&quot;;                      // The message to show when the mouse hovers over the icon
</pre>
<p>To create a rightclick menu we need to register the PopupMenu event handler:</p>
<pre class="brush: c#">
     myStatusIcon.PopupMenu += OnStatusIconPopupMenu;         // Link in the right click popup menu
     ...
     ...

    /* The Status Popup menu is shown when the user right clicks on the toolbar icon */

    protected void OnStatusIconPopupMenu(object sender, EventArgs e)
    {
        Menu popupMenu = new Menu();

        MenuItem helloItem = new MenuItem(&quot;About Hello World&quot;);
        helloItem.Show();
        helloItem.Activated += new EventHandler(OnHelloAboutActivated);

        popupMenu.Append(helloItem);
        popupMenu.Popup(null,null,null,3,Gtk.Global.CurrentEventTime);
    }
</pre>
<p>And that is really all there is to it. I have included the complete code below. If you create a new GTK solution in MonoDevelop you will end up with two files, Main.cs and MainWindows.Cs. Replace the MainWindow.CS file with the content below: </p>
<pre class="brush: c#">

using System;
using Gtk;

public partial class MainWindow: Gtk.Window
{
	StatusIcon  myStatusIcon;
	AboutDialog aboutDialog;

	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{

		/* The following lines create the notification area status icon */
		/* Make it visible and link in the right click popup menu       */ 

		myStatusIcon = StatusIcon.NewFromStock(Stock.Harddisk);  // I use a stock icon from Stock.*
		                                                         // to avoid having to include an icon file
		myStatusIcon.Tooltip = &quot;Hello World ToolTip&quot;;            // The message to show when the mouse hovers over the icon
		myStatusIcon.Visible = true;                             // Make sure we are displayed
		myStatusIcon.PopupMenu += OnStatusIconPopupMenu;         // Link in the right click popup menu 

		/* Not necessary */
		Label AppWindowLabel = new Label(&quot;Hello World&quot;);
		this.Add(AppWindowLabel);

		Build ();
	}

	/* Called when the main application closes */

	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}

	/* The Status Popup menu is shown when the user right clicks on the toolbar icon */

	protected void OnStatusIconPopupMenu(object sender, EventArgs e)
	{
		Menu popupMenu = new Menu();

		MenuItem helloItem = new MenuItem(&quot;About Hello World&quot;);
		helloItem.Show();
		helloItem.Activated += new EventHandler(OnHelloAboutActivated);

		popupMenu.Append(helloItem);
		popupMenu.Popup(null,null,null,3,Gtk.Global.CurrentEventTime);
	}

	/* If the user select the &quot;About Hello World&quot; menu option, we show the about dialog */

	protected void OnHelloAboutActivated(object sender, EventArgs e)
	{
		aboutDialog = new AboutDialog();

		aboutDialog.ProgramName = &quot;The About Dialog Popup Demo&quot;;
		aboutDialog.Version = &quot;1.0beta&quot;;
		aboutDialog.Comments = &quot;The best things in life are simple!&quot;;
		aboutDialog.License = &quot;Creative Commons&quot;;
		aboutDialog.Authors = new string[] { &quot;Martijn Dijksterhuis&quot; };
		aboutDialog.Website = &quot;http://www.dijksterhuis.org&quot;;
		aboutDialog.Response += new ResponseHandler(OnHelloAboutClose);

		aboutDialog.Run();
	}

	/* Catch the &quot;Close&quot; and &quot;X&quot; button event from the about dialog box */

	protected void OnHelloAboutClose(object sender, ResponseArgs e)
	{
		if (e.ResponseId==ResponseType.Cancel || e.ResponseId==ResponseType.DeleteEvent)
		 aboutDialog.Destroy();
	}

}
</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/creating-gtk-notification-area-icon-mono/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sorting Generic Lists in C#</title>
		<link>http://www.dijksterhuis.org/sorting-generic-lists/</link>
		<comments>http://www.dijksterhuis.org/sorting-generic-lists/#comments</comments>
		<pubDate>Thu, 01 Jan 2009 05:07:32 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[generic]]></category>
		<category><![CDATA[ICompare]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[quicksort]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=427</guid>
		<description><![CDATA[Sorting a basic generic list in C# is trivial as long as you store basic elements such as strings or integers for which default comparison classes have been defined. In this post we will look into how we can reverse the string sort by implementing your own ICompare comparer, and how you can build your [...]<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>Sorting a basic generic list in C# is trivial as long as you store basic elements such as strings or integers for which default comparison classes have been defined. In this post we will look into how we can reverse the string sort by implementing your own ICompare comparer, and how you can build your own comparison routines to compare other types. In the example we sort a list  (List<>) of people by both their name and their age.</em></p>
<p><span id="more-427"></span></p>
<p>The C# libraries already implement the Quicksort sorting algorithm. So for either a string or an int, sorting the list is as straightforward as calling &#8220;Sort&#8221;, as show in the below example. </p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;

namespace IComparer
{
    class MainClass
    {
        public static void Main(string[] args)
        {

            List&lt;string&gt; myList = new List&lt;string&gt;();

            myList.Add(&quot;z&quot;);
            myList.Add(&quot;c&quot;);
            myList.Add(&quot;a&quot;);
            myList.Add(&quot;d&quot;);
            myList.Add(&quot;b&quot;);

            myList.Sort();

            int cnt = 0;
            foreach(string letter in myList)
                Console.WriteLine(&quot;{0} = {1}&quot;,cnt++,letter);
        }
    }
}
</pre>
<p>This code will output:</p>
<pre class="brush: c#">
0 = a
1 = b
2 = c
3 = d
4 = z
</pre>
<p>But what to do if you would like to reverse the sorting order ? We will have to define our own reverse string comparison routine by sub-classing IComparer<string>. In the essential Compare function we simply call the standard String.Compare function with the parameters in reverse order:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;

namespace IComparer
{

    public class ReverseStringComparer : IComparer&lt;string&gt;
    {
        public int Compare(string x, string y)
        {
            // We reverse the result by flipping the input parameters
            return String.Compare(y,x);
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {

            List&lt;string&gt; myList = new List&lt;string&gt;();

            myList.Add(&quot;z&quot;);
            myList.Add(&quot;c&quot;);
            myList.Add(&quot;a&quot;);
            myList.Add(&quot;d&quot;);
            myList.Add(&quot;b&quot;);

            ReverseStringComparer myComparer = new ReverseStringComparer();        

            myList.Sort(myComparer);

            int cnt = 0;
            foreach(string letter in myList)
                Console.WriteLine(&quot;{0} = {1}&quot;,cnt++,letter);
        }
    }
}
</pre>
<p>This code will output:</p>
<pre class="brush: c#">
0 = z
1 = d
2 = c
3 = b
4 = a
</pre>
<p>Both strings and numbers are very basic types. If you want to sort a list build out of your own datatypes you will need to provide your own ICompare derived comparison class. In the following example we we create struct contained a basic personal record  with name, familyname and age. We provide two comparers, one that can sort the list by FamilyName and a second one that sorts the people in the list by their age.</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;

namespace IComparer
{

    struct Person
    {
        public string FamilyName;
        public string Name;
        public int    Age;
        public Person(string iFamilyName, string iName, int iAge)
        {
            FamilyName = iFamilyName; Name = iName; Age = iAge;
        }
    }

    class PersonComparerByName : IComparer&lt;Person&gt;
    {
        public int Compare(Person x, Person y)
        {
            return String.Compare(x.FamilyName,y.FamilyName);
        }
    }

    class PersonComparerByAge : IComparer&lt;Person&gt;
    {
        public int Compare(Person x, Person y)
        {
            return x.Age - y.Age;
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {

            List&lt;Person&gt; myList = new List&lt;Person&gt;();

            myList.Add( new Person(&quot;Mulder&quot;,&quot;Jan&quot;,22) );
            myList.Add( new Person(&quot;Dijkstra&quot;,&quot;Hans&quot;,45) );
            myList.Add( new Person(&quot;Zomer&quot;,&quot;Nara&quot;,25) );
            myList.Add( new Person(&quot;Italy&quot;,&quot;Jaro&quot;,38) );
            myList.Add( new Person(&quot;Robert&quot;,&quot;Nico&quot;,15) );

            // Sort the people in the list by their last name
            PersonComparerByName myComparerName = new PersonComparerByName();
            myList.Sort(myComparerName);

            int cnt1 = 0;
            foreach(Person aPerson in myList)
                Console.WriteLine(&quot;{0} = {1}&quot;,cnt1++,aPerson.FamilyName);

            // Sort the people in the list by their age
            PersonComparerByAge myComparerAge = new PersonComparerByAge();
            myList.Sort(myComparerAge);

            int cnt2 = 0;
            foreach(Person aPerson in myList)
                Console.WriteLine(&quot;{0} = {1} {2}&quot;,cnt2++,aPerson.FamilyName,aPerson.Age);

        }
    }
}
</pre>
<p>When run, the above code will output:</p>
<pre class="brush: c#">
0 = Dijkstra
1 = Italy
2 = Mulder
3 = Robert
4 = Zomer

0 = Robert 15
1 = Mulder 22
2 = Zomer 25
3 = Italy 38
4 = Dijkstra 45
</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/sorting-generic-lists/feed/</wfw:commentRss>
		<slash:comments>0</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>Implementing a Generic Binary Tree in C#</title>
		<link>http://www.dijksterhuis.org/implementing-a-generic-binary-tree-in-c/</link>
		<comments>http://www.dijksterhuis.org/implementing-a-generic-binary-tree-in-c/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 04:41:05 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=350</guid>
		<description><![CDATA[This post looks at how to implement a binary tree using generics in C#. A binary tree is a data structure in which each node has at most two children. They are a good way to store unsorted data, as the data becomes sorted as you insert it into the tree. 
Another benefit of storing [...]<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>This post looks at how to implement a binary tree using generics in C#. A binary tree is a data structure in which each node has at most two children. They are a good way to store unsorted data, as the data becomes sorted as you insert it into the tree. </p>
<p>Another benefit of storing information in a tree structure is the opportunity for faster search times. In an array (or list) you need to traverse the whole array to discover if it contains a particular value. A well-balanced binary tree can drastically reduce the number of look-ups required. </em></p>
<p><span id="more-350"></span></p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/12/binarytree_example.gif" alt="" title="Binary Tree Example" width="500" height="280" class="alignnone size-full wp-image-351" /></p>
<p>Given the left set of numbers, the tree on the right is created. If a value is smaller than the root, it goes left, if a value is larger it goes right. If both the left and right nodes have been assigned already, we need to travel further down the tree and create new entries there.</p>
<p>In the tree above the longest route from the root of the tree (5) is to discover that it contains (6) which in this example takes just 4 steps. All other values can be found in 1-3 steps.</p>
<p><strong>Balancing the tree</strong></p>
<p>Several algorithms exist for balancing trees &#8212; but in this post we keep things simple: our tree does not balance itself as new values are inserted.</p>
<p>By re-balancing it is possible to ensure that the maximum depth of the tree stays constant. If we were to insert data in-order into the tree, the tree itself would become lopsided and that would reduce its use in searching. The greater the trees depth (maximum number of steps from the root) the longer a potential search would take, and in the most unfortunate instance it would be the same as for a linked list or array.</p>
<p>So to maximize this trees potential we would need our data insertion to be as random as possible.</p>
<p><strong>The Tree Node Structure</strong></p>
<p>Each node in our tree can be described by a very simple class:</p>
<pre class="brush: c#">
       class BinaryTreeNode
        {
            public BinaryTreeNode Left;
            public BinaryTreeNode Right;
            public BinaryTreeNode Parent;
            public T Data;

            public BinaryTreeNode()
            {
                Left = null;
                Right = null;
                Parent = null;
            }
        }
</pre>
<p>We use a class, and not a struct as C# passes classes by reference, and structs by value. Passing by reference is the same as using pointers in C/C++. It allows us to dynamically add new entries &#8212; or remove them &#8212;  and to traverse the tree.</p>
<p>Each node has the potential to link to another Left and Right node and it stores one Data unit.</p>
<p>Because we will be traveling through the tree non-recursively we also need to keep a link to the Parent node. This allows us to travel back up the tree if we have reached a dead end in our search.</p>
<p><strong>Using Generics in a Binary Tree</strong></p>
<p>To allow us to store any kind of data &#8212; not just integers, the actual Binary Tree class is implemented using Generics. You are free to define your own datastructure and store it in the tree.</p>
<blockquote><p>class BinaryTree&lt;T&gt;</p></blockquote>
<p>But how to sort our data? Because T can be anything, the compiler does not know how to compare two instances of T to each other. For our tree algorithm we need to know if:</p>
<blockquote><p>T1 < T2<br />
T1 == T2<br />
T1 > T2
</p></blockquote>
<p>Generic sorting routines have the same problem, and the System class of C# provides a delegate function that we will use in our tree:</p>
<pre class="brush: c#">
public delegate int Comparison&lt;T&gt;(T x,T y)
</pre>
<p>A sample implementation for comparing integers is provided in the class:</p>
<pre class="brush: c#">
        /// &lt;summary&gt;
        /// For integer comparisons we provide a demonstration function.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;left&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;right&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&amp;lt;0 for left smaller than right, &amp;gt;0 if they are equal, +1 if right is larger than left&lt;/returns&gt;

        public static int CompareFunction_Int(int left, int right)
        {
            return left - right;
        }
</pre>
<p>This function is passed to the class constructor on creation:</p>
<pre class="brush: c#">
         BinaryTree&lt;int&gt; Test = new BinaryTree&lt;int&gt;(BinaryTree&lt;int&gt;.CompareFunction_Int);
</pre>
<p>If you use your own data type you will have to provide your own comparison function.</p>
<p><strong>Insert Algorithm</strong></p>
<p>Most of the work of building the tree is done in the insert algorithm.</p>
<p>The flowchart is a little long to insert in a blog post, but if you are interested you can <a href="http://www.dijksterhuis.org/wp-content/uploads/2008/12/flowchart_add.gif">find it here</a>.</p>
<p><strong>Custom Iterator</strong></p>
<p>To retrieve all the values from the binary tree the BinaryTree class provides a custom iterator. The iterator it returns performs an ordered walk through the binary tree returning each data entry stored in order of increasing value.</p>
<pre class="brush: c#">
            BinaryTree&lt;int&gt; Test = new BinaryTree&lt;int&gt;(BinaryTree&lt;int&gt;.CompareFunction_Int);

             /*...*/

            // Iterate over all members in the tree -- values are returned in sorted order
            foreach(int value in Test)
            {
                Console.WriteLine(&quot;Value: {0}&quot;, value);
            }
</pre>
<p>The code for the BinaryTree class is listed below, a small set of test routines is given in the TreeTest class.</p>
<pre class="brush: c#">
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Developer.Collections
{

    /// &lt;summary&gt;
    /// The BinaryTree class implements a simple non-balanced sorted Binary Tree in C#
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;The tree can contain any type, but you are required to provide your own comparison function.&lt;/typeparam&gt;

    class BinaryTree&lt;T&gt;
    {
        /// &lt;summary&gt;
        /// The tree is build up out of BinaryTreeNode instances
        /// &lt;/summary&gt;

        class BinaryTreeNode
        {
            public BinaryTreeNode Left;
            public BinaryTreeNode Right;
            public BinaryTreeNode Parent;
            public T Data;

            public BinaryTreeNode()
            {
                Left = null;
                Right = null;
                Parent = null;
            }
        }

        BinaryTreeNode Root;
        Comparison&lt;T&gt; CompareFunction;

        /// &lt;summary&gt;
        /// The BinaryTree constructor requires that we pass a comparison function. We need one as generics can only
        /// be compared as equals, but not for order. The solution is to allow the caller to pass a suitable comparison
        /// function. We use the C# Comparison delegate for this (found in System.Collections)
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;theCompareFunction&quot;&gt;Pass a delegate function of the type Comparison to the function&lt;/param&gt;

        public BinaryTree(Comparison&lt;T&gt; theCompareFunction)
        {
            Root = null;
            CompareFunction = theCompareFunction;
        }

        /// &lt;summary&gt;
        /// For integer comparisons we provide a demonstration function.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;left&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;right&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&amp;lt;0 for left smaller than right, &amp;gt;0 if they are equal, +1 if right is larger than left&lt;/returns&gt;

        public static int CompareFunction_Int(int left, int right)
        {
            return left - right;
        }

        /// &lt;summary&gt;
        /// For string comparisons we provide a demonstration function
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;left&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;right&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;-1 for left smaller than right, 0 if they are equal, +1 if right is larger than left&lt;/returns&gt;

        public static int CompareFunction_String(string left, string right)
        {
            return left.CompareTo(right);
        }

        /// &lt;summary&gt;
        /// The add function uses non-recursive tree traversal to find the next available insertion point
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Value&quot;&gt;The value to insert into tree.&lt;/param&gt;

        public void Add(T Value)
        {
            BinaryTreeNode child = new BinaryTreeNode();
            child.Data = Value;

            // Is the tree empty? Make the root the new child
            if (Root == null)
            {
                Root = child;
            }
            else
            {
                // Start from the root of the tree
                BinaryTreeNode Iterator = Root;
                while (true)
                {
                    // Compare the value to insert with the value in the current tree node
                    int Compare = CompareFunction(Value, Iterator.Data);
                    // The value is smaller or equal to the current node, we need to store it on the left side
                    // We test for equivalence as we allow duplicates (!)
                    if (Compare &lt;= 0)
                        if (Iterator.Left != null)
                        {
                            // Travel further left
                            Iterator = Iterator.Left;
                            continue;
                        }
                        else
                        {
                            // An empty left leg, add the new node on the left leg
                            Iterator.Left = child;
                            child.Parent = Iterator;
                            break;
                        }
                    if (Compare &gt; 0)
                        if (Iterator.Right != null)
                        {
                            // Continue to travel right
                            Iterator = Iterator.Right;
                            continue;
                        }
                        else
                        {
                            // Add the child to the right leg
                            Iterator.Right = child;
                            child.Parent = Iterator;
                            break;
                        }
                }

            }

        }

        /// &lt;summary&gt;
        /// This routine walks through the tree to see if the value given can be found.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Value&quot;&gt;The value to look for in the tree&lt;/param&gt;
        /// &lt;returns&gt;True if found, False if not found&lt;/returns&gt;

        public bool Find(T Value)
        {
            BinaryTreeNode Iterator = Root;
            while (Iterator != null)
            {
                int Compare = CompareFunction(Value, Iterator.Data);
                // Did we find the value ?
                if (Compare == 0) return true;
                if (Compare &lt; 0)
                {
                    // Travel left
                    Iterator = Iterator.Left;
                    continue;
                }
                // Travel right
                Iterator = Iterator.Right;
            }
            return false;
        }

        /// &lt;summary&gt;
        /// Given a starting node, this routine will locate the left most node in the sub-tree
        /// If no further nodes are found, it returns the starting node
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;start&quot;&gt;The sub-tree starting point&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;

        BinaryTreeNode FindMostLeft(BinaryTreeNode start)
        {
            BinaryTreeNode node = start;
            while (true)
            {
                if (node.Left != null)
                {
                    node = node.Left;
                    continue;
                }
                break;
            }
            return node;
        }

        /// &lt;summary&gt;
        /// Returns a list iterator of the elements in the tree implementing the IENumerator interface.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;IENumerator&lt;/returns&gt;

        public IEnumerator&lt;T&gt; GetEnumerator()
        {
            return new BinaryTreeEnumerator(this);
        }

        /// &lt;summary&gt;
        /// The BinaryTreeEnumerator implements the IEnumerator allowing foreach enumeration of the tree
        /// &lt;/summary&gt;

        class BinaryTreeEnumerator : IEnumerator&lt;T&gt;
        {
            BinaryTreeNode current;
            BinaryTree&lt;T&gt; theTree;

            public BinaryTreeEnumerator(BinaryTree&lt;T&gt; tree)
            {
                theTree = tree;
                current = null;
            }

            /// &lt;summary&gt;
            /// The MoveNext function traverses the tree in sorted order.
            /// &lt;/summary&gt;
            /// &lt;returns&gt;True if we found a valid entry, False if we have reached the end&lt;/returns&gt;
            public bool MoveNext()
            {
                // For the first entry, find the lowest valued node in the tree
                if (current == null)
                    current = theTree.FindMostLeft(theTree.Root);
                else
                {
                    // Can we go right-left?
                    if (current.Right != null)
                        current = theTree.FindMostLeft(current.Right);
                    else
                    {
                        // Note the value we have found
                        T CurrentValue = current.Data;

                        // Go up the tree until we find a value larger than the largest we have
                        // already found (or if we reach the root of the tree)
                        while (current != null)
                        {
                            current = current.Parent;
                            if (current != null)
                            {
                                int Compare = theTree.CompareFunction(current.Data,CurrentValue);
                                if (Compare &lt; 0) continue;
                            }
                            break;
                        }

                    }
                }
                return (current != null);
            }

            public T Current
            {
                get
                {
                    if (current == null)
                        throw new InvalidOperationException();
                    return current.Data;
                }
            }

            object IEnumerator.Current
            {
                get
                {
                    if (current == null)
                        throw new InvalidOperationException();
                    return current.Data;
                }
            }

            public void Dispose() { }
            public void Reset() { current = null; }
        }

    }

    class TreeTest
    {
        static void Main(string[] args)
        {
            BinaryTree&lt;int&gt; Test = new BinaryTree&lt;int&gt;(BinaryTree&lt;int&gt;.CompareFunction_Int);

            // Build the tree
            Test.Add(5);
            Test.Add(2);
            Test.Add(1);
            Test.Add(3);
            Test.Add(3); // Duplicates are OK
            Test.Add(4);
            Test.Add(6);
            Test.Add(10);
            Test.Add(7);
            Test.Add(8);
            Test.Add(9);

            // Test if we can find values in the tree
            for (int Lp = 1; Lp &lt;= 10; Lp++)
                Console.WriteLine(&quot;Find ({0}) = {1}&quot;, Lp,Test.Find(Lp));

            // Test if we can find a non-existing value
            Console.WriteLine(&quot;Find (999) = {0}&quot;, Test.Find(999));

            // Iterate over all members in the tree -- values are returned in sorted order
            foreach(int value in Test)
            {
                Console.WriteLine(&quot;Value: {0}&quot;, value);
            }

        }
    }

}
</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/implementing-a-generic-binary-tree-in-c/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>Querying System.Net.NetworkInformation in C#</title>
		<link>http://www.dijksterhuis.org/querying-systemnetnetworkinformation-in-c/</link>
		<comments>http://www.dijksterhuis.org/querying-systemnetnetworkinformation-in-c/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 07:24:09 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[network]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=329</guid>
		<description><![CDATA[.NET 2.0 added the NetworkInformation namespace which allow you to discover and query all the network interfaces in the local machine. The information this provides is very similar to what you can find by opening the &#8220;Network Connections&#8221; in Windows. In this post I have a look into the kinds information it provides &#8212; and [...]<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>.NET 2.0 added the NetworkInformation namespace which allow you to discover and query all the network interfaces in the local machine. The information this provides is very similar to what you can find by opening the &#8220;Network Connections&#8221; in Windows. In this post I have a look into the kinds information it provides &#8212; and what to look out for if your code has to run on Mono as well.</em></p>
<p><span id="more-329"></span></p>
<p>In <a href="http://www.dijksterhuis.org/finding-the-local-ip-addresses-in-c/">a previous post</a> we looked at how we could use <em>System.Net.NetworkInformation</em> to determine the machines local IP addresses, but there is much more stored in here. </p>
<p>The code below steps through each network interface on my machine: </p>
<blockquote><p>Interface information for mymachine.mydomain.com<br />
NetBIOS node type: Unknown<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
Name: Local Area Connection<br />
Description: ASUSTeK/Broadcom 440x 10/100 Integrated Controller &#8211; Packet Scheduler Miniport<br />
Network Interface Type: Ethernet<br />
Physical Address: 000EA99F2D04<br />
Adapter ID: {34F1A99A-3449-4290-8FFF-C1C62211696A}<br />
Receive only: False<br />
Status: Up<br />
Speed: 100000000<br />
Properties:<br />
|DNS Addresses: 255.255.255.255<br />
|DNS Suffic:<br />
|DNS Enabled: False<br />
|Dynamic DNS Enabled: True<br />
|DHPC Server Addresses: 255.255.255.255<br />
|UniCast Addresses: 10.0.0.6 192.168.1.6<br />
|AnyCast Addresses:<br />
|Supports multi-cast: True<br />
|Multicast Addresses: 224.0.0.1 239.255.255.250<br />
|Gateway Addresses: 10.0.0.253<br />
+IPV4 Properties:<br />
 |Interface Index: 2<br />
 |Automatic Private Addressing Active: False<br />
 |Automatic Private Addressing Enabled: True<br />
 |DHCP Enabled: False<br />
 |Forwarding Enabled: False<br />
 |MTU Size: 1500<br />
 \Uses Wins: False<br />
+IPV6 is not implemented
</p></blockquote>
<p>For brevity I have omitted the local loopback adaptor.</p>
<p>The Mono implementation of <em>System.Net.NetworkInformation</em> is spotty at best. This has much to do with the fact that on Linux much information isn&#8217;t easily stored in one central location. As can be seen from the comments in the Mono 2.01 source code:</p>
<pre class="brush: c#">
               [MonoTODO (&quot;Always returns an empty collection.&quot;)]
                public override IPAddressCollection DhcpServerAddresses {
                        get {
                                // There are lots of different DHCP clients
                                // that all store their configuration differently.
                                // I&#039;m not sure what to do here.
                                return new IPAddressCollection ();
                        }
                }

                [MonoTODO (&quot;Always returns an empty collection.&quot;)]
                public override IPAddressCollection DnsAddresses {
                        get {
                                // XXX: Parse /etc/resolv.conf, I suppose.
                                return new IPAddressCollection ();
                        }
                }
</pre>
<p>The following code runs under both .NET &#038; Mono and gives you a quick overview of the kinds of adapter information provided by <em>System.Net.NetworkInformation</em>. It is also possible to query each adapter for usage statistics &#8212; if you would like to know how many bytes it has send, but we won&#8217;t go there.</p>
<pre class="brush: c#">
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Text;

namespace Examples.System.Net.NetworkInformation.IfConfig
{
    public class IfConfig
    {
        public static bool DetectMono()
        {
            int p = (int)Environment.OSVersion.Platform;
            return (p == 4) || (p == 128);
        }

        public static void Main(string[] args)
        {
            // Mono&#039;s implementation of NetworkInformation is spotty, many values just return hard coded defaults
            // or throw an NotImplementedExceptions
            bool IsMono = DetectMono();

            // Global IP settings
            IPGlobalProperties global_properties = IPGlobalProperties.GetIPGlobalProperties();
            Console.WriteLine(&quot;Interface information for {0}.{1}&quot;, global_properties.HostName, global_properties.DomainName);
            Console.WriteLine(&quot;NetBIOS node type: {0}&quot;, global_properties.NodeType);

            //Gateway IP
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                Console.WriteLine(&quot;------------------------------------------------------&quot;);
                Console.WriteLine(&quot;Name: {0}&quot;, adapter.Name);
                Console.WriteLine(&quot;Description: {0}&quot;, adapter.Description);
                Console.WriteLine(&quot;Network Interface Type: {0}&quot;, adapter.NetworkInterfaceType);
                Console.WriteLine(&quot;Physical Address: {0}&quot;, adapter.GetPhysicalAddress());
                Console.WriteLine(&quot;Adapter ID: {0}&quot;, adapter.Id);
                Console.WriteLine(&quot;Receive only: {0}&quot;, adapter.IsReceiveOnly);
                Console.WriteLine(&quot;Status: {0}&quot;, adapter.OperationalStatus);

                if (!IsMono) Console.WriteLine(&quot;Speed: {0}&quot;, adapter.Speed); // 100 Mb is really a lot of zeros

                IPInterfaceProperties properties = adapter.GetIPProperties();
                Console.WriteLine(&quot;Properties: &quot;);

                Console.Write(&quot;|DNS Addresses: &quot;);
                foreach (IPAddress DnsServer in properties.DhcpServerAddresses)
                    Console.Write(&quot;{0} &quot;, DnsServer);
                Console.WriteLine();

                Console.WriteLine(&quot;|DNS Suffic: {0}&quot;, properties.DnsSuffix);

                Console.WriteLine(&quot;|DNS Enabled: {0}&quot;, properties.IsDnsEnabled);
                Console.WriteLine(&quot;|Dynamic DNS Enabled: {0}&quot;, properties.IsDynamicDnsEnabled);

                Console.Write(&quot;|DHPC Server Addresses: &quot;);
                foreach (IPAddress DhcpServer in properties.DhcpServerAddresses)
                    Console.Write(&quot;{0} &quot;, DhcpServer);
                Console.WriteLine();

                Console.Write(&quot;|UniCast Addresses: &quot;);
                foreach (IPAddressInformation uniCast in properties.UnicastAddresses)
                    Console.Write(&quot;{0} &quot;, uniCast.Address);
                Console.WriteLine();

                Console.Write(&quot;|AnyCast Addresses: &quot;);
                foreach (IPAddressInformation anyCast in properties.AnycastAddresses)
                    Console.Write(&quot;{0} &quot;, anyCast.Address);
                Console.WriteLine();

                Console.WriteLine(&quot;|Supports multi-cast: {0}&quot;, adapter.SupportsMulticast);
                Console.Write(&quot;|Multicast Addresses: &quot;);
                foreach (IPAddressInformation multiCast in properties.MulticastAddresses)
                    Console.Write(&quot;{0} &quot;, multiCast.Address);
                Console.WriteLine();

                Console.Write(&quot;|Gateway Addresses: &quot;);
                foreach (GatewayIPAddressInformation GateWay in properties.GatewayAddresses)
                    Console.Write(&quot;{0} &quot;, GateWay.Address);
                Console.WriteLine();

                if (adapter.Supports(NetworkInterfaceComponent.IPv4) == true)
                {
                    IPv4InterfaceProperties IPV4Props = properties.GetIPv4Properties();
                    // Loopback device does not have any property information associated
                    Console.WriteLine(&quot;+IPV4 Properties: &quot;);
                    if (IPV4Props != null)
                    {
                        Console.WriteLine(&quot; |Interface Index: {0}&quot;, IPV4Props.Index);
                        Console.WriteLine(&quot; |Automatic Private Addressing Active: {0}&quot;, IPV4Props.IsAutomaticPrivateAddressingActive);
                        Console.WriteLine(&quot; |Automatic Private Addressing Enabled: {0}&quot;, IPV4Props.IsAutomaticPrivateAddressingEnabled);
                        Console.WriteLine(&quot; |DHCP Enabled: {0}&quot;, IPV4Props.IsDhcpEnabled);
                        Console.WriteLine(&quot; |Forwarding Enabled: {0}&quot;, IPV4Props.IsForwardingEnabled);
                        Console.WriteLine(&quot; |MTU Size: {0}&quot;, IPV4Props.Mtu);
                        Console.WriteLine(&quot; \\Uses Wins: {0}&quot;, IPV4Props.UsesWins);
                    }
                    else
                    {
                        Console.WriteLine(&quot; |Device has no IPv4 properties&quot;);
                    }
                }
                else
                {
                    Console.WriteLine(&quot;+IPV4 is not implemented&quot;);
                }

                if (!IsMono &amp;&amp; adapter.Supports(NetworkInterfaceComponent.IPv6) == true)
                {
                    IPv6InterfaceProperties IPV6Props = properties.GetIPv6Properties();
                    Console.WriteLine(&quot;+IPV6 Properties: &quot;);
                    if (IPV6Props != null)
                    {
                        Console.WriteLine(&quot;+IPV6 Properties: &quot;);
                        Console.WriteLine(&quot; |Interface Index: {0}&quot;, IPV6Props.Index);
                        Console.WriteLine(&quot; \\MTU Size: {0}&quot;, IPV6Props.Mtu);
                    }
                    else
                    {
                        Console.WriteLine(&quot; |Device has no IPv6 properties&quot;);
                    }
                }
                else
                {
                    Console.WriteLine(&quot;+IPV6 is not implemented&quot;);
                }

            }

        }
    }
}
</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/querying-systemnetnetworkinformation-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finding all local IP Addresses in C#</title>
		<link>http://www.dijksterhuis.org/finding-the-local-ip-addresses-in-c/</link>
		<comments>http://www.dijksterhuis.org/finding-the-local-ip-addresses-in-c/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 06:53:29 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[local ip]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=321</guid>
		<description><![CDATA[A common problem is the find out the IP address of the machine your C# program is running on. C# provides two methods for obtaining the information. The first one is easy; but somewhat undocumented. The other one is just a little harder. If your code has to run on Mono then the second option [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>A common problem is the find out the IP address of the machine your C# program is running on. C# provides two methods for obtaining the information. The first one is easy; but somewhat undocumented. The other one is just a little harder. If your code has to run on Mono then the second option is your only alternative.</p>
<p><span id="more-321"></span></p>
<p>C# originally provided basic system information through the <em>System.Net.DNS</em> class. By querying the DNS &#8220;GetHostEntry&#8221; we could also discover the local IP addresses. The problem is that under Mono this only returns the local loop-back connector making this not a portable solution. </p>
<p>In .NET 2.0 the <em>System.Net.NetworkInformation</em> class was added, which allows you to browse all the network adapters and query their configuration in much greater detail. </p>
<p>The code below shows both methods for querying the local configuration: </p>
<pre class="brush: c#">
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Net.Sockets;

namespace IPLookup
{
    class MainClass
    {
        public static IPAddress[] GetAllUnicastAddresses_Old()
        {
            // By passing an empty string to GetHostEntry we receive all the IP addresses on the local machine
            // This breaks on Mono
            IPHostEntry LocalEntry = Dns.GetHostEntry(&quot;&quot;);
            return LocalEntry.AddressList;
        }

        public static IPAddress[] GetAllUnicastAddresses_New()
        {
            // This works on both Mono and .NET , but there is a difference: it also
            // includes the LocalLoopBack so we need to filter that one out
            List&lt;IPAddress&gt; Addresses = new List&lt;IPAddress&gt;();
            // Obtain a reference to all network interfaces in the machine
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();
                foreach (IPAddressInformation uniCast in properties.UnicastAddresses)
                {
                    // Ignore loop-back addresses &amp; IPv6
                    if (!IPAddress.IsLoopback(uniCast.Address) &amp;&amp; uniCast.Address.AddressFamily!= AddressFamily.InterNetworkV6)
                      Addresses.Add(uniCast.Address);
                }

            }
            return Addresses.ToArray();
        }

        public static void Main(string[] args)
        {
            IPAddress[] Adresses = GetAllUnicastAddresses_Old();
            foreach (IPAddress Adres in Adresses)
            {
                Console.WriteLine(&quot;OLD IP Address: {0}&quot;, Adres);
            }

            IPAddress[] Adresses2 = GetAllUnicastAddresses_New();
            foreach (IPAddress Adres in Adresses2)
            {
                Console.WriteLine(&quot;NEW IP Address: {0}&quot;, Adres);
            }
        }

    }
}
</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/finding-the-local-ip-addresses-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Building a simple portscanner in C#</title>
		<link>http://www.dijksterhuis.org/building-a-simple-portscanner-in-c/</link>
		<comments>http://www.dijksterhuis.org/building-a-simple-portscanner-in-c/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 08:29:33 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[portscanner]]></category>
		<category><![CDATA[tcpclient]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=284</guid>
		<description><![CDATA[
In the dark ages before the Internet there was &#8220;war-dialing&#8221;: randomly calling telephone numbers in the hope that on the other side a computer modem would pick up. War Dialing was glamorized by the movie &#8220;Wargames&#8221; but portscanning is just like that: you too can help the world  narrowly avoid nuclear Armageddon. This article [...]<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/dialer.jpg" alt="" title="Building a Portscanner in C#" width="500" height="295" class="alignnone size-full wp-image-288" /></p>
<p><em>In the dark ages before the Internet there was &#8220;war-dialing&#8221;: randomly calling telephone numbers in the hope that on the other side a computer modem would pick up. War Dialing was glamorized by the movie &#8220;Wargames&#8221; but portscanning is just like that: you too can help the world  narrowly avoid nuclear Armageddon. This article shows how you can build a simple Portscanner in C#. </em></p>
<p><span id="more-284"></span></p>
<p>And with simple we mean simple, this is no <a rel="nofollow" href="http://nmap.org/">NMAP</a>. But given an IP address or domain name address it will slowly scan each available port of the target computer to see if its open. </p>
<pre class="brush: c#">
Port scanning www.hinet.net (203.66.88.89)
Scanning port 0 : closed
Scanning port 1 : closed
Scanning port 2 : closed
Scanning port 3 : closed
....
Scanning port 7 :
</pre>
<p>Scanning is done by connect scanning the target computer. The program tries to build a connection to the IP address / port of the target. If it succeeds the port is open. </p>
<p>There is a gotcha here : The .NET implementation of TCPClient.Close() function does not actually close the connection properly. So we need to do the additional steps of obtaining the stream representing the connection and closing this as well before calling TCPClient.Close.</p>
<p>When starting the program you need to pass a domain name or IP address on the command line. We use a little regular expression magic in the <em>IsIpAddress()</em> method to determine if we were passed a valid IP address. </p>
<p>If a domain name was passed the <em>LookupDNSName()</em> method uses DNS to locate the matching IP address. Since more than one IP address can be represent a single domain name, the first one returned is selected. </p>
<p>The actual scanning is done by <em>ScanPort()</em>, a successful connection makes it return true.</p>
<pre class="brush: c#">
using System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace PortScanner
{
    class Program
    {

        // IsIpAddress
        //
        // The following routine returns true if a given string is a valid IP address 

        static bool IsIpAddress(string Address)
        {
            // The following pattern matches an IP address
            Regex IpMatch = new Regex(@&quot;\b(?:\d{1,3}\.){3}\d{1,3}\b&quot;);
            return IpMatch.IsMatch(Address);
        }

        // LookupDNSName
        //
        // 

        static bool LookupDNSName(string ScanAddress, out IPAddress ScanIPAddress)
        {
            ScanIPAddress = null;
            IPHostEntry NameToIpAddress;

            try
            {
                // Lookup the address we are going to scan
                NameToIpAddress = Dns.GetHostEntry(ScanAddress);
            }
            catch(SocketException)
            {
                // Thrown when we are unable to lookup the name
                return false;
            }

            // Pick the first address in the list , there should be at least 1
            if (NameToIpAddress.AddressList.Length &gt; 0)
            {
                ScanIPAddress = NameToIpAddress.AddressList[0];
                return true;
            }

            return false;
        }

        static bool ScanPort(IPAddress Address, int Port)
        {
            TcpClient Client = new TcpClient();
            try
            {
                // Attempt to connect to the given address + port
                Client.Connect(Address, Port);

                // This may seem like an avoidable step -- but TcpClient.Close does not
                // actually close the underlying connection
                // http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B821625

                NetworkStream ClientStream = Client.GetStream();
                ClientStream.Close();

                // Free the TCPClient resource
                Client.Close();
            }
            catch(SocketException)
            {
                // Assume that a socket exception means the connection failed
                // Client.Connect returns a void (so provides no insights into
                // what it was doing)
                return false;
            }
            return true;
        }

        static void Main(string[] args)
        {
            String ScanAddress;
            IPAddress ScanIPAddress;

            try
            {
                // Try to read the scan address from the command line, or default to localhost
                if (args.Length != 0)
                    ScanAddress = args[0];
                else
                    ScanAddress = &quot;127.0.0.1&quot;;

                // Both a hostname or an IP address are fine
                if (IsIpAddress(ScanAddress))
                {
                    ScanIPAddress = IPAddress.Parse(ScanAddress);
                }
                else
                if (!LookupDNSName(ScanAddress,out ScanIPAddress))
                {
                    Console.WriteLine(&quot;Error looking up {0}&quot;,ScanAddress);
                    return;
                }

                // Report what we are going to do
                Console.WriteLine(&quot;Port scanning {0} ({1})&quot;, ScanAddress, ScanIPAddress.ToString());

                // Scan all the possible posts
                for (int Port = IPEndPoint.MinPort; Port &lt; IPEndPoint.MaxPort; Port++)
                {
                    Console.Write(&quot;Scanning port {0} : &quot;, Port);
                    if (ScanPort(ScanIPAddress, Port))
                        Console.WriteLine(&quot;OPEN&quot;);
                    else
                        Console.WriteLine(&quot;closed&quot;);
                }

                // Close Up
                Console.WriteLine(&quot;Finished scanning all ports&quot;);

            }
            catch (Exception e)
            {
                Console.WriteLine(&quot;Exception caught!&quot;);
                Console.WriteLine(&quot;Source : &quot; + e.Source);
                Console.WriteLine(&quot;Message : &quot; + e.Message);
            }
        }
    }
}
</pre>
<p>As there are some 2^16 addresses (IPEndPoint.MinPort = 0 / IPEndPoint.MaxPort = 65536) this program will take its quite a bit of time to scan a whole machine. Also, if a port is closed (or hidden by a firewall) the <em>TCPClient</em> will need to wait for a timeout before being able to report this.  </p>
<p>One possible solution to this would be to scan multiple ports simultaneously with a set of ThreadPool workers as most of the time the main thread is waiting for the TCP stack. </p>
<p><small>Image credit: <a href="http://www.flickr.com/photos/makelessnoise/" rel="nofollow">makelessnoise</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/building-a-simple-portscanner-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
