<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Sankarsan's Journal</title>
	<atom:link href="http://sankarsan.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://sankarsan.wordpress.com</link>
	<description>Technology,Science,Books,Movies.....</description>
	<lastBuildDate>Mon, 05 Dec 2011 18:12:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='sankarsan.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Sankarsan's Journal</title>
		<link>http://sankarsan.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://sankarsan.wordpress.com/osd.xml" title="Sankarsan&#039;s Journal" />
	<atom:link rel='hub' href='http://sankarsan.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Inside ASP.NET 4.5 Bundling and Minification</title>
		<link>http://sankarsan.wordpress.com/2011/11/27/inside-asp-net-4-5-bundling-and-minification/</link>
		<comments>http://sankarsan.wordpress.com/2011/11/27/inside-asp-net-4-5-bundling-and-minification/#comments</comments>
		<pubDate>Sun, 27 Nov 2011 16:50:13 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[ASP.NET 4.5]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/?p=464</guid>
		<description><![CDATA[ASP.NET 4.5 has introduced built-in support for bundling and minification of javascript and css resources.Here minification refers to the mechanism of compressing the javascript &#38; stylesheet files thus reducing the size of data to transferred over the wire. The process of bundling involves combining multiple javascript/css files into one, thus reducing the number of HTTP [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=464&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:large;">ASP.NET 4.5</span> has introduced built-in support for bundling and minification of javascript and css resources.Here minification refers to the mechanism of compressing the javascript &amp; stylesheet files thus reducing the size of data to transferred over the wire. The process of bundling involves combining multiple javascript/css files into one, thus reducing the number of HTTP calls made from the browser. The following post by <a href="http://twitter.com/AbhijitJana" target="_blank">Abhijit Jana</a> gives a nice illustration of the feature covering the basics and  the advanced areas as well.</p>
<p><a title="http://abhijitjana.net/2011/10/06/bundling-and-minification-in-asp-net-4-5/" href="http://abhijitjana.net/2011/10/06/bundling-and-minification-in-asp-net-4-5/">http://abhijitjana.net/2011/10/06/bundling-and-minification-in-asp-net-4-5/</a></p>
<p>Having read this, I was just thinking about these elements/classes under the <span style="color:#0000ff;">System.Web.Optimization</span> namespace are all stitched together to implement the bundling and minification functionality.There were some design level questions as well like is the bundled content cached once created at server side or the bundling is done for every request?.</p>
<p><span id="more-464"></span></p>
<p>I went through the object model using the <strong>Visual Studio 11 Developer Preview</strong> and found the following key classes:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/aspnet_minifier.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ASPNET_Minifier" src="http://sankarsan.files.wordpress.com/2011/11/aspnet_minifier_thumb.png?w=484&#038;h=433" alt="ASPNET_Minifier" width="484" height="433" border="0" /></a></p>
<ul>
<li><span style="color:#0000ff;">BundleResponse</span> – This class represents a resource bundle which contains the response after the resources are bundled and minified.</li>
<li><span style="color:#0000ff;">IBundleTransform</span> – This is the interface, defining the contract for transformation i.e. Bundling + Minification</li>
<li><span style="color:#0000ff;">JSMinify</span> – This is default implementation of IBundleTransform provided by the framework for javascript resources.</li>
<li><span style="color:#0000ff;">Bundle</span> – This class represents a resource bundle with a list of files or directory from where resources needs to be read. This class accepts the type of transformer in the constructor as shown below:</li>
</ul>
<p>public Bundle(string virtualPath, System.Type transformType)</p>
<p><strong><span style="color:#ff0000;">NOTE: </span></strong></p>
<ul>
<li><strong><span style="color:#ff0000;">Not quite sure why this signature accepts a System.Type rather than accepting an instance of IBundleTransform.</span></strong></li>
<li><strong><span style="color:#ff0000;">The IBundleTransform.Process method should accept a Bundle as input and return BundleResponse as output not a void return type with BundleResponse as input. This does not seem to be a good API design to me.</span></strong></li>
</ul>
<p>So I can understand logically that</p>
<ul>
<li>A <span style="color:#0000ff;">Bundle</span> is defined by providing resource (js/css files &amp; folders) locations</li>
<li>A class implementing <span style="color:#0000ff;">IBundleTransform</span> interface converts this to a minified and merged content and puts them in <span style="color:#0000ff;">BundleResponse</span>.</li>
</ul>
<p>But how <span style="color:#0000ff;">IBundleTranform.Process</span> method is invoked? Is there any caching happening?</p>
<p>I implemented a small custom transform class which throws an Exception.</p>
<p><pre class="brush: csharp;">
public class MyJSTransform:IBundleTransform
{
    public void Process(BundleResponse bundle)
    {
        throw new ApplicationException(&quot;...&quot;);

    }
}
</pre></p>
<p>The stacktrace captured is as shown below:</p>
<p>[ApplicationException: ...]<br />
BundingDemo.MyJSTransform.Process(BundleResponse bundle) in d:\Demos\BundingDemo\BundingDemo\MyJSTransform.cs:12<br />
<strong>System.Web.Optimization.Bundle.GenerateBundleResponse(HttpContextBase context, String bundleVirtualPath) +99<br />
System.Web.Optimization.Bundle.GetBundleResponse(HttpContextBase context, String bundleVirtualPath) +37<br />
System.Web.Optimization.Bundle.ProcessRequest(HttpContextBase context) +25<br />
System.Web.Optimization.BundleHandler.ProcessRequest(HttpContext context) +62<br />
</strong>   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +116<br />
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp;amp; completedSynchronously)</p>
<p>There are many methods which seems to be internal methods and classes, not visible through object browser. So a decompiler is the only resort. From the decompiled code we get some insight into the three critical method:</p>
<ul>
<li><span style="color:#0000ff;">BundleHandler</span>
<ul>
<li>This is an <span style="color:#0000ff;">IHttpHandler</span> implementation handling the JS &amp; CSS resource requests</li>
<li>The <span style="color:#0000ff;">ProcessRequest</span>method
<ul>
<li>Get the Bundle from the Singleton class BundleTable.</li>
<li>Invokes <span style="color:#0000ff;">Bundle.ProcessRequest</span>  method</li>
</ul>
</li>
</ul>
</li>
<li><span style="color:#0000ff;">Bundle.ProcessRequest</span>
<ul>
<li>This method retrieves the bundle url first</li>
<li>Invokes the <span style="color:#0000ff;">GetBundleResponse</span> method</li>
</ul>
</li>
<li><span style="color:#0000ff;">Bundle.GetBundleResponse</span>
<ul>
<li><strong>Perform the cache lookup (normal ASP.NET cache with bundle url as key)</strong></li>
<li>If there is a cache miss it calls <span style="color:#0000ff;">GenerateBundleResponse</span></li>
</ul>
</li>
<li><span style="color:#0000ff;">Bundle.GenerateBundleResponse</span>
<ul>
<li>Create an instances of BundleResponse class</li>
<li>Set the files to be processed in correct order</li>
<li>Invokes <span style="color:#0000ff;">IBundleTransform.Process</span></li>
</ul>
</li>
</ul>
<p>The storage of the JS content in Cache can be easily viewed using Quick Watch window as shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/image3.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" src="http://sankarsan.files.wordpress.com/2011/11/image_thumb3.png?w=583&#038;h=207" alt="image" width="583" height="207" border="0" /></a></p>
<p>The entire flow can be summarized as:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/aspnet_minifier1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="ASPNET_Minifier" src="http://sankarsan.files.wordpress.com/2011/11/aspnet_minifier_thumb1.png?w=573&#038;h=408" alt="ASPNET_Minifier" width="573" height="408" border="0" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/464/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=464&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/11/27/inside-asp-net-4-5-bundling-and-minification/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/aspnet_minifier_thumb.png" medium="image">
			<media:title type="html">ASPNET_Minifier</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/image_thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/aspnet_minifier_thumb1.png" medium="image">
			<media:title type="html">ASPNET_Minifier</media:title>
		</media:content>
	</item>
		<item>
		<title>Roslyn CTP&#8211;Syntax Tree&#8211;Part II&#8211;Singleton Checker</title>
		<link>http://sankarsan.wordpress.com/2011/11/20/roslyn-ctpsyntax-treepart-iisingleton-checker/</link>
		<comments>http://sankarsan.wordpress.com/2011/11/20/roslyn-ctpsyntax-treepart-iisingleton-checker/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 18:55:37 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Roslyn CTP]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/?p=452</guid>
		<description><![CDATA[In the last post related to Roslyn we developed a very basic syntax walker. In this post we will see how we can use the same for code analysis and checking. As a good practice we generally try to avoid having instance members in a singleton class. This is true if you are making your [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=452&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the last <a href="http://sankarsan.wordpress.com/2011/11/20/roslyn-ctpa-walk-through-the-syntax-treepart-i/" target="_blank">post</a> related to Roslyn we developed a very basic syntax walker. In this post we will see how we can use the same for code analysis and checking. <font color="#0000ff" size="4"><em>As a good practice we generally try to avoid having instance members in a singleton class</em></font>. This is true if you are making your business logic layer classes Singleton and would prefer to avoid mess up by multiple threads. In order to check that we need to check the following:</p>
<p>a) Whether the class has any instance fields or properties</p>
<p>b) Whether class is a singleton i.e having a private constructor</p>
<p>Let’s consider the following singleton class:</p>
<p><span id="more-452"></span><br />
<pre class="brush: csharp;">
public class Test 
    { 
        private static Test instance = null; 
        private int i = 0; 
        private int J { get; set; } 
        private Test() 
        {

        } 
        public static Test GetInstance() 
        { 
            lock(typeof(Test)) 
            { 
                if(instance==null) 
                { 
                    instance = new Test(); 
                } 
            } 
            return instance; 
        } 
        public void M1() { } 
        public void M2() { } 
    }
</pre> </p>
<p>Here there are three static variables but we will not consider one field or property with type Test. As this is essential for the basic Singleton implementation. We will use the following rules:</p>
<ul>
<li><strong><em><font color="#748f3a">If the class is static then Singleton check is not required. </font></em></strong></li>
<li><strong><em><font color="#748f3a">If class has any constructor which is not private then it’s not a valid singleton class.</font></em></strong> </li>
<li><strong><em><font color="#748f3a">If all the methods are static then the code will issue an warning to mark it as static</font></em></strong> </li>
<li><strong><em><font color="#748f3a">If there instance variables of type other than the type of Singleton class then it’ll flag an error</font></em></strong> </li>
<li><strong><em><font color="#748f3a">If there are more than one instance variable to type of Singleton class then it’ll flag an error</font></em></strong> </li>
</ul>
<p>&#160;</p>
<p><pre class="brush: csharp;">
public class SingletonClassChecker 
{ 
     private bool isStatic = false; 
     private List&lt;string&gt; propertyFieldTypes = new List&lt;string&gt;();

     private List&lt;string&gt; methodStaticNonStatic = new List&lt;string&gt;(); 
     private int nonPrivateCnstrCounter = 0; 
     
     public void CheckSingletonClass(ClassDeclarationSyntax cds) 
     { 
         
         CollectData(cds); 
         AnalyzeData(cds);

     }

     private void CollectData(ClassDeclarationSyntax cds) 
     { 
         PropertyDeclarationSyntax prop = null; 
         FieldDeclarationSyntax field = null; 
         MethodDeclarationSyntax meth = null; 
         var hasPrivateConstructor = false; 
         var isStatic = false; 
         foreach (var md in cds.Modifiers) 
         { 
             if (md.GetText().Equals(&quot;static&quot;)) 
             { 
                 isStatic = true; 
                 break; 
             } 
         } 
         if (!isStatic) 
         { 
             foreach (var m in cds.Members) 
             { 
                 prop = m as PropertyDeclarationSyntax; 
                 field = m as FieldDeclarationSyntax; 
                 meth = m as MethodDeclarationSyntax; 
                 if (prop != null) 
                 { 
                     propertyFieldTypes.Add(prop.Type.PlainName); 
                 } 
                 if (field != null) 
                 { 
                     propertyFieldTypes.Add(field.Declaration.Type.PlainName); 
                 } 
                 if (m is ConstructorDeclarationSyntax) 
                 { 
                     hasPrivateConstructor = false; 
                     foreach (var cmd in (m as ConstructorDeclarationSyntax).Modifiers) 
                     { 
                         if (cmd.GetText().Equals(&quot;private&quot;)) 
                         { 
                             hasPrivateConstructor = true; 
                         } 
                     } 
                     if (!hasPrivateConstructor) nonPrivateCnstrCounter = nonPrivateCnstrCounter + 1; 
                 } 
                 if (meth!=null) 
                 { 
                     isStatic = false; 
                     foreach (var mm in meth.Modifiers) 
                     { 
                         if (mm.GetText().Equals(&quot;static&quot;)) isStatic = true; 
                     } 
                     if (isStatic == true) methodStaticNonStatic.Add(&quot;Static&quot;); else methodStaticNonStatic.Add(&quot;Non Static&quot;); 
                     

                 } 
             } 
         } 
     } 
     private void AnalyzeData(ClassDeclarationSyntax cds) 
     { 
         Console.WriteLine(&quot;Analyzing Class::&quot; + cds.Identifier); 
         //If class is static then Singleton check is not required 
         if (isStatic) 
         { 
             Console.WriteLine(&quot;Static Class.Singleton check is not required&quot;); 
         } 
         else 
         { 
             // If Class has non private constructor then it's not a singleton 
             if (nonPrivateCnstrCounter &gt; 0) 
             { 
                 Console.WriteLine(&quot;Has non private constructor.Not a valid singleton.Singleton check is not required&quot;); 
             } 
             else 
             { 
                 var count = methodStaticNonStatic.Count(p =&gt; p.Equals(&quot;static&quot;)); 
                 //If all methods are static then the class need not be a singleton 
                 if (count == methodStaticNonStatic.Count) 
                 { 
                     Console.WriteLine(&quot;Warning::All methods are static.Mark the class as static.Singleton not required.&quot;); 
                 } 
                 else 
                 { 
                     // If class contains instance variables other than singleton instance then there is an error 
                     if(propertyFieldTypes.Count(p=&gt;!p.Equals(cds.Identifier.GetText()))&gt;0) 
                     { 
                         Console.WriteLine(&quot;Error:: Singleton class with instance variables&quot;); 
                     }// If class contains instance variables of same type but more than one then there is an error. 
                     else if (propertyFieldTypes.Count(p =&gt; p.Equals(cds.Identifier.GetText())) &gt; 1) 
                     { 
                         Console.WriteLine(&quot;Error:: Singleton class with instance variables&quot;); 
                     } 
                 } 
             }

         } 
     }
} 
</pre></p>
<p>This method is invoked as shown below:</p>
<p><pre class="brush: csharp;">
static void Main(string[] args)
    {
        SyntaxTree tree = SyntaxTree.ParseCompilationUnit(@&quot;namespace RoslynCTPDemo
                        {
                        public class Test
                        {
                            private static Test instance = null;
                            private int i = 0;
                            private int J { get; set; }
                            private Test()
                            {

                            }
                            public static Test GetInstance()
                            {
                                lock(typeof(Test))
                                {
                                    if(instance==null)
                                    {
                                        instance = new Test();
                                    }
                                }
                                return instance;
                            }
                            public void M1() { }
                            public void M2() { }
                        }
                    }&quot;);
        SingletonClassChecker sc = new SingletonClassChecker();
        var root = (CompilationUnitSyntax)tree.Root;
        foreach (var n in root.Members)
        {
            if (n is NamespaceDeclarationSyntax)
            {
                //Find Classes if inside namespace
                foreach (var c in (n as NamespaceDeclarationSyntax).Members)
                {
                    if (c is ClassDeclarationSyntax) sc.CheckSingletonClass(c as ClassDeclarationSyntax);
                }
            } // For classes with namespace declaration
            else if (n is ClassDeclarationSyntax)
            {
                sc.CheckSingletonClass(n as ClassDeclarationSyntax);
            }
        }
        Console.Read();
    }
</pre></p>
<p>The output is:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/image2.png"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="image" border="0" alt="image" src="http://sankarsan.files.wordpress.com/2011/11/image_thumb2.png?w=468&#038;h=68" width="468" height="68" /></a></p>
<p>This example demonstrates the beauty, simplicity yet the power of Roslyn Syntax API. This small code snippet is converted to a suitable Visual Studio plug-in can serve the purpose of source code checker the way Resharper does that now.   </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/452/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/452/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/452/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/452/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/452/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/452/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/452/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/452/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/452/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/452/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/452/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/452/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/452/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/452/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=452&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/11/20/roslyn-ctpsyntax-treepart-iisingleton-checker/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Roslyn CTP&#8211;A Walk Through The Syntax Tree&#8211;Part I</title>
		<link>http://sankarsan.wordpress.com/2011/11/20/roslyn-ctpa-walk-through-the-syntax-treepart-i/</link>
		<comments>http://sankarsan.wordpress.com/2011/11/20/roslyn-ctpa-walk-through-the-syntax-treepart-i/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 15:53:22 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Roslyn]]></category>
		<category><![CDATA[Syntax API]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/?p=445</guid>
		<description><![CDATA[The Roslyn project aims to expose the functionalities of C#/VB complier as API/Services. The Roslyn CTP was released this October.One of the important components of Roslyn is the Compiler API. This exposes an object model which provides access to information generated at the different stages of compilation.The first phase of any compilation process involves parsing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=445&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The Roslyn project aims to expose the functionalities of C#/VB complier as API/Services. The Roslyn CTP was released this October.One of the important components of <font color="#0000ff">Roslyn</font> is the Compiler API. This exposes an object model which provides access to information generated at the different stages of compilation.The first phase of any compilation process involves parsing and generating the syntax tree. In this post we will discuss about the basics of the Syntax Tree API.</p>
<p><span id="more-445"></span></p>
<p>The major components of a syntax tree are shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/roslyn.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="roslyn" border="0" alt="roslyn" src="http://sankarsan.files.wordpress.com/2011/11/roslyn_thumb.png?w=591&#038;h=300" width="591" height="300" /></a></p>
<p>A sample node in a code fragment is shown in the figure below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/roslyn1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="roslyn1" border="0" alt="roslyn1" src="http://sankarsan.files.wordpress.com/2011/11/roslyn1_thumb.png?w=597&#038;h=276" width="597" height="276" /></a></p>
<p>In this post we will develop a small sample syntax tree walker to start with. But before that let’s take a quick look how the Roslyn Syntax API is structured for SyntaxNodes.</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/roslynuml.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="RoslynUML" border="0" alt="RoslynUML" src="http://sankarsan.files.wordpress.com/2011/11/roslynuml_thumb.png?w=679&#038;h=358" width="679" height="358" /></a></p>
<p>We will develop a&#160; syntax walker which will traverse the different declaration syntax nodes and print their text contents.</p>
<p><pre class="brush: csharp;">
static void Main(string[] args) 
{ 
     SyntaxTree tree = SyntaxTree.ParseCompilationUnit( 
                 @&quot; 
                 using System; 
                 using System.Collections; 
                 using System.Linq; 
                 using System.Text; 
  
                 namespace HelloWorld 
                 { 
                     class Program 
                     { 
                         
                         static void Main(string[] args) 
                         { 
                             var a = 10; 
                             Console.WriteLine(&quot;&quot;Hello, World!&quot;&quot;); 
                         } 
                         public int i {get;set;} 
                         var i = 11; 
                     } 
                 }&quot;); 
    
     var root = (CompilationUnitSyntax)tree.Root; 
     foreach (var n in root.Members) 
     { 
         if (n is NamespaceDeclarationSyntax) 
         { 
             foreach (var t in (n as NamespaceDeclarationSyntax).Members) 
             { 
                 if (t is ClassDeclarationSyntax) 
                 { 
                     foreach (var m in (t as ClassDeclarationSyntax).Members) 
                     { 
                         if (m is PropertyDeclarationSyntax) 
                         { 
                             Console.WriteLine(&quot;Property::&quot; + m.GetText()); 
                         } 
                         if (m is MethodDeclarationSyntax) 
                         { 
                             Console.WriteLine(&quot;Method::&quot; + m.GetText()); 
                         } 
                         if (m is FieldDeclarationSyntax) 
                         { 
                             Console.WriteLine(&quot;Variable::&quot; + m.GetText()); 
                         }  
                     } 
                 } 
             } 
         } 
    } 
     Console.Read();

} 


</pre></p>
<p>The programs does the following:</p>
<ul>
<li>Invokes <font color="#0000ff">SyntaxTree.ParseCompilationUnit</font> method with source code as input to generate SyntaxTree. </li>
<li>Loops through all the members of the root node </li>
<li>Checks the type of each member to determine the type of declaration syntax node and prints the contained text of that node. </li>
</ul>
<p>The output is as shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" border="0" alt="image" src="http://sankarsan.files.wordpress.com/2011/11/image_thumb.png?w=621&#038;h=102" width="621" height="102" /></a></p>
<p>&#160;</p>
<p>Now we will take a look into the different tokens of the method declaration. Every method has modifiers, return type, identifier and parameter list as shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/roslyn2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="roslyn" border="0" alt="roslyn" src="http://sankarsan.files.wordpress.com/2011/11/roslyn_thumb1.png?w=498&#038;h=121" width="498" height="121" /></a></p>
<p>The code below shown how <font color="#0000ff">Roslyn Syntax API</font> can be used to explore and walkthrough the same:</p>
<p><pre class="brush: csharp;">
if (m is MethodDeclarationSyntax) 
{ 
    var meth = (m as MethodDeclarationSyntax); 
    foreach (var mt in (m as MethodDeclarationSyntax).Modifiers) 
    { 
        Console.WriteLine(&quot;Modifier::&quot; + mt.GetText()); 
    } 
    Console.WriteLine(&quot;Identifier::&quot; + meth.ReturnType); 
    Console.WriteLine(&quot;Identifier::&quot; + meth.Identifier); 
    foreach (var p in meth.ParameterList.Parameters) 
    { 
        Console.WriteLine(&quot;Parameter Type::&quot; + p.TypeOpt.PlainName + &quot;::&quot; + p.TypeOpt.Kind ); 
        Console.WriteLine(&quot;Parameter Identifier::&quot; + p.Identifier); 
    }

} 
</pre>  </p>
<p>The output now changes to:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/11/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" border="0" alt="image" src="http://sankarsan.files.wordpress.com/2011/11/image_thumb1.png?w=438&#038;h=165" width="438" height="165" /></a>     </p>
<p>In the next post we will how we can use Syntax API in source code analysis and checking.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/445/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=445&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/11/20/roslyn-ctpa-walk-through-the-syntax-treepart-i/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/roslyn_thumb.png" medium="image">
			<media:title type="html">roslyn</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/roslyn1_thumb.png" medium="image">
			<media:title type="html">roslyn1</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/roslynuml_thumb.png" medium="image">
			<media:title type="html">RoslynUML</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/roslyn_thumb1.png" medium="image">
			<media:title type="html">roslyn</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/11/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Inside C# Extension Methods</title>
		<link>http://sankarsan.wordpress.com/2011/10/23/inside-c-extension-methods/</link>
		<comments>http://sankarsan.wordpress.com/2011/10/23/inside-c-extension-methods/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 07:50:26 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Extension Method]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/2011/10/23/inside-c-extension-methods/</guid>
		<description><![CDATA[C# Extension methods were introduced in C# 3.0. They provide a mechanism to extend(not the inheritance way) the functionality of an existing class by attaching methods to it.An extension method needs to be developed in a static class as a static method as shown below: We can invoke it as In this post we will [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=430&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>C# Extension methods were introduced in C# 3.0. They provide a mechanism to extend(not the inheritance way) the functionality of an existing class by attaching methods to it.An extension method needs to be developed in a static class as a static method as shown below:</p>
<p><pre class="brush: csharp;">
public static class MyExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }
</pre></p>
<p>We can invoke it as </p>
<p><pre class="brush: csharp;">
10.AddExt(12)
</pre> </p>
<p>In this post we will look at what’s happening inside extension method.</p>
<p>To understand the difference I am adding one more static method of exactly same signature.</p>
<p><pre class="brush: csharp;">
public static class MyExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }
</pre></p>
<p>The two methods are invoked as:</p>
<p><pre class="brush: csharp;">
static void Main(string[] args) 
        { 
            Console.WriteLine(10.AddExt(12)); 
            Console.WriteLine(MyExtensions.AddStatic(10,12)); 
            Console.Read(); 
        }
</pre></p>
<p>Let’s take a look into the IL code of the two method calls.</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/ext.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ext" border="0" alt="ext" src="http://sankarsan.files.wordpress.com/2011/10/ext_thumb.png?w=482&#038;h=311" width="482" height="311" /></a></p>
<p>The IL code of the two method calls are exactly same and they are just static method calls. Only in case of AddExt the object on which it is invoked in C# code is passed as first parameter value.</p>
<p>So what’s going on ? We have to go to the IL for method definitions:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" border="0" alt="image" src="http://sankarsan.files.wordpress.com/2011/10/image_thumb.png?w=496&#038;h=259" width="496" height="259" /></a></p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" border="0" alt="image" src="http://sankarsan.files.wordpress.com/2011/10/image_thumb1.png?w=316&#038;h=266" width="316" height="266" /></a></p>
<p>Only visible difference is the extension method has an attribute called ExtensionAttribute injected on the IL code. Let’s add this attribute to the other static method and see what happens?</p>
<p>This leads to a compiler error “<font color="#b80e30"><strong><em>Do not use &#8216;System.Runtime.CompilerServices.ExtensionAttribute&#8217;. Use the &#8216;this&#8217; keyword instead</em></strong></font>.”</p>
<p>So Mr. compiler is not allowing us to hack around with his magic wand of syntactic sugar.</p>
<p>However we can summarize as:</p>
<ul>
<li>When we write an extension method using “this” keyword in the first parameter compiler injects a <font color="#0000ff">ExtensionMethodAttribute</font> to the IL code of the method. </li>
<li>The invoking code for an extension is replaced as <strong><font color="#c0504d" size="4">&lt;Static Class Name&gt;.&lt;ExtensionMethodName&gt;(&lt;Object Instance on which method is invoked&gt;,…….)</font></strong> </li>
</ul>
<p>Hang on.. What if there are two classes with same extension method name on same class e.g. if we add something like:</p>
<p><pre class="brush: csharp;">
public static class MyOtherExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }
</pre></p>
<p>We immediately get a compiler error “<strong><em><font color="#b80e30">The call is ambiguous between the following methods or properties: &#8216;ExtensionMethods.MyExtensions.AddExt(int, int)&#8217; and &#8216;ExtensionMethods.MyOtherExtensions.AddExt(int, int)</font></em></strong>”</p>
<p>If I define the extension method on a dynamic type as</p>
<p><pre class="brush: csharp;">
public static Int32 AddExt(this dynamic i, Int32 j) 
{ 
            return i + j; 
}
</pre></p>
<p>Again compiler stops us from so with a message “<font color="#b80e30"><strong><em>The first parameter of an extension method cannot be of type &#8216;dynamic&#8217;</em></strong></font>”</p>
<p>We will go for a generic parameter now.</p>
<p><pre class="brush: csharp;">
public static Int32 AddExt&lt;T&gt;(this T i, Int32 j) 
        { 
            return ++j; 
        }
</pre></p>
<p>This one compiles. But which will be invoked? MyExtensions.AddExt or MyOtherExtensions.AddExt.</p>
<p><pre class="brush: csharp;">
static void Main(string[] args) 
       { 
           Console.WriteLine(10.AddExt(12)); 
           Console.WriteLine(new Object().AddExt(12));

           Console.WriteLine(MyExtensions.AddStatic(10, 12)); 
           Console.Read(); 
       } 


public static class MyExtensions 
    { 
        public static Int32 AddExt&lt;T&gt;(this T i, Int32 j) 
        { 
            return ++j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    } 
    public static class MyOtherExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }
</pre></p>
<p>It is MyOtherExtensions.AddExt that is compiler finds the closest match while generating the IL Code.</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/image2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" border="0" alt="image" src="http://sankarsan.files.wordpress.com/2011/10/image_thumb2.png?w=498&#038;h=255" width="498" height="255" /></a></p>
<p>So Extension methods are nothing but static calls accepting the object instance on which it is invoked (as if instance method) as the first parameter.</p>
<p>The last question we they can only be added in static classes. I think that’s good design decision.</p>
<ul>
<li>Extension methods are supposed to act &amp; designed like instance method on some other classes </li>
<li>We can’t add global methods without classes in C# every method needs a class container </li>
<li>But extension methods are not supposed be aware of instance properties of the class they belong to as that is a mere container for them. </li>
<li>So best way is to enforce through the complier that extension methods are within static classes </li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/430/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/430/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/430/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/430/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/430/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/430/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/430/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/430/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/430/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/430/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/430/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/430/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/430/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/430/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=430&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/10/23/inside-c-extension-methods/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/ext_thumb.png" medium="image">
			<media:title type="html">ext</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>EntityConnection &amp; Metadata in EntityFramework</title>
		<link>http://sankarsan.wordpress.com/2011/10/22/entityconnection-metadata-in-entityframework/</link>
		<comments>http://sankarsan.wordpress.com/2011/10/22/entityconnection-metadata-in-entityframework/#comments</comments>
		<pubDate>Sat, 22 Oct 2011 11:31:24 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ADO.NET Entity Framework]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Metadata]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/2011/10/22/entityconnection-metadata-in-entityframework/</guid>
		<description><![CDATA[EntityConnection (System.Data.EntityClient.EntityConnection) is the class which provides an abstraction for the connection established by the framework.What exactly we mean by connection established by the framework? A ORM framework stands in between an object model and a data source so it needs to connect to both i.e the model and the data source. When we add [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=413&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-large;">E</span>ntityConnection (<span style="color:#0000ff;">System.Data.EntityClient.EntityConnection</span>) is the class which provides an abstraction for the connection established by the framework.What exactly we mean by connection established by the framework? A ORM framework stands in between an object model and a data source so it needs to connect to both i.e the model and the data source.</p>
<p>When we add an Entity Data Model (*.edmx) a default connection string gets added to the solution as shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/ec.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ec" src="http://sankarsan.files.wordpress.com/2011/10/ec_thumb.png?w=697&#038;h=180" alt="ec" width="697" height="180" border="0" /></a></p>
<p>As indicated in the figure above the two critical components, one is metadata (model) and another is provider (datasource). The datasource part is quite obvious and easy to understand so let’s concentrate on the metadata part of it.</p>
<p>The entity data model (*.edmx) contains three xml based sections:</p>
<ul>
<li><strong>Storage Model</strong> define in Storage Schema Definition Language (SSDL)</li>
<li><strong>Conceptual Model</strong> (Class Model) defined in Conceptual Schema Definition Language(CSDL)</li>
<li><strong>Mapping</strong> defined in Mapping Specification Language(MSL)</li>
</ul>
<p>By default settings, when the code is compiled these three xml blocks get embedded into the assembly as resources. So in the metadata connection string we need to specify name of the SSDL/MSDL/CSDL and from which assembly we need to download them. This is shown in the figure below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/metadata.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="metadata" src="http://sankarsan.files.wordpress.com/2011/10/metadata_thumb.png?w=467&#038;h=166" alt="metadata" width="467" height="166" border="0" /></a></p>
<p>If we can change the Metadata location to output directory as shown below then SSDL/MSDL/CSDL files will be separately generated in the output (bin) folder</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/metaart.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="metaart" src="http://sankarsan.files.wordpress.com/2011/10/metaart_thumb.png?w=403&#038;h=239" alt="metaart" width="403" height="239" border="0" /></a></p>
<p>The files will be be generated as shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/output.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="output" src="http://sankarsan.files.wordpress.com/2011/10/output_thumb.png?w=313&#038;h=202" alt="output" width="313" height="202" border="0" /></a></p>
<p>The connection string gets modified as shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/metapath.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="metapath" src="http://sankarsan.files.wordpress.com/2011/10/metapath_thumb.png?w=435&#038;h=103" alt="metapath" width="435" height="103" border="0" /></a></p>
<p>So far so good. Though in most of the cases it seems to me that embedding inside the assembly makes much more sense but some of the configuration crazy crowd might think otherwise as well.So how we can manipulate this programmatically through the API.It’s time to go back to the <span style="color:#0000ff;">EntityConnection</span> class.</p>
<p>The EntityConnection class has a constructor which accepts a connection string as shown above containing both database and metadata information.But in case there are many metadata files this will be extremely cumbersome &amp; long.</p>
<p>So to do similar stuff using API we need to see metadata information is exposed through classes.</p>
<p><span style="color:#0000ff;">EntityConnection</span> holds a reference to <span style="color:#0000ff;">System.Data.Common.DbConnection</span> &amp; <span style="color:#0000ff;">System.Data.Metadata.Edm.MetadataWorkspace</span> as shown in the figure below</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/ecuml.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ecuml" src="http://sankarsan.files.wordpress.com/2011/10/ecuml_thumb.png?w=348&#038;h=255" alt="ecuml" width="348" height="255" border="0" /></a></p>
<p>MetadataWorkspace is the class representing the metadata and it has the following constructor which accepts list of paths and assemblies.</p>
<ul>
<li>public MetadataWorkspace(IEnumerable&lt;string&gt; paths,IEnumerable&lt;Assembly&gt; assembliesToConsider)</li>
</ul>
<p>The following code block shows how we can use this constructor to read the metadata from file system: Here I have passed null in the second parameter as we are not extracting metadata from assembly here.</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/mdw1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="mdw1" src="http://sankarsan.files.wordpress.com/2011/10/mdw1_thumb.png?w=840&#038;h=157" alt="mdw1" width="840" height="157" border="0" /></a></p>
<p>This leads to the following ArgumentNullException exception.</p>
<p><span style="color:#ff0000;">{&#8220;Value cannot be null.\r\nParameter name: assembliesToConsider&#8221;}</span></p>
<p>However passing a empty list works <img class="wlEmoticon wlEmoticon-smile" style="border-style:none;" src="http://sankarsan.files.wordpress.com/2011/10/wlemoticon-smile.png?w=614" alt="Smile" /><br />
<pre class="brush: csharp;">
static void Main(string[] args)
        {
            DbConnection dbc = new SqlConnection(@&quot;data source=.\SQLEXPRESS;initial catalog=AdventureWorksLT2008;
                                                integrated security=True;multipleactiveresultsets=True;&quot;);

            MetadataWorkspace mdw = new MetadataWorkspace(new List&lt;String&gt;()
                                                                {
                                                                    @&quot;D:\Demos\EFSample\AdventureWorks.Sales\bin\Debug\SalesModel.csdl&quot;,
                                                                    @&quot;D:\Demos\EFSample\AdventureWorks.Sales\bin\Debug\SalesModel.ssdl&quot;,
                                                                    @&quot;D:\Demos\EFSample\AdventureWorks.Sales\bin\Debug\SalesModel.msl&quot;
                                                                }
                                                                ,new List&lt;Assembly&gt;());
            AdventureWorksLT2008Entities a = null;

            try
            {
                a = new AdventureWorksLT2008Entities(new EntityConnection(mdw, dbc));
                Console.WriteLine(a.ProductCategories.First().Name);
            }
            finally
            {
                (a as IDisposable).Dispose();
            }
           
            Console.Read();
        }

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/413/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/413/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/413/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/413/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/413/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/413/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/413/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/413/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/413/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/413/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/413/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/413/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/413/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/413/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=413&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/10/22/entityconnection-metadata-in-entityframework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/ec_thumb.png" medium="image">
			<media:title type="html">ec</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/metadata_thumb.png" medium="image">
			<media:title type="html">metadata</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/metaart_thumb.png" medium="image">
			<media:title type="html">metaart</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/output_thumb.png" medium="image">
			<media:title type="html">output</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/metapath_thumb.png" medium="image">
			<media:title type="html">metapath</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/ecuml_thumb.png" medium="image">
			<media:title type="html">ecuml</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/mdw1_thumb.png" medium="image">
			<media:title type="html">mdw1</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>
	</item>
		<item>
		<title>Automatic Format Selection in WCF REST/HTTP Services</title>
		<link>http://sankarsan.wordpress.com/2011/10/08/automatic-format-selection-in-wcf-resthttp-services/</link>
		<comments>http://sankarsan.wordpress.com/2011/10/08/automatic-format-selection-in-wcf-resthttp-services/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 13:05:00 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WCF 4.0]]></category>
		<category><![CDATA[WCF REST]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/2011/10/08/automatic-format-selection-in-wcf-resthttp-services/</guid>
		<description><![CDATA[REST/HTTP Services in WCF is nothing new, it’s been there since 2008, version 3.5 of the framework. Yesterday I came across a question that whether a particular operation can support both XML/JSON format and return response in the suitable format as demanded by the client program. To my knowledge the answer was a both Yes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=389&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><font size="7">R</font>EST/HTTP Services in WCF is nothing new, it’s been there since 2008, version 3.5 of the framework. Yesterday I came across a question that whether a particular operation can support both XML/JSON format and return response in the suitable format as demanded by the client program. To my knowledge the answer was a both Yes &amp; No. Because I did quite extensive study of the <font color="#0000ff">System.ServiceModel.Web.</font><font color="#0000ff">WebHttpBehavior</font> and <font color="#0000ff">System.ServiceModel.Web.</font><font color="#0000ff">WebGetAttribute</font> back in 2008 as given in the post below:</p>
<p><a href="http://sankarsan.wordpress.com/2008/10/28/wcf-web-model-poxjson-support/">http://sankarsan.wordpress.com/2008/10/28/wcf-web-model-poxjson-support/</a></p>
<p>This limitation drew my attention. However there was a solution to the problem.We can always extend the <font color="#0000ff">WebHttpBehavior</font> and override the <font color="#0000ff">WebHttpBehavior.GetReplyDispatchFormatter</font> method to return our own custom implementation of <font color="#0000ff">System.ServiceModel.Dispatcher.IDispatchFormatter</font>. A similar implementation can be found in the post below:</p>
<p><a href="http://damianblog.com/2008/10/31/wcf-rest-dynamic-response/">http://damianblog.com/2008/10/31/wcf-rest-dynamic-response/</a></p>
<p>Wait …..</p>
<p>This kind of an implementation is actually now part of the .NET 4.0. This is controlled by the <strong><font color="#0000ff" size="4">automaticFormatSelectionEnabled</font></strong> property of the <font color="#0000ff">WebHttpBehavior</font>. This property when set to true then the response format of the operation is governed by the <strong><font color="#9bbb59">Accept</font></strong> , <font color="#8fb08c"><strong>Content-Type</strong></font> header of the request. This feature is called <strong>Automatic Format Selection</strong>. This is what we will discuss in this post.</p>
<p>I have a simple service with a Add operation as shown below:</p>
<p><pre class="brush: csharp;">
[OperationContract] 
[WebGet] 
public int  Add(int i , int j) 
{ 
   // Add your operation implementation here 
   return i+j; 
} 

</pre><br />
<br />The client code is a .NET program sending a HTTP request as shown below:</p>
<p><pre class="brush: csharp;">
HttpWebRequest request = HttpWebRequest.Create(&quot;http://localhost:5072/TestService.svc/Add?i=1&amp;j=1&quot;) as HttpWebRequest; 
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None; 
request.Method = &quot;GET&quot;; 
request.ContentType = &quot;text/xml&quot;; 
request.Accept = &quot;text/xml&quot;; 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
using (StreamReader rdr = new StreamReader(response.GetResponseStream())) 
{ 
    Console.WriteLine(rdr.ReadToEnd()); 
}
</pre></p>
<p>The response is in JSON format as shown below:</p>
<p>{&quot;d&quot;:2}</p>
<p>Now I will turn on auto format selection as shown below using config.</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/10/wcfauto.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="wcfauto" border="0" alt="wcfauto" src="http://sankarsan.files.wordpress.com/2011/10/wcfauto_thumb.png?w=495&#038;h=256" width="495" height="256" /></a>     </p>
<p>Now the output is XML as shown below:</p>
<p><pre class="brush: xml;">
&lt;AddResponse xmlns=&quot;http://sankarsanbose.com/test&quot;&gt;&lt;AddResult&gt;2&lt;/AddResult&gt;&lt;/Add 
Response&gt;
</pre> </p>
<p>Now I will change the Accept header to JSON.</p>
<p><pre class="brush: csharp;">
request.ContentType = &quot;text/xml&quot;; 
request.Accept = &quot;text/json&quot;;
</pre></p>
<p>The response is now again in JSON format as shown below:</p>
<p>{&quot;d&quot;:2}</p>
<p><strong><em><font color="#008040">NOTE: If both Accept and Content-Type are specified then Accept takes the higher priority.</font></em></strong></p>
<p>What happens if I set the response format in <font color="#0000ff">WebGetAttribute</font>? Say I make it Json as shown below:</p>
<p><pre class="brush: csharp;">
[OperationContract] 
        [WebGet(ResponseFormat=WebMessageFormat.Json)] 
        public int  Add(int i , int j) 
        { 
            // Add your operation implementation here 
            return i+j; 
        }
</pre></p>
<p>The output is driven by Accept Header and is in XML format</p>
<p><pre class="brush: xml;">
&lt;AddResponse xmlns=&quot;http://sankarsanbose.com/test&quot;&gt;&lt;AddResult&gt;2&lt;/AddResult&gt;&lt;/Add 
Response&gt; 
</pre></p>
<p><font color="#008040"><font color="#000000">If I change the headers to JSON obviously the output is JSON.</font></font></p>
<p><font color="#008040"><font color="#000000">Now I am changing the ResponseFormat to XML as shown below:</font></font></p>
<p><pre class="brush: csharp;">
[WebGet(ResponseFormat=WebMessageFormat.Xml)] 
</pre></p>
<p>The request headers are set as shown below:</p>
<p><pre class="brush: csharp;">
request.ContentType = &quot;text/json&quot;; 
request.Accept = &quot;text/json&quot;; 

</pre></p>
<p><font color="#008040">
<p><font color="#008040"><font color="#000000"></font></font><font color="#ff0000">The output surprisingly is just 2 neither JSON nor XML.</font>       </p>
<p> </font>
<p>The request headers are changed back to XML</p>
<p><pre class="brush: csharp;">
request.ContentType = &quot;text/xml&quot;;
request.Accept = &quot;text/xml&quot;;
</pre></p>
<p>Now the output is XML is as shown below:</p>
<p><pre class="brush: xml;"> 
&lt;int xmlns=&quot;http://schemas.microsoft.com/2003/10/Serialization/&quot;&gt;2&lt;/int&gt;
</pre></p>
<p>This is clearly different from structure of the XML generated earlier. Seems to be using the different serializer.</p>
<p>I was not able to articulate the reason for the above two anomalies very clearly. But I think when auto format selection is enabled then providing the ResponseFormat does not make much sense.   </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/389/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/389/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/389/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/389/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/389/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/389/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/389/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/389/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/389/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/389/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/389/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/389/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/389/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/389/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=389&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/10/08/automatic-format-selection-in-wcf-resthttp-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/10/wcfauto_thumb.png" medium="image">
			<media:title type="html">wcfauto</media:title>
		</media:content>
	</item>
		<item>
		<title>Serialization in WCF&#8211;Part I</title>
		<link>http://sankarsan.wordpress.com/2011/09/10/serialization-in-wcfpart-i/</link>
		<comments>http://sankarsan.wordpress.com/2011/09/10/serialization-in-wcfpart-i/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 20:28:26 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Serialization]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/2011/09/10/serialization-in-wcfpart-i/</guid>
		<description><![CDATA[In general, when we work with WCF services Serialization/Deserialization is taken care by the framework under the hood.We rarely bother about what serializer is used and how it works.But it’s important to understand this as the message payload generated is fully controlled by serializer you use. So a better understanding of the serialization process /techniques [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=384&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In general, when we work with WCF services Serialization/Deserialization is taken care by the framework under the hood.We rarely bother about what serializer is used and how it works.But it’s important to understand this as the message payload generated is fully controlled by serializer you use. So a better understanding of the serialization process /techniques and it’s limitations will help us to design the services better.</p>
<p>WCF uses the <font color="#0000ff">System.Runtime.Serialization.DataContractSerializer</font> class for this purpose.The code snippet below uses <font color="#0000ff">DataContractSerializer</font> to serialize Plain CLR Object.</p>
<p><pre class="brush: csharp;">
class Program 
    { 
        static void Main(string[] args) 
        { 
            Customer c = new Customer() { FirstName = &quot;Sankarsan&quot;, LastName = &quot;Bose&quot;, Address = &quot;404/6 NSC BOSE ROAD&quot; }; 
            DataContractSerializer ds = new DataContractSerializer(typeof(Customer)); 
            using(var m = new MemoryStream()) 
            { 
                ds.WriteObject(m,c); 
                m.Seek(0,SeekOrigin.Begin); 
                using (var sr = new StreamReader(m)) 
                { 
                    Console.WriteLine(sr.ReadToEnd()); 
                } 
                
            } 
                   Console.Read(); 
        } 
    } 
    public class Customer 
    { 
        public String FirstName { get; set; } 
        public String LastName { get; set; } 
        public String Address { get; set; }

    }


</pre>  </p>
<p>The output will be the following XML string.</p>
<p><pre class="brush: xml;">
&lt;Customer xmlns=&quot;http://schemas.datacontract.org/2004/07/SerializationDemo&quot; xmlns:i=&quot;'&gt;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;

&lt;Address&gt;404/6 NSC BOSE ROAD&lt;/Address&gt;

&lt;FirstName&gt;Sankarsan&lt;/FirstName&gt;

&lt;LastName&gt;Bose&lt;/LastName&gt;

&lt;/Customer&gt;

</pre> </p>
<p>We need to note the following points:</p>
<p>a) The output is XML format</p>
<p>b) A Plain CLR object(POCO) without any additional decoration(attributes) is serialized with Type Name and Properties as XML Elements (<strong>This is called inferred data contracts</strong>)</p>
<p>c) The <font color="#4bacc6">xmlns</font> attribute by default is <font color="#008000">http://schemas.datacontract.org/2004/07/&lt;&lt;CLR Namespace Name&gt;&gt;</font></p>
<p>d) The ordering of the properties/fields is alphabetically sorted.</p>
<p>e) The XML output does not contain any additional information CLR Datatypes.This is the reason we need to provide the type information while we instantiate the Serializer.</p>
<p>Now if we need to have more fine grained over the serialization output we need to have some mechanism to provide additional inputs to the serializer regarding how we can want to customize our output. The <font color="#0000ff">System.Runtime.Serialization.DataContractAttribute</font> and <font color="#0000ff">System.Runtime.Serialization.DataMemberAttribute</font> provides the same.</p>
<p>We have used these attributes in the Customer class as shown below:</p>
<p><pre class="brush: csharp;">
[DataContract(Name=&quot;customer&quot;,Namespace=&quot;http://sankarsanbose.com/Customer&quot;)] 
    public class Customer 
    { 
        [DataMember(Name=&quot;firstname&quot;,Order=1)] 
        public String FirstName { get; set; } 
        [DataMember(Name = &quot;lastname&quot;, Order = 2)] 
        public String LastName { get; set; } 
        [DataMember(Name = &quot;address&quot;, Order = 3)] 
        public String Address { get; set; }

    }


</pre></p>
<p>The XML output produced is as shown below:</p>
<p><pre class="brush: xml;">
&lt;customer xmlns=&quot;http://sankarsanbose.com/Customer&quot; xmlns:i=&quot;'&gt;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;

&lt;firstname&gt;Sankarsan&lt;/firstname&gt;

&lt;lastname&gt;Bose&lt;/lastname&gt;

&lt;address&gt;404/6 NSC BOSE ROAD&lt;/address&gt;

&lt;/customer&gt;
</pre></p>
<p>Here we have altered the name of the XML Elements, Namespace and ordering of the elements.</p>
<p>We will play around a little bit with this attributes and let’s remove DataMemberAttribute from one of the properties and make another one private.</p>
<p><pre class="brush: csharp;">
[DataContract(Name=&quot;customer&quot;,Namespace=&quot;http://sankarsanbose.com/Customer&quot;)] 
public class Customer 
{ 
    [DataMember(Name=&quot;firstname&quot;,Order=1)] 
    public String FirstName { get; set; } 
    [DataMember(Name = &quot;lastname&quot;, Order = 2)] 
    private String LastName { get; set; } 
    public String Address { get; set; }

} 
</pre> </p>
<p>As the xml output below shows the property(Address) without the DataMemberAttribute is not serialized and the private attribute is serialized with a default NULL value.   </p>
<p><pre class="brush: xml;">
&lt;customer xmlns=&quot;http://sankarsanbose.com/Customer&quot; xmlns:i=&quot;'&gt;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
&lt;firstname&gt;Sankarsan&lt;/firstname&gt;
&lt;lastname i:nil=&quot;true&quot;/&gt;
&lt;/customer&gt;
</pre></p>
<p>The default value can be controlled through the EmitDefaultValue parameter of the DataMember attribute.This is true by default and can be turned off as shown below:</p>
<p><pre class="brush: csharp;">
[DataContract(Name=&quot;customer&quot;,Namespace=&quot;http://sankarsanbose.com/Customer&quot;)]
public class Customer
{
    [DataMember(Name=&quot;firstname&quot;,Order=1)]
    public String FirstName { get; set; }
    [DataMember(Name = &quot;lastname&quot;, Order = 2,EmitDefaultValue=false)]
    private String LastName { get; set; }
    public String Address { get; set; }

}
</pre></p>
<p>So the serialized data now no longer emits the lastname with Null value:</p>
<p><pre class="brush: xml;">
&lt;customer xmlns=&quot;http://sankarsanbose.com/Customer&quot; xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
&lt;firstname&gt;Sankarsan&lt;/firstname&gt;
&lt;/customer&gt;
</pre></p>
<p>This post covers the basics and in the next post we will take a deeper look into the DataContractSerializer class.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/384/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=384&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/09/10/serialization-in-wcfpart-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy Like ConfigSlurper in C# using ExpandoObject</title>
		<link>http://sankarsan.wordpress.com/2011/08/21/groovy-like-configslurper-in-c-using-expandoobject/</link>
		<comments>http://sankarsan.wordpress.com/2011/08/21/groovy-like-configslurper-in-c-using-expandoobject/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 17:54:44 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 4.0]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Expando]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/2011/08/21/groovy-like-configslurper-in-c-using-expandoobject/</guid>
		<description><![CDATA[In Groovy ConfigSlurper is a utility class that is used for reading configuration files written in form of Groovy scripts.Let’s consider the following properties file. We will use a Groovy script to read from this properties file as shown in the snippet below: This is a very simple piece of code which makes use of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=381&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://groovy.codehaus.org/" target="_blank">Groovy</a> <font color="#0000ff">ConfigSlurper</font> is a utility class that is used for reading configuration files written in form of Groovy scripts.Let’s consider the following properties file.</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/08/props.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="props" border="0" alt="props" src="http://sankarsan.files.wordpress.com/2011/08/props_thumb.png?w=443&#038;h=128" width="443" height="128" /></a></p>
<p>We will use a Groovy script to read from this properties file as shown in the snippet below:</p>
<p><pre class="brush: groovy;">
package com.test

import java.util.Properties

class Start {

    static main(args) { 
        def p = new Properties() 
        new File(&quot;test.properties&quot;).withInputStream { 
          stream -&gt; p.load(stream) 
        } 
        println &quot;gfv3.admin.url=&quot; + p[&quot;gfv3.admin.url&quot;] 
  
    }

}


</pre></p>
<p>This is a very simple piece of code which makes use of the<font color="#0000ff"> java.util.Properties</font> class and load the properties file using <font color="#0000ff">java.io.File</font> and it’s associated <font color="#0000ff">InputStream</font> class.Here the properties are accessed as&#160; a map of name/value pairs. This code can be tweaked bit using the <font color="#0000ff">ConfigSlurper</font> class and the values can be accessed as object properties as shown below:</p>
<p><pre class="brush: groovy;">
package com.test

import java.util.Properties

class Start {

    static main(args) { 
        def p = new Properties() 
        new File(&quot;test.properties&quot;).withInputStream { 
          stream -&gt; p.load(stream) 
        } 
        def cfg = new ConfigSlurper().parse(p) 
        println &quot;gfv3.admin.url=&quot; + cfg.gfv3.admin.url 
    
    }

}
</pre>  </p>
<p>We can write a similar ConfigSlurper in C# using the <font color="#0000ff">System.Dynamic.ExpandoObject</font> which allows us to add and remove properties to this object at runtime.ExpandoObject implement a IDictionary and IDynamicMetaObjectProvider interfaces as shown in the definition below:</p>
<p><pre class="brush: csharp;">
public sealed class ExpandoObject : IDynamicMetaObjectProvider,IDictionary&lt;string, Object&gt;, ICollection&lt;KeyValuePair&lt;string, Object&gt;&gt;, IEnumerable&lt;KeyValuePair&lt;string, Object&gt;&gt;, IEnumerable, INotifyPropertyChanged
</pre></p>
<p>We can use the IDictionary implementation to attach properties at runtime as shown below in the ConfigSlurper class.</p>
<p><pre class="brush: csharp;">
public static class ConfigSlurper 
{ 
    public static ExpandoObject  Parse(System.Collections.Specialized.NameValueCollection settings) 
    { 
        var config = new ExpandoObject(); 
        var dictConfig = (config as IDictionary&lt;String, object&gt;); 
        foreach (var k in settings.AllKeys) 
        { 
            dictConfig[k] = settings[k]; 
        } 
        return config; 
    } 
} 
</pre></p>
<p>The config settings are defined as shown below:</p>
<p><pre class="brush: xml;">
&lt;appSettings&gt; 
  &lt;add key=&quot;gfv3AdminUrl&quot; value=&quot;http\://localhost\:4848&quot;/&gt; 
  &lt;add key=&quot;gfv3Root&quot; value=&quot;D\:\\Program Files\\glassfish-3.0.1\\glassfish&quot;/&gt; 
  &lt;add key=&quot;gfv3Port&quot; value=&quot;4848&quot;/&gt; 
  &lt;add key=&quot;gfv3Host&quot; value=&quot;localhost&quot;/&gt; 
  &lt;add key=&quot;gfv3Username&quot; value=&quot;admin&quot;/&gt; 
  &lt;add key=&quot;gfv3Url&quot; value=&quot;http\://localhost\:8080&quot;/&gt; 
&lt;/appSettings&gt; 

</pre></p>
<p>This config can be read using the ConfigSlurper class as:</p>
<p><pre class="brush: csharp;">
static void Main(string[] args)
{
    dynamic config = ConfigSlurper.Parse(ConfigurationManager.AppSettings);
    Console.WriteLine(config.gfv3AdminUrl);
    Console.Read();
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/381/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/381/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/381/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=381&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/08/21/groovy-like-configslurper-in-c-using-expandoobject/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/08/props_thumb.png" medium="image">
			<media:title type="html">props</media:title>
		</media:content>
	</item>
		<item>
		<title>Entity Framework 4.1 Annotations&#8211;Part 1</title>
		<link>http://sankarsan.wordpress.com/2011/06/05/entity-framework-4-1-annotationspart-1/</link>
		<comments>http://sankarsan.wordpress.com/2011/06/05/entity-framework-4-1-annotationspart-1/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 06:18:18 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ADO.NET Entity Framework]]></category>
		<category><![CDATA[Annotations]]></category>
		<category><![CDATA[EF 4.1]]></category>
		<category><![CDATA[ORM]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/2011/06/05/entity-framework-4-1-annotationspart-1/</guid>
		<description><![CDATA[Entity Framework 4.1 has introduced the Code First Approach with it’s Fluent API and Annotations.In this series of posts we will focus on the Annotations part of it and how it can be used to build the domain model and map it to the database. We will use the standard School data model to explain [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=376&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Entity Framework 4.1 has introduced the Code First Approach with it’s Fluent API and Annotations.In this series of posts we will focus on the Annotations part of it and how it can be used to build the domain model and map it to the database.</p>
<p>We will use the standard School data model to explain most of the stuff and take different examples in some of the special cases.The table diagram is shown below:</p>
<p><a href="http://sankarsan.files.wordpress.com/2011/06/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" border="0" alt="image" src="http://sankarsan.files.wordpress.com/2011/06/image_thumb.png?w=508&#038;h=295" width="508" height="295" /></a></p>
<p>We will start with the very basics, i.e. I have POCO and I want to map it to a database table.I need to use the annotations <font color="#0000ff">TableAttribute</font> and <font color="#0000ff">ColumnAttribute</font> under <font color="#0000ff">System.ComponentModel.DataAnnotations</font> as shown below</p>
<p><pre class="brush: csharp;">
[Table(&quot;Course&quot;)] 
   public class Course 
   { 
       [Column(&quot;CourseID&quot;)] 
       public int CourseID { get; set; } 
       [Column(&quot;Title&quot;)] 
       public string Title { get; set; } 
       [Column(&quot;Credits&quot;)] 
       public int Credits { get; set; } 
       [Column(&quot;DepartmentID&quot;)] 
       public int DepartmentID { get; set; } 
              
   }
</pre>  </p>
<p>The <font color="#0000ff">TableAttribute</font> also allows to specify the schema to which this table belongs to. Now the next thing is how to specify the primary key?. We have to use the <font color="#0000ff">KeyAttribute</font> as shown below:</p>
<p><pre class="brush: csharp;">
[Table(&quot;Course&quot;)] 
   public class Course 
   { 
       [Key] 
       [Column(&quot;CourseID&quot;)] 
       public int CourseID { get; set; } 
       [Column(&quot;Title&quot;)] 
       public string Title { get; set; } 
       [Column(&quot;Credits&quot;)] 
       public int Credits { get; set; } 
       [Column(&quot;DepartmentID&quot;)] 
       public int DepartmentID { get; set; } 
               
   }
</pre></p>
<p>In this table the Primary Key is an IDENTITY column automatically generated in the database. We need to use the <font color="#0000ff">DatabaseGeneratedAttribute</font> to specify the same. There are three types of database generation strategy supported by the framework using the <font color="#0000ff">DatabaseGeneratedOption</font> enumeration i.e </p>
<ul>
<li>None </li>
<li>Identity </li>
<li>Computed </li>
</ul>
<p>The completed class definition is shown below:</p>
<p><pre class="brush: csharp;">
[Table(&quot;Course&quot;)] 
   public class Course 
   { 
       [Key] 
       [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)] 
       [Column(&quot;CourseID&quot;)] 
       public int CourseID { get; set; } 
       [Column(&quot;Title&quot;)] 
       public string Title { get; set; } 
       [Column(&quot;Credits&quot;)] 
       public int Credits { get; set; } 
       [Column(&quot;DepartmentID&quot;)] 
       public int DepartmentID { get; set; } 
              
   } 
</pre></p>
<p>Next thing how we can define Composite Keys? In the table CourseInstructor we have both CourseID and InstructorID as Primary Key. This can be easily defined using the KeyAttribute as shown below:</p>
<p><pre class="brush: csharp;">
[Table(&quot;CourseInstructor&quot;)]
    public class CourseInstructor
    {
        [Key]
        [Column(&quot;PersonID&quot;)]
        public int PersonID { get; set; }
        [Column(&quot;CourseID&quot;)]
        [Key]
        public int CourseID { get; set; }
    }
</pre></p>
<p>While executing query on this object we get the following exception</p>
<p><font color="#ff0000"><em>Unable to determine composite primary key ordering for type &#8216;EFAnnoations.CourseInstructor&#8217;. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys.</em></font></p>
<p>We will use the <font color="#0000ff">Order</font> property of <font color="#0000ff">ColumnAttribute</font> as shown below:</p>
<p><pre class="brush: csharp;">
[Table(&quot;CourseInstructor&quot;)]
public class CourseInstructor
{
    [Key]
    [Column(&quot;PersonID&quot;,Order=0)]
    public int PersonID { get; set; }
    [Column(&quot;CourseID&quot;,Order=1)]
    [Key]
    public int CourseID { get; set; }
}
</pre></p>
<p>Next post onwards we will start exploring how we can establish the different types of relationship in our entity model.   </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/376/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/376/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/376/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=376&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/06/05/entity-framework-4-1-annotationspart-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>

		<media:content url="http://sankarsan.files.wordpress.com/2011/06/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Sorting Collections in C#</title>
		<link>http://sankarsan.wordpress.com/2011/05/07/sorting-collections-in-c/</link>
		<comments>http://sankarsan.wordpress.com/2011/05/07/sorting-collections-in-c/#comments</comments>
		<pubDate>Sat, 07 May 2011 21:18:22 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Comparison]]></category>
		<category><![CDATA[IComparer]]></category>
		<category><![CDATA[IComprable]]></category>
		<category><![CDATA[Sort]]></category>

		<guid isPermaLink="false">https://sankarsan.wordpress.com/2011/05/07/sorting-collections-in-c/</guid>
		<description><![CDATA[In this post we will discuss about different techniques of sorting collections of objects in C# using the functions provided by the base class libraries.This is something very common and there different types of provisions in .NET BCL to achieve the same.We will try to discuss the advantages and limitations of each of these approaches. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=369&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post we will discuss about different techniques of sorting collections of objects in C# using the functions provided by the base class libraries.This is something very common and there different types of provisions in .NET BCL to achieve the same.We will try to discuss the advantages and limitations of each of these approaches.</p>
<p>I will start with the most simplest of all the techniques that is implementing the interface <font color="#0000ff">IComparable&lt;T&gt;</font>. The <font color="#0000ff">IComparable&lt;T&gt;</font> has the following methods:</p>
<ul>
<li><strong><font color="#008000">int CompareTo(T other)</font></strong> – This method compares one instance of object of type T with another which is passed as parameter. </li>
</ul>
<p>The following class implements an <font color="#0000ff">IComparable&lt;T&gt;</font> interface as shown below:</p>
<p><pre class="brush: csharp;">
public class Member : IComparable&lt;Member&gt; 
    { 
        public int ID { get; set; } 
        public String FirstName { get; set; } 
        public String LastName { get; set; } 
        public DateTime DateOfJoining { get; set; }


        public int CompareTo(Member other) 
        { 
            return this.ID.CompareTo(other.ID); 
        } 
    }
</pre>  </p>
<p>Here the comparison is done based on the property ID of the member class. The following snippet is used to demonstrate the usage.</p>
<p><pre class="brush: csharp;">
List&lt;Member&gt; ls = new List&lt;Member&gt;() 
                                { 
                                    new Member(){ID=1,FirstName=&quot;John&quot;,LastName=&quot;Doe&quot;}, 
                                    new Member(){ID=3,FirstName=&quot;Allan&quot;,LastName=&quot;Jones&quot;}, 
                                    new Member(){ID=2,FirstName=&quot;Martin&quot;,LastName=&quot;Moe&quot;}, 
                                    new Member(){ID=4,FirstName=&quot;Ludwig&quot;,LastName=&quot;Issac&quot;} 
                                }; 
ls.Sort(); 
ls.ForEach(m =&gt; Console.WriteLine(&quot;Member &quot; + m.FirstName + &quot;:&quot; + m.LastName));
</pre></p>
<p>Here the output will be sorted by ID as shown below:</p>
<p>Member John:Doe    <br />Member Martin:Moe     <br />Member Allan:Jones     <br />Member Ludwig:Issac </p>
<p>Now if we want to sort by other properties as well like FirstName, LastName etc. One crud approach is to create different subclasses as shown below:</p>
<p><pre class="brush: csharp;">
public class MemberByFirstName : Member, IComparable&lt;MemberByFirstName&gt; 
    { 
        public int CompareTo(MemberByFirstName other) 
        { 
            return this.FirstName.CompareTo(other.FirstName); 
        } 
    }
</pre> </p>
<p>Then when we need to sort by say FirstName we will use List of this sub class as shown below:</p>
<p><pre class="brush: csharp;">
List&lt;MemberByFirstName&gt; ls = new List&lt;MemberByFirstName&gt;() 
{ 
            new MemberByFirstName(){ID=1,FirstName=&quot;John&quot;,LastName=&quot;Doe&quot;}, 
            new MemberByFirstName(){ID=3,FirstName=&quot;Allan&quot;,LastName=&quot;Jones&quot;}, 
            new MemberByFirstName(){ID=2,FirstName=&quot;Martin&quot;,LastName=&quot;Moe&quot;}, 
            new MemberByFirstName(){ID=4,FirstName=&quot;Ludwig&quot;,LastName=&quot;Issac&quot;} 
}; 
ls.Sort(); 
ls.ForEach(m =&gt; Console.WriteLine(&quot;Member &quot; + m.FirstName + &quot;:&quot; + m.LastName));
</pre></p>
<p>The output will be alphabetically sorted by FirstName as shown below:</p>
<p>Member Allan:Jones    <br />Member John:Doe     <br />Member Ludwig:Issac     <br />Member Martin:Moe</p>
<p>But this is a cumbersome and rigid approach.Similar stuff can be implemented in a much more cleaner way using the <font color="#0000ff"><strong>IComparer&lt;T&gt;</strong></font> interface.This interface defines the following method:</p>
<ul>
<li><font color="#008000"><strong>int Compare(T x,T y)</strong></font> – This method takes two objects of type T and compares between them. </li>
</ul>
<p>We can implement <font color="#0000ff"><strong>IComparer&lt;T&gt;</strong></font> as shown below:</p>
<p><pre class="brush: csharp;">
public class MemberSorterByLastName : IComparer&lt;Member&gt; 
   {

       public int Compare(Member x, Member y) 
       { 
           return x.LastName.CompareTo(y.LastName); 
       } 
   } 
   public class MemberSorterByFirstName : IComparer&lt;Member&gt; 
   {

       public int Compare(Member x, Member y) 
       { 
           return x.FirstName.CompareTo(y.FirstName); 
       } 
   } 
  
</pre></p>
<p>We can use the method Sort(IComparer comparer) as shown below to sort the List of Member by FirstName and LastName respectively:</p>
<p><pre class="brush: csharp;">
List&lt;Member&gt; ls = new List&lt;Member&gt;() 
                                { 
                                    new Member(){ID=1,FirstName=&quot;John&quot;,LastName=&quot;Doe&quot;}, 
                                    new Member(){ID=3,FirstName=&quot;Allan&quot;,LastName=&quot;Jones&quot;}, 
                                    new Member(){ID=2,FirstName=&quot;Martin&quot;,LastName=&quot;Moe&quot;}, 
                                    new Member(){ID=4,FirstName=&quot;Ludwig&quot;,LastName=&quot;Issac&quot;} 
                                };

ls.Sort(new MemberSorterByFirstName());

ls.ForEach(m =&gt; Console.WriteLine(&quot;Member &quot; + m.FirstName + &quot;:&quot; + m.LastName));

ls.Sort(new MemberSorterByLastName());

ls.ForEach(m =&gt; Console.WriteLine(&quot;Member &quot; + m.FirstName + &quot;:&quot; + m.LastName));
</pre></p>
<p>This approach is clean but has the overhead of creating separate classes for each different sort criteria.This can be achieved much more simply using the <font color="#0000ff">Comparison&lt;T&gt;</font> delegate. The <font color="#0000ff">Comparison&lt;T&gt;</font> delegate has the following signature:</p>
<ul>
<li><font color="#008000"><strong>public delegate int Comparison&lt;in T&gt;(T x,T y)</strong></font> – This is used to compare two objects of generic type T. </li>
</ul>
<p>We can use the <font color="#008000"><strong>Sort (Comparison&lt;T&gt; comparison)</strong></font> method as shown below:</p>
<p><pre class="brush: csharp;">
List&lt;Member&gt; ls = new List&lt;Member&gt;() 
                    { 
                        new Member(){ID=1,FirstName=&quot;John&quot;,LastName=&quot;Doe&quot;}, 
                        new Member(){ID=3,FirstName=&quot;Allan&quot;,LastName=&quot;Jones&quot;}, 
                        new Member(){ID=2,FirstName=&quot;Martin&quot;,LastName=&quot;Moe&quot;}, 
                        new Member(){ID=4,FirstName=&quot;Ludwig&quot;,LastName=&quot;Issac&quot;} 
                    };

ls.Sort((x, y) =&gt; x.FirstName.CompareTo(y.FirstName)); 
ls.ForEach(m =&gt; Console.WriteLine(&quot;Member &quot; + m.FirstName + &quot;:&quot; + m.LastName));

ls.Sort((x, y) =&gt; x.LastName.CompareTo(y.LastName)); 
ls.ForEach(m =&gt; Console.WriteLine(&quot;Member &quot; + m.FirstName + &quot;:&quot; + m.LastName)); 
</pre></p>
<p>By far this approach is the most simplest one. In other languages like Java the first two options are there e.g. Java Comparer interface is similar to IComparable and Comparator interface is similar to IComparer in C# respectively. But Java is yet to have support for Closures so the third approach is still not possible.   </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sankarsan.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sankarsan.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sankarsan.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sankarsan.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sankarsan.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sankarsan.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sankarsan.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sankarsan.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sankarsan.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sankarsan.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sankarsan.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sankarsan.wordpress.com/369/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sankarsan.wordpress.com/369/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sankarsan.wordpress.com/369/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sankarsan.wordpress.com&amp;blog=4205416&amp;post=369&amp;subd=sankarsan&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sankarsan.wordpress.com/2011/05/07/sorting-collections-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4c5994186de8b37552f4d055aab403e5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sankarsan</media:title>
		</media:content>
	</item>
	</channel>
</rss>
