<?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; Beginner</title>
	<atom:link href="http://www.dijksterhuis.org/category/csharp/beginner/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>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>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>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>
		<item>
		<title>C# Anonymous types: the Basics</title>
		<link>http://www.dijksterhuis.org/csharp-anonymous-types-basics/</link>
		<comments>http://www.dijksterhuis.org/csharp-anonymous-types-basics/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 12:26:14 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[anonymous]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=617</guid>
		<description><![CDATA[With the introduction of .NET 3.5 C# includes the &#8220;var&#8221; keyword to support anonymous types. One important motivation for this was to make code written with LINQ (Language-Integrated Query) easier to read. So what is an anonymous type? Anonymous types simply mean that you don&#8217;t specify the type &#8212; but let the compiler do it [...]<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>With the introduction of .NET 3.5 C# includes the &#8220;var&#8221; keyword to support anonymous types. One important motivation for this was to make code written with LINQ (Language-Integrated Query) easier to read. So what is an anonymous type? Anonymous types simply mean that you don&#8217;t specify the type &#8212; but let the compiler do it instead.</em></p>
<p><span id="more-617"></span></p>
<p>To understand how LINQ works, and to realize that its more than just syntactic sugar added to C# we first need to review a couple of basic concepts that when combined lead to LINQ.</p>
<p><strong>Simple definitions, simplified</strong></p>
<p>In typical C# you will always carefully spell out your definitions:</p>
<blockquote><p>string MyString = &#8220;Hello World&#8221;;</p></blockquote>
<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>
<blockquote><p>var MyString = &#8220;Hello World&#8221;;</p></blockquote>
<p>The above definition will also create a string variable named &#8220;MyString&#8221;. It is important to note that C# is still strongly typed &#8212; unlike scripted languages such as Visual Basic (or PHP) once you have assigned the variable type it sticks. The following will not work:</p>
<blockquote><p>var MyString2 = &#8220;Hello World&#8221;;<br />
MyString2 = 123; // Nice try, but no banana
</p></blockquote>
<p>The compiler will throw an implicit conversion error as 123 cannot be assigned to a string.</p>
<p>The above was an impressive (if somewhat pointless) example of what an anonymous type is. For simple types such as strings, integers etc anonymous types offer little benefits. It is even possible to argue that it reduces your code readability.</p>
<p><strong>Using anonymous types for creating arrays</strong></p>
<p>We are not limited to simple types – the following example show how we can create an anonymous array of integers:</p>
<blockquote><p>int[] myIntArray = new int[] { 1 , 2 , 3 , 4 , 5 , 6 };<br />
var myIntArrayVar = new [] { 1 , 2 , 3 , 4 , 5 , 6 };
</p></blockquote>
<p>The above two examples are equivalent. You still need to specify that you want to create an array using <em>new</em>. You are however limited by how flexible the compiler is. A mixed array is a little too much and we need to force it down to an object array:</p>
<blockquote><p>var myMixedArray = new [] { 1, &#8220;two&#8221; , 3 , &#8220;four&#8221; , 5 };  // this does NOT work<br />
object[] myMixedArray = new object[] { 1, &#8220;two&#8221; , 3 , &#8220;four&#8221; , 5 }; // this is OK
</p></blockquote>
<p><strong>Saving time and code with anonymous types</strong></p>
<p>One very powerful feature of  anonymous types it that they can save you a lot of work. Instead of having to type out everything explicitly, you can have the compiler infer the definition of a complete class:</p>
<pre class="brush: c#">
using System;
class MainClass
{
        public static void Main(string[] args)
        {
            var Person = new { Name = &quot;Michael&quot;, Age = 23 };
            Console.WriteLine(&quot;Name: {0} Age: {1}&quot;,Person.Name,Person.Age);
        }
}
</pre>
<p>The compiler creates an anonymous definition of a class and assigns to it Name and Age as public fields. We can combine anonymous classes and anonymous arrays to create an Employee data structure. Note that we use a &#8220;Var&#8221; in the ForEach loop. Because we are combining anonymous types it is impossible to determine the correct type to loop over each element in the array. Thankfully we can ask the compiler to fill in the correct iterator type for us:</p>
<pre class="brush: c#">
    using System;
    class MainClass
    {
        public static void Main(string[] args)
        {
            var Person1 = new { Name = &quot;Michael&quot;, Age = 23 };
            var Person2 = new { Name = &quot;Sandra&quot;, Age = 33 };
            var Employees = new [] { Person1, Person2 };

            foreach (var P in Employees)
                Console.WriteLine(&quot;Name: {0} Age: {1}&quot;,P.Name,P.Age);

        }
    }
</pre>
<p>As Employees is an array we can use an iterator to step through it as shown above, but we can just as easily use a for loop:</p>
<pre class="brush: c#">
    using System;
    class MainClass
    {
        public static void Main(string[] args)
        {
            var Person1 = new { Name = &quot;Michael&quot;, Age = 23 };
            var Person2 = new { Name = &quot;Sandra&quot;, Age = 33 };
            var Employees = new [] { Person1, Person2 };

            for(int Lp = 0; Lp &lt; Employees.Length; Lp++)
              Console.WriteLine(&quot;Name: {0} Age: {1}&quot;,Employees[Lp].Name,Employees[Lp].Age);
        }
    }
</pre>
<p><strong>Lambda expressions and anonymous methods</strong></p>
<p>Lambda expressions are an extension of Anonymous Methods which were introduced in C# 2.0  Lambda expressions add a lot of power to C#, but they can be hard to understand. They are however great for small filters than can be passed on to functions as variables as we will see in the following example:</p>
<blockquote><p>Func&lt;int,bool&gt; mySeniorStaffFilter = a => a > 35;<br />
Console.WriteLine(&#8221;36 is senior? {0}&#8221;,mySeniorStaffFilter(36));
</p></blockquote>
<p>The above function can be defined anywhere inside your code. It takes a single integer as a parameter and returns a boolean. The integer is defined as &#8220;a&#8221;, and the function checks whether a is larger than 35.</p>
<p>Using the &#8220;old&#8221; anonymous methods we could have written the above as:</p>
<blockquote><p>Func&lt;int,bool&gt; mySeniorStaffFilter = delegate(int a) { return a > 35; };</p></blockquote>
<p>The Lambda expression syntax is the same, but shorter and this make them slightly easier to understand.</p>
<p><strong>Combining Lambda expressions with Queries</strong></p>
<p>If you have used Intellisense in Visual Studio or the greatly improved object browser in MonoDevelop 2.0 you will discover that with C# 3.0 arrays have a much larger set of methods associated with them. One of these methods is &#8220;Where&#8221;. It takes a filter as an argument ; and then simply applies each member of the array to the filter. If the filter returns &#8220;true&#8221; the value is yielded and returned in a sub-set.</p>
<p>In plain language: If you have an array of employees you can pass mySeniorStaffFilter function to the Where method. It checks every staff member to see if their age is over 35 and then returns an array containing only those members of staff. </p>
<blockquote><p>var SeniorStaff = Employees.Where(s => s.Age > 35);</p></blockquote>
<p>The following code example shows how this works:</p>
<pre class="brush: c#">
   using System;
   using System.Linq;

    class MainClass
    {
        public static void Main(string[] args)
        {
            var Employees = new [] { new { Name = &quot;Michael&quot;, Age = 23 },
                                     new { Name = &quot;Anton&quot;, Age = 43 },
                                     new { Name = &quot;Nadia&quot;, Age = 36 },
                                     new { Name = &quot;Lydia&quot;, Age = 34 } };

            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>From the above you can see that the compiler needs to infers,create and apply several anonymous types to create a working code sample. We thankfully can use &#8220;var&#8221; to specify our SeniorStaff sub-set. Behind the scenes the compiler has created an anonymous IEnumberable for SeniorStaff that contains our Employee records with anonymous staff members. And for the Where method it applied an anonymous delegate to create the correct filter. </p>
<p>And this leads us to the first real &#8220;LINQ&#8221; statement.</p>
<blockquote><p>var SeniorStaff = from S in Employees where S.Age > 35 select S;</p></blockquote>
<p>When you take away the syntactic sugar the C# compiler will build from this the same (or very similar) &#8220;Employees.Where(s => s.Age > 35)&#8221; statement. Using the same anonymous methods, variables and functions as we used earlier.</p>
<p>This took a lot of getting to. It is however important to understand that LINQ is implemented in C# through basic, strongly typed variables and methods.</p>
<p>To keep the complexity of our C# code down the &#8220;var&#8221; keyword was added allowing the programmer to focus on coding the logic of the program instead of having to write long hand type definitions for each variable. </p>
<p><strong>Q. Is var typesafe?</strong></p>
<p>There&#8217;s no concern about type-safety, as the variable created is not dynamic. It&#8217;s just compiler magic and any type unsafe calls you make will get caught.</p>
<p><strong>Q. Is there a performance penalty for using &#8220;var&#8221; ?</strong></p>
<p>The var keyword only tells the compiler to infer the type from the assignment, there&#8217;s no runtime difference, so no, there&#8217;s no penalty performance wise.</p>
<p><strong>Q. On using anonymous definitions in large projects</strong></p>
<p>Anonymous types cannot be shared across assembly boundaries. The compiler ensures that there is at most one anonymous type for a given sequence of property name/type pairs within each assembly. To pass structures between assemblies you will need to properly define them.</p>
<p><strong>References</strong></p>
<p>   1. <a href="http://msdn.microsoft.com/en-us/library/bb308959.aspx">http://msdn.microsoft.com/en-us/library/bb308959.aspx</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/csharp-anonymous-types-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using String.Split and String.Join to build a simple CSV reader and writer in C#</title>
		<link>http://www.dijksterhuis.org/stringsplit-stringjoin-build-simple-csv-reader-writer/</link>
		<comments>http://www.dijksterhuis.org/stringsplit-stringjoin-build-simple-csv-reader-writer/#comments</comments>
		<pubDate>Thu, 05 Feb 2009 07:14:38 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[csv]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=590</guid>
		<description><![CDATA[
Whole programming languages have been designed (*cough* perl) so that we can cut delimited strings into bits and string them back together. For this purpose C# provides the String.Split() and String.Join() functions. You specify how you would like to split or merge the string and they do the work. In this post we look at [...]<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/535944717_08993f62a0_o.jpg" alt="Creating Delimited Strings in C#" title="Creating Delimited Strings in C#" width="500" height="178" class="alignnone size-full wp-image-598" /><br />
<em>Whole programming languages have been designed (*cough* perl) so that we can cut delimited strings into bits and string them back together. For this purpose C# provides the String.Split() and String.Join() functions. You specify how you would like to split or merge the string and they do the work. In this post we look at some common example uses and then put together a simple CSV (comma separated values) parser.</em></p>
<p><span id="more-590"></span><br />
<strong>Cutting a string using a delimiter </strong></p>
<blockquote><p>string Msg = &#8220;1997,Ford,E350,Super luxurious truck&#8221;;</p></blockquote>
<p>The String.Split function allows you to specify one or more separators. If we want to cut the above string at each comma we would do the following:</p>
<pre class="brush: c#">
string Msg = &quot;1997,Ford,E350,Super luxurious truck&quot;;
string[] Data = Msg.Split(new char[] {&#039;,&#039;});
int Cnt = 0;
foreach(string Field in Data)
Console.WriteLine(&quot;{0} = {1}&quot;,Cnt++,Field);
</pre>
<p><em>This outputs: </em></p>
<blockquote><p>0 = 1997<br />
1 = Ford<br />
2 = E350<br />
3 = Super luxurious truck
</p></blockquote>
<p>The split method takes an array of char[] as its parameter. It is possible to specify more than one separator. So if you would like to split a string on both comma&#8217;s and exclamation marks you could do the following:</p>
<pre class="brush: c#">
string Msg = &quot;The world is not enough ! I have one, two, no three! plans for conquering it&quot;;
string[] Data = Msg.Split(new char[] {&#039;,&#039;,&#039;!&#039;});
</pre>
<p>If you specify nothing at all then String.Split() will break on a predefined set of separators. These include spaces (all Unicode defined spaces), line breaks, tabs etc.</p>
<p>If you don&#8217;t want the returned array to contain empty strings, you can specify <em>StringSplitOptions.<span class="selflink">RemoveEmptyEntries</span></em></p>
<pre class="brush: c#">
string Msg = &quot;One,Two,,Four,,,Six,,Eight&quot;;
string[] Data = Msg.Split(new char[] {&#039;,&#039;},StringSplitOptions.RemoveEmptyEntries);
</pre>
<p><strong>Putting things back together again using String.Join()</strong></p>
<p>To quickly put things back together again we just String.Join(), its use is simple: You specify the character you would like to use to join, and pass an array of strings and the first element in the array to use. Lastly it is possible to limit the number of items Joined together.</p>
<blockquote><p>String[] val = {&#8221;ape&#8221;,&#8221;monkey&#8221;,&#8221;lion&#8221;,&#8221;human&#8221;,&#8221;woman&#8221;};<br />
Console.WriteLine(&#8221;{0}&#8221;, String.Join(&#8221;|&#8221;,val,0,4));</p></blockquote>
<p>This results in:</p>
<blockquote><p>ape|monkey|lion|human</p></blockquote>
<p><strong>Building a Comma Separated Values (CSV) reader / writer using String.Split and String.Join</strong></p>
<p>Comma Seperated Values files are created by spreadsheets (such as Excel, OpenOffice Calc), databases (Microsoft Access). They are used to quickly transport data between different programs.   As we can now split input, and put it back together again I have created a very simple CSV reader and writer. It can read and write a CSV file and for good measure display to contents on the console.</p>
<p><em>Note that this reader is very simple, it does not deal with many potential data formatting issues that are perfectly legal for a CSV file. If you intend to import large data sets from databases you will want to create something stronger. </em></p>
<p>To play with this code the following data set provides a little bit of history on Japanese car manufacturers. It contains the name of the company, its founding year, current number of employees and founders name.</p>
<p><em>Data.CSV</em></p>
<blockquote><p>Toyota,1937,316000,Kiichiro Toyoda<br />
Mazda,1920,39364,Jujiro Matsuda<br />
Honda,1948,167231,Soichiro Honda</p></blockquote>
<pre class="brush: c#">
using System;
using System.IO;
using System.Collections;
using System.Text;

namespace consoleoutput
{
	class MainClass
	{

		public static ArrayList ReadCSV(string FileName)
		{
			ArrayList DataRows = new ArrayList();

		    // Create a Streamreader and open the file
		    using (StreamReader sr = new StreamReader(FileName))
            {
                String line;
                // Read lines from the file until the end of
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
					// Skip over empty lines
					if (line.Length == 0) continue;

					// Split the line at the comma
					string[] DataColumn = line.Split(new char[] {&#039;,&#039;});

					// Add the row of data to the ArrayList
					DataRows.Add(DataColumn);
                }
            }

			return DataRows;
		}

		public static void WriteCSV(string FileName, ArrayList CSVData)
		{
		    // Create a StreamWriter and open the file
		    using (StreamWriter sw = new StreamWriter(FileName))
            {
				foreach(string[] CSVRow in CSVData)
				{
					string line = String.Join(&quot;,&quot;,CSVRow);
					sw.WriteLine(line);
				}
			}
		}

		public static void PrintCVS(ArrayList CSVData)
		{
			foreach(string[] CSVRow in CSVData)
			{
				string line = String.Join(&quot;,&quot;,CSVRow);
				Console.WriteLine(line);
			}
		}
		public static void Main(string[] args)
		{
			ArrayList myArrayList = ReadCSV(&quot;/home/martijn/cars.csv&quot;);
			PrintCVS(myArrayList);
			WriteCSV(&quot;/home/martijn/output.csv&quot;,myArrayList);
		}
	}
}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/kacey/">Kacey</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/stringsplit-stringjoin-build-simple-csv-reader-writer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Formatting Strings in C# with String.Format</title>
		<link>http://www.dijksterhuis.org/formatting-strings-stringformat/</link>
		<comments>http://www.dijksterhuis.org/formatting-strings-stringformat/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 09:21:58 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[string.format]]></category>

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

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

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