<?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; c#</title>
	<atom:link href="http://www.dijksterhuis.org/tag/c/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>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>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>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>
		<item>
		<title>C# Preprocessor Directives Explained</title>
		<link>http://www.dijksterhuis.org/csharp-preprocessor-directives-explained/</link>
		<comments>http://www.dijksterhuis.org/csharp-preprocessor-directives-explained/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 09:09:42 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[preprocessor directives]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=653</guid>
		<description><![CDATA[By using pre-processor directives you can exclude parts of your code from being seen by the compiler. Excluded from the assembly they are never seen at run-time.  This is different from a regular if (x) {}  block where code is actually compiled in, evaluated at runtime and added to the assembly.
To understand why [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>By using pre-processor directives you can exclude parts of your code from being seen by the compiler. Excluded from the assembly they are never seen at run-time.  This is different from a regular<em> if (x) {} </em> block where code is actually compiled in, evaluated at runtime and added to the assembly.</p>
<p>To understand why you would want to do this, a little history: One of the good things about C is that it works on every imaginable platform, the bad thing was of course that it works on every imaginable platform. There was always a little tweaking required to get your code to compile. Your program might have needed to compile on Amiga, DOS , OS/2, Windows or Linux. The invention of the preprocessor made this much easier. As a separate step prior to compilation it combs through the source code and modifies it according to the pre-processing instructions found in the source code. The C compiler never gets to see the things that don&#8217;t apply to it.</p>
<p><span id="more-653"></span></p>
<p>In C# there is no separate preprocessor step instead the compiler itself skims through the code as it reads it. Fortunately it is also nowhere near as complex as the C pre-processor.</p>
<p><strong>Contents</strong></p>
<ul>
<li><a href="#A">The #define and #undef directives</a></li>
<li><a href="#B">Unlike C and C++ there are no macros in C#</a></li>
<li><a href="#C">Conditional Compilation with #if / #else / #endif</a></li>
<li><a href="#D">Avoid the clutter &#8211; use conditional attributes instead</a></li>
<li><a href="#E">Using #error and #warning during compilation</a></li>
<li><a href="#F">Generated code builds and error reporting with #line</a></li>
<li><a href="#G">Region Directives</a></li>
</ul>
<p><a name="a"></a><strong>The #define and #undef directives</strong></p>
<p>The basis of the C# preprocessor directives are #define and #undef. They allow you to create and destroy symbols used by the preprocessing step.</p>
<blockquote><p>#define TESTVERSION<br />
#undef  DEBUG</p></blockquote>
<p>A common use is for a programmer to turn on and off the inclusion of debugging code. When you are coding and debugging this allow you to test your code but this code shouldn&#8217;t be present in the production version of your software.</p>
<p>It is possible to set symbols using <em>/define</em> on the compilers command line allowing you to build scripts that produce different versions of your code. For example a &#8220;full version&#8221; and a limited &#8220;demo&#8221; version.</p>
<p><strong>C# does not have any pre-defined symbols, except for maybe DEBUG</strong></p>
<p>If you are used to your C/C++ compiler <a rel="nofollow" href="http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html">setting large numbers of symbols</a> so that you could identify the compiler and version you will puzzled to discover the C# doesn&#8217;t have any. So you cannot check for the .NET version from a pre-defined symbol and branch your code based on that. (The closest that you can do is to check for the execution environment at runtime, for example if you want to know <a rel="nofollow" href="http://www.mono-project.com/FAQ:_Technical#How_can_I_detect_if_am_running_in_Mono.3F">if you a running under mono</a>.)</p>
<p>If you are compiling your code in the Visual C# / MonoDevelop environment there will be one symbol defined you can use: DEBUG. This is set in the project options and if you are building your code you can select if you want to build the Debug or Release version.</p>
<p><a name="B"></a><strong>Unlike C and C++ there are no macros in C#</strong></p>
<p>The following is not going to fly on C#. Macro&#8217;s are commonly used to expand expressions while compiling C code. A common problem is that C doesn&#8217;t have a boolean type. So the first thing most programmers do when starting a new project is to define their own as shown in the next little C code snippet:</p>
<pre class="brush: c">
#include &lt;stdio.h&gt;

#define BOOL  int
#define TRUE   1
#define FALSE  0
#define IS_TRUE(x) (x == TRUE)

void main()
{
        if (IS_TRUE(TRUE))
        {
          printf(&quot;It is TRUE!&quot;);
        }
}
</pre>
<p>When the C preprocessor comes across this it would replace &#8220;BOOL&#8221; with int, FALSE with 0 and TRUE with 1. The compiler never saw the BOOL, or the TRUE or FALSE. But lets not hang around here &#8212; as said, this is not supported by C#</p>
<p><a name="C"></a><strong>Conditional Compilation with #if / #else / #endif</strong></p>
<p>Of course, if you can define symbols you need to be able to test for them as well. The #if / #else / #endif directives do just that. If you are building the debug version of your code, you can check for the DEBUG symbol:</p>
<blockquote><p>#if DEBUG<br />
            Console.WriteLine(&#8221;Things are not going so well!&#8221;);<br />
#endif
</p></blockquote>
<p>If you are not building the Debug version of your code &#8212; the above line is never seen by the compiler, and thus is not included in the assembly. All #if statements need to be closed by an #endif, and of course you can also use an #else statement:</p>
<blockquote><p>
#if DEBUG<br />
            Console.WriteLine(&#8221;Things are not going so well, some more debugging is needed!&#8221;);<br />
#else<br />
            Console.WriteLine(&#8221;Fatal Error: Please call free support (0800) 123 123&#8243;);<br />
#endif
</p></blockquote>
<p>The <em>#eif</em> directive is a short form for &#8220;#else #if #endif&#8221;, it works the same but you can save some space as you do not need to end with another #endif. If your project has a more complicated release schedule with alpha, beta and production releases you could try this:</p>
<blockquote><p>
#if (!RELEASE)<br />
           Console.WriteLine(&#8221;This is not a release version&#8221;);<br />
    #if (BETA)<br />
          Console.WriteLine(&#8221;Beta, for limited release only&#8221;);<br />
    #eif (ALPHA)<br />
            Console.WriteLine(&#8221;Alpha, for internal testing only&#8221;);<br />
    #endif<br />
#else<br />
           Console.WriteLine(&#8221;Welcome to Widgets 1.0&#8243;);<br />
#endif
</p></blockquote>
<p>As can be seen you can apply several operators to the symbols: ! (not),== (equality), != (inequality), &#038;&#038; (and) and || (or).</p>
<p><a name="D"></a><strong>Avoid the clutter &#8211; use conditional attributes instead</strong></p>
<p>Even a small program has many potential spots where you might like to introduce a debug statement or a log function. If you have to put each of them into a seperate #if DEBUG / #endif block they will start to take up a lot of space in your code. C# has its own slightly more elegant solution to this problem: conditional attributes. They are included in the System.Diagnostics namespace.</p>
<p>In the following program the &#8220;LogLine&#8221; function will only ever run if the &#8220;DEBUG&#8221; symbol has been set.</p>
<pre class="brush: c#">
using System;
using System.Diagnostics;

namespace MyNameSpace
{
    class MainClass
    {
        [ Conditional(&quot;DEBUG&quot;) ]
        public static void LogLine(string msg,string detail)
        {
            Console.WriteLine(&quot;Log: {0} = {1}&quot;,msg,detail);
        }

        public static void Main(string[] args)
        {
            int Total = 0;
            for(int Lp = 1; Lp &lt; 10; Lp++)
            {
                LogLine(&quot;Total&quot;,Total.ToString());
                Total = Total + Lp;
            }
        }
    }
}
</pre>
<p>You can also define combinations chained together with OR to decide if the code is enabled:</p>
<blockquote><p>
        [ Conditional("ALPHA"),Conditional("BETA") ]<br />
        public static void LogLine(string msg,string detail)
</p></blockquote>
<p>Conditionals work differently from the #if/#endif directives that in the above example the &#8220;LogLine&#8221; code will still be included in the assembly. It will never get called however. The compiler will ensure that the LogLine method isn&#8217;t called. In fact if you use a dissasembler (like monodis) the code for Main will look like this:</p>
<pre class="brush: c#">
        public static void Main(string[] args)
        {
            int Total = 0;
            for(int Lp = 1; Lp &lt; 10; Lp++)
                Total = Total + Lp;
        }
</pre>
<p><a name="E"></a><strong>Using #error and #warning during compilation</strong></p>
<p>C# provides the #error and #warning directives to output messages during compilation. As you can expect, if the compiler encounters an #error it will report the problem and stop compiling. The #warning directive just causes a log entry to be displayed in the build output.</p>
<blockquote><p>
#if !DEBUG<br />
    #warning This code is NOT production ready<br />
#endif
</p></blockquote>
<p><a name="F"></a><strong>Generated code builds and error reporting with #line</strong></p>
<p>In regular coding there are not many uses for #line. This directive is mostly useful when you build a code generator that turns one source file into another. Microsoft uses this for example for ASP.NET. Normally if something breaks during such an intermediate step, the compiler would report the error as being in the intermediate file.</p>
<p>The #line directive can force the compiler to report the error as coming from a different line numer, or even a completely different source file.</p>
<pre class="brush: c#">
        public static void Main(string[] args)
        {

#line 250
#if DEBUG
#error This code is NOT production ready
#endif
</pre>
<p>Even though in my original test code the warning was given at line 19 in the source file, the #line directive forces the compiler to report 250 instead.</p>
<p><a name="G"></a><strong>Region Directives</strong></p>
<p>The Visual Studio suite, and the newer MonoDevelop versions allow for outlining of code blocks. You click the little (+) next to the code and it expands the class or method. The #region and #endregion directives allow you to define your own outlined blocks.</p>
<pre class="brush: c#">
#region myregion
        public static void Main(string[] args)
        {
            int Total = 0;
            for(int Lp = 1; Lp &lt; 10; Lp++)
{
                LogLine(&quot;Total&quot;,Total.ToString());
                Total = Total + Lp;
            }
        }
#endregion
</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/csharp-preprocessor-directives-explained/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manipulating Strings in C# -Replacing part of a string / Replacing all occurences of a sub-string</title>
		<link>http://www.dijksterhuis.org/manipulating-strings-in-csharp-replacing-part-string/</link>
		<comments>http://www.dijksterhuis.org/manipulating-strings-in-csharp-replacing-part-string/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 02:04:05 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=637</guid>
		<description><![CDATA[Very often you need to change part of a string, maybe just once, or many times over. Strings in .NET/C# are immutable we cannot actually change a string in-place. But we are able to work on copies. The code example below attaches two new methods to the C# string class.

The ReplaceFirst method replaces the first [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>Very often you need to change part of a string, maybe just once, or many times over. Strings in .NET/C# are immutable we cannot actually change a string in-place. But we are able to work on copies. The code example below attaches two new methods to the C# string class.</p>
<ul>
<li>The ReplaceFirst method replaces the first occurrence of &#8220;needle&#8221; in a string and replaces it with &#8220;replacement&#8221;.</li>
<li>The ReplaceAll function is similar: it steps through the string modifying it each time it finds &#8220;needle&#8221; and replaces it. To avoid a possible infinite loop it first checks whether &#8220;needle&#8221; is equivalent to &#8220;replacement&#8221;.</li>
</ul>
<p><span id="more-637"></span></p>
<pre class="brush: c#">
using System;
using System.Collections;

namespace StringItems
{
        static class StringExt
        {
                public static string ReplaceFirst(this 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);
                }

                public static string ReplaceAll(this 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;
                }

        }
}
</pre>
<p>Both methods are implemented using a class extension. (for more on creating class extensions see also <a href="../manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/">Finding all occurrences of a string within another string</a>) After you include these methods into your project you can call them directly from any string instance:</p>
<blockquote><p>string myString = &#8220;Hello World&#8221;;<br />
string myModifiedString = myString.ReplaceFirst(&#8221;World&#8221;,&#8221;People&#8221;);<br />
Console.WriteLine(&#8221;{0}&#8221;,myModifiedString); // Writes: &#8220;Hello People&#8221;</p></blockquote>
<p>An example use of the ReplaceAll method:</p>
<blockquote><p>string myString = &#8220;boo foo is not foo boo or foo boo foo&#8221;;<br />
string myModifiedString = myString.ReplaceFirst(&#8221;boo&#8221;,&#8221;goo&#8221;);<br />
Console.WriteLine(&#8221;{0}&#8221;,myModifiedString); // Writes: &#8220;goo foo is not foo goo or foo goo foo&#8221;;</p></blockquote>
<p><strong>Why not just use a regular expression?</strong></p>
<p><strong></strong>If you are familiar with the RegEx class in C# you can easily write a regular expression to achieve the same string replacement result:</p>
<blockquote><p>using System.Text.RegularExpressions;<br />
Regex regex = new Regex(&#8221;boo&#8221;);<br />
string result = regex.Replace(&#8221;boo foo is not foo boo or foo boo foo&#8221;, &#8220;goo&#8221;);</p></blockquote>
<p>Regular expressions are flexible and if you do anything more complex than just a basic string replacement they are your only choice. But they come at a hefty performance price. To run a regular expression it needs to be compiled first and then executed. The .NET runtime caches the expression for performance but using a regular expression for string replacement is still much slower.</p>
<p><strong>How much slower are regular expressions for string replacement?</strong></p>
<p>In an earlier post I described <a href="http://www.dijksterhuis.org/timing-function-performance-stopwatch-class/">the Stopwatch class in System.Diagnostics</a>. It is ideal for a little benchmark testing &#8212; so lets compare my string replacement methods with the build-in regular expression library:</p>
<pre class="brush: c#">
string haystack = &quot;boo foo is not foo boo or foo boo foo&quot;;
string result;
Stopwatch sw = Stopwatch.StartNew();
for (int Lp = 0; Lp &lt; 100000; Lp++)
result = regex.Replace($haystack, &quot;goo&quot;);
sw.Stop();
Console.WriteLine(&quot;Time used (float): {0} ms&quot;,sw.Elapsed.TotalMilliseconds);
</pre>
<p><span>And the same for the string replacement functions:</span></p>
<pre class="brush: c#">
string haystack = &quot;boo foo is not foo boo or foo boo foo&quot;;
string result;
Stopwatch sw = Stopwatch.StartNew();
for(int Lp = 0; Lp &lt; 100000; Lp++)
result = haystack.ReplaceAll(&quot;boo&quot;,&quot;goo&quot;);
sw.Stop();
Console.WriteLine(&quot;Time used (float): {0} ms&quot;,sw.Elapsed.TotalMilliseconds);
</pre>
<p>The regular expression code needed <strong>1100ms </strong>, whereas the string replacement code needed just<strong> 27ms</strong>. So for this particular example, the string replacement was <strong>40 times faster</strong> than a regular expression.</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/manipulating-strings-in-csharp-replacing-part-string/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Manipulating Strings in C# &#8211; Finding all occurrences of a string within another string</title>
		<link>http://www.dijksterhuis.org/manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/</link>
		<comments>http://www.dijksterhuis.org/manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 07:57:50 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=633</guid>
		<description><![CDATA[A common programming problem is to find the position of all copies of a string in another string.  For finding the first copy the C# string method IndexOf is similar to the C strpos() function. It returns the first occurrence of a string in another string. But what if you would like to find [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>A common programming problem is to find the position of all copies of a string in another string.  For finding the first copy the C# string method IndexOf is similar to the C strpos() function. It returns the first occurrence of a string in another string. But what if you would like to find the position of all occurances of the substring?  The following &#8220;IndexOfAll&#8221; method does just that. It returns an IEnumerable containing the offsets of each sub-string in the main string.</p>
<p><span id="more-633"></span></p>
<p>Because you might want to use this code throughout your project it is implemented as an Extension class. Simply put: the IndexOfAll method is attached to the String class. So if we want to call it we can just use <string>.IndexOfAll(needle)</p>
<p>To be able to define an extension we need to create a static method and put it into a static class. The first parameter of the method identifies the class the method should associate with. In our case: string. We do this by defining it as &#8220;this string&#8221;.</p>
<pre class="brush: c#">
using System;
using System.Collections;

namespace StringItems
{
    static class StringExt
    {
        public static IEnumerable IndexOfAll(this string haystack, string needle)
        {
            int pos,offset = 0;
            while ((pos = haystack.IndexOf(needle))&gt;0)
            {
                haystack = haystack.Substring(pos+needle.Length);
                offset += pos;
                yield return offset;
            }
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            string needle = &quot;x&quot;;
            string haystack = &quot;3 x 4 = 2 x 6 = 1 x 12&quot;;
            foreach(int Pos in haystack.IndexOfAll(needle))
                Console.WriteLine(&quot;Offset: {0}&quot;,Pos);
        }
    }
}
</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/manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
