<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Jaimal Chohan</title>
	<atom:link href="http://jaimalchohan.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jaimalchohan.wordpress.com</link>
	<description></description>
	<lastBuildDate>Mon, 03 Aug 2009 23:05:55 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='jaimalchohan.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/1d927f0431afe41e1aaa91490b1cd54d?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Jaimal Chohan</title>
		<link>http://jaimalchohan.wordpress.com</link>
	</image>
			<item>
		<title>The Cached, Compiled, XSL Web Control</title>
		<link>http://jaimalchohan.wordpress.com/2009/08/03/the-cached-compiled-xsl-web-control/</link>
		<comments>http://jaimalchohan.wordpress.com/2009/08/03/the-cached-compiled-xsl-web-control/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 23:05:55 +0000</pubDate>
		<dc:creator>jaimalchohan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Control]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[Xsl]]></category>
		<category><![CDATA[Xslt]]></category>

		<guid isPermaLink="false">http://jaimalchohan.wordpress.com/?p=26</guid>
		<description><![CDATA[I&#8217;ve decided to kick this blog off again, after much time off, and for my first post &#8230; I&#8217;ll introduce my Cached, Compiled, XSL Web Control. 
Ever used the XSL control?  It looks something like this:

 &#60;asp:Xml ID=&#34;xml1&#34; DocumentSource=&#34;/MyData.xml&#34; TransformSource=&#34;/MyStyle.xsl&#34; /&#62;

I was working on a XML content driven project recently where I had to do many [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=26&subd=jaimalchohan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I&#8217;ve decided to kick this blog off again, after much time off, and for my first post &#8230; I&#8217;ll introduce my Cached, Compiled, XSL Web Control. </p>
<p>Ever used the XSL control?  It looks something like this:</p>
<pre class="brush: xml;">
 &lt;asp:Xml ID=&quot;xml1&quot; DocumentSource=&quot;/MyData.xml&quot; TransformSource=&quot;/MyStyle.xsl&quot; /&gt;
</pre>
<p>I was working on a XML content driven project recently where I had to do many XML transforms on a page, and the above simly did not cut it, for the following reasons:</p>
<ol>
<li>No Caching &#8211; Everytime I want to perform a Transform, the control has to read my XSL from disk</li>
<li>Due to the lack of caching, the XSL has to be compiled for each transform.</li>
<li>Can&#8217;t pass paramaters via markup, they all have to be done via the code behind, which can be slighly more difficult to manage</li>
<li>XML either from disk or via string, why do I have to ToString my XMLDocument/XDocument?</li>
</ol>
<p>Mainly it was the lack of caching that annoyed me</p>
<p>My solution? come up with my own XsltControl</p>
<p>I started off with a basic XsltControl, wrapped a WebControl around it and added caching CompiledTransforms.  Extra support was added for adding paramaters via markup.</p>
<p>So, now, you I can write</p>
<pre class="brush: xml;">
&lt;custom:XsltControl ID=&quot;MyTransform&quot; runat=&quot;server&quot;&gt;
            &lt;custom:Argument Name=&quot;markup&quot; Value=&quot;This text came from a paramater added via markup&quot; /&gt;
            &lt;custom:Argument Name=&quot;resource&quot; meta:resourcekey=&quot;Resource&quot; /&gt;
&lt;/custom:XsltControl&gt;
</pre>
<p>The control also allows you to set the path of a xsl include directory which it will cache and add cache dependencies to the Xsl for, so when the Xsl changes, or an includes file changes the cached version is invalidated and the new version picked up on the next transform.</p>
<h3>Code for XsltControl</h3>
<p><a href="http://jaimalchohan.files.wordpress.com/2009/08/xsltcontrol.doc">XsltControl</a><br />
Visual Studio 2008 Solution. [you'll have to rename the file to .zip]</p>
 Tagged: Caching, Control, XML, Xsl, Xslt <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaimalchohan.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaimalchohan.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaimalchohan.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaimalchohan.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaimalchohan.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaimalchohan.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaimalchohan.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaimalchohan.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaimalchohan.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaimalchohan.wordpress.com/26/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=26&subd=jaimalchohan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaimalchohan.wordpress.com/2009/08/03/the-cached-compiled-xsl-web-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acd3c4998414b55ef98d2430bf119b8f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaimalchohan</media:title>
		</media:content>
	</item>
		<item>
		<title>The GAC</title>
		<link>http://jaimalchohan.wordpress.com/2008/05/15/the-gac/</link>
		<comments>http://jaimalchohan.wordpress.com/2008/05/15/the-gac/#comments</comments>
		<pubDate>Wed, 14 May 2008 23:00:57 +0000</pubDate>
		<dc:creator>jaimalchohan</dc:creator>
				<category><![CDATA[Assemblies]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[GAC]]></category>

		<guid isPermaLink="false">http://www.jchohan.com/?p=25</guid>
		<description><![CDATA[The GAC
Way back as part of .NET 1.1, Microsoft introduced a feature called the Global Assembly Cache, or GAC.  The GAC is a virtual folder which holds references to assemblies on the hard disk.
You can view assemblies in the GAC by navigating to C:\Windows\Assembly (or whatever your root drive is) and what you should [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=25&subd=jaimalchohan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>The GAC</strong></p>
<p>Way back as part of .NET 1.1, Microsoft introduced a feature called the Global Assembly Cache, or GAC.  The GAC is a virtual folder which holds references to assemblies on the hard disk.</p>
<p>You can view assemblies in the GAC by navigating to C:\Windows\Assembly (or whatever your root drive is) and what you should see is a unusual looking folder with lots of assemblies in it. Scroll through and should find all the .NET assemblies as well as a few for other applications you have installed.</p>
<p><a href='http://www.jchohan.com/wp-content/uploads/2008/05/gac_folder.jpg'><img src="http://www.jchohan.com/wp-content/uploads/2008/05/gac_folder.jpg" alt="The GAC" width="495" height="264" class="alignnone size-full wp-image-26" /></a></p>
<p>The GAC can only store CLR assemblies, and as you might have noticed each one has a public key, which suggests that they have been signed.  Each assembly also has a version, and a culture (a blank culture defaults to neutral culture.  Together with the name these 3 pieces of information make up the identity of an individual assembly.</p>
<p>The purpose of the GAC is to allow the sharing of assemblies across multiple applications.  Imagine a scenario where you have 3 applications installed on the same server using a common Utilities assembly, if you added a reference the Utilities assembly to each project individually, then on that server you would have find 3 copies of the assembly, 1 in each bin folder.  By installing the Utilities assembly it the GAC you would only need to have 1 copy.</p>
<p>It may sound a replacement for COM, but it&#8217;s not, the GAC is for .NET assemblies only and.NET applications are the only applications that can directly access an assembly in GAC.  For legacy or non .NET applications you still have to use COM.</p>
<p>When you need multiple applications to use the same assembly then the GAC could be the best place to install it.  You only have 1 copy per server which eases management; you only have to update 1 assembly to update all applications. All the .NET Framework assemblies are installed in GAC, that’s why you never see the .NET Framework assemblies such as the System.dll and System.Collections.dll in your applications bin folder.</p>
<p><strong>Signing</strong></p>
<p>To install an assembly into the GAC you first need to sign it.  This can be done though Visual Studio by going to the Project properties, and clicking on the Signing tab.  There you will have to check the &#8220;Sign the Assembly&#8221; checkbox and then either choose an existing string name key or let Visual Studio create a strong name key for you.</p>
<p><a href='http://www.jchohan.com/wp-content/uploads/2008/05/strongname.jpg'><img src="http://www.jchohan.com/wp-content/uploads/2008/05/strongname.jpg" alt="Strong Name Dialog" width="581" height="198" class="alignnone size-full wp-image-27" /></a></p>
<p>A strong name key consists of a private/public pair.  First a hash of your assembly is created, and then the hash is encrypted with the private key part of.  To distribute the assembly you provide the assembly and the public key to the receiver.  The receiver decrypts the assembly using the public key and generates a hash.  If the hash generated by the receiver matches the hash they decrypted then the assembly can be verified as being un-tampered with.</p>
<p>It may sound like the same as a Digital certificate, but it isn&#8217;t.  Digital certificates are created by a certificate authority who is a trusted party and verifies that a certificate you attach to an assembly belongs to you.  With a strong names there’s nobody to provide that facility and therefore somebody could replace your key with their own, there’s no mechanism to verify who the key belongs to. Knowing this if you plan to distribute an assembly outside of your department or company then you should obtain a digital certificate from a trusted certificate authority.</p>
<p>Another method to create a strong name key is to use the Visual Studio Command Prompt and run the following</p>
<p>sn -k <keyFileName></p>
<p>After you have assigned a key to your project the assembly will be signed when built.</p>
<p><strong>Deployment</strong></p>
<p>Once you have built your assembly you can install it into the GAC by drag-dropping it into the C:\Windows\Assemby folder or by running the following command in the Visual Studio Command Prompt.</p>
<p>gacutil -i <assembly_paht></p>
<p>You can also create a setup project to deploy your assembly via an installer which is a much cleaner method for deployment.</p>
<p><a href='http://www.jchohan.com/wp-content/uploads/2008/05/gac_setupproject.jpg'><img src="http://www.jchohan.com/wp-content/uploads/2008/05/gac_setupproject.jpg" alt="GAC Setup Project" width="581" height="198" class="alignnone size-full wp-image-28" /></a></p>
<p>Once deployed you can use your assembly like any other .NET assembly by adding a reference to it into your .config file:</p>
<pre class="brush: xml;">
&lt;assemblies&gt;
   &lt;add assembly=&quot;&lt;assemblyName&gt;, Version=&lt;version&gt;, Culture=&lt;culture&gt;, PublicKeyToken=&lt;publicKey&gt;&quot;/&gt;
&lt;/assemblies&gt;
</pre>
<p>&#8220;Hold on&#8221;, i hear you say, who adds references manually to their .config file like above?  normally you&#8217;d right click on your references folder in Visual Studio and add it from there.  Unfortunately the Add Reference dialog is not driven from the GAC, its driven from the registry, so you&#8217;ll have to add a registry key for this level of functionality; another reason to use a setup project for deployment.</p>
<p>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\\[Default String Key with value = </p>
<p><strong>Version Management</strong></p>
<p>When you do have a shared assembly, you want to be able to version it, so that in the future you can create a new version and not break the existing one.  Make sure you have a versioning strategy in place, it doesn’t have t be complex, you don’t have to make use of the minor digits, a simple X.0.0.0 version will do.</p>
<p>When you deploy your new version it will be a completely separate install so make sure you&#8217;ve archived your previous version, and the source files to go with it in case a bug crops up in the future that you need to fix.  Your new assembly will not affect the old assembly as long as the version numbers are different.</p>
<p>Once you&#8217;ve deployed the new version you&#8217;ll do 1 of three things.</p>
<p><strong>1.</strong> Use your new version for new applications and let applications using the old version carry on using the old version.</p>
<p><strong>2. </strong>Force some applications on a server to use the new version: In this case you have to add a binding redirect element ton your applications .config file.</p>
<pre class="brush: xml;">
&lt;configuration&gt;
   &lt;runtime&gt;
      &lt;assemblyBinding xmlns=&quot;urn:schemas-microsoft-com:asm.v1&quot;&gt;
         &lt;dependentAssembly&gt;
            &lt;assemblyIdentity name=&quot;&lt;assemblyName&gt;&quot;
                              publicKeyToken=&quot;&lt;publicKey&gt;&quot;
                              culture=&quot;&lt;culture&gt;&quot; /&gt;
            &lt;bindingRedirect oldVersion=&quot;1.0.0.0&quot;
                             newVersion=&quot;2.0.0.0&quot;/&gt;
         &lt;/dependentAssembly&gt;
      &lt;/assemblyBinding&gt;
   &lt;/runtime&gt;
&lt;/configuration&gt;
</pre>
<p><strong>3. </strong>Force all applications on a server to use the new version (only likely to do this if a version is backwards compatible):  You&#8217;ll have configure this using the Microsoft .NET Framework Configuration Tool via Control Panel &gt; Administration Tools.</p>
<p>Expand the My Computer node, expand the Configured Assemblies Node, click on Configure and Assembly and then choose an Assembly to configure.  This will add the Assembly to the list of Configured Assemblies and from here you can set the binding policy.</p>
<p><a href='http://www.jchohan.com/wp-content/uploads/2008/05/bindingpolicy.jpg'><img src="http://www.jchohan.com/wp-content/uploads/2008/05/bindingpolicy.jpg" alt="Binding Policy Dialog" width="488" height="304" class="alignnone size-full wp-image-29" /></a></p>
<p>As you can see, the GAC is a very handy feature and easy to use, if you need to deploy an assembly which will be shared by multiple applications, then the GAC is the way to go.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaimalchohan.wordpress.com/25/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaimalchohan.wordpress.com/25/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaimalchohan.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaimalchohan.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaimalchohan.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaimalchohan.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaimalchohan.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaimalchohan.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaimalchohan.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaimalchohan.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaimalchohan.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaimalchohan.wordpress.com/25/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=25&subd=jaimalchohan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaimalchohan.wordpress.com/2008/05/15/the-gac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acd3c4998414b55ef98d2430bf119b8f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaimalchohan</media:title>
		</media:content>

		<media:content url="http://www.jchohan.com/wp-content/uploads/2008/05/gac_folder.jpg" medium="image">
			<media:title type="html">The GAC</media:title>
		</media:content>

		<media:content url="http://www.jchohan.com/wp-content/uploads/2008/05/strongname.jpg" medium="image">
			<media:title type="html">Strong Name Dialog</media:title>
		</media:content>

		<media:content url="http://www.jchohan.com/wp-content/uploads/2008/05/gac_setupproject.jpg" medium="image">
			<media:title type="html">GAC Setup Project</media:title>
		</media:content>

		<media:content url="http://www.jchohan.com/wp-content/uploads/2008/05/bindingpolicy.jpg" medium="image">
			<media:title type="html">Binding Policy Dialog</media:title>
		</media:content>
	</item>
		<item>
		<title>Asynchronous Programming Part 2 &#8211; Threading</title>
		<link>http://jaimalchohan.wordpress.com/2008/05/13/asynchronous-programming-part-2-threading/</link>
		<comments>http://jaimalchohan.wordpress.com/2008/05/13/asynchronous-programming-part-2-threading/#comments</comments>
		<pubDate>Tue, 13 May 2008 19:49:52 +0000</pubDate>
		<dc:creator>jaimalchohan</dc:creator>
				<category><![CDATA[Asynchronous]]></category>
		<category><![CDATA[Delegates]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://jchohan.com/?p=24</guid>
		<description><![CDATA[Threading
If you don&#8217;t know what a process is, click Crtl + Shift + Esc to bring up the task manager, click on the processes tab and you&#8217;ll see all the processes running on your PC (You might need to uncheck &#8220;Show processes from all users&#8221; to see all of the processes).
A process is a programs [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=24&subd=jaimalchohan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>Threading</strong></p>
<p>If you don&#8217;t know what a process is, click Crtl + Shift + Esc to bring up the task manager, click on the processes tab and you&#8217;ll see all the processes running on your PC (You might need to uncheck &#8220;Show processes from all users&#8221; to see all of the processes).</p>
<p>A process is a programs container to which the operating system assigns security privileges, memory and processing priority (as well as a few other things).  Open up Microsoft Word and you&#8217;ll see the WORD process pop up on the list.</p>
<p>In the Task Manager click on View, on the toolbar, select Columns, check Thread Count and click OK. You&#8217;ll see a new column displaying the number of threads contained within a process.  The threads are what actually execute code, and most applications will have several threads running.  For example Microsoft Word might have 1 thread for the window where you type another listening for events (clicking an icon, typing a character etc).   It might also have some sleeping threads, threads waiting for something to occur, for example Word will auto-save your document every 5 minutes, As auto-saving doesn’t happen all the time, Word might put this into a Wait state (Sleep) until required.</p>
<p>Multi-threading allows Microsoft Word to provide you with a responsive experience, where a lot of processing occurs, but you would never tell from the speed of the application.</p>
<p>Threading in .NET allows you to create your own multi-threaded applications so your users can have a smoother user experience, and you can make better use of your processor.</p>
<p>Lets jump into an example.</p>
<p>public static class Program<br />
{<br />
    public static void Main()<br />
    {<br />
        SimpleThreadingDemo simple = new SimpleThreadingDemo();<br />
        simple.FirstThread();<br />
        Console.ReadLine();<br />
    }<br />
}</p>
<p>internal class SimpleThreadingDemo<br />
{<br />
    public void FirstThread()<br />
    {<br />
        ThreadStart ts = new ThreadStart(DoWork);<br />
        Thread newThread = new Thread(ts);<br />
        newThread.Start();<br />
        Console.WriteLine(&#8220;First Thread&#8221;);</p>
<p>    }</p>
<p>    private void DoWork()<br />
    {<br />
        Console.WriteLine(&#8220;Second Thread&#8221;);<br />
    }<br />
}</p>
<p>See that delegate.  Arn&#8217;t you glad you <a href="http://www.jchohan.com/2008/04/26/asynchronous-programming-part-1-delegates/">read Part 1 now</a>?</p>
<p>You&#8217;ll also notice as were doing 2 things at the same time, they&#8217;re running asynchronously!  Although it’s not truly Asynchronous programming as DoWork() can&#8217;t return data to FirstThread().</p>
<p>Lets do something slightly more intresting</p>
<p>public static class Program<br />
{<br />
    public static void Main()<br />
    {<br />
        SimpleThreadingDemo simple = new SimpleThreadingDemo();<br />
        simple.FirstThread();<br />
        Console.ReadLine();<br />
    }<br />
}</p>
<p>internal class SimpleThreadingDemo<br />
{<br />
    public void FirstThread()<br />
    {<br />
        ThreadStart ts = new ThreadStart(DoWork);<br />
        Thread newThread = new Thread(ts);<br />
        newThread.Start();<br />
        for (int i = 0; i < 10; i++)<br />
        {<br />
            Console.WriteLine(&#8220;First  Thread: {0}&#8221;, DateTime.Now.Ticks);<br />
            Thread.Sleep(100);<br />
        }</p>
<p>    }</p>
<p>    private void DoWork()<br />
    {<br />
        for (int i = 0; i < 10; i++)<br />
        {<br />
            Console.WriteLine(&#8220;Second Thread: {0}&#8221;, DateTime.Now.Ticks);<br />
            Thread.Sleep(100);<br />
        }<br />
    }<br />
}</p>
<p>When you run this you&#8217;ll see that both threads are defiantly running at the same time, and if you have a fairly modern CPU (Dual/Quad Core or Hyper Threaded) you&#8217;ll see that some of the messages get written to the console screen at exactly the same time!</p>
<p>You&#8217;ll notice the Thread.Sleep method.  This method pauses the thread for the specified number of seconds.  What&#8217;s important to remember here is that it will only pause the current thread (the that thread which executes that line of code).  You can&#8217;t call Sleep on other threads.</p>
<p><strong>Parameters</strong></p>
<p>What if we wanted to pass some data to the DoWork method? Use the ParameterizedThreadStart delegate.</p>
<p>public static class Program<br />
{<br />
    public static void Main()<br />
    {<br />
        SimpleThreadingDemo simple = new SimpleThreadingDemo();<br />
        simple.FirstThread();<br />
        Console.ReadLine();<br />
    }<br />
}</p>
<p>internal class SimpleThreadingDemo<br />
{<br />
    public void FirstThread()<br />
    {<br />
        ParameterizedThreadStart ts = new ParameterizedThreadStart(DoWork);<br />
        Thread newThread = new Thread(ts);<br />
        newThread.Start(&#8220;This String Will be Cast Into an Object&#8221;);<br />
        for (int i = 0; i < 10; i++)<br />
        {<br />
            Console.WriteLine(&#8220;First  Thread&#8221;);<br />
            Thread.Sleep(100);<br />
        }</p>
<p>    }</p>
<p>    private void DoWork(object myObject)<br />
    {<br />
        string s = (string)myObject;</p>
<p>        for (int i = 0; i < 10; i++)<br />
        {<br />
            Console.WriteLine(s);<br />
            Thread.Sleep(100);<br />
        }<br />
    }<br />
}</p>
<p>Hopefully you will have noticed above that I had to pass the parameter as an object.  With ParameterizedThreadStart you can only pass 1 parameter and it has to be an object type. Personally I really dislike passing objects as parameters but there’s no other option here.</p>
<p><strong>Locking</strong></p>
<p>When running a muti-threaded application, special care must be taken when modifying shared data.  For example imagine you had a counter which was incremented every time a method was called.  Being multi-threaded it&#8217;s likely that the method will be called twice (or more) at exactly the same time, in which case your counter might not work as intended.</p>
<p>public static class Program<br />
{<br />
    public static void Main()<br />
    {<br />
        SimpleThreadingDemo simple = new SimpleThreadingDemo();<br />
        simple.FirstThread();<br />
        Console.ReadLine();<br />
    }<br />
}</p>
<p>internal class SimpleThreadingDemo<br />
{<br />
    public void FirstThread()<br />
    {<br />
        Thread[] threads = new Thread[10];<br />
	SharedCounter shared = new SharedCounter()</p>
<p>        for (int looper = 0; looper < 10; looper++)<br />
        {<br />
            Thread th = new Thread(new ThreadStart(shared.Increment));<br />
            threads[looper] = th;<br />
            th.Start();<br />
        }</p>
<p>        for (int looper = 0; looper < 10; looper++)<br />
        {<br />
            threads[looper].Join();<br />
        }</p>
<p>        Console.WriteLine(&#8220;Value is: &#8221; + shared.counter);<br />
    }<br />
}</p>
<p>internal class SharedCounter<br />
{<br />
    public int counter;</p>
<p>    public void Increment()<br />
    {<br />
        for (int i = 0; i < 100000; i++)<br />
        {<br />
            counter += 1;<br />
        }<br />
        Console.WriteLine(&#8220;Finished a loop&#8221;);<br />
    }<br />
}</p>
<p>10 threads are created; each one executes the increment method on the same SharedCounter instance. This means that the counter variable is effectively shared between them</p>
<p>The above code created 10 threads and each thread calls a method which increments the counter 100,000 times.  The result we expect is 100,000 x 10 = 1,000,000, but it’s not.</p>
<p>That’s because the counter variable is stored in memory somewhere, and every time a thread needs to increment it, it has to retrieve the value from memory, add 1, and save it again.  If during this process another thread retrieves the value from memory, then it will overwrite what the previous thread saved.</p>
<p>Using the Join() method on the threads above tells the main thread (the thread which had to run the loop to create the 10 threads) to wait until each thread is finished.  If we don&#8217;t include this then the value of counter will be displayed before all the threads have finished executing (try it).</p>
<p>How can we solve this?  By using the Interlocked.Increment method.</p>
<p>internal class SharedCounter<br />
{<br />
    public int counter;</p>
<p>    public void Increment()<br />
    {<br />
        for (int i = 0; i < 100000; i++)<br />
        {<br />
            Interlocked.Increment(ref counter);<br />
        }<br />
        Console.WriteLine(&#8220;Finished a loop&#8221;);<br />
    }<br />
}</p>
<p>When a thread attempts to increment counter, a lock will be created on counter variable, and all other threads will have to queue up and wait until it is unlocked.  Now when we run the code, we get the desired result.</p>
<p>There&#8217;s a limitation in using Interlocked.Increment() in that it only works with integers.  What if we need to modify a string, or any other object instead of just an int?  In this situation we need to use a Synchronization (Sync) Lock.</p>
<p>internal class SharedCounter<br />
{<br />
    public int counter;</p>
<p>    public void Increment()<br />
    {<br />
        lock (this)<br />
        {<br />
            for (int i = 0; i < 100000; i++)<br />
            {<br />
                counter++;<br />
            }<br />
        }<br />
        Console.WriteLine(&#8220;Finished a loop&#8221;);<br />
    }<br />
}</p>
<p>This time, as soon as a thread gets to the lock(this) keyword, the first thread creates a lock on the entire object (SharedCounter) until the end of the lock is reached. When the next thread reaches the lock keyword, it will wait until the object is unlocked.</p>
<p>Under the covers the lock keyword uses the Monitor class to perform its task, and if you need a greater amount of control, then the Monitor class allows you to specify timeouts for locks and allows you to reacquire a lock after you lose it.  Its unlikely that you&#8217;ll ever need this amount of control in your day to day coding, but its good know.</p>
<p>internal class SharedCounter<br />
{<br />
    public int counter;</p>
<p>    public void Increment()<br />
    {<br />
        Monitor.Enter(this);<br />
        try<br />
        {<br />
            for (int i = 0; i < 100000; i++)<br />
            {<br />
                counter++;<br />
            }<br />
        }<br />
        finally<br />
        {<br />
            Monitor.Exit(this);<br />
        }<br />
       Console.WriteLine(&#8220;Finished a loop&#8221;);<br />
    }<br />
}</p>
<p>If the code within the try&#8230; catch were to throw an exception then the lock would never be released, hence the try&#8230; catch.. finally&#8230; block.</p>
<p><strong>Thread Pool</strong></p>
<p>All the above code samples involve you creating your own threads.  What if your multi-thread application had hundreds of users logged on at the same time?  Then you&#8217;d be creating hundreds of threads and as you might imagine this would decrease the performance of your application as each thread requires processor time to execute.  You&#8217;d probably have to create a class to limit the number of threads created, and if all threads are being used then queue up work so it can be executed once a thread becomes available.  That’s what the ThreadPool does.</p>
<p>To use the ThreadPool you do the following</p>
<p>private void ThreadPool(object sender, EventArgs e)<br />
{<br />
     ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), 20);<br />
}</p>
<p>It’s that easy.</p>
<p>The default maximum number of threads is 20, to change this you can add the following into your web.config.</p>
<p><system.web></p>
<processModel minWorherThreads="5" maxWorkerThreads="20" minIoThreads="20" maxIoThreads="100" />
</system.web></p>
<p>IO threads as the name suggests are used for IO operations (e.g. reading/writing to disk) and generally you&#8217;ll have more IO threads than worker threads.  There’s no magic formula for calculating the best number of Threads for your application, it’s a case of testing and tweaking to an individual applications needs.</p>
<p>There is one slight caveat when using the ThreadPool, all of the threads are created as background threads (the Thread.IsBackground property is set to true).  What this means is that if the thread which created those background threads, the main thread, ends or aborts then the background threads will also be aborted and will never be executed.  For example, if your web page completes all its processing and returns to the user before you’ve done the work on the ThreadPool thread.  To avoid this it’s best to perform short operations on background threads and use normal threads ( foreground threads) for more time consuming or critical work.</p>
<p>That’s it for part 2 of Asynchronous Programming, in the final part I&#8217;ll combine Threading, Delegates and Events to show of the Asynchronous Programming model.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaimalchohan.wordpress.com/24/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaimalchohan.wordpress.com/24/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaimalchohan.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaimalchohan.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaimalchohan.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaimalchohan.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaimalchohan.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaimalchohan.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaimalchohan.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaimalchohan.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaimalchohan.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaimalchohan.wordpress.com/24/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=24&subd=jaimalchohan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaimalchohan.wordpress.com/2008/05/13/asynchronous-programming-part-2-threading/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acd3c4998414b55ef98d2430bf119b8f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaimalchohan</media:title>
		</media:content>
	</item>
		<item>
		<title>Custom Configuration Sections</title>
		<link>http://jaimalchohan.wordpress.com/2008/04/29/custom-configuration-sections/</link>
		<comments>http://jaimalchohan.wordpress.com/2008/04/29/custom-configuration-sections/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 22:45:41 +0000</pubDate>
		<dc:creator>jaimalchohan</dc:creator>
				<category><![CDATA[Configuration]]></category>

		<guid isPermaLink="false">http://jchohan.com/?p=22</guid>
		<description><![CDATA[
Custom configuration sections were revamped in .net 2.0 and are a great way to validate and manage your applications configuration with a minimal amount of work.


Instead of storing multiple keys in the  you can consolidate your keys into their own cleaner and clearer section.  Consider the following section.  This is a really [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=21&subd=jaimalchohan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>
Custom configuration sections were revamped in .net 2.0 and are a great way to validate and manage your applications configuration with a minimal amount of work.
</p>
<p>
Instead of storing multiple keys in the  you can consolidate your keys into their own cleaner and clearer section.  Consider the following section.  This is a really simple example, the below appSettings would likely contain a mix of other keys.
</p>
<pre class="brush: xml;">
&lt;appSettings&gt;
	&lt;add key=&quot;euTax&quot; value=&quot;on&quot; /&gt;
	&lt;add key=&quot;euRate&quot; value=&quot;15&quot; /&gt;
	&lt;add key=&quot;euName&quot; value=&quot;Tax&quot; /&gt;
	&lt;add key=&quot;euTaxRegion&quot; value=&quot;Europe&quot; /&gt;

	&lt;add key=&quot;ukTax&quot; value=&quot;off&quot; /&gt;
	&lt;add key=&quot;ukRate&quot; value=&quot;17.5&quot; /&gt;
	&lt;add key=&quot;ukName&quot; value=&quot;VAT&quot; /&gt;
	&lt;add key=&quot;ukTaxRegion&quot; value=&quot;UK&quot; /&gt;

	&lt;add key=&quot;usTax&quot; value=&quot;on&quot; /&gt;
	&lt;add key=&quot;usRate&quot; value=&quot;10&quot; /&gt;
	&lt;add key=&quot;usName&quot; value=&quot;Tax&quot; /&gt;
	&lt;add key=&quot;usTaxRegion&quot; value=&quot;WorldWide&quot; /&gt;
&lt;/appSettings&gt;
</pre>
<p>
This would be better if it was condensed into</p>
<pre class="brush: xml;">
&lt;taxSettings&gt;
	&lt;euTax mode=&quot;on&quot; rate=&quot;15&quot; name=&quot;Tax&quot; taxRegion =&quot;Europe&quot;/&gt;
	&lt;ukTax mode=&quot;off&quot; rate=&quot;17.5&quot; name=&quot;VAT&quot; taxRegion =&quot;UK&quot; /&gt;
	&lt;usTax mode=&quot;on&quot; rate=&quot;10&quot; name=&quot;Tax&quot; taxRegion =&quot;WorldWide&quot; /&gt;
&lt;/taxSettings&gt;
</pre>
<p>
It’s clear that the TaxSettings configuration is a lot easier to read than the appSettings.  Its also easier to manage and maintain.
</p>
<p>
With appSettings, if a key was missing how would you handle that?  You’d have to create a class to access the keys, throw exceptions if required key is missing, write code to use default values if a non-required key was missing; essentially create your own Configuration Management Class.
</p>
<p>
.Net alrady hs this built it! By inheriting the ConfigurationSection and ConfigurationElement types, you can let .Net do a lot of the work for you.
</p>
<p><b>Step 1 &#8211; Create classes to represent your config data</b></p>
<p>
its pretty much your standard class format.  I&#8217;ve defined a TaxSettings class almost as a base for each countries tax settings, and then in the TaxConfiguration class i&#8217;ve defined TaxSettings for EuTax, UkTax and UsTax.
</p>
<p>public class TaxConfiguration<br />
{<br />
    public TaxSetting EuTax<br />
    {<br />
        get { return ; }<br />
    }</p>
<p>    public TaxSetting UkTax<br />
    {<br />
        get { return ; }<br />
    }</p>
<p>    public TaxSetting UsTax<br />
    {<br />
        get { return ; }<br />
    }<br />
}</p>
<p>public class TaxSetting<br />
{<br />
    public Mode Mode<br />
    {<br />
        get { return ; }<br />
    }</p>
<p>    public string Name<br />
    {<br />
        get { return ; }<br />
    }</p>
<p>    public decimal Rate<br />
    {<br />
        get { return ; }<br />
    }</p>
<p>    public TaxRegionType TaxRegion<br />
    {<br />
        get { return ; }<br />
    }<br />
}</p>
<p>public enum TaxRegionType<br />
{<br />
    UK,<br />
    Europe,<br />
    WorldWide<br />
}</p>
<p>public enum Mode<br />
{<br />
    On,<br />
    Off<br />
}</p>
<p><b>Step 2 &#8211; Inherit &amp; Decorate</b></p>
<p>
Your the class which will represent your root node should inherit from ConfigurationSection<br />
, with other classes which represent child nodes inheriting from ConfigurationElement.
</p>
<p>
Decorate each property you want to retrive from the config with ConfigurationProperty, defining the name of the node or attribute that you will use in the .config file.  .Net will automagically map your .config file to your custom classes, to return a particular item just return this["nameOfyourNode"] and cast it to the appropriate type.  (nameOfYourNode = the same name you used in the attribute)
</p>
<p>
The ConfigurationProperty has a number of parameters including DefaultValue and IsRequired which you can set too.  I&#8217;ve also included a StringValidator on one of the attributes, theres a Regex Validator and IntValidator avaliable to use too you can even create your own!
</p>
<p>public class TaxConfiguration : ConfigurationSection<br />
{<br />
    [ConfigurationProperty("euTax")]<br />
    public TaxSetting EuTax<br />
    {<br />
        get { return (TaxSetting)this["euTax"]; }<br />
    }</p>
<p>    [ConfigurationProperty("ukTax")]<br />
    public TaxSetting UkTax<br />
    {<br />
        get { return (TaxSetting)this["ukTax"]; }<br />
    }</p>
<p>    [ConfigurationProperty("usTax")]<br />
    public TaxSetting UsTax<br />
    {<br />
        get { return (TaxSetting)this["usTax"]; }<br />
    }<br />
}</p>
<p>public class TaxSetting : ConfigurationElement<br />
{<br />
    [ConfigurationProperty("mode", DefaultValue = Mode.On, IsRequired = false)]<br />
    public Mode Mode<br />
    {<br />
        get { return (Mode)this["mode"]; }<br />
    }</p>
<p>    [ConfigurationProperty("name", IsRequired = true)]<br />
    [StringValidator(MaxLength=10, InvalidCharacters="?@~#%$£&#038;*()!_-'£")]<br />
    public string Name<br />
    {<br />
        get { return (string)this["name"]; }<br />
    }</p>
<p>    [ConfigurationProperty("rate", IsRequired = true)]<br />
    public decimal Rate<br />
    {<br />
        get { return (decimal)this["rate"]; }<br />
    }</p>
<p>    [ConfigurationProperty("taxRegion", IsRequired = true)]<br />
    public TaxRegionType TaxRegion<br />
    {<br />
        get { return (TaxRegionType)this["taxRegion"]; }<br />
    }<br />
}</p>
<p>public enum TaxRegionType<br />
{<br />
    UK,<br />
    Europe,<br />
    WorldWide<br />
}</p>
<p>public enum Mode<br />
{<br />
    On,<br />
    Off<br />
}</p>
<p><b>Step 3 &#8211; Configure Your .Config</b></p>
<p>
Add a configSection to your .config, the name can be anything you want and will be use to map to the class derived from ConfigurationSection (TaxConfiguration in our case), the type consists of 2 parts, the first is the full name of the class deriving from ConfigurationSection, the second is the name of the Assembly (you can get this from the project properties dialog)
</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;

&lt;configuration&gt;
    &lt;configSections&gt;
        &lt;section name=&quot;TaxSettings&quot; type=&quot;ConfigurationTest.TaxConfiguration, ConfigurationTest&quot; /&gt;
    &lt;/configSections&gt;

    &lt;taxSettings&gt;
        &lt;euTax mode=&quot;On&quot; rate=&quot;15&quot; name=&quot;Tax&quot; taxRegion =&quot;Europe&quot;/&gt;
        &lt;ukTax mode=&quot;Off&quot; rate=&quot;17.5&quot; name=&quot;VAT&quot; taxRegion =&quot;UK&quot; /&gt;
        &lt;usTax mode=&quot;On&quot; rate=&quot;10&quot; name=&quot;Tax&quot; taxRegion =&quot;WorldWide&quot; /&gt;
    &lt;/taxSettings&gt;
&lt;/configuration&gt;
</pre>
<p><b>Step 4: Access your Custom Configuration</b></p>
<p>
What I usually do is wrap this up in a static class (as static properties) so that I don&#8217;t have to cast the ConfigSection to my type every time I want to access the data.
</p>
<p>class Program<br />
{<br />
    static void Main(string[] args)<br />
    {<br />
        //You could do this everytime you needed to access the config data<br />
        decimal UkTaxRate = ((TaxConfiguration)ConfigurationManager.GetSection(&#8220;TaxSettings&#8221;)).UkTax.Rate;</p>
<p>        //Or you could do this, by creating a static class as below<br />
        string taxName = MyConfiguration.EuTaxSettings.Name;<br />
    }</p>
<p>}</p>
<p>public static class MyConfiguration<br />
{<br />
    public static TaxSetting EuTaxSettings<br />
    {<br />
        get { return ((TaxConfiguration)ConfigurationManager.GetSection(&#8220;TaxSettings&#8221;)).EuTax; }<br />
    }</p>
<p>    public static TaxSetting UkTaxSettings<br />
    {<br />
        get { return ((TaxConfiguration)ConfigurationManager.GetSection(&#8220;TaxSettings&#8221;)).UkTax; }<br />
    }</p>
<p>    public static TaxSetting UsTaxSettings<br />
    {<br />
        get { return ((TaxConfiguration)ConfigurationManager.GetSection(&#8220;TaxSettings&#8221;)).UsTax; }<br />
    }<br />
}</p>
<p><b>Collections</b></p>
<p>
What I&#8217;ve done above is okay, but it&#8217;s not easy to extend.  Every time I wasnt to add a new country Ill have to create new properties in the TaxConfiguration and MyConiguration classes.  What I&#8217;d rather do is have the following fomat so I don&#8217;t have to edit my Configuration handlers every time I need to add a new country:
</p>
<pre class="brush: xml;">
&lt;taxSettings&gt;
    &lt;settings&gt;
        &lt;add key=&quot;EU&quot; mode=&quot;On&quot; rate=&quot;15&quot; name=&quot;Tax&quot; taxRegion =&quot;Europe&quot;/&gt;
        &lt;add key=&quot;UK&quot; mode=&quot;Off&quot; rate=&quot;17.5&quot; name=&quot;VAT&quot; taxRegion =&quot;UK&quot; /&gt;
        &lt;add key=&quot;US&quot; mode=&quot;On&quot; rate=&quot;10&quot; name=&quot;Tax&quot; taxRegion =&quot;WorldWide&quot; /&gt;
    &lt;/settings&gt;
&lt;/taxSettings&gt;
</pre>
<p>
To do this were going to have to inheirt from ConfigurationElementCollection. The complete modified class is below.
</p>
<p>class Program<br />
{<br />
    static void Main(string[] args)<br />
    {<br />
        string taxName = MyConfiguration.TaxSettings["EU"].Name;<br />
    }</p>
<p>}</p>
<p>public static class MyConfiguration<br />
{<br />
    public static TaxSettingsCollection TaxSettings<br />
    {<br />
        get { return ((TaxConfiguration)ConfigurationManager.GetSection(&#8220;TaxSettings&#8221;)).TaxSettingsCollection; }<br />
    }<br />
}</p>
<p>public class TaxConfiguration : ConfigurationSection<br />
{<br />
    [ConfigurationProperty("Settings", IsDefaultCollection=false)]<br />
    [ConfigurationCollection(typeof(TaxSetting))]<br />
    public TaxSettingsCollection TaxSettingsCollection<br />
    {<br />
        get { return (TaxSettingsCollection)this["Settings"]; }<br />
    }<br />
}</p>
<p>public class TaxSettingsCollection : ConfigurationElementCollection<br />
{<br />
    [ConfigurationProperty("euTax")]<br />
    public TaxSetting EuTax<br />
    {<br />
        get { return (TaxSetting)this["euTax"]; }<br />
    }</p>
<p>    public TaxSetting this[int index]<br />
    {<br />
        get { return (TaxSetting)BaseGet(index); }<br />
    }</p>
<p>    public TaxSetting this[string key]<br />
    {<br />
        get {<br />
                for(int i = 0; i < Count; i++)<br />
                    if (this[i].Key == key)<br />
                        return this[i];<br />
                throw new KeyNotFoundException();<br />
            }<br />
    }</p>
<p>    protected override object GetElementKey(ConfigurationElement element)<br />
    {<br />
        return ((TaxSetting)element).Key;<br />
    }</p>
<p>    protected override ConfigurationElement CreateNewElement()<br />
    {<br />
        return new TaxSetting();</p>
<p>    }<br />
}</p>
<p>public class TaxSetting : ConfigurationElement<br />
{<br />
    [ConfigurationProperty("key", IsRequired=true, IsKey=true)] //note the use of IsKey<br />
    public string Key<br />
    {<br />
        get { return (string)this["key"]; }<br />
    }</p>
<p>    [ConfigurationProperty("mode", DefaultValue = Mode.On, IsRequired = false)]<br />
    public Mode Mode<br />
    {<br />
        get { return (Mode)this["mode"]; }<br />
    }</p>
<p>    [ConfigurationProperty("name", IsRequired = true)]<br />
    [StringValidator(MaxLength=10, InvalidCharacters="?@~#%$£&#038;*()!_-'£")]<br />
    public string Name<br />
    {<br />
        get { return (string)this["name"]; }<br />
    }</p>
<p>    [ConfigurationProperty("rate", IsRequired = true)]<br />
    public decimal Rate<br />
    {<br />
        get { return (decimal)this["rate"]; }<br />
    }</p>
<p>    [ConfigurationProperty("taxRegion", IsRequired = true)]<br />
    public TaxRegionType TaxRegion<br />
    {<br />
        get { return (TaxRegionType)this["taxRegion"]; }<br />
    }<br />
}</p>
<p>public enum TaxRegionType<br />
{<br />
    UK,<br />
    Europe,<br />
    WorldWide<br />
}</p>
<p>public enum Mode<br />
{<br />
    On,<br />
    Off<br />
}</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaimalchohan.wordpress.com/21/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaimalchohan.wordpress.com/21/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaimalchohan.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaimalchohan.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaimalchohan.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaimalchohan.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaimalchohan.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaimalchohan.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaimalchohan.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaimalchohan.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaimalchohan.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaimalchohan.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=21&subd=jaimalchohan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaimalchohan.wordpress.com/2008/04/29/custom-configuration-sections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acd3c4998414b55ef98d2430bf119b8f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaimalchohan</media:title>
		</media:content>
	</item>
		<item>
		<title>.NET XML Serialization &amp; T-SQL XML &#8211; DateTime</title>
		<link>http://jaimalchohan.wordpress.com/2008/04/29/net-xml-serialization-t-sql-xml-datetime/</link>
		<comments>http://jaimalchohan.wordpress.com/2008/04/29/net-xml-serialization-t-sql-xml-datetime/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 20:07:36 +0000</pubDate>
		<dc:creator>jaimalchohan</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://jchohan.com/?p=21</guid>
		<description><![CDATA[Today whilst trying to validate an XML document in Sql Server 2005, which had been passed in as a paramater from .Net, I came accross an issue with DateTime serialization.
XML Date Time Sepcification

The W3C XML Schema Scpeification specifies that a valid datetime is the following


2008-04-28T22:45:32+01:00


The first portion before the &#8216;T&#8217; is obviously the date.  [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=23&subd=jaimalchohan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Today whilst trying to validate an XML document in Sql Server 2005, which had been passed in as a paramater from .Net, I came accross an issue with DateTime serialization.</p>
<p><p><strong>XML Date Time Sepcification</strong></p>
<p>
The W3C XML Schema Scpeification specifies that a valid datetime is the following
</p>
<p>
2008-04-28T22:45:32+01:00
</p>
<p>
The first portion before the &#8216;T&#8217; is obviously the date.  The second portion consists of the UTC time, plus an offset value.  This allows times to be compared around in a standard manner, with the ability to obtain the local time.  +01:00 means UTC+1, or British Summer Time for us in the UK.
</p>
<p>
Instead of having an offset of +00:00 for a UTC time with no offset, the specification allow for this to be replaced with a Z, so that
</p>
<p>
2008-04-28T22:45:32+00:00
</p>
<p>
becomes
</p>
<p>
2008-04-28T22:45:32Z
</p>
<p>
In addition, the scpeification allows for fractional seconds, so that a precise UTC+0 datetime can be represented as
</p>
<p>
2008-04-28T22:45:32.1845Z
</p>
<p>
<strong>Where does .Net &amp; SQL fit into all of this?</strong>
</p>
<p>
Well, imagine like me you want to take advantage of the XML schema feature of Sql Server 2005.  You can create a schema, register it within 2005 and then rather than pass in individual paramaters to a stored procedure, you can pass in an XML document.
</p>
<p>
Consider the implications this has when inserting data like a Shopping Bag object.  Typically you would insert the Shopping Bag Order Header first to retrive some form of reference id from the database, and then iterate over each of the Order Lines, creating a command and inserting one at a time.  For each order line you will be firing off TCP packets to the database, and each packet will contain some overhead.  Having to wait for a reply from the database prior to inserting the next Order Line can also cause a delay.
</p>
<p>
So, rather than processing each line at a time, we could make our Shopping Bag object serializable, create an XML schema to validate this Shopping Bag, register the schema with the database and create a Sql Script to validate and parse the serialized XML and insert the data into the correct tables (using the OPENXML methods).
</p>
<p>
We don&#8217;t have to make multiple calls to the database, reducing the chance of failure and any application could call the Stored Procedure without having to know the specific order in which data needs to be inserted.  With the typical method we need to call the stored procedure to insert the order Header first and then insert the Order Lines; with the XML method all of this is handled within the stored procedure.
</p>
<p>
More than likely your Shopping Bag object will have a DateTime type property.  When .Net serializes this property it will be a standard XML Schema Specification valid DateTime, with a fractional component and a DateTime offset, like 2008-04-28T22:45:32.0128+01:00
</p>
<p>
T-SQL however cannot cast this format to a T-SQL DateTime, and although the XML you pass to Sql will validate against the XML Schema held in the database, you won&#8217;t be able to insert the value into a column. What T-Sql actually requires is the following 2008-04-28T22:45:32Z.  No fractional component and no UTC offset.  Once the date is in the database all concept of UTC is lost, T-SQL doesn;t not understand what UTC is.
</p>
<p>
Becuase you&#8217;re going to be using the XMLSerializer class to serialize the Shopping Bag object you can&#8217;t control how the DateTime property is serialized, there&#8217;s no &#8216;XmlDateTime&#8217; attribute.  Instead, we have to format the data in the get method of our property.
</p>
<p>public DateTime _myDate;</p>
<p>public DateTime MyDate<br />
{<br />
    get { return DateTime.SpecifyKind(DateTime.Parse(_myDate.ToString(&#8220;u&#8221;)), DateTimeKind.Utc); }<br />
    set { _myDate = value; }<br />
}</p>
<p>
_myDate.ToString(&#8220;u&#8221;) makes sure we lose any fractional component. The format string u is known as an invaritant DateTime format.  This does not however remove the offset value.  Todo this we need to tell .Net that this is a UTC timezone time (rather than British Summer Time, UTC+1), hence the use of DateTime.SpecifyKind().
</p>
<p>Now when this is serialized .Net will serialize our DateTime as a T-SQL compabtible datetime., and we havn&#8217;t lost the exact datetime that was originally set, however we would need to create method to access this.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaimalchohan.wordpress.com/23/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaimalchohan.wordpress.com/23/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaimalchohan.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaimalchohan.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaimalchohan.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaimalchohan.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaimalchohan.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaimalchohan.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaimalchohan.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaimalchohan.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaimalchohan.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaimalchohan.wordpress.com/23/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=23&subd=jaimalchohan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaimalchohan.wordpress.com/2008/04/29/net-xml-serialization-t-sql-xml-datetime/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acd3c4998414b55ef98d2430bf119b8f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaimalchohan</media:title>
		</media:content>
	</item>
		<item>
		<title>.NET XML Serialization &amp; T-SQL XML &#8211; DateTime</title>
		<link>http://jaimalchohan.wordpress.com/2008/04/29/net-xml-serialization-t-sql-xml-datetime-2/</link>
		<comments>http://jaimalchohan.wordpress.com/2008/04/29/net-xml-serialization-t-sql-xml-datetime-2/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 20:07:36 +0000</pubDate>
		<dc:creator>jaimalchohan</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://jchohan.com/?p=21</guid>
		<description><![CDATA[Today whilst trying to validate an XML document in Sql Server 2005, which had been passed in as a paramater from .Net, I came accross an issue with DateTime serialization.
XML Date Time Sepcification

The W3C XML Schema Scpeification specifies that a valid datetime is the following


2008-04-28T22:45:32+01:00


The first portion before the &#8216;T&#8217; is obviously the date.  [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=20&subd=jaimalchohan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Today whilst trying to validate an XML document in Sql Server 2005, which had been passed in as a paramater from .Net, I came accross an issue with DateTime serialization.</p>
<p><p><strong>XML Date Time Sepcification</strong></p>
<p>
The W3C XML Schema Scpeification specifies that a valid datetime is the following
</p>
<p>
2008-04-28T22:45:32+01:00
</p>
<p>
The first portion before the &#8216;T&#8217; is obviously the date.  The second portion consists of the UTC time, plus an offset value.  This allows times to be compared around in a standard manner, with the ability to obtain the local time.  +01:00 means UTC+1, or British Summer Time for us in the UK.
</p>
<p>
Instead of having an offset of +00:00 for a UTC time with no offset, the specification allow for this to be replaced with a Z, so that
</p>
<p>
2008-04-28T22:45:32+00:00
</p>
<p>
becomes
</p>
<p>
2008-04-28T22:45:32Z
</p>
<p>
In addition, the scpeification allows for fractional seconds, so that a precise UTC+0 datetime can be represented as
</p>
<p>
2008-04-28T22:45:32.1845Z
</p>
<p>
<strong>Where does .Net &amp; SQL fit into all of this?</strong>
</p>
<p>
Well, imagine like me you want to take advantage of the XML schema feature of Sql Server 2005.  You can create a schema, register it within 2005 and then rather than pass in individual paramaters to a stored procedure, you can pass in an XML document.
</p>
<p>
Consider the implications this has when inserting data like a Shopping Bag object.  Typically you would insert the Shopping Bag Order Header first to retrive some form of reference id from the database, and then iterate over each of the Order Lines, creating a command and inserting one at a time.  For each order line you will be firing off TCP packets to the database, and each packet will contain some overhead.  Having to wait for a reply from the database prior to inserting the next Order Line can also cause a delay.
</p>
<p>
So, rather than processing each line at a time, we could make our Shopping Bag object serializable, create an XML schema to validate this Shopping Bag, register the schema with the database and create a Sql Script to validate and parse the serialized XML and insert the data into the correct tables (using the OPENXML methods).
</p>
<p>
We don&#8217;t have to make multiple calls to the database, reducing the chance of failure and any application could call the Stored Procedure without having to know the specific order in which data needs to be inserted.  With the typical method we need to call the stored procedure to insert the order Header first and then insert the Order Lines; with the XML method all of this is handled within the stored procedure.
</p>
<p>
More than likely your Shopping Bag object will have a DateTime type property.  When .Net serializes this property it will be a standard XML Schema Specification valid DateTime, with a fractional component and a DateTime offset, like 2008-04-28T22:45:32.0128+01:00
</p>
<p>
T-SQL however cannot cast this format to a T-SQL DateTime, and although the XML you pass to Sql will validate against the XML Schema held in the database, you won&#8217;t be able to insert the value into a column. What T-Sql actually requires is the following 2008-04-28T22:45:32Z.  No fractional component and no UTC offset.  Once the date is in the database all concept of UTC is lost, T-SQL doesn;t not understand what UTC is.
</p>
<p>
Becuase you&#8217;re going to be using the XMLSerializer class to serialize the Shopping Bag object you can&#8217;t control how the DateTime property is serialized, there&#8217;s no &#8216;XmlDateTime&#8217; attribute.  Instead, we have to format the data in the get method of our property.
</p>
<p>public DateTime _myDate;</p>
<p>public DateTime MyDate<br />
{<br />
    get { return DateTime.SpecifyKind(DateTime.Parse(_myDate.ToString(&#8220;u&#8221;)), DateTimeKind.Utc); }<br />
    set { _myDate = value; }<br />
}</p>
<p>
_myDate.ToString(&#8220;u&#8221;) makes sure we lose any fractional component. The format string u is known as an invaritant DateTime format.  This does not however remove the offset value.  Todo this we need to tell .Net that this is a UTC timezone time (rather than British Summer Time, UTC+1), hence the use of DateTime.SpecifyKind().
</p>
<p>Now when this is serialized .Net will serialize our DateTime as a T-SQL compabtible datetime., and we havn&#8217;t lost the exact datetime that was originally set, however we would need to create method to access this.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaimalchohan.wordpress.com/20/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaimalchohan.wordpress.com/20/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaimalchohan.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaimalchohan.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaimalchohan.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaimalchohan.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaimalchohan.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaimalchohan.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaimalchohan.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaimalchohan.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaimalchohan.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaimalchohan.wordpress.com/20/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=20&subd=jaimalchohan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaimalchohan.wordpress.com/2008/04/29/net-xml-serialization-t-sql-xml-datetime-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acd3c4998414b55ef98d2430bf119b8f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaimalchohan</media:title>
		</media:content>
	</item>
		<item>
		<title>Asynchronous Programming Part 1 &#8211; Delegates</title>
		<link>http://jaimalchohan.wordpress.com/2008/04/26/asynchronous-programming-part-1-delegates/</link>
		<comments>http://jaimalchohan.wordpress.com/2008/04/26/asynchronous-programming-part-1-delegates/#comments</comments>
		<pubDate>Sat, 26 Apr 2008 16:15:47 +0000</pubDate>
		<dc:creator>jaimalchohan</dc:creator>
				<category><![CDATA[Asynchronous]]></category>
		<category><![CDATA[Delegates]]></category>
		<category><![CDATA[Events]]></category>

		<guid isPermaLink="false">http://jchohan.com/?p=20</guid>
		<description><![CDATA[Asynchronous Programming Part 1 &#8211; Delegates
Asynchronous Programming is the ability to perform multiple operations at the same time. For example, connect to a web service whilst at the same time connecting to a database and still responding to user input (avoiding a ‘frozen’ window).

To understand and be able to use Asynchronous programming techniques there are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=16&subd=jaimalchohan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>Asynchronous Programming Part 1 &#8211; Delegates</strong></p>
<p>Asynchronous Programming is the ability to perform multiple operations at the same time. For example, connect to a web service whilst at the same time connecting to a database and still responding to user input (avoiding a ‘frozen’ window).</p>
<p>
To understand and be able to use Asynchronous programming techniques there are a couple of .Net features that need to be covered first, and this 3 part blog will provide you will all the knowledge you need to assess when and understand how to implement Asynchronous code.
</p>
<p>
At the core of Async is a feature known as delegates.
</p>
<p>
Delegates have been around since .Net 1.  You’re using delegates every time you build any application with a UI, and behind the scenes Visual Studio .Net implements the delegates on your behalf.
</p>
<p>
To wire a button to an event, in your client side .aspx you’d usually write the following:
</p>
<p><asp:Button ID="btnOne" Text="Click Me!" OnClick="btnOne_OnClick" runat="server" /></p>
<p>
And in your server side .cs:
</p>
<p>protected void btnOne_Click(object sender, EventArgs e)<br />
{<br />
    // do work<br />
}</p>
<p>
<b>But how does .Net actually call the btnOne_Click method?</b>
</p>
<p>
<u>Event Handlers = Delegate</u></p>
<p>
In .Net 1.0 you had to explicitly define Event Handlers, in .Net 2.0 this is all performed at runtime during page initialization. What .Net 2.0 actually does during page initialization is create and run the following:
</p>
<p>protected void Page_Init(object sender, EventArgs e)<br />
{<br />
    btnOne.Click += new EventHandler(btnOne_Click);<br />
}</p>
<p>
As you can see, I’ve done this in the Page_Init event, and I’ve had to append to the btnOne.Click event an EventHandler class, which takes the btnOne_Click method as its parameter.
</p>
<p>
The EventHandler class is a special type of class whose sole purpose it is to wrap up calls to another method.
</p>
<p>
By using the EventHandler above, we can assign as many methods as we like to the btnOne.Click event without btnOne.Click having to know the names of our methods. Then when btnOne is clicked it can execute each of those methods.
</p>
<p>protected void Page_Init(object sender, EventArgs e)<br />
{<br />
    //All the 3 below do eactly the same thing<br />
    EventHandler handler = new EventHandler(btnOne_Click_1);<br />
    btnOne.Click += handler;</p>
<p>    btnOne.Click += new EventHandler(btnOne_Click_2);</p>
<p>    btnOne.Click += btnOne_Click_3;</p>
<p>    //Events are similar to arrays, we can remove delagates from them<br />
    btnOne_Click -= new EventHandler(btnOne_Click_1);<br />
}</p>
<p>
<em>Note: you can’t depend on the delegates to be invoked in any specific order </em></p>
<p><p>
If delegates are a special type of class, then surly you can create your own? Absolutely. A delegate is basically a method signature (no code body, just the name, parameters and return value of a method). Also it’s good practice to include the word ‘Handler’ as a name suffix so that other coders can immediately tell that it’s a delegate.
</p>
<p>public partial class WebForm1 : System.Web.UI.Page<br />
{<br />
    delegate int MyCustomHandler(int a, int b);</p>
<p>
The delegate above requires that any method to be wrapped up by MyCustomHandler must return an int and must have 2 int&#8217;s as it&#8217;s parameters.
</p>
<p>
You can then define a method, use the delegate to wrap up the method and call the invoke method on the delegate to execute the wrapped up method.
</p>
<p>delegate int MyCustomHandler(int a, int b);</p>
<p>protected int DoWork(int a, int b)<br />
{<br />
    return a + b;<br />
}</p>
<p>protected void PageLoad(object sender, EventArgs e)<br />
{<br />
    MyCustomHandler = new MyCustomHandler(DoWork);<br />
    ExecuteDelegate(handler);<br />
}</p>
<p>protected void ExecuteDelegate(MyCustomHandler handler)<br />
{<br />
    int myInt = handler.Invoke(3, 7);<br />
    // myInt = 10<br />
}</p>
<p>
As you will have noticed, the delegate can be passed around and you can use anything you want as the parameters, however it’s standard practice to pass an object (the object which raised the event) and EventArgs (or a class deriving from it) as the delegates parameters.
</p>
<p>public partial class WebForm1 : System.Web.UI.Page<br />
{</p>
<p>    delegate int MyCustomHandler(object sender, MathsArgs e);</p>
<p>    protected void PageLoad(object sender, EventArgs e)<br />
    {<br />
        MyCustomHandler = new MyCustomHandler(DoWork);<br />
        ExecuteDelegate(handler);<br />
    }</p>
<p>    protected void ExecuteDelegate(MyCustomHandler handler)<br />
    {<br />
        MathsArgs args = new MathsArgs(3, 7);<br />
        int myInt = handler.Invoke(this, args);<br />
        // myInt = 10<br />
    }</p>
<p>    protected int DoWork(object sender, MathsArgs e)<br />
    {<br />
        // by allowing the calling object to be<br />
        // passed it as a paramater you can easily obtain<br />
        // a reference to it, very handy when working<br />
        // with asp.net controls<br />
        // WebForm1 form = (WebForm1)sender;</p>
<p>        return e.A + e.B;<br />
    }<br />
}</p>
<p>public class MathsArgs : EventArgs<br />
{<br />
    public int A;<br />
    public int B;</p>
<p>    public MathsArgs(int a, int b)<br />
    {<br />
        A = a;<br />
        B = b;<br />
    }<br />
}</p>
<p>
Finally a quick look at events, an event basically has the job of containing and calling the invoke method on multiple delegates. Using delegates you subscribe to the event, and when the event is raised (by calling Invoke) the delegates have their Invoke methods called.
</p>
<p>
It’s important to check that the event actually contains a delegate, else the event will be a null object and attempting to invoke it will throw an error.
</p>
<p>namespace DelegatesAndEvents<br />
{<br />
    // You would probably store this is in an assembly which could be used by<br />
    // other applications<br />
    public class UserController<br />
    {<br />
        // declare a delegate which will define the signature<br />
        // of the methods which can subscribe to the event<br />
        public delegate void LoginHandler(object sender, EventArgs e);</p>
<p>        //declare an event and define the type of delagte it allows<br />
        public event LoginHandler LoginEvent;</p>
<p>        protected void Login(object sender, EventArgs e)<br />
        {<br />
            //Log the user into the system</p>
<p>            //Then invoke the Login Event<br />
            if (LoginEvent != null)<br />
                LoginEvent.Invoke(this, new EventArgs());<br />
        }<br />
    }</p>
<p>    public class WebForm1 : Page<br />
    {<br />
        UserController userController;</p>
<p>        public void Page_Load(object sender, EventArgs e)<br />
        {<br />
            if(!Page.IsPostBack)<br />
            {<br />
                userController = new UserController();</p>
<p>                userController.LoginEvent += new UserController.LoginHandler(SendEmail);<br />
                userController.LoginEvent += new UserController.LoginHandler(LogtoDB);<br />
            }<br />
        }</p>
<p>        protected void SendEmail(object sender, EventArgs e)<br />
        {<br />
            // send an email alert informing people that somebody<br />
            // has logged in<br />
        }</p>
<p>        protected void LogtoDB(object sender, EventArgs e)<br />
        {<br />
            // write data to the database becuase somebody has logged in<br />
        }<br />
    }<br />
}</p>
<p>
<em>Note: the C# compiler allows you to leave the Invoke method, so you could call the above by calling MyCustomEvent(this, new EventArgs())</em>
</p>
<p>
That concludes Asynchronous programming Part 1; in Part 2 I will be covering Threading.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaimalchohan.wordpress.com/16/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaimalchohan.wordpress.com/16/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaimalchohan.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaimalchohan.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaimalchohan.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaimalchohan.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaimalchohan.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaimalchohan.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaimalchohan.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaimalchohan.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaimalchohan.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaimalchohan.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaimalchohan.wordpress.com&blog=3317047&post=16&subd=jaimalchohan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaimalchohan.wordpress.com/2008/04/26/asynchronous-programming-part-1-delegates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/acd3c4998414b55ef98d2430bf119b8f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaimalchohan</media:title>
		</media:content>
	</item>
	</channel>
</rss>