<?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/category/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>Exploring C# Boxing</title>
		<link>http://www.dijksterhuis.org/exploring-boxing/</link>
		<comments>http://www.dijksterhuis.org/exploring-boxing/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 07:29:49 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Chapter]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[boxing]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=908</guid>
		<description><![CDATA[
Boxing in C# has little to do with Saturday night television but quite a bit more with that part-time job at the warehouse you had as a student. It is an important concept in C# that is related to how the compiler handles different kinds of variables in memory. Knowing how the compiler handles the [...]<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/03/boxes2.jpg" alt="C# Boxing Explained" title="C# Boxing Explained" width="570" height="246" class="alignleft size-full wp-image-934" /></p>
<p><em>Boxing in C# has little to do with Saturday night television but quite a bit more with that part-time job at the warehouse you had as a student. It is an important concept in C# that is related to how the compiler handles different kinds of variables in memory. Knowing how the compiler handles the various types allows you to avoid unexpected side effects in your code. </em></p>
<p>This article explains what boxing is, how it works and how it can negatively effect your code if you don&#8217;t pay attention to it. We also look at how generics can be used to improve your code&#8217;s efficiency. And we try to answer the ultimate question: Is everything in C# an object?</p>
<p><span id="more-908"></span></p>
<h3>Everything is an object in C# .. but not all objects are created equally</h3>
<p>In C#, everything inherits from System.Object, so they share all the common object methods :</p>
<blockquote><p>
string a = &#8220;hello world&#8221;;<br />
int     b = 34;<br />
Console.WriteLine( &#8220;{0} {1}&#8221;,a.ToString(),b.ToString());
</p></blockquote>
<p>At first glance all objects look the same in C#. But an important distinction is made between <em>value types</em> and <em>reference types</em>. Value types are basic types such as <em>struct</em>, <em>int</em>, <em>long</em>, <em>short</em> etc. Reference types are all the classes you will use (strings, delegates, objects)</p>
<ul>
<li>Value types (int,struct..) etc are located on the stack. (unless they are part of a reference type, such as a class)</li>
<li>Reference types (classes&#8230;) are accessed through a pointer to their actual location on the heap.</li>
</ul>
<p>We simplify things a little for this article: The stack keeps track of what is executing in our application. As we enter and exit methods items are added to or removed from the top. The heap stores all the applications data, and since data can be added to and removed from it randomly it needs to be garbage collected.</p>
<p>Why the difference ? The stack is faster to access for the runtime so by putting simple types close at hand the code gains in efficiency.</p>
<p><strong>Assigning variables</strong></p>
<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2009/03/boxing.png" alt="C# Boxing" title="C# Boxing" width="250" height="261" class="alignleft size-full wp-image-920" />The graphic shows four possible scenarios :</p>
<ol>
<li><strong>Boxing: </strong>When you assign an integer to an object (object b=a): a new managed memory block is created on the heap. For this C# has to allocate memory at runtime.</li>
<li><strong>By Value: </strong>If you copy the integer to another integer (int c=a) the value is simply copied to another memory slot on the stack (which is allocated at compile time), this is the fastest assignment as most checks can be done at compile time.</li>
<li><strong>Unboxing:</strong> When you cast an object to a value type (d=(int)b) the result is stored on the stack. This is also an expensive operation as at runtime the value has to be retrieved from the heap and is then checked to see if the cast was valid. (If the source argument is null or a reference to an incompatible object, an<strong> InvalidCastException</strong> is thrown.)</li>
<li><strong>By Reference: </strong>Classes are reference types so if you assign a new object to an older object (object e = b) no new instance is created, the object pointer on the stack simply points to the older object. A direct result of this is that if you modify either b or e, they will both reflect the change as they both point to the same location in memory.</li>
</ol>
<p>Boxing is as simply putting a basic type in wrapper (making it a fully blown object), and unboxing taking that wrapped object and converts it back to a simpler type. To do the boxing managed memory needs to be allocated on the heap, references need to be updated, and the contents of the value type have to be copied. </p>
<p><strong>Value types are copied, reference types just refer to the original object</strong></p>
<p>The following code example shows how a simple change in code can have very different results.</p>
<div>
<table border="1" cellspacing="0" cellpadding="3" width="100%">
<tbody>
<tr>
<td width="50%"><strong>Example A</strong></td>
<td width="50%"><strong>Example B</strong></td>
</tr>
<tr>
<td width="50%">
<pre class="brush: c#">
    class MainClass
    {
        struct Demo
        {
            public int x;
            public Demo(int x)
            {
                this.x = x;
            }
        }

        public static void Main(string[] args)
        {
            Demo p = new Demo(10);
            object box = p;
            p.x = 20;
            Console.Write(((Demo)box).x);
        }
    }
</pre>
</td>
<td width="50%">
<pre class="brush: c#">
   class MainClass
    {
        class Demo
        {
            public int x;
            public Demo(int x)
            {
                this.x = x;
            }
        }

        public static void Main(string[] args)
        {
            Demo p = new Demo(10);
            object reference = p;
            p.x = 20;
            Console.Write(((Demo)reference).x);
        }
    }
</pre>
</td>
</tr>
<tr>
<td width="50%">Result: 10</td>
<td width="50%">Result: 20</td>
</tr>
</tbody>
</table>
</div>
<p>In Example A, because Demo is a struct (and thus a value type on the stack) when we box it a copy is made. When we modify the original no change is made to the copy.</p>
<p>In Example B, we have created Demo as a class. In this situation we can assign it to another object and we don&#8217;t need to box it. A reference is made instead. So when we update the original, the copy is also updated as they both point to the same location in memory.</p>
<h3>Boxing and unboxing value types slows things down</h3>
<p>Often you can&#8217;t rely on what the type of variable a function will take so you need to use an object variable as object is the lowest common denominator in .NET. In the following example we use the <em>ArrayList</em> class to store a set of integers. The <em>ArrayList</em> can store any type of variable, but to be able to do this it accept the <em>object</em> class. </p>
<pre class="brush: c#">
        using System.Collections;

        public static void Main(string[] args)
        {
            int total = 0;
            ArrayList myList = new ArrayList();
            for (int Lp = 0; Lp &lt; 10000000; Lp++)
                myList.Add(Lp); // Box: Integer to an object
            foreach(object item in myList)
                total += (int)item; // Unbox: Object to integer
        }
</pre>
<p>When we add an integer to the Arraylist it is boxed into an object, and when we retrieve it it is unboxed back into an integer.</p>
<p>Note that this is only an issue if we are trying to store value types in the arraylist. If we were trying to store objects (eg. classes) there is no boxing done, as the original type was an object already. In this situation a simple reference is stored. On retrieval there is no unboxing necessary as only a reference is returned.</p>
<h3>Boxing in Action</h3>
<p>When we look at our code in a dissassembler the boxing operation is clearly visible in the output stream:</p>
<blockquote><p>
;<em> myList.Add(Lp); // Box: Integer to an object</em><br />
IL_000f:  ldloc.1<br />
IL_0010:  ldloc.2<br />
IL_0011:  box [mscorlib]System.Int32<br />
IL_0016:  callvirt instance int32 class [mscorlib]System.Collections.ArrayList::Add(object)
</p></blockquote>
<p>And when we convert the object back to an integer the reverse happens:</p>
<blockquote><p>
; total += (int)item; <strong>// Unbox: Object to integer</strong><br />
IL_0042:  unbox [mscorlib]System.Int32
</p></blockquote>
<h3>Generics remove the need to box and unbox value types</h3>
<p>In .NET 2.0 generics and generic collections were introduced that remove the need to box and unbox variables in many common situations. The following example is functionally equivalent to the earlier boxing example. We use a generic here, but force it to be &#8220;object&#8221;:</p>
<pre class="brush: c#">
        using System.Collections.Generic;
        public static void Main(string[] args)
        {
            int total = 0;
            List&lt;object&gt; myList = new List&lt;object&gt;();
            for (int Lp = 0; Lp &lt; 10000000; Lp++)
                myList.Add((object)Lp); // We need a boxing operation
            foreach(int item in myList)
                total += (int)item; // Unbox back to an int
        }
</pre>
<p>The above example of course makes little sense because we are inefficient on purpose. I included it to demonstrate how with generics we can get around the need for boxing with generic collections.</p>
<pre class="brush: c#">
        using System.Collections.Generic;
        public static void Main(string[] args)
        {
            int total = 0;
            List&lt;int&gt; myList = new List&lt;int&gt;();
            for (int Lp = 0; Lp &lt; 10000000; Lp++)
                myList.Add(Lp); // No need to box things
            foreach(int item in myList)
                total += item; // No need to unbox
        }
</pre>
<p>Generic are similar to templates in C++, they allow you to specify a type and the compiler will generate all the required code. In our example we specify that our list is of type int, so the compiler will create a List class that supports integers. There is no longer a need to convert our integer type to an object first.  If you would like to know more about how generics work have a look at another post I wrote on the subject: <a id="s6of" title="Generics in C#" href="../generics-in-c/">Generics in C#</a> .</p>
<h3>So how much of a difference does boxing make?</h3>
<p>Boxing is slower but how much is the difference and do you need to care? To put things into perspective I tested the timing on the three code examples above. For this I used .NET&#8217;s Stopwatch class to <a id="gx9k" title="measure our code's performance" href="../timing-function-performance-stopwatch-class/">measure the code&#8217;s performance</a>. First of all, the .NET runtime is pretty fast and I found that I needed to set the loop iterations at some 10 milion before I was able to get a consistent result across runs.</p>
<ul>
<li>Boxing/Unboxing ListArray example: 2580 ms</li>
<li>Boxing/Unboxing List&lt;object&gt; example: 2050ms</li>
<li>Non boxing List&lt;int&gt; example: 825 ms</li>
</ul>
<p>The non boxing List&lt;int&gt; example is about 2.5 times faster than List&lt;object&gt;, which is quite considerable.</p>
<h3>To finish up&#8230;</h3>
<p>Based on this should you rewrite all your code to implement generics? Probably not unless you have several tight loops that could use your attention, note that this only applies to value types (structs, ints) . For reference types (i.e. all classes) this is less of a problem as they are stored as a reference anyway. </p>
<p>It is however a good idea to implement generics in any code you write from here on. Not just because of the potential gains in speed but also because generics provide the compiler with much more information.</p>
<ul>
<li>Generics reduce the number of coding errors as you have compile-time checking of types</li>
<li>Generics are more readable, you don&#8217;t need to cast all over the place and it&#8217;s always obvious what type it is associated with</li>
</ul>
<p>Also if possible avoid passing value types as parameters to methods if these force a conversion to an object.</p>
<p>Image credit: Wall of boxed by <a rel="nofollow" href="http://www.flickr.com/photos/celesteh/">celesteh</a></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.dijksterhuis.org%2fexploring-boxing%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.dijksterhuis.org%2fexploring-boxing%2f" border="0" alt="kick it on DotNetKicks.com" /></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/exploring-boxing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>10 C# Shorthands that improve productivity</title>
		<link>http://www.dijksterhuis.org/10-c-coding-shorthands-that-improve-productivity/</link>
		<comments>http://www.dijksterhuis.org/10-c-coding-shorthands-that-improve-productivity/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 07:54:38 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=897</guid>
		<description><![CDATA[
One of the best things about C# is that as the language and libraries expand thought is put into keeping things readable. Below I have listed 10 shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already &#8212; but do you currently use all [...]<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/03/coding.jpg" alt="C# shortcuts and shorthand" title="C# shortcuts and shorthand" width="570" height="236" class="alignright size-full wp-image-905" /></p>
<p><I>One of the best things about C# is that as the language and libraries expand thought is put into keeping things readable. Below I have listed 10 shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already &#8212; but do you currently use all ten of them ?</I></p>
<p><span id="more-897"></span></p>
<p><strong>1. The ? conditional evaluation operator</strong></p>
<p>I first read about the ? operator in the &#8220;The C Programming Language&#8221; book by Brian Kernighan and Dennis Ritchie (first published in 1978, but I didn&#8217;t get around to reading it until well into the second edition). So this isn&#8217;t anything new. But it IS handy. It allows you to compress a common if-then-else pattern into a single assignment.</p>
<pre class="brush: c#">
int x = 10;
int y = 20;
int max;

if (x &gt; y)
  max = x;
else
  max = y;
</pre>
<p>Using the (Question) ? Positive Answer : Negative Answer patterns the above can be rewritten as:</p>
<pre class="brush: c#">
int x = 10;
int y = 20;
int max = (x &gt; y) ? x : y;
</pre>
<p><strong>2. Null-Coalesce operator (??)</strong></p>
<p>How often do you test for null values in your code? Often? Then the null-coalesce operator (??) comes in handy. To see how it works consider the following code example:</p>
<pre class="brush: c#">
object cache = null;
object d = new object();
object e;

if (c != null)
    e = c;
else
   e = d;
</pre>
<p>It is obvious that we can rewrite this using the single ? operator :</p>
<pre class="brush: c#">
object cache = null;
object d = new object();
object e = (c != null) ? c : d;
</pre>
<p>Using the ?? operator we can make it even shorter. If the left hand side is null, the right hand side is assigned.</p>
<pre class="brush: c#">
object cache = null;
object d = new object();
object e = c ?? d;
</pre>
<p><strong>3. Object Initializers</strong></p>
<p>After you create a new object you often have to assign one or more of its properties. With the introduction of C# 3.0 it is now possible to use object initializers to both improve the readability of this, and to shorten your code.</p>
<pre class="brush: c#">
Customer c = new Customer();
c.Name = &quot;James&quot;;

c.Address = &quot;204 Lime Street&quot;;
</pre>
<p>can be written as:</p>
<pre class="brush: c#">
Customer c = new Customer { Name=&quot;James&quot;, Address = &quot;204 Lime Street&quot; };
</pre>
<p><strong>4. The using statement</strong></p>
<p>Often you will need to allocate a system resource such as a font, file handle, network resource etc. Each time you need such a resource there are three critical steps to go through: You acquire the resource, you use it, and then you dispose of it. If you forget to properly dispose of it you will have created a memory or resource leak. This is best illustrated through the following patterns:</p>
<pre class="brush: c#">
     // 1. Allocation of the object
     Font font1 = new Font(&quot;Arial&quot;, 10.0f);
     try
     {
      // 2. The bit where we use the resource
     }
     finally
     {
     // 3. Disposal of the object
     if (font1 != null)
     ((IDisposable)font1).Dispose();
     }
</pre>
<p>The using statement allows us to compress this down to:</p>
<pre class="brush: c#">
// Allocate the resource
using (Font font1 = new Font(&quot;Arial&quot;, 10.0f))
{
    // The bit where we use the resource
}
// Disposal is automatic
</pre>
<p>The using statement is intended to be used with objects that implement the &#8220;IDisposable&#8221; interface which in practice is all .NET objects that allocate and manage resources.</p>
<p><strong>5. Aliases for long winded namespaces and types</strong></p>
<p>The names of C# identifiers can become quite long. If you are doing Microsoft Office automation in C# you might want to do something simple like open MS Word and change a document. You can use the &#8220;using&#8221; statement to create an alias for either a class or a namespace.</p>
<pre class="brush: c#">
using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }
</pre>
<p><strong>6. Nullable objects</strong></p>
<p>A variable needs to have a value, it cannot be null. Sometimes it would be handy it was possible to assign &#8220;null&#8221; (eg. undefined) to a variable. .NET 2.0 introduced the Nullable<T> generic that makes this possible. The following two lines produce exactly the same object:</p>
<pre class="brush: c#">
Nullable&lt;int&gt; x = null;
int? x = null;
</pre>
<p>By putting a ? following a variable definition the compiler will wrap a Nullable&lt;T&gt; generic around the type.</p>
<p><strong>7. Automatic Properties</strong></p>
<p>C# 3.0 introduced automatic properties. A property typically consists of (but doesn&#8217;t have to) a private variable which is exposed to the outside world through getters and setters. The following is common example of this:</p>
<pre class="brush: c#">
public class Person
{
 private string _firstName;
 public string FirstName
 {
    get { return _firstName; }
    set { _firstName = value; }
 }
}
</pre>
<p>From C# 3.0 on we can reduce the above to: </p>
<pre class="brush: c#">
public class Person
{
 public string Firstname { get; set; }
}
</pre>
<p>The C# compiler will automatically generate a backing variable and the correct get and set properties. Why is this useful? After all you could have just made a string variable in the class public instead. </p>
<p>By defining it as a property allows you to add the actual validation logic to your class at a later stage. The in-memory signature of the class won&#8217;t change which means that any external libraries compiled against your code will not have to be recompiled.</p>
<p><strong>8. Type inference</strong></p>
<p>In typical C# you will always carefully spell out your definitions:</p>
<pre class="brush: c#">
    string MyString = “Hello World”;
</pre>
<p>From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?</p>
<pre class="brush: c#">
    var MyString = “Hello World”;
</pre>
<p>The above definition will also create a string variable named “MyString”. It is important to note that C# is still strongly typed.There is no performance impact results from using type inference.</p>
<p>The compiler does all the work figuring out the data type at compile time. Of course this feature created two opposite camps, one that thinks var should be liberally applied, and another one that abhors the whole idea. The middle ground seems to be that var should be used there were its use is obvious.</p>
<pre class="brush: c#">
var SeniorStaff = Employees.Where(s =&gt; s.Age &gt; 35);
foreach(var Member in SeniorStaff)
           Console.WriteLine(&quot;Name: {0} Age: {1}&quot;,Member.Name,Member.Age);
</pre>
<p>For example what type would SeniorStaff be ?</p>
<blockquote><p>((System.Linq.Enumerable.Iterator<<>f__AnonymousType0<string,int>>)(SeniorStaff))</p></blockquote>
<p>This should make you glad that the compiler figured it all out for you. I wrote more about this in another post: <a href="http://www.dijksterhuis.org/csharp-anonymous-types-basics/">Anonymous Types : The Basics</a>.</p>
<p><strong>9. Lambda Expressions</strong></p>
<p>C# 2.0 introduced anonymous methods, which are methods defined inside a method. Incredibly powerful and a nice way to put all kinds of evaluation logic inside your code they had the drawback that they could be quite hard to read.</p>
<blockquote><p>
Func<int,bool> mySeniorStaffFilter = delegate(int a) { return a > 35; };
</p></blockquote>
<p>The above method takes an integer as a parameter, and returns a boolean. It checks if the staff member passed to it is older than 35. If so, it returns true. </p>
<p>Lamba expressions make things a little easier to read, while being functionally exactly the same:</p>
<blockquote><p>
    Func<int,bool> mySeniorStaffFilter = a => a > 35;
</p></blockquote>
<p>Even better, you can define them anywhere a delegate would have fitted:</p>
<blockquote><p>
    var SeniorStaff = Employees.Where(s => s.Age > 35);
</p></blockquote>
<p><strong>10. string.IsNullOrEmpty</strong></p>
<p>Not really a language feature, but a useful little library function in its own right. How often do you need to test if a string is empty? Or null? The string.IsNullOrEmpty method returns true if this is the case.</p>
<pre class="brush: c#">
if (String.IsNullOrEmpty(s) == true)
    return &quot;is null or empty&quot;;
else
     return String.Format(&quot;(\&quot;{0}\&quot;) is not null or empty&quot;, s);
</pre>
<h3>Optional and named parameters in C# 4.0</h3>
<p>As a bonus a little on the upcoming C# 4.0 which will introduce optional and named parameters. It is quite difficult to see what all the hoopla is about until you realize what optional parameters will do to improve Office automation coding in C#:</p>
<p>Before optional and named parameters:</p>
<pre class="brush: c#">
Word.Application app = new Word.Application() { Visible = true; }
object missing = System.Reflection.Missing.Value;
object filename = @&quot;c:\Document.docx&quot;;
object readOnlyValue = true;

app.Document.Open(ref filename, ref missing, ref readOnlyValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
</pre>
<p>With the support of optional and named parameters this becomes:</p>
<pre class="brush: c#">
Word.Application app = new Word.Application() { Visible = true; }
app.Documents.Open(@&quot;c:\Document.docx&quot;,ReadOnly:true);
</pre>
<p>Microsoft Office certainly uses a lot of optional parameters. Note that in the first example all parameters are passed by reference. They still are in the second example. Behind the scenes the C# compiler creates the appropriate temporary variables to pass on, saving us from having to hand add them to the code. </p>
<p>To give proper credit, the above example comes from a video on this subject by <a href="http://channel9.msdn.com/posts/mike+ormond/C-40-New-Features-COM-Interop-Enhancements/">Mike Ormond</a> on Channel 9.</p>
<p>Image credit: Thinking About Something by <a rel="nofollow" href="http://www.flickr.com/photos/goljadkin/"> Grazie Daverro</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/10-c-coding-shorthands-that-improve-productivity/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>C# Regular Expression Cheat Sheet</title>
		<link>http://www.dijksterhuis.org/csharp-regular-expression-operator-cheat-sheet/</link>
		<comments>http://www.dijksterhuis.org/csharp-regular-expression-operator-cheat-sheet/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 05:38:31 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[regex]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=769</guid>
		<description><![CDATA[I have been doing quite a bit with regular expressions recently and to avoid having to look them up again and again I made myself a little table with the most important C# regular expression operators and stuck it on the wall. This post contains the C# regular expression operators as used by the .NET [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>I have been doing quite a bit with regular expressions recently and to avoid having to look them up again and again I made myself a little table with the most important C# regular expression operators and stuck it on the wall. This post contains the C# regular expression operators as used by the .NET regular expression classes such as <em>RegEx</em>.</p>
<p>If you would like to print this, click here for a <a href='http://www.dijksterhuis.org/wp-content/uploads/2009/03/regular_expressions_in_.html'>pure HTML version</a>. </p>
<p><span id="more-769"></span></p>
<h3>Escape Characters</h3>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td width="20%"><b>Character</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td>ordinary characters</td>
<td>Characters other than . $ ^ { [ ( | ) * + ? \ match<br />
themselves.</td>
</tr>
<tr>
<td>. (dot)</td>
<td>Matches any character</td>
</tr>
<tr>
<td>\w</td>
<td>Matches any word character. </td>
</tr>
<tr>
<td>\W</td>
<td>The negation of \w</td>
</tr>
<tr>
<td>\s</td>
<td>Matches any white-space character.</td>
</tr>
<tr>
<td>\S</td>
<td>Matches any non-white-space character. </td>
</tr>
<tr>
<td>\d</td>
<td>Matches any decimal digit. </td>
</tr>
<tr>
<td>\D</td>
<td>Matches any non-decimal digit.</td>
</tr>
<tr>
<td><b>\a</b></td>
<td>Matches a bell (alarm) \u0007.</td>
</tr>
<tr>
<td><b>\b</b></td>
<td>Matches a backspace \u0008 if in a [] character class</td>
</tr>
<tr>
<td><b>\t</b></td>
<td>Matches a tab</td>
</tr>
<tr>
<td><b>\r</b></td>
<td>Carriage return</td>
</tr>
<tr>
<td><b>\v</b></td>
<td>Vertical tab</td>
</tr>
<tr>
<td><b>\f</b></td>
<td>Form feed</td>
</tr>
<tr>
<td><b>\n</b></td>
<td>New line</td>
</tr>
<tr>
<td><b>\e</b></td>
<td>Matches an escape</td>
</tr>
<tr>
<td><b>\040</b></td>
<td>Matches an ASCII character as octal (up to three digits);</td>
</tr>
<tr>
<td><b>\x20</b></td>
<td>Matches an ASCII character using hexadecimal representation<br />
(exactly two digits).</td>
</tr>
<tr>
<td><b>\cC</b></td>
<td>Matches an ASCII control character; for example, \cC is<br />
control-C.</td>
</tr>
<tr>
<td><b>\u0020</b></td>
<td>Matches a Unicode character using hexadecimal representation<br />
(exactly four digits).</td>
</tr>
<tr>
<td><b>\</b></td>
<td>When followed by a character that is not recognized as an<br />
escaped character, matches that character. For example, <b>\*</b><br />
is the same as <b>\x2A</b>.</td>
</tr>
</table>
<p></p>
<h3>Alternation</h3>
<table width="100%" cellpadding="0" cellspacing="0" border="1">
<tbody>
<tr>
<th width="20%"><b>Alternation</b></th>
<th><b>Definition</b></th>
</tr>
<tr>
<td><b>|</b></td>
<td>Matches any one of the terms separated by the | (vertical bar)<br />
character; for example, <span>cat|dog|tiger</span>. The leftmost<br />
successful match wins.</td>
</tr>
<tr>
<td><b>(?(</b><i>expression</i><b>)yes|no)</b></td>
<td>Matches the &#8220;yes&#8221; part if the expression matches at this point;<br />
otherwise, matches the &#8220;no&#8221; part.&nbsp;</td>
</tr>
<tr>
<td><b>(?(</b><i>name</i><b>)yes|no)</b></td>
<td>Matches the &#8220;yes&#8221; part if the named capture string has a match;<br />
otherwise, matches the &#8220;no&#8221; part.</td>
</tr>
</tbody>
</table>
<p></p>
<h3>Substitutions</h3>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td width="20%"><b>Character</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td><b>$</b><i>number</i></td>
<td>Substitutes the last substring matched by group number<br />
<i>number</i> (decimal).</td>
</tr>
<tr>
<td><b>${</b><i>name</i><b>}</b></td>
<td>Substitutes the last substring matched by a<br />
(?&lt;<i>name</i>&gt; ) group.</td>
</tr>
<tr>
<td><b>$$</b></td>
<td>Substitutes a single &#8220;$&#8221; literal.</td>
</tr>
<tr>
<td><b>$&amp;</b></td>
<td>Substitutes a copy of the entire match itself.</td>
</tr>
<tr>
<td><b>$`</b></td>
<td>Substitutes all the text of the input string before the<br />
match.</td>
</tr>
<tr>
<td><b>$&#8217;</b></td>
<td>Substitutes all the text of the input string after the<br />
match.</td>
</tr>
<tr>
<td><b>$+</b></td>
<td>Substitutes the last group captured.</td>
</tr>
<tr>
<td><b>$_</b></td>
<td>Substitutes the entire input string.</td>
</tr>
</table>
<p></p>
<h3>Word boundaries</h3>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td width="20%"><b>Assertion</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td><b>^</b></td>
<td>Specifies that the match must occur at the beginning of the<br />
string or the beginning of the line.</td>
</tr>
<tr>
<td><b>$</b></td>
<td>Specifies that the match must occur at the end of the string,<br />
before <b>\n</b> at the end of the string, or at the end of the<br />
line.</td>
</tr>
<tr>
<td><b>\A</b></td>
<td>Specifies that the match must occur at the beginning of the<br />
string (ignores the <b>Multiline</b> option).</td>
</tr>
<tr>
<td><b>\Z</b></td>
<td>Specifies that the match must occur at the end of the string or<br />
before <b>\n</b> at the end of the string (ignores the<br />
<b>Multiline</b> option).</td>
</tr>
<tr>
<td><b>\z</b></td>
<td>Specifies that the match must occur at the end of the string<br />
(ignores the <b>Multiline</b> option).</td>
</tr>
<tr>
<td><b>\G</b></td>
<td>Specifies that the match must occur at the point where the<br />
previous match ended. When used with Match.NextMatch(), this<br />
ensures that matches are all contiguous.</td>
</tr>
<tr>
<td><b>\b</b></td>
<td>Specifies that the match must occur on a boundary between<br />
<b>\w</b> (alphanumeric) and <b>\W</b> (nonalphanumeric)<br />
characters. The match must occur on word boundaries (that is, at<br />
the first or last characters in words separated by any<br />
nonalphanumeric characters). The match can also occur on a word<br />
boundary at the end of the string.</td>
</tr>
<tr>
<td><b>\B</b></td>
<td>Specifies that the match must not occur on a <b>\b</b><br />
boundary.</td>
</tr>
</tbody>
</table>
<p></p>
<h3>Quantifiers</h3>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td width="20%">*</td>
<td>Matches the preceding element zero or more times. It is<br />
equivalent to <b>{0,}</b>. <span>*</span> is a greedy quantifier<br />
whose non-greedy equivalent is <span class="input">*?</span>.</td>
</tr>
<tr>
<td>+</td>
<td>Matches the preceding element one or more times. It is<br />
equivalent to <span>{1,}</span>. <span class="input">+</span> is a<br />
greedy quantifier whose non-greedy equivalent is<br />
<span>+?</span>.</td>
</tr>
<tr>
<td>?</td>
<td>Matches the preceding element zero or one time. It is<br />
equivalent to <span>{0,1}</span>. <span class="input">?</span> is a<br />
greedy quantifier whose non-greedy equivalent is<br />
<span>??</span>.</td>
</tr>
<tr>
<td>{n}</td>
<td>Matches the preceding element exactly <i>n</i> times.<br />
<span>{n}</span> is a greedy quantifier whose non-greedy equivalent<br />
is <span>{n}?</span>.</td>
</tr>
<tr>
<td>{n,}</td>
<td>Matches the preceding element at least <i>n</i> times.<br />
<span>{n,}</span> is a greedy quantifier whose non-greedy<br />
equivalent is <span>{n}?</span>.</td>
</tr>
<tr>
<td>{<i>n</i>,<i>m</i>}</td>
<td>Matches the preceding element at least <i>n</i>, but no more<br />
than <i>m</i>, times. <span>{n,m}</span> is a greedy quantifier<br />
whose non-greedy equivalent is <span class=<br />
"input">{n,m}?</span>.</td>
</tr>
<tr>
<td>*?</td>
<td>Matches the preceding element zero or more times, but as few<br />
times as possible. It is a lazy quantifier that is the counterpart<br />
to the greedy quantifier <span>*</span>.</td>
</tr>
<tr>
<td>+?</td>
<td>Matches the preceding element one or more times, but as few<br />
times as possible. It is a lazy quantifier that is the counterpart<br />
to the greedy quantifier <span>+</span>.</td>
</tr>
<tr>
<td>??</td>
<td>Matches the preceding element zero or one time, but as few<br />
times as possible. It is a lazy quantifier that is the counterpart<br />
to the greedy quantifier <span>?</span>.</td>
</tr>
<tr>
<td>{<i>n</i>}?</td>
<td>Matches the preceding element exactly <span class=<br />
"parameter">n</span> times. It is a lazy quantifier that is the<br />
counter to the greedy quantifier <span class=<br />
"input">{n}+</span>.</td>
</tr>
</tbody>
</table>
<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/csharp-regular-expression-operator-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Safely cleaning HTML with strip_tags in C#</title>
		<link>http://www.dijksterhuis.org/safely-cleaning-html-with-strip_tags-in-csharp/</link>
		<comments>http://www.dijksterhuis.org/safely-cleaning-html-with-strip_tags-in-csharp/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 05:37:50 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[striptags]]></category>
		<category><![CDATA[strip_tags]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=758</guid>
		<description><![CDATA[
One of my favorites in the PHP libraries is the strip_tags function. Not only does it neatly remove HTML from an input it also allows you to specify which tags should stay. This is great if you are allowing your visitors to apply some basic HTML tags to their comments. This post explores two issues: [...]<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/03/sub.jpg" alt="Removing unwanted tags with StripTags/strip_tags" title="Removing unwanted tags with StripTags/strip_tags" width="500" height="205" class="aligncenter size-full wp-image-763" /></p>
<p><em>One of my favorites in the PHP libraries is the strip_tags function. Not only does it neatly remove HTML from an input it also allows you to specify which tags should stay. This is great if you are allowing your visitors to apply some basic HTML tags to their comments. This post explores two issues: using C# to remove unwanted tags, and cleaning up unwanted attributes that might be hidden in the allowed tags.</em></p>
<p><span id="more-758"></span></p>
<p>I wanted to clean some comments posted to a website from unwanted HTML tags. The users are allowed to &lt;B&gt; or &lt;I&gt; and even &lt;A href=&#8221;"&gt;&lt;/a&gt; their posts but anything else must be stripped before it is posted to the site. I found several regular expressions for C# that allow you to strip HTML but these magically wipe all the HTML and leave nothing.</p>
<p>Below is the end result of of some hacking, and of course much love-hate with the regular expression library. </p>
<p><strong><span>string StripTags(string Input, string[] AllowedTags)</span></strong></p>
<p>The StripTags method takes an input string, and an array of allowed tags. It returns the input as a string, minus all not wanted tags.</p>
<pre class="brush: c#">
string test1 = StripTags(&quot;&lt;p&gt;George&lt;/p&gt;&lt;b&gt;W&lt;/b&gt;&lt;i&gt;Bush&lt;/i&gt;&quot;, new string[]{&quot;i&quot;,&quot;b&quot;});
string test2 = StripTags(&quot;&lt;p&gt;George &lt;img src=&#039;someimage.png&#039; onmouseover=&#039;someFunction()&#039;&gt;W &lt;i&gt;Bush&lt;/i&gt;&lt;/p&gt;&quot;, new string[]{&quot;p&quot;});
string test3 = StripTags(&quot;&lt;a href=&#039;http://www.dijksterhuis.org&#039;&gt;Martijn &lt;b&gt;Dijksterhuis&lt;/b&gt;&lt;/a&gt;&quot;, new string[]{&quot;a&quot;});
</pre>
<p></span>Using the above example code returns the following:<br />
<span><br />
</span></p>
<div style="margin-left: 40px;"><span>George&lt;b&gt;W&lt;/b&gt;&lt;i&gt;Bush&lt;/i&gt;</span><br />
<span>&lt;p&gt;George W Bush&lt;/p&gt;</span><br />
<span>&lt;a href=&#8217;http://www.dijksterhuis.org&#8217;&gt;Martijn Dijksterhuis&lt;/a&gt;</span></div>
<p><em><br />
</em><strong><span>string StripTagsAndAttributes(string Input, string[] AllowedTags)</span></strong></p>
<p>The above StripTags function is similar to the original PHP strip_tags function in having the same weakness: It is still possible for a malicious user to insert attributes into each of the tags. Think &#8220;style=&#8221; and &#8220;id=&#8221;. We would be somewhat saver if we cleaned these as well. The <em><span>StripTagsAndAttributes </span></em><span>method</span> does just that.</p>
<p>It first runs the input through <em>StripTags</em>, and for the remaining tags is strips out all but a restricted set of attributes.</p>
<pre class="brush: c#">
string test4 = &quot;&lt;a class=\&quot;classof69\&quot; onClick=&#039;crosssite.boom()&#039; href=&#039;http://www.dijksterhuis.org&#039;&gt;Martijn Dijksterhuis&lt;/a&gt;&quot;;
Console.WriteLine(StripTagsAndAttributes(test4, new string[]{&quot;a&quot;}));
</pre>
<p>That &#8220;OnClick&#8221; attribute looks mighty unsafe. Running the above string through </span><em><span>StripTagsAndAttributes </span></em><span>as in the example above returns: </span></p>
<div style="margin-left: 40px;"><span>&lt;a class=&#8221;classof69&#8243; href=&#8217;http://www.dijksterhuis.org&#8217;&gt;Martijn Dijksterhuis&lt;/a&gt;</span></div>
<p>This function probably needs some tuning if you want to allow, or restrict things even further.</p>
<p><strong>A word of caution</strong></p>
<p>Regular expressions are voodoo, very cool, but still voodoo. The above functions work for the tests I have applied to them, but your mileage may vary! If you have a special situation that doesn&#8217;t work leave a note below and maybe we can work out the problems.</p>
<p><strong>Credits</strong></p>
<p>The strip_tags function is of course inspired by the <a id="ixfp" title="PHP version" href="http://tw.php.net/manual/en/function.strip-tags.php">PHP version</a> , and a Javascript implementation thereof by <a id="evns" title="Kevin van Sonderveld" href="http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strip_tags/">Kevin van Sonderveld. </a>The attribute stripping routine is based on the regular expressions by <a id="q100" title="mdw252" href="http://tw.php.net/manual/en/function.strip-tags.php#88491">mdw252</a> in one of the strip_tags manual page comments.</p>
<p><strong>Source code</strong></p>
<p>The complete source code for the <em>StripTags</em> function and <span><em>StripTagsAndAttributes</em> function with my test code can be found below:</p>
<p></span></p>
<pre class="brush: c#">

using System;
using System.Text.RegularExpressions;

namespace StripHTML
{
	class MainClass
	{

        private static string ReplaceFirst(string haystack, string needle, string replacement)
        {
       		int pos = haystack.IndexOf(needle);
            if (pos &lt; 0) return haystack;
            return haystack.Substring(0,pos) + replacement + haystack.Substring(pos+needle.Length);
        }

		private static string ReplaceAll(string haystack, string needle, string replacement)
        {
             int pos;
			 // Avoid a possible infinite loop
             if (needle == replacement) return haystack;
              while((pos = haystack.IndexOf(needle))&gt;0)
                       haystack = haystack.Substring(0,pos) + replacement + haystack.Substring(pos+needle.Length);
                        return haystack;
        }		

		public static string StripTags(string Input, string[] AllowedTags)
		{
			Regex StripHTMLExp = new Regex(@&quot;(&lt;\/?[^&gt;]+&gt;)&quot;);
		    string Output = Input;

			foreach(Match Tag in StripHTMLExp.Matches(Input))
			{
				string HTMLTag = Tag.Value.ToLower();
				bool IsAllowed = false;

				foreach(string AllowedTag in AllowedTags)
				{
					int offset = -1;

					// Determine if it is an allowed tag
					// &quot;&lt;tag&gt;&quot; , &quot;&lt;tag &quot; and &quot;&lt;/tag&quot;
					if (offset!=0) offset = HTMLTag.IndexOf(&#039;&lt;&#039;+AllowedTag+&#039;&gt;&#039;);
					if (offset!=0) offset = HTMLTag.IndexOf(&#039;&lt;&#039;+AllowedTag+&#039; &#039;);
					if (offset!=0) offset = HTMLTag.IndexOf(&quot;&lt;/&quot;+AllowedTag);

					// If it matched any of the above the tag is allowed
					if (offset==0)
					{
					 	IsAllowed = true;
						break;
					}
				}

				// Remove tags that are not allowed
				if (!IsAllowed) Output = ReplaceFirst(Output,Tag.Value,&quot;&quot;);
			}

			return Output;
		}

		public static string StripTagsAndAttributes(string Input, string[] AllowedTags)
		{
			/* Remove all unwanted tags first */
			string Output = StripTags(Input,AllowedTags);

			/* Lambda functions */
			MatchEvaluator HrefMatch = m =&gt; m.Groups[1].Value + &quot;href..;,;..&quot; + m.Groups[2].Value;
			MatchEvaluator ClassMatch = m =&gt; m.Groups[1].Value + &quot;class..;,;..&quot; + m.Groups[2].Value;
			MatchEvaluator UnsafeMatch = m =&gt; m.Groups[1].Value + m.Groups[4].Value;

			/* Allow the &quot;href&quot; attribute */
			Output = new Regex(&quot;(&lt;a.*)href=(.*&gt;)&quot;).Replace(Output,HrefMatch);

			/* Allow the &quot;class&quot; attribute */
			Output = new Regex(&quot;(&lt;a.*)class=(.*&gt;)&quot;).Replace(Output,ClassMatch);

			/* Remove unsafe attributes in any of the remaining tags */
			Output = new Regex(@&quot;(&lt;.*) .*=(\&#039;|\&quot;&quot;|\w)[\w|.|(|)]*(\&#039;|\&quot;&quot;|\w)(.*&gt;)&quot;).Replace(Output,UnsafeMatch);

			/* Return the allowed tags to their proper form */
			Output = ReplaceAll(Output,&quot;..;,;..&quot;, &quot;=&quot;);

			return Output;
		}

		public static void Main(string[] args)
		{
			string test1 = StripTags(&quot;&lt;p&gt;George&lt;/p&gt;&lt;b&gt;W&lt;/b&gt;&lt;i&gt;Bush&lt;/i&gt;&quot;, new string[]{&quot;i&quot;,&quot;b&quot;});
			string test2 = StripTags(&quot;&lt;p&gt;George &lt;img src=&#039;someimage.png&#039; onmouseover=&#039;someFunction()&#039;&gt;W &lt;i&gt;Bush&lt;/i&gt;&lt;/p&gt;&quot;, new string[]{&quot;p&quot;});
			string test3 = StripTags(&quot;&lt;a href=&#039;http://www.dijksterhuis.org&#039;&gt;Martijn &lt;b&gt;Dijksterhuis&lt;/b&gt;&lt;/a&gt;&quot;, new string[]{&quot;a&quot;});

			Console.WriteLine(test1);
			Console.WriteLine(test2);
			Console.WriteLine(test3);

			string test4 = &quot;&lt;a class=\&quot;classof69\&quot; onClick=&#039;crosssite.boom()&#039; href=&#039;http://www.dijksterhuis.org&#039;&gt;Martijn Dijksterhuis&lt;/a&gt;&quot;;
			Console.WriteLine(StripTagsAndAttributes(test4, new string[]{&quot;a&quot;}));
		}
	}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/jesper/">Jesper Rønn-Jensen&#8217;s</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/safely-cleaning-html-with-strip_tags-in-csharp/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using C# and .NET to send an e-mail through SMTP</title>
		<link>http://www.dijksterhuis.org/using-csharp-to-send-an-e-mail-through-smtp/</link>
		<comments>http://www.dijksterhuis.org/using-csharp-to-send-an-e-mail-through-smtp/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 07:02:26 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[email]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=744</guid>
		<description><![CDATA[
Sending an e-mail is pretty old news by now so it should come as no surprise that .NET contains a significant SMTP mail client. One old programming truth still holds: All programs will expand to eventually include sending (and receiving) e-mails. So how about adding e-mail to your program ? This post explores how we [...]<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/03/email.jpg" alt="Sending an e-mail using .NET" title="Sending an e-mail using .NET" width="500" height="238" class="aligncenter size-full wp-image-749" /></p>
<p><em>Sending an e-mail is pretty old news by now so it should come as no surprise that .NET contains a significant SMTP mail client. One old programming truth still holds: All programs will expand to eventually include sending (and receiving) e-mails. So how about adding e-mail to your program ? This post explores how we can use the System.Mail.SmtpClient to send formatted e-mails. There are plenty of options available and we will explore most of them.</em></p>
<p><span id="more-744"></span></p>
<p><em></em>In another lifetime together with friends I wrote <a id="ltp8" title="a massive e-mail parser" href="http://brazerko.com/watergate/wgman/welcome.htm">a massive e-mail parser</a> for the then popular FidoNet, and the (for us) new RFC822 based Internet. Written in Pascal for DOS it chewed its way through megabytes of modem downloaded Usenet groups and e-mail for our local BBS, night after night. It was fun and I learned that when it comes to e-mail that there are no real standards, just broken implementations.</p>
<p>Some 15 years later things have become quite a bit easier. Sending an e-mail is as straightforward as calling a few basic library functions and .NET of course includes a solid implementation.</p>
<p><strong>Quickly sending an e-mail</strong></p>
<p>If you are in a hurry then the following constructor will create a simple mail message from just 4 string parameters:</p>
<pre class="brush: c#">
// public client.Send(string from,string to,string subject,string body)
using System.Net.Mail;
SmtpClient client = new SmtpClient();
client.Send(&quot;martijn@dijksterhuis.org&quot;,&quot;test@dijksterhuis.org&quot;,&quot;Testing!&quot;,&quot;If this break again,.. I won&#039;t know what to do&quot;);
</pre>
<p>In the above example the e-mail is send using the system default settings as discovered by the .NET framework. If you are curious which system acted as the Default SMTP server you can query SmtpClient.Host</p>
<blockquote><p>Console.WriteLine(&#8221;Default SMTP Server: {0}&#8221;,client.Host);</p></blockquote>
<p>Note that there is a good chance that the .NET libraries are unable to work out the SMTP host and will fail with an <em>System.InvalidOperationException</em> (The SMTP host was not specified) when you attempt to send the e-mail. </p>
<p><strong>Sending a proper e-mail</strong></p>
<p>An basic e-mail is build up out of a sender, one or more recipients, a message body and one or more attachments. And of course the e-mail is probably encoded in an outdated Russian font.</p>
<p>The e-mail sender and receiver are represented by the <em>MailAddress</em> class. So of course you need an e-mail address, optionally a name, and in case you really want to send a Russian formatted name, a proper encoding format.</p>
<pre class="brush: c#">
MailAddress toUser = new MailAddress(&quot;martijn@dijksterhuis.org&quot;);
MailAddress toUser2 = new MailAddress(&quot;martijn@dijksterhuis.org&quot;,&quot;Martijn Dijksterhuis&quot;);
MailAddress toUser3 = new MailAddress(&quot;martijn@dijksterhuis.org&quot;,&quot;Martijn Dijksterhuis&quot;, System.Text.Encoding.UTF8);
</pre>
<p>My name doesn&#8217;t include any funky characters so I specified the default UTF-8 encoding.</p>
<p><strong>Sending an e-mail with only a single sender and receiver</strong></p>
<p>If your e-mail only contains a single sender and a single receiver the <em>MailMessage(MailAddress From,MailAddress To)</em> constructor provides all you need. It creates a new e-mail message structure, assigning the sending and receiver in the constructor.</p>
<pre class="brush: c#">
MailAddress toUser = new MailAddress(&quot;myfriend@yahoo.com&quot;);
MailAddress fromUser = new MailAddress(&quot;martijn@dijksterhuis.org&quot;);
MailMessage msg  = new MailMessage(fromUser,toUser);
</pre>
<p><strong>Adding more receivers to the same e-mail</strong></p>
<p>A single recipient is probably not sufficient. Not to worry, you can add as many To&#8217;s, CC&#8217;s, BCC&#8217;s etc to the e-mail as you would like:</p>
<pre class="brush: c#">
msg.To.Add( new MailAddress(&quot;second_to@dijksterhuis.org&quot;) );
msg.CC.Add( new MailAddress(&quot;first_cc@dijksterhuis.org&quot;) );
msg.CC.Add( new MailAddress(&quot;second_cc@dijksterhuis.org&quot;) );
msg.Bcc.Add( new MailAddress(&quot;first_bcc@dijksterhuis.org&quot;) );
</pre>
<p><strong>Setting the E-mail subject and body content</strong></p>
<p>Setting the subject of the e-mail is not hard, just set it from <em>Msg.Subject</em>.  And if you would like to encode that in a format other the Unicode, say BIG-5 Chinese:</p>
<pre class="brush: c#">
msg.Subject = &quot;一分鐘換一年&quot;
msg.SubjectEncoding = Encoding.GetEncoding(&quot;big5&quot;);
</pre>
<p>(The above Chinese came from my junk box and to the best of my knowledge its harmless)</p>
<p>Setting the actual message body works in a very similar fashion:</p>
<pre class="brush: c#">
msg.Body = &quot;Dear Customer, &quot; + Environment.NewLine + Environment.NewLine;
msg.Body += &quot;Because of repeated violations of our terms and conditions we had no choice but to&quot;;
msg.Body += &quot;terminate your account with us.&quot; + Environment.NewLine + Environment.NewLine;
msg.Body += &quot;The Management&quot;;
msg.BodyEncoding = System.Text.Encoding.UTF8;
</pre>
<p><strong>Adding an attachment to the e-mail</strong></p>
<p>An e-mail can have more than one attachment, and each attachment is represented by the System.Net.Mail.Attachment class. You can add them to the attachment collection of the message by calling &#8220;Attachments.Add()&#8221;</p>
<pre class="brush: c#">
using System.Net.Mime;
Attachment firstAttachment = new Attachment(&quot;document.doc&quot;,MediaTypeNames.Application.Octet);
MailMessage msg  = new MailMessage(fromUser,toUser);
msg.Attachments.Add(firstAttachement);
</pre>
<p>The first parameter passed to the constructor is the path to the attachment to include. If no full path is given, the current working directory is tried. The file type is defined in <em>System.Net.Mime</em> &#8212; available options are:</p>
<table border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="33%">MediaTypeNames</td>
<td width="33%">Application</td>
<td width="33%">Octet</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">PDF</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">RTF</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Soap</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Zip</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%">Image</td>
<td width="33%">Gif</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">JPEG</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Tiff</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%">Text</td>
<td width="33%">HTML</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Plain</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">RichText</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">XML</td>
</tr>
</tbody>
</table>
<p>If the type of file is not specified use <em>MediaTypesNames.Application.Octet</em> , which stands for &#8220;data is not interpreted&#8221;.</p>
<p><strong>Adding custom e-mail headers to your e-mail</p>
<p></strong>The <em>Msg.Header</em> property allows you to query and add to the e-mail headers set  by the .NET framework. A brand new e-mail will only contain a single header: &#8220;Mime: 1.0&#8243;. Adding your own custom header to this is trivial as is shown in the following code example: <strong><br />
</strong></p>
<pre class="brush: c#">

MailMessage Msg = new MailMessage(new               MailAddress(&quot;martijn@dijksterhuis.org&quot;),new MailAddress(&quot;martijn@dijksterhuis.org&quot;));

// Add a custom header to the e-mail
Msg.Headers.Add(&quot;X-Header&quot;,&quot;2.0&quot;);

// Display all the message headers.
string[] Keys = Msg.Headers.AllKeys;
foreach (string s in Keys)

Console.WriteLine(&quot;{0}: {1}&quot;, s,Msg.Headers[s]);
</pre>
<p><strong>Sending your e-mail with SmtpClient</strong></p>
<p>The hard work of delivering the e-mail is done through the <em>SmtpClient</em> class and the most basic delivery only takes two lines:</p>
<blockquote><p> SmtpClient client = new SmtpClient();<br />
 client.Send(Msg);
</p></blockquote>
<p>It might be wise to catch exceptions at this point because sending an SMTP e-mail can throw a number:</p>
<p><OL><br />
<LI>SmtpFailedRecipientsException: The message could not be delivered to one or more of the recipients in To, CC, or Bcc.</LI><br />
<LI>SmtpException : Connection failed, authentication failed or a time-out</LI><br />
<LI>ArgumentNullException / ArgumentOutOfRangeException / InvalidOperationException : Something wrong with the input fields of the e-mail</LI><br />
</OL></p>
<p>If you do not specify any parameters the default <em>SmtpClient</em> constructor will lookup the SMTP server to use through the .NET environment. </p>
<p>You can specify a specific server and optional port through the second constructor:</p>
<blockquote><p>SmtpClient client = new SmtpClient(&#8221;mail.dijksterhuis.org&#8221;,3000);</p></blockquote>
<p>The above <em>SmtpClient.Send</em> call is a blocking call &#8212; your application halts while the e-mail is being send. Naturally there is also an asynchronous call: <em>SmtpClient.SendAsync</em>.</p>
<p>Using <em>SmtpClient.SendAsync</em> is a little more work. How to do this is shown in the following example: </p>
<pre class="brush: c#">
using System;
using System.Net.Mail;
using System.Threading;
using System.ComponentModel;

namespace SnmpMailer
{
    class MainClass
    {
        static Semaphore mailSendSemaphore;

        private static void MailSendCallback(object sender, AsyncCompletedEventArgs arg)
        {
            // Get our unique token for this asynchronous operation.
            String token = (string) arg.UserState;

            // Did the user abort the sent ?
            if (arg.Cancelled)
                Console.WriteLine(&quot;[{0}] Send canceled.&quot;, token);
            // Did an error occur during the send?
            if (arg.Error != null)
                 Console.WriteLine(&quot;[{0}] {1}&quot;, token, arg.Error.ToString());
            else
                Console.WriteLine(&quot;Message sent succesfully!&quot;);

            // Release the main thread
            mailSendSemaphore.Release();
        }

        public static void Main(string[] args)
        {
            mailSendSemaphore = new Semaphore(0,1);

            /* Create the mail message with to &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; from */
            MailMessage Msg = new MailMessage(new MailAddress(&quot;noreply@dijksterhuis.org&quot;),
                                              new MailAddress(&quot;martijn@dijksterhuis.org&quot;));

            Msg.Body = &quot;Dear Customer, &quot; + Environment.NewLine + Environment.NewLine;
            Msg.Body += &quot;Because of repeated violations of our terms and conditions we had no choice but to&quot;;
            Msg.Body += &quot;terminate your account with us.&quot; + Environment.NewLine + Environment.NewLine;
            Msg.Body += &quot;The Management&quot;;
            Msg.BodyEncoding = System.Text.Encoding.UTF8;

            /* Set the subject */
            Msg.Subject = &quot;Termination of service notice&quot;;

            /* Add our own header */
            Msg.Headers.Add(&quot;X-Deliverator&quot;,&quot;Terminator&quot;);

            /* Deliver the message in an asynchronous fashion */
            SmtpClient Deliverator = new SmtpClient(&quot;mymailserver.com&quot;);

            /* Print the default client */
            Console.WriteLine(&quot;Default SMTP Server: {0}&quot;,Deliverator.Host);

            /* Specify the call back function */
            Deliverator.SendCompleted += new SendCompletedEventHandler(MailSendCallback);

            /* For an asyncronous call we can pass a token to help us determine the message being send */
            Deliverator.SendAsync(Msg,&quot;Msg ID 1212&quot;);

            /* Because we have little else to do, we set a semaphore and wait */
            mailSendSemaphore.WaitOne();

            Console.WriteLine(&quot;Mail delivery finished&quot;);
        }
    }
}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/biscotte/">Mzelle Biscotte</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/using-csharp-to-send-an-e-mail-through-smtp/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Show all assemblies loaded by your C# program</title>
		<link>http://www.dijksterhuis.org/show-assemblies-loaded-program/</link>
		<comments>http://www.dijksterhuis.org/show-assemblies-loaded-program/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 07:29:15 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[reflection]]></category>

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

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

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

            foreach (Assembly MyAssembly in AssembliesLoaded)
            {
                Console.WriteLine(&quot;Loaded: {0}&quot;, MyAssembly.FullName);
            }
        }
    }
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/show-assemblies-loaded-program/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Simple class to submit (POST) a Web form from C#</title>
		<link>http://www.dijksterhuis.org/simple-class-to-submit-post-a-web-form-from-csharp/</link>
		<comments>http://www.dijksterhuis.org/simple-class-to-submit-post-a-web-form-from-csharp/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 16:00:01 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[networking]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=697</guid>
		<description><![CDATA[Today I needed to automate posting some data to a web form from a C# program, and sure enough this is not at all that difficult. But surprisingly you need to call quite a large number of methods to get your data ready to ship. A working code example only took a few minutes to [...]<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>Today I needed to automate posting some data to a web form from a C# program, and sure enough this is not at all that difficult. But surprisingly you need to call quite a large number of methods to get your data ready to ship. A working code example only took a few minutes to write but it took quite a bit more time to clean things up. You can find the full implementation at the end of this post.</em></p>
<p><span id="more-697"></span></p>
<p>If you like to submit a POST form to your server the following will explain how to do create the program. </p>
<p>To help with debugging I created a tiny test script on my server to see if my code was working as advertised: <em>http://www.dijksterhuis.org/test/post.php</em> Please feel free to use this script to see if your program is working correctly.</p>
<p>My wrapper code is easy to use and allows for you to add any number of parameters to the POST request:</p>
<pre class="brush: c#">
			WebPostRequest myPost = new WebPostRequest(&quot;http://www.dijksterhuis.org/test/post.php&quot;);
			myPost.Add(&quot;keyword&quot;,&quot;void&quot;);
			myPost.Add(&quot;data&quot;,&quot;hello&amp;+-[]&quot;);
</pre>
<p>I use the <em>HttpUtility.UrlEncode</em> method to ensure that all parameters containing weird symbols survive their trip over the Internet intact.</p>
<blockquote><p>string Response = myPost.GetResponse();</p></blockquote>
<p>The above function call executes the query and returns any response from the server. The test script simply echoes the parameters and their values. </p>
<pre class="brush: c#">
using System;
using System.Net;
using System.Web;
using System.Collections;
using System.IO;

namespace WebRequestExample
{

	class WebPostRequest
	{
		WebRequest theRequest;
		HttpWebResponse theResponse;
		ArrayList  theQueryData;

		public WebPostRequest(string url)
		{
			theRequest = WebRequest.Create(url);
			theRequest.Method = &quot;POST&quot;;
			theQueryData = new ArrayList();
		}

		public void Add(string key, string value)
		{
			theQueryData.Add(String.Format(&quot;{0}={1}&quot;,key,HttpUtility.UrlEncode(value)));
		}

		public string GetResponse()
		{
			// Set the encoding type
			theRequest.ContentType=&quot;application/x-www-form-urlencoded&quot;;

			// Build a string containing all the parameters
			string Parameters = String.Join(&quot;&amp;&quot;,(String[]) theQueryData.ToArray(typeof(string)));
			theRequest.ContentLength = Parameters.Length;

			// We write the parameters into the request
			StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
  			sw.Write(Parameters);
  			sw.Close();

			// Execute the query
			theResponse =  (HttpWebResponse)theRequest.GetResponse();
  			StreamReader sr = new StreamReader(theResponse.GetResponseStream());
   			return sr.ReadToEnd();
		}

	}

	class MainClass
	{
		public static void Main(string[] args)
		{
			WebPostRequest myPost = new WebPostRequest(&quot;http://www.dijksterhuis.org/test/post.php&quot;);
			myPost.Add(&quot;keyword&quot;,&quot;void&quot;);
			myPost.Add(&quot;data&quot;,&quot;hello&amp;+-[]&quot;);
			Console.WriteLine(myPost.GetResponse());
		}
	}
}
</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/simple-class-to-submit-post-a-web-form-from-csharp/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using the C# WebClient class to upload and download FTP files</title>
		<link>http://www.dijksterhuis.org/webclient-class-upload-download-ftp-files/</link>
		<comments>http://www.dijksterhuis.org/webclient-class-upload-download-ftp-files/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 02:18:16 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[networking]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=693</guid>
		<description><![CDATA[Your C# program has just calculated the weekly sales report and you need to upload it to the company file server. The C# System.Net.Webclient class makes this quite trivial. The same for downloading a file from the server and then parsing it for content. This post shows how you can use basic FTP actions to [...]<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>Your C# program has just calculated the weekly sales report and you need to upload it to the company file server. The C# System.Net.Webclient class makes this quite trivial. The same for downloading a file from the server and then parsing it for content. This post shows how you can use basic FTP actions to upload, download files and either store them in memory or write them to disk.<br />
</em></p>
<p>At the end of this post you will find my <em>BasicFTPClient</em> class that implements the uploading and downloading code.</p>
<p><span id="more-693"></span></p>
<p><strong>1. Download an FTP file to disk</strong></p>
<p>If you have a file called &#8220;fileonftpserver.txt&#8221; and would like to download it to &#8220;/tmp/mydownload.txt&#8221; use the &#8220;DownloadFile&#8221; method:</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
     MyClient.DownloadFile(&quot;fileonftpserver.txt&quot;,&quot;/tmp/mydownload.txt&quot;); // c:\temp\mydownload.txt for Windows
}
catch (WebException e)
{
     Console.WriteLine(e.ToString());
}
</pre>
<p><strong>2. Download an FTP file to memory</strong></p>
<p>If you would like to directly process the file you have downloaded (and don&#8217;t need to save it to disk first) the &#8220;DownloadData&#8221; method is your friend. If you would like to print the contents of the file to the console you could try this:</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
    byte[] Data = MyClient.DownloadData(&quot;download.test&quot;);

    // Convert the data to a string
    String s = System.Text.Encoding.UTF8.GetString(Data);
    Console.WriteLine(s);
}
catch (WebException e)
{
    Console.WriteLine(e.ToString());
}
</pre>
<p><strong>3. Upload a file to the FTP server</strong></p>
<p>If you have a file on disk and would like to upload it to an FTP server then use the  &#8220;UploadFile&#8221; method.</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
    MyClient.UploadFile(&quot;upload.test&quot;,&quot;/tmp/output.txt&quot;);
}
catch (WebException e)
{
    Console.WriteLine(e.ToString());
}
</pre>
<p><strong>4. Upload a byte[] to the FTP server</strong></p>
<p>The &#8220;UploadData&#8221; method takes a byte array as the source of its data, allowing you to create something in memory and then save it to an FTP server. Usefull for those reports you have just generated.</p>
<pre class="brush: c#">
BasicFTPClient MyClient = new BasicFTPClient();

MyClient.Host=&quot;myserver.com&quot;;
MyClient.Username=&quot;yourusername&quot;;
MyClient.Password=&quot;yourpassword&quot;;

try
{
    string MyReport = &quot;Sales figures for October 2010&quot;;
    byte[] Data = System.Text.Encoding.UTF8.GetBytes(MyReport);
    MyClient.UploadData(&quot;upload.test&quot;,Data);
}
catch (WebException e)
{
    Console.WriteLine(e.ToString());
}
</pre>
<p><strong>The Mono angle</strong></p>
<p>All of the above examples work on Mono just as well as on Microsoft&#8217;s .NET. With a catch: I found two bugs in the Mono class libraries that made things quite impossible. Both were fixed by the mono team within hours of reporting them (thanks!). So if you are using the Mono CVS code for Mono 2.4 you are in luck, otherwise the following code is not going to work until the next Mono release.</p>
<p>If you come across a problem with Mono reporting a bug is trivial, you can report them at bugzilla.novell.com</p>
<p><strong>The BasicFTPClient class</strong></p>
<pre class="brush: c#">
using System;
using System.Net;
using System.IO;

namespace BasicFTPClientNamespace
{
    class BasicFTPClient
    {
        public string Username;
        public string Password;
        public string Host;
        public int Port;

        public BasicFTPClient()
        {
            Username = &quot;anonymous&quot;;
            Password = &quot;anonymous@internet.com&quot;;
            Port = 21;
            Host = &quot;&quot;;
        }

        public BasicFTPClient(string theUser, string thePassword, string theHost)
        {
            Username = theUser;
            Password = thePassword;
            Host = theHost;
            Port = 21;
        }

        private Uri BuildServerUri(string Path)
        {
            return new Uri(String.Format(&quot;ftp://{0}:{1}/{2}&quot;, Host, Port, Path));
        }

        /// &lt;summary&gt;
        /// This method downloads the given file name from the FTP server
        /// and returns a byte array containing its contents.
        /// Throws a WebException on encountering a network error.
        /// &lt;/summary&gt;

        public byte[] DownloadData(string path)
        {
            // Get the object used to communicate with the server.
            WebClient request = new WebClient();

            // Logon to the server using username + password
            request.Credentials = new NetworkCredential(Username, Password);
            return request.DownloadData(BuildServerUri(path));
        }

        /// &lt;summary&gt;
        /// This method downloads the FTP file specified by &quot;ftppath&quot; and saves
        /// it to &quot;destfile&quot;.
        /// Throws a WebException on encountering a network error.
        /// &lt;/summary&gt;
        public void DownloadFile(string ftppath, string destfile)
        {
            // Download the data
            byte[] Data = DownloadData(ftppath);

            // Save the data to disk
            FileStream fs = new FileStream(destfile, FileMode.Create);
            fs.Write(Data, 0, Data.Length);
            fs.Close();
        }

        /// &lt;summary&gt;
        /// Upload a byte[] to the FTP server
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;path&quot;&gt;Path on the FTP server (upload/myfile.txt)&lt;/param&gt;
        /// &lt;param name=&quot;Data&quot;&gt;A byte[] containing the data to upload&lt;/param&gt;
        /// &lt;returns&gt;The server response in a byte[]&lt;/returns&gt;

        public byte[] UploadData(string path, byte[] Data)
        {
            // Get the object used to communicate with the server.
            WebClient request = new WebClient();

            // Logon to the server using username + password
            request.Credentials = new NetworkCredential(Username, Password);
            return request.UploadData(BuildServerUri(path), Data);
        }

        /// &lt;summary&gt;
        /// Load a file from disk and upload it to the FTP server
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ftppath&quot;&gt;Path on the FTP server (/upload/myfile.txt)&lt;/param&gt;
        /// &lt;param name=&quot;srcfile&quot;&gt;File on the local harddisk to upload&lt;/param&gt;
        /// &lt;returns&gt;The server response in a byte[]&lt;/returns&gt;

        public byte[] UploadFile(string ftppath, string srcfile)
        {
            // Read the data from disk
            FileStream fs = new FileStream(srcfile, FileMode.Open);
            byte[] FileData = new byte[fs.Length];

            int numBytesToRead = (int)fs.Length;
            int numBytesRead = 0;
            while (numBytesToRead &gt; 0)
            {
                // Read may return anything from 0 to numBytesToRead.
                int n = fs.Read(FileData, numBytesRead, numBytesToRead);

                // Break when the end of the file is reached.
                if (n == 0) break;

                numBytesRead += n;
                numBytesToRead -= n;
            }
            numBytesToRead = FileData.Length;
            fs.Close();

            // Upload the data from the buffer
            return UploadData(ftppath, FileData);
        }

    }
}
</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/webclient-class-upload-download-ftp-files/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Exploring C# reflection</title>
		<link>http://www.dijksterhuis.org/exploring-reflection/</link>
		<comments>http://www.dijksterhuis.org/exploring-reflection/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 16:00:39 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Chapter]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=680</guid>
		<description><![CDATA[
In this post I look at how we can simply retrieve basic information about our own types, discover their methods and lastly how we can import a foreign assembly, inspect its contents, load a class and execute its methods. 
When C# compiles your code it not only stores the program in the assembly but the [...]<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/horses.jpg" alt="Reflecting on our C# selves" title="Reflecting on our C# selves" width="500" height="260" class="alignnone size-full wp-image-684" /></p>
<p><em>In this post I look at how we can simply retrieve basic information about our own types, discover their methods and lastly how we can import a foreign assembly, inspect its contents, load a class and execute its methods. </p>
<p>When C# compiles your code it not only stores the program in the assembly but the complete information on each of the structures you have defined. Each class, its types, parameters and methods described into detail are all available. This might sound like stating the obvious, but until recently most compilers treated this kind of &#8220;meta&#8221; data as a waste of space and never included it into the final assembly.</em></p>
<p><span id="more-680"></span></p>
<p>Through reflection C#  offers a way of inspecting this meta information from a running program. The program reflects on itself to discover itself. It can use this to change the way it runs, or to report the results back to the user.</p>
<p>Why is this useful? If you distribute an application that accepts third plug-ins you need some kind of mechanism to inspect whether the supplied plug-in provides the correct set of methods for your code to work with. Very similar to how Visual Studio works with plug-ins.</p>
<p><strong>Type</strong></p>
<p>To be able to interact with their own code C# programs rely heavily on the <em>Type</em> class. The <em>Type</em> class can represent all C# type declarations: class types, interface types, array types, value types, enumeration types, type parameters etc. You can use it to query a type and discover what kind of contents it has.</p>
<p><em>GetType()</em> is the most common way to access C# reflection and I&#8217;ll show in the next example how you can find out the original type of an object after it has been cast down to a basic object. The<em> GetType()</em> method is inherited from object, so each C# object has access to it. As can be expected, <em>GetType()</em> returns an instance of the Type class.</p>
<p>But first have a look a simple example of how we can use <em>GetType()</em></p>
<pre class="brush: c#">
    using System;
    using System.Reflection;
    class MainClass
    {
        // This routine takes an object, which is the root of all
        // types in C#
        public static void PrintType(object Data)
        {
            Console.WriteLine(&quot;Type of Data: {0}&quot;,Data.GetType());
        }

        public static void Main(string[] args)
        {
            string msg = &quot;Hello World&quot;;
            PrintType(msg);
            int    theValue = 1024;
            PrintType(theValue);
        }
    }
</pre>
<p>This will print:</p>
<blockquote><p>Type of Data: System.String<br />
Type of Data: System.Int32
</p></blockquote>
<p>If you know that the object you were passed was really a <em>System.Int32</em> object, you can could cast it back and modify it as a regular integer. The following works but isn&#8217;t very nice:</p>
<pre class="brush: c#">
         object Test = new int();

         // This only works if the above object is an integer
         if (Test.GetType().ToString()==&quot;System.Int32&quot;)
            {
                int MyInt = (System.Int32) Test;
                MyInt = 20;
            }
</pre>
<p>A much better way of course in your own code to do the following:</p>
<pre class="brush: c#">
         object Test = new int();
         if (Test is int)
            {
                int MyInt = (int) Test;
                MyInt = 20;
            }
</pre>
<p><strong>The TypeOf operator</strong></p>
<p>The <em>typeof()</em> operator works in similar fashion at GetType but on type definitions at compile time. The <em>GetType()</em> operator works on instances of variables and is available at run-time. The benefit is that you don&#8217;t have to instantiate a class to obtain an type instance. To illustrate the difference have a look at the following:</p>
<pre class="brush: c#">
Type e = typeof(MyExampleClass);

// This is the same as:

MyClass example = new MyExampleClass();
Type t = example.GetType();
</pre>
<p><strong>Using Type to query a class methods and members</strong></p>
<p>Of course we can obtain much more information about a class than just its name. We can use the <em>GetMethods()</em> method to obtain a list of all the methods in the class, and <em>GetMembers()</em> to obtain all its member variables. Not only that, we can also call these members after we discover them.</p>
<pre class="brush: c#">
using System;
using System.Reflection;

namespace Reflection
{
    class MySecretClass
    {
        public int Z;

        public int Add(int x) { return x+1; }
        public int Sub(int x) { return x-1; }

         MySecretClass()
        {
            Z = 0;
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
         Type t = typeof(MySecretClass);

         MethodInfo[] MethodArray = t.GetMethods();
         foreach (MethodInfo Method in MethodArray)
          Console.WriteLine(&quot;Method: {0}&quot;,Method.ToString());

         MemberInfo[] MemberArray = t.GetMembers();
         foreach (MemberInfo Member in MemberArray)
          Console.WriteLine(&quot;Member: {0}&quot;,Member.ToString());

        }
    }
}
</pre>
<p><strong>Loading an external assembly</strong></p>
<p>Inspecting our own types is not nearly as adventurous as trying to decode the definitions found in a assembly you are trying to understand or validate. The following code loads the &#8220;mscorlib.dll&#8221; (which is the present in all .NET environments) and prints its name, version, culture and public key:</p>
<pre class="brush: c#">
            System.Reflection.Assembly LoadedAssembly = System.Reflection.Assembly.Load(&quot;mscorlib.dll&quot;);
            System.Console.WriteLine(LoadedAssembly.GetName());
</pre>
<p>We can query the assembly for a couple of basic variables, such as its name, location etc:</p>
<pre class="brush: c#">
            Console.WriteLine(&quot;Full Name: {0}&quot;, LoadedAssembly.FullName);
            Console.WriteLine(&quot;Location: {0}&quot;, LoadedAssembly.Location);
            Console.WriteLine(&quot;Code Base: {0}&quot;, LoadedAssembly.CodeBase);
            Console.WriteLine(&quot;Escaped Code Base: {0}&quot;, LoadedAssembly.EscapedCodeBase);
            Console.WriteLine(&quot;Loaded from GAC: {0}&quot;, LoadedAssembly.GlobalAssemblyCache);
</pre>
<p>Now the assembly is in memory we can explore it using the above introduced Type class, the GetTypes() method returns an array of all types in the assembly. The full code that queries the mscorlib.dll in detail is below:</p>
<pre class="brush: c#">
using System;
using System.Reflection;

namespace Reflection
{
    class MainClass
    {

        public static void Main(string[] args)
        {
            System.Reflection.Assembly LoadedAssembly = System.Reflection.Assembly.Load(&quot;mscorlib.dll&quot;);
            System.Console.WriteLine(LoadedAssembly.GetName());

            Console.WriteLine(&quot;Full Name: {0}&quot;, LoadedAssembly.FullName);
            Console.WriteLine(&quot;Location: {0}&quot;, LoadedAssembly.Location);
            Console.WriteLine(&quot;Code Base: {0}&quot;, LoadedAssembly.CodeBase);
            Console.WriteLine(&quot;Escaped Code Base: {0}&quot;, LoadedAssembly.EscapedCodeBase);
            Console.WriteLine(&quot;Loaded from GAC: {0}&quot;, LoadedAssembly.GlobalAssemblyCache);

            Type[] types = LoadedAssembly.GetTypes();

            foreach (Type t in types)
            {
                Console.WriteLine (&quot;Name: {0}&quot;, t.FullName);
                Console.WriteLine (&quot;Namespace: {0}&quot;, t.Namespace);
            }
        }
    }
}
</pre>
<p><strong>Calling dynamically bound assemblies at runtime</strong></p>
<p>After we have loaded an assembly we want to execute some code in it. In the above example we used the <em>mscorelib.dll</em> because it conveniently is available on all .NET systems. In the following example I show how you can create an object instance and call a named method.</p>
<p>The <em>System.DateTime</em> class is one of many stored in this dll, and we are interested in the <em>ToLongDateString</em> method. Normally we would call it in a manner similar to the below:</p>
<pre class="brush: c#">
System.DateTime myTime   = new System.DateTime(2000,1,1,12,0,0);
Console.WriteLine(&quot;Current Time: {0}&quot;,myTime.ToLongDateString());
</pre>
<p>As we have loaded <em>mscorlib</em> dynamically we need to go through some more steps to locate the method and constructor we are interested in:</p>
<pre class="brush: c#">
object myObject = LoadedAssembly.CreateInstance(&quot;System.DateTime&quot;,false,BindingFlags.ExactBinding,null,new Object[] {2000,1,1,12,0,0},null,null);
</pre>
<p>We use <em>CreateInstance</em> to create an instance of the class we require, &#8220;System.DateTime&#8221;. Just ignore the other parameters for now; the second important one is where we pass an object array containing the exact number of variables to match the correct constructor.</p>
<p>Next we need to obtain a handle to the method inside the class we want to invoke.</p>
<pre class="brush: c#">
MethodInfo m = LoadedAssembly.GetType(&quot;System.DateTime&quot;).GetMethod(&quot;ToLongDateString&quot;);
</pre>
<p>We execute the method by calling &#8220;Invoke&#8221;, passing our object and an object array of parameters (null as ToLongDateString does not take any). We need to cast the resulting object to a string.</p>
<pre class="brush: c#">string result = (string) m.Invoke(myObject,null);
Console.WriteLine(&quot;The time and date: {0}&quot;,result);
</pre>
<p>From the above it is clear that calling methods from a dynamically loaded and bound assembly is considerably more work. It does however allow you to extend your program through third party extensions, or by enabling functionality through assemblies that might not be available on all systems.</p>
<p>The full code for the final example is below:</p>
<pre class="brush: c#">
using System;
using System.Reflection;

namespace Reflection
{
        class MainClass
        {

                public static void Main(string[] args)
                {
                        System.Reflection.Assembly LoadedAssembly = System.Reflection.Assembly.Load(&quot;mscorlib.dll&quot;);
                        System.Console.WriteLine(LoadedAssembly.GetName());

                        // Doing it the statically bound way
                        System.DateTime myTime   = new System.DateTime(2000,1,1,12,0,0);
                        Console.WriteLine(&quot;Current Time: {0}&quot;,myTime.ToLongDateString());

                        // And now through an assembly loaded at runtime
                        object myObject = LoadedAssembly.CreateInstance(&quot;System.DateTime&quot;,false,BindingFlags.ExactBinding,null,new Object[] {2000,1,1,12,0,0},null,null);

                        MethodInfo m = LoadedAssembly.GetType(&quot;System.DateTime&quot;).GetMethod(&quot;ToLongDateString&quot;);
                        string result = (string) m.Invoke(myObject,null);
                        Console.WriteLine(&quot;The time and date: {0}&quot;,result);

                }
        }
}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/mikebaird/">Mike Baird</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/exploring-reflection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Uncommon C# : Using C style unions in C#</title>
		<link>http://www.dijksterhuis.org/uncommon-style-unions/</link>
		<comments>http://www.dijksterhuis.org/uncommon-style-unions/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 02:16:47 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Uncommon C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[language]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=672</guid>
		<description><![CDATA[
A union is a data structure that stores several different types of data at the same single location in memory. Although this might sound like madness in a garbage collected world many older binary data formats still heavily rely on this. A possible use is if you want to modify an IPv4 address. An IPv4 [...]<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/rings1.jpg" alt="Uncommon unions in C#" title="Uncommon unions in C#" width="500" height="226" class="alignnone size-full wp-image-676" /></p>
<p><em>A union is a data structure that stores several different types of data at the same single location in memory. Although this might sound like madness in a garbage collected world many older binary data formats still heavily rely on this. A possible use is if you want to modify an IPv4 address. An IPv4 address is 4 bytes, or an unsigned C# int. You might want to manipulate the IP address as a single value, or by splitting it into four separate bytes.</em></p>
<p><span id="more-672"></span></p>
<p>C# does not have a union keyword like C or C++ but it is still possible to create the same result by using the StructLayout(LayoutKind.Explicit) and FieldOffset attributes which are part of System.Runtime.InteropServices (which as the name suggests supplies code for working with unmanaged code).</p>
<p>C# allows for three distinct ways of layout data structures in memory: Auto, Explicit, and Sequential. The default is &#8220;Auto&#8221;, but for this to work we need &#8220;Explicit&#8221;. </p>
<p>The FieldOffset sets the physical position of fields within the representation of a class or structure. But what it also allow you to do is to set the same position twice. In the below example we will let the unsigned int for the IP address start at the same spot as the most significant byte.</p>
<pre class="brush: c#">
using System;
using System.Runtime.InteropServices;

namespace ipv4
{

    [StructLayout(LayoutKind.Explicit)]
    struct IPv4Address
    {
        [FieldOffset(0)]
        public uint Address;
        [FieldOffset(0)]
        public byte b3;
        [FieldOffset(1)]
        public byte b2;
        [FieldOffset(2)]
        public byte b1;
        [FieldOffset(3)]
        public byte b0;
    }

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

            // Assign localhost to the IPv4 address
            myAddress.Address = 0; // Avoid CS0170: Unassigned Field error
            myAddress.b0 = 127;
            myAddress.b1 = 0;
            myAddress.b2 = 0;
            myAddress.b3 = 1;

            Console.WriteLine(&quot;The address in hexadecimal: {0:x}&quot;,myAddress.Address);
        }
    }
}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/jeffbelmonte/">Jeff Belmonte</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/uncommon-style-unions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
