﻿<?xml version="1.0" encoding="utf-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Matlus - Internet Technology &amp; Software Engineering</title><link>http://www.matlus.com/</link><atom:link href="http://www.matlus.com/feed/" rel="self" type="application/rss+xml" /><description><![CDATA[]]></description><pubDate>Wed, 22 Feb 2012 19:09:49 GMT</pubDate><language>en</language><item><title>C# to Html Syntax Highlighter using Roslyn</title><pubDate>Sun, 27 Nov 2011 10:00:00 GMT</pubDate><link>http://www.matlus.com/c-to-html-syntax-highlighter-using-roslyn/</link><guid isPermaLink="true">http://www.matlus.com/c-to-html-syntax-highlighter-using-roslyn/</guid><description><![CDATA[<p>Ever since Roslyn was announced I’ve had a few ideas about what I’d want to do with Roslyn. Primarily there are two things I’d love to use Roslyn for:  <ol> <li>Code generation – Generating code in such a way that I would have more semantic information about the existing code and thus be able to generate code in a “smarter” way.  <li>C# to Html syntax highlighting – There are a few solutions out there but for one reason or another, I’m just not happy with them.</li></ol> <p>At the time of this writing the Roslyn project does not support attributes or partial methods. For my code generation ideas, I need support for both these C# language features. The syntax highlighting “project” is more a way for getting my feet wet with Roslyn, since I’ve never really worked with a parser/ lexical scanner/compiler.  <p>Here is a <em><strong>live online demo version</strong></em> you can use to colorize your C# code:  <p><a href="/syntaxhighlighter">C# to Html Syntax Highlighter</a>  <p>In this post I’ll present a C# to Html syntax highlighter that I’ll publish online as a service so anyone can use it independent of an IDE. The primary point of focus (in terms of highlighting) in this project is the ability to highlight types that are unknown. This area is the biggest problem I have with other syntax highlighters.  <p>The Roslyn Syntax APIs give you information about the syntactic structure of the code you provide it with. However, that’s not enough to do a good job of colorizing code the way we’d expect it to. The reason is that there are many cases in which names of types have no meaning unless the appropriate assemblies and namespaces are “in-scope” in order to glean more semantic information about the code. So for example, lets take a look at the snippet of code below. </p> <div class="panel code content/images/csharp.png" title="Sample snippet of code"><pre><span class="Keyword">using</span> System;<br><span class="Keyword">using</span> System.Collections.Generic;<br><span class="Keyword">using</span> System.Linq;<br><span class="Keyword">using</span> System.Text;<br><br><span class="Keyword">namespace</span> ConsoleApplication27<br>{<br>&nbsp; <span class="Keyword">class</span> <span class="Identifier">Program</span><br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; <span class="Keyword">static</span> <span class="Keyword">void</span> Main(<span class="Keyword">string</span>[] args)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="Identifier">Customer</span> customer = <span class="Keyword">new</span> <span class="Identifier">Customer</span>();<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp; }<br>}</pre><br>
<h3>Code Listing 1: Sample Code</h3></div>The line: <pre><span class="Identifier">Customer</span> customer = <span class="Keyword">new</span> <span class="Identifier">Customer</span>();
</pre>
<p>Is syntactically legal C# code. However, without any semantic information about the rest of the code, the type <code>Customer</code> is unknown and as as result won’t get colored as an identifier (in teal) as we see above. In fact in VS the compiler will issue an error and put squiggles under the text <code>Customer</code>. The error would be: The type or namespace name 'Customer' could not be found (are you missing a using directive or an assembly reference?)</p>
<p>There are many such cases that present difficulties in proper colorizing when attempting to do this outside of the IDE, as we are since the project presented here is for online use or as a plug-in to other tools such as Windows Live Writer that won’t be able to provide the additional semantic information needed for this job.</p>
<div class="panel">
<h3 class="note">Bare minimum</h3>
<p>The code presented here requires a certain bare minimum in order to syntax highlight correctly. Code needs to be in a method body at a minimum. So if you have a few lines of code without the rest of the method the code will not highlight correctly. This is intentional as I didn’t want to hardcode a bunch of C# keywords and a bunch of “well known” identifiers etc. I wanted to see how far I could take this method too much work and with no hard coded list of keywords or identifiers. </p>
<p>The single line above will get highlighted correctly. But that's the odd case. Snippets of code that include the entire method, or entire class get correctly highlighted (in all my tests so far). </p></div>
<p>When I initially started down this road I thought this would be a fairly simple matter because I found <code><span class="identifier"><code>SyntaxFacts</code></span></code> (as static class in the <font size="2" face="Consolas"><font size="2" face="Consolas">Roslyn.Compilers.CSharp namespace</font></font>) that had methods such as:</p>
<ul>
<li>IsKeyword 
<li>IsContextualKeyword 
<li>IsTypeDecleration 
<li>IsPredefinedType</li></ul>
<p>So it would be a simple matter of iterating over all of the tokens in the syntax tree and processing each token differently. Instead of iterating over all of the tokens, we could Visit each token (Visitor Pattern).</p>
<p>As part of the Roslyn project we get a class called <code>SyntaxWalker</code> that descends an entire <code>SyntaxNode</code> graph visiting each <code>SyntaxNode</code> and its children nodes and <code>SyntaxTokens</code> in depth-first order. For our purposes this is perfect since the depth-first order will allow us to write out html as we’re walking the tree.</p>
<p>Thanks go out to <a href="http://social.msdn.microsoft.com/profile/shyam%20namboodiripad/?ws=usercard-mini" target="_blank">Shyam Namboodiripad</a> who is on the Roslyn team and without whose help this project would have take a heck of a lot longer and probably never have completed. So Thank you Shyam!</p>
<h2>C# to Html Syntax Highlighter</h2>
<p>The way you would use the classes presented in this post is really very simple.</p><pre><span class="Keyword">var</span> html = <span class="Identifier">CSharpToHtmlSyntaxHighlighter</span>.GetHtml(<span class="StringLiteral">"SomeCode"</span>));
</pre>Where "SomeCode" is the entire code you want highlighted. What you get back is html that you can insert into a blog post or html page, etc. The html generated uses CSS classes to color code the generated Html. So you'll need the following styles declared in your stylesheet or page: <pre>  .Keyword { color: #0000ff; }
  .StringLiteral { color: #a31515; }
  .CharacterLiteral { color: #d202fe; }
  .Identifier { color: #2b91af; }
  .Comment { color: #008000; }
  .Region { color: #e0e0e0; }
</pre>
<h2>Introducing the CSharpToHtmlSyntaxHighlighter</h2>This class is a static class and you'd use it like shown above. The code listing below shows the entire class. 
<div class="panel code content/images/csharp.png" title="CSharpToHtmlSyntaxHighlighter.cs"><pre><span class="Keyword">using</span> System.Text;
<span class="Keyword">using</span> System.Web;
<span class="Keyword">using</span> Roslyn.Compilers;
<span class="Keyword">using</span> Roslyn.Compilers.CSharp;

<span class="Keyword">namespace</span> Matlus.SyntaxHighlighter
{
  <span class="Keyword">public</span> <span class="Keyword">static</span> <span class="Keyword">class</span> <span class="Identifier">CSharpToHtmlSyntaxHighlighter</span>
  {
    <span class="Keyword">private</span> <span class="Keyword">static</span> <span class="Keyword">readonly</span> <span class="Identifier">AssemblyFileReference</span> mscorlib = <span class="Keyword">new</span> <span class="Identifier">AssemblyFileReference</span>(<span class="Keyword">typeof</span>(<span class="Keyword">object</span>).Assembly.Location);

    <span class="Keyword">private</span> <span class="Keyword">static</span> <span class="Identifier">SemanticModel</span> GetSemanticModelForSyntaxTree(<span class="Identifier">SyntaxTree</span> syntaxTree)
    {      
      <span class="Keyword">var</span> compilation = <span class="Identifier">Compilation</span>.Create(
        outputName: <span class="StringLiteral">"CSharpToHtmlSyntaxHighlighterCompilation"</span>,
        syntaxTrees: <span class="Keyword">new</span>[] { syntaxTree },
        references: <span class="Keyword">new</span>[] { mscorlib });

      <span class="Keyword">return</span> compilation.GetSemanticModel(syntaxTree);
    }

    <span class="Keyword">public</span> <span class="Keyword">static</span> <span class="Keyword">string</span> GetHtml(<span class="Keyword">string</span> snippetOfCode)
    {
      <span class="Keyword">var</span> syntaxTree = <span class="Identifier">SyntaxTree</span>.ParseCompilationUnit(snippetOfCode);
      <span class="Keyword">var</span> semanticModel = GetSemanticModelForSyntaxTree(syntaxTree);
      <span class="Keyword">var</span> htmlColorizerSyntaxWalker = <span class="Keyword">new</span> <span class="Identifier">HtmlColorizerSyntaxWalker</span>();

      <span class="Keyword">var</span> htmlBuilder = <span class="Keyword">new</span> <span class="Identifier">StringBuilder</span>();
      htmlColorizerSyntaxWalker.DoVisit(syntaxTree.Root, semanticModel, (tk, text) =&gt;
        {
          <span class="Keyword">switch</span> (tk)
          {
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.None:
              htmlBuilder.Append(text);
              <span class="Keyword">break</span>;
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.Keyword:
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.Identifier:
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.StringLiteral:
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.CharacterLiteral:
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.Comment:
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.DisabledText:
            <span class="Keyword">case</span> <span class="Identifier">TokenKind</span>.Region:
              htmlBuilder.Append(<span class="StringLiteral">"&lt;span class=\""</span> + tk.ToString() + <span class="StringLiteral">"\"&gt;"</span> + <span class="Identifier">HttpUtility</span>.HtmlEncode(text) + <span class="StringLiteral">"&lt;/span&gt;"</span>);
              <span class="Keyword">break</span>;
            <span class="Keyword">default</span>:
              <span class="Keyword">break</span>;
          }
        });
      <span class="Keyword">return</span> htmlBuilder.ToString();
    }
  }
}

</pre>
<h3>Code Listing 2: Showing the entire CSharpToHtmlSyntaxHighlighter class</h3></div>
<p>Let's take a look at the GetHtml() static method. This is the method that kicks off the whole process. </p>
<ul>
<li>Given a snippet of code, we create a <code class="Identifier">SyntaxTree</code> using a helper method of the <code class="Identifier">SyntaxTree</code> class. 
<li>Next, using the syntax tree we create a <code class="Identifier">SemanticModel</code> using the code in the <code>GetSemanticModelForSyntaxTree</code> method. 
<li>And finally, we call the <code>DoVisit()</code> method of the <code class="Identifier">HtmlColorizerSyntaxWalker</code> class.</li></ul>
<p>When we call the <code>DoVisit()</code> method we pass it an <code class="Identifier">Action</code> delegate that we implement as a lambda expression as shown above. Each time the <code class="Identifier">HtmlColorizerSyntaxWalker</code> class finds a token of "interest" while walking the tree it calls us back in this Action delegate (the lambda above) and it is in this method that we generate the html and colorize each of the tokens in the way we desire. </p>
<h2>Introducing the HtmlColorizerSyntaxWalker</h2>
<p>The code listing below shows the entire HtmlColorizerSyntaxWalker class. The primary method in this class is the DoVisit() method. This method initiates the “Visit” process, providing the SyntaxWalker with the root of the syntax tree that we want it to walk along with a couple of other parameters.</p>
<div class="panel code content/images/csharp.png" title="HtmlColorizerSyntaxWalker.cs"><pre><span class="Keyword">using</span> System;
<span class="Keyword">using</span> Roslyn.Compilers.CSharp;

<span class="Keyword">namespace</span> Matlus.SyntaxHighlighter
{
  <span class="Keyword">internal</span> <span class="Keyword">class</span> <span class="Identifier">HtmlColorizerSyntaxWalker</span> : <span class="Identifier">SyntaxWalker</span>
  {
    <span class="Keyword">private</span> <span class="Identifier">SemanticModel</span> semanticModel;
    <span class="Keyword">private</span> <span class="Identifier">Action</span>&lt;<span class="Identifier">TokenKind</span>, <span class="Keyword">string</span>&gt; writeDelegate;

    <span class="Keyword">internal</span> <span class="Keyword">void</span> DoVisit(<span class="Identifier">SyntaxNode</span> token, <span class="Identifier">SemanticModel</span> semanticModel, <span class="Identifier">Action</span>&lt;<span class="Identifier">TokenKind</span>, <span class="Keyword">string</span>&gt; writeDelegate)
    {
      <span class="Keyword">this</span>.semanticModel = semanticModel;
      <span class="Keyword">this</span>.writeDelegate = writeDelegate;
      Visit(token);
    }

    <span class="Comment">// Handle SyntaxTokens</span>
    <span class="Keyword">protected</span> <span class="Keyword">override</span> <span class="Keyword">void</span> VisitToken(<span class="Identifier">SyntaxToken</span> token)
    {
      <span class="Keyword">base</span>.VisitLeadingTrivia(token);

      <span class="Keyword">var</span> isProcessed = <span class="Keyword">false</span>;
      <span class="Keyword">if</span> (token.IsKeyword())
      {
        writeDelegate(<span class="Identifier">TokenKind</span>.Keyword, token.GetText());
        isProcessed = <span class="Keyword">true</span>;
      }
      <span class="Keyword">else</span>
      {
        <span class="Keyword">switch</span> (token.Kind)
        {
          <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.StringLiteralToken:
            writeDelegate(<span class="Identifier">TokenKind</span>.StringLiteral, token.GetText());
            isProcessed = <span class="Keyword">true</span>;
            <span class="Keyword">break</span>;
          <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.CharacterLiteralToken:
            writeDelegate(<span class="Identifier">TokenKind</span>.CharacterLiteral, token.GetText());
            isProcessed = <span class="Keyword">true</span>;
            <span class="Keyword">break</span>;
          <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.IdentifierToken:
            <span class="Keyword">if</span> (token.Parent <span class="Keyword">is</span> SimpleNameSyntax)
            {
              <span class="Comment">// SimpleName is the base type of IdentifierNameSyntax, GenericNameSyntax etc.</span>
              <span class="Comment">// This handles type names that appear in variable declarations etc.</span>
              <span class="Comment">// e.g. "TypeName x = a + b;"</span>
              <span class="Keyword">var</span> name = (<span class="Identifier">SimpleNameSyntax</span>)token.Parent;
              <span class="Keyword">var</span> semanticInfo = semanticModel.GetSemanticInfo(name);
              <span class="Keyword">if</span> (semanticInfo.Symbol != <span class="Keyword">null</span> &amp;&amp; semanticInfo.Symbol.Kind != <span class="Identifier">SymbolKind</span>.ErrorType)
              {
                <span class="Keyword">switch</span> (semanticInfo.Symbol.Kind)
                {
                  <span class="Keyword">case</span> <span class="Identifier">SymbolKind</span>.NamedType:
                    writeDelegate(<span class="Identifier">TokenKind</span>.Identifier, token.GetText());
                    isProcessed = <span class="Keyword">true</span>;
                    <span class="Keyword">break</span>;
                  <span class="Keyword">case</span> <span class="Identifier">SymbolKind</span>.Namespace:
                  <span class="Keyword">case</span> <span class="Identifier">SymbolKind</span>.Parameter:
                  <span class="Keyword">case</span> <span class="Identifier">SymbolKind</span>.Local:
                  <span class="Keyword">case</span> <span class="Identifier">SymbolKind</span>.Field:
                  <span class="Keyword">case</span> <span class="Identifier">SymbolKind</span>.Property:
                    writeDelegate(<span class="Identifier">TokenKind</span>.None, token.GetText());
                    isProcessed = <span class="Keyword">true</span>;
                    <span class="Keyword">break</span>;
                  <span class="Keyword">default</span>:
                    <span class="Keyword">break</span>;
                }
              }
            }
            <span class="Keyword">else</span> <span class="Keyword">if</span> (token.Parent <span class="Keyword">is</span> TypeDeclarationSyntax)
            {
              <span class="Comment">// TypeDeclarationSyntax is the base type of ClassDeclarationSyntax etc.</span>
              <span class="Comment">// This handles type names that appear in type declarations</span>
              <span class="Comment">// e.g. "class TypeName { }"</span>
              <span class="Keyword">var</span> name = (<span class="Identifier">TypeDeclarationSyntax</span>)token.Parent;
              <span class="Keyword">var</span> symbol = semanticModel.GetDeclaredSymbol(name);
              <span class="Keyword">if</span> (symbol != <span class="Keyword">null</span> &amp;&amp; symbol.Kind != <span class="Identifier">SymbolKind</span>.ErrorType)
              {
                <span class="Keyword">switch</span> (symbol.Kind)
                {
                  <span class="Keyword">case</span> <span class="Identifier">SymbolKind</span>.NamedType:
                    writeDelegate(<span class="Identifier">TokenKind</span>.Identifier, token.GetText());
                    isProcessed = <span class="Keyword">true</span>;
                    <span class="Keyword">break</span>;
                }
              }
            }
            <span class="Keyword">break</span>;
        }
      }

      <span class="Keyword">if</span> (!isProcessed)
        HandleSpecialCaseIdentifiers(token);

      <span class="Keyword">base</span>.VisitTrailingTrivia(token);
    }

    <span class="Keyword">private</span> <span class="Keyword">void</span> HandleSpecialCaseIdentifiers(<span class="Identifier">SyntaxToken</span> token)
    {
      <span class="Keyword">switch</span> (token.Kind)
      {
        <span class="Comment">// Special cases that are not handled because there is no semantic context/model that can truely identify identifiers.</span>
        <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.IdentifierToken:
          <span class="Keyword">if</span> ((token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.Parameter)
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.EnumDeclaration)
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.Attribute)
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.CatchDeclaration)
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.ObjectCreationExpression)
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.ForEachStatement &amp;&amp; !(token.GetNextToken().Kind == <span class="Identifier">SyntaxKind</span>.CloseParenToken))
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.CaseSwitchLabel &amp;&amp; !(token.GetPreviousToken().Kind == <span class="Identifier">SyntaxKind</span>.DotToken))
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.MethodDeclaration)
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.CastExpression)
            <span class="Comment">//e.g. "private static readonly HashSet<string> patternHashSet = new HashSet<string>();" the first HashSet in this case</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.GenericName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.VariableDeclaration)
            <span class="Comment">//e.g. "private static readonly HashSet<string> patternHashSet = new HashSet<string>();" the second HashSet in this case</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.GenericName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.ObjectCreationExpression)
            <span class="Comment">//e.g. "public sealed class BuilderRouteHandler : IRouteHandler" IRouteHandler in this case</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.BaseList)
            <span class="Comment">//e.g. "Type baseBuilderType = typeof(BaseBuilder);" BaseBuilder in this case</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.TypeOfExpression)
            <span class="Comment">// e.g. "private DbProviderFactory dbProviderFactory;" OR "DbConnection connection = dbProviderFactory.CreateConnection();"</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.VariableDeclaration)
            <span class="Comment">// e.g. "DbTypes = new Dictionary<string dbtype ,>();" DbType in this case</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.TypeArgumentList)
            <span class="Comment">// e.g. "DbTypes.Add("int", DbType.Int32);" DbType in this case</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.MemberAccessExpression &amp;&amp; token.Parent.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.Argument &amp;&amp; !(token.GetPreviousToken().Kind == <span class="Identifier">SyntaxKind</span>.DotToken || <span class="Identifier">Char</span>.IsLower(token.GetText()[0])))
            <span class="Comment">// e.g. "schemaCommand.CommandType = CommandType.Text;" CommandType in this case</span>
            || (token.Parent.Kind == <span class="Identifier">SyntaxKind</span>.IdentifierName &amp;&amp; token.Parent.Parent.Kind == <span class="Identifier">SyntaxKind</span>.MemberAccessExpression &amp;&amp; !(token.GetPreviousToken().Kind == <span class="Identifier">SyntaxKind</span>.DotToken || <span class="Identifier">Char</span>.IsLower(token.GetText()[0])))
            )
          {
            writeDelegate(<span class="Identifier">TokenKind</span>.Identifier, token.GetText());
          }
          <span class="Keyword">else</span>
          {
            <span class="Keyword">if</span> (token.GetText() == <span class="StringLiteral">"HashSet"</span>)
            {
            }
            writeDelegate(<span class="Identifier">TokenKind</span>.None, token.GetText());
          }
          <span class="Keyword">break</span>;
        <span class="Keyword">default</span>:
          writeDelegate(<span class="Identifier">TokenKind</span>.None, token.GetText());
          <span class="Keyword">break</span>;
      }
    }

    <span class="Comment">// Handle SyntaxTrivia</span>
    <span class="Keyword">protected</span> <span class="Keyword">override</span> <span class="Keyword">void</span> VisitTrivia(<span class="Identifier">SyntaxTrivia</span> trivia)
    {
      <span class="Keyword">switch</span> (trivia.Kind)
      {
        <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.MultiLineCommentTrivia:
        <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.SingleLineCommentTrivia:
          writeDelegate(<span class="Identifier">TokenKind</span>.Comment, trivia.GetText());
          <span class="Keyword">break</span>;
        <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.DisabledTextTrivia:
          writeDelegate(<span class="Identifier">TokenKind</span>.DisabledText, trivia.GetText());
          <span class="Keyword">break</span>;
        <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.DocumentationComment:
          writeDelegate(<span class="Identifier">TokenKind</span>.Comment, trivia.GetText());
          <span class="Keyword">break</span>;
        <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.RegionDirective:
        <span class="Keyword">case</span> <span class="Identifier">SyntaxKind</span>.EndRegionDirective:
          writeDelegate(<span class="Identifier">TokenKind</span>.Region, trivia.GetText());
          <span class="Keyword">break</span>;
        <span class="Keyword">default</span>:
          writeDelegate(<span class="Identifier">TokenKind</span>.None, trivia.GetText());
          <span class="Keyword">break</span>;
      }
      <span class="Keyword">base</span>.VisitTrivia(trivia);
    }
  }
}
</pre>
<h3>Code Listing 3: Showing the entire HtmlColorizerSyntaxWalker class</h3></div>
<p>The 3rd parameter to the <code>DoVisit()</code> method is an <code>Action</code> delegate or a callback that gets called each time the SyntaxWalker has determined that the token it is currently on is one we would be <strong><em>interested</em></strong> in. When it calls us back on this delegate it also lets us know the kind of token is has found using the <code>TokenKind</code> enum. The <code>TokenKind</code> enum is not a built in type. I couldn’t find a suitable type so I had to define one that worked best for this purpose (syntax highlighting). The definition of this enum is shown below:</p>
<div class="panel code content/images/csharp.png" title="TokenKind.cs"><pre><span class="Keyword">namespace</span> Matlus.SyntaxHighlighter
{
  <span class="Keyword">internal</span> <span class="Keyword">enum</span> <span class="Identifier">TokenKind</span>
  {
    None,
    Keyword,
    Identifier,
    StringLiteral,
    CharacterLiteral,
    Comment,
    DisabledText,
    Region    
  }
}
</pre>
<h3>Code Listing 4: Showing the TokenKind enum</h3></div>
<p>The rest of the code looks quite complicated but really isn't. It is basically a bunch of conditional statements.</p>
<p>The method that handles all of the (special) cases where *we* know the token is an identifier but Roslyn can't (because it lacks semantic information) is, <code>HandleSpecialCaseIdentifiers</code>. If you come across any token that falls through the cracks, you’ll need to add a conditional statement here to handle that case.</p>]]></description><category>Programming/C#</category><category>CodeGen</category><category>Roslyn</category></item><item><title>Disrupting the World Wide Web - Innovating the World Wide Net</title><pubDate>Mon, 21 Mar 2011 13:03:16 GMT</pubDate><link>http://www.matlus.com/innovating-the-world-wide-net/</link><guid isPermaLink="true">http://www.matlus.com/innovating-the-world-wide-net/</guid><description><![CDATA[<p>We’ve been in the World Wide Web "phase” for a little over 2 decades. A lot has happened and a lot has changed in this period. This post is not about what has happened but rather what will, or needs to happen next.</p> <p>In my mind it is inevitable and as an entrepreneur or business if you want to stay ahead of the “S” curve, this is the time to get cracking. The <strong>World Wide Net</strong> is about <strong><em>getting out of and beyond the box</em></strong>.</p> <p>But first let me level-set a couple of terms for this discussion.<br><strong><em>Internet</em></strong>: Internet is a short form for the word Internetwork. It is essentially an infrastructure comprised of hardware communication devices providing connectivity between computers.</p> <p><strong><em>World Wide Web</em></strong>: The World Wide Web is web of interconnected documents and application that use the Internet as a transport medium. As a visual, what you see depicted in the image below is the current state.</p> <p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="WorldWideWeb" border="0" alt="WorldWideWeb" src="http://www.matlus.com/content/uploads/2011/03/WorldWideWeb_9dab62e5-b2a2-4e04-8688-c9dbd85e95e1.jpg" width="640" height="360"></p> <p>You have:</p> <ul> <li>Computers connected via the Internet sharing documents and applications  <li>Humans primarily living in a virtual space<br></li></ul> <p>There are a few problems as I see it, with this status. Humans need more than “virtual”, we need to be able to share and feel more than we currently can. Essentially, we need to get out of and beyond the box. How is this going to happen and what is it going to take?</p> <p>A Browser as we know it today is not going to cut it, for many reasons. Browsers confine us even more to the “box”.</p> <p>Mobile phones and devices (Android and iPhone/iPad) have taken a step in the right direction and that is, native application (available from the store) that have access to hardware on the device such as the gyro, accelerometer, GPS etc. These differences make the big difference in our experience between what we can do over the Internet with our PCs and mobile devices. Gaming consoles such as the XBOX and Play Station provide other capabilities such as high performance HD graphics, and have bridged a gap by bringing the Internet to these devices.</p> <p>World Wide Net is more than the two (mobile phones and gaming consoles) combined. First Gaming consoles and PCs will need to merge and the browser needs to go. Don’t get me wrong, I love the direction browsers are moving in and I spend virtually all of my time working with browsers. As a result I feel the constraints more so, I guess. Browsers provide us with a sandbox and that’s important but we need more then what this sandbox provides us.</p> <p>So imagine a world where your PC has all of the capabilities of a PC and a gaming console and in addition the operating system rather than the browser provides the sandbox. The sandbox the operating system provides is similar to what mobile devices provide for applications downloaded from the app store. When applications need access to certain hardware (like the GPS system) they ask for permission.</p> <p>But <em><strong>beyond the box</strong></em> goes further than the box (obviously). So the World Wide Net is about having access to hardware devices that may be connected directly to your PC via a USB port or serial port or via your home network. The devices I’m talking about don’t exist yet (for the most part). Some are around the corner but most of them are yet to be dreamed up. Devices that are around the corner are devices such as networked refrigerators, microwave ovens, music system etc..</p> <p>These devices need to be programmable via an API and not just networked, such that any software engineer can program a certain class of device using this API.</p> <p>Talking to peripheral and networked devices is already possible today and has been for many years now, but it requires native applications (written in C, C++, C#, Java etc.). User interfaces are going to be more “game like” than what we have today. All of this will require an operating system level sandbox rather than a browser based sandbox and the capabilities of programming languages such as those mentioned above, rather than HTML, SVG and JavaScript.</p> <p>The image below shows you my vision of the World Wide Net. The Internet is still the transport/communications layer, but we move from the World Wide Web, to the World Wide Net, of connections out of and beyond the box, more "real". Where people you interact with on the World Wide Net can control devices connected to your computer via applications that run in the sandbox of the operating system.</p> <p><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="WorldWideNet" border="0" alt="WorldWideNet" src="http://www.matlus.com/content/uploads/2011/03/WorldWideNet_6204a363-20de-4ae8-a193-5ecfd00ef01b.jpg" width="640" height="640"></p> <p>Being an electronics engineer by qualification (It’s a hobby now), I can dream up a number of devices that I can build and hook up to my computer and share with friends and family and interact and socialize with them in the “real” world, beyond the box. But as I said, most devices (that I’m talking about) don’t exist yet. They are a new breed of devices we don’t have a need for today, primarily because we don’t have the means to use them.</p> <p>We’ll still have browsers and a need for them in the era of the World Wide Net because we'll continue to share "documents", we just need go out of and beyond the box to share more the documents.</p>]]></description><category>Opinion/Mine</category><category>Devices</category><category>Future</category></item><item><title>WCF 4.0 Getting Started</title><pubDate>Sat, 05 Mar 2011 01:01:25 GMT</pubDate><link>http://www.matlus.com/wcf-4-0-getting-started/</link><guid isPermaLink="true">http://www.matlus.com/wcf-4-0-getting-started/</guid><description><![CDATA[<p>In this post we'll be looking at build a simple WCF client and WCF service application. You'll be up and running in no time guaranteed.</p> <p>In WCF 4.0 (in contrast to earlier versions), things have gotten a lot easier in as far a configuration is concerned. WCF 4.0 stresses convention over configuration. So we'll first get our client and service up and running using conventions (no configuration at all) and then we'll take a look at how we would configure things if we need to. But rather than using the config file we'll programmatically configure things.</p> <h2>WCF Service Application</h2> <p>We'll start with the WCF service application first. So create a new console application and follow along. We'll need reference 2 assemblies in this project so lets go ahead and do that as well. The 2 assemblies are:</p> <ol> <li>System.ServiceModel  <li>System.Runtime.Serialization</li></ol> <p>In order to define what methods and properties our service has we define an interface that will represent our service contract. This is a regular interface that has the properties and methods we want to include in our service contract. The only additional thing to do here is to decorate the interface with the <code>ServiceContract</code> attribute. So go ahead and create a new class file define the service contract as shown below:</p> <div class="panel code content/images/csharp.png" title="ICustomerService Interface - The Service Contract"><pre style="text-align: left; line-height: normal"><span style="color: " class="keyword"><font color="#0000ff" face="Courier New"><font style="font-size: 12pt">using</font></font></span><font style="font-size: 12pt"><font face="Courier New"><font color="#000000"> <span class="identifier">System</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Collections</span><span class="operator">.</span><span class="identifier">Generic</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Linq</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Text</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WCFTcpServer</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span>;
 
</font><span style="color: " class="keyword"><font color="#0000ff">namespace</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WcfServer</span>
{
  [</font><span style="color: " class="User Types"><font color="#2b91af">ServiceContract</font></span></font><font face="Courier New"><font color="#000000">]
  </font><span style="color: " class="keyword"><font color="#0000ff">interface</font></span><font color="#000000"> </font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span>
</font><font face="Courier New"><font color="#000000">  {
    [</font><span style="color: " class="User Types"><font color="#2b91af">OperationContract</font></span></font><font face="Courier New"><font color="#000000">]
    </font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">IEnumerable</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">&gt;</span> <span class="identifier">GetCustomers</span>();
    [</font><span style="color: " class="User Types"><font color="#2b91af">OperationContract</font></span></font><font face="Courier New"><font color="#000000">]
    </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span><font color="#000000"> <span class="identifier">GetCustomer</span>(</font><span style="color: " class="keyword"><font color="#0000ff">int</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">id</span>);
    [</font><span style="color: " class="User Types"><font color="#2b91af">OperationContract</font></span></font><font face="Courier New"><font color="#000000">]
    </font><span style="color: " class="keyword"><font color="#0000ff">int</font></span><font color="#000000"> <span class="identifier">InsertCustomer</span>(</font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customer</span>);
    [</font><span style="color: " class="User Types"><font color="#2b91af">OperationContract</font></span></font><font face="Courier New"><font color="#000000">]
    </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">UpdateCustomer</span>(</font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customer</span>);
    [</font><span style="color: " class="User Types"><font color="#2b91af">OperationContract</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000">]
    </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">DeleteCustomer</span>(</font><span style="color: " class="keyword"><font color="#0000ff">int</font></span><font color="#000000"> <span class="identifier">customerId</span>);
  }
}
</font></font></font></pre>
<h3>Showing the ICustomerService.cs file</h3></div>
<p>&nbsp;</p>
<p>Notice that the interface is decorated with the <code>ServiceContract</code> attribute and each of the methods we want to expose is decorated with the <code>OperationContract</code> attribute. That takes care of our service contract.</p>
<p>The next thing we need to do is define the Customer class that this service contract is operating on. So lets create a new class file and define our Customer class as shown below:</p>
<div class="panel code content/images/csharp.png" title="Customer Class"><pre style="text-align: left; line-height: normal"><span style="color: " class="keyword"><font color="#0000ff" face="Courier New"><font style="font-size: 12pt">using</font></font></span><font style="font-size: 12pt"><font face="Courier New"><font color="#000000"> <span class="identifier">System</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Collections</span><span class="operator">.</span><span class="identifier">Generic</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Linq</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Text</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Runtime</span><span class="operator">.</span><span class="identifier">Serialization</span>;
 
</font><span style="color: " class="keyword"><font color="#0000ff">namespace</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WcfServer</span>
{
  [</font><span style="color: " class="User Types"><font color="#2b91af">DataContract</font></span></font><font face="Courier New"><font color="#000000">]
  </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">class</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span>
</font><font face="Courier New"><font color="#000000">  {
    [</font><span style="color: " class="User Types"><font color="#2b91af">DataMember</font></span></font><font face="Courier New"><font color="#000000">]
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">int</font></span><font color="#000000"> <span class="identifier">Id</span> { </font><span style="color: " class="keyword"><font color="#0000ff">get</font></span><font color="#000000">; </font><span style="color: " class="keyword"><font color="#0000ff">set</font></span></font><font face="Courier New"><font color="#000000">; }
    [</font><span style="color: " class="User Types"><font color="#2b91af">DataMember</font></span></font><font face="Courier New"><font color="#000000">]
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">string</font></span><font color="#000000"> <span class="identifier">FirstName</span> { </font><span style="color: " class="keyword"><font color="#0000ff">get</font></span><font color="#000000">; </font><span style="color: " class="keyword"><font color="#0000ff">set</font></span></font><font face="Courier New"><font color="#000000">; }
    [</font><span style="color: " class="User Types"><font color="#2b91af">DataMember</font></span></font><font face="Courier New"><font color="#000000">]
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">string</font></span><font color="#000000"> <span class="identifier">LastName</span> { </font><span style="color: " class="keyword"><font color="#0000ff">get</font></span><font color="#000000">; </font><span style="color: " class="keyword"><font color="#0000ff">set</font></span></font><font face="Courier New"><font color="#000000">; }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">override</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">string</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">ToString</span>()
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">return</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">String</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">Concat</span>(
        </font><span style="color: " class="string"><font color="#a31515">"Id: "</font></span></font><font face="Courier New"><font color="#000000"> <span class="operator">+</span> <span class="identifier">Id</span><span class="operator">.</span><span class="identifier">ToString</span>(),
        </font><span style="color: " class="string"><font color="#a31515">"  Name: "</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000"> <span class="operator">+</span> <span class="identifier">FirstName</span>,
        </font><span style="color: " class="string"><font color="#a31515">" "</font></span><font color="#000000"> <span class="operator">+</span> <span class="identifier">LastName</span>);
    }
  }
}
</font></font></font></pre>
<h3>Showing the Customer.cs file</h3></div>
<p>Notice that the Customer class has been decorated with the <code>DataContract</code> attribute and each of the public properties we wish to expose as part of our service contract is decorated with the <code>DataMember</code> attribute. We've also overridden the <code>ToString()</code>method here just as a convenience (displaying in the console window).</p>
<p>Next, well need to implement our service contract. That is we'll need to define a class that implements our <code>ICustomerService</code> interface. The implementation is not important for this discussion as it is a regular class and indeed, the implementation is not specific to WCF.</p>
<div class="panel code content/images/csharp.png" title="The CustomerService class that implements the ICustomerService interface"><pre style="text-align: left; line-height: normal"><span style="color: " class="keyword"><font color="#0000ff" face="Courier New"><font style="font-size: 12pt">using</font></font></span><font style="font-size: 12pt"><font face="Courier New"><font color="#000000"> <span class="identifier">System</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Collections</span><span class="operator">.</span><span class="identifier">Generic</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Linq</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Text</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span>;
 
</font><span style="color: " class="keyword"><font color="#0000ff">namespace</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WcfServer</span>
{
  [</font><span style="color: " class="User Types"><font color="#2b91af">ServiceBehavior</font></span><font color="#000000">(<span class="identifier">ConcurrencyMode</span> <span class="operator">=</span> </font><span style="color: " class="User Types(Enums)"><font color="#2b91af">ConcurrencyMode</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">Multiple</span>,
    <span class="identifier">InstanceContextMode</span> <span class="operator">=</span> </font><span style="color: " class="User Types(Enums)"><font color="#2b91af">InstanceContextMode</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">Single</span>)]
  </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">class</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">CustomerService</font></span><font color="#000000"> : </font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span>
</font><font face="Courier New"><font color="#000000">  {
    </font><span style="color: " class="keyword"><font color="#0000ff">private</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">List</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">&gt;</span> <span class="identifier">customers</span>;
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">CustomerService</span>()
    {
      <span class="identifier">customers</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">List</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">&gt;</span> {
        </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span><font color="#000000"> { <span class="identifier">Id</span><span class="operator">=</span><span class="number">1</span>, <span class="identifier">FirstName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"George"</font></span><font color="#000000">, <span class="identifier">LastName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"Washington"</font></span></font><font face="Courier New"><font color="#000000">},
        </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span><font color="#000000"> { <span class="identifier">Id</span><span class="operator">=</span><span class="number">2</span>, <span class="identifier">FirstName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"John"</font></span><font color="#000000">, <span class="identifier">LastName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"Adams"</font></span></font><font face="Courier New"><font color="#000000">},
        </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span><font color="#000000"> { <span class="identifier">Id</span><span class="operator">=</span><span class="number">3</span>, <span class="identifier">FirstName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"Thomas"</font></span><font color="#000000">, <span class="identifier">LastName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"Jefferson"</font></span></font><font face="Courier New"><font color="#000000">},
        </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span><font color="#000000"> { <span class="identifier">Id</span><span class="operator">=</span><span class="number">4</span>, <span class="identifier">FirstName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"James"</font></span><font color="#000000">, <span class="identifier">LastName</span><span class="operator">=</span></font><span style="color: " class="string"><font color="#a31515">"Madison"</font></span></font><font face="Courier New"><font color="#000000">}         
      };
    }
    
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">IEnumerable</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">&gt;</span> <span class="identifier">GetCustomers</span>()
    {
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(</font><span style="color: " class="string"><font color="#a31515">"GetCustomers()"</font></span></font><font face="Courier New"><font color="#000000">);
      </font><span style="color: " class="keyword"><font color="#0000ff">return</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customers</span>;
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span><font color="#000000"> <span class="identifier">GetCustomer</span>(</font><span style="color: " class="keyword"><font color="#0000ff">int</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">id</span>)
    {
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(</font><span style="color: " class="string"><font color="#a31515">"GetCustomer("</font></span><font color="#000000"> <span class="operator">+</span> <span class="identifier">id</span><span class="operator">.</span><span class="identifier">ToString</span>() <span class="operator">+</span> </font><span style="color: " class="string"><font color="#a31515">")"</font></span></font><font face="Courier New"><font color="#000000">);
      </font><span style="color: " class="keyword"><font color="#0000ff">return</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customers</span><span class="operator">.</span><span class="identifier">Where</span>(<span class="identifier">c</span> <span class="operator">=&gt;</span> <span class="identifier">c</span><span class="operator">.</span><span class="identifier">Id</span> <span class="operator">==</span> <span class="identifier">id</span>)<span class="operator">.</span><span class="identifier">First</span>();
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">int</font></span><font color="#000000"> <span class="identifier">InsertCustomer</span>(</font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customer</span>)
    {
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(</font><span style="color: " class="string"><font color="#a31515">"InsertCustomer()"</font></span></font><font face="Courier New"><font color="#000000">);
      </font><span style="color: " class="keyword"><font color="#0000ff">var</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">newId</span> <span class="operator">=</span> <span class="identifier">customers</span><span class="operator">.</span><span class="identifier">Max</span>(<span class="identifier">c</span> <span class="operator">=&gt;</span> <span class="identifier">c</span><span class="operator">.</span><span class="identifier">Id</span>) <span class="operator">+</span> <span class="number">1</span>;
      <span class="identifier">customer</span><span class="operator">.</span><span class="identifier">Id</span> <span class="operator">=</span> <span class="identifier">newId</span>;
      <span class="identifier">customers</span><span class="operator">.</span><span class="identifier">Add</span>(<span class="identifier">customer</span>);
      </font><span style="color: " class="keyword"><font color="#0000ff">return</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">newId</span>;
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">UpdateCustomer</span>(</font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customer</span>)
    {
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(</font><span style="color: " class="string"><font color="#a31515">"UpdateCustomer()"</font></span></font><font face="Courier New"><font color="#000000">);
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(<span class="identifier">customer</span>);
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">DeleteCustomer</span>(</font><span style="color: " class="keyword"><font color="#0000ff">int</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customerId</span>)
    {
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(</font><span style="color: " class="string"><font color="#a31515">"DeleteCustomer("</font></span><font color="#000000"> <span class="operator">+</span> <span class="identifier">customerId</span><span class="operator">.</span><span class="identifier">ToString</span>() <span class="operator">+</span> </font><span style="color: " class="string"><font color="#a31515">")"</font></span></font><font face="Courier New"><font color="#000000">);
      </font><span style="color: " class="keyword"><font color="#0000ff">var</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000"> <span class="identifier">customerToDelete</span> <span class="operator">=</span> <span class="identifier">customers</span><span class="operator">.</span><span class="identifier">Where</span>(<span class="identifier">c</span> <span class="operator">=&gt;</span> <span class="identifier">c</span><span class="operator">.</span><span class="identifier">Id</span> <span class="operator">==</span> <span class="identifier">customerId</span>)<span class="operator">.</span><span class="identifier">Select</span>(<span class="identifier">c</span> <span class="operator">=&gt;</span> <span class="identifier">c</span>)<span class="operator">.</span><span class="identifier">First</span>();
      </font><span style="color: " class="keyword"><font color="#0000ff">if</font></span><font color="#000000"> (<span class="identifier">customerToDelete</span> <span class="operator">!=</span> </font><span style="color: " class="keyword"><font color="#0000ff">null</font></span><font color="#000000">)
        <span class="identifier">customers</span><span class="operator">.</span><span class="identifier">Remove</span>(<span class="identifier">customerToDelete</span>);
    }
  }
}
</font></font></font></pre>
<h3>Showing CustomerService.cs</h3></div>
<p>Notice that the CustomerService class has been decorated with the <code>ServiceBehavior</code>. You don't need to specify any of the named parameters you see there.</p>
<p>We're now at the final part of our WCF Service application. WCF services can support multiple transport protocols (in the same service application without any code changes in our service), such as HTTP, HTTPS, TCP, P2P (Peer to Peer), IPC (Named Pipes), MSMQ (Message Queue). We can even choose to host our service in IIS or choose to host it in our own application (as we are doing here). In the service we're building we'll support 3 of these transport protocols (just for kicks).</p>
<div class="panel code content/images/csharp.png" title="The WCF Service Host with endpoint configuration"><pre style="text-align: left; line-height: normal"><span style="color: " class="keyword"><font color="#0000ff" face="Courier New"><font style="font-size: 12pt">using</font></font></span><font style="font-size: 12pt"><font face="Courier New"><font color="#000000"> <span class="identifier">System</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Collections</span><span class="operator">.</span><span class="identifier">Generic</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Linq</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Text</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span><span class="operator">.</span><span class="identifier">Description</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span><span class="operator">.</span><span class="identifier">Channels</span>;
 
</font><span style="color: " class="keyword"><font color="#0000ff">namespace</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WcfServer</span>
{
  </font><span style="color: " class="keyword"><font color="#0000ff">class</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">WcfServiceHost</font></span>
</font><font face="Courier New"><font color="#000000">  {
    </font><span style="color: " class="keyword"><font color="#0000ff">static</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">Main</span>(</font><span style="color: " class="keyword"><font color="#0000ff">string</font></span></font><font face="Courier New"><font color="#000000">[] <span class="identifier">args</span>)
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">using</font></span><font color="#000000"> (</font><span style="color: " class="User Types"><font color="#2b91af">ServiceHost</font></span><font color="#000000"> <span class="identifier">host</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">ServiceHost</font></span><font color="#000000">(</font><span style="color: " class="keyword"><font color="#0000ff">typeof</font></span><font color="#000000">(</font><span style="color: " class="User Types"><font color="#2b91af">CustomerService</font></span></font><font face="Courier New"><font color="#000000">),
        </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Uri</font></span><font color="#000000">(</font><span style="color: " class="string"><font color="#a31515">"http://localhost:8080"</font></span></font><font face="Courier New"><font color="#000000">),
        </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Uri</font></span><font color="#000000">(</font><span style="color: " class="string"><font color="#a31515">"net.pipe://localhost"</font></span></font><font face="Courier New"><font color="#000000">),
        </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Uri</font></span><font color="#000000">(</font><span style="color: " class="string"><font color="#a31515">"net.tcp://localhost:8081"</font></span></font><font face="Courier New"><font color="#000000">)))
      {
        <span class="identifier">host</span><span class="operator">.</span><span class="identifier">AddServiceEndpoint</span>(</font><span style="color: " class="keyword"><font color="#0000ff">typeof</font></span><font color="#000000">(</font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span></font><font face="Courier New"><font color="#000000">),
          </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">BasicHttpBinding</font></span></font><font face="Courier New"><font color="#000000">(),
          </font><span style="color: " class="string"><font color="#a31515">"CustomerService"</font></span></font><font face="Courier New"><font color="#000000">);
 
        <span class="identifier">host</span><span class="operator">.</span><span class="identifier">AddServiceEndpoint</span>(</font><span style="color: " class="keyword"><font color="#0000ff">typeof</font></span><font color="#000000">(</font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span></font><font face="Courier New"><font color="#000000">),
          </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">NetNamedPipeBinding</font></span></font><font face="Courier New"><font color="#000000">(),
          </font><span style="color: " class="string"><font color="#a31515">"CustomerService"</font></span></font><font face="Courier New"><font color="#000000">);
 
        <span class="identifier">host</span><span class="operator">.</span><span class="identifier">AddServiceEndpoint</span>(</font><span style="color: " class="keyword"><font color="#0000ff">typeof</font></span><font color="#000000">(</font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span></font><font face="Courier New"><font color="#000000">),
          </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">NetTcpBinding</font></span></font><font face="Courier New"><font color="#000000">(),
          </font><span style="color: " class="string"><font color="#a31515">"CustomerService"</font></span></font><font face="Courier New"><font color="#000000">);
 
        <span class="identifier">host</span><span class="operator">.</span><span class="identifier">Open</span>();
 
        </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(</font><span style="color: " class="string"><font color="#a31515">"Service is ready and waiting.\r\nPress &lt;ENTER&gt; to exit."</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000">);
        </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">ReadLine</span>();
 
        <span class="identifier">host</span><span class="operator">.</span><span class="identifier">Close</span>();
      }
    }
  }
}</font></font></font></pre>
<h3>Showing the WcfServiceHost.cs file</h3></div>
<p>When we construct our <code>ServiceHost</code> instance (the <code>host</code> variable in the code above) we specify two parameters:</p>
<ol>
<li>The Type of our service (that is the Type of the class that implements our service contract) 
<li>A <code>params</code> array <code>Uri</code> that is the array of <code>BaseAddresses</code> our service will support.</li></ol>
<p>A BaseAddress is essentially the initial part of the Uri for the hosted service. It includes the transport protocol as well as a port number (if required by the transport protocol). So you can see above that we've provided 3 bases addresses, one for each of the transport protocols we'd like our service to support.</p>
<p>Once we have our <code>ServiceHost</code> instance, we add the endpoints for each of the transport protocols we've added (those BaseAddresses in the constructor).</p>
<div class="panel">
<h3 class="note">Endpoint</h3>
<p>An endpoint is the name for an entity on one end of a transport layer and it comprises of the these 3 things:</p>
<ol>
<li>Address 
<li>Binding 
<li>Contract</li></ol>
<p>The Address is comprised on the base address plus the "tail" of the Uri. In our case the "tail" is "CustomerService" string parameter you see in the code above. So the "address" for the basic http binding is <code>http://localhost:8080/CustomerService</code></p>
<p>The Binding is essentially the transport protocol. However, each transport protocol essentially implies certain things for instance, HTTP implies a disconnected, stateless Request-Response protocol. So a binding implicitly implies the capabilities and modes of the transport protocol as well.</p>
<p>A Contract is a platform neutral way of describing what the service does (or is capable of) and in WCF there are 4 types of contracts (we've already meet 2 of them)</p>
<ol>
<li>Service Contracts 
<li>Data Contract 
<li>Fault Contracts 
<li>Message Contracts</li></ol>
<p>Message contracts are rarely used. They're typically used due to interoperability needs with legacy services.</p></div>
<p>The AdServiceEnpoint() method has 9 overloads, bur essentially we need to either provide and endpoint instance or provide the information that makes up an endpoint (see note above). In the overload we're using we provide the Contract (ICustomerService), the Binding (for example BasicHttpBinding) and the Address (the string "CustomerService"). The address can be an absolute url or a relative url. We're using a relative url since we've provided the BaseAddress for each of the transport protocols earlier. Effectively, the address for each of the endpoints is the concatenation of the BaseAddress and the relative url. For for the Http endpoint our url is <code>http://localhost:8080/CustomerService</code>.</p>
<p>Once we've configured our host we can call the Open() method on it and that starts the host listening for requests from clients. Our WCF service application is now complete.</p>
<h2>WCF Client Application</h2>
<p>The typical way to start with building a client for a service is to get the IDE to generate a proxy (just like with a SOAP service). With WCF you can do that, however, at the moment, our service does not support metadata discovery. With WCF there is a simpler way to create a proxy and that is to use the <code>ChannelFactory&lt;T&gt;</code> class. For the client we add a new console application project our solution. The code listing below shows the code for the WCF client.</p>
<div class="panel code content/images/csharp.png" title="The Main method of the client application."><pre style="text-align: left; line-height: normal"><span style="color: " class="keyword"><font color="#0000ff" face="Courier New"><font style="font-size: 12pt">using</font></font></span><font style="font-size: 12pt"><font face="Courier New"><font color="#000000"> <span class="identifier">System</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Linq</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WcfServer</span>;
 
</font><span style="color: " class="keyword"><font color="#0000ff">namespace</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WCFClient</span>
{
  </font><span style="color: " class="keyword"><font color="#0000ff">class</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">WcfCustomerServiceClient</font></span>
</font><font face="Courier New"><font color="#000000">  {
    </font><span style="color: " class="keyword"><font color="#0000ff">static</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">Main</span>(</font><span style="color: " class="keyword"><font color="#0000ff">string</font></span></font><font face="Courier New"><font color="#000000">[] <span class="identifier">args</span>)
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">var</font></span><font color="#000000"> <span class="identifier">channelFactory</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">ChannelFactory</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span><font color="#000000"><span class="operator">&gt;</span>(</font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">BasicHttpBinding</font></span><font color="#000000">(),</font></font></font></pre><pre style="text-align: left; line-height: normal"><font style="font-size: 12pt"><font face="Courier New"><font color="#000000">        </font><span style="color: " class="string"><font color="#a31515">"http://localhost:8080/CustomerService"</font></span></font><font face="Courier New"><font color="#000000">);
      </font><span style="color: " class="keyword"><font color="#0000ff">var</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customerService</span> <span class="operator">=</span> <span class="identifier">channelFactory</span><span class="operator">.</span><span class="identifier">CreateChannel</span>();
      </font><span style="color: " class="keyword"><font color="#0000ff">try</font></span>
</font><font face="Courier New"><font color="#000000">      {
        </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(</font><span style="color: " class="string"><font color="#a31515">"GetCustomers()"</font></span></font><font face="Courier New"><font color="#000000">);
        </font><span style="color: " class="keyword"><font color="#0000ff">var</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customers</span> <span class="operator">=</span> <span class="identifier">customerService</span><span class="operator">.</span><span class="identifier">GetCustomers</span>();
        </font><span style="color: " class="keyword"><font color="#0000ff">foreach</font></span><font color="#000000"> (</font><span style="color: " class="keyword"><font color="#0000ff">var</font></span><font color="#000000"> <span class="identifier">customer</span> </font><span style="color: " class="keyword"><font color="#0000ff">in</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customers</span>)
          </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(<span class="identifier">customer</span>);
      }
      </font><span style="color: " class="keyword"><font color="#0000ff">finally</font></span>
</font><font face="Courier New"><font color="#000000">      {
        </font><span style="color: " class="keyword"><font color="#0000ff">if</font></span><font color="#000000"> (<span class="identifier">customerService</span> <span class="operator">!=</span> </font><span style="color: " class="keyword"><font color="#0000ff">null</font></span></font><font face="Courier New"><font color="#000000">)
          (<span class="identifier">customerService</span> </font><span style="color: " class="keyword"><font color="#0000ff">as</font></span><font color="#000000"> </font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">IDisposable</font></span></font><font face="Courier New"><font color="#000000">)<span class="operator">.</span><span class="identifier">Dispose</span>();
        </font><span style="color: " class="keyword"><font color="#0000ff">if</font></span><font color="#000000"> (<span class="identifier">channelFactory</span> <span class="operator">!=</span> </font><span style="color: " class="keyword"><font color="#0000ff">null</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000">)
          <span class="identifier">channelFactory</span><span class="operator">.</span><span class="identifier">Close</span>();
      }
 
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">ReadLine</span>();
    }
  }
}
</font></font></font></pre>
<h3>Showing the WcfCustomerServiceClient.cs file</h3></div>
<p>Before this code will compile, we need to have a definition for <code>Customer</code> and <code>ICustomerService</code>. There are a few ways to do this:</p>
<ol>
<li>Ideally we would have a library project in our solution and these two classes/interfaces would be in this library project and both the server and client projects would reference this library project. 
<li>We could simply link to these classes/interface in our client project. That way if/when we make any changes to them, those changes are automatically visible in our client project as well. 
<li>We could simply redefine these classes/interfaces in our client project. That will work, but it's really bad idea.</li></ol>
<p>In this project I've opted for option #2 above.</p>
<p>The ChannelFactory and the channel/proxy (the customerService variable) both need to be Disposed or Closed which is why we're using the try-finally here.</p>
<p>Our client only uses the BasicHttpBinding (as you can see above). Typically a client only every uses a single binding while servers may implement/support multiple bindings and since our server does support multiple binding, let's see how we'd use those from our client. It's simple really. You can see the two other variations below. </p>
<div class="panel code content/images/csharp.png" title="Creating a ChannelFactory instance that uses the NetTcpBinding"><pre style="text-align: left; line-height: normal"><font face="Courier New"><font style="font-size: 12pt"><span style="color: " class="keyword"><font color="#0000ff">var</font></span><font color="#000000"> <span class="identifier">channelFactory</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">ChannelFactory</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span><font color="#000000"><span class="operator">&gt;</span>(</font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">NetTcpBinding</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000">(),
</font><span style="color: " class="string"><font color="#a31515">  "net.tcp://localhost:8081/CustomerService"</font></span><font color="#000000">);</font></font></font></pre><pre style="text-align: left; line-height: normal"><font face="Courier New"><font style="font-size: 12pt"><font color="#000000">
</font></font></font></pre>
<h3></h3></div>
<div class="panel code content/images/csharp.png" title="Creating an instane of a ChannelFactory that uses the NetNamedPipes Binding"><pre style="text-align: left; line-height: normal"><font face="Courier New"><span style="color: " class="keyword"><font color="#0000ff"><font style="font-size: 12pt">var</font></font></span><font style="font-size: 12pt"><font color="#000000"> <span class="identifier">channelFactory</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">ChannelFactory</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span><font color="#000000"><span class="operator">&gt;</span>(</font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">NetNamedPipeBinding</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000">(),
  </font><span style="color: " class="string"><font color="#a31515">"net.pipe://localhost/CustomerService"</font></span><font color="#000000">);
</font></font></font>

</pre></div>
<p>&nbsp;</p>
<p>At this point we're really done. We could run our service and then run our client and we should see a list of customers output to the console window. In the rest of this post, we'll look at:</p>
<ol>
<li>Building a WCF client proxy by hand 
<li>Getting our service to support metadata publishing so we can use the VS.NET IDE or svcutil.exe to have our proxy class generated for us.</li></ol>
<h2>WCF Proxy by hand</h2>
<p>We could if we wanted to, create a proxy for our <code>ICustomerService</code> contract by hand. Essentially, we'll be doing what the <code>ChannelFactory&lt;T&gt;</code> is doing behind the scenes.</p>
<p>Every proxy descends from <code>ClientBase&lt;T&gt;</code>. Because <code>ClientBase&lt;T&gt;</code> has a number of constructor overloads, we'll need to (or should) implement all of the constructor overloads and simply forward to calls on to <code>base()</code>.</p>
<p>In addition to the constructor overloads, we need to implement the methods our ICustomerService has. As you can see, from the code listing below, it's really not had and at all. It should be noted that the ChannelFactory does not support asynchronous calls. So if we need to make asynchronous calls we could either get the IDE to generate a proxy for us, provided our service supports generating metadata. Or we'll need to implement the proxy ourselves and also implement the asynchronous versions of the methods as well. See this earlier post on how to make existing synchronous calls asynchronous.</p>
<p><a href="http://www.matlus.com/iasyncresult-making-existing-methods-asnchronous/" target="_blank">IAsyncResult–Making Existing methods Asnchronous</a></p>
<div class="panel code content/images/csharp.png" title="Generating a proxy by hand by descending from ClientBase&lt;T&gt;"><pre style="text-align: left; line-height: normal"><span style="color: " class="keyword"><font color="#0000ff" face="Courier New"><font style="font-size: 12pt">using</font></font></span><font style="font-size: 12pt"><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">Collections</span><span class="operator">.</span><span class="identifier">Generic</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span>;
</font><span style="color: " class="keyword"><font color="#0000ff">using</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WcfServer</span>;
 
</font><span style="color: " class="keyword"><font color="#0000ff">namespace</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">WCFTcpClient</span>
{
  </font><span style="color: " class="keyword"><font color="#0000ff">class</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">CustomerClient</font></span><font color="#000000"> : </font><span style="color: " class="User Types"><font color="#2b91af">ClientBase</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">ICustomerService</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">&gt;</span>
  {
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">CustomerClient</span>()
    {
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> <span class="identifier">CustomerClient</span>(</font><span style="color: " class="keyword"><font color="#0000ff">string</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">endpointConfigurationName</span>) :
      </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000">(<span class="identifier">endpointConfigurationName</span>)
    {
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> <span class="identifier">CustomerClient</span>(</font><span style="color: " class="keyword"><font color="#0000ff">string</font></span><font color="#000000"> <span class="identifier">endpointConfigurationName</span>, </font><span style="color: " class="keyword"><font color="#0000ff">string</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">remoteAddress</span>) :
      </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000">(<span class="identifier">endpointConfigurationName</span>, <span class="identifier">remoteAddress</span>)
    {
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> <span class="identifier">CustomerClient</span>(</font><span style="color: " class="keyword"><font color="#0000ff">string</font></span><font color="#000000"> <span class="identifier">endpointConfigurationName</span>, <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span><span class="operator">.</span></font><span style="color: " class="User Types"><font color="#2b91af">EndpointAddress</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">remoteAddress</span>) :
      </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000">(<span class="identifier">endpointConfigurationName</span>, <span class="identifier">remoteAddress</span>)
    {
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> <span class="identifier">CustomerClient</span>(<span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span><span class="operator">.</span><span class="identifier">Channels</span><span class="operator">.</span></font><span style="color: " class="User Types"><font color="#2b91af">Binding</font></span><font color="#000000"> <span class="identifier">binding</span>, <span class="identifier">System</span><span class="operator">.</span><span class="identifier">ServiceModel</span><span class="operator">.</span></font><span style="color: " class="User Types"><font color="#2b91af">EndpointAddress</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">remoteAddress</span>) :
      </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000">(<span class="identifier">binding</span>, <span class="identifier">remoteAddress</span>)
    {
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">IEnumerable</font></span><span class="operator"><font color="#000000">&lt;</font></span><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">&gt;</span> <span class="identifier">GetCustomers</span>()
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">return</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">Channel</span><span class="operator">.</span><span class="identifier">GetCustomers</span>();
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span><font color="#000000"> <span class="identifier">GetCustomer</span>(</font><span style="color: " class="keyword"><font color="#0000ff">int</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">id</span>)
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">return</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">Channel</span><span class="operator">.</span><span class="identifier">GetCustomer</span>(<span class="identifier">id</span>);
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">int</font></span><font color="#000000"> <span class="identifier">InsertCustomer</span>(</font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customer</span>)
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">return</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">Channel</span><span class="operator">.</span><span class="identifier">InsertCustomer</span>(<span class="identifier">customer</span>);
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">UpdateCustomer</span>(</font><span style="color: " class="User Types"><font color="#2b91af">Customer</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customer</span>)
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span></font><font face="Courier New"><font color="#000000"><span class="operator">.</span><span class="identifier">Channel</span><span class="operator">.</span><span class="identifier">UpdateCustomer</span>(<span class="identifier">customer</span>);
    }
 
    </font><span style="color: " class="keyword"><font color="#0000ff">public</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">DeleteCustomer</span>(</font><span style="color: " class="keyword"><font color="#0000ff">int</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000"> <span class="identifier">customerId</span>)
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">base</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">Channel</span><span class="operator">.</span><span class="identifier">DeleteCustomer</span>(<span class="identifier">customerId</span>);
    }
  }
}
</font></font></font></pre>
<h3>Showing the CustomerServiceClientProxy.cs file</h3></div>
<p>Once we have this class in place, the way we'd create an instance of the proxy and use it is shown in the code listing below.</p>
<div class="panel code content/images/csharp.png" title="Creating an instance of our hand-crafted WCF client proxy and using it"><pre style="text-align: left; line-height: normal"><font face="Courier New"><font style="font-size: 12pt"><span style="color: " class="keyword"><font color="#0000ff">var</font></span><font color="#000000"> <span class="identifier">customerService</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">CustomerClient</font></span><font color="#000000">(</font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">NetTcpBinding</font></span></font></font><font style="font-size: 12pt"><font face="Courier New"><font color="#000000">(),
  </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">EndpointAddress</font></span><font color="#000000">(</font><span style="color: " class="string"><font color="#a31515">"net.tcp://localhost:8081/CustomerService"</font></span></font><font face="Courier New"><font color="#000000">));
</font><span style="color: " class="keyword"><font color="#0000ff">  try</font></span>
</font><font face="Courier New"><font color="#000000">  {
    </font><span style="color: " class="keyword"><font color="#0000ff">foreach</font></span><font color="#000000"> (</font><span style="color: " class="keyword"><font color="#0000ff">var</font></span><font color="#000000"> <span class="identifier">customer</span> </font><span style="color: " class="keyword"><font color="#0000ff">in</font></span></font><font face="Courier New"><font color="#000000"> <span class="identifier">customerService</span><span class="operator">.</span><span class="identifier">GetCustomers</span>())
      </font><span style="color: " class="User Types"><font color="#2b91af">Console</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000"><span class="operator">.</span><span class="identifier">WriteLine</span>(<span class="identifier">customer</span>);
  }
  </font><span style="color: " class="keyword"><font color="#0000ff">finally</font></span>
<font color="#000000">  {
    <span class="identifier">customerService</span><span class="operator">.</span><span class="identifier">Close</span>();
  }
</font></font></font>

</pre>
<h3>Showing how we've use our hand crafted WCF client proxy.</h3></div>
<p>In the code above, the proxy is using the <code>NetTcpBinding</code>. You can make the required changes as shown earlier if you wanted to use the <code>BaseHttpBinding</code> or the <code>NetNamedPipesBinding</code>.</p>
<h2>WCF Service supporting metadata publishing</h2>
<p>Next, well look at programmatically configuring our WCF service to support metadata publishing. There two ways for a service in WCF to support metadata publishing.</p>
<p>Before we start adding this capability to our service, let's confirm that our service does not support this capability yet. So start up the service application and then using a browser browser to the base address of the http binding, which is http://localhost:8080 . What you should see is a page that looks like this:</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="MetadataPublishingNotSupported" border="0" alt="MetadataPublishingNotSupported" src="http://www.matlus.com/content/uploads/2011/03/MetadataPublishingNotSupported_680328fc-b106-4c9a-bf7e-6a29678f6863.jpg" width="638" height="767"></p>
<p>As you can see in the image above, metadata publishing is not currently enabled. There are two styles in which a WCF service may published metadata. Both are industry standards. One is by way of a WSDL document and it always works over HTTP-GET. Let's look at enabling this first. The code below shows that we've added a behavior to our service description in order to enabled metadata publishing as WSDL document. <strong><em>This code MUST appear before you Open the host</em></strong>.</p>
<div class="panel code content/images/csharp.png" title="Enabling Metadata Publishing as a WSDL document"><pre style="text-align: left; line-height: normal"><font face="Courier New"><span style="color: " class="keyword"><font color="#0000ff"><font style="font-size: 12pt">var</font></font></span><font style="font-size: 12pt"><font color="#000000"> <span class="identifier">serviceMetadataBehavior</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">ServiceMetadataBehavior</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000">();
<span class="identifier">serviceMetadataBehavior</span><span class="operator">.</span><span class="identifier">HttpGetEnabled</span> <span class="operator">=</span> </font><span style="color: " class="keyword"><font color="#0000ff">true</font></span><font color="#000000">;
<span class="identifier">host</span><span class="operator">.</span><span class="identifier">Description</span><span class="operator">.</span><span class="identifier">Behaviors</span><span class="operator">.</span><span class="identifier">Add</span>(<span class="identifier">serviceMetadataBehavior</span>);
</font></font></font></pre>
<h3>Adding the ServiceMetadataBehavior to the service Description</h3></div>
<p>Now, run the service and browse to the same url again. What you should see is something similar to what is shown in the image blow.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="MetadataPublishingAsWSDL" border="0" alt="MetadataPublishingAsWSDL" src="http://www.matlus.com/content/uploads/2011/03/MetadataPublishingAsWSDL_5d893635-44d3-45fa-ab08-563b293cd63e.jpg" width="638" height="767"></p>
<p>Navigating to the first link we see will bring up the WSDL document that clients can use to build a proxy for our service. The other way to publish metadata is to use the Metadata Exchange protocol. This protocol works via endpoints (and not behaviors). And since they are endpoints they also include (or indicate) the transport protocol (the binding). In other words, if your service only supports the <code>NetTcpBinding</code>, then you can publish the metadata using another NetTcpbinding endpoint (rather than only HTTP-GET) or you may decide to publish the metadata over HTTP. It's up to you.</p>
<div class="panel code content/images/csharp.png" title="Adding the MetadataExchangeBinding for the IMetaDataExchange contract"><pre style="text-align: left; line-height: normal"><font face="Courier New"><span style="color: " class="User Types"><font color="#2b91af"><font style="font-size: 12pt">Binding</font></font></span><font style="font-size: 12pt"><font color="#000000"> <span class="identifier">mexBinding</span> <span class="operator">=</span> </font><span style="color: " class="User Types"><font color="#2b91af">MetadataExchangeBindings</font></span></font></font><font face="Courier New"><font style="font-size: 12pt"><font color="#000000"><span class="operator">.</span><span class="identifier">CreateMexHttpBinding</span>();
<span class="identifier">host</span><span class="operator">.</span><span class="identifier">AddServiceEndpoint</span>(</font><span style="color: " class="keyword"><font color="#0000ff">typeof</font></span><font color="#000000">(</font><span style="color: " class="User Types(Interfaces)"><font color="#2b91af">IMetadataExchange</font></span><font color="#000000">), <span class="identifier">mexBinding</span>, </font><span style="color: " class="string"><font color="#a31515">"mex"</font></span><font color="#000000">);
</font></font></font></pre>
<h3>Adding a Metadata echange endpoint</h3></div>
<p>Notice in the code above that we're using the MexHttpBinding (CreateMexHttpBinding()). The other methods available are:</p>
<ol>
<li>CreateMexHttpsBinding</li>
<li>CreateMexTcpBinding</li>
<li>CreateMexNamedPipeBinding</li></ol>
<p>At the time of adding the endpoint to our service host, we've included a relative Url ("mex"). So once again, the complete Url will be the <code>BaseAddress</code> (of that Binding <code>http://localhost:8080</code>) plus the relative Url. So the complete Url for our MEX metadata endpoint is <code>http://localhost:8008/mex</code>.</p>
<p>It should be noted that even if we wanted to only publish our MEX endpoint, we'd still need to add the <code>ServiceMetadataBehavior</code> like we did to enabled WSDL publishing. We won't have to set the <code>HttpGetEnabled</code> property to true (we could if we wanted to) however.</p>]]></description><category>Programming/WCF</category><category>Bindings</category><category>Proxy</category><category>WCF</category></item><item><title>ASP.NET Response.Redirect Performance Issue</title><pubDate>Wed, 02 Mar 2011 00:33:03 GMT</pubDate><link>http://www.matlus.com/asp-net-response-redirect-performance-issue/</link><guid isPermaLink="true">http://www.matlus.com/asp-net-response-redirect-performance-issue/</guid><description><![CDATA[<p><a name="codelisting1"></a></p> <p>This is a short post and I'm writing this because I've seen a lot of people using <code>Response.Redirect(url)</code> or <code>Response.RedirectPremanent(url)</code> and not using the overloads:</p> <ul> <li><code>Response.Redirect(url, false)</code></li> <li><code>Response.RedirectPermanent(url, false)</code></li></ul> <p>So rather than repeat the same thing over and over, I've decided to write a blog post about it in the hopes that others may find it and learn from it. There are two overloads to these methods (I'm only showing the Response.Redirect method but the same applies to Response.RedirectPermanent):</p> <p><pre class="csharpcode">Response.Redirect(<span class="kwrd">string</span> url)
Response.Redirect(<span class="kwrd">string</span> url, <span class="kwrd">bool</span> endResponse)

</pre>
<p>You typically use <code>Response.Redirect</code> when we want to redirect a request to another page in our application or another website or a send an Http status 301 Permanently moved or something similar. In our code the way that this works is that the line right after the call to redirect <em>does not execute</em>. Indeed, most times (if not all the time) this is exactly the behavior we want/expect. It's like (in C#) saying <code>return</code> and the execution jumps right out of the current method. It makes structuring your flow of logic that much easier.</p>
<p>Here's the problem. Think about how, when you call Response.Redirect(url) the next line in our code is not executed (without explicitly saying return)? Yup, that's right, an exception was thrown. That's the only way to boot right out of a method without explicitly saying return. When we call Response.Redirect(url), it calls the second overload passing in <code>true</code> as the parameter to <code>endResponse</code>. What this does is, it calls <code>Response.End()</code>, and Response.End() throws a <code>ThreadAbortException</code> (that's the only way it can truly end the response).</p>
<p>So what we should do is use the second overload (always) and pass it <code>false</code> as the second parameter (always). But….but…but, yes, I know, in that case our code continues to execute and that's not what we want!</p>
<p>There are two solutions to this predicament.</p>
<ol>
<li>Structure our code such that the condition that warrants a Response.Redirect follows a path such that nothing else is done in our Page/Handler/Controller and our method ends gracefully. 
<li>Call <code>CompleteRequest()</code> right after calling Response.Redirect(url, false). This is a method of the ApplicationInstance object, which we can get from the current context, so something like HttpContext.ApplicationInstance.CompleteRequest();. Note that the <em><strong>execution of code will continue as normal</strong></em> (and not exit/abort). But what will happen is that as soon as the Page/Handler/Controller completes the response the ASP.NET pipeline will jump straight to the EndRequest event. So the Request does "complete" (without any ThreadAbortException), but your code also executes. This may not be something you want to happen. But I thought I'd mention it anyway.</li></ol>
<p>As regards option 1 above, here is a code listing that show you what I mean. Think of the <code>BuildPage</code> method shown below as the <code>ProcessRequest</code> method of a handler. That is once this method finishes we're done processing the request (this is code I've pulled out from <a href="http://www.matlus.com/orion/" target="_blank">Orion</a> by blog engine). There is only one case in which we want to process the request (the if condition). All other cases warrant either a permanent redirect or redirect. All of the code expected to be executed under the normal case is inside the if condition. </p>
<p>&nbsp;</p>
<div class="panel code content/images/csharp.png" title="Using Response.Redirect/RedirectPermanent to gracefully exist from a method"><pre style="text-align: left; line-height: normal"><font color="#000000"><font style="font-size: 9.8pt">    </font></font><font style="font-size: 9.8pt"><span style="color: " class="keyword"><font color="#0000ff">protected</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">override</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">void</font></span><font color="#000000"> <span class="identifier">BuildPage</span>(</font><span style="color: " class="User Types"><font color="#2b91af">HttpContextBase</font></span><font color="#000000"> <span class="identifier">httpContext</span>, </font><span style="color: " class="keyword"><font color="#0000ff">object</font></span><font color="#000000"> <span class="identifier">model</span>)
    {
      </font><span style="color: " class="keyword"><font color="#0000ff">var</font></span><font color="#000000"> <span class="identifier">postDisplayDataDto</span> <span class="operator">=</span> (</font><span style="color: " class="User Types"><font color="#2b91af">PostDisplayDataDto</font></span><font color="#000000">)<span class="identifier">model</span>;
      </font><span style="color: " class="keyword"><font color="#0000ff">if</font></span><font color="#000000"> (<span class="identifier">model</span> <span class="operator">!=</span> </font><span style="color: " class="keyword"><font color="#0000ff">null</font></span><font color="#000000"> <span class="operator">&amp;&amp;</span> <span class="identifier">postDisplayDataDto</span><span class="operator">.</span><span class="identifier">PostsDataTable</span><span class="operator">.</span><span class="identifier">Rows</span><span class="operator">.</span><span class="identifier">Count</span> <span class="operator">==</span> <span class="number">1</span>)
      {
        </font><span style="color: " class="comment"><font color="#008000">//Ttile of the Post + On + Blog name</font></span>
<font color="#000000">        <span class="identifier">TitleView</span><span class="operator">.</span><span class="identifier">Text</span> <span class="operator">=</span> <span class="identifier">postDisplayDataDto</span><span class="operator">.</span><span class="identifier">PostsDataTable</span><span class="operator">.</span><span class="identifier">Rows</span>[<span class="number">0</span>][<span class="number">4</span>]<span class="operator">.</span><span class="identifier">ToString</span>() <span class="operator">+</span> </font><span style="color: " class="string"><font color="#a31515">" On "</font></span><font color="#000000"> <span class="operator">+</span> <span class="identifier">BlogInfo</span><span class="operator">.</span><span class="identifier">BlogInfoName</span>;
        </font><span style="color: " class="comment"><font color="#008000">//Title of the Post plus the Post Text</font></span>
<font color="#000000">        <span class="identifier">MetaDescriptionView</span><span class="operator">.</span><span class="identifier">Description</span> <span class="operator">=</span> <span class="identifier">postDisplayDataDto</span><span class="operator">.</span><span class="identifier">PostsDataTable</span><span class="operator">.</span><span class="identifier">Rows</span>[<span class="number">0</span>][<span class="number">4</span>]<span class="operator">.</span><span class="identifier">ToString</span>() <span class="operator">+</span> </font><span style="color: " class="string"><font color="#a31515">" "</font></span><font color="#000000"> <span class="operator">+</span> <span class="identifier">postDisplayDataDto</span><span class="operator">.</span><span class="identifier">PostsDataTable</span><span class="operator">.</span><span class="identifier">Rows</span>[<span class="number">0</span>][<span class="number">5</span>]<span class="operator">.</span><span class="identifier">ToString</span>();
 
        <span class="identifier">RegisterView</span>(</font><span style="color: " class="string"><font color="#a31515">"Body"</font></span><font color="#000000">, </font><span style="color: " class="keyword"><font color="#0000ff">new</font></span><font color="#000000"> </font><span style="color: " class="User Types"><font color="#2b91af">PostView</font></span><font color="#000000">(<span class="identifier">httpContext</span>, <span class="identifier">postDisplayDataDto</span>,
          <span class="identifier">Configuration</span>[</font><span style="color: " class="string"><font color="#a31515">"CategoryCaption"</font></span><font color="#000000">],
          <span class="identifier">Configuration</span>[</font><span style="color: " class="string"><font color="#a31515">"TagCaption"</font></span><font color="#000000">]
          ));
      }
      </font><span style="color: " class="keyword"><font color="#0000ff">else</font></span><font color="#000000"> </font><span style="color: " class="keyword"><font color="#0000ff">if</font></span><font color="#000000"> (<span class="identifier">model</span> <span class="operator">==</span> </font><span style="color: " class="keyword"><font color="#0000ff">null</font></span><font color="#000000">)
        <span class="identifier">HttpContext</span><span class="operator">.</span><span class="identifier">Response</span><span class="operator">.</span><span class="identifier">RedirectPermanent</span>(</font><span style="color: " class="User Types"><font color="#2b91af">Url</font></span><font color="#000000"><span class="operator">.</span><span class="identifier">Post</span>(<span class="identifier">AppDomainAppVirtualPath</span>, <span class="identifier">PostSlug</span>), </font><span style="color: " class="keyword"><font color="#0000ff">false</font></span><font color="#000000">);
      </font><span style="color: " class="keyword"><font color="#0000ff">else</font></span>
<font color="#000000">        <span class="identifier">PermanentlyRedirectToAppropriateLocation</span>();
    }
</font></font></pre>
<h3>Showing one way to gracefully exit from a method</h3></div>]]></description><category>Programming/ASP.NET</category><category>Performance</category></item><item><title>HttpWebRequest - Asynchronous Programming Model/Task.Factory.FromAsyc</title><pubDate>Wed, 23 Feb 2011 23:22:01 GMT</pubDate><link>http://www.matlus.com/httpwebrequest-asynchronous-programming/</link><guid isPermaLink="true">http://www.matlus.com/httpwebrequest-asynchronous-programming/</guid><description><![CDATA[<p>The Asynchronous Programming Model (or APM) has been around since .NET 1.1 and is still (as of .NET 4.0) the best/recommended solution for asynchronous I/O. Many people go down the route of using a multi-threaded approach to try get speedup when the workload is I/O bound. Using multiple threads to do I/O bound tasks such as Disk I/O and Network I/O, won't (in most cases) give you any speed up and in fact could end up hurting performance. </p> <p>If the workload is compute bound (rather than I/O bound) then it makes complete sense to use multiple threads (provided you have multiple cores and the work is fairly long running and so justifies the overhead of spawning and managing multiple threads), as discussed in this post <a title="Data Parallel &ndash; Parallel Programming in C#/.NET" href="http://www.matlus.com/data-parallel-parallel-programming-in-net/" target="_blank">Data Parallel – Parallel Programming in C#/.NET</a></p> <p>Using the APM is not the easiest thing to do primarily because it works with callbacks so you start in one method in your code and you get the result in another method. So ideally you should re-think you design so as to work in an asynchronous workflow pattern rather than a synchronous pattern.</p> <p>In this post I’m going to show you a few ways in which you can use the HttpWebRequest class to make multiple http requests while getting really good performance/throughput. I strongly advice against using threads for I/O bound work when you're after performance and throughput. Of course in some cases, you could be using the synchronous option or the synchronous option with threads if I/O throughput is not a big concern. Or you could use a combination of threads and asynchronous work. It all depends.</p> <p>When working with Http we invariably have different needs in different projects. Sometimes we:</p> <ol> <li>Need to make multiple calls to some endpoint and wait till each one is done before we can process all of the responses.  <li>Need to make multiple calls but have to wait for each one to complete because the response of one feeds into the request of the next.  <li>Need to make multiple calls to some endpoint and can continue processing the responses as soon as we receive them (the ideal situation for an Asynchronous work flow).  <li>All of the above could be using either the Http GET or POST methods. In the case of the Http POST method there is an additional asynchronous call to be made so it adds a bit more complexity.<br></li></ol> <p>In this post I’ll show you various options to accomplish these kinds of things using the APM as well as Tasks (System.Threading.Tasks.Task).</p> <p>The HttpWebRequest makes it particularly difficult to use the APM because if you want to use it (correctly) for POST methods in an asynchronous manner it involves calling two methods asynchronously back to back and thus also involves 2 separate callback methods.</p> <p>First let’s take a look at how we’d use the HttpWebRequest in an asynchronous manner, with the assumption that your program logic (or workflow) is designed to be asynchronous as well. I’m intentionally not using lambdas here for those of you who either don’t like to use lambdas or get confused by them.</p> <p>In the code listing below, I present the HttpSocket class that essentially makes it really simple to make asynchronous Http calls. Note that the reason I've presented a class here is because there are some common methods that the primary methods (listed below) use and so I thought it best to present 4 of these methods in the form of a class.</p> <p>The class is a static class and essentially a wrapper that provides some helper methods as well. This class has 4 public methods of interest to this discussion, namely:</p> <ol> <li>PostAsync  <li>GetAsync  <li>PostAsyncTask  <li>GetAsyncTask</li></ol> <p>The <code>PostAsync</code> and <code>GetAsync</code> methods use the Begin/End pairs of methods available in the <code>HttpWebRequest</code> class. While the <code>PostAsyncTask</code> and <code>GetAsyncTask</code> methods use <code>Tasks</code> (new in .NET 4.0) to get the job done. In particular, they use the <code>Task.Factory.FromAsync</code> method.</p> <p>From a performance perspective, both styles perform the same, but the <code>PostAsync</code> and <code>GetAsync</code> methods use less resources and this could be beneficial in large production systems where you make tons of http calls out to some other http service.</p> <p>&nbsp;</p><a name="codelisting1"></a> <div class="panel code content/images/csharp.png" title="The HttpSocket class"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> System.Text;
<span class="kwrd">using</span> System.Net;
<span class="kwrd">using</span> System.Collections.Specialized;
<span class="kwrd">using</span> System.IO;
<span class="kwrd">using</span> System.Threading;
<span class="kwrd">using</span> System.Threading.Tasks;
<span class="kwrd">using</span> System.Runtime.Serialization.Json;

<span class="kwrd">namespace</span> ConsoleApplication3
{
  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> HttpSocket
  {
    <span class="kwrd">static</span> HttpWebRequest CreateHttpWebRequest(<span class="kwrd">string</span> url, <span class="kwrd">string</span> httpMethod, <span class="kwrd">string</span> contentType)
    {
      var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
      httpWebRequest.ContentType = contentType;
      httpWebRequest.Method = httpMethod;
      <span class="kwrd">return</span> httpWebRequest;
    }

    <span class="kwrd">static</span> <span class="kwrd">byte</span>[] GetRequestBytes(NameValueCollection postParameters)
    {
      <span class="kwrd">if</span> (postParameters == <span class="kwrd">null</span> || postParameters.Count == 0)
        <span class="kwrd">return</span> <span class="kwrd">new</span> <span class="kwrd">byte</span>[0];
      var sb = <span class="kwrd">new</span> StringBuilder();
      <span class="kwrd">foreach</span> (var key <span class="kwrd">in</span> postParameters.AllKeys)
        sb.Append(key + <span class="str">"="</span> + postParameters[key] + <span class="str">"&amp;"</span>);
      sb.Length = sb.Length - 1;
      <span class="kwrd">return</span> Encoding.UTF8.GetBytes(sb.ToString());
    }

    <span class="kwrd">static</span> <span class="kwrd">void</span> BeginGetRequestStreamCallback(IAsyncResult asyncResult)
    {
      Stream requestStream = <span class="kwrd">null</span>;
      HttpWebRequestAsyncState asyncState = <span class="kwrd">null</span>;
      <span class="kwrd">try</span>
      {
        asyncState = (HttpWebRequestAsyncState)asyncResult.AsyncState;
        requestStream = asyncState.HttpWebRequest.EndGetRequestStream(asyncResult);
        requestStream.Write(asyncState.RequestBytes, 0, asyncState.RequestBytes.Length);
        requestStream.Close();
        asyncState.HttpWebRequest.BeginGetResponse(BeginGetResponseCallback,
          <span class="kwrd">new</span> HttpWebRequestAsyncState
          {
            HttpWebRequest = asyncState.HttpWebRequest,
            ResponseCallback = asyncState.ResponseCallback,
            State = asyncState.State
          });
      }
      <span class="kwrd">catch</span> (Exception ex)
      {
        <span class="kwrd">if</span> (asyncState != <span class="kwrd">null</span>)
          asyncState.ResponseCallback(<span class="kwrd">new</span> HttpWebRequestCallbackState(ex));
        <span class="kwrd">else</span>
          <span class="kwrd">throw</span>;
      }
      <span class="kwrd">finally</span>
      {
        <span class="kwrd">if</span> (requestStream != <span class="kwrd">null</span>)
          requestStream.Close();
      }
    }

    <span class="kwrd">static</span> <span class="kwrd">void</span> BeginGetResponseCallback(IAsyncResult asyncResult)
    {
      WebResponse webResponse = <span class="kwrd">null</span>;
      Stream responseStream = <span class="kwrd">null</span>;
      HttpWebRequestAsyncState asyncState = <span class="kwrd">null</span>;
      <span class="kwrd">try</span>
      {
        asyncState = (HttpWebRequestAsyncState)asyncResult.AsyncState;
        webResponse = asyncState.HttpWebRequest.EndGetResponse(asyncResult);
        responseStream = webResponse.GetResponseStream();
        var webRequestCallbackState = <span class="kwrd">new</span> HttpWebRequestCallbackState(responseStream, asyncState.State);
        asyncState.ResponseCallback(webRequestCallbackState);
        responseStream.Close();
        responseStream = <span class="kwrd">null</span>;
        webResponse.Close();
        webResponse = <span class="kwrd">null</span>;
      }
      <span class="kwrd">catch</span> (Exception ex)
      {
        <span class="kwrd">if</span> (asyncState != <span class="kwrd">null</span>)
          asyncState.ResponseCallback(<span class="kwrd">new</span> HttpWebRequestCallbackState(ex));
        <span class="kwrd">else</span>
          <span class="kwrd">throw</span>;
      }
      <span class="kwrd">finally</span>
      {
        <span class="kwrd">if</span> (responseStream != <span class="kwrd">null</span>)
          responseStream.Close();
        <span class="kwrd">if</span> (webResponse != <span class="kwrd">null</span>)
          webResponse.Close();
      }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// If the response from a remote server is in text form</span>
    <span class="rem">/// you can use this method to get the text from the ResponseStream</span>
    <span class="rem">/// This method Disposes the stream before it returns</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="responseStream"&gt;The responseStream that was provided in the callback delegate's HttpWebRequestCallbackState parameter&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> GetResponseText(Stream responseStream)
    {
      <span class="kwrd">using</span> (var reader = <span class="kwrd">new</span> StreamReader(responseStream))
      {
        <span class="kwrd">return</span> reader.ReadToEnd();
      }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method uses the DataContractJsonSerializer to</span>
    <span class="rem">/// Deserialize the contents of a stream to an instance</span>
    <span class="rem">/// of an object of type T.</span>
    <span class="rem">/// This method disposes the stream before returning</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;</span>
    <span class="rem">/// &lt;param name="stream"&gt;A Stream. Typically the ResponseStream&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;An instance of an object of type T&lt;/returns&gt;</span>
    <span class="kwrd">static</span> T DeSerializeToJson&lt;T&gt;(Stream stream)
    {
      <span class="kwrd">using</span> (stream)
      {
        var deserializer = <span class="kwrd">new</span> DataContractJsonSerializer(<span class="kwrd">typeof</span>(T));
        <span class="kwrd">return</span> (T)deserializer.ReadObject(stream);
      }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method does an Http POST sending any post parameters to the url provided</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="url"&gt;The url to make an Http POST to&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="postParameters"&gt;The form parameters if any that need to be POSTed&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="responseCallback"&gt;The callback delegate that should be called when the response returns from the remote server&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="state"&gt;Any state information you need to pass along to be available in the callback method when it is called&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="contentType"&gt;The Content-Type of the Http request&lt;/param&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> PostAsync(<span class="kwrd">string</span> url, NameValueCollection postParameters,
      Action&lt;HttpWebRequestCallbackState&gt; responseCallback, <span class="kwrd">object</span> state = <span class="kwrd">null</span>,
      <span class="kwrd">string</span> contentType = <span class="str">"application/x-www-form-urlencoded"</span>)
    {
      var httpWebRequest = CreateHttpWebRequest(url, <span class="str">"POST"</span>, contentType);
      var requestBytes = GetRequestBytes(postParameters);
      httpWebRequest.ContentLength = requestBytes.Length;

      httpWebRequest.BeginGetRequestStream(BeginGetRequestStreamCallback,
        <span class="kwrd">new</span> HttpWebRequestAsyncState()
        {
          RequestBytes = requestBytes,
          HttpWebRequest = httpWebRequest,
          ResponseCallback = responseCallback,  
          State = state
        });
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method does an Http GET to the provided url and calls the responseCallback delegate</span>
    <span class="rem">/// providing it with the response returned from the remote server.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="url"&gt;The url to make an Http GET to&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="responseCallback"&gt;The callback delegate that should be called when the response returns from the remote server&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="state"&gt;Any state information you need to pass along to be available in the callback method when it is called&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="contentType"&gt;The Content-Type of the Http request&lt;/param&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetAsync(<span class="kwrd">string</span> url, Action&lt;HttpWebRequestCallbackState&gt; responseCallback,
      <span class="kwrd">object</span> state = <span class="kwrd">null</span>, <span class="kwrd">string</span> contentType = <span class="str">"application/x-www-form-urlencoded"</span>)
    {
      var httpWebRequest = CreateHttpWebRequest(url, <span class="str">"GET"</span>, contentType);

      httpWebRequest.BeginGetResponse(BeginGetResponseCallback,
        <span class="kwrd">new</span> HttpWebRequestAsyncState()
        {
          HttpWebRequest = httpWebRequest,
          ResponseCallback = responseCallback,
          State = state
        });
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> PostAsyncTask(<span class="kwrd">string</span> url, NameValueCollection postParameters,
      Action&lt;HttpWebRequestCallbackState&gt; responseCallback, <span class="kwrd">object</span> state = <span class="kwrd">null</span>,
      <span class="kwrd">string</span> contentType = <span class="str">"application/x-www-form-urlencoded"</span>)
    {
      var httpWebRequest = CreateHttpWebRequest(url, <span class="str">"POST"</span>, contentType);
      var requestBytes = GetRequestBytes(postParameters);
      httpWebRequest.ContentLength = requestBytes.Length;

      var asyncState = <span class="kwrd">new</span> HttpWebRequestAsyncState()
      {
        RequestBytes = requestBytes,
        HttpWebRequest = httpWebRequest,
        ResponseCallback = responseCallback,
        State = state
      };

      Task.Factory.FromAsync&lt;Stream&gt;(httpWebRequest.BeginGetRequestStream,
        httpWebRequest.EndGetRequestStream, asyncState, TaskCreationOptions.None)
        .ContinueWith&lt;HttpWebRequestAsyncState&gt;(task =&gt;
        {
          var asyncState2 = (HttpWebRequestAsyncState)task.AsyncState;
          <span class="kwrd">using</span> (var requestStream = task.Result)
          {
            requestStream.Write(asyncState2.RequestBytes, 0, asyncState2.RequestBytes.Length);
          }          
          <span class="kwrd">return</span> asyncState2;
        })
        .ContinueWith(task =&gt;
        {
          var httpWebRequestAsyncState2 = (HttpWebRequestAsyncState)task.Result;
          var hwr2 = httpWebRequestAsyncState2.HttpWebRequest;
          Task.Factory.FromAsync&lt;WebResponse&gt;(hwr2.BeginGetResponse,
            hwr2.EndGetResponse, httpWebRequestAsyncState2, TaskCreationOptions.None)
            .ContinueWith(task2 =&gt;
            {
              WebResponse webResponse = <span class="kwrd">null</span>;
              Stream responseStream = <span class="kwrd">null</span>;
              <span class="kwrd">try</span>
              {
                var asyncState3 = (HttpWebRequestAsyncState)task2.AsyncState;
                webResponse = task2.Result;
                responseStream = webResponse.GetResponseStream();
                responseCallback(<span class="kwrd">new</span> HttpWebRequestCallbackState(responseStream, asyncState3));
              }
              <span class="kwrd">finally</span>
              {
                <span class="kwrd">if</span> (responseStream != <span class="kwrd">null</span>)
                  responseStream.Close();
                <span class="kwrd">if</span> (webResponse != <span class="kwrd">null</span>)
                  webResponse.Close();
              }
            });
        });
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetAsyncTask(<span class="kwrd">string</span> url, Action&lt;HttpWebRequestCallbackState&gt; responseCallback,
      <span class="kwrd">object</span> state = <span class="kwrd">null</span>, <span class="kwrd">string</span> contentType = <span class="str">"application/x-www-form-urlencoded"</span>)
    {
      var httpWebRequest = CreateHttpWebRequest(url, <span class="str">"GET"</span>, contentType);
      Task.Factory.FromAsync&lt;WebResponse&gt;(httpWebRequest.BeginGetResponse,
        httpWebRequest.EndGetResponse, <span class="kwrd">null</span>).ContinueWith(task =&gt;
          {
            var webResponse = task.Result;
            var responseStream = webResponse.GetResponseStream();
            responseCallback(<span class="kwrd">new</span> HttpWebRequestCallbackState(webResponse.GetResponseStream(), state));
            responseStream.Close();
            webResponse.Close();
          });
    }
  }

  <span class="rem">/// &lt;summary&gt;</span>
  <span class="rem">/// This class is used to pass on "state" between each Begin/End call</span>
  <span class="rem">/// It also carries the user supplied "state" object all the way till</span>
  <span class="rem">/// the end where is then hands off the state object to the</span>
  <span class="rem">/// HttpWebRequestCallbackState object.</span>
  <span class="rem">/// &lt;/summary&gt;</span>
  <span class="kwrd">class</span> HttpWebRequestAsyncState
  {
    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] RequestBytes { get; set; }
    <span class="kwrd">public</span> HttpWebRequest HttpWebRequest { get; set; }
    <span class="kwrd">public</span> Action&lt;HttpWebRequestCallbackState&gt; ResponseCallback { get; set; }
    <span class="kwrd">public</span> Object State { get; set; }
  }

  <span class="rem">/// &lt;summary&gt;</span>
  <span class="rem">/// This class is passed on to the user supplied callback method</span>
  <span class="rem">/// as a parameter. If there was an exception during the process</span>
  <span class="rem">/// then the Exception property will not be null and will hold</span>
  <span class="rem">/// a reference to the Exception that was raised.</span>
  <span class="rem">/// The ResponseStream property will be not null in the case of</span>
  <span class="rem">/// a sucessful request/response cycle. Use this stream to</span>
  <span class="rem">/// exctract the response.</span>
  <span class="rem">/// &lt;/summary&gt;</span>
  <span class="kwrd">public</span> <span class="kwrd">class</span> HttpWebRequestCallbackState
  {
    <span class="kwrd">public</span> Stream ResponseStream { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Exception Exception { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Object State { get; set; }

    <span class="kwrd">public</span> HttpWebRequestCallbackState(Stream responseStream, <span class="kwrd">object</span> state)
    {
      ResponseStream = responseStream;
      State = state;
    }

    <span class="kwrd">public</span> HttpWebRequestCallbackState(Exception exception)
    {
      Exception = exception;
    }
  }
}</pre>
<h3>Code List 1: Showing the Complete HttpSocket class</h3></div>
<h2>Using HttpWebRequests in Asynchronous Workflows</h2>
<p>Using any of the methods in the HttpSocket class for asynchronous workflows is really simple. You call one of the Postxxx or Getxxx methods passing it some parameters and the callback delegate as shown in the <a href="#codelisting2">Code Listing 2</a> below.</p>
<p>In this case we're using the PostAsyn method. We send in the url and since it is a POST (rather than a GET) we send in the postParameters as well. Each of these methods also requires a callback delegate that is called back with the response of the http call. In the example below we've used a lambda as the callback. The response call back is an</p><pre class="csharpcode"><span class="identifier">Action</span>&lt;<span class="identifier">HttpWebRequestCallbackState</span>&gt;
</pre>
<p>&nbsp;</p>
<p>The <code>HttpWebRequestCallbackState</code> is a custom class that holds a bunch of state information including the Response Stream (that contains the response). You can find that class in <a href="#codelisting1">Code Listing 1</a> above. </p>
<p>What's important to realize here is that the loop finishes almost instantly. We don't block the main thread and we're not spawning additional threads. The callback will be called for each response, as and when a response is received and we simply continue on with processing the response as we see fit. In the example, we're simply writing out the response to the console. Another thing to keep in mind is that the responses will not arrive in the order in which requests were made. This is quite normal and if our workflow is truly asynchronous then this shouldn't be a problem.</p>
<div class="panel">
<h3 class="note">A Note ServicePointManager</h3>If you are making multiple http requests to the same domain, you'll find that only two concurrent requests are actually being made. This is because the DefaultConnectionLimit (per domain) is 2. If you're making multiple concurrent requests to different domains, then you don't need to modify this limit. If you do modify the limit (because you're making multiple calls to the same domain) then be sure to test various numbers to see what works best. Please also keep in mind that the server being called will be heavily loaded and if the work the server side needs to do is "long running", then you could potentially stress the server more than it can handle, or because you're stressing the server the performance of your application starts to degrade rather than improve. </div>
<p>&nbsp;<a name="codelisting2"></a></p>
<div class="panel code content/images/csharp.png" title="Simple useage scenario with Asynchronous Workflow"><pre class="csharpcode">      <span class="identifier">ServicePointManager</span>.DefaultConnectionLimit = 50;
      <span class="kwrd">var</span> url = <span class="str">"http://localhost/HttpTaskServer/default.aspx"</span>;

      var iterations = 1000;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; iterations; i++)
      {
        var postParameters = <span class="kwrd">new</span> NameValueCollection();
        postParameters.Add(<span class="str">"data"</span>, i.ToString());
        HttpSocket.PostAsync(url, postParameters, callbackState =&gt;
          {
            <span class="kwrd">if</span> (callbackState.Exception != <span class="kwrd">null</span>)
              <span class="kwrd">throw</span> callbackState.Exception;
            Console.WriteLine(HttpSocket.GetResponseText(callbackState.ResponseStream));
          });
      }
</pre>
<h3>Code Listing 2: Using the PostAsync method of the HttpSocket class</h3></div>
<h2>Making Multiple Concurrent Requests and Waiting on All</h2>
<p>Sometimes, we can't use an asynchronous workflow but we'd like to fire multiple requests as fast as possible and then wait till all jobs have complete before we continue on to process the responses. There are many ways in which to tackle this kind of problem. In this post we'll be looking at 5 different ways in which we can accomplish this kind of thing.</p>
<p>Each one has it's merits (ease of use versus complexity) and performance and resource utilization metrics.</p>
<div class="panel">
<h3 class="note">Using the techniques presented here for other kinds of work</h3>
<p>The techniques shown here can be used for work other than Http requests such as:</p>
<ul>
<li>Sending bulk Emails 
<li>Processing Files on a disk 
<li>Sending/Receiving files over Ftp 
<li>Pretty much and I/O bound work</li></ul>
<p>If you do use these techniques for other work, be sure to do your own testing if performance/throughput is a primary concern. If performance is not a major criteria, then any one of these methods can be used.</p></div>
<ol>
<li>Use Tasks to make synchronous Http requests and wait on all tasks to complete before proceeding. The method <code>CallHttpWebRequestTaskAndWaitOnAll</code> in <a href="#codelisting4">Code Listing 4</a> below demonstrates this. 
<li>We could spawn <code><i>n</i></code> number of threads and in each thread make synchronous Http requests and as soon as a thread completes, spawn another thread and keep doing this till all work items have finished. In other word, we put a cap on the number of threads we spawn and therefore the number of threads executing at any given point in time but ensure that at all times there are n threads busy doing work rather than sitting idle. The method <code>CallHttpWebRequestSyncAndWaitOnAll</code> in <a href="#codelisting5">Code Listing 5</a> below demonstrates this. 
<li>We could do the actual Http requests asynchronously and somehow collect the results of each response as they complete while blocking the main thread till all asynchronous jobs have completed. This technique is demonstrated in the method <code>CallHttpWebRequestAsyncAndWaitOnAll</code> in <a href="#codelisting6">Code Listing 6</a> below. 
<li>A variation on the previous theme is that we could use a combination of a parallel programming technique called <a href="http://www.matlus.com/data-parallel-parallel-programming-in-net/" target="_blank">Data Parallel</a>, where the work items are partitioned in chunks and then each chunk is processed by a thread. Within each thread we make asynchronous Http requests collecting the responses as they come in and wait for all threads to complete before returning. The method <code>CallHttpWebRequestASyncDataParallelAndWaitOnAll</code> shown in <a href="#codelisting7">Code Listing 7</a> below demonstrates this. 
<li>We could use another construct available to us as part of the .NET 4.0 framework, the <code>Parallel</code>, class. This class essentially uses the <a href="http://www.matlus.com/data-parallel-parallel-programming-in-net/" target="_blank">Data Parallel</a> technique as well but the it has the advantage of being able to use new features of the .NET 4.0 thread pool. Using the <code>Parallel</code> class is really simple as you you'll see. Within the <code>Parallel.ForEach</code> loop, we'll make synchronous Http calls and store the responses for each request and wait till all work items have been processed. The Parallel class makes it simple to "wait on all" because it finishes when all work items have finished. The method <code>CallHttpWebRequestSyncParallelForEachAndWaitOnAll</code> in <a href="#codelisting8">Code Listing 8</a> below shows such an implementation.</li></ol>
<p>Some explanation as to how some of this works (in the way these methods are being used in these tests) is in order. In <a href="#codelisting3">Code Listing 3</a> below you can see We initialize the <code>DefaultConnectionLimit</code> to 100. We then initialize an array of <code>Work</code> object instances (100 elements in the array) that we'll be passing to each of these methods as the "work load". The <code>Work</code> class is also shown in <a href="#codelisting3">Code Listing 3</a> below.</p>
<p>&nbsp;</p><a name="codelisting3"></a>
<div class="panel code content/images/csharp.png" title="Initialization code"><pre class="csharpcode">    <span class="kwrd">static</span> <span class="kwrd">void</span> <span class="identifier">Main</span>(<span class="kwrd">string</span>[] args)
    {
      ServicePointManager.DefaultConnectionLimit = 100;
      var url = <span class="str">"http://localhost/HttpTaskServer/default.aspx"</span>;
      var iterations = 10;

      var workItems = (from w <span class="kwrd">in</span> Enumerable.Range(0, 100)
                       let postParameters = <span class="kwrd">new</span> NameValueCollection { { <span class="str">"data"</span>, w.ToString() } }
                       select <span class="kwrd">new</span> Work() { Id = w, PostParameters = postParameters }).ToArray();

      Thread.Sleep(1000);
      Benchmarker.MeasureExecutionTime(<span class="str">"ParallelForEach              "</span>, iterations, CallHttpWebRequestASyncParallelForEachAndWaitOnAll, url, workItems);
      Benchmarker.MeasureExecutionTime(<span class="str">"AsyncAndWaitOnAll            "</span>, iterations, CallHttpWebRequestAsyncAndWaitOnAll, url, workItems);
      Benchmarker.MeasureExecutionTime(<span class="str">"ASyncDataParallelAndWaitOnAll"</span>, iterations, CallHttpWebRequestASyncDataParallelAndWaitOnAll, url, workItems);
      Benchmarker.MeasureExecutionTime(<span class="str">"TaskAndWaitOnAll             "</span>, iterations, CallHttpWebRequestTaskAndWaitOnAll, url, workItems);
      Benchmarker.MeasureExecutionTime(<span class="str">"SyncAndWaitOnAll             "</span>, iterations, CallHttpWebRequestSyncAndWaitOnAll, url, workItems);
      Console.WriteLine(<span class="str">"All work Done."</span>);      
      Console.ReadLine();
    }

  <span class="kwrd">class</span> <span class="identifier">Work</span>
  {
    <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; set; }
    <span class="kwrd">public</span> NameValueCollection PostParameters { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> ResponseData { get; set; }
    <span class="kwrd">public</span> Exception Exception { get; set; }
  }
</pre>
<h3>Code Listing 3: Showing the initialization and calls to each of the methods</h3></div>
<p>While initializing the work object instances we initialize the <code>Id</code> property of each instance to the "index" of the array element. So the first element's <code>Id</code> property is set to 1, the second's to 2 and so on. We also initialize the PostParameters property to an instance containing the name and value of "data" and "1" for the first element and "data" and "2" for the second element and so on. This is essentially the data that is POSTed to the remote server. In other words the Http content for each http request will be</p>
<p>data=x</p>
<p>Where "x" is different for each request and will be the same as the Id of the work item. Of course you'll change this to suit your particular needs.</p>
<p>Next, you should notice that the Work class has a <code>ResonseData</code> property. This is the property that holds the response of each http request we make. Again, in this case the response is a string but you can change this to be any other type to suite your response (like a JSON object for example).</p>
<p>The key point to notice here is that each work item contains the data required to make the request and then the response that comes back for each request. So after each of these methods returns, iterating over the array of work items and accessing the <code>ResponseData</code> property of each element will yield the response that each work item got back from the remote server.</p>
<p>The Benchmarker class simply calls a method n times and profiles it. In this case there are 100 items on our workItems array and we call each method 10 times. So effectively, each method makes a total 1,000 Http Requests but in batches of 10. We could increase the number of items in our workItems array to 1000 and do only one iteration as well.</p><a name="codelisting4"></a>
<div class="panel code content/images/csharp.png" title="Using Tasks and Task.WaitAll"><pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method makes a bunch (workItems.Count()) of HttpRequests using Tasks</span>
    <span class="rem">/// The work each task performs is a synchronous Http request. Essentially each</span>
    <span class="rem">/// Task is performed on a different thread and when all threads have completed</span>
    <span class="rem">/// this method returns</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="url"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="workItems"&gt;&lt;/param&gt;</span>
    <span class="kwrd">static</span> <span class="kwrd">void</span> CallHttpWebRequestTaskAndWaitOnAll(<span class="kwrd">string</span> url, IEnumerable&lt;Work&gt; workItems)
    {      
      var tasks = <span class="kwrd">new</span> List&lt;Task&gt;();
      <span class="kwrd">foreach</span> (var workItem <span class="kwrd">in</span> workItems)
      {
        tasks.Add(Task.Factory.StartNew(wk =&gt;
        {
          var wrkItem = (Work)wk;
          wrkItem.ResponseData = GetWebResponse(url, wrkItem.PostParameters);
        }, workItem));
      }
      Task.WaitAll(tasks.ToArray());
    }
</pre>
<h3>Code Listing 4: Showing the CallHttpWebRequestTaskAndWaitOnAll method</h3></div><a name="codelisting5"></a>
<div class="panel code content/images/csharp.png" title="Using the ThreadPool and putting a cap on the number of threads"><pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method makes a bunch (workItems.Count()) of HttpRequests synchronously</span>
    <span class="rem">/// using a pool of threads with a certain cap on the number of threads.</span>
    <span class="rem">/// As soon as a thread finishes a now job is started till no more work items are left.</span>
    <span class="rem">/// After all http requests are complete, this method returns</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="url"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="workItems"&gt;&lt;/param&gt;</span>
    <span class="kwrd">static</span> <span class="kwrd">void</span> CallHttpWebRequestSyncAndWaitOnAll(<span class="kwrd">string</span> url, IEnumerable&lt;Work&gt; workItems)
    {
      <span class="rem">//Since the threads will be blocked for the most part (not using the CPU)</span>
      <span class="rem">//We're using 4 times as many threads as there are cores on the machine.</span>
      <span class="rem">//Play with this number to ensure you get the performance you keeping an</span>
      <span class="rem">//eye on resource utlization as well.</span>
      <span class="kwrd">int</span> maxThreadCount = Environment.ProcessorCount * 4;
      <span class="kwrd">int</span> executingThreads = 0;
      <span class="rem">//This variable is used to throttle the number of threads</span>
      <span class="rem">//created to the maxThreadCount</span>
      <span class="kwrd">object</span> lockObj = <span class="kwrd">new</span> <span class="kwrd">object</span>();

      <span class="kwrd">foreach</span> (var workItem <span class="kwrd">in</span> workItems)
      {
        ThreadPool.QueueUserWorkItem((state) =&gt;
          {
            var work = (Work)state;
            <span class="kwrd">try</span>
            {
              work.ResponseData = GetWebResponse(url, work.PostParameters);
              Interlocked.Decrement(<span class="kwrd">ref</span> executingThreads);
            }
            <span class="kwrd">catch</span> (Exception ex)
            {
              work.Exception = ex;
              Interlocked.Decrement(<span class="kwrd">ref</span> executingThreads);
            }

          }, workItem);

        <span class="rem">//If maxThreadCount threads have been spawned</span>
        <span class="rem">//then wait for any of them to finish before</span>
        <span class="rem">//spawning additional threads. Therby limiting</span>
        <span class="rem">//the number of executing (and spawned)</span>
        <span class="rem">//threads to maxThreadCount</span>
        <span class="kwrd">lock</span> (lockObj)
        {
          executingThreads++;
          <span class="kwrd">while</span> (executingThreads == maxThreadCount)
            Thread.Sleep(1);
        }
      }

      <span class="rem">//Wait on all executing threads to complete</span>
      <span class="kwrd">while</span> (executingThreads != 0)
        Thread.Sleep(1);
    }
</pre>
<h3>Code Listing 5: Showing the CallHttpWebRequestSyncAndWaitOnAll method </h3></div><a name="codelisting6"></a>
<div class="panel code content/images/csharp.png" title="Using Asynchronous Http Requests and waiting on all"><pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method makes a bunch (workItems.Count()) of HttpRequests asynchronously</span>
    <span class="rem">/// The main thread is blocked until all asynchronous jobs are complete.</span>
    <span class="rem">/// After all http requests are complete, this method returns</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="url"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="workItems"&gt;&lt;/param&gt;</span>
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> CallHttpWebRequestAsyncAndWaitOnAll(<span class="kwrd">string</span> url, IEnumerable&lt;Work&gt; workItems)
    {
      var pending = workItems.Count();
      <span class="kwrd">using</span> (var mre = <span class="kwrd">new</span> ManualResetEvent(<span class="kwrd">false</span>))
      {
        <span class="kwrd">foreach</span> (var workItem <span class="kwrd">in</span> workItems)
        {
          HttpSocket.PostAsync(url, workItem.PostParameters, callbackState =&gt;
          {
            var hwrcbs = (HttpWebRequestCallbackState)callbackState;
            <span class="kwrd">using</span> (var responseStream = hwrcbs.ResponseStream)
            {
              var reader = <span class="kwrd">new</span> StreamReader(responseStream);
              ((Work)hwrcbs.State).ResponseData = reader.ReadToEnd();
              <span class="kwrd">if</span> (Interlocked.Decrement(<span class="kwrd">ref</span> pending) == 0)
                mre.Set();
            }
          }, workItem);
        }
        mre.WaitOne();
      }
    }
</pre>
<h3>Code Listing 6: Showing the CallHttpWebRequestAsyncAndWaitOnAll method</h3></div><a name="codelisting7"></a>
<div class="panel code content/images/csharp.png" title="Using a combination of Data Parallel and Asynchronous Http Requests"><pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method makes a bunch (workItems.Count()) of HttpRequests asynchronously</span>
    <span class="rem">/// but partitions the workItem into chunks. The number of chunks is determined</span>
    <span class="rem">/// by the number of cores in the machine. The main thread is blocked</span>
    <span class="rem">/// until all asynchronous jobs are complete</span>
    <span class="rem">/// After all http requests are complete, this method returns</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="url"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="workItems"&gt;&lt;/param&gt;</span>
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> CallHttpWebRequestASyncDataParallelAndWaitOnAll(<span class="kwrd">string</span> url, IEnumerable&lt;Work&gt; workItems)
    {
      var coreCount = Environment.ProcessorCount;
      var itemCount = workItems.Count();
      var batchSize = itemCount / coreCount;

      var pending = itemCount;
      <span class="kwrd">using</span> (var mre = <span class="kwrd">new</span> ManualResetEvent(<span class="kwrd">false</span>))
      {
        <span class="kwrd">for</span> (<span class="kwrd">int</span> batchCount = 0; batchCount &lt; coreCount; batchCount++)
        {
          var lower = batchCount * batchSize;
          var upper = (batchCount == coreCount - 1) ? itemCount : lower + batchSize;
          var workItemsChunk = workItems.Skip(lower).Take(upper).ToArray();

          <span class="kwrd">foreach</span> (var workItem <span class="kwrd">in</span> workItemsChunk)
          {
            HttpSocket.PostAsync(url, workItem.PostParameters, callbackState =&gt;
              {
                var hwrcbs = (HttpWebRequestCallbackState)callbackState;
                <span class="kwrd">using</span> (var responseStream = hwrcbs.ResponseStream)
                {
                  var reader = <span class="kwrd">new</span> StreamReader(responseStream);
                  ((Work)hwrcbs.State).ResponseData = reader.ReadToEnd();
                  <span class="kwrd">if</span> (Interlocked.Decrement(<span class="kwrd">ref</span> pending) == 0)
                    mre.Set();
                }
              }, workItem);
          }
        }
        mre.WaitOne();
      }
    }
</pre>
<h3>Code Listing 7: Showing the CallHttpWebRequestASyncDataParallelAndWaitOnAll method</h3></div><a name="codelisting8"></a>
<div class="panel code content/images/csharp.png" title="Using the Parallel.ForEach method to make synchronous Http calls in parallel"><pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method makes a bunch (workItems.Count()) of HttpRequests synchronously</span>
    <span class="rem">/// using Parallel.ForEach. Behind the scenes Parallel.ForEach partitions the</span>
    <span class="rem">/// workItem into chunks (Data Parallel). The main thread is blocked</span>
    <span class="rem">/// until all workItems have been processed.</span>
    <span class="rem">/// After all http requests are complete, this method returns</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="url"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="workItems"&gt;&lt;/param&gt;</span>
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> CallHttpWebRequestSyncParallelForEachAndWaitOnAll(<span class="kwrd">string</span> url, IEnumerable&lt;Work&gt; workItems)
    {
      <span class="identifier">Parallel</span>.ForEach(workItems, work =&gt;
      {
        <span class="kwrd">try</span>
        {
          work.ResponseData = GetWebResponse(url, work.PostParameters);
        }
        <span class="kwrd">catch</span> (Exception ex)
        {
          work.Exception = ex;
        }
      });
    }
</pre>
<h3>Code Listing 8: Showing the CallHttpWebRequestSyncParallelForEachAndWaitOnAll method</h3></div>
<p>The table below shows the timing results of each of the methods listed above. The results are shown in the order for fastest first. As you can see the method that does Not use threads is the fastest. The next is the method that uses as many threads as there are CPU cores on the machine (The machine used to perform these tests has 4 cores) but all work is done asynchronously (on 4 threads).</p>
<p>The hand crafted method SyncAndWaitOnAll comes in, in 3rd place and very close in 4th place is the Parralel.ForEach and last is the method that uses Tasks.</p>
<p>I should note that I performed <strong>each test by itself multiple times</strong>, and during these test the SyncAndWaitOnAll and the Parallel.ForEach methods were extremely close, frequently swapping places and you can see from their timings that they were in fact very close. The TaskAndWaitOnAll method wasn't too far behind most times either.</p>
<p>The reason the results turned out the way they did is because the workload is an I/O bound workload and I/O bound workloads don't benefit by spawning threads. In fact spawning threads for I/O bound work only hurts performance due to the thread management and context switching overheads. Keep in mind also that the results here are for making 1000 http requests and even then the results are not that different.</p>
<p>In the real world it may not be possible to use an asynchronous workflow, especially if you are trying to back-fit it into already existing synchronous workflows. So any of the methods resented here will work just as well.</p>
<p><b>All times are in milliseconds</b> </p>
<table style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid">
<tbody>
<tr>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">Method</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">Total</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">Average</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">Min</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">Max</td></tr>
<tr>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">AsyncAndWaitOnAll</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">20114.2131</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2011.4213</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2004.7027</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2055.6508</td></tr>
<tr>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">ASyncDataParallelAndWaitOnAll</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">21306.043</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">21306.043</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2005.8313</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2412.8763</td></tr>
<tr>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">SyncAndWaitOnAll</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">23136.3949</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2313.6394</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2011.8277</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2603.461</td></tr>
<tr>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">ParallelForEach</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">23438.7341</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2343.8734</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2010.1335</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">3154.8706</td></tr>
<tr>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; font-weight: bold; border-right: #cccccc 1px solid; padding-top: 2px">TaskAndWaitOnAll</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">27978.052</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2797.8052</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">2211.2131</td>
<td style="border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid; padding-bottom: 2px; padding-left: 2px; padding-right: 2px; border-top: #cccccc 1px solid; border-right: #cccccc 1px solid; padding-top: 2px">4459.7625</td></tr></tbody></table>
<p>&nbsp;</p>
<p>The method shown in <a href="#codelisting9">Code Listing 9</a> below is the method some of the methods listed above call. It makes synchronous Http requests and returns after receiving the response.</p><a name="codelisting9"></a>
<div class="panel code content/images/csharp.png" title="The GetWebResponse (Synchronous) method that some of the other methods use."><pre class="csharpcode">    <span class="kwrd">static</span> <span class="kwrd">string</span> GetWebResponse(<span class="kwrd">string</span> url, NameValueCollection parameters)
    {
      var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
      httpWebRequest.ContentType = <span class="str">"application/x-www-form-urlencoded"</span>;
      httpWebRequest.Method = <span class="str">"POST"</span>;

      var sb = <span class="kwrd">new</span> StringBuilder();
      <span class="kwrd">foreach</span> (var key <span class="kwrd">in</span> parameters.AllKeys)
        sb.Append(key + <span class="str">"="</span> + parameters[key] + <span class="str">"&amp;"</span>);
      sb.Length = sb.Length - 1;

      <span class="kwrd">byte</span>[] requestBytes = Encoding.UTF8.GetBytes(sb.ToString());
      httpWebRequest.ContentLength = requestBytes.Length;

      <span class="kwrd">using</span> (var requestStream = httpWebRequest.GetRequestStream())
      {
        requestStream.Write(requestBytes, 0, requestBytes.Length);
      }

      Task&lt;WebResponse&gt; responseTask = Task.Factory.FromAsync&lt;WebResponse&gt;(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, <span class="kwrd">null</span>);
      <span class="kwrd">using</span> (var responseStream = responseTask.Result.GetResponseStream())
      {
        var reader = <span class="kwrd">new</span> StreamReader(responseStream);
        <span class="kwrd">return</span> reader.ReadToEnd();
      }
    }
</pre>
<h3>Code Listing 9: Showing the GetWebResponse method that is called from some of the other methods</h3></div>Here is the Benchmark class that was used for the performance tests. 
<div class="panel code content/images/csharp.png" title="The Benchmark class used for these Performance Tests"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> System.Text;
<span class="kwrd">using</span> System.Diagnostics;

<span class="kwrd">namespace</span> Diagnostics.Performance
{
  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> Benchmarker
  {
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> WarmUp(Action action)
    {
      action();
      GC.Collect();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> DisplayResults(<span class="kwrd">string</span> benchmarkName, TimeSpan totalTime, TimeSpan averageTime, TimeSpan minTime, TimeSpan maxTime)
    {
      Console.WriteLine(<span class="str">"---------------------------------"</span>);
      Console.WriteLine(benchmarkName);
      Console.WriteLine(<span class="str">"\tTotal time  : "</span> + totalTime.TotalMilliseconds + <span class="str">"ms"</span>);
      Console.WriteLine(<span class="str">"\tAverage time: "</span> + averageTime.TotalMilliseconds + <span class="str">"ms"</span>);
      Console.WriteLine(<span class="str">"\tMin time    : "</span> + minTime.TotalMilliseconds + <span class="str">"ms"</span>);
      Console.WriteLine(<span class="str">"\tMax time    : "</span> + maxTime.TotalMilliseconds + <span class="str">"ms"</span>);
      Console.WriteLine(<span class="str">"---------------------------------"</span>);
      Console.WriteLine();
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> MeasureExecutionTime(<span class="kwrd">string</span> benchmarkName, <span class="kwrd">int</span> noOfIterations, Action action)
    {
      var totalTime = <span class="kwrd">new</span> TimeSpan(0);
      var averageTime = <span class="kwrd">new</span> TimeSpan(0);
      var minTime = TimeSpan.MaxValue;
      var maxTime = TimeSpan.MinValue;

      WarmUp(action);
      GC.Collect();
      GC.WaitForPendingFinalizers();
      GC.Collect();

      var total = <span class="kwrd">new</span> TimeSpan(0);
      var sw = Stopwatch.StartNew(); 
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; noOfIterations; i++)
      {
        sw.Restart();
        action();
        sw.Stop();

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        var thisIteration = sw.Elapsed;
        total += thisIteration;

        <span class="kwrd">if</span> (thisIteration &gt; maxTime)
          maxTime = thisIteration;
        <span class="kwrd">if</span> (thisIteration &lt; minTime)
          minTime = thisIteration;
      }

      totalTime = total;
      averageTime = <span class="kwrd">new</span> TimeSpan(total.Ticks / noOfIterations);

      DisplayResults(benchmarkName, totalTime, averageTime, minTime, maxTime);
    }
  }
}
</pre>
<h3>The Benchmarker Class</h3></div>
<p>I hope you've found this post and the information and data I've presented here useful.</p>]]></description><category>Programming/C#</category><category>Asynchronous</category><category>Http</category><category>Performance</category></item><item><title>Linq - SelectMany</title><pubDate>Thu, 17 Feb 2011 05:36:35 GMT</pubDate><link>http://www.matlus.com/linq-selectmany/</link><guid isPermaLink="true">http://www.matlus.com/linq-selectmany/</guid><description><![CDATA[<p>The linq SelectMany method is probably one of the most powerful method on the Enumerable class but sadly also of of the most difficult to understand. As per the the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx" target="_blank">MSDN documentation for Enumerable.SelectMany</a>, this method is described as:</p> <blockquote> <p><em><strong>Projects each element of a sequence to an IEnumerable&lt;T&gt; and flattens the resulting sequences into one sequence.</strong></em></p></blockquote> <p>I don't know about you, but I had to re-read this statement multiple times just to figure out what it was saying and even then, couldn't figure out where or why I'd use it. And then I thought well, maybe it's like doing a join, where for each element of sequence 1, I could produce many elements from sequence 2 and then get a flatten result (similar to doing a join in a database across a one-to-many relationship). Another way to look it is a nested foreach, where where you iterate over sequence 1 and for each element of sequence 1 you "find" or get all matching elements in sequence 2.</p> <p>Once I had that picture in mind I set about trying to write a linq query to see how I could achieve this. Before we take a look at that, lets take a look at the classes and data, we'll be using in this post. Code Listing 1 below, shows the two classes we'll be working with, and the initial data these classes have.</p> <div class="panel code content/images/csharp.png" title="The Category and Post classes"><pre class="csharpcode">  <span class="kwrd">public</span> <span class="kwrd">class</span> Category
  {
    <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; }
  }

  <span class="kwrd">class</span> Post
  {
    <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">int</span> CategoryId { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> Title { get; set; }
  }
</pre>
<h3>Code Listing 1: Showing the Category and Post classes</h3></div>
<p>In Code Listing 2, below we can see the initial data we'll be working with. You'll notice that there are 3 Categories</p>
<ol>
<li>Programming 
<li>Html 5 
<li>jQuery</li></ol>
<p>And that there are multiple posts in each of these categories. For instance there are 2 posts categorized as Html 5 (Category id = 2).</p>
<ol>
<li>Html 5 Video Element Poster 
<li>Html5 File Upload with Progress</li></ol>
<div class="panel code cotnent/images/csharp.png" title="The Category and Post data"><pre class="csharpcode">var categories = <span class="kwrd">new</span> Category[]
{
  <span class="kwrd">new</span> Category() { Id=1, Name =<span class="str">"Programming"</span>},
  <span class="kwrd">new</span> Category() { Id=2, Name =<span class="str">"Html"</span>},
  <span class="kwrd">new</span> Category() { Id=3, Name =<span class="str">"jQuery"</span>}
};

var posts = <span class="kwrd">new</span> Post[]
{
  <span class="kwrd">new</span> Post { Id=1, CategoryId=1, Title=<span class="str">"Data Parallel – Parallel Programming in C#/.NET"</span>},
  <span class="kwrd">new</span> Post { Id=2, CategoryId=1, Title=<span class="str">"Getting the No Of CPUs and Cores"</span>},
  <span class="kwrd">new</span> Post { Id=3, CategoryId=1, Title=<span class="str">"Orion - A Blog Engine"</span>},
  <span class="kwrd">new</span> Post { Id=4, CategoryId=1, Title=<span class="str">"Quartz for ASP.NET"</span>},
  <span class="kwrd">new</span> Post { Id=5, CategoryId=2, Title=<span class="str">"Html 5 Video Element Poster"</span>},
  <span class="kwrd">new</span> Post { Id=6, CategoryId=2, Title=<span class="str">"Html5 File Upload with Progress"</span>},
  <span class="kwrd">new</span> Post { Id=7, CategoryId=3, Title=<span class="str">"Expanding Code listings"</span>},
  <span class="kwrd">new</span> Post { Id=8, CategoryId=3, Title=<span class="str">"jQuery working with select option"</span>},
  <span class="kwrd">new</span> Post { Id=9, CategoryId=3, Title=<span class="str">"jQuery working with checkboxes and radio button"</span>}
};
</pre>
<h3>Code Listing 2: Showing the Category and Post classes populated with data</h3></div>
<p>The "foreign key" in the Post class in this case is CategoryId. No that's not how the database is modeled in <a title="Quartz for ASP.NET" href="http://www.matlus.com/quartz-for-aspnet/" target="_blank">Quartz for ASP.NET</a> (the blogging engine I use for this blog), I'm using this structure to keep things simple. Moving on…So if we were to do a "inner join" between these two sequences, the result should look like the output below.</p>
<div class="panel"><pre>Programming :  Data Parallel - Parallel Programming in C#/.NET
Programming :  Getting the No Of CPUs and Cores
Programming :  Orion - A Blog Engine
Programming :  Quartz for ASP.NET
Html        :  Html 5 Video Element Poster
Html        :  Html5 File Upload with Progress
jQuery      :  Expanding Code listings
jQuery      :  jQuery working with select option
jQuery      :  jQuery working with checkboxes and radio button

</pre></div>
<p>&nbsp;</p>
<p>The linq query syntax for this is actually quite simple if you've done joins using linq before. It looks like that shown in Code Listing 3 below. Both versions produce the same result. It's almost like the old join syntax versus the ASNI SQL syntax for a join in SQL.</p>
<div class="panel code content/images/csharp.png"><pre class="csharpcode"><span class="kwrd">var</span> categoryPosts = <span class="kwrd">from</span> c <span class="kwrd">in</span> categories                          
                    <span class="kwrd">join</span> p <span class="kwrd">in</span> posts on c.Id equals p.CategoryId
                    <span class="kwrd">select</span> <span class="kwrd">new</span> { CategoryName = c.Name, PostTitle = p.Title };

OR

<span class="kwrd">var</span> categoryPosts = <span class="kwrd">from</span> c <span class="kwrd">in</span> categories
                    <span class="kwrd">from</span> p <span class="kwrd">in</span> posts                           
                    <span class="kwrd">where</span> c.Id == p.CategoryId
                    <span class="kwrd">select</span> <span class="kwrd">new</span> { CategoryName = c.Name, PostTitle = p.Title };

</pre>
<h3>Code Listing 3: Doing a Join using Linq and query expression syntax</h3></div>
<p>What's important to note here is that the first version shown in Code Listing 3 above is actually translated by the compiler to use a SelectMany. The code thus generated would look similar to what have in Code Listing 4 below.</p>
<p>So far so good. Now lets go back to the SelectMany method. Let's also re-examine the statement of what SelectMany does.</p>
<p><em>Projects each element of a sequence to an IEnumerable&lt;T&gt;.</em></p>
<p>So the elements in our sequence are the various Categories and we have the ability to project each Category to an IEnumerable&lt;Post&gt;. That is for each Category, project the Posts that pertain to the Category. Effectively, a one-to-many. But we're not done yet.</p>
<p><em>Flattens the resulting sequence into <strong>one</strong> sequence.</em></p>
<p>So essentially producing one resulting sequence that is the flattened version of multiple, one-to-manys, thus giving us a "join". You could also think of SelectMany that does a nested foreach (as explained earlier), where the outer foreach is our categories sequence and the inner foreach is the sequence of posts.</p>
<p>Well, even after digesting the above, attempting to write the linq statement using the method syntax (versus the query expression syntax) turned out to be quite confusing indeed.</p>
<p>Here is the equivalent linq method syntax for using one of the many overloads of the SelectMany method:</p>
<div class="panel code content/images/csharp.png" title="Showing the syntax for using the SelectMany Enumerable Method"><pre class="csharpcode"><span class="kwrd">var</span> categoryPosts2 = categories.SelectMany(
            c =&gt; posts.Where(p =&gt; p.CategoryId == c.Id),
            (c, p) =&gt; <span class="kwrd">new</span> { CategoryName = c.Name, PostTitle = p.Title });
</pre>
<h3>Code Listing 4: Using the SelectMany method to do the same thing</h3></div>
<p>Let's break this down so we can better understand what is going on. The overload we're using in this case is:</p>
<div class="panel code content/images/csharp.png" title="The SelectMany overload being used"><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;TResult&gt; SelectMany&lt;TSource, TCollection, TResult&gt;(
    <span class="kwrd">this</span> IEnumerable&lt;TSource&gt; source,
    Func&lt;TSource, IEnumerable&lt;TCollection&gt;&gt; collectionSelector,
    Func&lt;TSource, TCollection, TResult&gt; resultSelector
)

which in our case translates to

<span class="identifier">Enumerable</span>&lt;<span class="identifier">Category</span>&gt;.SelectMany(<span class="identifier">Func</span>&lt;<span class="identifier">Category</span>, IEnumerable&lt;<span class="identifier">Post</span>&gt;&gt;, collectionSelector, <span class="identifier">Func</span>&lt;<span class="identifier">Category</span>, <span class="identifier">Post</span>, `a&gt; resultSelector


</pre></div>
<p>&nbsp;</p>
<p>So the first parameter is a Func that takes a Category and returns an IEnumerable&lt;Post&gt;. Of course the posts it returns are those that match the category (see&nbsp; code listing 4 above). In other words, <em>the first parameter maps each category to a sequence of matching posts.</em></p>
<p>The second parameter transforms each matched pair:</p>
<p>{ (c1, p1), (c1, p2), (c1, p3), (c1, p4), (c2, p5), (c2, p6), (c3, p7), (c3, p8), (c3, p9)}</p>
<p>into a new anonymous type that has a CategoryName property and a PostTitle property.</p>
<p>The implementation of SelectMany would look like the following:</p>
<div class="panel code content/images/csharp.png" title="The actual implementation of SelectMany"><pre class="csharpcode"><span class="kwrd">foreach</span> (TSource item <span class="kwrd">in</span> source)
  <span class="kwrd">foreach</span> (TCollection subItem <span class="kwrd">in</span> collectionSelector(item))
    <span class="kwrd">yield</span> <span class="kwrd">return</span> resultSelector(item, subItem);</pre>
<h3>Implementation of SelectMany in terms of nested foreaches and calling delegates </h3></div>
<p>Where the <code>collectionSelector</code> delegate and <code>resultSelector</code> delegates have the signature described above.</p>
<p>Now it so happens that the second parameter of the SelectMany method we're using is optional, in that there is another overload that requires only the first parameter. So what would happen if we used this overload instead?</p>
<p>In order to better understand what we'll get, we need to modify our data a bit. So let's remove the Programming Category from our sequence of categories (just comment out the first item).</p>
<p>What we'll get is simply a sequence of Posts (IEnumerable&lt;Post&gt;) that have associated categories (an "inner join" if you will) but without the projection (our anonymous type). So the first 4 posts in our data won't be part of this result a shown below. The number is the Id of the Post (and not the CategoryId).</p>
<div class="panel"><pre>5 : Html 5 Video Element Poster
6 : Html5 File Upload with Progress
7 : Expanding Code listings
8 : jQuery working with select option
9 : jQuery working with checkboxes and radio button

</pre></div>]]></description><category>Programming/C#</category><category>Join</category><category>Linq</category><category>SelectMany</category></item><item><title>Data Parallel – Parallel Programming in C#/.NET</title><pubDate>Thu, 10 Feb 2011 03:51:02 GMT</pubDate><link>http://www.matlus.com/data-parallel-parallel-programming-in-net/</link><guid isPermaLink="true">http://www.matlus.com/data-parallel-parallel-programming-in-net/</guid><description><![CDATA[<p>In .NET 4.0 Microsoft have introduced a slew of support for parallel programming. Parallel programming is not something you can ignore any more since CPUs are not getting any faster but instead the number of cores per CPU is increasing and unless we as software engineers begin to use all cores available on a given machine our software is not going to get any faster.</p> <p>There was a time when multiple CPUs were only available on servers and server side application platforms such as IIS are inherently multi-threaded so if we were building an ISAPI or ASP.NET application we automatically got the benefit of multiple threads in our applications without the need to know how to write parallel programs in order to make the best use of server hardware.</p> <p>On the client side, we typically used multiple threads to perform some background work so as to not freeze the UI. But very rarely did we spawn threads in client application to perform some compute-bound work, because for the most part, client machines had only one CPU and one core. But that has changed. Most desktop computers have at least 2 cores and in the future even normal desktop machines will have 4-8 cores and we need to learn how to utilize these cores in order to speed up our applications and to make good use of the available hardware.</p> <p>Even in server side applications, it is important to know how to best utilize the hardware available in order to speed up our applications. If the CPU cores on your server are not busy and your application is not running as fast as it should then it is likely we could benefit from parallelizing some of the work we do in our application.</p> <p>Parallel programming is extremely difficult to get right. I don’t mean getting it to work, but rather to get it right. It requires an in-depth knowledge of various hardware components such as CPU and CPU Architecture, Memory and memory architecture (UMA/NUMA), and the Disk I/O subsystem.</p> <p>In this article, we’re not going to go into the details of hardware, though if you’re serious about parallel programming you should dig real deep into hardware architecture of modern computers, especially as it relates to Memory access, including L1, L2, L3 cache and the Disk I/O subsystem.</p> <div class="panel"> <h3 class="note">Compute Bound and I/O Bound</h3> <p><strong>Compute-Bound:</strong> or CPU bound, is the term used in computer science for when the time taken for a process to complete is predominantly determined by the speed of the CPUs. That is the process is computationally intensive and increasing the CPU speed or the number of CPU/Cores will decrease the time it takes for a process to complete.</p> <p><strong>I/O Bound:</strong> An I/O bound task is one that relies on either Network I/O (reading data from across the Internet) or disk I/O (reading files or data from a database) and the bottleneck is not the CPU or memory. So effectively, the CPU is waiting on the I/O subsystem more often than it is doing any processing. I/O bound could also mean reading and writing to and from main memory.</p></div> <h2>Parallelization support in .NET 4.0</h2> <p>In .NET 4.0 we have access to a few specialized classes/libraries that can help us very easily achieve parallelization. In this post we'll be looking at the following:</p> <ol> <li>PLINQ (Parallel LINQ)  <li>The Parallel class. Namely the Parallel.For method</li></ol> <p>Both of these classes make it extremely simple to parallelize new and even existing code. We'll look at these two later in the post, but I wanted to introduce them and to assure you that stuff is simple. But like with most things, one needs to have a really good understanding of the background or foundations in order to best utilize the tools available. So in this post I attempt to introduce you to some of the foundational concepts with examples.</p> <p>A big change in .NET 4.0 is the CLR thread pool. There have been some major overhauls to the thread pool in .NET 4.0 to support parallel workloads and of course PLINQ and the Parallel class (as well as the new Task class that's part of the TPL – Task Parallel Library) make good use of these changes. A key change is the introduction on Work Stealing. We'll talk about work stealing later in this post as it makes a huge difference to the performance of some parallel workloads.</p> <h2>Data Parallelism</h2> <p>Data Parallelism is a parallelization pattern. This is, it is <em>commonly used</em> and is therefore considered a pattern. It is also called SIMD (Single Instruction Multiple Data). What this means is that given a set of data you want to perform a certain function on it. A very simple example of is a typical for-loop where within the loop you perform some action on this data.</p> <p>Task parallelism is another parallelization pattern that is commonly used. You use Task parallelization when you have a bunch of tasks that need to be performed on a piece of data and typically (or ideally) the order in which these tasks are performed is not important.&nbsp; I plan to write a post on Task Parallelism soon.</p> <p>In this post I’d like to present Data Parallelism and how we can very easily start to use this pattern in our .NET applications for compute-bound work. A lot of what we do in application programming is a good candidate for data parallelism. In <a href="#codelisting1">Code Listing 1</a> below we see a simple for-loop, that iterates over an array of integers. Within the loop we determine if the array element is a prime number. If it is, we increment a count. When the loop finishes, we have our answer, which is, the number of prime numbers in a given array of integers. The IsPrime() method is a compute-bound method.</p><a name="codelisting1"></a> <div class="panel code content/images/csharp.png" title="Non-Parallel version of GetNumberOfPrimes"><pre class="csharpcode">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetNumberOfPrimes(<span class="kwrd">int</span>[] numbers)
    {
      var count = 0;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; numbers.Length; i++)
      {
        <span class="kwrd">if</span> (IsPrime(numbers[i]))
          count++;
      }
      <span class="rem">//Console.WriteLine(count);</span>
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> IsPrime(<span class="kwrd">int</span> number)
    {
      <span class="kwrd">if</span> ((number &amp; 1) == 0)
        <span class="kwrd">return</span> (number != 2) ? <span class="kwrd">false : </span><span class="kwrd">true</span>;

      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 3; i * i &lt;= number; i += 2)
      {
        <span class="kwrd">if</span> (number % i == 0)
          <span class="kwrd">return</span> <span class="kwrd">false</span>;
      }
      <span class="kwrd">return</span> number != 1;
    }
</pre>
<h3>Code Listing 1: Showing the Non-Parallel GetNumberOfPrimes method and the IsPrime method</h3></div>
<div class="panel">
<h3 class="note">Parallelizing the IsPrime() method</h3>Of course a good candidate for parallelization is the <code>IsPrime()</code> method. However, in this post, I wanted to show you how you could Data Parallelize existing operations very simply and the IsPrime() method serves purely as a "compute bound" work load we'll be using here to <strong><em>simulate some operation over data</em></strong> you have in your applications. </div>
<p>For the moment let's stick with the non-parallelized method <code>GetNumberOfPrimes()</code>shown in <a href="#codelisting1">Code Listing 1</a> above and the initialization code in the <code>Main</code> method shown in Code Listing 2 below.</p><a name="codelisting2"></a>
<div class="panel code content/images/csharp.png" title="Initialization in the Main method"><pre class="csharpcode"><span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
{
  var numbers = Enumerable.Range(1, 500000).ToArray();
  var iterations = 500;

  Benchmarker.MeasureExecutionTime(<span class="str">"Non-Parallel"</span>, iterations, () =&gt; GetNumberOfPrimes(numbers));
  Benchmarker.MeasureExecutionTime(<span class="str">"Plinq"</span>, iterations, () =&gt; GetNumberOfPrimesUsingPLinq(numbers));
  Benchmarker.MeasureExecutionTime(<span class="str">"QueueUserWorkItem"</span>, iterations, () =&gt; GetNumberOfPrimesUsingThreadPool(numbers));
  Benchmarker.MeasureExecutionTime(<span class="str">"Parallel.For"</span>, iterations, () =&gt; GetNumberOfPrimesUsingParallelFor(numbers));
      
  Console.ReadLine();
}</pre>
<h3>Code Listing 2: Showing the Initialization method</h3></div>
<p>At the very beginning, you'll notice that the <code>numbers</code> int[] is being initialized to integers from 1-500,000. That is we want to see how many numbers between 1 and 500,000 are prime numbers. We run each method 500 times because we're doing some performance benchmarking and so the average time across the 500 runs will give us a good reference for how long each method takes to do the job.</p>
<p>What we see below is the result of running the GetNumberOfPrimes() (single threaded) method.</p><pre><p>---------------------------------<br>Non-Parallel<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Total time&nbsp; : 62920.7195ms<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Average time: 125.8414ms<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Min time&nbsp;&nbsp;&nbsp; : 125.2776ms<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Max time&nbsp;&nbsp;&nbsp; : 130.5586ms<br>---------------------------------</p>
</pre>
<p>The average time was 125.3 milliseconds. What's more interesting is what you see in Image 1 below. I'm running this on a quad core machine. so 25% utilization on a quad core CPU equates to 1 core being used 100%. It is a tight loop so 100% utilization is expected. However, we're only using 1 of the 4 cores available to us.</p>
<p><em><strong>Typically, when we parallelize, we want to see all CPU cores saturated. That is all cores are utilized 100% for the duration of processing.</strong></em> That indicates 2 things:</p>
<p>1. The work we're doing is being done as fast as possible on the current hardware</p>
<p>2. More importantly, if we were to throw more cores at the machine the work will be done sooner.</p>
<p>This is the ideal. But very rarely do we achieve this ideal and in production environments we have to take into consideration other software that's running on the hardware. Nonetheless if the job needs to be done, it will be done faster if the cores being utilized are saturated. So you may decide that it's ok to saturate all cores for a shorter period of time, than to saturate fewer cores for a longer period of time.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CPU Utilization By Non-ParallelizedMethod" border="0" alt="CPU Utilization By Non-ParallelizedMethod" src="http://www.matlus.com/content/uploads/2011/02/CPUUtilizationByNonParallelizedMethod_9144915f-c898-4efc-a807-cec7d5a1aff3.jpg" width="412" height="459"></p>
<h3>Image 1: Showing that the non-parallelized method uses only 1 core</h3>
<p>Now let's talk about what Data Parallelization is and how we'd use it in this context. Basically, the "data" is partitioned. That is the data is split into multiple partitions and each partition of data is executed on a different thread. Within a loop inside the thread we call our method (in this case IsPrime()) passing it the "data. Remember SIMD? Single Instruction multiple data. Does that make sense now? The single instruction is the IsPrime() method. The multiple data is the partitioned data.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="DataParallel-ForkJoin" border="0" alt="DataParallel-ForkJoin" src="http://www.matlus.com/content/uploads/2011/02/DataParallel-ForkJoin_16eb5d66-5a94-48ae-af92-ce4d9e9af7f4.jpg" width="541" height="505"></p>
<h3>Image 2: Data Parallelization – Partitioning data and processing each partition in a thread</h3>
<p>Since we're working with an array the easiest way to partition our data is to break it up into smaller partitions. How many partitions? Well, since we have 4 cores (in this case) we could partition the data into 4 equal parts and then spawn 4 threads and pass each one a partition. This technique is called <strong>Range Partitioning</strong>. Range partitioning is by far the simplest algorithm one can use to partition data. As you'll see later in this post the partitioning algorithm is a key component of data parallelization and the best algorithm to use depends largely on the data and the function you perform on this data.</p>
<p>When using PLINQ or the Parallel class we don't have to do the partitioning ourselves (Whew!). More about PLINQ and Parallel class partitioning algorithms later.</p>
<p>I mentioned 4 partitions because we have 4 cores. Without going into details, remember that normally you may double up on the partitions and threads. That is 8 partitions and 8 threads. but it all depends on the data, the partitioning logic, hardware in use and the existing workload (other applications that share the hardware etc.).</p>
<p>We'll be looking at 3 parallelized implementations that do the same job (count the number of prime numbers in our int[] numbers) using different techniques.</p>
<ol>
<li>PLINQ 
<li>Parallel.For 
<li>QueueUserWorkItem</li></ol>
<p>The QueueUserWorkItem implementation does not require .NET 4.0 and in fact is something you can do using earlier versions of .NET including .NET 2.0. It's implementation is fairly complex so what I hope to impart in this post is that with the support for parallelization introduced in .NET 4.0 (especially Data Parallelization and Task Parallelization) it behooves us to use these capabilities in our software so we make good use of the hardware our software is running on.</p>
<h2>PLINQ</h2>
<p>As I mentioned before, with PLINQ we don't have to concern ourselves with partitioning or threads, PLINQ handles it all for us. All you have to do (for the most part) is call the .AsParallel() method on the IEnumerable! That is to say that the only difference between the non-parallel LINQ version and the parallel PLINQ version is the .AsParallel() method call. Couldn't be any simpler!</p>
<p>This gives us a lot of opportunities to parallelize our code where possible. Just don't go about blindly adding the .AsParallel() call to all LINQ to object queries! They won't all work and not all LINQ queries will benefit from being parallelized.</p>
<p>Behind the scenes PLINQ will use one of many partitioning algorithms depending on various criteria. (We can also provide our own partitioning algorithm implementation but for the most part that's not required and not covered in this post). I won't go into the details of how PLINQ makes these decisions in this post but the following are the algorithms that could be used</p>
<ol>
<li>Range Partitioning 
<li>Chunk Partitioning 
<li>Stripe Partitioning 
<li>Hash Partitioning</li></ol>
<p>With simple queries PLINQ will spawn multiple threads (normally equaling the number of cores on the system) to get the job done. A lot of the algorithms PLINQ uses in order to get the results of queries require cross thread communication. This could slow things down a bit (depending on the query and data). In some cases the algorithm could require PLINQ to wait for all threads to finish while in other cases it may not. Any way this is not stuff you need to be concerned about. And indeed, you don't need to know the inner workings of PLINQ in order to use it.</p>
<div class="panel code content/images/csharp.png" title="The method that uses Plinq. Notice the AsParallel()"><pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetNumberOfPrimesUsingPLinq(<span class="kwrd">int</span>[] numbers)
{
  <span class="kwrd">var</span> query = <span class="kwrd">from</span> n <span class="kwrd">in</span> numbers.AsParallel()
              <span class="kwrd">where</span> IsPrime(n)
              <span class="kwrd">select</span> n;
  <span class="kwrd">var</span> count = query.Count();
  <span class="rem">//Console.WriteLine(count);</span>
}
</pre>
<h3>Code Listing 3: Showing a method using Plinq</h3></div>
<h2>Parallel.For</h2>
<p>Using Parallel.For we don't have to concern ourselves with data partitioning or threads either and link with PLINQ we could provide our own partitioning algorithm if we wanted to as well.</p>
<p>Parallel.For uses combinations of partitioning algorithms (dynamic partitioning) depending on the data and other workloads on the system. It could start with Range Partitioning and change to range/work stealing (explained later). Again, we don't need to know the inner workings in order to use this class.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.threading.parallel.for.aspx" target="_blank">Parallel.For method has a number of overloads</a>. For most tasks, you can use the simplest (to use) overload that essentially works like a regular for-loop. The method signature for this method looks like this:</p>
<div class="panel code content/images/csharp.png" title="Parallel.For method signature for the simplest overload"><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="identifier">ParallelLoopResult</span> For(<span class="kwrd">int</span> fromInclusive, <span class="kwrd">int</span> toExclusive,
  <span class="identifier">Action</span>&lt;<span class="kwrd">int</span>&gt; body);</pre></div>
<p>To implement the functionality we require in this case the code would look like this:</p>
<div class="panel code content/images/csharp.png" title="Parallel.For implementation using the simplest overload"><pre class="csharpcode">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetNumberOfPrimesUsingParallelForSharedState(<span class="kwrd">int</span>[] numbers)
    {
      <span class="kwrd">var</span> total = 0;
      <span class="identifier">Parallel</span>.For(0, numbers.Length,(j, loopState) =&gt;
      {
        <span class="kwrd">if</span> (IsPrime(numbers[j]))
          <span class="identifier">Interlocked</span>.Add(<span class="kwrd">ref</span> total, 1);
      });
      <span class="rem">//Console.WriteLine("Parallel.For - # Of Primes: " + total);</span>
    }
</pre></div>
<p>&nbsp;</p>
<p>This code works and is really simple to understand. But it is not as performant as another alternative. So let's understand the problem with this code and see what other alternatives the Parallel class has to offer.</p>
<p>Notice (in the code listing above) that we have a single variable called total. Next, in the parallel loop, if the number in question is a prime number we need to increment the value of total. But because the code within the loop is running in parallel (on multiple threads), we need to serialize access to the total variable because it is shared by multiple threads. That is we need to ensure that only one thread writes to (or reads from) this variable at any time. And so, we use the <a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx" target="_blank">Interlocked</a> class to increment the value of the total variable. The Interlocked class provides us with many methods that are atomic (meaning that they are performed in their entirety or not at all) and thread safe. Worst case scenario is that during each iteration, when a thread needs to increment the count of the total variable, all other threads are blocked. This could hurt performance terribly in other situations but no so in our situation because not all numbers are prime.</p>
<p>But what if the tasks you want to perform in the real world is such that the result of each task has to be written to a variable that is shared by all threads (shared state)? That's the worst case scenario for the above code. So in this post we will concentrate on another overload of the Parallel.For method how we would implement this method. It is a bit complex and unfortunately not the most intuitive either but I'll do my best to explain the parameters about the implementation.</p>
<h2>Parallel.For Thread-local state</h2>
<p>So we know we don't want to use shared state. So we could use thread-local state (that is a variable that is local to each thread and somehow at the end of each loop if we could add up all of the results, we'd have our answer. The .NET team has given us this capability in the Parallel class as another overload of the For method. Let's take a look at the signature of this overload and try and understand what each of the parameters mean and how we'd use them.</p>
<div class="panel code content/images/csharp.png" title="Parallel.For method overload for Thread-Local variables"><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="identifier">ParallelLoopResult</span> For&lt;TLocal&gt;(<span class="kwrd">int</span> fromInclusive, <span class="kwrd">int</span> toExclusive,
  <span class="identifier">Func</span>&lt;TLocal&gt; localInit, <span class="identifier">Func</span>&lt;<span class="kwrd">int</span>, <span class="identifier">ParallelLoopState</span>, TLocal, TLocal&gt; body,
  <span class="identifier">Action</span>&lt;TLocal&gt; localFinally);</pre></div>
<p>The first two parameters are the same, so no problem there. The third parameter</p>
<p><code>localInit</code>: Is a <code>Func</code> delegate that returns the initial state of the local data for each thread. In other words a method that returns the initial value of the thread local data (or local state). "Local state" in this context means a variable whose lifetime extends from just prior to the first iteration of the loop on the current thread, to just after the last iteration. In our case our local state is a variable of type int and it's initial state needs to be zero (for all threads).</p>
<p><code>body</code>: This is a <code>Func</code> delegate for the body of our loop that is invoked once per iteration. The first parameter to this method is our loop increment counter (same as the other method overload), the second parameter is a type <code>ParallelLoopState</code> (let's not worry about this parameter since we're not using it here. The third parameter is the local state. So in other words, we're passed in this parameter (so we have the current state it is in, we can do what we need to do with it (in this case increment it is the number is a prime number). The last parameter (as per the typicaly <code>Func</code> delegate convention is the return type. So we return the local state at the end of each iteration. so it can be given back to us in the next iteration. </p>
<p><code>localFinally</code>: The <code>Action</code> delegate that performs a final action on the local state of each thread. This is where you define the method that will be called <b>once</b>, after all the iterations on this thread have completed. The parameter this method provides us is none other than our thread-local state, so basically, this is where we get the opportunity to add up all of the thread-local variables into a variable that holds our final result. </p>
<p>Make sense? If this doesn't make sense now, it probably will when you see our implementation using this overload (you'll be able to join the dots). Our implementation of this overload is shown in <a href="#codelisting4">Code Listing 4</a> below. 
<p><a name="codelisting4"></a>
<div class="panel code content/images/csharp.png" title=""><pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetNumberOfPrimesUsingParallelFor(<span class="kwrd">int</span>[] numbers)
{
  <span class="kwrd">var</span> total = 0;
  <span class="identifier">Parallel</span>.For(0, numbers.Length, () =&gt; 0, (j, loopState, subtotal) =&gt;
    {
      <span class="kwrd">if</span> (IsPrime(numbers[j]))
        subtotal++;
      <span class="kwrd">return</span> subtotal;
    },
      (x) =&gt; <span class="identifier">Interlocked</span>.Add(<span class="kwrd">ref</span> total, x)
    );
  <span class="rem">//Console.WriteLine(total);</span>
}
</pre>
<h3>Code Listing 4: Showing a method using Parallel.For with Thread-Local state</h3></div>
<p>Looking at Code Listing 4 above, our 3rd parameter (localInit) is a lamba function that gets no parameters and returns the initial state of our local state (which is zero). The body parameter (the 4th parameter) is a <code>Func</code> delegate that passes in 3 parameters and expects a return parameter of type int. <code>j</code> is our loop counter, we don't use <code>loopState</code> in this example and <code>subTotal</code> is the loop state variable that holds the count of prime numbers of each thread. It is passed in as a parameter, we increment it in the body of our loop and return it in each iteration (so it can be passed in to us in the next iteration). The 5th parameter (localFinally) is an <code>Action</code> delegate that passes in one parameter, our local state. It is implemented as a lambda here, where <code>x</code> is the parameter that is our local state and we need to increment our <code>total</code> variable with this value. But here, because we're now dealing with shared state, we use the Interlocked class again. But keep in mind that in this case the localFinally action delegate is called once at the end of each thread's execution. So we're only blocking other threads once, at the end of each thread's execution rather than once during each iteration. </p>
<p>So in other words, using thread-local data, we can avoid the overhead of serializing a large number of accesses to shared state. Instead of writing to a shared resource on each iteration, we compute and store the value until all iterations for the task are complete. </p>
<h2>Performance Results</h2>
<p>Let's look at some performance numbers now. Here are the timing results of the various implementations. </p><pre>---------------------------------
Plinq
        Total time  : 20860.5636ms
        Average time: 41.7211ms
        Min time    : 41.5165ms
        Max time    : 62.3814ms
---------------------------------

---------------------------------
QueueUserWorkItem
        Total time  : 20107.1865ms
        Average time: 40.2143ms
        Min time    : 39.9199ms
        Max time    : 58.2553ms
---------------------------------

---------------------------------
Parallel.For
        Total time  : 16517.1344ms
        Average time: 33.0342ms
        Min time    : 32.5172ms
        Max time    : 37.0311ms
---------------------------------
</pre>
<p>From the performance numbers we see above, the method that uses Parallel.For performs the best. The method that uses QueueUserWorkItem comes in at 2nd place, while the Plinq method comes in at 3rd place. These numbers could change depending on the workload, data as well as the hardware architecture on which you run this code. We'll examine another case later in this post where the data (or the arrangement of data) makes a difference to the outcome.</p>
<p>However, let's not loose sight of the point of this post and that is to make use of and to&nbsp; benefit from parallelization of either existing or new code. Any one of these methods is almost 4 times faster than the original method. 4 times faster because I'm running this on a 4 core machine. If I was to run this on an 8 core machine they would all be almost 8 times faster.</p>
<p>The Plinq implementation does not saturate all cores as you can see in the CPU utilization screen shot below. There is a reason for this and we'll talk about this later in the post. Over the duration of processing the CPU utilization fluctuated between 74% and 76% but stayed mostly at 76%. So I've shown you 76% here. The same goes with the other CPU utilization screen shots you see later.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CPUUtilizationByPLinqMethod" border="0" alt="CPUUtilizationByPLinqMethod" src="http://www.matlus.com/content/uploads/2011/02/CPUUtilizationByPLinqMethod_cd525471-4b88-4024-b39d-a0926a9498df.jpg" width="412" height="459"></p>
<h3>Image 3: Plinq CPU Utilization – all cores, but not 100% saturation</h3>
<p>In the next image we see the CPU utilization of the method that uses QueueUserWorkItem to queue multiple worker threads on the thread pool, each with it's own partition of data. As you can see here, the CPU utilization is slightly higher (consistently) showing that the parallelization implementation makes better use of the hardware available to us.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CPUUtilizationByQueueUserWorkItemMethod" border="0" alt="CPUUtilizationByQueueUserWorkItemMethod" src="http://www.matlus.com/content/uploads/2011/02/CPUUtilizationByQueueUserWorkItemMethod_7d5c31c8-7bbe-42a0-8562-1bbc8be90c98.jpg" width="412" height="459"></p>
<h3>Image 4: QueueUserWorkItem CPU Utilization almost 100% saturation</h3>
<p>The next image shows the CPU utilization of the Parallel.For method. Here we see that all cores are 100% saturated (almost all the time). So it looks like the Parallel.For method does the best job of utilizing all of the available hardware.</p>
<p>That's the nature of parallel computing. There are a lot of variations possible and way too many factors that will impact the outcome. So what I want you to keep in mind is that there is no one method that will always outperform any other. It depends largely on the data and and kind of processing (the prime number algorithm used in case) and how well each of the methods manage threads, memory I/O and minimizes the cost of overheads as well as the hardware architecture of the system (as mentioned earlier).</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CPUUtilizationByParallelForMethod" border="0" alt="CPUUtilizationByParallelForMethod" src="http://www.matlus.com/content/uploads/2011/02/CPUUtilizationByParallelForMethod_58e06240-4303-4163-8953-1b71688367d1.jpg" width="412" height="459"></p>
<h3>Image 5: Parallel.For CPU Utilization showing 100% saturation</h3>
<h2>Data Partitioning is Important</h2>
<p>So why is the data partitioning algorithm important? In this case it is extremely important and it has to do with the way the IsPrime() method is implemented. You see in order to determine if a given number is a prime number or not, we iterate from 3 up to the square of the number to see if the number is wholly divisible by any of those numbers. As the number gets larger we have to iterate over more numbers and check against each of those numbers to determine if the number is a prime number or not. So effectively, larger numbers will take longer to determine and since our initial int[] is an ordered sequence of numbers from 1-500,000 the last partition has the largest numbers and processing the last partition will take the longest to process and processing the second to last partition will take a little less time and so on.</p>
<p>If that part is clear, then you'll realize that the way we're partitioning the data is kind of unfair, in that the thread that gets the first partition will finish before the thread that gets the last partition since the data in the last partition contains larger numbers. So how we partition our data plays an important role in how performant our parallelization is.</p>
<p>But it's not so much about being unfair but rather about underutilization of hardware. You see when the first thread finishes, it sits there doing nothing until the other threads complete their workload. Then the second thread finishes and waits for the other two to finish. As a result, the cores are not 100% saturated. That's not good.</p>
<h2>Work Stealing And Dynamic Data Partitioning</h2>
<p>So then how come the method that uses Parallel.For seems to not be affected by the unbalanced data partitioning? What's not quite apparent is that because of the new features built into the CLR Thread Pool, namely <strong>work stealing and dynamic data partitioning</strong>, the method that uses Parallel.For outperforms all the others even though the data partitioning is not ideal, because when thread 1 finishes it's work load, it starts to steal work from the other threads, when thread 2 finishes it's workload it starts to steal from the other threads as well. So effectively all threads are busy all of the time giving us 100% or close to 100% saturation of cores.</p>
<p>So the clear lesson here is that the .NET implementation of Parallel.For is highly optimized and behind the scenes the CLR thread pool is able to employ the new work stealing feature (using the Hill Climbing heuristic where the aim is to keep all cores busy). The Parallel.For method (a few of the other overloads) allows you to control or define the data partitioning that should be used as well. But here we're just letting it do whatever it does by default.</p>
<p>It should be noted that the new features of the thread pool are used by the Parallel class, Plinq as well as Tasks (all introduced in .NET 4.0). ThreadPool.QueueUserWorkItem does not utilize these new features because the way these features are implemented would likely break legacy code and since QueueUserWorkItem has been around since .NET 1.1 the team at Microsoft decided to make it an "opt-in" feature and you opt-in by simply using the new features in .NET 4.0.</p>
<p>In order to fix our data partitioning all we need to do is order the integers in the array randomly. Of course bear in mind that working with real world data is very different and balancing your data partitions may not be that simple or possible or may not be required at all. It just depends on what you're doing with your data.</p>
<p>The code below shows a simple way to randomly sort our int[] of numbers between 1-500,000. </p>
<div class="panel"><pre class="csharpcode">  <span class="kwrd">var</span> rnd = <span class="kwrd">new</span> <span class="identifier">Random</span>();
  <span class="kwrd">var</span> numbers = <span class="identifier">Enumerable</span>.Range(1, 500000)
                          .OrderBy(r =&gt; rnd.Next())
                          .ToArray();

</pre></div>
<p>&nbsp;</p>
<p>Let's see if this change has any impact on our benchmarks.</p><pre>---------------------------------
Plinq
        Total time  : 16712.8642ms
        Average time: 33.4257ms
        Min time    : 33.1166ms
        Max time    : 37.4965ms
---------------------------------

---------------------------------
QueueUserWorkItem
        Total time  : 16080.1191ms
        Average time: 32.1602ms
        Min time    : 31.7991ms
        Max time    : 48.0894ms
---------------------------------

---------------------------------
Parallel.For
        Total time  : 16497.6999ms
        Average time: 32.9953ms
        Min time    : 32.7595ms
        Max time    : 35.3307ms
---------------------------------
</pre>
<p>Compared to the earlier results each of the algorithms has improved by about 3-4%. The method that uses QueUserWorkItem comes in at the 1st place and next is the Parallel.For and in 3rd place is Plinq.</p>
<p>The Plinq and QueueUserWorkItem method both showed CPU utilizations of about 99% as shown below, while the Parallel.For method remained close to 100% through the duration (probably due to thread management and other overhead reasons).</p>
<p>Please take note that this example (and the data) is very simplistic and in the real world, with real data the Parallel.For method will almost always outperform the other approaches. The thread pool with its work stealing, hill climbing heuristic, dynamic data partitioning and awareness of what other applications/processes are currently running on the hardware has a lot more information and capabilities than our simplistic (almost naïve) implementation of the method that uses QueueUserWorkItem.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CPUUtilizationRandomDataByPLinqAndQUWIMethod" border="0" alt="CPUUtilizationRandomDataByPLinqAndQUWIMethod" src="http://www.matlus.com/content/uploads/2011/02/CPUUtilizationRandomDataByPLinqAndQUWIMethod_79e57c0e-ca55-4021-99b2-b5b36073629e.jpg" width="412" height="459"></p>
<p>&nbsp;</p>
<p>If you take a look at the implementation of method that uses QueueUserWorkItem in Code Listing 5 below, you'll see that there is a lot going on here. But also notice that we determine the number of threads to spawn based on the number of Cores available (but we don't take into account the workload already present on the hardware). So this method should scale just as well as the other methods presented in this post. But is the complexity of the implementation worth the gains? And remember every workload is different and there might be more complexity involved that will make your implementations more complex as well. So I highly recommend using Plinq and/or the Parallel class' Parallel.For or Parallel.ForEach methods and let the underlying framework do the optimizations for you while you keep you code simple and easy to understand and maintain.</p>
<div class="panel code content/images/csharp.png" title="Implementation of a method that uses QueueUserWorkItem"><pre class="csharpcode">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetNumberOfPrimesUsingThreadPool(<span class="kwrd">int</span>[] numbers)
    {
      <span class="kwrd">var</span> noOfPrimes = 0;
      <span class="kwrd">var</span> coreCount = <span class="identifier">Environment</span>.ProcessorCount;
      <span class="kwrd">var</span> batchSize = numbers.Length / coreCount;

      <span class="kwrd">var</span> pending = coreCount;
      <span class="kwrd">using</span> (<span class="kwrd">var</span> mre = <span class="kwrd">new</span> <span class="identifier">ManualResetEvent</span>(<span class="kwrd">false</span>))
      {
        <span class="kwrd">for</span> (<span class="kwrd">int</span> batchCount = 0; batchCount &lt; coreCount; batchCount++)
        {
          <span class="kwrd">var</span> lower = batchCount * batchSize;
          <span class="kwrd">var</span> upper = (batchCount == coreCount - 1) ? numbers.Length : lower + batchSize;
          <span class="identifier">ThreadPool</span>.QueueUserWorkItem(st =&gt;
          {
            <span class="kwrd">var</span> count = 0;
            <span class="kwrd">for</span> (<span class="kwrd">int</span> i = lower; i &lt; upper; i++)
              <span class="kwrd">if</span> (IsPrime(numbers[i]))
                count++;
            <span class="identifier">Interlocked</span>.Add(<span class="kwrd">ref</span> noOfPrimes, count);
            <span class="kwrd">if</span> (<span class="identifier">Interlocked</span>.Decrement(<span class="kwrd">ref</span> pending) == 0)
              mre.Set();
          });
        }
        mre.WaitOne();
      }
      <span class="rem">//Console.WriteLine(noOfPrimes);</span>
    }
</pre></div>
<h2>8 Core Machine</h2>
<p>I ran the application on an 8 core machine. That's 2 CPUs with 4 cores each. Keep in mind that a single CPU with 8 cores will perform better than 2 CPUs with 4 cores each. That's because memory access is extremely slow as compared to CPU speed and if all cores can get the data they need (including the work stealing) from the same chip (L1, L2 cache) rather than having to make trips to main memory or in the case of work stealing, having to steal from work that's on a different chip altogether, things will slow down a bit. I should add that the CLR Thread pool's work stealing algorithms do account for this and optimize accordingly.</p>
<p>The benchmark timings and CPU utilization is shown below</p><pre>---------------------------------
Plinq
        Total time  : 4023.2581ms
        Average time: 8.0465ms
        Min time    : 6.8322ms
        Max time    : 10.0536ms
---------------------------------

---------------------------------
QueueUserWorkItem
        Total time  : 3658.2514ms
        Average time: 7.3165ms
        Min time    : 6.3065ms
        Max time    : 9.6705ms
---------------------------------

---------------------------------
Parallel.For
        Total time  : 3508.3063ms
        Average time: 7.0166ms
        Min time    : 6.0755ms
        Max time    : 9.5767ms
---------------------------------
</pre>
<p>&nbsp;</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="RunningOn8CoreMachine" border="0" alt="RunningOn8CoreMachine" src="http://www.matlus.com/content/uploads/2011/02/RunningOn8CoreMachine_754c22d0-632c-4ee0-9431-e84f0369cd91.jpg" width="562" height="447"></p>]]></description><category>Programming/C#</category><category>Parrallel</category><category>Performance</category><category>Plinq</category><category>Threading</category></item><item><title>Getting the No Of CPUs and Cores</title><pubDate>Mon, 07 Feb 2011 14:50:30 GMT</pubDate><link>http://www.matlus.com/getting-the-no-of-cpus-and-cores/</link><guid isPermaLink="true">http://www.matlus.com/getting-the-no-of-cpus-and-cores/</guid><description><![CDATA[<p>Using WMI (Windows Management Instrumentation) it is really simple to get the all kinds of weird and useful information about the hardware of a computer. Here I use <code>ManagementObjectSearcher</code> from the <code>System.Management</code> assembly/namespace to get at information on the CPU. In particular: </p> <ul> <li>No of Cores  <li>No of Logical Processors  <li>No of Physical Processors  <li>Hardware Bitness (32/64 bit etc.)  <li>CPU Architecture (x86, x64, Itanium etc.) </li></ul> <div class="panel code content/images/csharp.png" title="WMI Code to Extract information in the CPU"><pre class="csharpcode">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GetCpuInformation()
    {
      var noOfCores = 0;
      <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> <span class="kwrd">new</span> System.Management.ManagementObjectSearcher(<span class="str">"Select * from Win32_Processor"</span>).Get())
      {
        noOfCores += <span class="kwrd">int</span>.Parse(item[<span class="str">"NumberOfCores"</span>].ToString());
        Console.WriteLine(<span class="str">"Bitness: {0}"</span>, item[<span class="str">"AddressWidth"</span>]);
        Console.WriteLine(<span class="str">"Architecture: {0}"</span>, GetArchitectureDiscription(<span class="kwrd">int</span>.Parse(item[<span class="str">"Architecture"</span>].ToString())));
      }

      Console.WriteLine(<span class="str">"Number Of Cores: {0}"</span>, noOfCores);

      <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> <span class="kwrd">new</span> System.Management.ManagementObjectSearcher(<span class="str">"Select * from Win32_ComputerSystem"</span>).Get())
      {
        Console.WriteLine(<span class="str">"Number Of Logical Processors: {0} "</span>, item[<span class="str">"NumberOfLogicalProcessors"</span>]);
        Console.WriteLine(<span class="str">"Number Of Physical Processors: {0} "</span>, item[<span class="str">"NumberOfProcessors"</span>]);
      }      
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">string</span> GetArchitectureDiscription(<span class="kwrd">int</span> architectureNo)
    {
      <span class="kwrd">switch</span> (architectureNo)
      {
        <span class="kwrd">case</span> 0: <span class="kwrd">return</span> <span class="str">"x86"</span>;
        <span class="kwrd">case</span> 1: <span class="kwrd">return</span> <span class="str">"MIPS"</span>;
        <span class="kwrd">case</span> 2: <span class="kwrd">return</span> <span class="str">"Alpha"</span>;
        <span class="kwrd">case</span> 3: <span class="kwrd">return</span> <span class="str">"PowerPC"</span>;
        <span class="kwrd">case</span> 6: <span class="kwrd">return</span> <span class="str">"Itanium-based systems"</span>;
        <span class="kwrd">case</span> 9: <span class="kwrd">return</span> <span class="str">"x64"</span>;
        <span class="kwrd">default</span>:
          <span class="kwrd">return</span> <span class="str">"Unkown"</span>;
      }
    }
</pre></div>&nbsp; <p>There is quite a bit more information available from both the <a title="WMI Win32_Processor Class" href="http://msdn.microsoft.com/en-us/library/aa394373(v=vs.85).aspx" target="_blank">Win32_Processor</a> WMI class as well as the <a title="WMI Win32_ComputerSystem Class" href="http://msdn.microsoft.com/en-us/library/aa394102(v=vs.85).aspx" target="_blank">Win32_ComputerSystem</a>, so you may want to check out the other properties/information these object provide.</p>
<p>I use the number of cores information to (naïvely) determine how many threads I can/should spawn when I'm doing some multi-threaded work. Of course nowadays with availability of <code>Tasks</code> in .NET and <code>Parallel.For</code> etc. one should probably use facilities built into the .NET framework where possible.</p>
<p>You can optimize the queries if you need to. For example, we're doing a select * from for each of queries you see in the code listing above. You could change that to return only the properties you're interested in. For example the seconds query above could be rewritten as</p><pre style="font-family: consolas"><span style="color: #a31515">"Select NumberOfLogicalProcessors, NumberOfProcessors from Win32_ComputerSystem"</span><br></pre>
<p>&nbsp;</p>
<p>The rest of the code will remain the same, including the way in which the properties are extracted from the result.</p>]]></description><category>Programming/C#</category><category>Asynchronous</category><category>WMI</category></item><item><title>IAsyncResult–Making Existing methods Asnchronous</title><pubDate>Mon, 07 Feb 2011 08:06:03 GMT</pubDate><link>http://www.matlus.com/iasyncresult-making-existing-methods-asnchronous/</link><guid isPermaLink="true">http://www.matlus.com/iasyncresult-making-existing-methods-asnchronous/</guid><description><![CDATA[<p>The APM or Asynchronous programming model has been in .NET since the beginning. There are quite a few BCL classes that use this programming model to effectively provide asynchronous methods to methods that also have synchronous counterparts. But what if you want to make one of your existing methods asynchronous? In this post I show you how simple it is to make an existing synchronous method available as an asynchronous method.</p> <p>Before we go down that route, let me say that I assume you're somewhat familiar with using asynchronous methods. The intent of this post is to show you how you would convert one or more of your own synchronous methods into asynchronous method. So I'm not going to be explaining the basics of asynchronous programming in .NET.</p> <p>The APM design pattern in .NET uses some naming conventions for the method names as well as the basic method signatures. You'll have BeginXXX and EndXXX method, where XXX is the name of the synchronous method. In other words asynchronous operations that use the APM (IAsyncResult) design pattern are implemented as a pair of methods. The basic method signature for the BeginXXX method is</p><pre class="csharpcode"><span class="identifier">IAsyncResult</span> BeginXXX(<span class="identifier">AsyncCallback</span> callback, <span class="kwrd">object</span> state)
</pre>
<p>&nbsp;</p>
<p>The basic method signature for the EndXXX method is</p><pre class="csharpcode"><span class="kwrd">void</span> EndXXX(<span class="identifier">IAsyncResult</span> result)
</pre>
<p>&nbsp;</p>
<p>Now if we want to make one of our own methods asynchronous then we'll have to follow the basic signature. If our method required additional parameters or has a return type then we can include these parameters, while keeping the basic signature. <strong><em>The idea is to re-use our existing method (and implementation) but as an asynchronous operation.</em></strong></p>
<p>So lets say we have a method in our business layer class that does some compute-bound work. For the sake of an example let's say the method requires an <code class="csharpcode"><span class="kwrd">int</span>[]</code>as an input parameter and it returns the number of prime numbers in the array as an int. The synchronous version of the method in shown in the code listing below. 
<div class="panel code content/images/csharp.png" title="Synchronous Version of the GetNumberOfPrimeNumbersInArray method"><pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Synchronous Method to Get the number of prime numbers in an array of numbers</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="numbers"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">int</span> GetNumberOfPrimeNumbersInArray(<span class="kwrd">int</span>[] numbers)
    {
      <span class="kwrd">int</span> count = 0;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; numbers.Length; i++)
      {
        <span class="kwrd">if</span> (IsPrime(numbers[i]))
          count++;
      }
      <span class="kwrd">return</span> count;
    }

    <span class="kwrd">private</span> <span class="kwrd">bool</span> IsPrime(<span class="kwrd">int</span> number)
    {
      <span class="kwrd">if</span> (number == 4)
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 2; i &lt; number / 2; i++)
        <span class="kwrd">if</span> (number % i == 0)
          <span class="kwrd">return</span> <span class="kwrd">false</span>;
      <span class="kwrd">return</span> <span class="kwrd">true</span>;
    }
  }
</pre></div>
<h2>Implementing Asynchronous Methods</h2>
<p>The BeginXXX method takes any parameters declared in the signature of the synchronous version of the method that are passed by value or by reference (in this case the int[]). Any out parameters <strong>are not</strong> part of the BeginXXX method signature. The BeginXXX method signature also includes two additional parameters which are part of the basic method signature as shown above. Further, the BeginXXX method needs to also return an instance of IAsyncResult which is also part of the basic method signature. So effectively, our BeginGetNumberOfPrimeNumbersInArray method signature will look like the following</p><pre class="csharpcode"> <span class="kwrd">public</span> <span class="identifier">IAsyncResult</span> BeginGetNumberOfPrimeNumbersInArray(<span class="kwrd">int</span>[] numbers,
   <span class="identifier">AsyncCallback</span> callback, <span class="kwrd">object</span> state)
 {
 }</pre>
<p>Similarly, our EndGetNumberOfPrimeNumbersInArray method will follow the basic signature but because our synchronous version returns an int, so our End method will return an int. Following the basic method signature and making appropriate modifications to the signature, the method signature for our EndGetNumberOfPrimeNumbersInArray will look like the following:</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">int</span> EndGetNumberOfPrimeNumbersInArray(IAsyncResult result)
{
}
</pre>
<p>So now, all we're left with is the actual implementation of these methods. Keep in mind that we're going to use the existing synchronous method in here so we don't have to re-implement the existing method but rather re-use it asynchronously.</p>
<p>Looking at the signature of our BeginXXX method a question that's going to come up (if it hasn't already) is that we'll need an implementation of the IAsyncResult interface. That's true. Implementing the IAsyncResult is not a trivial task. However all delegates provide us with an instance of an IAsyncResult upon calling their BeginInvoke method. So we could look at using this approach. The general consensus on the .NET community is that using the delegate's BeginInvoke/EndInvoke is slow. Slow is a relative term. If the method itself is going to take 2-3 seconds or more to complete then any performance gains you might get by implementing your own IAsyncResult quickly diminishes. Remember that you only call BeginInvoke once. Now in the case where you're calling your asynchronous method thousands of times or more then improving on this slowness could make a difference.</p>
<div class="panel">
<h2 class="note">IAsyncResult Implementations</h2>
<p>There are some well written implementations available that you could use instead of delegates, but I'll leave that up to you. The concept remains the same and you can easily swap out the delegate version for any of the other implementations. The <code>LazyAsyncResult</code> internal class (that's part of the System.NET assembly) is a good place to look (using Reflector) if you're interested in implementing your own IAsyncResult implementation.</p>
<p>A few others are</p>
<ul>
<li>Jeffrey Richter's implementation 
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc163467.aspx">Implementing the CLR Asynchronous Programming Model</a> 
<li>Joe Duffy's implementation 
<li><a href="http://www.bluebytesoftware.com/blog/PermaLink,guid,661dc0d7-9759-4a91-ad97-247c66d6f784.aspx">Implementing a high-perf IAsyncResult: lock-free lazy allocation</a> </li></ul></div>
<p>The code listing below shows the completed implementations of the BeginGetNumberOfPrimeNumbersInArray and the EndGetNumberOfPrimeNumbersInArray method. We also use an AsyncState class that is shown towards the end of the code listing. It's just a simple class that is used to pass state information between the Begin and End methods.</p>
<p>In the Begin method, we define a delegate that has the same signature as our synchronous method. That's because we will be calling our synchronous method asynchronously and we use a delegate to help with calling it asynchronously. A reference to this delegate is passed along to the End method via the AsyncState object.</p>
<p>&nbsp;</p>
<div class="panel code content/images/csharp.png" title="Code Listing Showing the BeginXXX and EndXXX implementations"><pre class="csharpcode">  <span class="kwrd">public</span> <span class="kwrd">class</span> BusinessModule
  {
    <span class="kwrd">public</span> IAsyncResult BeginGetNumberOfPrimeNumbersInArray(<span class="kwrd">int</span>[] numbers, AsyncCallback callback, <span class="kwrd">object</span> state)
    {
      Func&lt;<span class="kwrd">int</span>[], <span class="kwrd">int</span>&gt; del = GetNumberOfPrimeNumbersInArray;
      var asyncState = <span class="kwrd">new</span> AsyncState(del, state);
      <span class="kwrd">return</span> del.BeginInvoke(numbers, callback, asyncState);
    }

    <span class="kwrd">public</span> <span class="kwrd">int</span> EndGetNumberOfPrimeNumbersInArray(IAsyncResult result)
    {
      var asyncState = (AsyncState)result.AsyncState;
      var del = (Func&lt;<span class="kwrd">int</span>[], <span class="kwrd">int</span>&gt;)asyncState.Del;
      <span class="kwrd">return</span> del.EndInvoke(result);
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Synchronous Method to Get the number of prime numbers in an array of numbers</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="numbers"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">int</span> GetNumberOfPrimeNumbersInArray(<span class="kwrd">int</span>[] numbers)
    {
      <span class="kwrd">int</span> count = 0;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; numbers.Length; i++)
      {
        <span class="kwrd">if</span> (IsPrime(numbers[i]))
          count++;
      }
      <span class="kwrd">return</span> count;
    }

    <span class="kwrd">private</span> <span class="kwrd">bool</span> IsPrime(<span class="kwrd">int</span> number)
    {
      <span class="kwrd">if</span> (number == 4)
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 2; i &lt; number / 2; i++)
        <span class="kwrd">if</span> (number % i == 0)
          <span class="kwrd">return</span> <span class="kwrd">false</span>;
      <span class="kwrd">return</span> <span class="kwrd">true</span>;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">class</span> AsyncState
  {
    <span class="kwrd">public</span> Delegate Del { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> <span class="kwrd">object</span> State { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> AsyncState(Delegate del, <span class="kwrd">object</span> state)
    {
      Del = del;
      State = state;
    }
  }
</pre></div>
<h2>Using Asynchronous Methods</h2>
<p>The code listing below is the entire code you'll need to run this application. Using our new asynchronous method is similar to using any asynchronous method you would encounter in the .NET BCL. You can see the call to our BeginGetNumberOfPrimeNumbersInArray method in the main method shown below.</p>
<div class="panel code content/images/csharp.png" title="Complete code listing - Showing how ot call the Async method."><pre class="csharpcode">  <span class="kwrd">class</span> Program
  {
    <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
    {
      var bm = <span class="kwrd">new</span> BusinessModule();
      var numbers = Enumerable.Range(0, 10000).ToArray();

      bm.BeginGetNumberOfPrimeNumbersInArray(numbers, GetNumberOfPrimeNumbersInArrayCallback, bm);
      Console.WriteLine(<span class="str">"You should see the number of primes after this message"</span>);      
      Console.ReadLine();
    }

    <span class="kwrd">static</span> <span class="kwrd">void</span> GetNumberOfPrimeNumbersInArrayCallback(IAsyncResult result)
    {
      var asyncState = (AsyncState)result.AsyncState;
      var del = (Func&lt;<span class="kwrd">int</span>[], <span class="kwrd">int</span>&gt;)asyncState.Del;
      var numberOfPrimes = del.EndInvoke(result);
      Console.WriteLine(numberOfPrimes);
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">class</span> BusinessModule
  {
    <span class="kwrd">public</span> IAsyncResult BeginGetNumberOfPrimeNumbersInArray(<span class="kwrd">int</span>[] numbers, AsyncCallback callback, <span class="kwrd">object</span> state)
    {
      Func&lt;<span class="kwrd">int</span>[], <span class="kwrd">int</span>&gt; del = GetNumberOfPrimeNumbersInArray;
      var asyncState = <span class="kwrd">new</span> AsyncState(del, state);
      <span class="kwrd">return</span> del.BeginInvoke(numbers, callback, asyncState);
    }

    <span class="kwrd">public</span> <span class="kwrd">int</span> EndGetNumberOfPrimeNumbersInArray(IAsyncResult result)
    {
      var asyncState = (AsyncState)result.AsyncState;
      var del = (Func&lt;<span class="kwrd">int</span>[], <span class="kwrd">int</span>&gt;)asyncState.Del;
      <span class="kwrd">return</span> del.EndInvoke(result);
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Synchronous Method to Get the number of prime numbers in an array of numbers</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="numbers"&gt;&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">int</span> GetNumberOfPrimeNumbersInArray(<span class="kwrd">int</span>[] numbers)
    {
      <span class="kwrd">int</span> count = 0;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; numbers.Length; i++)
      {
        <span class="kwrd">if</span> (IsPrime(numbers[i]))
          count++;
      }
      <span class="kwrd">return</span> count;
    }

    <span class="kwrd">private</span> <span class="kwrd">bool</span> IsPrime(<span class="kwrd">int</span> number)
    {
      <span class="kwrd">if</span> (number == 4)
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 2; i &lt; number / 2; i++)
        <span class="kwrd">if</span> (number % i == 0)
          <span class="kwrd">return</span> <span class="kwrd">false</span>;
      <span class="kwrd">return</span> <span class="kwrd">true</span>;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">class</span> AsyncState
  {
    <span class="kwrd">public</span> Delegate Del { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> <span class="kwrd">object</span> State { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> AsyncState(Delegate del, <span class="kwrd">object</span> state)
    {
      Del = del;
      State = state;
    }
  }
</pre></div>
<p>&nbsp;</p>
<p>Because the method is asynchronous and we're calling in asynchronously rather than making a blocking call (which is also an option when using the APM), you'll see the message:</p><pre style="font-family: consolas"><span style="color: #a31515">You should see the number of primes after this message</span><br></pre>Before you see the count of the number of prime numbers in the int array. So for example, on my desktop, the output I see is. 
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="AMPSampleOutput" border="0" alt="AMPSampleOutput" src="http://www.matlus.com/content/uploads/2011/02/AMPSampleOutput_0d7e9d93-2f31-4af4-948e-9dac2fbf2d41.jpg" width="605" height="255"></p>]]></description><category>Programming/C#</category><category>Asynchronous</category></item><item><title>UrlEncode –The correct encoding</title><pubDate>Thu, 03 Feb 2011 07:13:05 GMT</pubDate><link>http://www.matlus.com/urlencode-the-correct-encoding/</link><guid isPermaLink="true">http://www.matlus.com/urlencode-the-correct-encoding/</guid><description><![CDATA[<p>While developing the <a href="http://www.matlus.com/oauth-c-library/">OAuth C# Lubrary</a> I discovered that the <code>HttpUtility</code> class that's available in the <code>System.Web</code> assembly in .NET (in particular the <code>HttpUtility.UrlEncode()</code> method) doesn't quite do it correctly. So I had to develop my own method that did the encoding correctly. I used <a href="http://en.wikipedia.org/wiki/Percent-encoding">this wiki page</a> as a reference.</p> <p>Notice the <code>UrlEncode()</code> method in the code listing below, that's the method I present in this post. The outputs of the <code>HttpUtility.UrlEncode()</code> method any my <code>UrlEncode()</code> method are listed below such that you can compare the two outputs.</p> <div class="panel code content/images/csharp.png" title="UrlEncoding a string in C# the correct way"><pre class="csharpcode">  <span class="kwrd">class</span> Program
  {
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> <span class="kwrd">static</span> <span class="kwrd">string</span> unreservedCharacters = <span class="str">"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"</span>;

    <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
    {
      var url = <span class="str">"!*'();:@&amp;=+$,/?#[] &lt;&gt;~.\"{}|\\-`_^%"</span>;

      Console.WriteLine(<span class="str">"Using HttpUtility: "</span> + HttpUtility.UrlEncode(url));
      Console.WriteLine(<span class="str">"Using UrlEncode:   "</span> + UrlEncode(url));
      Console.WriteLine(HttpUtility.UrlDecode(UrlEncode(url)));

      Console.ReadLine();
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method is the correct implementation of UrlEncode.</span>
    <span class="rem">/// Given a string, it returns a UrlEncoded version on the string.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="value"&gt;the string/url to be UrlEncoded&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;The UrlEncoded string&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> UrlEncode(<span class="kwrd">string</span> <span class="kwrd">value</span>)
    {
      <span class="kwrd">if</span> (String.IsNullOrEmpty(<span class="kwrd">value</span>))
        <span class="kwrd">return</span> String.Empty;

      var sb = <span class="kwrd">new</span> StringBuilder();

      <span class="kwrd">foreach</span> (<span class="kwrd">char</span> @<span class="kwrd">char</span> <span class="kwrd">in</span> <span class="kwrd">value</span>)
      {
        <span class="kwrd">if</span> (unreservedCharacters.IndexOf(@<span class="kwrd">char</span>) != -1)
          sb.Append(@<span class="kwrd">char</span>);
        <span class="kwrd">else</span>
          sb.AppendFormat(<span class="str">"%{0:x2}"</span>, (<span class="kwrd">int</span>)@<span class="kwrd">char</span>);
      }
      <span class="kwrd">return</span> sb.ToString();
    }
  }
</pre></div>
<p>&nbsp;</p>
<table style="border-bottom: #ccc 1px solid; text-align: center; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" border="0" cellspacing="3" cellpadding="3">
<tbody>
<tr>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">&nbsp;</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">!</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">*</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">'</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">(</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">)</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">;</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">:</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">@</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">&amp;</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">=</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">+</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">$</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">,</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">/</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">?</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">#</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">[</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">]</td></tr>
<tr>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">HttpUtility<br></td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">!</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">*</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%27</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">(</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">)</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3a</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%40</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%26</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3d</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%2b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%24</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%2c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%2f</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3f</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%23</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5d</td></tr>
<tr>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">UrlEncode</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%21</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%2a</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%27</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%28</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%29</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3a</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%40</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%26</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3d</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%2b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%24</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%2c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%2f</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3f</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%23</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5d</td></tr></tbody></table>
<p>&nbsp;</p>
<table style="border-bottom: #ccc 1px solid; text-align: center; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" border="0" cellspacing="3" cellpadding="3">
<tbody>
<tr>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">&nbsp;</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">&lt;</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">&gt;</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">~</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">.</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">"</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">{</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">}</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">|</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">\</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">-</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">`</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">_</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">^</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">space</td></tr>
<tr>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">HttpUtility</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3e</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%7e</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">.</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%22</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%7b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%7d</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%7c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">-</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%60</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">_</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5e</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%25</td>
<td valign="top">+</td></tr>
<tr>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">UrlEncode</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%3e</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">~</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">.</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%22</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%7b</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%7d</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%7c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5c</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">-</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%60</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">_</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%5e</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%25</td>
<td style="border-bottom: #ccc 1px solid; border-left: #ccc 1px solid; border-top: #ccc 1px solid; border-right: #ccc 1px solid" valign="top">%20</td></tr></tbody></table>]]></description><category>Programming/C#</category><category>Http</category></item><item><title>Stop/Start Windows Service</title><pubDate>Wed, 02 Feb 2011 15:16:19 GMT</pubDate><link>http://www.matlus.com/stopstart-windows-service/</link><guid isPermaLink="true">http://www.matlus.com/stopstart-windows-service/</guid><description><![CDATA[<p>There are two code snippets presented in this post. Both of them deal with starting and stopping Windows Services. One option is to use the <code>net start/stop</code> command line option via C# and <code>System.Diagnostics.Process</code> so as to make the usage of this code more object oriented while the other option is to use the <code>ServiceController</code> class that's part of the .NET framework.</p> <p>Nothing spectacular really, but the purpose of me posting these code snippets is so its out there for those who are trying to figure this out and for me if/when I need to do this kind of thing again.</p> <p>Some features of the code presented below are:</p> <ol> <li>Re-Directs the Standard output stream using RedirectStandardOutput = true  <li>Re-Directs the Standard Error stream using RedirectStandardError = true  <li>Waits for the process to complete. In this case it waits for two processes to complete. The process that stops and then the process that starts.  <li>Asynchronously read from the Standard output and Standard Error streams</li></ol> <p>&nbsp;</p> <div class="panel code content/images/csharp.png" title="Using System.Diagnostics.Process"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> System.Text;
<span class="kwrd">using</span> System.Diagnostics;
<span class="kwrd">using</span> System.Runtime.Serialization;

<span class="kwrd">namespace</span> ResetService
{
  <span class="kwrd">enum</span> NetOperation { STOP, START };

  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> ServiceBounce
  {
    <span class="kwrd">private</span> <span class="kwrd">static</span> StringBuilder errorMessage = <span class="kwrd">new</span> StringBuilder();
    <span class="kwrd">private</span> <span class="kwrd">static</span> StringBuilder outputMessage = <span class="kwrd">new</span> StringBuilder();

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">int</span> TIMEOUT = 60000;

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">int</span> ExecuteNetProcess(NetOperation operation, <span class="kwrd">string</span> instanceName)
    {
      <span class="kwrd">using</span> (var process = <span class="kwrd">new</span> Process())
      {
        process.StartInfo = <span class="kwrd">new</span> ProcessStartInfo(<span class="str">"net"</span>, operation.ToString() + <span class="str">" "</span> + instanceName);
        process.StartInfo.UseShellExecute = <span class="kwrd">false</span>;
        process.StartInfo.RedirectStandardOutput = <span class="kwrd">true</span>;
        process.StartInfo.RedirectStandardError = <span class="kwrd">true</span>;
        process.OutputDataReceived += <span class="kwrd">new</span> DataReceivedEventHandler(OnOutputDataReceived);
        process.ErrorDataReceived += <span class="kwrd">new</span> DataReceivedEventHandler(OnErrorDataReceived);
        process.Start();
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        process.WaitForExit(TIMEOUT);
        <span class="kwrd">int</span> exitCode = process.ExitCode;
        process.Close();
        <span class="kwrd">return</span> exitCode;
      }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> ClearMessages()
    {
      outputMessage.Length = 0;
      errorMessage.Length = 0;    
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Restart(<span class="kwrd">string</span> serviceName)
    {
      Stop(serviceName);
      Start(serviceName);
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Stop(<span class="kwrd">string</span> serviceName)
    {
      ClearMessages();
      <span class="kwrd">string</span> errMessage = <span class="kwrd">null</span>;

      var exitCodeStop = ExecuteNetProcess(NetOperation.STOP, serviceName);
      <span class="kwrd">if</span> (exitCodeStop != 0)
      {
        errMessage = errorMessage.ToString();
        <span class="kwrd">if</span> (!errMessage.Contains(<span class="str">"service is not started"</span>))
          <span class="kwrd">throw</span> <span class="kwrd">new</span> MSSQLServiceBounceException(errorMessage.ToString());
      }
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Start(<span class="kwrd">string</span> serviceName)
    {
      ClearMessages();
      <span class="kwrd">string</span> errMessage = <span class="kwrd">null</span>;

      var exitCodeStart = ExecuteNetProcess(NetOperation.START, serviceName);
      Console.ForegroundColor = ConsoleColor.White;
      <span class="kwrd">if</span> (exitCodeStart != 0)
      {
        errMessage = errorMessage.ToString();
        <span class="kwrd">if</span> (!errMessage.Contains(<span class="str">"The requested service has already been started"</span>))
          <span class="kwrd">throw</span> <span class="kwrd">new</span> MSSQLServiceBounceException(errMessage);
      }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> OnOutputDataReceived(<span class="kwrd">object</span> sender, DataReceivedEventArgs e)
    {
      outputMessage.Append(e.Data);
      Console.ForegroundColor = ConsoleColor.DarkGreen;
      Console.WriteLine(e.Data);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> OnErrorDataReceived(<span class="kwrd">object</span> sender, DataReceivedEventArgs e)
    {
      errorMessage.Append(e.Data);
      Console.ForegroundColor = ConsoleColor.DarkRed;
      Console.WriteLine(e.Data);
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">class</span> MSSQLServiceBounceException : Exception
  {
    <span class="kwrd">public</span> MSSQLServiceBounceException(<span class="kwrd">string</span> message)
      :<span class="kwrd">base</span>(message)
    {
    }

    <span class="kwrd">public</span> MSSQLServiceBounceException(<span class="kwrd">string</span> message, Exception innerException)
      : <span class="kwrd">base</span>(message, innerException)
    {
    }

    <span class="kwrd">public</span> MSSQLServiceBounceException(SerializationInfo serializationInfo, StreamingContext context)
      : <span class="kwrd">base</span>(serializationInfo, context)
    {
    }
  }
}</pre></div>
<p>&nbsp;</p>
<p>The class shown in the code listing below uses the <code>ServiceController</code> class from the <code>System.ServiceProcess</code> assembly. This is a pure .NET solution to working with Windows Services. The <code>ServiceController</code> class makes it simple to make "synchronous" calls to stop and start services using the <code>WaitForStatus</code> method as you can see in the code listing below. The next code listing (the one below this one) shows you sample code of how you might use this class.</p>
<p>The features of the class presented below are:</p>
<p>The methods provide synchronous calls. That is the calls don't return until the service is either stopped or stated or stop/started as the case may be. If you do required asynchronous behavior, it's easy enough to modify the code since the normal behavior of the ServiceController class is async.</p>
<p>&nbsp;</p>
<div class="panel code content/images/csharp.png" title="Using System.ServiceProcess.ServiceController"><pre class="csharpcode">  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> WindowsServiceBounce
  {
    <span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;ServiceController&gt; FindService(Func&lt;ServiceController, <span class="kwrd">bool</span>&gt; predicate)
    {
      ServiceController[] services = ServiceController.GetServices();
      var servicesFound = from s <span class="kwrd">in</span> services
                          <span class="kwrd">where</span> predicate(s)
                          select s;
      <span class="kwrd">return</span> servicesFound;
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Restart(ServiceController service)
    {
      Restart(service, <span class="kwrd">new</span> TimeSpan(0, 1, 0));
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Restart(ServiceController service, TimeSpan waitTimeout)
    {
      Stop(service, waitTimeout);
      Start(service, waitTimeout);
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Stop(ServiceController service, TimeSpan waitTimeout)
    {
      <span class="kwrd">if</span> (service.Status == ServiceControllerStatus.StartPending)
        service.WaitForStatus(ServiceControllerStatus.StartPending, waitTimeout);
      
      <span class="kwrd">if</span> (service.Status == ServiceControllerStatus.Running)
      {
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, waitTimeout);
      }
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Start(ServiceController service, TimeSpan waitTimeout)
    {
      <span class="kwrd">if</span> (service.Status == ServiceControllerStatus.StopPending)
        service.WaitForStatus(ServiceControllerStatus.StopPending, waitTimeout);

      <span class="kwrd">if</span> (service.Status == ServiceControllerStatus.Stopped)
      {
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, waitTimeout);
      }
    }
  }</pre></div>
<p>&nbsp;</p>
<p>The code listing below shows and sample of how you might use the class presented in the previous code listing. </p>
<p>&nbsp;</p>
<div class="panel code content/images/csharp.png" title=""><pre class="csharpcode">      <span class="kwrd">var</span> services = WindowsServiceBounce.FindService(s =&gt; String.Compare(s.ServiceName, <span class="str">"MSSQL$SQLEXPRESS"</span>, StringComparison.OrdinalIgnoreCase) == 0);
      
      <span class="kwrd">foreach</span> (var service <span class="kwrd">in</span> services)
        WindowsServiceBounce.Restart(service, <span class="kwrd">new</span> TimeSpan(0, 1, 0));
      <span class="kwrd">foreach</span> (var service <span class="kwrd">in</span> services)
        service.Dispose();
</pre></div>]]></description><category>Programming/C#</category><category>Windows Services</category></item><item><title>MSSQL–Reset Identity seed</title><pubDate>Wed, 02 Feb 2011 06:32:00 GMT</pubDate><link>http://www.matlus.com/mssql-reset-identity-seed/</link><guid isPermaLink="true">http://www.matlus.com/mssql-reset-identity-seed/</guid><description><![CDATA[<p>There are times when I need to reset the identity seed value for tables with identity columns. Its rare that I need to do this and so this post is really a "note to self" if you will. But maybe others might find it handy as well:</p> <p>&nbsp;</p> <p><code>DBCC CHECKIDENT('sometable', RESEED, 0);</code></p> <p>&nbsp;</p> <p>Change 'sometable' to the name of your table. If you need to set the seed value to something other than zero, change the last parameter in the call from 0 to what you need. The way that last parameter works is this:</p> <p>Let's say you have a table (with an identity column) with 20 records. You've deleted a few records (because you've inserted records during test and you've now deleted them) and you know if you were to insert another record it is going to get an identity value of 42 say, but you want it to be 21. In order for this to work as you'd expect, set the last parameter to 20. Note, that's 20 and not 21. Of course make sure there are no records with an identity value greater than the value you set.</p>]]></description><category>Programming/SQL</category><category>Database</category></item><item><title>Linq Group By - Finding Duplicates</title><pubDate>Wed, 02 Feb 2011 04:11:51 GMT</pubDate><link>http://www.matlus.com/linq-group-by-finding-duplicates/</link><guid isPermaLink="true">http://www.matlus.com/linq-group-by-finding-duplicates/</guid><description><![CDATA[<p>This post is a little snippet on using Linq to find duplicates in a list of objects where a specific property of the object is used to find the duplicates. In this particular example, the objects are <code>Lessons</code> and in addition to other properties each lesson has a <code>AddedDate</code> property and what we need to do is find all lessons where the <code>AddedDate</code> is a duplicate of another lesson.</p> <p>In order to solve this we use <code>Group By</code> and we group by the <code>AddedDate</code> property and if any group has a count greater than 1, it is a duplicate and we need to get those. For test purposes, I've defined a variable called <code>testDateAndTime</code> that is assigned to the current DateTime. And then at the time of initializing the Lesson instances, I've assigned two lessons the same date and time using this variable. The two lessons (as shown in the code listing below) are:</p> <ol> <li>Preposition / Phrasal Verb  <li>German Verbs in the Present Tense</li></ol> <div class="panel code content/images/csharp.png" title="Linq - Group By Finding Duplicates"><pre class="csharpcode">  <span class="kwrd">class</span> Program
  {
    <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
    {
      var testDateAndTime = DateTime.Now;

      var lessons = <span class="kwrd">new</span> Lesson[] {
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Verb Tense"</span>, Subject=<span class="str">"English"</span>, AddedDate = DateTime.Now.AddMinutes(1)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Conditionals"</span>, Subject=<span class="str">"English"</span>, AddedDate = DateTime.Now.AddDays(2)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Gerunds and Infinitives"</span>, Subject=<span class="str">"English"</span>, AddedDate = DateTime.Now.AddDays(3)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Vocabulary"</span>, Subject=<span class="str">"English"</span>, AddedDate = DateTime.Now.AddDays(4)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Preposition / Phrasal Verb"</span>, Subject=<span class="str">"English"</span>, AddedDate = testDateAndTime},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Greetings"</span>, Subject=<span class="str">"German"</span>, AddedDate = DateTime.Now.AddMinutes(5)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Personal pronouns"</span>, Subject=<span class="str">"German"</span>, AddedDate = DateTime.Now.AddDays(6)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Introduction to nouns and gender"</span>, Subject=<span class="str">"German"</span>, AddedDate = DateTime.Now.AddDays(7)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"Two important verbs"</span>, Subject=<span class="str">"German"</span>, AddedDate = DateTime.Now.AddDays(8)},
        <span class="kwrd">new</span> Lesson { Title=<span class="str">"German Verbs in the Present Tense"</span>, Subject=<span class="str">"German"</span>, AddedDate = testDateAndTime}
      };

      var groupedLessons = from l <span class="kwrd">in</span> lessons
                           group l by l.AddedDate into g
                           <span class="kwrd">where</span> g.Count() &gt; 1
                           select <span class="kwrd">new</span> { AddedDate = g.Key, Lessons = g };

      <span class="kwrd">foreach</span> (var k <span class="kwrd">in</span> groupedLessons)
      {
        Console.WriteLine(<span class="str">"Added Date: "</span> + k.AddedDate);
        <span class="kwrd">foreach</span> (var l <span class="kwrd">in</span> k.Lessons)
        {
          Console.WriteLine(<span class="str">"\t Lesson Title: "</span> + l.Title);
        }
      }
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">class</span> Lesson
  {
    <span class="kwrd">public</span> <span class="kwrd">string</span> Title { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> Subject { get; set; }
    <span class="kwrd">public</span> DateTime AddedDate { get; set; }
  }</pre></div>
<p>&nbsp;</p>
<p>If you run this program you'll see the following output, which is what you'd expect.</p>
<div class="panel"><pre>Added Date: 2/2/2011 8:08:59 AM<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Lesson Title: Preposition / Phrasal Verb<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Lesson Title: German Verbs in the Present Tense
</pre></div>]]></description><category>Programming/C#</category><category>Linq</category></item><item><title>DataContractSerializer-IEnumerable&lt;T&gt;</title><pubDate>Tue, 25 Jan 2011 01:49:55 GMT</pubDate><link>http://www.matlus.com/ienumerablet-datacontractserializer/</link><guid isPermaLink="true">http://www.matlus.com/ienumerablet-datacontractserializer/</guid><description><![CDATA[<p>The <a title="Serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract." href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx"><code>DataContractSerializer</code></a> class is mainly used in WCF services but you can use it in any kind of project including ASP.NET based applications.</p> <p>There are some nice features this class offers in contrast to <a title="Provides serialization and deserialization functionality for AJAX-enabled applications." href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx"><code>JavaScriptSerializer</code></a> like the ability to control how property names get serialized using the DataMember attribute. One problem with this class is that it does not support serializing <code>IEnumerable&lt;T&gt;</code>. It supports generic collections such as <code>List&lt;T&gt;</code> but that's not what I need since there is a reason I'm using an <code>IEnumerable&lt;T&gt;</code> to serialize to JSON.</p> <p>In this post I'll present a <code><a href="#jsonserializer">JsonSerlizer</a></code> class that supports <code>IEnumerable&lt;T&gt;.</code> Some of the features of this class are as follows:</p> <ol> <li>Supports serializing IEnumberable&lt;T&gt; in addition to other collections types as well as non-collection types  <li>Serializes directly to System.IO.Stream (in contrast to JavaScriptSerializer)  <li>Supports JSONP, so you can publish your JSON feeds to the public</li></ol> <p>First let me begin by showing how I get the data and why I need to serialize and IEnumerable&lt;T&gt; in the first place.</p> <p>In <a href="#codelisting1">code listing 1</a> below, you can see the class <code>SubCategoryDrw</code> that will be serialized. It looks a bit complex but it's really just a POCO. It's what I call a <a title="DataReader Wrappers - TypeSafe" href="http://www.matlus.com/datareader-wrappers-typesafe/">DataReader Wrapper</a>. Anyway, I've decorated the class with the required <code>DataContract</code> attribute and its properties with the <code>DataMember</code> attribute while also modifying the property names and/or case that I'd like each property to be serialized as. This feature (the ability to change the name and /or case of property name) is the reason why I prefer using the <code>DataContractSerializer</code> class over the <code>JavaScriptSerializer</code> class.</p> <p>&nbsp;</p><a name="codelisting1"></a> <div class="panel code content/images/csharp.png" title="The SubCategoryDrw class"><pre class="csharpcode">  [DataContract]
  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> SubCategoryDrw : BaseDbDataReaderWrapper
  {
    <span class="preproc">#region</span> Properties

    <span class="kwrd">private</span> Int32 categoryId;
    [DataMember(Name=<span class="str">"categoryId"</span>)]
    <span class="kwrd">public</span> Int32 CategoryId { get { <span class="kwrd">switch</span> (Mode) { <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (Int32)DbDataReader[0]; <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> categoryId; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(Int32); } } set { categoryId = <span class="kwrd">value</span>; } }
    <span class="kwrd">private</span> Int32 subCategoryId;
    [DataMember(Name = <span class="str">"subCategoryId"</span>)]
    <span class="kwrd">public</span> Int32 SubCategoryId { get { <span class="kwrd">switch</span> (Mode) { <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (Int32)DbDataReader[1]; <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> subCategoryId; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(Int32); } } set { subCategoryId = <span class="kwrd">value</span>; } }
    <span class="kwrd">private</span> String categoryDescription;
    [DataMember(Name = <span class="str">"categoryDesc"</span>)]
    <span class="kwrd">public</span> String CategoryDescription { get { <span class="kwrd">switch</span> (Mode) { <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (String)DbDataReader[2]; <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> categoryDescription; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(String); } } set { categoryDescription = <span class="kwrd">value</span>; } }
    <span class="kwrd">private</span> String subCategoryDescription;
    [DataMember(Name = <span class="str">"subCategoryDesc"</span>)]
    <span class="kwrd">public</span> String SubCategoryDescription { get { <span class="kwrd">switch</span> (Mode) { <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (String)DbDataReader[3]; <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> subCategoryDescription; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(String); } } set { subCategoryDescription = <span class="kwrd">value</span>; } }

    <span class="preproc">#endregion</span> Properties

    <span class="kwrd">public</span> SubCategoryDrw(DbDataReader dbDataReader, WrapperMode mode)
      : <span class="kwrd">base</span>(dbDataReader, mode)
    {
      <span class="kwrd">switch</span> (Mode)
      {
        <span class="kwrd">case</span> WrapperMode.Wrapper:
          <span class="kwrd">break</span>;
        <span class="kwrd">case</span> WrapperMode.Dto:
          categoryId = (Int32)DbDataReader[0];
          subCategoryId = (Int32)DbDataReader[1];
          categoryDescription = (String)DbDataReader[2];
          subCategoryDescription = (String)DbDataReader[3];
          <span class="kwrd">break</span>;
      }
    }
  }
</pre>
<h3>Code Listing 1: Showing the POCO SubCategory class that will be serlized</h3></div>
<p>&nbsp;</p>
<p>In <a href="#codelisting2">code listing 2</a>, you see a method I have in my business layer, that returns an <code>IEnumerable&lt;SubCategoryDrw&gt;</code>. Because the intent is to go from data stream, straight out to the Http Response Stream in order to get the best performance possible, not only do I use a <code>DbDataReader</code> directly (along with a <a title="DataReader Wrappers - TypeSafe" href="http://www.matlus.com/datareader-wrappers-typesafe/">DataReader wrapper class</a> so I get type safety) and return an <code>IEnumerable&lt;T&gt;</code>, which basically means the data that comes out of the database is streamed directly to the Http Response stream in one single iteration.</p>
<p>&nbsp;</p><a name="codelisting2"></a>
<div class="panel code content/images/csharp.png" title="Business Layer Method - GetSubCategories()"><pre class="csharpcode">    <span class="kwrd">public</span> IEnumerable&lt;<span class="identifier">SubCategoryDrw</span>&gt; GetSubCategories()
    {
      <span class="kwrd">using</span> (var dr = DataModule.GetSubCategories())
      {
        var subCategoryDrw = <span class="kwrd">new</span> <span class="identifier">SubCategoryDrw</span>(dr, <span class="identifier">WrapperMode</span>.Wrapper);
        <span class="kwrd">while</span> (dr.Read())
          <span class="kwrd">yield</span> <span class="kwrd">return</span> subCategoryDrw;
      }
    }
</pre>
<h3>Code Listing 2: Showing the Business layer method returning an IEnumerable&lt;SubCategoryDrw&gt;</h3></div><a name="codelisting3"></a>
<p>&nbsp;</p>
<p>In <a href="#codelisting3">code listing 3</a> below you can see a WCF method wherein I use the JsonSerializer presented in this post to serialize a sequence of SubCategories. Note that I'm showing you a WCF method implementation, but you'll most likely use the JsonSerializer presented in this post in non-WCF applications since WCF 4.0 does handle serializing IEnumerable&lt;T&gt;.</p><a name="codelisting3"></a>
<div class="panel code content/images/csharp.png" title="WCF Operation Contract"><pre class="csharpcode">    [WebGet(UriTemplate = <span class="str">"/subcategories/"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> GetSubCategories()
    {
      var categories = BusinessModule.GetSubCategories();
      <span class="identifier">JsonSerializer</span>.Serialize(categories, Response.OutputStream, Request.QueryString[<span class="str">"callback"</span>]);
    }
</pre>
<h3>Code Listing 3: The WCF method that uses the JsonSerlizer to serialize an IEnumerable&lt;SubCategoryDrw&gt;</h3></div>
<p>&nbsp;</p>
<div class="panel">
<h3 class="note">WCF 4.0 Supports Serializing IEnumerable&lt;T&gt; via <code>CreateJsonResponse</code></h3><pre class="csharpcode">    [WebGet(UriTemplate = <span class="str">"/subcategories/"</span>)]
    <span class="kwrd">public</span> Message GetSubCategories()
    {
      var categories = BusinessModule.GetSubCategories();
      <span class="kwrd">return</span> <span class="identifier">WebOperationContext</span>.Current
        .CreateJsonResponse&lt;IEnumerable&lt;<span class="identifier">SubCategoryDrw</span>&gt;&gt;(categories);
    }

</pre></div>
<p>&nbsp;</p><a name="jsonserializer"></a>
<h2>JsonSerializer</h2>
<p>As I mentioned earlier, some of the features of this class are as follows: </p>
<ol>
<li>Supports serializing IEnumberable&lt;T&gt; in addition to other collections types as well as non-collection types 
<li>Serializes directly to System.IO.Stream (in contrast to JavaScriptSerializer) 
<li>Supports JSONP, so you can publish your JSON feeds to the public </li></ol>
<p>There are just 2 public methods in this class. One that expects and IEnumerable&lt;T&gt; as the object to serialize and another where the object is not an IEnumerable&lt;T&gt; either a List&lt;T&gt; or a non collection type object.</p>
<p>&nbsp;</p><a name="codelisting4"></a>
<div class="panel code content/images/csharp.png" title="JsonSerializer class"><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> <span class="identifier">JsonSerializer</span>
{
  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">byte</span>[] lBracketBytes = <span class="identifier">Encoding</span>.UTF8.GetBytes(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">'['</span> });
  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">byte</span>[] rBracketBytes = <span class="identifier">Encoding</span>.UTF8.GetBytes(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">']'</span> });
  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">byte</span>[] commaBytes = <span class="identifier">Encoding</span>.UTF8.GetBytes(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">','</span> });
  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">byte</span>[] rparenBytes = <span class="identifier">Encoding</span>.UTF8.GetBytes(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">')'</span> });

  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Serialize&lt;T&gt;(T obj, <span class="identifier">Stream</span> stream, <span class="kwrd">string</span> jsonpCallback = <span class="kwrd">null</span>)
  {
    <span class="kwrd">if</span> (jsonpCallback == <span class="kwrd">null</span>)
      WriteObject(obj, stream);
    <span class="kwrd">else</span>
    {
      WriteJsonPCallbackStart(stream, jsonpCallback);
      WriteObject(obj, stream);
      WriteJsonPCallbackEnd(stream);
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Serialize&lt;T&gt;(IEnumerable&lt;T&gt; sequence, <span class="identifier">Stream</span> stream, <span class="kwrd">string</span> jsonpCallback = <span class="kwrd">null</span>)
  {
    <span class="kwrd">if</span> (jsonpCallback == <span class="kwrd">null</span>)
      WriteSequence(sequence, stream);
    <span class="kwrd">else</span>
    {
      WriteJsonPCallbackStart(stream, jsonpCallback);
      WriteSequence(sequence, stream);
      WriteJsonPCallbackEnd(stream);
    }
  }

  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> WriteJsonPCallbackStart(<span class="identifier">Stream</span> stream, <span class="kwrd">string</span> jsonpCallback)
  {
    <span class="kwrd">byte</span>[] callbackStartBytes = <span class="identifier">UTF8Encoding</span>.UTF8.GetBytes(jsonpCallback + <span class="str">"("</span>);
    stream.Write(callbackStartBytes, 0, callbackStartBytes.Length);
  }

  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> WriteJsonPCallbackEnd(<span class="identifier">Stream</span> stream)
  {
    stream.Write(rparenBytes, 0, rparenBytes.Length);
  }

  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> WriteObject&lt;T&gt;(T obj, <span class="identifier">Stream</span> stream)
  {
    var serializer = <span class="kwrd">new</span> <span class="identifier">DataContractJsonSerializer</span>(<span class="kwrd">typeof</span>(T));
    serializer.WriteObject(stream, obj);
  }

  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> WriteSequence&lt;T&gt;(IEnumerable&lt;T&gt; sequence, <span class="identifier">Stream</span> stream)
  {
    var serializer = <span class="kwrd">new</span> <span class="identifier">DataContractJsonSerializer</span>(<span class="kwrd">typeof</span>(T));
    stream.Write(lBracketBytes, 0, lBracketBytes.Length);
    <span class="kwrd">int</span> i = 0;
    <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> sequence)
    {
      <span class="kwrd">if</span> (i != 0)
        stream.Write(commaBytes, 0, commaBytes.Length);
      serializer.WriteObject(stream, item);
      i++;
    }
    stream.Write(rBracketBytes, 0, rBracketBytes.Length);
  }
}</pre>
<h3>Code Listing 4: Listing of the entire JsonSerializer class</h3></div>
<p>That brings us to the end of this post.</p>]]></description><category>Programming/WCF</category><category>DbDataReader</category><category>JSON</category></item><item><title>svcTraceViewer - Debugging WCF Sevices</title><pubDate>Mon, 24 Jan 2011 01:44:12 GMT</pubDate><link>http://www.matlus.com/svctraceviewer-debugging-wcf-sevices/</link><guid isPermaLink="true">http://www.matlus.com/svctraceviewer-debugging-wcf-sevices/</guid><description><![CDATA[<p>This is a quick post about Debugging WCF Services and using svcTraceViewer. I'm writing this because I spent over half an hour trying to figure out what was wrong with one of my WCF services and then another half hour trying to figure out where to find svcTraceViewer.</p> <p>Once I figured out all of this the error happened to be really simple (the class I was trying to serialize was not marked with the <code>DataContract</code> attribute! If I were doing the same thing in ASP.NET or Quartz I would have seen the exception the first time and fixed it in the next second.</p> <p>The error I was seeing in Fiddler and Chrome was:</p> <p><code>Replying to an operation threw a exception</code></p> <h2>Where is scvTraceViewer?</h2> <p>On my machine I found it in the following folders:</p> <ul> <li><code><font size="2">C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\</font></code>  <li><code><font size="2">C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools</font></code>  <li><code><font size="2">C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64</font></code>  <li><code><font size="2">C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin</font></code></li></ul> <p>The first one seemed to be the latest version so I used that.</p> <p>Modifying Web.config for tracing</p> <div class="panel code content/images/html.png" title="Web.config file - system.dianostics section"><pre class="csharpcode">  <span class="kwrd">&lt;</span><span class="html">system.diagnostics</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">trace</span> <span class="attr">autoflush</span><span class="kwrd">="true"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">sources</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">source</span> <span class="attr">name</span><span class="kwrd">="System.ServiceModel"</span> <span class="attr">switchValue</span><span class="kwrd">="Information, ActivityTracing, Error, Critical"</span> <span class="attr">propagateActivity</span><span class="kwrd">="true"</span><span class="kwrd">&gt;</span>
          <span class="kwrd">&lt;</span><span class="html">listeners</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">name</span><span class="kwrd">="sdt"</span> <span class="attr">type</span><span class="kwrd">="System.Diagnostics.XmlWriterTraceListener"</span> <span class="attr">initializeData</span>= <span class="kwrd">"wcfTrace.svclog"</span> <span class="kwrd">/&gt;</span>
          <span class="kwrd">&lt;/</span><span class="html">listeners</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">source</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">sources</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">system.diagnostics</span><span class="kwrd">&gt;</span>
</pre></div>
<p>&nbsp;</p>
<p>If you don't have a &lt;system.diagnostics&gt; section in your web.config file already, this section is a top level section, that is, it is a sibling of <code>&lt;system.web&gt;</code> or <code>&lt;system.webServer&gt;</code> or <code>&lt;appSettings&gt;</code> or a child of the root node <code>&lt;configuration&gt;</code></p>
<p>Once you've set up your diagnostics section as shown above, exercise your service (and the method that's causing the problem) and you'll see the file <code>wcfTrace.svclog</code> created in the folder of your website application/website.</p>
<p>It so happens that files with the extension <code>*.svclog</code> are associated with svcTraceViewer! Of course I didn't know that when I first configured tracing and so I spent all that time trying to find scvTraceViewer. When I went to open the trace log file using svcTraceViewer and noticed that the default file extension it expects is .svclog I changed it.</p>
<p>Once you open the viewer you'll see log entries with errors highlighted in red (as shown in the image below), click on one of those entries and you'll see the cause for your error on the right hand side pane.</p>
<p><a href="http://www.matlus.com/content/uploads/2011/01/svcTraceViewerScreenShot_2.jpg"><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="svcTraceViewerScreenShot" border="0" alt="svcTraceViewerScreenShot" src="http://www.matlus.com/content/uploads/2011/01/svcTraceViewerScreenShot_thumb.jpg" width="640" height="463"></a></p>
<p>I hope this post helps others who have a similar problem. It's just not fun when you're trying to debug a problem and you can't figure out how to configure tracing and finding the tool that's going to get you out of the predicament.</p>]]></description><category>Programming/WCF</category><category>Debugging</category><category>REST</category></item><item><title>Fastest Website on the Planet!</title><pubDate>Sat, 22 Jan 2011 06:16:08 GMT</pubDate><link>http://www.matlus.com/fastest-website-on-the-planet/</link><guid isPermaLink="true">http://www.matlus.com/fastest-website-on-the-planet/</guid><description><![CDATA[<p>During the design and development of <a href="http://www.matlus.com/quartz-for-aspnet/">Quartz for ASP.NET</a> and <a title="Orion - A Blog Engine" href="http://www.matlus.com/orion/">Orion</a>, performance was an extremely important area I focused on. Optimizing a framework such as <a href="http://www.matlus.com/quartz-for-aspnet/">Quartz for ASP.NET</a> is important because other websites and application will be built using it and I believe it is imperative that frameworks pay close attention to performance. The same goes for Orion but of course at a different level since Orion is a web application.</p> <p>I should add that Quartz for ASP.NET does not sacrifice maintainability for performance however, there are many aspects of the design of the framework that lend themselves towards mind-bending performance. And of course code constructs.</p> <p>Anyway, this post is about the fastest website on the planet and you should know, you're on it! Yes, <a href="http://www.matlus.com/">Matlus</a> is currently the fastest website ranked by <a href="http://www.showslow.com/">http://www.showslow.com/</a>. Matlus has the following score:</p> <p><a title="Yahoo! YSlow" href="http://developer.yahoo.com/yslow/">YSlow</a> – Grade A</p> <p><a title="Google PageSpeed" href="http://code.google.com/speed/page-speed/">PageSpeed</a> – 99/100</p> <p>If it weren't for the Google analytics JavaScript file not being cached, <a title="Google PageSpeed" href="http://code.google.com/speed/page-speed/">PageSpeed</a> would have given it a 100/100!</p> <p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="MatlusOnShowSlow" border="0" alt="MatlusOnShowSlow" src="http://www.matlus.com/content/uploads/2011/01/MatlusOnShowSlow_1cfbf4af-1bba-4d61-ba73-cba4dd96d0ad.jpg" width="637" height="492"></p> <p>&nbsp;</p> <p>In Google Webmaster tools under "Labs" there is a Site Performance link and this is what I see there</p> <p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://www.matlus.com/content/uploads/2011/01/image_b76464eb-2c6f-4e97-9263-c7d748cac2ec.png" width="638" height="605"></p> <p>&nbsp;</p>  <p>Under the "Diagnostics" section, the "Crawl stats" shows me this. It so happens that I moved my blog from using WordPress as the blog engine to using <a title="Orion - A Blog Engine" href="http://www.matlus.com/orion/">Orion</a>. So if you look at the January portion of the graph that takes a big dip towards the end, that's when the switch happened.</p> <p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="GoogleTimeSpentDownloadingAPage" border="0" alt="GoogleTimeSpentDownloadingAPage" src="http://www.matlus.com/content/uploads/2011/01/GoogleTimeSpentDownloadingAPage_b3de8a26-9d46-4f02-acef-368171d77405.jpg" width="637" height="363"></p>]]></description><category>Programming/ASP.NET</category><category>Framework Design</category><category>Orion</category><category>Performance</category><category>Quartz for ASP.NET</category></item><item><title>Orion - A Blog Engine</title><pubDate>Thu, 13 Jan 2011 01:13:32 GMT</pubDate><link>http://www.matlus.com/orion/</link><guid isPermaLink="true">http://www.matlus.com/orion/</guid><description><![CDATA[<p>Orion is a high performance blogging engine written using the <a href="/quartz-for-aspnet/">Quartz for ASP.NET</a> framework. This blog is now powered by the <strong>Orion engine</strong>, so what you see by way of features, function and speed (responsiveness) is what you get with the Orion engine and of course the <a href="/quartz-for-aspnet/">Quartz for ASP.NET</a> framework.</p> <p>I was initially using WordPress for my blog (this blog) and eventually just got tired of having to deal with some of the nuances of WordPress and more specifically the theme I was using. However I had gotten used to using <a href="http://explore.live.com/windows-live-writer?os=other">Windows Live Writer</a> to write my posts and so the first thing I did, even before starting the Orion project was to implement and have a functional <a href="/metaweblog-api-c-library/">MetaWeblog API</a> implementation that I could use in Orion.</p> <p>&nbsp;</p> <p>I’ve posted source code for the Orion Project (as is). This is a VS.NET 2010 solution that also requires (references) the Quartz engine project (and not just the assemblies). If you are not too comfortable with VS.NET solutions and/or are not able to recover from problems such as missing projects due to missing paths etc. this download may not be for you. The only part I expect people might have trouble with is that this solution includes the Quartz project rather than referencing the assemblies and so the solution will not find the Quartz project when you first open it.</p> <p><a href="http://www.matlus.com/uploads/orion/orion.zip">Orion VS.NET 2010 Solution</a></p> <p>Download the <a href="http://www.matlus.com/quartz-for-aspnet/" target="_blank">Quartz for ASP.NET</a> project and source code for the link provided on that project’s page.</p>]]></description><category>Programming/ASP.NET</category><category>Html 5</category><category>Performance</category><category>Quartz for ASP.NET</category></item><item><title>MetaWeblog API C# Library</title><pubDate>Wed, 12 Jan 2011 19:22:45 GMT</pubDate><link>http://www.matlus.com/metaweblog-api-c-library/</link><guid isPermaLink="true">http://www.matlus.com/metaweblog-api-c-library/</guid><description><![CDATA[<p>When I started down the path of writing the <a title="Orion  - A Blogging Engine" href="/orion/">Orion</a> engine (a high performance blogging engine written in <a title="Quartz - A High Performance ASP.NET Framework" href="/quartz-for-aspnet/" target="_blank">Quartz for ASP.NET</a>), which is what drives this website, I wanted to be able to use <a href="http://explore.live.com/windows-live-writer?os=other" target="_blank">Windows Live Writer</a> to write my blog posts and so that need sent be down this path and so here we are. </p> <div class="panel"> <h3 class="note">Open Source Project - ooMetaWeblog</h3> <p>I've published this library as an open source project on <a title="CodePlex.com" href="http://www.codeplex.com/" target="_blank">CodePlex</a>. The project page is at: <a title="MetaWeblog API Open source project" href="http://metaweblogger.codeplex.com/" target="_blank">ooMetaWeblog</a> </p></div> <h2>Windows Live Writer</h2> <p>If you've got a blog, you should look at using <a title="Windows Live Writer 2011" href="http://explore.live.com/windows-live-writer?os=other" target="_blank">Windows Live Writer</a> and your blog writer/editor, there is nothing like it out there. It's very much like Microsoft Word and it is complete tailor made for blog writing, and for the kind of blog writing I do, which includes a lot of images and code snippets, it's perfect since there is a plug-in available for converting code from your VS.NET editor into html including all of the color highlighting etc.</p> <p>Windows Live Writer supports a number of blog writing/editing APIs and so I decided to implement one of those APIs for ThoughtStream so I didn't have to write and screen for the same (at least not right off the bat). And that's where the <a href="http://www.xmlrpc.com/metaWeblogApi" target="_blank">MataWeblog API</a> comes in.</p> <h2>MetaWeblog API</h2> <p>The <a title="XML-RPC.com" href="http://www.xmlrpc.com/metaWeblogApi" target="_blank">MetaWeblog API</a> is a well known API for writing and editing blog posts. There are many blog writers that support this API. It's not the best (read that as most complete) API for blog writing/editing but I've chose it after a lot of thought and debate. None of the APIs have good documentation so I went with the one API that almost all other APIs are based on.</p> <p>Personally I'm surprised that in this day and age there is no "real" blogging API. I've looked at the WordPress blogging API and even though it handles a few more things as compared to the MetaWeblog API (and Live Writer supports the WordPress API as well) it's really not a well thought out API. In fact none of the API are well thought out.</p><img alt="MetaWebLog API Flow" src="/content/uploads/2011/01/MetaWeblogFlow.jpg" width="640" height="243">  <p>Since documentation is sparse and I've seen a lot of people struggling with implementing this API, I've decided to make the library I've developed available to the public. I've use this library for my blog along with Windows Live Writer so I know it is tests and works as expected.</p> <h2>MetaWeblog C# Library</h2> <p>The first thing you want to look at are all the methods that are available in the API and their signatures. Take a look at code listing 1 below. The <code>IMetaWeblogProvider</code> interface has a bunch of methods as you can see.</p> <p>This is the interface you will need to implement in blog your blogging engine in order to make it compliant with the MetaWeblog API, so you can use a blog writer such as Window Live Writer to write your blog posts.</p> <p>You'll notice that the interface is completely decoupled from any http or xml nuance that is part of the MetaWeblog API. This was by design so as to make testing your implementation of this interface a lot simpler.</p> <div class="panel code content/images/csharp.png" title="IMetaWeblogProvider.cs"><pre><span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Collections.Generic;
<span style="color: blue">using </span>System.Linq;
<span style="color: blue">using </span>System.Web;

<span style="color: blue">namespace </span>Matlus.MetaWeblog
{
  <span style="color: blue">public interface </span><span style="color: #2b91af">IMetaWeblogProvider
  </span>{
    <span style="color: #2b91af">BlogInfo</span>[] GetUserBlogs(<span style="color: blue">string </span>appkey, <span style="color: blue">string </span>userName, <span style="color: blue">string </span>password);
    <span style="color: #2b91af">Post</span>[] GetRecentPosts(<span style="color: blue">string </span>userName, <span style="color: blue">string </span>password, <span style="color: blue">string </span>blogid, <span style="color: blue">int </span>noOfPosts);
    <span style="color: #2b91af">CategoryInfo</span>[] GetCategories(<span style="color: blue">string </span>userName, <span style="color: blue">string </span>password);
    <span style="color: blue">int </span>NewPost(<span style="color: blue">string </span>userName, <span style="color: blue">string </span>password, <span style="color: blue">string </span>blogid, <span style="color: #2b91af">Post </span>post);
    <span style="color: blue">void </span>EditPost(<span style="color: blue">string </span>userName, <span style="color: blue">string </span>password, <span style="color: #2b91af">Post </span>post);
    <span style="color: #2b91af">Post </span>GetPost(<span style="color: blue">string </span>userName, <span style="color: blue">string </span>password, <span style="color: blue">int </span>postid);
    <span style="color: blue">void </span>DeletePost(<span style="color: blue">string </span>userName, <span style="color: blue">string </span>password, <span style="color: blue">int </span>postid);
    <span style="color: #2b91af">MediaObjectInfo </span>NewMediaObject(<span style="color: blue">string </span>userName, <span style="color: blue">string </span>password, <span style="color: #2b91af">MediaObject </span>mediaObject);
  }
}
</pre>
<h3 style="margin-top: 0px">Code Listing 1</h3></div>
<p>Once you have the implementation of this interface functioning as you expect it to, getting it to work with Windows Live Writer or any other blog writer that supports the MetaWeblog API is quite simple. I do strongly suggest implementing this interface and testing it thoroughly before using the MetaWeblogManager class. </p>
<p>Now lets just take a brief look at the various other classes that are part of the library. Below is the class diagram of the complete MetaWeblog API library that's available for download. All of the heavy lifting is done by the <code>MetaWeblogManager</code> class. This class talks the MetaWeblog API language (which is essentially xml over http) and translates all of the communication into simple C# method calls. So you don't really have to mess with anything but your own implementation of the <code>IMetaWeblogProvider</code> interface. All of the other classes are supporting classes. The classes you see going down the left hand side are classes that will shuttle data between the MetaWeblogManager and your implementation of the IMetaWeblogProvider. They are simple DTOs and have no methods, just properties.</p>
<p>&nbsp;</p><img alt="Class Diagram of the MeataWeblog C# Library" src="/content/uploads/2011/01/MatlusMetaWeblogClassDiagram.jpg" width="634" height="643"> 
<h2>MetaWeblogManager</h2>
<p>Now, let's take a look at the <code>MetaWeblogManager</code> class in code listing 2 below. Once again you'll notice that this class really only works with a <code>System.IO.Stream</code>. This design decouples this class from any "web" stuff per se. Of course the Stream must contain the correct content (the xml content as per the API specification - you don't really have to worry about the xml aspect since the library handles that for you) but you're free to decide how exactly you'll provide it with this stream. The simplest way is to use this class from within an <code>IHttpHandler</code>, but you're not confined to this. It could be a WCF service or a regular ASP.NET web page.</p>
<p>I'm only listing the <code>ProcessMetaWeblogApiCall</code> method, which is the entry point of this class. This method calls into other methods within the class that do the translation from xml to regular C# (and back) and then call the appropriate methods in the <code>IMetaWeblogProvider</code> interface.</p>
<div class="panel code content/images/csharp.png" title="MetaWeblogManager.cs"><pre><span style="color: blue">public void </span>ProcessMetaWeblogApiCall(<span style="color: #2b91af">Stream </span>inputStream, <span style="color: #2b91af">Stream </span>outputStream)
{
  XmlDocument = <span style="color: blue">new </span><span style="color: #2b91af">XmlDocument</span>();
  XmlDocument.Load(inputStream);
  OutputStream = outputStream;

  <span style="color: blue">var </span>methodName = GetMethodName();

  <span style="color: blue">try
  </span>{        
    <span style="color: blue">switch </span>(methodName)
    {
      <span style="color: blue">case </span><span style="color: #a31515">"blogger.getUsersBlogs"</span>:
        GetUsersBlogs();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"metaWeblog.getCategories"</span>:
      <span style="color: blue">case </span><span style="color: #a31515">"wp.getCategories"</span>:
        GetCategories();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"metaWeblog.getRecentPosts"</span>:
        GetRecentPosts();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"metaWeblog.newPost"</span>:
        NewPost();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"metaWeblog.editPost"</span>:
        EditPost();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"metaWeblog.getPost"</span>:
        GetPost();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"blogger.deletePost"</span>:
        DeletePost();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"metaWeblog.newMediaObject"</span>:
        NewMediaObject();
        <span style="color: blue">break</span>;
      <span style="color: blue">case </span><span style="color: #a31515">"blogger.getUserInfo"</span>:
        GetUserInfo();
        <span style="color: blue">break</span>;
    }

  }
  <span style="color: blue">catch </span>(<span style="color: #2b91af">Exception </span>e)
  {
    WriteXmlRpcFault(e, outputStream);
  }      
}
</pre>
<h3 class="imgFooter">Code Listing 2: Showing the ProcessMetaWeblogApiCall method</h3></div>
<h2>The Complete Setup</h2>
<p>Of course in order to get Window Live Writer or any other blog writer to work against your blogging engine, you'll need to go all the way out to Http and that translates to an <code>IHttpHandler</code> or something similar. I've use a <code>Builder</code> (part of the <a title="Builder for ASP.NET Framework" href="/quartz-for-aspnet/" target="_blank">Quartz for ASP.NET</a> framework) as my point of entry into the <a href="/orion/">Orion</a> blog engine, but I'll show an implementation of an <code>IHttpHandler</code>. The handler is really very simple as you can see in code listing 3 below.</p>
<p>The <code>MetaWeblogManager</code> class expects an instance of a class that implements the <code>IMetaWeblogProvider</code> interface. In my case, my <code>BusinessModule</code> class is the class that implements this interface.</p>
<p>You'll need to register your handler like you would any other handler in ASP.NET.</p>
<div class="panel code content/images/csharp.png" title="An HttpHandler using the MetaWeblogManager class"><pre><span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Collections.Generic;
<span style="color: blue">using </span>System.Linq;
<span style="color: blue">using </span>System.Web;
<span style="color: blue">using </span>System.IO;
<span style="color: blue">using </span>System.Xml.Linq;
<span style="color: blue">using </span>System.Xml;
<span style="color: blue">using </span>Matlus.MetaWeblog;

<span style="color: blue">namespace </span>Orion.WebLib
{
  <span style="color: blue">public class </span><span style="color: #2b91af">XmlRpcHandler </span>: <span style="color: #2b91af">HandlerBase
  </span>{
    <span style="color: blue">public override bool </span>IsReusable
    {
      <span style="color: blue">get </span>{ <span style="color: blue">return true</span>; }
    }

    <span style="color: blue">public override void </span>ProcessRequest(<span style="color: #2b91af">HttpContext </span>context)
    {
      <span style="color: blue">var </span>metaWeblogManager = <span style="color: blue">new </span><span style="color: #2b91af">MetaWeblogManager</span>(BusinessModule);
      metaWeblogManager.ProcessMetaWeblogApiCall(<span style="color: #2b91af">HttpContext</span>.Current.Request.InputStream, <span style="color: #2b91af">HttpContext</span>.Current.Response.OutputStream);
    }
  }
}
</pre>
<h3 class="imgFooter">Code Listing 3: The IHttpHandler that instantiates the MetaWeblogManager</h3></div>
<p>This brings us to the end of this post. You can download the library from the link below.</p>
<p><a href="http://www.matlus.com/content/uploads/MetaWeblog/MatlusMetaWeblog.zip">Matlus.MetaWeblog</a></p>
<p>The download contains the complete source to the library. I'm using .NET 4.0 and I don't believe I'm using any .NET 4.0 specific features so you should be able to compile the library for .NET 3.5 if need be.</p>]]></description><category>Programming/ASP.NET</category><category>Orion</category><category>Quartz for ASP.NET</category></item><item><title>Data Access Layer CodeGen</title><pubDate>Sun, 19 Dec 2010 05:48:00 GMT</pubDate><link>http://www.matlus.com/data-access-layer-codegen/</link><guid isPermaLink="true">http://www.matlus.com/data-access-layer-codegen/</guid><description><![CDATA[<p>In an earlier article (<a href="http://www.matlus.com/datareader-wrappers-typesafe/">DataReader Wrappers – Type Safe</a>) I talked about using a DbDataReader wrapper class that allowed you to use a DbDataReader in a strongly typed way giving you the following additional benefit:</p> <p>The ability to use a DbDataReader as an IEnumerable&lt;T&gt;, giving is a performance advantage over other options because there is only ever one instance of the wrapper class created no matter how many records you've got.</p> <p>In this post I'll be presenting a tool that generates the Data Access Layer code using ADO.NET Core as the method of Data Access. ADO.NET core is the fastest way to access any database, bar none. According to Microsoft ADO.NET Core is about 3 times faster than any other Data Access method including Entity Framework and Linq to SQL.</p> <div class="panel"> <h3 class="note">Source Code and Project download</h3>You can download the source code and sample project from here <a href="http://www.matlus.com/content/uploads/SpCodeGenerator/SpCodeGenerator.zip">SpCodeGenerator</a>. Keep in mind that the GUI in the sample project is just a simple GUI. The source code of the Meta Data Extraction and code generation is pretty solid. I've used this tool to generate code for large production system as well as this blog. </div> <p>In addition, this tool also produces the DbDataReader wrapper classes and code you'll require.</p> <h2>Features of the Generated Code</h2> <p>For every "Get_XXX" stored procedure in your database the tool generates the appropriate data access code, including the DbDataReader wrapper class that matches the schema of the result set.</p> <p>If your stored procedure returns multiple result sets then the code generator will generate the appropriate DbDataReader wrapper classes for each of the results sets.</p> <p>For the Insert, Update, Delete stored procedures, the code generates the code for the command parameter assignment part of the code. You'll need to write the code that makes that actual call to the stored procedure. Mind you, the bulk of the code is generated for you (creating instances of the command parameters that match your stored procedure's parameters and types and assigning them to a command). You could easily modify the code generation to create that code for you as well.</p> <p>The generated code also includes a method that creates a DataTable or DataSet (as the case may be) for each of the "Get_XXX" stored procedures.</p> <p>If you prefer to use POCO classes instead of a DataTable or DbDataReader, you can easily add a code generator that does that for you. The tool is extensible and it's really a matter of subscribing to an event that provides all the meta data information about your stored procedure making it really easy to generate the code required for a POCO class definition.</p> <p>The code that available for download also includes a class that generates DataTable wrappers. This allows you to use a DataTable in a strongly typed fashion. It is not "active" (that is by default this class is not in use) but it's a simple matter of hooking it in.</p> <p>I've used the tool to generate all of the Data Access layer code including the DbDataReader wrapper classes and a few other classes (explained later) for over 980 stored procedures I have in one of the projects I've worked on. It takes about 30 seconds to generate close to 100,000 lines of code.</p> <p><a href="#codelisting1">Code listing 1</a> below, show the code it generated for one of my stored procedures called usp_GET_MEMBER_BLOGS. The namespace and class name of the partial class for the Data Access layer it generates are configurable. Your main Data Access layer class will be a partial class that has the same name and is in the same namespace.</p> <p>The two <code>internal</code> methods:</p> <p><code>GetMemberBlogs</code> (this returns a DbDataReader)</p> <p><code>GetMemberBlogsDataSet</code> (this returns a DataSet in this particular case since my stored procedure returns multiple result sets)</p> <p>are the ones you'll call from your Business Layer. Notice that the method names are derived from the name of the stored procedure and are in Pascal case as is the convention in C# for method names.</p><a name="codelisting1"></a> <div class="panel code content/images/csharp.png" title="Data Access layer code gen"><pre class="csharpcode"><span class="rem">//################################################################################</span>
<span class="rem">//                 This code file is an Auto Generated file</span>
<span class="rem">//      Do NOT Modify this file. All changes to this file WILL BE LOST</span>
<span class="rem">//################################################################################</span>

<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Data;
<span class="kwrd">using</span> System.Data.Common;

<span class="kwrd">namespace</span> MyApp.DataAccessLayer
{
    <span class="kwrd">internal</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> DataAccessModule
    {
        <span class="preproc">#region</span> usp_GET_MEMBER_BLOGS

        <span class="kwrd">internal</span> DbDataReader GetMemberBlogs(<span class="kwrd">long</span> memberId)
        {
            <span class="kwrd">using</span> (var command = CreateCommandForGetBlogItem(memberId))
            {
                DbConnection.Open();
                <span class="kwrd">return</span> command.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }

        <span class="kwrd">internal</span> DataSet GetMemberBlogsDataSet(<span class="kwrd">long</span> memberId)
        {
            var adapter = DbProviderFactory.CreateDataAdapter();
            adapter.SelectCommand = CreateCommandForGetBlogItem(memberId);
            var ds = <span class="kwrd">new</span> DataSet();
            adapter.Fill(ds);
            <span class="kwrd">return</span> ds;
        }

        <span class="kwrd">private</span> DbCommand CreateCommandForGetBlogItem(<span class="kwrd">long</span> memberId)
        {
            var command = DbConnection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = <span class="str">"usp_GET_BLOG_ITEM"</span>;
            var parameter = DbProviderFactory.CreateParameter();
            parameter.DbType = DbType.Int32;
            parameter.Direction = ParameterDirection.ReturnValue;
            parameter.ParameterName = <span class="str">"@RETURN"</span>;
            command.Parameters.Add(parameter);
            parameter = DbProviderFactory.CreateParameter();
            parameter.DbType = DbType.Int64;
            parameter.Direction = ParameterDirection.Input;
            parameter.ParameterName = <span class="str">"@MEMBER_ID"</span>;
            parameter.Value = memberId;
            command.Parameters.Add(parameter);
            <span class="kwrd">return</span> command;
        }

        <span class="preproc">#endregion</span> usp_GET_MEMBER_BLOGS

    }
}</pre></div>
<h3>Code Listing 1 – Showing the basic code generated for the Data Access Layer</h3>
<p>&nbsp;</p>
<p><a href="#codelisting2">Code listing 2</a> below shows the DbDataReader wrapper code that is generated. The code listing also includes a base class that was generated. The wrapper class that has been generated is called <code>MemberBlog0</code> in this case. The stored procedure I've used here returns 8 result sets and so the real code that was generated included 8 class definitions numbered from 0-7. In cases where the stored procedure returns only one result set, the name of the generated class would be <code>MemberBlogs.</code></p><a name="codelisting2"></a>
<div class="panel code content/images/csharp.png" title="DbDataReader Wrapper code gen"><pre class="csharpcode"><span class="rem">//################################################################################</span>
<span class="rem">//                 This code file is an Auto Generated file</span>
<span class="rem">//      Do NOT Modify this file. All changes to this file WILL BE LOST</span>
<span class="rem">//################################################################################</span>

<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Data;
<span class="kwrd">using</span> System.Data.Common;

<span class="kwrd">namespace</span> MyApp.BusinessLayer
{
    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// The WrapperMode enum determines the behavior of</span>
    <span class="rem">/// the Wrapper class. That is the class is either</span>
    <span class="rem">/// a "wrapper" around the DbDataReader or</span>
    <span class="rem">/// it initializes its properties using the DbDataReader</span>
    <span class="rem">/// as a "data source"</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">enum</span> WrapperMode { Wrapper, Dto }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">///This is the Base Class for all DbDataReader Wrappers</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">class</span> BaseDbDataReaderWrapper
    {
        <span class="kwrd">protected</span> DbDataReader DbDataReader { get; <span class="kwrd">private</span> set; }
        <span class="kwrd">protected</span> WrapperMode Mode { get; <span class="kwrd">private</span> set; }

        <span class="kwrd">public</span> BaseDbDataReaderWrapper(DbDataReader dbDataReader, WrapperMode mode)
        {
            DbDataReader = dbDataReader;
            Mode = mode;
        }
    }

    <span class="preproc">#region</span> [usp_GET_MEMBER_BLOGS]

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">///This class is a wrapper around a DbDataReader,</span>
    <span class="rem">///Associated with the stored procedure - usp_GET_MEMBER_BLOGS</span>
    <span class="rem">///This class provides a strongly typed interface to access data from the DbDataReader.</span>
    <span class="rem">///containing the result of the given stored procedure.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> MemberBlog0 : BaseDbDataReaderWrapper
    {
        <span class="preproc">#region</span> Properties

        <span class="kwrd">private</span> Int64 categoryId;
        <span class="kwrd">public</span> Int64 CategoryId { get { <span class="kwrd">switch</span>(Mode){ <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (Int64)DbDataReader[0]; <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> categoryId; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(Int64); } } set { categoryId = <span class="kwrd">value</span>; } }
        <span class="kwrd">private</span> String categoryName;
        <span class="kwrd">public</span> String CategoryName { get { <span class="kwrd">switch</span>(Mode){ <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (String)DbDataReader[1]; <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> categoryName; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(String); } } set { categoryName = <span class="kwrd">value</span>; } }
        <span class="kwrd">private</span> Int64 itemId;
        <span class="kwrd">public</span> Int64 ItemId { get { <span class="kwrd">switch</span>(Mode){ <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (DbDataReader[2] != DBNull.Value) ? (Int64)DbDataReader[2] : <span class="kwrd">default</span>(Int64); <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> itemId; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(Int64); } } set { itemId = <span class="kwrd">value</span>; } }
        <span class="kwrd">private</span> Int64 memberId;
        <span class="kwrd">public</span> Int64 MemberId { get { <span class="kwrd">switch</span>(Mode){ <span class="kwrd">case</span> WrapperMode.Wrapper: <span class="kwrd">return</span> (DbDataReader[3] != DBNull.Value) ? (Int64)DbDataReader[3] : <span class="kwrd">default</span>(Int64); <span class="kwrd">case</span> WrapperMode.Dto: <span class="kwrd">return</span> memberId; <span class="kwrd">default</span>: <span class="kwrd">return</span> <span class="kwrd">default</span>(Int64); } } set { memberId = <span class="kwrd">value</span>; } }

        <span class="preproc">#endregion</span> Properties

        <span class="kwrd">public</span> BMemberlog0(DbDataReader dbDataReader, WrapperMode mode)
            :<span class="kwrd">base</span>(dbDataReader, mode)
        {
            <span class="kwrd">switch</span>(Mode)
            {
                <span class="kwrd">case</span> WrapperMode.Wrapper:
                    <span class="kwrd">break</span>;
                <span class="kwrd">case</span> WrapperMode.Dto:
                    categoryId = (Int64)DbDataReader[0];
                    categoryName = (String)DbDataReader[1];
                    itemId = DbDataReader[2] != DBNull.Value ? (Int64)DbDataReader[2] : <span class="kwrd">default</span>(Int64);
                    memberId = DbDataReader[3] != DBNull.Value ? (Int64)DbDataReader[3] : <span class="kwrd">default</span>(Int64);
                    <span class="kwrd">break</span>;
            }
        }
    }</pre><pre class="csharpcode"><span class="preproc">    #endregion</span> [usp_GET_MEMBER_BLOGS]
}</pre></div>
<h3>Code Listing 2 – The DbDataReader Wrapper generated code</h3>
<p>&nbsp;</p>
<h2>Using the Generated DbDataReader wrapper class</h2>
<p><a href="#codelisting3">Code listing 3</a> shows 2 methods from the Business Layer that call into the Data Access layer. One of the methods returns <code>IEnumerable&lt;MemberBlogs&gt;</code> and the other return a <code>IList&lt;MemberBlogs&gt;</code>.</p>
<p>These methods are not code generated, however it would be simple enough to generate them as well if need be. The key thing to remember is that the classes that are part of the tool provide all the metadata you'll need to generate any code that works off of this information.</p>
<p>There are times when you'd use the first method and there are times when you'd use the second method. If you're simply iterating over the result (as fast as possible) to generate html in your ASP.NET MVC or ASP.NET WebForms application or streaming the result as a JSON stream or as a collection in a WCF application or WebService, then you should use the method that returns an <code>IEnumerable&lt;T&gt;</code>.</p>
<p>On the other hand, if you intend to hang on to the result (in your UI layer – ASP.NET WebForms/MVC application for example) or you intend to manipulate the result in some way (using Linq for example) then you should use the method that returns an <code>IList&lt;T&gt;</code>.</p>
<p>The reason is that when you're using a DbDataReader you want to consume the result as fast as possible, since the connection to your database is "open" till you do. In the same token, for the cases cited above you *want* to use a DbDataReader because there is no need to create a collection of some POCO objects only to stream them (serialize them) across the internet as a WebService message or JSON message for example). Going from a DbDataReader straight out as a JSON/WebService message is much faster and taxes your server far less (by way of less CPU utilization as well as less memory pressure) allowing you to process many more Request/Response cycles per second.</p>
<div class="panel code content/images/csharp.png" title="Using the DbDataReader Wrapper class"><pre class="csharpcode"><span class="kwrd">internal</span> IEnumerable&lt;BlogItem&gt; GetMemberBlogs(<span class="kwrd">long</span> memberId, <span class="kwrd">long</span> itemId)
{
  <span class="kwrd">using</span> (var dr = DataAccessModule.GetMemberBlogs(memberId, itemId))
  {
    var blogItem = <span class="kwrd">new</span> BlogItem(dr, WrapperMode.Wrapper);
    <span class="kwrd">while</span> (dr.Read())
      <span class="kwrd">yield</span> <span class="kwrd">return</span> blogItem;
  }
}

<span class="kwrd">internal</span> IList&lt;BlogItem&gt; GetMemberBlogsList(<span class="kwrd">long</span> memberId, <span class="kwrd">long</span> itemId)
{
  <span class="kwrd">using</span> (var dr = DataAccessModule.GetMemberBlogs(memberId, itemId))
  {
    var list = <span class="kwrd">new</span> List&lt;BlogItem&gt;();
    <span class="kwrd">while</span> (dr.Read())
      list.Add(<span class="kwrd">new</span> BlogItem(dr, WrapperMode.Dto));
    <span class="kwrd">return</span> list;
  }
}</pre></div>
<h3>Code Listing 3 – Showing how you'd use the Wrapper classes from your Business Layer</h3>
<p>&nbsp;</p>
<h2>The Case for using DbDataReaders</h2>
<p>There are few reasons for using a DbDataReader in general. I know ma lot of people in the .NET community shun the use of a DbDataReader or DataTable/DataSet. They think that using these classes ties them to a database. Well, that's not true and all. You can create a DataTable or DataSet simply by new-ing up an instance of a DataTable or DataSet and pumping data into it manually or reading in data from an Xml file. That is they don't have to be connected to a database at all.</p>
<p>Similarly, from an instance of a DataTable you can get an instance of a DbDataReader (which is an in memory DbDataReader effectively). No matter how you dice it, these classes do not tie you to a database and nor do they imply you're using a database of any kind.</p>
<p>There are some issues with using DbDataReader or DataTable/DataSet from within a Business layer, and I talked it earlier (<a href="http://www.matlus.com/datareader-wrappers-typesafe/">DataReader Wrappers – Type Safe</a>) and the wrapper classes are the solution to those issues.</p>
<p>In cases where you're extracting data from your database and simply iterating over this data and producing Html (via an ASP.NET MVC or WebForms app, or JSON or any other "serialized" format, using a DbDataReader makes total sense. There is absolutely no need to go from a DbDataReader to a collection of POCO objects to Html or other serialized formats.</p>
<p>Creating a collection of POCO objects means you've iterated over your result once. Then producing html or JSON or any other serialized format means you're iterating over your result again. Not only that, creating these objects only to throw them away is adding a lot of memory pressure on the GC and it takes a lot of time (CPU cycles) to create instances and assign their properties with values from a DbDataReader. Keep in mind that no matter what data access technology you use, including any ORMs as well as Linq to SQL, they all use DbDataReaders under the hood.</p>
<p>In some performance tests I've conducted, wherein I go from a DbDataReader, eventually out to a Web Page using Html, XML and JSON via one of the following:</p>
<p>1. POCO objects</p>
<p>2. DataTable/DataSet</p>
<p>3. Directly to the output format</p>
<p>I found that going from DbDataReader to POCO objects and then serializing them was by far the slowest. Going from DbDataReader to DataTable to the output format was way faster than POCO but quite a bit slower than going directly from DbDataReader to the desired output format. The difference becomes even more noticeable as the number of records in your result set increases.</p>
<p>And as I mentioned in the beginning of this post, according to Microsoft, ADO.NET core is about 3 times faster than any other Data Access technology. So if speed and scalability are a concern then DbDataReaders are the way to go.</p>
<p>Nonetheless, the code generation tool presented here doesn't stop you from creating POCO classes and using those instead. You're still using ADO.NET core (which is 3 times faster) and you get to use POCO objects in your business layer code.</p>]]></description><category>Programming/C#</category><category>ADO.NET</category><category>CodeGen</category><category>Data Access</category><category>DbDataReader</category><category>Performance</category></item><item><title>OAuth C# Library</title><pubDate>Mon, 06 Dec 2010 23:47:00 GMT</pubDate><link>http://www.matlus.com/oauth-c-library/</link><guid isPermaLink="true">http://www.matlus.com/oauth-c-library/</guid><description><![CDATA[<p>OAuth is a security protocol that enables a user to grant a third-party access to her web resources without sharing her password. <a href="http://oauth.net/core/1.0/" target="_blank">OAuth 1.0</a> was published in December 2007 and quickly become the industry standard for web-based access delegation. Then in June 2008 a minor revision (<a href="http://oauth.net/core/1.0a/" target="_blank">OAuth 1.0 Revision A</a>) was published, which fixed a security hole in the previous specification.</p> <p>OAuth 1.0 was based largely on two existing proprietary protocols:</p> <ol> <li><a href="http://code.google.com/apis/accounts/docs/AuthSub.html" target="_blank">Google’s AuthSub</a>  <li>Flickr’s API Auth </li></ol> <p>At the time (due the combined experiences) it was considered the best implementation of a security protocol for the purposes of authenticating third party applications and granting access to limited secured information of the user.</p> <p>OAuth is a complex protocol with a lot of to and fro between the relying party (the consumer or third party application) and the provider. As a result there are only a few implementation of the protocol that actually work across multiple providers.</p> <p>In this post, I'll be presenting you with a C# library that not only works across multiple providers but is also very simple to use and not over engineered like one or two of the other implementations and not so simple that it only works against one provider.</p> <p>The library presented has been tested against the following providers</p> <ol> <li>Google – <a href="http://code.google.com/apis/accounts/docs/OAuth_ref.html" target="_blank">OAuth Reference</a>  <li>Twitter – <a href="http://dev.twitter.com/pages/auth#at-twitter" target="_blank">OAuth Reference</a>  <li>Yahoo! – <a href="http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html" target="_blank">OAuth Reference</a>  <li>Vimeo – <a href="http://vimeo.com/api/docs/oauth" target="_blank">OAuth Reference</a> </li></ol> <p>The links above point to documentation on each of those sites so I won't repeat that information here as I believe each one presents the process flow pretty well and there is nothing I can really add to that information except to say that you do need to understand it pretty clearly in order to use any library that simplifies the process for you. Because there is a process involved and you have to code against that process.</p> <div class="panel"> <h2 class="note">Yahoo! won't work locally</h2> <p>You can't test against Yahoo! using your development machine or at least from a non routable IP address. All other services listed above do work using a non routable IP or localhost. The reason is that Yahoo! verifies that your request is truly coming from the domain you registered your application for.</p></div> <p>I found that working against Google's OAuth provider really cleaned up the library I present here (and where most other libraries fail) because of the tokens and keys Google sends back (which invariably need to be encoded before that can be used). I also believe that Google's design is the worst of the lot (unnecessarily complicated).</p> <p>For those of you just wanting dive right in and get the code, I've started an open source project on Google code, that houses the source code and a very simple ASP.NET application that will help you hit the ground running in no time flat. You can find the source code and sample project here</p> <div style="margin: 0px 0px -3px" id="pname"><a href="http://code.google.com/p/oauth-csharp-dotnet/">oauth-csharp-dotnet</a></div> <p>&nbsp;</p> <p>I've intentionally kept the code in the sample project really simple so it is easy to grasp how to use the library as well as the sequences of steps involved in the OAuth protocol. Once you understand the process you'll most likely want to re-engineer your application's code for your production systems. The library can be used as is.</p> <h2>The Sample Project</h2> <p>The screen shot below shows the default page of the application. If you've signed up with Google for example, then fill in the consumer key and consumer secret in the appropriate places in the code (there are two places you'll need to do this in – if you don't you'll get an exception, letting you know that that's what you need to do).</p> <p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="OAuthPage" border="0" alt="OAuthPage" src="http://www.matlus.com/content/uploads/2011/01/OAuthPage_f13d6eed-ed75-4506-bd7a-2632acdecfb6.png" width="559" height="317"></p> <p>Clicking on the Google icon will take you to Google. And Google will present the log in page where you can enter your Google account credentials. The page on Google will also present you with other information as shown below.</p> <p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="GoogleAccountLogin" border="0" alt="GoogleAccountLogin" src="http://www.matlus.com/content/uploads/2011/01/GoogleAccountLogin_fd0b4cab-b441-40c8-aca5-33abd9ef9765.jpg" width="559" height="485"></p> <p>Once you grant access you will have completed the process and you'll see the screen shot shown below</p> <p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="OAuthSuccess" border="0" alt="OAuthSuccess" src="http://www.matlus.com/content/uploads/2011/01/OAuthSuccess_240cb52b-0c57-429e-b564-610bf9f459fe.png" width="559" height="485"></p> <p>&nbsp;</p> <h2>OAuth Process</h2> <p>Essentially there are two kinds of application that may need to use OAuth for authentication purposes.</p> <ul> <li>Web Applications  <li>Installed Application </li></ul> <p>The library presented here is for Web Application, however the core code should be usable in an installed application as well since the core code handles all of the encryption/decryption (or hashing really) and other nuances of the protocol itself.</p> <p>In Web Application (for the purposes of OAuth) we employ what is frequently known as the 3-legged scenario. In word words there are essentially 3 steps to the entire process. It's all explained in the links above.</p> <h2>Getting Started</h2> <p>The very first step is getting a consumer key and consumer secret (also known as the shared secret). You'll need to sign up with a provider and register your domain and application in order to get these. Each provider will provide you with a consumer key and consumer secret that you'll have to use when communicating with their service.</p> <p>Once you have a consumer key and consumer secret, you'll also you're ready to begin. The sample project has code and the urls you'll need for the 4 providers I listed earlier. If you're working with another provider you'll also need the 3 endpoints (the urls) for each of the steps.</p> <div class="panel code content/images/csharp.png" title="OAuthConsumer.cs"><pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Step 1 of the oAuth protocol process</span>
<span class="rem">/// Make a request with the provider for a &lt;see cref="RequestToken"/&gt;</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;param name="requestTokenEndpoint"&gt;The url (as per the provider) to use for making a requet for a token&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="realm"&gt;Typically the url of Your "application" or website&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="consumerKey"&gt;The Consumer Key given to you by the provider&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="consumerSecret"&gt;The Consumer Secret given to you by the provider&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="callback"&gt;The url you'd like the provider to call you back on&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="signatureMethod"&gt;defaults to HMAC-SHA1 - the only signature method currently supported&lt;/param&gt;</span>
<span class="rem">/// &lt;returns&gt;An instance of a &lt;see cref="RequestToken" /&gt; class&lt;/returns&gt;</span>
<span class="kwrd">public</span> <span class="identifier">RequestToken</span> GetOAuthRequestToken(<span class="kwrd">string</span> requestTokenEndpoint, <span class="kwrd">string</span> realm, <span class="kwrd">string</span> consumerKey, <span class="kwrd">string</span> consumerSecret, <span class="kwrd">string</span> callback, <span class="identifier">SignatureMethod</span> signatureMethod = <span class="identifier">SignatureMethod</span>.HMACSHA1)
{
  <span class="kwrd">var</span> oAuthUtils = <span class="kwrd">new</span> OAuthUtils();
  <span class="kwrd">var</span> authorizationHeader = oAuthUtils.GetRequestTokenAuthorizationHeader(requestTokenEndpoint, realm, consumerKey, consumerSecret, callback, signatureMethod);
  <span class="kwrd">return</span> MakeRequest&lt;<span class="identifier">RequestToken</span>&gt;(requestTokenEndpoint, authorizationHeader);
}

<span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Step 3 of the oAuth protocol process</span>
<span class="rem">/// Make a request on the provider to Exchange a &lt;see cref="RequesToken"/&gt; for an &lt;see cref="AccessToken"/&gt;</span>
<span class="rem">/// (Step 2 is a simple redirect and so there is no method for it in this class)</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;param name="accessTokenEndpoint"&gt;The url (as per the provider) to use for making a requet to Exchange a request token for an access token&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="realm"&gt;Typically the url of Your "application" or website&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="consumerKey"&gt;The Consumer Key given to you by the provider&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="consumerSecret"&gt;The Consumer Secret given to you by the provider&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="token"&gt;The token you got at the end of Step 1 or Step 2&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="verifier"&gt;The verifier you got at the end of step 2&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="tokenSecret"&gt;The tokenSecret you got at the end of step 1&lt;/param&gt;</span>
<span class="rem">/// &lt;param name="signatureMethod"&gt;defaults to HMAC-SHA1 - the only signature method currently supported&lt;/param&gt;</span>
<span class="rem">/// &lt;returns&gt;An instance of a &lt;see cref="AccessToken"/&gt; class&lt;/returns&gt;</span>
<span class="kwrd">public</span> <span class="identifier">AccessToken</span> GetOAuthAccessToken(<span class="kwrd">string</span> accessTokenEndpoint, <span class="kwrd">string</span> realm, <span class="kwrd">string</span> consumerKey, <span class="kwrd">string</span> consumerSecret, <span class="kwrd">string</span> token, <span class="kwrd">string</span> verifier, <span class="kwrd">string</span> tokenSecret, <span class="identifier">SignatureMethod</span> signatureMethod = <span class="identifier">SignatureMethod</span>.HMACSHA1)
{
  <span class="kwrd">var</span> oAuthUtils = <span class="kwrd">new</span> OAuthUtils();
  <span class="kwrd">var</span> authorizationHeader = oAuthUtils.GetAccessTokenAuthorizationHeader(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, tokenSecret, signatureMethod);
  <span class="kwrd">return</span> MakeRequest&lt;<span class="identifier">AccessToken</span>&gt;(accessTokenEndpoint, authorizationHeader);
}</pre></div>
<h3>Code Listing 1: The Two Methods you'll use</h3>
<p>The two methods you see in the code listing above are the only two methods you'll use during the process of authenticating the user. The seconds step in the process is a simple re-direct and so there is no method for it in the library per-se. Besides the sample project if you need an explanation of the various parameters, please read the comments provided.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="OAuthProcess" border="0" alt="OAuthProcess" src="http://www.matlus.com/content/uploads/2011/01/OAuthProcess_8910534d-5ff9-4bff-a2d4-fe4a3b3df152.jpg" width="428" height="768"></p>
<p>These two methods will get you as far as authenticating the user using an external OAuth service provider. In other words, <em>she is who she says she is</em>. But you don't necessarily have any other information about her. In other words, executing and completing the Authentication process <strong>does not inherently provide you with any information about the authenticated user</strong>.</p>
<p>To get additional information you'll need to use the <code>AccessToken</code> (given to you by the provider in the 3rd and final step of the OAuth process), and make additional calls against the provider. The core library has the methods and functionality you'll need (at the core level) to make these additional calls.</p>
<p>Each provider has a different endpoint you'll need to use and not all providers have the same API and not all providers will provide the information you'll need about your user either.</p>
<h2>Retrieving Additional Information</h2>
<p>In the sample application there is a line that has been commented out at the end of the method that will retrieve the user's email address from Google. Of course you can use that only if you're using Google as the provider.</p>
<p>&nbsp;</p>
<div class="panel code content/images/csharp.png" title="Getting the Email Address"><pre class="csharpcode"><span class="kwrd">var</span> responseText = oAuthConsumer.GetUserInfo(<span class="str">"https://www.googleapis.com/userinfo/email"</span>, realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);</pre></div>
<h3>Retrieving an Authenticated user's Email Address (Google)</h3>
<p>&nbsp;</p>
<p>You should be able to write any additional methods you'll need using the code in <code>OAuthConsumer.cs</code> (partial listing in the code listing above) file that pertains to your needs and the specific provider(s) you're using.</p>
<p>That brings us to the end of this post. I truly hope the library and sample project will help you get started and in no time you'll have an OAuth implementation in your production applications.</p>]]></description><category>Programming/C#</category><category>Federated Identity</category><category>OAuth</category><category>Open Id</category></item><item><title>C# Class Factory - High Performance</title><pubDate>Tue, 23 Nov 2010 12:14:00 GMT</pubDate><link>http://www.matlus.com/high-performance-class-factory/</link><guid isPermaLink="true">http://www.matlus.com/high-performance-class-factory/</guid><description><![CDATA[<h2>Why use a class factory?</h2>There are many scenarios in software design where a factory comes in handy. Essentially, when you use a family of classes polymorphic-ally, you could benefit from using a Factory. Typically a factory provides the following benefits:  <ol> <li>Decouples the client code (your code that uses these classes) from knowing how to create instances of concrete types <li>Decouples the client code from knowledge of the concrete classes themselves. That is the client code knows only of the abstract base class or an interface but not the derived or concrete class</li></ol> <p>An important facet of system design is how objects are created. Most frameworks (including the .NET framework) make it extremely simple to create instances of classes and rightly so. However, what is not apparent is that you introduce coupling between the class that has been created and the class that uses the object. In small systems this coupling is not a problem but in large systems coupling between classes makes the system inflexible or rigid making changes over time more difficult to accommodate. The Factory design pattern helps alleviate this coupling.</p> <p>&nbsp;</p> <p><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="FactoryDesignPattern" border="0" alt="FactoryDesignPattern" src="http://www.matlus.com/content/uploads/2011/02/FactoryDesignPattern_41e6373b-9f78-413f-9163-bf7b1f3563aa.jpg" width="640" height="295">&nbsp;</p> <p>&nbsp;</p> <p>There are many ways in which to implement a factory. Ranging from simple to exotic. But essentially their implementations differ in the following area: </p> <ol> <li>How the decision is made as to which class to instantiate  <li>How an instance of a class is actually created </li></ol>In this article I'll show you an implementation that makes it really simple to use the factory design pattern while at the same time providing incredible performance. A high performance class factory comes in handy when you are creating hundreds of instances of your classes (typically in a server application scenario) and you need to squeeze out performance from core areas of your framework or application. I use this technique in the <a href="http://www.matlus.com/quartz-for-aspnet/">Quartz for ASP.NET</a> framework as it is critical that framework level code is high performance. Those of you who know what a factory is and when you'd use it can jump right to <a href="#highperformancefactory">High Performance Factory</a>  <h2>Understanding the use of a Factory</h2>By way of an example, lets say we have a bunch of employees and each <code>Employee</code> has a property called <code>EmployeeType</code> that specifies how the employee is paid. As you can see in the code listing below the <code>EmployeeType</code> enum has 3 possible values. The system uses this information to process the payment for each employee.  <div class="panel code content/images/csharp.png" title="Employee Class"><pre class="csharpcode"><span class="kwrd">enum</span> EmployeeType { Salaried, Commission, Hourly }

<span class="kwrd">class</span> Employee
{
  <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; <span class="kwrd">private</span> set; }
  <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; <span class="kwrd">private</span> set; }
  <span class="kwrd">public</span> EmployeeType EmployeeType { get; <span class="kwrd">private</span> set; }

  <span class="kwrd">public</span> Employee(<span class="kwrd">int</span> id, <span class="kwrd">string</span> name, EmployeeType employeeType)
  {
    Id = id;
    Name = name;
    EmployeeType = employeeType;
  }
}</pre></div>Then the code you'd write in order to process payments for each employee might look like this: 
<div class="panel code content/images/csharp.png" title="Sample Code"><pre class="csharpcode">var employees = <span class="kwrd">new</span> List&lt;Employee&gt;
  {
    <span class="kwrd">new</span> Employee(1, <span class="str">"Employee One"</span>, EmployeeType.Commission),
    <span class="kwrd">new</span> Employee(2, <span class="str">"Employee Two"</span>, EmployeeType.Hourly),
    <span class="kwrd">new</span> Employee(3, <span class="str">"Employee Three"</span>, EmployeeType.Salaried),
    <span class="kwrd">new</span> Employee(4, <span class="str">"Employee Four"</span>, EmployeeType.Salaried)
  };

  <span class="kwrd">foreach</span> (var employee <span class="kwrd">in</span> employees)
  {
    <span class="kwrd">switch</span> (employee.EmployeeType)
    {
      <span class="kwrd">case</span> EmployeeType.Salaried:
        <span class="rem">//Process payment for salaried employee</span>
        <span class="kwrd">break</span>;
      <span class="kwrd">case</span> EmployeeType.Commission:
        <span class="rem">//Process payment for commision employee</span>
        <span class="kwrd">break</span>;
      <span class="kwrd">case</span> EmployeeType.Hourly:
        <span class="rem">//Process payment for hourly employee</span>
        <span class="kwrd">break</span>;
    }
  }
</pre></div>Now in order to help with the payment processing, let's say we had a family of classes (one class for each <code>EmployeeType</code> that all descend from an abstract base class, like that shown below: 
<div class="panel code content/images/csharp.png" title="Payment Processor classes"><pre class="csharpcode"><span class="kwrd">abstract</span> <span class="kwrd">class</span> PaymentProcessorBase
{
  <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">void</span> ProcessPayment(Employee employee);
}

<span class="kwrd">class</span> SalariedPaymentProcessor : PaymentProcessorBase
{
  <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> ProcessPayment(Employee employee)
  {
    Console.WriteLine(employee.Name + <span class="str">"'s Payment was processed using Salaried Payment Processor"</span>);
  }
}

<span class="kwrd">class</span> CommissionPaymentProcessor : PaymentProcessorBase
{
  <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> ProcessPayment(Employee employee)
  {
    Console.WriteLine(employee.Name + <span class="str">"'s Payment was processed using Commission Payment Processor"</span>);
  }
}

<span class="kwrd">class</span> HourlyPaymentProcessor : PaymentProcessorBase
{
  <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> ProcessPayment(Employee employee)
  {
    Console.WriteLine(employee.Name + <span class="str">"'s Payment was processed using Hourly Payment Processor"</span>);
  }
}</pre></div>We could then alter our code to use these classes like so: 
<div class="panel code content/images/csharp.png" title="Sample Code"><pre class="csharpcode">PaymentProcessorBase processor = <span class="kwrd">null</span>;

<span class="kwrd">foreach</span> (var employee <span class="kwrd">in</span> employees)
{
  <span class="kwrd">switch</span> (employee.EmployeeType)
  {
    <span class="kwrd">case</span> EmployeeType.Salaried:
      processor = <span class="kwrd">new</span> SalariedPaymentProcessor();
      <span class="kwrd">break</span>;
    <span class="kwrd">case</span> EmployeeType.Commission:
      processor = <span class="kwrd">new</span> CommissionPaymentProcessor();
      <span class="kwrd">break</span>;
    <span class="kwrd">case</span> EmployeeType.Hourly:
      processor = <span class="kwrd">new</span> HourlyPaymentProcessor();
      <span class="kwrd">break</span>;
  }
  processor.ProcessPayment(employee);
}
</pre></div>This code works as expected, however there are two problems with this design. 
<ol>
<li>The client code is tightly coupled to the various concrete classes and has intimate knowledge of how to create them
<li>If you add a new EmployeeType you would have to alter this code to account for the new EmployeeType.</li></ol>
<p>&nbsp;</p>
<h2>&nbsp;</h2>
<h2>Factory - Simple implementation</h2>The simplest implementation of a factory might look something like that shown below 
<div class="panel code content/images/csharp.png" title="Simple Factory"><pre class="csharpcode"><span class="kwrd">class</span> SimplePaymentProcessorFactory
{
  <span class="kwrd">public</span> PaymentProcessorBase CreateFactory(<span class="kwrd">string</span> identifier)
  {
    <span class="kwrd">if</span> (identifier == <span class="str">"SalariedPaymentProcessor"</span>)
      <span class="kwrd">return</span> <span class="kwrd">new</span> SalariedPaymentProcessor();
    <span class="kwrd">else</span> <span class="kwrd">if</span> (identifier == <span class="str">"CommissionPaymentProcessor"</span>)
      <span class="kwrd">return</span> <span class="kwrd">new</span> CommissionPaymentProcessor();
    <span class="kwrd">else</span> <span class="kwrd">if</span> (identifier == <span class="str">"HourlyPaymentProcessor"</span>)
      <span class="kwrd">return</span> <span class="kwrd">new</span> HourlyPaymentProcessor();
    <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentException(<span class="str">"The identifier: "</span> + identifier + <span class="str">", is not a valid identifier"</span>, identifier);
  }
}
</pre></div>This design works well and the performance you get is unbeatable. However the implementation suffers from the following: 
<ol>
<li>Adding new classes means the code in the factory now need to be modified. So you shifted "the problem" from the client code to the factory. 
<li>If you're dealing with a lot of classes then this code could get pretty unwieldy 
<li>This design won't work in situations where you don't know the classes up front. Say in a plug-in scenario or similar, where all descendants current and future won't be known at the time of compiling this code. </li></ol>So what we need then is a way to allow some client code to register classes with the factory and then the way we create instances of the required classes has to resort to using Reflection since we don't know the types at compile time so we couldn't possible write code that instantiates an instance of a class we don't know about. The most common way to create an instance of a class using Reflection is <pre class="csharpcode"><span class="identifier">Activator</span>.CreateInstance()
</pre>and one of it's many overloads. This solution works really well but it can end up being slow if you're creating hundreds or thousands of classes in rapid succession (for example, in an ASP.NET application, your pages and handlers and controllers are created in Rapid succession). If you've got business rules that need to process thousands or millions of products items that the factory could end up being a bottle neck. <a name="highperformancefactory"></a>
<h2>High Performance Factory</h2>The key difference in the Factory presented in this article is that the creation of an instance of a class uses a delegate. Which means the performance is as good as calling a delegate which is as fast as calling a virtual method (in .NET). Considering the circumstances (that you don't know of the class you're going to be creating an instance of at the time of compiling your code) that is as good as it can get. Further, the factory automatically registers classes for you, so you don't have to register the classes you want the factory to create. You could easily modify the implementation such that classes need to register themselves with the factory. The implementation uses <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx" target="_blank">DynamicMethod</a> and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.ilgenerator.aspx" target="_blank">ILGenerator</a> and then use the <a href="http://msdn.microsoft.com/en-us/library/cye39zsf.aspx" target="_blank">CreateDelegate</a> method of <code>DynamicMethod</code> to create and instance of a delegate that really references the constructor of the class you intend to create. Onces it creates a delegate instance it caches it so, so the next time it simply calls the delegate. The entire class is listed in the code listing below 
<h3>Factory class - Using the default constructor of your classes</h3>
<div class="panel code content/images/csharp.png" title="Factory Class - Default Constructor"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Concurrent;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> System.Reflection;
<span class="kwrd">using</span> System.Reflection.Emit;

<span class="kwrd">namespace</span> Factory
{
  <span class="kwrd">static</span> <span class="kwrd">class</span> PaymentProcessorFactory
  {
    <span class="kwrd">private</span> <span class="kwrd">static</span> Type classType = <span class="kwrd">typeof</span>(PaymentProcessorBase);
    <span class="kwrd">private</span> <span class="kwrd">static</span> Type[] constructorArgs = <span class="kwrd">new</span> Type[] { };

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, Type&gt; classRegistry = <span class="kwrd">new</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, Type&gt;();
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, ConstructorDelegate&gt; classConstructors = <span class="kwrd">new</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, ConstructorDelegate&gt;();

    <span class="kwrd">delegate</span> PaymentProcessorBase ConstructorDelegate();

    <span class="kwrd">static</span> PaymentProcessorFactory()
    {
      var sw = System.Diagnostics.Stopwatch.StartNew();
      
      var paymentProcessors = from b <span class="kwrd">in</span> Assembly.GetEntryAssembly().GetTypes()
                             <span class="kwrd">where</span> b.IsSubclassOf(classType)
                             select b;

      <span class="kwrd">foreach</span> (var type <span class="kwrd">in</span> paymentProcessors)
        classRegistry.TryAdd(type.Name, type);
    }


    <span class="kwrd">public</span> <span class="kwrd">static</span> PaymentProcessorBase Create(<span class="kwrd">string</span> identifier)
    {
      <span class="kwrd">if</span> (String.IsNullOrEmpty(identifier))
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentException(<span class="str">"identifier can not be null or empty"</span>, identifier);
      <span class="kwrd">if</span> (!classRegistry.ContainsKey(identifier))
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentException(<span class="str">"No PaymentProcessor has been registered with the identifier: "</span> + identifier);

      <span class="kwrd">return</span> Create(classRegistry[identifier]);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> PaymentProcessorBase Create(Type type)
    {
      ConstructorDelegate del;

      <span class="kwrd">if</span> (classConstructors.TryGetValue(type.Name, <span class="kwrd">out</span> del))
        <span class="kwrd">return</span> del();

      <span class="identifier">DynamicMethod</span> dynamicMethod = <span class="kwrd">new</span> <span class="identifier">DynamicMethod</span>(<span class="str">"CreateInstance"</span>, type, constructorArgs, classType);
      <span class="identifier">ILGenerator</span> ilGenerator = dynamicMethod.GetILGenerator();

      ilGenerator.Emit(<span class="identifier">OpCodes</span>.Newobj, type.GetConstructor(constructorArgs));
      ilGenerator.Emit(<span class="identifier">OpCodes</span>.Ret);

      del = (ConstructorDelegate)dynamicMethod.CreateDelegate(<span class="kwrd">typeof</span>(ConstructorDelegate));
      classConstructors.TryAdd(type.Name, del);
      <span class="kwrd">return</span> del();
    }
  }
}</pre></div>
<p>&nbsp;</p>Now with our factory in place, then code that does the payment processing would become as simple as: 
<div class="panel code content/images/csharp.png" title="Code using the Factory"><pre class="csharpcode"><span class="kwrd">foreach</span> (var employee <span class="kwrd">in</span> employees)
{
  var paymentProcessor = PaymentProcessorFactory.Create(employee.EmployeeType.ToString() + <span class="str">"PaymentProcessor"</span>);
  paymentProcessor.ProcessPayment(employee);
}
</pre></div>
<p>&nbsp;</p>Notice that the "client code" (the code that uses the <code>PaymentProcessor</code> classes and the <code>Factory</code> is completely decoupled from any knowledge of the actual classes that help with the payment processing of the different types. Thus when you need to add new payment processor types, it's a matter of defining a class the descends from the base class and implementing it. The Factory will automatically find the new class and register it and your client code will not have to change one bit. Now if your classes require say two parameters in their constructor then there are a few modifications you'll need to do. Let's say your class requires an <code>Employee</code> and an <code>int</code> parameter in it's constructor. I've provided a complete listing on the Factory class that includes the changes you'll need to make. 
<h3>Factory class - Handling two parameters in the constructor of your classes</h3>
<div class="panel code content/images/csharp.png" title="Factory Class - 2 constructor parameters"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Concurrent;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> System.Reflection;
<span class="kwrd">using</span> System.Reflection.Emit;

<span class="kwrd">namespace</span> Factory
{
  <span class="kwrd">static</span> <span class="kwrd">class</span> PaymentProcessorFactory
  {
    <span class="kwrd">private</span> <span class="kwrd">static</span> Type classType = <span class="kwrd">typeof</span>(PaymentProcessorBase);
    <span class="kwrd">private</span> <span class="kwrd">static</span> Type[] constructorArgs = <span class="kwrd">new</span> Type[] { <span class="kwrd">typeof</span>(Employee), <span class="kwrd">typeof</span>(<span class="kwrd">int</span>) };

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, Type&gt; classRegistry = <span class="kwrd">new</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, Type&gt;();
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, ConstructorDelegate&gt; classConstructors = <span class="kwrd">new</span> ConcurrentDictionary&lt;<span class="kwrd">string</span>, ConstructorDelegate&gt;();

    <span class="kwrd">delegate</span> PaymentProcessorBase ConstructorDelegate(Employee employee, <span class="kwrd">int</span> intParam);

    <span class="kwrd">static</span> PaymentProcessorFactory()
    {
      var sw = System.Diagnostics.Stopwatch.StartNew();
      
      var paymentProcessors = from b <span class="kwrd">in</span> Assembly.GetEntryAssembly().GetTypes()
                             <span class="kwrd">where</span> b.IsSubclassOf(classType)
                             select b;

      <span class="kwrd">foreach</span> (var type <span class="kwrd">in</span> paymentProcessors)
        classRegistry.TryAdd(type.Name, type);
    }


    <span class="kwrd">public</span> <span class="kwrd">static</span> PaymentProcessorBase Create(<span class="kwrd">string</span> identifier, Employee employee, <span class="kwrd">int</span> intParam)
    {
      <span class="kwrd">if</span> (String.IsNullOrEmpty(identifier))
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentException(<span class="str">"identifier can not be null or empty"</span>, identifier);
      <span class="kwrd">if</span> (!classRegistry.ContainsKey(identifier))
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentException(<span class="str">"No PaymentProcessor has been registered with the identifier: "</span> + identifier);

      <span class="kwrd">return</span> Create(classRegistry[identifier], employee, intParam);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> PaymentProcessorBase Create(Type type, Employee employee, <span class="kwrd">int</span> intParam)
    {
      ConstructorDelegate del;

      <span class="kwrd">if</span> (classConstructors.TryGetValue(type.Name, <span class="kwrd">out</span> del))
        <span class="kwrd">return</span> del(employee, intParam);

      <span class="identifier">DynamicMethod</span> dynamicMethod = <span class="kwrd">new</span> <span class="identifier">DynamicMethod</span>(<span class="str">"CreateInstance"</span>, type, constructorArgs, classType);
      <span class="identifier">ILGenerator</span> ilGenerator = dynamicMethod.GetILGenerator();

      ilGenerator.Emit(<span class="identifier">OpCodes</span>.Ldarg_0);
      ilGenerator.Emit(<span class="identifier">OpCodes</span>.Ldarg_1);
      ilGenerator.Emit(<span class="identifier">OpCodes</span>.Newobj, type.GetConstructor(constructorArgs));
      ilGenerator.Emit(<span class="identifier">OpCodes</span>.Ret);

      del = (ConstructorDelegate)dynamicMethod.CreateDelegate(<span class="kwrd">typeof</span>(ConstructorDelegate));
      classConstructors.TryAdd(type.Name, del);
      <span class="kwrd">return</span> del(employee, intParam);
    }
  }
}</pre></div>If you classes require only 1 parameter in their constructor, you'll need to make the appropriate changes, and you'll need to remove the line: <pre class="csharpcode">ilGenerator.Emit(<span class="identifier">OpCodes</span>.Ldarg_1);
</pre>That brings us to the end of this article. I hope you found it useful. 

]]></description><category>Programming/C#</category><category>Design Pattern</category><category>Factory</category><category>Performance</category></item><item><title>The Purpose and function of a Data Access Layer</title><pubDate>Sat, 20 Nov 2010 00:54:00 GMT</pubDate><link>http://www.matlus.com/the-purpose-and-function-of-a-data-access-layer/</link><guid isPermaLink="true">http://www.matlus.com/the-purpose-and-function-of-a-data-access-layer/</guid><description><![CDATA[My inspiration for writing this post comes from answering questions for co-workers, colleagues and others in various forums. The various data access frameworks such as Entity Framework (EF4) and other open source frameworks seem to have confused or fooled people into thinking, either that these frameworks are the data access layer or that the function they perform is in fact the function of a data access layer. I beg to differ (obviously) and so this blog post...  <h2>The Purpose</h2>There are two primary purposes of a Data Access Layer  <ol> <li>Abstract the actual database engine or other data store, such that your applications can switch from using say Oracle to using MS SQL server  <li>Abstract the logical data model such that your Business Layer is decoupled from this knowledge and is agnostic of it. Giving you the ability to modify the logical data model without impacting the business layer </li></ol>Even though I've ordered the two primary purposes above as I have, #2 is far more important than #1. How often will you switch database engines in the lifetime of your application? Sure if you're building a customizable off-the-shelf product, you want to give your customers the option to pick any database engine of their choosing. but for the most part people are building business system for an organization and having the ability to switch database engines is not that important. But isolating your business layer from the logical (and physical) data model is paramount.  <div class="panel"> <h3 class="note">Changing the logical data model</h3>You will frequently change the logical design of your database during the lifetime of your system. I don't mean adding fields. Adding fields is extra information that your business system needs to account for so you can't help but impact almost every aspect of your system (if it is a field the user needs to see). I'm talking about normalization changes, or breaking tables into 1-1 relationships where the second table contains fields that relate directly to records in the first table but are infrequently used so as to optimize your query performance, for example. </div>The primary reason people seem to be using Entity Framework and other ORMs is "productivity". This productivity is essentially due to the data access code being generated, making it easy for them to access their data. Well, there are other tools that generate code but use ADO.NET Core to access data rather than creating another layer. ORMs have quite a few performance related issues as well, such as: 1. Doing a <code>select * from xxx</code> when you may only need say two fields from a table that has 50 fields 2. In order to do a delete or update, they first select the record and then fire a query to the delete or update. 3. There are many cases in which you have to resort to using Stored Procedures when using an ORM. So why bother? It's better to have one methodology of data access in a system instead of two. 4. In order to do some things in an ORM you have to use their proprietary language and/or mess about in the xml definition files. EF4 calls these Conceptual Model Functions or User Defined Functions that are a proprietary SQL dialect. That's one more language and tooling/designer that you have to learn to use.  <div class="panel"> <h3 class="note">EF4 and other ORMs</h3>Granted EF4 and other ORMs give you the option to use an additional "mapping" layer that in a way isolates your data classes from the logical data model. However, data bases already have such capabilities by way of Views and Stored Procedures. </div>In my opinion, these frameworks encourage you to break your design by giving you the ability to query the database from your business layers, effectively tightly coupling your business layer to the logical model. If you have to use an ORM (barring the issues cited above), then please wrap the ORM in a Data Access layer that surfaces domain specific methods (as explained layer). Don't assume that your ORM layer is your data access layer. ORMs do provide #1 above, but fail miserably at #2 and then go further and tie your business layer directly to the logical data model, defeating the whole purpose of a data access layer. So the moment you find yourself using <code>Linq</code> queries (that go against your database) from within your Business Layer, Stop! My advice to ORM fans, is to get familiar with your database and SQL. Knowledge and familiarity with SQL will go a very long way in making you a really good and effective software engineer. You can't hide from your database so you might as well embrace it.  <h2>The Business Layer</h2>Your Business Layer should not have intimate knowledge of your data model so it can't possibly fire a query against your data. Using <code>Linq</code> to objects in your Business Layer is fine so long as these objects are not data from your database. Just because you have the ability to use <code>Linq</code> doesn't mean you should. What is really important is to keep your business layer agnostic of your logical data model. That is the business layer shouldn't really know how the data is arranged or stored, in the database. To given an example, let's say you started out with a database design such that you have one table that contained the customers and their orders (not a normalized data model, I know, but bear with me for a bit). You business layer in turn has a need to see this data in a normalized form (header-detail). So it expects a DataSet say, with two DataTables, one for customers and one for their orders. Later, you change your data model to have customers and order is two different tables with a header-detail relationship. Your Business layer should not be impacted by this. And that is the function of the Data Layer (including the the use of Stored procedure).  <h2>Design of a Data Access Layer</h2>The best way to understand what your data layer must do for you is to see it from the perspective of a Business Layer. Since the <strong>Business Layer is data model agnostic</strong> it asks for data in the way *it* understands and it does so in very simple terms. That is the business layer talks in the language of the business or domain language. such as <pre>GetCustomers();
or 
GetCustomerOrders(42);
or
GetAllOrdersForThisMonth();
</pre>What the Business Layer gets back from the Data Layer can in the form of: 
<ol>
<li><code>DbDataReaders</code> that contain one or more result sets 
<li><code>DataTables</code> or <code>DataSets</code> 
<li>Instances of some POCOs (Plain Old CLR Objects) </li></ol>If you're using <code>DataTables</code> or <code>DataSets</code>, just remember to use them as <strong>one way only</strong> in-memory data. That is don't use them to post data back to the database. 
<div class="panel&gt;
&lt;h3 class=" note?>Yes DbDataReader is just fine!
<h3></h3>Some people might freak out when they read <code>DbDataReader</code>. Well, a DataReader *does not* have to be tied to a database or database engine, it can represent in-memory data completely independent of any database. So treat it as just that. A base class that holds one or more result sets. There are some drawbacks to using a DbDataReader but <a href="http://www.matlus.com/datareader-wrappers-typesafe/" target="_blank">those can be easily addressed</a> as I've demonstrated. DbDataReaders should be used only when you consume the data as fast as possible. So if you're binding your DbDataReader to a web page or if you're streaming a collection of objects out to clients from a WCF application or Web Service application then use a DbDataReader to go directly to the output stream. </div>The Data Layer is turn tries hard to isolate itself from data model changes and to some extent deep knowledge of the logical design of the database. This isolation is achieved by the use of stored procedure. Stored procedures, give you the ability to perform joins and projections on your data while the output is one or more flattened result sets. The Data Access layer has no idea how the data was really stored and that's the way it should be. So going back to our earlier example of customer orders. When the Business layer wants to create an order for a customer, if receives data from the UI, validates it and then it might use a method in the data access layer that looks like this: <pre>CreateCustomerOrder(42, order);
</pre>The Business Layer has no knowledge of the data model, it knows only of the business rules that are applicable. The DataAccess layer in turn might break up the data into an order and order line items but preferably it should make just one call to a stored procedure that knows what to do with this data and which tables to store it into. Isolating the Data Access layer from the logical model may not always be possible, in such cases it's ok to do things in the Data Access layer that warrant it's keen knowledge of the logical data model. But try and avoid it as far as possible. The Business Module on the other hand should never have intimate knowledge of the structure of data and relationships in the database. This whole subject is actually quite involved but I hope I've managed to impart the important aspects (albeit at a high level) of the purpose and function of a Data Access Layer and to some extent the Business Layer as well.
]]></description><category>Programming/C#</category><category>Data Access</category><category>Design Pattern</category></item><item><title>ASP.NET Performance-Instantiating Business Layers</title><pubDate>Fri, 19 Nov 2010 22:52:00 GMT</pubDate><link>http://www.matlus.com/instantiating-business-layers-asp-net-performance/</link><guid isPermaLink="true">http://www.matlus.com/instantiating-business-layers-asp-net-performance/</guid><description><![CDATA[The typical model of instantiating your Business Layer or business classes is to create an new instance each time you are servicing a request. That is, in your page or controller, you create a new instance of your business layer. Is there another way to do this and what would be the advantages? And would it be thread-safe? Yes, there is and the option I'll be presenting in this post has a few advantages as well. However, before we going into the details of this option we need to understand how things work insofar as IIS and the ASP.NET pipeline are concerned.  <h2>Relationship between IIS and ASP.NET</h2>In IIS your ASP.NET application really runs in an App Pool, or more specifically in a worker process that the App pool creates for your application (Take a look at Figure 1 below). A Worker Process is an application that hosts your ASP.NET application and effectively that is the App Domain in .NET terms.  <p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="IISAppPoolAndGlobal" border="0" alt="IISAppPoolAndGlobal" src="http://www.matlus.com/content/uploads/2011/01/IISAppPoolAndGlobal_7a87db2b-b0be-4e84-96dd-d2bf6d0f4cfa.jpg" width="457" height="337">  <h3 class="imgFooter">Figure1</h3> <div class="panel tbmargin"> <h3 class="note">IIS, App Pool and Worker Process</h3>For the purposes of this discussion, I'll treat IIS, App Pool and the Worker Process as one and the same and so you may see me use these synonymously. </div>When IIS fields a request for your application it hands it over to the worker process. The worker process in turn creates and instance of your Global class (which is of type <code>HttpApplication</code>). From that point on the typical flow of an ASP.NET application takes place (the ASP.NET pipeline). However, what you need to know and understand is that the worker process (think of it as IIS really) keeps the instance of your <code>HttpApplication</code> (an instance of your <code>Global</code> class) alive, in order to field other requests. In fact it by default it would create and cache up to 10 instances of your <code>Global</code> class, if required (Lazy instantiation) depending on load the number of requests your website receives other factors. In Figure1 above the instances of your ASP.NET application are shown as the red boxes. There could be up to 10 of these cached by the worker process. These are really threads that the worker process has created and cached and each thread has its own instance of your <code>Global</code> class. Note that each of these threads is in the same App Domain. So any static classes you may have in your application are shared across each of these threads or application instances.  <div class="panel tbmargin"> <h3 class="note">IIS and Request Queuing</h3>If your site is really busy and/or your requests are long running requests and the 10 cached instances are all busy servicing other requests, then when a new request arrives for your application, IIS will queue this request. In fact it will (by default) queue up to 1000 requests in the hope that one of the 10 threads will eventually free up and it can hand the request over to it. Beyond that your site visitors will see a "Server too busy" error. </div> <h2>Business Layers and Global</h2>Given the information discussed thus far, lets move on to the matter at hand and that is the strategy we can and should employ in creating instances of our business layer. Let's just recap what we've learn't so far: Multiple instances of your <code>Global</code> class will exist in the Worker process for your application (in IIS). Each one waiting to be called upon by IIS to satisfy a request. IIS will pick any one of these instances. They are actually threads that have been cached by IIS and each thread has an instance of your Global class. When a request comes in, one of these threads is called upon to handle the request-response cycle. If multiple requests arrive simultaneously, then multiple threads (each containing an instance of your Global class) will be called upon to satisfy each of those requests. IIS guarantees that one thread will service <b>one and only one</b> Request-Response cycle at any given time. If other requests arrive simultaneously, they will be handled by other threads. These other threads are either cached from earlier or a new thread will be created and new instance of your <code>Global</code> class will be created and assigned to this thread in order to service the request. If all of the above is clear, then the answer is pretty simple. Global should create an instance of your Business layer! Because we know that  <ol> <li>A Request-Response is handled by one and only one (IIS) thread  <li>This thread has it's own instance of <code>Global</code>  <li>By default there there may be up to 10 instances of <code>Global</code> created  <li>These instances are cached </li></ol> <p>If we create an instance of our Business Layer within the Global class the instance is not shared with other threads and so it's all thread-safe. Further, instances of our Business Layer will be in tandem with instances of Global so there will be only 10 instances created and these will be cached, so we won't be creating and disposing instances for every request-response cycle in our application. This gives us a huge performance benefit as well. </p> <p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="GlobalBusinessLayerDataLayer" border="0" alt="GlobalBusinessLayerDataLayer" src="http://www.matlus.com/content/uploads/2011/01/GlobalBusinessLayerDataLayer_2819bcfe-6884-4589-be6f-b17b6fc03791.jpg" width="337" height="264"></p> <p>&nbsp;</p> <div class="panel tbmargin"> <h3 class="note">Business Layer MUST be stateless</h3>Be aware that your Business Layers and DataAccess layers MUST be stateless. That is they should not rely on any state that may have been set in a previous request-response cycle. Remember that once an instace has been created, it will likely serve thousands of requests over it's lifetime. If you do need to reset any state, you can do it in the <code>BeginRequest</code> event of <code>Global</code>. This will ensure that at the start of each Request-Response cycle, all state has been reset. </div>The code below, shows how you would go about creating an instance of your business layer in <code>Global</code>. Due to the way the ASP.NET framework has been designed, it is important that you create the instance in the <code>Init()</code> method as shown below. Notice also, that we have a property in <code>Global</code> for our Business layer. This is so we can get a reference to it from our <code>Pages</code>, <code>Controllers</code> and <code>Handlers</code>.  <div class="panel code content/images/csharp.png" title="Creating and instance Business Layer in Global "><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> <span class="identifier">Global</span> : HttpApplication
{
  <span class="kwrd">public</span> <span class="identifier">BusinessModule</span> BusinessModule { get; <span class="kwrd">private</span> set; }

  <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Init()
  {
    <span class="kwrd">base</span>.Init();
    BusinessModule = <span class="kwrd">new</span> <span class="identifier">BusinessModule</span>();      
  }
}</pre></div>When we want to get a reference to our Business layer instance from within a <code>Page</code>, <code>Controller</code> or <code>Handler</code>, we can define 
<div class="panel code content/images/csharp.png" title="Getting a Reference to BusinessModule from Pages, Controllers etc."><pre class="csharpcode"><span class="kwrd">protected</span> <span class="identifier">BusinessModule</span> BusinessModule { get { <span class="kwrd">return</span> ((<span class="identifier">Global</span>)<span class="identifier">HttpContext</span>.Current.ApplicationInstance).BusinessModule; } }</pre></div>I hope you found this discussion helpful and useful. I've been using this technique ever since I first started with ASP.NET using version 1.0 and 1.1. I've used it in every project so far and a lot of these project are large/busy website's and have benefited tremendously from the performance gains of this technique.
]]></description><category>Programming/ASP.NET</category><category>Performance</category></item><item><title>DataReader Wrappers - TypeSafe</title><pubDate>Thu, 18 Nov 2010 18:33:00 GMT</pubDate><link>http://www.matlus.com/datareader-wrappers-typesafe/</link><guid isPermaLink="true">http://www.matlus.com/datareader-wrappers-typesafe/</guid><description><![CDATA[DataReaders (<code>DbDataReader</code>), in .NET give you the fastest access to your data. There is nothing that beats the speed of DataReaders. However, there are a few drawbacks to using them <ol> 	<li>No Type Checking</li> 	<li>If field ordering or field name changes in your stored procedures or queries will likely break your code</li> 	<li>Code that uses DataReaders tends to be not so clear to read</li> </ol> Here is a example of what the typical code looks like: Lets say we have a blog item record that has the following fields: <ol> 	<li>ItemId</li> 	<li>MemberId</li> 	<li>ItemTitle</li> 	<li>ItemDesc</li> 	<li>ItemPubdate</li> 	<li>ItemCommentCnt</li> 	<li>ItemAllowComment</li> </ol> In order to use a DataReader your code might look like the following: <div class="panel code content/images/csharp.png" title="DataReader - using field names"> <pre class="csharpcode"><span class="kwrd">using</span> (DbDataReader dr = GetBlog(42))
{
  var blogs = <span class="kwrd">new</span> List&lt;BlogItem&gt;();
  <span class="kwrd">while</span> (dr.Read())
  {
    var blogItem = <span class="kwrd">new</span> BlogItem();

    blogItem.ItemId = (<span class="kwrd">long</span>)dr[<span class="str">"ItemId"</span>];
    blogItem.MemberId = (<span class="kwrd">long</span>)dr[<span class="str">"MemberId"</span>];
    blogItem.ItemTitle = (<span class="kwrd">string</span>)dr[<span class="str">"Itemtitle"</span>];
    blogItem.ItemDesc = dr[<span class="str">"ItemDesc"</span>] != DBNull.Value ? (<span class="kwrd">string</span>)dr[<span class="str">"ItemDesc"</span>] : <span class="kwrd">null</span>;
    blogItem.ItemPubdate = (DateTime)dr[<span class="str">"ItemPubdate"</span>];
    blogItem.ItemCommentCnt = (<span class="kwrd">int</span>)dr[<span class="str">"ItemCommentCnt"</span>];
    blogItem.ItemAllowComment = (<span class="kwrd">bool</span>)dr[<span class="str">"ItemAllowComment"</span>];

    blogs.Add(blogItem);

  }
  <span class="kwrd">return</span> blogs;
}</pre>
</div>
In the code above, I'm using field names to get at the fields, but it is faster if you index into the fields as shown below.
<div class="panel code content/images/csharp.png" title="DataReader using Field index">
<pre class="csharpcode"><span class="kwrd">using</span> (DbDataReader dr = GetBlog(42))
{
  var blogs = <span class="kwrd">new</span> List&lt;BlogItem&gt;();
  <span class="kwrd">while</span> (dr.Read())
  {
    var blogItem = <span class="kwrd">new</span> BlogItem();

    blogItem.ItemId = (<span class="kwrd">long</span>)dr[0];
    blogItem.MemberId = (<span class="kwrd">long</span>)dr[1];
    blogItem.ItemTitle = (<span class="kwrd">string</span>)dr[2];
    blogItem.ItemDesc = dr[3] != DBNull.Value ? (<span class="kwrd">string</span>)dr[3] : <span class="kwrd">null</span>;
    blogItem.ItemPubdate = (DateTime)dr[4];
    blogItem.ItemCommentCnt = (<span class="kwrd">int</span>)dr[5];
    blogItem.ItemAllowComment = (<span class="kwrd">bool</span>)dr[6];

    blogs.Add(blogItem);

  }
  <span class="kwrd">return</span> blogs;
}</pre>
</div>
In both these code snippets there are a few problems.
<ol>
	<li>No compile type type checking</li>
	<li>Readability isn't too good</li>
	<li>If a field is null-able (like ItemDesc above) then the code to access the field's value is even more cumbersome</li>
</ol>
Here is what I use in order to be able to use DataReaders but no have the issues cited above.
<div class="panel code content/images/csharp.png" title="DataReader Wrapper">
<pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">///This is the Base Class for all DbDataReader Wrappers</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> <span class="identifier">BaseDbDataReaderWrapper</span>
{
    <span class="kwrd">public</span> <span class="identifier">DbDataReader</span> DbDataReader { get; set; }

    <span class="kwrd">public</span> BaseDbDataReaderWrapper()
    {
    }

    <span class="kwrd">public</span> BaseDbDataReaderWrapper(DbDataReader dbDataReader)
      :<span class="kwrd">this</span>()
    {
        DbDataReader = dbDataReader;
    }
}

<span class="rem">/// &lt;summary&gt;</span>
<span class="rem">///This class is a wrapper around a DbDataReader,</span>
<span class="rem">///Associated with the stored procedure - usp_GET_BLOG_ITEM</span>
<span class="rem">///This class provides a strongly typed interface to access data from the DbDataReader.</span>
<span class="rem">///containing the result of the given stored procedure.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> <span class="identifier">BlogItemDrw</span> : <span class="identifier">BaseDbDataReaderWrapper</span>
{
    <span class="kwrd">public</span> <span class="identifier">Int64</span> ItemId { get { <span class="kwrd">return</span> (<span class="identifier">Int64</span>)DbDataReader[0]; } }
    <span class="kwrd">public</span> <span class="identifier">Int64</span> MemberId { get { <span class="kwrd">return</span> (<span class="identifier">Int64</span>)DbDataReader[1]; } }
    <span class="kwrd">public</span> <span class="identifier">String</span> ItemTitle { get { <span class="kwrd">return</span> (<span class="identifier">String</span>)DbDataReader[2]; } }
    <span class="kwrd">public</span> <span class="identifier">String</span> ItemDesc { get { <span class="kwrd">if</span> (DbDataReader[3] != <span class="identifier">DBNull</span>.Value) <span class="kwrd">return</span> (<span class="identifier">String</span>)DbDataReader[3]; <span class="kwrd">else</span> <span class="kwrd">return</span> <span class="kwrd">default</span>(<span class="identifier">String</span>); } }
    <span class="kwrd">public</span> <span class="identifier">DateTime</span> ItemPubdate { get { <span class="kwrd">return</span> (<span class="identifier">DateTime</span>)DbDataReader[4]; } }
    <span class="kwrd">public</span> <span class="identifier">Int32</span> ItemCommentCnt { get { <span class="kwrd">return</span> (<span class="identifier">Int32</span>)DbDataReader[5]; } }
    <span class="kwrd">public</span> <span class="identifier">Boolean</span> ItemAllowComment { get { <span class="kwrd">return</span> (<span class="identifier">Boolean</span>)DbDataReader[6]; } }
    <span class="kwrd">public</span> BlogItemDrw()
      :<span class="kwrd">base</span>()
    {
    }

    <span class="kwrd">public</span> BlogItemDrw(DbDataReader dbDataReader)
      :<span class="kwrd">base</span>(dbDataReader)
    {
    }
}</pre>
</div>
The class above is designed in such as way as to require only one instance of the class while you're iterating over the DataReader. This technique also has a postivate impact on performance, since you're not creating a new instance of this class for each record in your DataReader.
<h2>IEnumerable&lt;T&gt; - DbDataReader</h2>
The way you'd use this class is really in a method that returns an <code>IEnumerable&lt;T&gt;</code>.
<div class="panel code content/images/csharp.png" title="IEnumerable&lt;T&gt; DataReader Wrapper">
<pre class="csharpcode"><span class="kwrd">public</span> IEnumerable&lt;BlogItem&gt; GetBlogs()
{
  <span class="kwrd">using</span> (DbDataReader dr = GetBlogsDataReader())
  {
    var blogItem = <span class="kwrd">new</span> BlogItem(dr);
    <span class="kwrd">while</span> (dr.Read())
    {
      <span class="kwrd">yield</span> <span class="kwrd">return</span> blogItem;
    }
  }
}</pre>
</div>
When you use a DataReader like this (<code>IEnumerable&lt;T&gt;</code>) you have to be careful in that you need to be aware that each time you iterate over the <code>IEnumerable</code>, you're really querying the database again. Further, the code that returns the DataReader (<code>GetBlogsDataReader()</code> in this case) should make sure the connection is closed when the DataReader is disposed by using the <code>CommandBehavior.CloseConnection</code> behavior at the time of calling the <code>ExecuteReader()</code> method on a command instance like so:
<pre><span class="kwrd">return</span> command.ExecuteReader(<span class="identifier">CommandBehavior</span>.CloseConnection);</pre>
<h2>List&lt;T&gt; - DbDataReader</h2>
There may be times when you need to use a List&lt;T&gt; instead of an IEnumerable&lt;T&gt; because you either have multiple result sets being returned in the DataReader or you need to fire another query and you can't have a DbDataReader open and fire another query using the same connection. In such situations your class could look like this:

<div class="panel code content/images/csharp.png" title="List&lt;T&gt; DataReader">
<pre class="csharpcode">
  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> BlogItem
  {
    <span class="kwrd">public</span> Int64 ItemId { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Int64 MemberId { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> String ItemTitle { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> String ItemDesc { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> DateTime ItemPubdate { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> DateTime ItemPubtime { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Decimal ItemRatingAvg { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Int32 ItemViewCnt { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Int32 ItemCommentCnt { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Int32 ItemRatingCnt { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Int32 ItemFavoriteCnt { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Boolean ItemIsPrivate { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Boolean ItemAllowComment { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Boolean ItemIsPublished { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> BlogItem(DbDataReader dbDataReader)
      : <span class="kwrd">base</span>()
    {
      ItemId = (Int64)dbDataReader[0];
      MemberId = (Int64)dbDataReader[1];
      ItemTitle = (String)dbDataReader[2];
      ItemDesc = dbDataReader[3] != DBNull.Value ? (String)dbDataReader[3] : <span class="kwrd">default</span>(String);
      ItemPubdate = (DateTime)dbDataReader[4];
      ItemRatingAvg = (Decimal)dbDataReader[5];
      ItemViewCnt = (Int32)dbDataReader[6];
      ItemCommentCnt = (Int32)dbDataReader[7];
      ItemRatingCnt = (Int32)dbDataReader[8];
      ItemFavoriteCnt = (Int32)dbDataReader[9];
      ItemIsPrivate = (Boolean)dbDataReader[10];
      ItemAllowComment = (Boolean)dbDataReader[11];
      ItemIsPublished = (Boolean)dbDataReader[12];
    }
  }</pre>
</div>

And the way you'd use this class to return a <code>List&lt;<span class="identifier">BlogItem</span>&gt;</code> is

<div class="panel code content/images/csharp.png" title="Using List&lt;T&gt; DataReader Wrapper class">
<pre style="margin:0em;">     <span style="color:#0000ff">internal</span><span style="color:#000000">  <span style="color:#2b91af">List</span><span style="color:#000000"> &lt;<span style="color:#2b91af">BlogItem</span><span style="color:#000000"> &gt; GetMemberBlogsList(<span style="color:#0000ff">long</span><span style="color:#000000">  memberId)</pre>
<pre style="margin:0em;">     <span style="color:#000000">{</span></pre>
<pre style="margin:0em;">       <span style="color:#0000ff">using</span><span style="color:#000000">  (<span style="color:#0000ff">var</span><span style="color:#000000">  dr = DataAccessModule.GetMemberBlogs(memberId))</pre>
<pre style="margin:0em;">       <span style="color:#000000">{</span></pre>
<pre style="margin:0em;">         <span style="color:#0000ff">var</span><span style="color:#000000">  blogItems = <span style="color:#0000ff">new</span><span style="color:#000000">  <span style="color:#2b91af">List</span><span style="color:#000000"> &lt;<span style="color:#2b91af">BlogItem</span><span style="color:#000000"> &gt;();</pre>
<pre style="margin:0em;">         <span style="color:#0000ff">while</span><span style="color:#000000">  (dr.Read())</pre>
<pre style="margin:0em;">           blogItems.Add(<span style="color:#0000ff">new</span><span style="color:#000000">  <span style="color:#2b91af">BlogItem</span><span style="color:#000000"> (dr));</pre>
<pre style="margin:0em;">         <span style="color:#0000ff">return</span><span style="color:#000000">  blogItems;</pre>
<pre style="margin:0em;">       <span style="color:#000000">}</span></pre>
<pre style="margin:0em;">     <span style="color:#000000">}</span></pre>
<pre style="margin:0em;"> </pre>
<pre style="margin:0em;"> </pre>
</div>

<h2>Code Generation</h2>
Ideally, you'd want these wrapper classes to be automatically generated for you as per the stored procedure's metadata. That way, if you change the number of fields or field ordering in your stored procedures the class definition changes and of course if there is a breaking change, you'll know that as soon as you compile your project.

I'll be posting another blog about the code generation aspect and I'll make the source code and a sample project available for download as well.]]></description><category>Programming/C#</category><category>ADO.NET</category><category>CodeGen</category><category>Data Access</category><category>DbDataReader</category><category>Performance</category></item><item><title>Quartz for ASP.NET</title><pubDate>Wed, 10 Nov 2010 18:03:00 GMT</pubDate><link>http://www.matlus.com/quartz-for-aspnet/</link><guid isPermaLink="true">http://www.matlus.com/quartz-for-aspnet/</guid><description><![CDATA[<p>The genesis of <b>Quartz for ASP.NET</b> was what I felt were some <a href="http://www.matlus.com/problems-with-asp-net-mvc-framework-design/">Problems with ASP.NET MVC Framework Design</a>. Quartz for ASP.NET can be used in conjunction with ASP.NET MVC or in regular ASP.NET WebApplication/Website projects (without any WebForms). It works the same either way. </p> <p>&nbsp;</p> <div class="panel"> <h3 class="note">Videos and Downloads</h3> <p>There are a few Videos in the <a href="#videos">Videos section</a> below, that you may want to watch. </p> <p>In the <a href="#downloads">Downloads</a> you can find the following:  <ol> <li>The Complete source code (.Net 4.0 compatible only at the moment)  <li>A Sample Project  <li>A New Quartz Project Item - for VS 2010  <li>A New Quarts Builder Item - for VS 2010  <li>A New Quartz View Item - for VS 2010 </li></ol></div> <p>&nbsp;</p> <p>Quartz for ASP.NET is the most intuitive way to build dynamic web pages, using a powerful combination of class Composition and Inheritance. Today’s dynamic pages are rarely simple, so you need something that gives you more control over how your pages are composed. With Quartz for ASP.NET you continue to get the <b>loose coupling</b> and <b>separation of concerns</b> that the MVC design pattern provides and in addition you also get  <ul> <li>Loose coupling between Views and Template  <li>Templates are Html. That is there is no html+code OR code+html  <li>Views can be treated as real classes - inheritance/polymorphism and you write code in a.cs file  <li>Strong typing and F12 navigation  <li>Plug-able Websites/applications </li></ul> <p>However, the primary driver for Quartz for ASP.NET was the way in which you build pages in ASP.NET MVC and the problems with that design. Figure 1 below, shows the relationship and flow of control in the ASP.NET MVC design, between a Controller and a View, Partial View and Master Page/Layout Page. </p><a name="figure1"></a><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Quartz Design And Control Flow" border="0" alt="Quartz Design And Control Flow" src="http://www.matlus.com/content/uploads/2011/01/BuilderDesignAndControlFlow_8873aee6-9745-4fcf-a5b3-49b4e1d9070e.jpg" width="421" height="282">  <h4>Figure 1: ASP.NET MVC - relationship between a Controller and "views"</h4> <div class="mgntop10"></div> <p>You'll notice that the process of building a page is akin to a chain reaction. That wouldn't be so bad if it weren't for the fact that the controller is not really controlling anything besides starting off a specific chain reaction (everything to the left of the Controller on the right in <a href="#figure1">Figure1</a>). </p> <h2 class="sectionheading">How Quartz for ASP.NET Works</h2> <p>Figure 2 shows the relationship and flow of control between the <code>Builder</code> and the Views and Master Page Template. <a name="figure2"></a> <p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Quartz For ASP.NET - Build By Composition" border="0" alt="Quartz For ASP.NET Build By Composition" src="http://www.matlus.com/content/uploads/2011/01/BuilderForASPNETBuildByComposition_970bef33-dcda-4898-86fd-f96df20651c5.jpg" width="547" height="312">&nbsp; <h4>Figure 2: Quartz for ASP.NET - relationship between a Builder and Views</h4> <div class="mgntop10"></div>In Quartz for ASP.NET you use composition to build your pages. That is, a page is a composition of multiple View objects. The <code>Builder</code> orchestrates the entire composition. The way it works is this:  <ol> <li>The Builder picks a Master Template (an Html file). This template usually has spots that need to be filled in, as shown in <a href="#figure2">Figure 2 above</a>, the "Page"  <li>It then picks the appropriate views for each of these spots (a base class (of the Builder) could enlist some views to do the "common" parts and the descendant Builder could choose to override these choices)  <li>Since the Builder has access to instances of each of the views enlisted to render the page, it can talk directly to these views to hand them the data each of them will need to do their part.  <li>Again, since the Builder has access to views as objects instances it can treat views polymorphic-ally if required or use inheritance or both  <li>Once it has done the above, each of the views go off and do their part (generate html) and a page is produced.  <li>Since views are regular .NET classes you have the full might of the .NET framework at your disposal. And since their only job is to produce html in conjunction with the Request Context (of the current request) and the data they’ve been handed by the Builder, it’s totally up to you, how you do that. The Quartz framework does provide some options out of the box, and they are:  <ul> <li>Simply generate html using just code and data, writing directly to the output  <li>Use html templates (with placeholder tags – parser included with the framework) to render html directly to the output. This method has the added advantage that you have no html in code and templates can be re-used across multiple views and/or a view can use multiple templates or decide to use a different template conditionally  <li>Use any other mechanism to generate html, such as T4 Templates. </li></ul></li></ol> <p>The code listing below is a sample of the code you'd write in a <code>Builder</code>'s <code>BuildPage()</code> method.  <div class="panel code content/images/csharp.png" title="Sample Code"><pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> BuildPage(HttpContextBase httpContext, <span class="kwrd">object</span> model)
{
    var featuresAllPageViewModel = (<span class="identifier">FeaturesAllPageViewModel</span>)model;

    TitleView.Title = <span class="str">"Quartz for ASP.NET - Features"</span>;
    AdBoxTopView.BoxTitle = <span class="str">"Highlights"</span>;
    AdBoxTopView.Model = featuresAllPageViewModel.AdBoxModel;

    RegisterView(<span class="str">"Body"</span>, <span class="kwrd">new</span> <span class="identifier">FeaturesAllView</span>(httpContext, <span class="kwrd">this</span>, featuresAllPageViewModel.Features));
  }
}
</pre></div>
<h2 class="sectionheading">Composing Pages with Quartz for ASP.NET</h2>
<p>Traditionally, web application frameworks work in a inside-out fashion. That is, when you field a request for a page, you’re really starting with the inner most part of the page and working your way out (by calling <code>RenderAction</code> or <code>RenderPartial</code> in MVC parlance). In Quartz for ASP.NET you start with a template and compose your page using multiple views. It’s really a lot more intuitive to think and work this way, than inside-out.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="InsideOutFlow" border="0" alt="InsideOutFlow" src="http://www.matlus.com/content/uploads/2011/01/InsideOutFlow_e8aa0001-1671-4c15-9a88-fddb80b7753e.jpg" width="640" height="480"></p>
<h3>Figure 3: Quartz for ASP.NET - Composing Pages in an intuitive manner</h3>
<h2 class="sectionheading">More Features of Quartz for ASP.NET</h2>
<p>
<ul class="list">
<li>Since all templates are html, your designer can build templates using the html design tool of her choice, and both you and the designer can live an uncluttered life (no more html+code or code+html) 
<li>Views are completely unaware of the Builder that enlisted them or any other Builders for that matter. In Quartz for ASP.NET, Views are the "leaf nodes". There is only one loosely coupled linkage, that between the Builder and the views it enlists. 
<li>All the code you write is strongly typed so you get all the benefits of strong typing and the IDE can help you navigate your classes and methods (F12). 
<li>Blazingly FAST! </li></ul>
<div class="panel">
<h3 class="note">Razor Views</h3>In the Quartz framework, templates are really just html templates. This keeps your templates clean, reusable and designable by web designers. However, since the Razor syntax is so cool, there is an <b><i>experimental</i></b> RazorView that you can try out. At the moment the view template is compiled each time the view is rendered. I'm not sure this feature will go too far since it kind of goes against the grain. But it's there... </div><a name="videos"></a>
<h2>Quartz for ASP.NET - Quick-Dive Video</h2>In the video below I attempt to give you a really good overview of what the Quartz framework is and how you would use it. So please take a look at the video since not only will you get a really good sense of what Quartz for ASP.NET is but I'm sure a lot of your questions will be answered as well. 
<p>&nbsp;</p><script type="text/javascript">
     var id= "89ffddc9e66c496b8d4cfc3343f1cf5b";
     var size="lr";
     var showTitle="false";
     var titlePosition = "above";
     var showDescription="false";
     var viewOnXR = "true";
     var width = 640;
     
     document.write(unescape("%3Cscript src=\"http://exposureroom.com/XRVideoPlayerEmbed.aspx?id=" + id + "&amp;size=" + size + "&amp;width=" + width + "&amp;viewOnXR=" + viewOnXR + "&amp;title=" + showTitle + "&amp;titlePosition=" + titlePosition + "&amp;description=" + showDescription + "&amp;urlLocation=") + encodeURIComponent(window.location.href) + unescape('\" type=\"text/javascript\"%3E%3C/script%3E')); document.close();
   </script>
<p>&nbsp;</p>
<h2>Quartz for ASP.NET - Data Binding</h2>This is a short video that shows you how data binding works. We use the <code>Repeater</code> in this demo as well so you'll also get to see how the <code>Repeater</code> can be used along with templates. <script type="text/javascript">
     var id= "1bc6b78507f34a008a921468947757e2";
     var size="lr";
     var showTitle="false";
     var titlePosition = "above";
     var showDescription="false";
     var viewOnXR = "true";
     var width = 640;
     
     document.write(unescape("%3Cscript src=\"http://exposureroom.com/XRVideoPlayerEmbed.aspx?id=" + id + "&amp;size=" + size + "&amp;width=" + width + "&amp;viewOnXR=" + viewOnXR + "&amp;title=" + showTitle + "&amp;titlePosition=" + titlePosition + "&amp;description=" + showDescription + "&amp;urlLocation=") + encodeURIComponent(window.location.href) + unescape('\" type=\"text/javascript\"%3E%3C/script%3E')); document.close();
   </script>
<p>&nbsp;</p>
<p><a name="downloads"></a>
<h2>Downloads</h2>The downloadable .zip files contains the following files 
<ol>
<li>The Complete source code (.Net 4.0 compatible only at the moment) 
<li>A Sample Project 
<li>A New Quartz Project Item - for VS 2010 
<li>A New Quartz Builder Item - for VS 2010 
<li>A New Quartz View Item - for VS 2010 </li></ol><a href="http://www.matlus.com/content/uploads/Quartz/Matlus.Quartz.zip">Quartz For ASP.NET Source</a> 
<h2>Installing Project and Item Templates in VS.NET</h2>
<p>If you've not installed project and item templates in Visual Studio before, please follow these steps:</p>
<p>Extract the files from the downloaded zip file to a temporary folder.</p>
<p>First we'll installed the <strong>Project Item Template</strong>.</p>
<ol>
<li>Locate the file called – <code>Quartz Web Application.zip</code> 
<li>Navigate to the Visual Studio Project Templates (C#) folder. On my machine this folder is located at: 
<li><pre>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplates\CSharp\</pre>
<li>Create a folder called <code>Quartz</code> under the <code>CSharp</code> folder as shown in <a href="#figure4">Figure 4</a> below 
<li>Copy the <code>Quartz Web Application.zip</code> into this folder 
<li>Follow the steps listed in the <a href="#rebuildingvscache">Rebuilding the Visual Studio Cache</a> section below in order to rebuild the VS.NET cache. 
<li>Start Visual Studio (rebuild the cache first!) and create a new project. 
<li>You'll notice a <code>Quartz</code> folder in <code>Installed Templates</code> ree view on the left (as seen in <a href="#figure5">Figure 5</a> below) and when you select it, you'll see the Quartz Web Application project item template and shown in Figure 5 below</li></ol>
<p>&nbsp;</p><a name="figure4"></a>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CreatingTheQuartzProjectItemFolder" border="0" alt="CreatingTheQuartzProjectItemFolder" src="http://www.matlus.com/content/uploads/2011/01/CreatingTheQuartzProjectItemFolder_1940c44b-7133-4db9-90ca-288e50e2e1f6.jpg" width="615" height="455"></p>
<h3>Figure 4: Creating the Quartz Project Template folder </h3>
<p>&nbsp;</p><a name="figure5"></a>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="QuartzNewProjectDialog" border="0" alt="QuartzNewProjectDialog" src="http://www.matlus.com/content/uploads/2011/01/QuartzNewProjectDialog_1041fdb7-162a-4b89-aa0a-c36ee4830e87.jpg" width="620" height="381"></p>
<h3>Figure 5: Quartz Web Application Project Item</h3>
<p>&nbsp;</p>
<p>The steps involved in installing the Item Templates in Visual Studio are similar to the steps we followed earlier for installing the Project Item Template. This time you need to create a folder under a different hive.</p>
<ol>
<li>You'll need to create a folder under the <code>ItemTemplates\CSharp</code> folder, which on my machine is: 
<li><pre>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp</pre>
<li>Like before, create a folder called <code>Quartz</code> under this folder as shown in <a href="#figure6">Figure 6</a> below. 
<li>Copy the <code>QuartzBuilder.zip</code> and <code>QuartzView.zip</code> files into this new folder 
<li>Rebuild the Visual Studio cache again using the steps listed in the <a href="#rebuildingvscache">Rebuilding the Visual Studio Cache</a> section below. 
<li>After you've done that, you'll see item templates for a Quartz Builder and Quartz View when you add an item to your Quartz Web Application project, as shown in <a href="#figure7">Figure 7</a> below </li></ol><a name="figure6"></a>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="CreatingTheQuartzItemTemplateFolder" border="0" alt="CreatingTheQuartzItemTemplateFolder" src="http://www.matlus.com/content/uploads/2011/01/CreatingTheQuartzItemTemplateFolder_2de25e85-d46c-4adc-b68b-5d9358ba94a8.jpg" width="615" height="453"></p>
<h3>Figure 6: Showing the Quartz folder under the ItemTemplates\CSharp folder</h3>
<p>&nbsp;</p><a name="figure7"></a>
<p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="QuartzAddNewItemShowingBuilderAndView" border="0" alt="QuartzAddNewItemShowingBuilderAndView" src="http://www.matlus.com/content/uploads/2011/01/QuartzAddNewItemShowingBuilderAndView_e91d1d44-9cee-4458-b51f-8db7123c347b.jpg" width="640" height="360"></p>
<h3>Figure 7: Showing the Quartz Builder and View items in the Add new Item dialog</h3><a name="rebuildingvscache"></a>
<h2>Rebuilding the Visual Studio Cache</h2>
<p>Once installed the item templates into VS.NET, you'll need to get Visual Studio to rebuild its cache. You do that by doing the following:</p>
<ol>
<li>Close all instances of Visual Studio 
<li>Open a <code>Visual Studio Command Prompt</code> (i.e. Start | All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools | Visual Studio Command Prompt) 
<li>Execute the following command: <code>devenv /installvstemplates</code></li></ol>]]></description><category>Programming/ASP.NET</category><category>MVC</category><category>Performance</category><category>Quartz for ASP.NET</category></item><item><title>ChangeType&lt;T&gt; - Changing the type of a variable in C#</title><pubDate>Mon, 08 Nov 2010 19:38:00 GMT</pubDate><link>http://www.matlus.com/changetypet-changing-the-type-of-a-variable-in-c/</link><guid isPermaLink="true">http://www.matlus.com/changetypet-changing-the-type-of-a-variable-in-c/</guid><description><![CDATA[Working on Web applications invariably means you need to change the data received (which is generally in the form of a string) into some other data type such as <code>Int32</code> or <code>Double</code> etc. In the .NET framework there are a few ways in which you can accomplish this (sort of):  <ul> <li>Using the <code><a href="http://msdn.microsoft.com/en-us/library/system.convert(v=VS.100).aspx" target="_blank">Convert</a></code> static class  <li>Using the <code><a href="http://msdn.microsoft.com/en-us/library/dtb69x08.aspx" target="_blank">Convert.ChangeType</a></code> method if your types implement the<code><a href="http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx" target="_blank">IConvertible</a></code> interface  <li>Using the <code><a href="http://msdn.microsoft.com/en-us/library/ms171819.aspx" target="_blank">Type Descriptor</a></code> Architecture that's part of the .NET framework (typically used by visual controls at design time) </li></ul> <h2>Converting from String to ValueTypes</h2>Typically, converting from a string to <code>ValueTypes</code> is fairly simple since you can either use the <code>Convert.ToXXX</code> or use the <code>XXX.Parse()</code> methods. In fact on the face of it this doesn't seem like a problem that needs a solution since the solutions already exist. However, when you're building an application, you don't want keep repeating your code, and as it applies Web applications, this is a need you have in every page of your website. That is, there are some Form fields or QueryStrings that you're interested in that need to be converted from a string to another data type. And because there is no real framework in place that can handle this very common scenario you end up writing the same code over and over.  <h2>A Solution to the ChangeType problem</h2>Let me start with stating the problem clearly. You've got data coming to you in the form of a string, typically in the form of a <code>NameValueCollection</code>, since the <code>Request</code> object provides the <code>Form</code> fields and <code>QueryString</code> in the form of NameValueCollections. You want to extract the values from these collections to assign them to variables or properties you've defined in your class. This data is typically user input data so you need to accommodate the various styles in which a user may input data. So let's look at a specific case. We have a variable or property of type <code>Int32</code> called <code>Price</code>. The user may input this data in the form in one of the following ways:  <ol> <li>4236  <li>$4236  <li>4,236  <li>$4,236 </li></ol>Or leave the field blank. Another common scenario is a form field that accepts tag that are comma separated, such as: <code>C#,ASP.NET,Http</code> and you need to convert these values to a string[] in your code. Ideally, you'd want one method in a class within your framework that can do all this for you. Let's call this method <code>ChangeType</code>, since this method needs to return different kinds of types it could either return an <code>Object</code> type or we could have a generic method in the form <pre>public T ChangeType&lt;T&gt;(string parameterName, T defaultValue = default(T))
</pre>You'll quickly realize that implementing this method is really not that simple. The reason is that you can't convert the return type of this method to be a specific type even though you know the type parameter is that type. In other words the code below won't compile with the error, "Cannot convert type int to 'T'" or "Cannot implicitly convert type int to 'T'". <pre class="csharpcode"><span class="kwrd">public</span> T ChangeType&lt;T&gt;(<span class="kwrd">string</span> parameterName, T defaultValue = <span class="kwrd">default</span>(T))
{
  Type typeOft = <span class="kwrd">typeof</span>(T);
  var <span class="kwrd">value</span> = Request.Form[parameterName];

  <span class="kwrd">if</span> (typeOft == <span class="kwrd">typeof</span>(Int32))
    <span class="kwrd">return</span> (T)Int32.Parse(<span class="kwrd">value</span>);
  <span class="kwrd">else</span> <span class="kwrd">if</span> (typeOft == <span class="kwrd">typeof</span>(Int64))
    <span class="kwrd">return</span> (T)Int64.Parse(<span class="kwrd">value</span>);
}</pre>
<h3>A Simple Solution</h3>A simple (non extensible) solution would be to have this method call out to other methods that return an <code>Object</code> type and you can then cast it to <code>T</code> in this method and return it. Like so. <pre class="csharpcode"><span class="kwrd">public</span> T ChangeType&lt;T&gt;(<span class="kwrd">string</span> parameterName, T defaultValue = <span class="kwrd">default</span>(T))
{
  Type typeOft = <span class="kwrd">typeof</span>(T);
  var <span class="kwrd">value</span> = Request.Form[parameterName];

  <span class="kwrd">if</span> (String.IsNullOrEmpty(<span class="kwrd">value</span>.Trim()))
    <span class="kwrd">return</span> <span class="kwrd">default</span>(T);
  <span class="kwrd">if</span> (typeOft == <span class="kwrd">typeof</span>(Int32))
    <span class="kwrd">return</span> (T)ConvertToInt32(<span class="kwrd">value</span>);
  <span class="kwrd">else</span> <span class="kwrd">if</span> (typeOft == <span class="kwrd">typeof</span>(Int64))
    <span class="kwrd">return</span> (T)ConvertToInt64(<span class="kwrd">value</span>);
  <span class="kwrd">else</span> <span class="kwrd">if</span> (typeOft == <span class="kwrd">typeof</span>(Double))
    <span class="kwrd">return</span> (T)ConvertToDouble(<span class="kwrd">value</span>);
  <span class="kwrd">else</span> <span class="kwrd">if</span> (typeOft == <span class="kwrd">typeof</span>(Decimal))
    <span class="kwrd">return</span> (T)ConvertToDecimal(<span class="kwrd">value</span>);
  <span class="kwrd">return</span> <span class="kwrd">default</span>(T);
}
</pre>And the implementations of the secondary methods might look like this: <pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">object</span> ConvertToInt32(<span class="kwrd">string</span> <span class="kwrd">value</span>)
{
  <span class="kwrd">return</span> Int32.Parse(<span class="kwrd">value</span>,
    NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint);
}

<span class="kwrd">private</span> <span class="kwrd">object</span> ConvertToInt64(<span class="kwrd">string</span> <span class="kwrd">value</span>)
{
  <span class="kwrd">return</span> Int64.Parse(<span class="kwrd">value</span>,
    NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint);
}

<span class="kwrd">private</span> <span class="kwrd">object</span> ConvertToDouble(<span class="kwrd">string</span> <span class="kwrd">value</span>)
{
  <span class="kwrd">return</span> Double.Parse(<span class="kwrd">value</span>, NumberStyles.Currency);
}

<span class="kwrd">private</span> <span class="kwrd">object</span> ConvertToDecimal(<span class="kwrd">string</span> <span class="kwrd">value</span>)
{
  <span class="kwrd">return</span> Decimal.Parse(<span class="kwrd">value</span>, NumberStyles.Currency);
}</pre>
<h2>An Extensible solution for ChangeType&lt;T&gt;</h2>The solution I present is an extensible solution, in that you can add your own binders for types (custom types) that you'd like to handle. The way you'd use the solution is really simple. In your page class for example, you'd call this method like so: <pre>int amount = ChangeType&lt;int&gt;("Amount");
</pre>If you wanted to specify a default value (other than zero in this case) in case that field was not entered by the user then you could do this: <pre>int amount = ChangeType&lt;int&gt;("Amount", -1);
</pre>In the case of the tags field that needs to be converted to a string[] <pre>string[] tags = ChangeType&lt;string[]&gt;("tags");
</pre>There are 3 parts to this solution. 
<ol>
<li>And Interface called <code>IRequestBinder</code>. Your custom binders will implement this interface (just one method) 
<li>The <code>RequestBinder</code> class that maintains a list of registered binders and issues the appropriate binder 
<li>A Generic method <code>ChangeType&lt;T&gt;</code> that does all the hard work of abstracting all of this and allows you to write code like that shown above.</code> </li></ol>So first, lets take a look at the <code>IRequestBinder</code> interface <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IRequestBinder
{
  <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType,
    <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>);
}
</pre>The <code>RequestBinder</code> is the class you register your binders with by using the <code>Add</code> method. If you have binders that you want your system to handle out of the box, then you can register those binders in the static constructor of this class as you can see the the code listing below. Because the class is a static class you can register a binder from anywhere in your system as well. As a result, you don't have to modify the class in order to register new binders. Simply call the <code>Add</code> static method of the class from anywhere in your application. The <code>RequestBinder</code> class handles all of the registration as well as instantiation of your binder classes for you. Furthermore, once it has created an instance of your binder class, if maintains that instance in a dictionary so it doesn't have to keep creating instances each time you need a binder for the same type again. <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> RequestBinder
{
  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Dictionary&lt;<span class="kwrd">string</span>, RuntimeTypeHandle&gt;
    registeredBinders = <span class="kwrd">new</span> Dictionary&lt;<span class="kwrd">string</span>, RuntimeTypeHandle&gt;();
  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Dictionary&lt;<span class="kwrd">string</span>, IRequestBinder&gt;
    instantiatedBinders = <span class="kwrd">new</span> Dictionary&lt;<span class="kwrd">string</span>, IRequestBinder&gt;();

  <span class="kwrd">static</span> RequestBinder()
  {
    Add(<span class="kwrd">typeof</span>(String), <span class="kwrd">typeof</span>(StringRequestBinder));
    Add(<span class="kwrd">typeof</span>(Int32), <span class="kwrd">typeof</span>(Int32RequestBinder));
    Add(<span class="kwrd">typeof</span>(Int64), <span class="kwrd">typeof</span>(Int64RequestBinder));
    Add(<span class="kwrd">typeof</span>(Double), <span class="kwrd">typeof</span>(DoubleRequestBinder));
    Add(<span class="kwrd">typeof</span>(DateTime), <span class="kwrd">typeof</span>(DateTimeRequestBinder));
    Add(<span class="kwrd">typeof</span>(Boolean), <span class="kwrd">typeof</span>(BooleanRequestBinder));
    Add(<span class="kwrd">typeof</span>(Decimal), <span class="kwrd">typeof</span>(DecimalRequestBinder));
    Add(<span class="kwrd">typeof</span>(Int32[]), <span class="kwrd">typeof</span>(Int32ArrayRequestBinder));
    Add(<span class="kwrd">typeof</span>(String[]), <span class="kwrd">typeof</span>(StringArrayRequestBinder));
    Add(<span class="kwrd">typeof</span>(Double[]), <span class="kwrd">typeof</span>(DoubleArrayRequestBinder));
    Add(<span class="kwrd">typeof</span>(Enum), <span class="kwrd">typeof</span>(EnumRequestBinder));
  }

  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Add(Type binderForType, Type requestBinderType)
  {
    Type interfaceType = requestBinderType.GetInterface(<span class="str">"IRequestBinder"</span>);
    <span class="kwrd">if</span> (interfaceType != <span class="kwrd">null</span>)
    {
      var fullName = binderForType.FullName;
      <span class="kwrd">if</span> (registeredBinders.ContainsKey(fullName))
        registeredBinders.Remove(fullName);
      registeredBinders.Add(fullName, requestBinderType.TypeHandle);
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> Contains(Type type)
  {
    <span class="kwrd">return</span> registeredBinders.ContainsKey(type.FullName);
  }

  <span class="kwrd">public</span> <span class="kwrd">static</span> IRequestBinder GetBinder(Type type)
  {
    var fullName = type.FullName;
    <span class="kwrd">if</span> (!registeredBinders.ContainsKey(fullName))
      <span class="kwrd">throw</span> <span class="kwrd">new</span> RequestBinderException(
        <span class="str">"No RequestBinder found for Type: "</span> + fullName);
    <span class="kwrd">if</span> (instantiatedBinders.ContainsKey(fullName))
      <span class="kwrd">return</span> instantiatedBinders[fullName];
    <span class="kwrd">else</span>
    {
      var typeHandle = registeredBinders[fullName];
      IRequestBinder binder = 
        (IRequestBinder)Activator.CreateInstance(
        Type.GetTypeFromHandle(typeHandle));
      instantiatedBinders.Add(fullName, binder);
      <span class="kwrd">return</span> binder;
    }
  }
}</pre>In order to retrieve a registered binder, you'll use the <code>GetBinder</code> method passng in the <code>Type</code> for which you need a binder. So for example if you need the binder for an <code>Int32</code> type you'll make the following call. <pre>var binder = RequestBinder.GetBinder(typeof(Int32));
Int32 value = (Int32)binder.Bind(HttpContext, type, parameterName, defaultValue);
</pre>In order to make all of this a lot easier to use we can have our ChangeType&lt;T&gt; method do all the work like so. <pre class="csharpcode"><span class="kwrd">protected</span> T ChangeType&lt;T&gt;(<span class="kwrd">string</span> parameterName,
  T defaultValue = <span class="kwrd">default</span>(T))
{
  Type type = <span class="kwrd">typeof</span>(T);
  <span class="kwrd">if</span> (RequestBinder.Contains(type))
    <span class="kwrd">return</span> (T)RequestBinder
      .GetBinder(type)
      .Bind(HttpContext, type, parameterName, defaultValue);
  <span class="kwrd">else</span> <span class="kwrd">if</span> (type.IsEnum)
    <span class="kwrd">return</span> (T)RequestBinder
      .GetBinder(<span class="kwrd">typeof</span>(Enum))
      .Bind(HttpContext, type, parameterName, defaultValue);
  <span class="kwrd">else</span>
    <span class="kwrd">return</span> defaultValue;        
}</pre>
<h2>Handling Custom Types</h2>What if you wanted the <code>RequestBinder</code> to be able to handle your custom types? Well, it's a simple matter of registering a binder for your custom type. However the ChangeType&lt;T&gt; method probably needs an overload since you don't need to send it the name of a parameter since typically, the custom object binds to multiple fields in your form. So the overloaded method would look like this: <pre class="csharpcode"><span class="kwrd">protected</span> T ChangeType&lt;T&gt;() <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
  Type type = <span class="kwrd">typeof</span>(T);
  <span class="kwrd">if</span> (RequestBinder.Contains(type))
    <span class="kwrd">return</span> (T)RequestBinder.GetBinder(type).Bind(HttpContext, type);
  <span class="kwrd">else</span>
    <span class="kwrd">return</span> <span class="kwrd">default</span>(T);
}</pre>
<h2>the Complete Solution</h2>The code listing below is a listing on the <code>RequetBinder</code> class along with various custom binders that handle the default scenarios for the most part. There is a base class called <code>RequestBinderBase</code> that has some common functionality the other binders use. But you don't need to have your binders descend from this base class unless you need that functionality. 
<div class="panel code content/images/csharp.png" title="RequestBinder and others"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Collections.Specialized;
<span class="kwrd">using</span> System.Globalization;
<span class="kwrd">using</span> System.Web;
<span class="kwrd">using</span> Matlus.Web.Builder.Exceptions;

<span class="kwrd">namespace</span> Matlus.Web.Builder
{
  <span class="kwrd">public</span> <span class="kwrd">interface</span> IRequestBinder
  {
    <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType,
      <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>);
  }

  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> RequestBinder
  {
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Dictionary&lt;<span class="kwrd">string</span>, RuntimeTypeHandle&gt;
      registeredBinders = <span class="kwrd">new</span> Dictionary&lt;<span class="kwrd">string</span>, RuntimeTypeHandle&gt;();
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Dictionary&lt;<span class="kwrd">string</span>, IRequestBinder&gt;
      instantiatedBinders = <span class="kwrd">new</span> Dictionary&lt;<span class="kwrd">string</span>, IRequestBinder&gt;();

    <span class="kwrd">static</span> RequestBinder()
    {
      Add(<span class="kwrd">typeof</span>(String), <span class="kwrd">typeof</span>(StringRequestBinder));
      Add(<span class="kwrd">typeof</span>(Int32), <span class="kwrd">typeof</span>(Int32RequestBinder));
      Add(<span class="kwrd">typeof</span>(Int64), <span class="kwrd">typeof</span>(Int64RequestBinder));
      Add(<span class="kwrd">typeof</span>(Double), <span class="kwrd">typeof</span>(DoubleRequestBinder));
      Add(<span class="kwrd">typeof</span>(DateTime), <span class="kwrd">typeof</span>(DateTimeRequestBinder));
      Add(<span class="kwrd">typeof</span>(Boolean), <span class="kwrd">typeof</span>(BooleanRequestBinder));
      Add(<span class="kwrd">typeof</span>(Decimal), <span class="kwrd">typeof</span>(DecimalRequestBinder));
      Add(<span class="kwrd">typeof</span>(Int32[]), <span class="kwrd">typeof</span>(Int32ArrayRequestBinder));
      Add(<span class="kwrd">typeof</span>(String[]), <span class="kwrd">typeof</span>(StringArrayRequestBinder));
      Add(<span class="kwrd">typeof</span>(Double[]), <span class="kwrd">typeof</span>(DoubleArrayRequestBinder));
      Add(<span class="kwrd">typeof</span>(Enum), <span class="kwrd">typeof</span>(EnumRequestBinder));
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Add(Type binderForType, Type requestBinderType)
    {
      Type interfaceType = requestBinderType.GetInterface(<span class="str">"IRequestBinder"</span>);
      <span class="kwrd">if</span> (interfaceType != <span class="kwrd">null</span>)
      {
        var fullName = binderForType.FullName;
        <span class="kwrd">if</span> (registeredBinders.ContainsKey(fullName))
          registeredBinders.Remove(fullName);
        registeredBinders.Add(fullName, requestBinderType.TypeHandle);
      }
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> Contains(Type type)
    {
      <span class="kwrd">return</span> registeredBinders.ContainsKey(type.FullName);
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> IRequestBinder GetBinder(Type type)
    {
      var fullName = type.FullName;
      <span class="kwrd">if</span> (!registeredBinders.ContainsKey(fullName))
        <span class="kwrd">throw</span> <span class="kwrd">new</span> RequestBinderException(
          <span class="str">"No RequestBinder found for Type: "</span> + fullName);
      <span class="kwrd">if</span> (instantiatedBinders.ContainsKey(fullName))
        <span class="kwrd">return</span> instantiatedBinders[fullName];
      <span class="kwrd">else</span>
      {
        var typeHandle = registeredBinders[fullName];
        IRequestBinder binder =
          (IRequestBinder)Activator.CreateInstance(
          Type.GetTypeFromHandle(typeHandle));
        instantiatedBinders.Add(fullName, binder);
        <span class="kwrd">return</span> binder;
      }
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> RequestBinderBase : IRequestBinder
  {
    <span class="kwrd">protected</span> <span class="kwrd">static</span> NameValueCollection GetRequestNameValueCollection(HttpContextBase httpContext)
    {
      var combinedNameValueCollection = <span class="kwrd">new</span> NameValueCollection();
      <span class="kwrd">foreach</span> (<span class="kwrd">string</span> key <span class="kwrd">in</span> httpContext.Request.Form.Keys)
      {
        var <span class="kwrd">value</span> = httpContext.Request.Form[key];
        <span class="kwrd">if</span> (<span class="kwrd">value</span> != <span class="kwrd">null</span>)
          combinedNameValueCollection.Add(key, <span class="kwrd">value</span>);
      }

      <span class="kwrd">foreach</span> (<span class="kwrd">string</span> key <span class="kwrd">in</span> httpContext.Request.QueryString.Keys)
      {
        var <span class="kwrd">value</span> = httpContext.Request.QueryString[key];
        <span class="kwrd">if</span> (<span class="kwrd">value</span> != <span class="kwrd">null</span>)
          combinedNameValueCollection.Add(key, <span class="kwrd">value</span>);
      }
      <span class="kwrd">return</span> combinedNameValueCollection;
    }

    <span class="preproc">#region</span> IRequestBinder Members

    <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>);

    <span class="preproc">#endregion</span>
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> Int32RequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">return</span> Int32.Parse(<span class="kwrd">value</span>, NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint);
      }
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> StringRequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
        <span class="kwrd">return</span> <span class="kwrd">value</span>;
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> Int64RequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">return</span> Int64.Parse(<span class="kwrd">value</span>, NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint);
      }
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> DoubleRequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">return</span> Double.Parse(<span class="kwrd">value</span>, NumberStyles.Currency);
      }
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> DateTimeRequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">return</span> DateTime.Parse(<span class="kwrd">value</span>);
      }
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> DecimalRequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">return</span> Decimal.Parse(<span class="kwrd">value</span>, NumberStyles.Currency);
      }
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> BooleanRequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">switch</span> (<span class="kwrd">value</span>.ToString().Trim())
        {
          <span class="kwrd">case</span> <span class="str">"False"</span>:
          <span class="kwrd">case</span> <span class="str">"false"</span>:
          <span class="kwrd">case</span> <span class="str">"0"</span>:
          <span class="kwrd">case</span> <span class="str">"off"</span>:
          <span class="kwrd">case</span> <span class="str">""</span>:
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
          <span class="kwrd">case</span> <span class="str">"True"</span>:
          <span class="kwrd">case</span> <span class="str">"true"</span>:
          <span class="kwrd">case</span> <span class="str">"1"</span>:
          <span class="kwrd">case</span> <span class="str">"on"</span>:
            <span class="kwrd">return</span> <span class="kwrd">true</span>;
          <span class="kwrd">default</span>:
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
        }
      }
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> StringArrayRequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">value</span> = <span class="kwrd">value</span>.Trim();
        <span class="kwrd">if</span> (<span class="kwrd">value</span>.Length == 0)
          <span class="kwrd">return</span> Activator.CreateInstance(convertToType, <span class="kwrd">new</span> <span class="kwrd">object</span>[] { 0 });
        <span class="kwrd">else</span>
        {
          var values = <span class="kwrd">value</span>.Split(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">','</span> }, StringSplitOptions.RemoveEmptyEntries);
          var strArray = <span class="kwrd">new</span> String[values.Length];
          <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; values.Length; i++)
            strArray[i] = values[i];
          <span class="kwrd">return</span> strArray;
        }
      }
      <span class="kwrd">return</span> defaultValue;
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> Int32ArrayRequestBinder : RequestBinderBase
  {
    <span class="preproc">#region</span> IRequestBinder Members

    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">value</span> = <span class="kwrd">value</span>.Trim();
        <span class="kwrd">if</span> (<span class="kwrd">value</span>.Length == 0)
          <span class="kwrd">return</span> Activator.CreateInstance(convertToType, <span class="kwrd">new</span> <span class="kwrd">object</span>[] { 0 });
        <span class="kwrd">else</span>
        {
          var values = <span class="kwrd">value</span>.Split(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">','</span> }, StringSplitOptions.RemoveEmptyEntries);
          var intArray = <span class="kwrd">new</span> Int32[values.Length];
          <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; values.Length; i++)
            intArray[i] = Int32.Parse(values[i]);
          <span class="kwrd">return</span> intArray;
        }
      }
      <span class="kwrd">return</span> defaultValue;
    }

    <span class="preproc">#endregion</span>
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> DoubleArrayRequestBinder : RequestBinderBase
  {
    <span class="preproc">#region</span> IRequestBinder Members

    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">value</span> = <span class="kwrd">value</span>.Trim();
        <span class="kwrd">if</span> (<span class="kwrd">value</span>.Length == 0)
          <span class="kwrd">return</span> Activator.CreateInstance(convertToType, <span class="kwrd">new</span> <span class="kwrd">object</span>[] { 0 });
        <span class="kwrd">else</span>
        {
          var values = <span class="kwrd">value</span>.Split(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">','</span> }, StringSplitOptions.RemoveEmptyEntries);
          var dblArray = <span class="kwrd">new</span> Double[values.Length];
          <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; values.Length; i++)
            dblArray[i] = Double.Parse(values[i]);
          <span class="kwrd">return</span> dblArray;
        }
      }
      <span class="kwrd">return</span> defaultValue;
    }

    <span class="preproc">#endregion</span>
  }

  <span class="kwrd">public</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> EnumRequestBinder : RequestBinderBase
  {
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">object</span> Bind(HttpContextBase httpContext, Type convertToType, <span class="kwrd">string</span> parameterName = <span class="kwrd">null</span>, <span class="kwrd">object</span> defaultValue = <span class="kwrd">null</span>)
    {
      var <span class="kwrd">value</span> = GetRequestNameValueCollection(httpContext)[parameterName];
      <span class="kwrd">if</span> (!String.IsNullOrEmpty(<span class="kwrd">value</span>))
      {
        <span class="kwrd">return</span> Enum.Parse(convertToType, <span class="kwrd">value</span>);
      }
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> defaultValue;
    }
  }

}</pre></div>
<h2>Handling Custom classes (DTOs)</h2>The class <code>DtoBinder</code> listed below can handle most DTO type classes, including properties that are arrays or <code>Int32</code> or <code>string</code>. 
<div class="panel code content/images/csharp.png" title="DtoBinder.cs"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Globalization;
<span class="kwrd">using</span> System.Reflection;
<span class="kwrd">using</span> System.Web;

<span class="kwrd">namespace</span> Matlus.Web.Builder
{
  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DtoBinder
  {
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> BindingFlags PROP_BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> BindingFlags PROP_SET_BINDING_FLAGS = BindingFlags.SetProperty | BindingFlags.SetField | BindingFlags.IgnoreCase;

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">object</span> GetPropertyValue(<span class="kwrd">object</span> dtoObject, <span class="kwrd">string</span> propertyName)
    {
      PropertyInfo propInfo = dtoObject.GetType().GetProperty(propertyName, PROP_BINDING_FLAGS);
      <span class="kwrd">if</span> (propInfo != <span class="kwrd">null</span>)
        <span class="kwrd">return</span> propInfo.GetValue(dtoObject, <span class="kwrd">null</span>);
      <span class="kwrd">else</span>
        <span class="kwrd">return</span> <span class="kwrd">null</span>;
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> Dictionary&lt;<span class="kwrd">string</span>, PropertyInfo&gt; GetPropertyInfos(<span class="kwrd">object</span> dtoObject)
    {
      var properties = <span class="kwrd">new</span> Dictionary&lt;<span class="kwrd">string</span>, PropertyInfo&gt;();
      <span class="kwrd">foreach</span> (var propInfo <span class="kwrd">in</span> dtoObject.GetType().GetProperties(PROP_BINDING_FLAGS))
        properties.Add(propInfo.Name, propInfo);
      <span class="kwrd">return</span> properties;
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> T CreateInstanceFromRequest&lt;T&gt;(HttpRequestBase request) <span class="kwrd">where</span> T : <span class="kwrd">new</span>()
    {      
      Type t = <span class="kwrd">typeof</span>(T);
      var propertyInfos = t.GetProperties(PROP_BINDING_FLAGS);
      var instance = <span class="kwrd">new</span> T();
      
      <span class="kwrd">foreach</span> (var propInfo <span class="kwrd">in</span> propertyInfos)
      {
        var <span class="kwrd">value</span> = request.Form[propInfo.Name];
        <span class="kwrd">if</span> (<span class="kwrd">value</span> == <span class="kwrd">null</span>)
          <span class="kwrd">value</span> = request.QueryString[propInfo.Name];
        <span class="kwrd">if</span> (<span class="kwrd">value</span> != <span class="kwrd">null</span>)
          SetPropertyValue(instance, propInfo, <span class="kwrd">value</span>);
      }
      <span class="kwrd">return</span> instance;
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> SetPropertyValue(<span class="kwrd">object</span> dtoObject, <span class="kwrd">string</span> propertyName, <span class="kwrd">object</span> propertyValue)
    {
      var propInfo = dtoObject.GetType().GetProperty(propertyName, PROP_BINDING_FLAGS);
      SetPropertyValue(dtoObject, propInfo, propertyValue);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> CleanUpPropertyValue&lt;TResult&gt;(<span class="kwrd">ref</span> <span class="kwrd">object</span> propertyValue) <span class="kwrd">where</span> TResult : <span class="kwrd">struct</span>
    {
      var <span class="kwrd">value</span> = propertyValue <span class="kwrd">as</span> String;
      <span class="kwrd">if</span> (<span class="kwrd">value</span> != <span class="kwrd">null</span>)
      {
        var trimmed = <span class="kwrd">value</span>.Trim();
        <span class="kwrd">if</span> (trimmed.Length == 0)
          propertyValue = <span class="kwrd">default</span>(TResult);
        <span class="kwrd">else</span>
        {
          Type resultType = <span class="kwrd">typeof</span>(TResult);

          <span class="kwrd">if</span> (resultType == <span class="kwrd">typeof</span>(Int32))
            propertyValue = ConvertToInt32(trimmed);
          <span class="kwrd">else</span> <span class="kwrd">if</span> (resultType == <span class="kwrd">typeof</span>(Int64))
            propertyValue = ConvertToInt64(trimmed);
          <span class="kwrd">else</span> <span class="kwrd">if</span> (resultType == <span class="kwrd">typeof</span>(Double))
            propertyValue = ConvertToDouble(trimmed);
          <span class="kwrd">else</span> <span class="kwrd">if</span> (resultType == <span class="kwrd">typeof</span>(Decimal))
            propertyValue = ConvertToDecimal(trimmed);
          <span class="kwrd">else</span>
            propertyValue = trimmed;
        }
      }
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> SetPropertyValue(<span class="kwrd">object</span> dtoObject, PropertyInfo propInfo, <span class="kwrd">object</span> propertyValue)
    {
      Type propType = propInfo.PropertyType;
      var typeCode = Type.GetTypeCode(propertyValue.GetType());

      <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(String))
        propInfo.SetValue(dtoObject, propertyValue, PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Int32))
      {
        CleanUpPropertyValue&lt;Int32&gt;(<span class="kwrd">ref</span> propertyValue);        
        propInfo.SetValue(dtoObject, propertyValue, PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      }
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Int64))
      {
        CleanUpPropertyValue&lt;Int64&gt;(<span class="kwrd">ref</span> propertyValue);
        propInfo.SetValue(dtoObject, propertyValue, PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      }
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Boolean))
        propInfo.SetValue(dtoObject, ConvertToBool(propertyValue), PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(DateTime))
      {
        CleanUpPropertyValue&lt;DateTime&gt;(<span class="kwrd">ref</span> propertyValue);
        propInfo.SetValue(dtoObject, Convert.ToDateTime(propertyValue), PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      }
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Double))
      {
        CleanUpPropertyValue&lt;Double&gt;(<span class="kwrd">ref</span> propertyValue);
        propInfo.SetValue(dtoObject, propertyValue, PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      }
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Decimal))
      {
        CleanUpPropertyValue&lt;Decimal&gt;(<span class="kwrd">ref</span> propertyValue);
        propInfo.SetValue(dtoObject, Convert.ToDecimal(propertyValue), PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      }
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType.IsEnum)
        propInfo.SetValue(dtoObject, Enum.Parse(propType, Convert.ToString(propertyValue), <span class="kwrd">true</span>), PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Array))
        propInfo.SetValue(dtoObject, propertyValue, PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(String[]))
      {
        <span class="kwrd">if</span> (propertyValue <span class="kwrd">is</span> String)
        {
          var propertyValueAsString = propertyValue.ToString().Trim();
          <span class="kwrd">if</span> (propertyValueAsString.Length == 0)
            propertyValue = <span class="kwrd">new</span> <span class="kwrd">string</span>[0];
          <span class="kwrd">else</span>
            propertyValue = propertyValueAsString.Split(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">','</span> }, StringSplitOptions.RemoveEmptyEntries);
        }
        propInfo.SetValue(dtoObject, propertyValue, PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      }
      <span class="kwrd">else</span> <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Int32[]) || propType == <span class="kwrd">typeof</span>(Int64[]))
      {
        <span class="kwrd">if</span> (propertyValue <span class="kwrd">is</span> String)
        {
          var propertyValueAsString = propertyValue.ToString().Trim();
          <span class="kwrd">if</span> (propertyValueAsString.Length == 0)
            propertyValue = Activator.CreateInstance(propType, <span class="kwrd">new</span> <span class="kwrd">object</span>[] { 0 });
          <span class="kwrd">else</span>
          {
            var values = propertyValueAsString.Split(<span class="kwrd">new</span> <span class="kwrd">char</span>[] { <span class="str">','</span> }, StringSplitOptions.RemoveEmptyEntries);
            <span class="kwrd">if</span> (propType == <span class="kwrd">typeof</span>(Int32[]))
            {
              var intArray = <span class="kwrd">new</span> Int32[values.Length];
              <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; values.Length; i++)
                intArray[i] = Int32.Parse(values[i]);
              propertyValue = intArray;
            }
            <span class="kwrd">else</span>
            {
              var intArray = <span class="kwrd">new</span> Int64[values.Length];
              <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; values.Length; i++)
                intArray[i] = Int64.Parse(values[i]);
              propertyValue = intArray;
            }
          }
        }
        propInfo.SetValue(dtoObject, propertyValue, PROP_SET_BINDING_FLAGS, <span class="kwrd">null</span>, <span class="kwrd">null</span>, CultureInfo.CurrentCulture);
      }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> Int32 ConvertToInt32(<span class="kwrd">string</span> <span class="kwrd">value</span>)
    {
      <span class="kwrd">return</span> Int32.Parse(<span class="kwrd">value</span>, NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> Int64 ConvertToInt64(<span class="kwrd">string</span> <span class="kwrd">value</span>)
    {
      <span class="kwrd">return</span> Int64.Parse(<span class="kwrd">value</span>, NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> Double ConvertToDouble(<span class="kwrd">string</span> <span class="kwrd">value</span>)
    {
      <span class="kwrd">return</span> Double.Parse(<span class="kwrd">value</span>, NumberStyles.Currency);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> Decimal ConvertToDecimal(<span class="kwrd">string</span> <span class="kwrd">value</span>)
    {
      <span class="kwrd">return</span> Decimal.Parse(<span class="kwrd">value</span>, NumberStyles.Currency);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> ConvertToBool(<span class="kwrd">object</span> objBool)
    {
      <span class="kwrd">switch</span> (objBool.ToString().Trim())
      {
        <span class="kwrd">case</span> <span class="str">"False"</span>:
        <span class="kwrd">case</span> <span class="str">"false"</span>:
        <span class="kwrd">case</span> <span class="str">"0"</span>:
        <span class="kwrd">case</span> <span class="str">"off"</span>:
        <span class="kwrd">case</span> <span class="str">""</span>:
          <span class="kwrd">return</span> <span class="kwrd">false</span>;
        <span class="kwrd">case</span> <span class="str">"True"</span>:
        <span class="kwrd">case</span> <span class="str">"true"</span>:
        <span class="kwrd">case</span> <span class="str">"1"</span>:
        <span class="kwrd">case</span> <span class="str">"on"</span>:
          <span class="kwrd">return</span> <span class="kwrd">true</span>;
        <span class="kwrd">default</span>:
          <span class="kwrd">return</span> <span class="kwrd">false</span>;
      }
    }
  }
}</pre></div>Then in order to invoke the DtoBinder from the <code>ChangeType&lt;T&gt;</code> method, you'll need to make a small modification to its implementation. The complete implementations are shown below: 
<div class="panel code content/images/csharp.png" title="ChangeType&lt;T&gt; methods"><pre class="csharpcode"><span class="kwrd">protected</span> T ChangeType&lt;T&gt;() <span class="kwrd">where</span> T : <span class="kwrd">class</span>, <span class="kwrd">new</span>()
{
  Type type = <span class="kwrd">typeof</span>(T);
  <span class="kwrd">if</span> (RequestBinder.Contains(type))
    <span class="kwrd">return</span> (T)RequestBinder.GetBinder(type).Bind(HttpContext, type);
  <span class="kwrd">else</span> <span class="kwrd">if</span> (!type.IsValueType)
    <span class="kwrd">return</span> DtoBinder.CreateInstanceFromRequest&lt;T&gt;(Request);
  <span class="kwrd">else</span>
    <span class="kwrd">return</span> <span class="kwrd">default</span>(T);
}

<span class="kwrd">protected</span> T ChangeType&lt;T&gt;(<span class="kwrd">string</span> parameterName, T defaultValue = <span class="kwrd">default</span>(T))
{
  Type type = <span class="kwrd">typeof</span>(T);
  <span class="kwrd">if</span> (RequestBinder.Contains(type))
    <span class="kwrd">return</span> (T)RequestBinder.GetBinder(type).Bind(HttpContext, type, parameterName, defaultValue);
  <span class="kwrd">else</span> <span class="kwrd">if</span> (type.IsEnum)
    <span class="kwrd">return</span> (T)RequestBinder.GetBinder(<span class="kwrd">typeof</span>(Enum)).Bind(HttpContext, type, parameterName, defaultValue);
  <span class="kwrd">else</span>
    <span class="kwrd">return</span> defaultValue;        
}</pre></div>]]></description><category>Programming/C#</category><category>Change Type</category><category>TypeConverter</category></item><item><title>Razor Engine Host</title><pubDate>Fri, 05 Nov 2010 05:34:00 GMT</pubDate><link>http://www.matlus.com/razor-engine-host/</link><guid isPermaLink="true">http://www.matlus.com/razor-engine-host/</guid><description><![CDATA[<p>The new <a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx">Razor View Engine</a> that is part of <a href="http://www.asp.net/mvc/mvc3">ASP.NET MVC 3</a> can be hosted outside of any Web related stuff. In other words, the Razor Engine is not dependent on IIS and can be sued in a non-Web application such as a GUI or console app. This makes a whole lot of things possible, since you can use the Razor syntax in any kind of template and generate some text output. This output could be a mail-merged text document or a code file that in turn is compiled into your application. In this post, I'm simply going to provide you with a class that wraps the Razor Engine Host making it really simple for you to use in any kind of project, including a GUI project that is targeted to the Client profile of .Net 4.0. <b>Your project will need to reference the System.Web.Razor assembly that's part of (currently) ASP.NET MVC 3 Beta.</b>&nbsp;</p> <p>&nbsp;<img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="RazorEngineHostApp" border="0" alt="RazorEngineHostApp" src="http://www.matlus.com/content/uploads/2011/01/RazorEngineHostApp_f2491d0f-d745-4f2d-aa71-d6e1c22f1121.jpg" width="612" height="559"></p> <h2>Razor Engine Host Wrapper</h2><a href="#codeListing1">Code listing 1</a> below, is the listing of the entire class. It has just one public method called <code>ParseAndCompileTemplate</code> that returns a compiled assembly that contains the newly generated class. <a name="codeListing1"></a> <div class="panel code content/images/csharp.png" title="RazorEngineHostWrapper.cs"><pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.CodeDom.Compiler;
<span class="kwrd">using</span> System.IO;
<span class="kwrd">using</span> System.Reflection;
<span class="kwrd">using</span> System.Text;
<span class="kwrd">using</span> System.Web.Razor;
<span class="kwrd">using</span> Microsoft.CSharp;

<span class="kwrd">namespace</span> RazorHost
{
  <span class="rem">/// &lt;summary&gt;</span>
  <span class="rem">/// This class is a wrapper around the Razor Engine and Razor Engine Host</span>
  <span class="rem">/// &lt;/summary&gt;</span>
  <span class="kwrd">public</span> <span class="kwrd">class</span> RazorEngineHostWrapper
  {
    <span class="kwrd">private</span> RazorTemplateEngine InitializeRazorEngine(Type baseClassType, <span class="kwrd">string</span> namespaceOfGeneratedClass, <span class="kwrd">string</span> generatedClassName)
    {
      RazorEngineHost host = <span class="kwrd">new</span> RazorEngineHost(<span class="kwrd">new</span> CSharpRazorCodeLanguage());
      host.DefaultBaseClass = baseClassType.FullName;
      host.DefaultClassName = generatedClassName;
      host.DefaultNamespace = namespaceOfGeneratedClass;
      host.NamespaceImports.Add(<span class="str">"System"</span>);
      host.NamespaceImports.Add(<span class="str">"System.Collections.Generic"</span>);
      host.NamespaceImports.Add(<span class="str">"System.Linq"</span>);
      <span class="kwrd">return</span> <span class="kwrd">new</span> RazorTemplateEngine(host);
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// This method Parses and compiles the source code into an Assembly and returns it</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="baseClassType"&gt;The Type of the Base class the generated class descends from&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="namespaceOfGeneratedClass"&gt;The Namespace of the generated class&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="generatedClassName"&gt;The Class Name of the generated class&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="ReferencedAssemblies"&gt;Assembly refereces that may be required in order to compile the generated class&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="sourceCodeReader"&gt;A Text reader that is a warpper around the "Template" that is to be parsed and compiled&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;An instance of a generated assembly that contains the generated class&lt;/returns&gt;</span>
    <span class="kwrd">public</span> Assembly ParseAndCompileTemplate(Type baseClassType, <span class="kwrd">string</span> namespaceOfGeneratedClass, <span class="kwrd">string</span> generatedClassName, <span class="kwrd">string</span>[] ReferencedAssemblies, TextReader sourceCodeReader)
    {
      RazorTemplateEngine engine = InitializeRazorEngine(baseClassType, namespaceOfGeneratedClass, generatedClassName);
      GeneratorResults razorResults = engine.GenerateCode(sourceCodeReader);

      CSharpCodeProvider codeProvider = <span class="kwrd">new</span> CSharpCodeProvider();
      CodeGeneratorOptions options = <span class="kwrd">new</span> CodeGeneratorOptions();

      <span class="kwrd">string</span> generatedCode = <span class="kwrd">null</span>;
      <span class="kwrd">using</span> (StringWriter writer = <span class="kwrd">new</span> StringWriter())
      {
        codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
        generatedCode = writer.GetStringBuilder().ToString();
      }

      var outputAssemblyName = Path.GetTempPath() + Guid.NewGuid().ToString(<span class="str">"N"</span>) + <span class="str">".dll"</span>;
      CompilerParameters compilerParameters = <span class="kwrd">new</span> CompilerParameters(ReferencedAssemblies, outputAssemblyName);
      compilerParameters.ReferencedAssemblies.Add(<span class="str">"System.dll"</span>);
      compilerParameters.ReferencedAssemblies.Add(<span class="str">"System.Core.dll"</span>);
      compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));
      compilerParameters.GenerateInMemory = <span class="kwrd">false</span>;

      CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
      <span class="kwrd">if</span> (compilerResults.Errors.Count &gt; 0)
      {
        var compileErrors = <span class="kwrd">new</span> StringBuilder();
        <span class="kwrd">foreach</span> (System.CodeDom.Compiler.CompilerError compileError <span class="kwrd">in</span> compilerResults.Errors)
          compileErrors.Append(String.Format(<span class="str">"Line: {0}\t Col: {1}\t Error: {2}\r\n"</span>, compileError.Line, compileError.Column, compileError.ErrorText));

        <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(compileErrors.ToString() + generatedCode);
      }

      <span class="kwrd">return</span> compilerResults.CompiledAssembly;
    }
  }
}</pre></div>
<h3>Code Listing 1: RazorEngineHostWrapper.cs</h3>
<h2>Using the Razor Engine Wrapper</h2><a href="#codeListing2">Code Listing 2</a> shows you a sampling of how you would use the RazorEngineHost Wrapper. The class <code>TemplateBase</code> that you see referenced in <a href="#codeListing2">Code listing 2</a> is sort of specific to this project but you'll need a similar class in your own projects. The base class of the class that is generated using the Razor Engine must have the following two methods with functional implementations (as shown in <a href="#codeListing3">Code Listing 3</a>): 
<ul>
<li><code>public virtual void Write(object value)</code> 
<li><code>public virtual void WriteLiteral(object value)</code> </li></ul>This base class must also have a virtual (or abstract) method called <code>Execute()</code>. So your classes can descend from any class of your choosing so long it it meets the above requirements. The class that is generated then descends from that class. <a name="codeListing2"></a>
<div class="panel code content/images/csharp.png" title="Using the RazorEngineHostWrapper"><pre class="csharpcode">    <span class="kwrd">private</span> <span class="kwrd">void</span> button1_Click(<span class="kwrd">object</span> sender, EventArgs e)
    {
      TextReader sourceCodeReader = <span class="kwrd">new</span> StringReader(textBox1.Text);
      <span class="kwrd">string</span>[] referencesAssemblies = <span class="kwrd">new</span> String[]
      {
        <span class="str">@"System.dll"</span>,
        <span class="str">@"System.Core.dll"</span>
      };
      RazorEngineHostWrapper razorEngineHostWrapper = <span class="kwrd">new</span> RazorHost.RazorEngineHostWrapper();
      var generatedAssembly = razorEngineHostWrapper.ParseAndCompileTemplate(<span class="kwrd">typeof</span>(TemplateBase), <span class="str">"RazorHost"</span>, <span class="str">"MyTemplate"</span>, referencesAssemblies, sourceCodeReader);

      Type type = generatedAssembly.GetType(<span class="str">"RazorHost.MyTemplate"</span>);
      var instance = (TemplateBase)Activator.CreateInstance(type);
      <span class="kwrd">object</span> result = type.InvokeMember(<span class="str">"Execute"</span>, BindingFlags.InvokeMethod, <span class="kwrd">null</span>, instance, <span class="kwrd">null</span>);
      textBox2.Text = instance.Buffer.ToString();
    }
</pre></div><a name="codeListing3"></a>
<div class="panel code content/images/csharp.png" title="TemplateBase.cs"><pre class="csharpcode">  <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> TemplateBase
  {
    <span class="kwrd">public</span> StringBuilder Buffer { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">private</span> TextWriter writer;
    <span class="kwrd">private</span> TextWriter Writer { get { <span class="kwrd">return</span> writer; } }

    <span class="kwrd">public</span> List&lt;Customer&gt; Customers { get; set; }

    <span class="kwrd">public</span> TemplateBase()
    {
      Buffer = <span class="kwrd">new</span> StringBuilder();
      writer = <span class="kwrd">new</span> StringWriter(Buffer);
      Customers = <span class="kwrd">new</span> List&lt;Customer&gt;()
      {
        <span class="kwrd">new</span> Customer() { FirstName=<span class="str">"Bill"</span>, LastName=<span class="str">"Gates"</span> },
        <span class="kwrd">new</span> Customer() { FirstName=<span class="str">"Steve"</span>, LastName=<span class="str">"Jobs"</span> },
        <span class="kwrd">new</span> Customer() { FirstName=<span class="str">"Larry"</span>, LastName=<span class="str">" Ellison"</span> },
        <span class="kwrd">new</span> Customer() { FirstName=<span class="str">"Samuel"</span>, LastName=<span class="str">"Palmisano"</span> }
      };
    }

    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> Write(<span class="kwrd">object</span> <span class="kwrd">value</span>)
    {
      Writer.Write(<span class="kwrd">value</span>);
    }

    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> WriteLiteral(<span class="kwrd">object</span> <span class="kwrd">value</span>)
    {
      Writer.Write(<span class="kwrd">value</span>);
    }

    <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">void</span> Execute();
  }

  <span class="kwrd">public</span> <span class="kwrd">class</span> Customer
  {
    <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { get; set; }
  }
</pre></div>
<h3>Code Listing 3: The TemplateBase class</h3>
<h2>A Sample Template</h2><a href="#codeListing4">Code Listing 4</a> shows you a sample template that you can use. Note that the template itself is specific to the code in <a href="#codeListing2">Code Listing 2</a> and <a href="#codeListing3">Code Listing 3</a>, in that the template references <code>Customers</code>. The generated output is shown <a href="#codeListing5">Code Listing 5</a>. <a name="codeListing4"></a>
<div class="panel code content/images/csharp.png" title="Template using Razor Syntax"><pre class="csharpcode">@functions {
  <span class="kwrd">string</span> GetCustomerFullName(Customer customer)
  {
    <span class="kwrd">return</span> customer.FirstName + <span class="str">" "</span> + customer.LastName;
  }
}
&lt;ul&gt;
@<span class="kwrd">foreach</span>(var customer <span class="kwrd">in</span> Customers)
{
    &lt;li&gt;@customer.FirstName @customer.LastName&lt;/li&gt;
    &lt;li&gt;Full Name: @GetCustomerFullName(customer)&lt;/li&gt;
}
&lt;/ul&gt;</pre></div>
<h3>Code Listing 4: A Sample Template using the Razor Syntax</h3><a name="codeListing5"></a>
<div class="panel code content/images/html.png" title="Generated Output"><pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">ul</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Bill Gates<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Full Name: Bill Gates<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Steve Jobs<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Full Name: Steve Jobs<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Larry  Ellison<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Full Name: Larry  Ellison<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Samuel Palmisano<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;</span>Full Name: Samuel Palmisano<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">ul</span><span class="kwrd">&gt;</span></pre></div>
<h3>Code Listing 5: The Generated Output</h3>]]></description><category>Programming/C#</category><category>CodeGen</category><category>Razor</category><category>Razor Host</category><category>Templating Engine</category></item><item><title>ASP.NET MVC Framework Design Problems</title><pubDate>Wed, 27 Oct 2010 01:31:00 GMT</pubDate><link>http://www.matlus.com/problems-with-asp-net-mvc-framework-design/</link><guid isPermaLink="true">http://www.matlus.com/problems-with-asp-net-mvc-framework-design/</guid><description><![CDATA[<p>The MVC design pattern is probably the most misunderstood and misinterpreted design pattern. It’s probably due to this that the various implementations of the MVC design pattern are so different. Another way to look at it is that the MVC design pattern is not the most suitable design pattern for web based applications and as a result, many implementations/interpretations of the MVC design pattern go against the original intent. This article is about what I think are the problems with the design and implementation of Microsoft’s ASP.NET MVC framework. I believe that one design flaw leads to a tower of design flaws and as it relates to the ASP.NET MVC implementation, a couple of design flaws have led to many others. Rather than focus on Microsoft’s implementation of the MVC design pattern, I’ll be focusing on system design related issues (independent of the MVC design pattern) from the perspective of Web Application framework design. <b>Figure 1</b> below shows you the design and control flow of the various parts of the ASP.NET MVC framework. <a name="figure1"></a></p> <p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="MVCAndBuilderDesignPattern" border="0" alt="MVCAndBuilderDesignPattern" src="http://www.matlus.com/content/uploads/2011/01/MVCAndBuilderDesignPattern_e3b9fae1-b5cc-4557-8214-f7042d037bed.jpg" width="540" height="247">&nbsp;</p> <h3>Figure 1: ASP.NET MVC Design and control flow</h3> <h2 class="header">List of Problems with ASP.NET MVC</h2> <ol> <li>No access to view or partial view instances  <li>ViewData is your loosely typed information carrier  <li>Controller is not really in control  <li>Child Actions have no sense of the Request Context  <li>Views are coupled to controllers  <li>Referencing Layout Pages using virtual paths  <li>Routing  <li>Html interspersed with code and code interspersed with html nightmare  <li>Naming conventions </li></ol> <h2 class="header">No Access to View or Partial View instances</h2>I believe this is the first major design flaw (not from an MVC design perspective but rather, just from a framework design perspective) and the cause of a number of other design issues. Because a controller doesn't have access to an instance of the view it enlists, the only way for a controller to communicate information to a view is by using ViewData which is a <code>Dictionary&lt;string, object&gt;</code>. So you can stuff anything you want in there, with each “thing” identified by a string key. The two code listings below show you some code that do the same things but in entirely different ways. <a href="#codeListing1">Code listing 1</a>, shows you the code you'd write in a controller's <code>Action</code> method in ASP.NET MVC and <a href="#codeListing2">Code listing 2</a> shows you the code you'd write in a builder's <code>BuildPage()</code> method in <a href="http://www.matlus.com/quartz-for-aspnet/" target="_blank">Quartz for ASP.NET</a>  <div class="panel"><a name="codeListing1"></a><pre class="csharpcode"><span class="kwrd">public</span> ActionResult Index()
{
  <span class="rem">/* If a specific features is selected */</span>
  <span class="kwrd">if</span> (FeatureId != 0)
  {
    var featurePageModel = BusinessModule.GetFeaturePageModel(FeatureId);

    ViewData[<span class="str">"Title"</span>] = featurePageModel.CurrentFeature.Title;
    ViewData[<span class="str">"AdBoxTopViewBoxTitle"</span>] = <span class="str">"More Features"</span>;
    ViewData[<span class="str">"AdBoxTopViewModel"</span>] = featurePageModel.AdBoxModel;
    ViewData.Model = featurePageModel.CurrentFeature;
    <span class="kwrd">return</span> View(<span class="str">"FeatureDisplay"</span>);
  }
  <span class="kwrd">else</span>
  {
    var featuresAllPageModel = BusinessModule.GetFeaturesAllPageModel();

    ViewData[<span class="str">"Title"</span>] = featurePageModel.CurrentFeature.Title;
    ViewData[<span class="str">"AdBoxTopViewBoxTitle"</span>] = <span class="str">"Highlights"</span>;
    ViewData[<span class="str">"AdBoxTopViewModel"</span>] = featuresAllPageModel.AdBoxModel;
    ViewData.Model = featuresAllPageModel.Features;
    <span class="kwrd">return</span> View(<span class="str">"FeaturesAllView"</span>);
  }
}</pre></div>
<h3>Code Listing 1: Showing ASP.NET MVC code in a Controller Action method</h3><a name="codeListing2"></a>
<div class="mgntop20"></div>
<div class="panel"><pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> BuildPage(HttpContextBase httpContext, <span class="kwrd">object</span> model)
{
  <span class="rem">/* If a specific features is selected */</span>
  <span class="kwrd">if</span> (FeatureId != 0)
  {
    <span class="kwrd">var</span> featurePageModel = (<span class="identifier">FeaturePageModel</span>)model;

    TitleView.Title = featurePageModel.CurrentFeature.Title;
    AdBoxTopView.BoxTitle = <span class="str">"More Features"</span>;
    AdBoxTopView.Model = featurePageModel.AdBoxModel;
    RegisterView(<span class="str">"Body"</span>, <span class="kwrd">new</span> <span class="identifier">FeatureDisplayView</span>(httpContext,
      <span class="kwrd">this</span>, featurePageModel.CurrentFeature));
  }
  <span class="kwrd">else</span>
  {
    var featuresAllPageModel = (<span class="identifier">FeaturesAllPageModel</span>)model;

    TitleView.Title = <span class="str">"Builder for ASP.NET - Features"</span>;
    AdBoxTopView.BoxTitle = <span class="str">"Highlights"</span>;
    AdBoxTopView.Model = featuresAllPageModel.AdBoxModel;
    RegisterView(<span class="str">"Body"</span>, <span class="kwrd">new</span> <span class="identifier">FeaturesAllView</span>(httpContext, <span class="kwrd">this</span>,
      featuresAllPageModel.Features));
  }
}
</pre></div>
<h3>Code Listing 2: Showing Builder for ASP.NET code in a Builder's BuildPage() method</h3>The problems with this (<a href="#codeListing1">code listing 1</a>) approach are: 
<ol>
<li>The controller can’t ensure that the view and all partial views are looking for (and getting) the data it stuffed in ViewData using the same string keys. 
<li>By looking at the code in the controller's <code>action</code> method, it is impossible to tell what is really going on, because all you see is a bunch of things added to ViewData, but you can’t tell who is using what (if at all). That is, you can't tell which View and or partial view is using what thing in the dictionary and if this thing (the item in the dictionary) is even the correct type for the other thing (view and/or partial view) using it 
<li>No strong typing, and so no type checking, no compile time checks and no IDE navigation help between controller and view's methods and properties, sub classes/super classes 
<li>If the same partial view is used by other controllers then these controllers also need to use the same string keys to stuff their data into ViewData. But there is no way to ensure that at the time of writing or reading code 
<li>If the API of the partial view changes or the names of the keys a partial view relies upon changes there is no way to tell during development time what pages are going to break. In a strongly typed system like .NET a simple Ctrl + Shift + B would highlight all such breaking changes. But this is not the case with ASP.NET MVC due to the loosely typed ViewData </li></ol>A strongly typed view makes thing slightly better. So you can define a specific ViewModel for your view and now the view can refer to this ViewModel is a strongly typed manner. But what about the partial views? Needless to say that if you analyze all this you'll conclude that: 
<ol>
<li>The controller has to know about all the requirements of the view, partial views, master views as well as any child actions 
<li>Either the view further breaks down your ViewModel into sub viewmodels and hands these sub viewmodels to each of the partial views. Or, every partial view and master view are privy to some other view's data. If you do the former, then the view needs to be aware of what the partial views need (just like the controller needs to know), which means both the controller and view need to know about the partial views, master views and child actions. So that's not any better. Doing the later is not correct either. </li></ol>If the controller had access to instances of the view, partial views, master views etc. then you'd have code like that shown in <a href="#codeListing2">Code listing 2</a>. Doing all of the above *is* the controller's concern. If not, these concerns propagate throughout. Take a look at <a href="#figure3">Figure 3</a>. It shows you the connectivity and control flow of what the picture would look like where the controller has direct access to the view, partial views and master views. 
<h2 class="header">The Controller is not really in control</h2>Take a look at <a href="#figure1">Figure 1</a>, and you’ll see that the controller only really talks to the view (via ViewData nonetheless because it never really has access to an instance of the view). It doesn’t control or seemingly know of the partial views this view may in turn enlist, in order to get the job done. But the controller does need to know of the partial views because it has to pass data and instructions to partial views. One could argue separation of concerns here. But I beg to differ because propagating responsibilities down the line makes a system incoherent, unmanageable and a maintenance/debugging nightmare. You have to follow bread crumbs from the controller to the view and from there to other partial views just to get a sense of what is going on and who is doing it and who is using what piece of data (that the controller put into ViewData). A big part of the reason for this design seems to be that the view needs to be compiled (the html + code) and so an instance of the view can only be realized after compiling. However, since the view does not use a code file, the controller won't know how to reference the view since it doesn't have a class type to reference at the time of compilation. One could get around this by having the view descend from one of your own base classes, that way you can reference the view solely as the base type and so the controller can be compiled. But getting an instance of a view (due to the ViewEngine and compilation model) is not that easy. <a href="#codeListing2">Code listing 3</a>, below shows how you can get an instance of a view. It's pretty convoluted, since it is not the intent of code compilation model. <a name="codeListing2"></a>
<div class="mgntop20"></div>
<div class="panel"><pre class="csharpcode">  <span class="kwrd">public</span> <span class="kwrd">class</span> HomeController : BaseController
  {
    <span class="kwrd">public</span> ActionResult Index()
    {
      ViewData[<span class="str">"Title"</span>] = <span class="str">"Movies In Theaters"</span>;
      ViewData[<span class="str">"AdvertBoxTopName"</span>] = <span class="str">"Popular Channels"</span>;
      ViewData.Model = BusinessModule.GetHomePageThumbnails();

      ViewEngineResult result = <span class="kwrd">new</span> ViewEngineResult(
        <span class="kwrd">new</span> RazorViewExt(ControllerContext,
        <span class="str">"~/Views/Home/Index.cshtml"</span>,
        <span class="str">"~/Views/Shared/LayoutSite.cshtml"</span>),
        <span class="kwrd">new</span> RazorViewEngine());      
      
      <span class="kwrd">return</span> View(result.View);
    }
  }

  <span class="kwrd">public</span> <span class="kwrd">class</span> RazorViewExt : RazorView
  {
    <span class="kwrd">public</span> RazorViewExt(ControllerContext controllerContext, <span class="kwrd">string</span> viewPath,
      <span class="kwrd">string</span> layoutPath)
      :<span class="kwrd">base</span>(controllerContext, viewPath, layoutPath, <span class="kwrd">false</span>, <span class="kwrd">null</span>) 
    {

    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="
