<?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>It Works On My Machine</title>
	<atom:link href="http://itworksonmymachine.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://itworksonmymachine.wordpress.com</link>
	<description></description>
	<lastBuildDate>Tue, 23 Apr 2013 07:35:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='itworksonmymachine.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>It Works On My Machine</title>
		<link>http://itworksonmymachine.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://itworksonmymachine.wordpress.com/osd.xml" title="It Works On My Machine" />
	<atom:link rel='hub' href='http://itworksonmymachine.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Dependency Injection in ASP.NET MVC3</title>
		<link>http://itworksonmymachine.wordpress.com/2011/02/11/dependency-injection-in-asp-net-mvc3/</link>
		<comments>http://itworksonmymachine.wordpress.com/2011/02/11/dependency-injection-in-asp-net-mvc3/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 03:46:05 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[DefaultControllerFactory]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[IDependencyResolver]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/?p=87</guid>
		<description><![CDATA[What dependency injection means is that instead of writing code like this in your controller private IBlogService _BlogService; public BlogController() { _BlogService = new BlogService(); } you write code like this private IBlogService _BlogService; public BlogController(IBlogService blogService) { _BlogService = blogService; } the benefits of dependency injection are your classes are not tightly coupled, are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=87&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>What dependency injection means is that instead of writing code like this in your controller</p>
<div id="codeSnippetWrapper" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:'Courier New', courier, monospace;direction:ltr;max-height:200px;font-size:8pt;overflow:auto;cursor:text;border:silver 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:'Courier New', courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">private</span> IBlogService _BlogService;
<span style="color:#0000ff;">public</span> BlogController()
{
    _BlogService = <span style="color:#0000ff;">new</span> BlogService();
}</pre>
</div>
<p>you write code like this</p>
<div id="codeSnippetWrapper" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:'Courier New', courier, monospace;direction:ltr;max-height:200px;font-size:8pt;overflow:auto;cursor:text;border:silver 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:'Courier New', courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">private</span> IBlogService _BlogService;
<span style="color:#0000ff;">public</span> BlogController(IBlogService blogService)
{
    _BlogService = blogService;
}</pre>
</div>
<p>the benefits of dependency injection are your classes are not tightly coupled, are more testable, and really is pluggable.</p>
<p>To enable dependency injection into your controllers in ASP.NET MVC2 you had to create a new class derived from DefaultControllerFactory and override the GetControllerInstance method to create the controller using your dependency injection container e.g.</p>
<div id="codeSnippetWrapper" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:'Courier New', courier, monospace;direction:ltr;max-height:200px;font-size:8pt;overflow:auto;cursor:text;border:silver 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:'Courier New', courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> IoCControllerFactory : DefaultControllerFactory
{

    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        <span style="color:#0000ff;">return</span> (IController)_container.GetInstance(controllerType);
    }
}</pre>
</div>
<p>and then you had to register this controller factory as the default in the Application_Start event in the global.ascx file</p>
<div id="codeSnippetWrapper" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:'Courier New', courier, monospace;direction:ltr;max-height:200px;font-size:8pt;overflow:auto;cursor:text;border:silver 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:'Courier New', courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">void</span> Application_Start()
{

    ControllerBuilder.Current.SetControllerFactory(<span style="color:#0000ff;">typeof</span>(IoCControllerFactory));
    ...
}</pre>
</div>
<p>The problem here is that you need to create a separate custom class for the model binders, and for custom model metadata.</p>
<p>ASP.NET MVC 3 makes things easier to inject dependencies by introducing a new interface IDependencyResolver. The benefit here is that this DependencyResolver is responsible to resolve dependencies not only for the controller but also for the services (repository, logger etc.) consumed by the controller, view engine, view binders, and the model and model metadata.</p>
<p>The interface has two methods</p>
<div id="codeSnippetWrapper" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:'Courier New', courier, monospace;direction:ltr;max-height:200px;font-size:8pt;overflow:auto;cursor:text;border:silver 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:'Courier New', courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">object</span> GetService(Type serviceType);
IEnumerable&lt;<span style="color:#0000ff;">object</span>&gt; GetServices(Type serviceType);</pre>
</div>
<p>which return either a single object or a list of object of serviceType. If a type cannot be resolved by the dependency resolver then ASP.NET MVC3 expects the resolver to return null.</p>
<p>If the dependency resolver returns null then ASP.NET MVC3 will fall back to the default factory class to instantiate the interface object.</p>
<p>To use this new interface simply create a new class which implements this interface</p>
<div id="codeSnippetWrapper" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:'Courier New', courier, monospace;direction:ltr;max-height:200px;font-size:8pt;overflow:auto;cursor:text;border:silver 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:'Courier New', courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> UnityDependencyResolver : IDependencyResolver
{
    <span style="color:#0000ff;">private</span> IUnityContainer _contianer;
    UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }

    <span style="color:#cc6633;">#region</span> IDependencyResolver Members
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">object</span> GetService(Type serviceType)
    {
        <span style="color:#0000ff;">try</span>
        {
            <span style="color:#0000ff;">return</span> _container.GetInstance(serviceType);
        }
        <span style="color:#0000ff;">catch (ResolutionFailedException)</span>
        {
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;
        }
    }
    <span style="color:#0000ff;">public</span> IEnumerable&lt;<span style="color:#0000ff;">object</span>&gt; GetServices(Type serviceType)
    {
        <span style="color:#0000ff;">try</span>
        {
            <span style="color:#0000ff;">return</span> _container.GetAllInstances(serviceType);
        }
        <span style="color:#0000ff;">catch (ResolutionFailedException)</span>
        {
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;
        }
    }
    <span style="color:#cc6633;">#endregion</span>
}</pre>
</div>
<p>I’m using Unity as my dependency container and since Unity throws a ResolutionFailedException exception if it cannot resolve a  type we need to wrap it in a try/catch block and return null in case of exception.</p>
<p>Just like the controller factory we need to register our dependency resolver at Application_Start event in our global.ascx</p>
<div id="codeSnippetWrapper" style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:'Courier New', courier, monospace;direction:ltr;max-height:200px;font-size:8pt;overflow:auto;cursor:text;border:silver 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="text-align:left;line-height:12pt;background-color:#f4f4f4;width:100%;font-family:'Courier New', courier, monospace;direction:ltr;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">void</span> Application_Start()
{
    var container = <span style="color:#0000ff;">new</span> UnityContainer()
        .LoadConfiguration();

    DependencyResolver.SetResolver(container);
    ...
}</pre>
</div>
<p>You can either configure your container at runtime or via the .config file. I prefer the .config approach because then I can easily take my application to any environment (DEv vs QA) and switch out my EmailLogger with NullLogger or as required by changing the mapping in the .config file.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/87/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=87&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2011/02/11/dependency-injection-in-asp-net-mvc3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>
	</item>
		<item>
		<title>SQL to LINQ Cheat Sheet</title>
		<link>http://itworksonmymachine.wordpress.com/2009/09/27/sql-to-linq-cheat-sheet/</link>
		<comments>http://itworksonmymachine.wordpress.com/2009/09/27/sql-to-linq-cheat-sheet/#comments</comments>
		<pubDate>Sun, 27 Sep 2009 01:18:20 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2009/09/27/sql-to-linq-cheat-sheet</guid>
		<description><![CDATA[If you are already working with SQL and are familiar with SQL queries then you may find you at time are thinking of converting SQL syntax to LINQ syntax when writing LINQ. Following cheat sheet should help you with some of the common queries   SQL LINQ Lambda SELECT * FROM HumanResources.Employee from e in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=4&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!470" class="bvMsg">
<p>If you are already working with SQL and are familiar with SQL queries then you may find you at time are thinking of converting SQL syntax to LINQ syntax when writing LINQ. Following cheat sheet should help you with some of the common queries</p>
<p style="font-family:calibri;font-size:11pt;margin:0;"> </p>
<div style="direction:ltr;">
<table style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;border-collapse:collapse;direction:ltr;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;color:#444444;font-size:11pt;font-weight:bold;margin:0;">SQL</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;color:#444444;font-size:11pt;font-weight:bold;margin:0;">LINQ</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;font-weight:bold;margin:0;">Lambda</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT *</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Select (e =&gt; e)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.LoginID, e.JobTitle</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;e.LoginID, e.JobTitle&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Select (<br /><span>      </span>e =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>LoginID = e.LoginID, <br /><span>            </span>JobTitle = e.JobTitle<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.LoginID AS ID, e.JobTitle AS Title</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;ID = e.LoginID, Title = e.JobTitle&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Select (<br /><span>      </span>e =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>ID = e.LoginID, <br /><span>            </span>Title = e.JobTitle<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT DISTINCT e.JobTitle</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">(from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e.JobTitle).Distinct()</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Select (e =&gt; e.JobTitle)<br /><span>   </span>.Distinct ()</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.*</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">WHERE e.LoginID = &#8216;test&#8217;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">where e.LoginID == &quot;test&quot;</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Where (e =&gt; (e.LoginID == &quot;test&quot;))</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.*</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">WHERE e.LoginID = &#8216;test&#8217; AND e.SalariedFlag = 1</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">where e.LoginID == &quot;test&quot; &amp;&amp; e.SalariedFlag</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Where (e =&gt; ((e.LoginID == &quot;test&quot;) &amp;&amp; e.SalariedFlag))</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.*<br />FROM HumanResources.Employee AS e</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">WHERE e.VacationHours &gt;= 2 AND e.VacationHours &lt;= 10</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">where e.VacationHours &gt;= 2 &amp;&amp; e.VacationHours &lt;= 10</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Where (e =&gt; (((Int32)(e.VacationHours) &gt;= 2) &amp;&amp; ((Int32)(e.VacationHours) &lt;= 10)))</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.*</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e<br />ORDER BY e.NationalIDNumber</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">orderby e.NationalIDNumber</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.OrderBy (e =&gt; e.NationalIDNumber)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.*</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">ORDER BY e.HireDate DESC, e.NationalIDNumber</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">orderby e.HireDate descending, e.NationalIDNumber</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.OrderByDescending (e =&gt; e.HireDate)<br /><span>   </span>.ThenBy (e =&gt; e.NationalIDNumber)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.*<br />FROM HumanResources.Employee AS e</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">WHERE e.JobTitle LIKE &#8216;Vice%&#8217; OR SUBSTRING(e.JobTitle, 0, 3) = &#8216;Pro&#8217;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">where e.JobTitle.StartsWith(&quot;Vice&quot;) || e.JobTitle.Substring(0, 3) == &quot;Pro&quot;</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.Where (e =&gt; (e.JobTitle.StartsWith (&quot;Vice&quot;) || (e.JobTitle.Substring (0, 3) == &quot;Pro&quot;)))</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT SUM(e.VacationHours)</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;"> </p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">Employees.Sum(e =&gt; e.VacationHours);</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT COUNT(*)</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;"> </p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">Employees.Count();</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT SUM(e.VacationHours) AS TotalVacations, e.JobTitle</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">GROUP BY e.JobTitle</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">group e by e.JobTitle into g</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;JobTitle = g.Key, TotalVacations = g.Sum(e =&gt; e.VacationHours)&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.GroupBy (e =&gt; e.JobTitle)<br /><span>   </span>.Select (<br /><span>      </span>g =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>JobTitle = g.Key, <br /><span>            </span>TotalVacations = g.Sum (e =&gt; (Int32)(e.VacationHours))<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT e.JobTitle, SUM(e.VacationHours) AS TotalVacations</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM HumanResources.Employee AS e</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">GROUP BY e.JobTitle</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">HAVING e.COUNT(*) &gt; 2</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from e in Employees</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">group e by e.JobTitle into g</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">where g.Count() &gt; 2</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;JobTitle = g.Key, TotalVacations = g.Sum(e =&gt; e.VacationHours)&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Employees<br /><span>   </span>.GroupBy (e =&gt; e.JobTitle)<br /><span>   </span>.Where (g =&gt; (g.Count () &gt; 2))<br /><span>   </span>.Select (<br /><span>      </span>g =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>JobTitle = g.Key, <br /><span>            </span>TotalVacations = g.Sum (e =&gt; (Int32)(e.VacationHours))<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT *</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM Production.Product AS p, Production.ProductReview AS pr</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from p in Products</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">from pr in ProductReviews</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;p, pr&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Products<br /><span>   </span>.SelectMany (<br /><span>      </span>p =&gt; ProductReviews, <br /><span>      </span>(p, pr) =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>p = p, <br /><span>            </span>pr = pr<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT *</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM Production.Product AS p</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">INNER JOIN Production.ProductReview AS pr ON p.ProductID = pr.ProductID</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from p in Products</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">join pr in ProductReviews on p.ProductID equals pr.ProductID</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;p, pr&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Products<br /><span>   </span>.Join (<br /><span>      </span>ProductReviews, <br /><span>      </span>p =&gt; p.ProductID, <br /><span>      </span>pr =&gt; pr.ProductID, <br /><span>      </span>(p, pr) =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>p = p, <br /><span>            </span>pr = pr<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT *</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM Production.Product AS p</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">INNER JOIN Production.ProductCostHistory AS pch ON p.ProductID = pch.ProductID AND p.SellStartDate = pch.StartDate</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from p in Products</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">join pch in ProductCostHistories on new &#123;p.ProductID, StartDate = p.SellStartDate&#125; equals new &#123;pch.ProductID, StartDate = pch.StartDate&#125;</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;p, pch&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Products<br /><span>   </span>.Join (<br /><span>      </span>ProductCostHistories, <br /><span>      </span>p =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>ProductID = p.ProductID, <br /><span>            </span>StartDate = p.SellStartDate<br /><span>         </span>&#125;, <br /><span>      </span>pch =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>ProductID = pch.ProductID, <br /><span>            </span>StartDate = pch.StartDate<br /><span>         </span>&#125;, <br /><span>      </span>(p, pch) =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>p = p, <br /><span>            </span>pch = pch<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT *</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM Production.Product AS p</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">LEFT OUTER JOIN Production.ProductReview AS pr ON p.ProductID = pr.ProductID</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from p in Products</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">join pr in ProductReviews on p.ProductID equals pr.ProductID</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">into prodrev</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;p, prodrev&#125;</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Products<br /><span>   </span>.GroupJoin (<br /><span>      </span>ProductReviews, <br /><span>      </span>p =&gt; p.ProductID, <br /><span>      </span>pr =&gt; pr.ProductID, <br /><span>      </span>(p, prodrev) =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>p = p, <br /><span>            </span>prodrev = prodrev<br /><span>         </span>&#125;<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT p.ProductID AS ID</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM Production.Product AS p</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">UNION</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT pr.ProductReviewID</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM Production.ProductReview AS pr</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">(from p in Products</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;ID = p.ProductID&#125;).Union(</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">from pr in ProductReviews </p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select new &#123;ID = pr.ProductReviewID&#125;)</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Products<br /><span>   </span>.Select (<br /><span>      </span>p =&gt; <br /><span>         </span>new<span>  </span><br /><span>         </span>&#123;<br /><span>            </span>ID = p.ProductID<br /><span>         </span>&#125;<br /><span>   </span>)<br /><span>   </span>.Union (<br /><span>      </span>ProductReviews<br /><span>         </span>.Select (<br /><span>            </span>pr =&gt; <br /><span>               </span>new<span>  </span><br /><span>               </span>&#123;<br /><span>                  </span>ID = pr.ProductReviewID<br /><span>               </span>&#125;<br /><span>         </span>)<br /><span>   </span>)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT TOP (10) *</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM Production.Product AS p</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">WHERE p.StandardCost &lt; 100</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">(from p in Products</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">where p.StandardCost &lt; 100</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select p).Take(10)</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Products<br /><span>   </span>.Where (p =&gt; (p.StandardCost &lt; 100))<br /><span>   </span>.Take (10)</p>
</td>
</tr>
<tr>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.711in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">SELECT *</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">FROM [Production].[Product] AS p</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">WHERE p.ProductID IN(</p>
<p style="font-family:calibri;font-size:11pt;margin:0;"><span>    </span>SELECT pr.ProductID</p>
<p style="font-family:calibri;font-size:11pt;margin:0;"><span>    </span>FROM [Production].[ProductReview] AS [pr]</p>
<p style="font-family:calibri;font-size:11pt;margin:0;"><span>    </span>WHERE pr.[Rating] = 5</p>
<p style="font-family:calibri;font-size:11pt;margin:0;"><span>    </span>)</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:3.414in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:calibri;font-size:11pt;margin:0;">from p in Products</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">where (from pr in ProductReviews</p>
<p style="font-family:calibri;font-size:11pt;margin:0 0 0 .375in;">where pr.Rating == 5</p>
<p style="font-family:calibri;font-size:11pt;margin:0 0 0 .375in;">select pr.ProductID).Contains(p.ProductID)</p>
<p style="font-family:calibri;font-size:11pt;margin:0;">select p</p>
</td>
<td style="border-bottom:#a3a3a3 1pt solid;border-left:#a3a3a3 1pt solid;width:4.593in;vertical-align:top;border-top:#a3a3a3 1pt solid;border-right:#a3a3a3 1pt solid;padding:4pt;">
<p style="font-family:verdana;font-size:11pt;margin:0;">Products<br /><span>   </span>.Where (<br /><span>      </span>p =&gt; <br /><span>         </span>ProductReviews<br /><span>            </span>.Where (pr =&gt; (pr.Rating == 5))<br /><span>            </span>.Select (pr =&gt; pr.ProductID)<br /><span>            </span>.Contains (p.ProductID)<br /><span>   </span>)</p>
</td>
</tr>
</tbody>
</table>
</div>
<p style="font-family:calibri;font-size:11pt;margin:0;"> </p>
<p style="font-family:calibri;font-size:11pt;margin:0;">Also, here is an excellent LINQ query comprehension diagram <a href="http://www.albahari.com/nutshell/linqsyntax.emf">http://www.albahari.com/nutshell/linqsyntax.emf</a></p>
<p></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!470.entry"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!470.entry" /></a></p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=4&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2009/09/27/sql-to-linq-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!470.entry" medium="image" />
	</item>
		<item>
		<title>Select top n rows from a table for each group</title>
		<link>http://itworksonmymachine.wordpress.com/2009/03/06/select-top-n-rows-from-a-table-for-each-group/</link>
		<comments>http://itworksonmymachine.wordpress.com/2009/03/06/select-top-n-rows-from-a-table-for-each-group/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 17:18:17 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ROW_NUMBER()]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2009/03/06/select-top-n-rows-from-a-table-for-each-group</guid>
		<description><![CDATA[We have a retail shop online and with just 2 weeks of our website launch we already have close to 30 orders. Now of course marketing wanted to get some ads up on the site to derive more orders and one for the reports was to get the top two products from each manufacturer which [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=5&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!366" class="bvMsg">
<p>We have a retail shop online and with just 2 weeks of our website launch we already have close to 30 orders. Now of course marketing wanted to get some ads up on the site to derive more orders and one for the reports was to get the top two products from each manufacturer which have the best promotional price. </p>
<p>A GROU BY clause immediately comes to mind for the above scenario, but SQL 2005/2008 offer a much better solution. </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">SELECT</span>    
    ProductId,
    MfgPartNumber,
    DescriptionText,
    MfgListPrice,
    SellPrice,
    SavingsPercentage
<span style="color:#0000ff;">FROM</span>    (
    <span style="color:#0000ff;">SELECT</span>
        ROW_NUMBER() <span style="color:#0000ff;">OVER</span>(PARTITION <span style="color:#0000ff;">BY</span> P.MfgCode <span style="color:#0000ff;">ORDER</span> <span style="color:#0000ff;">BY</span> (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">DESC</span>) <span style="color:#0000ff;">AS</span> RowNumber,
        P.ProductId,
        P.MfgPartNumber,
        P.DescriptionText,
        P.MfgListPrice,
        PR.SellPrice,
        (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">AS</span> SavingsPercentage
    <span style="color:#0000ff;">FROM</span>    Product P
    <span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    Price PR
        <span style="color:#0000ff;">ON</span>    P.ProductId = PR.ProductId
    <span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    SpecialPricingXRef SP
        <span style="color:#0000ff;">ON</span>    PR.PriceGroupId = SP.PriceGroupId
    <span style="color:#0000ff;">WHERE</span>    SP.PricingType = <span style="color:#006080;">'Promo'</span>
        <span style="color:#0000ff;">AND</span>    P.MfgListPrice &gt; PR.SellPrice
    ) <span style="color:#0000ff;">AS</span> InnerTable
<span style="color:#0000ff;">WHERE</span>    RowNumber &lt; 3
<span style="color:#0000ff;">ORDER</span> <span style="color:#0000ff;">BY</span>    SavingsPercentage <span style="color:#0000ff;">DESC</span>;</pre>
</div>
<p>Aside from normal use of the ROW_NUMBER() function to generate sequence numbers for the result set the above is the perfect scenario where the ROW_NUMBER() function is really useful. ROW_NUMBER() function creates a new column in the result set with a unique / incremental number for each row. If the PARTITION BY clause (think of a partition as a category or group) is also specified then the sequence number of a row is reset to 1 for each new partition / category. </p>
<p>Lets dissect the above query; following query returns all the products which have a promo price record with a RowNumber incremented for each row. I’ll get to why we need the RowNumber in our query later. </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">SELECT</span>
    ROW_NUMBER() <span style="color:#0000ff;">OVER</span>(<span style="color:#0000ff;">ORDER</span> <span style="color:#0000ff;">BY</span> (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">DESC</span>) <span style="color:#0000ff;">AS</span> RowNumber,
    P.ProductId,
    P.MfgPartNumber,
    P.DescriptionText,
    P.MfgListPrice,
    PR.SellPrice,
    (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">AS</span> SavingsPercentage
<span style="color:#0000ff;">FROM</span>    Product P
<span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    Price PR
    <span style="color:#0000ff;">ON</span>    P.ProductId = PR.ProductId
<span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    SpecialPricingXRef SP
    <span style="color:#0000ff;">ON</span>    PR.PriceGroupId = SP.PriceGroupId
<span style="color:#0000ff;">WHERE</span>    SP.PricingType = <span style="color:#006080;">'Promo'</span>
    <span style="color:#0000ff;">AND</span>    P.MfgListPrice &gt; PR.SellPrice</pre>
</div>
<p>Adding the PARTITION BY clause to the above changes the output slightly. When the PARTITION BY clause is also specified the sequence number generated by ROW_NUMBER() is reset to 1 for each new partition. In concept the PARTITION BY clause is similar to a GROUP BY except it only applies to the function and not the select as a whole. </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">SELECT</span>
    ROW_NUMBER() <span style="color:#0000ff;">OVER</span>(PARTITION <span style="color:#0000ff;">BY</span> P.MfgCode <span style="color:#0000ff;">ORDER</span> <span style="color:#0000ff;">BY</span> (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">DESC</span>) <span style="color:#0000ff;">AS</span> RowNumber,
    P.ProductId,
    P.MfgPartNumber,
    P.DescriptionText,
    P.MfgListPrice,
    PR.SellPrice,
    (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">AS</span> SavingsPercentage
<span style="color:#0000ff;">FROM</span>    Product P
<span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    Price PR
    <span style="color:#0000ff;">ON</span>    P.ProductId = PR.ProductId
<span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    SpecialPricingXRef SP
    <span style="color:#0000ff;">ON</span>    PR.PriceGroupId = SP.PriceGroupId
<span style="color:#0000ff;">WHERE</span>    SP.PricingType = <span style="color:#006080;">'Promo'</span>
    <span style="color:#0000ff;">AND</span>    P.MfgListPrice &gt; PR.SellPrice</pre>
</div>
<p>The where clause in our outer select is just filtering the results so that only those rows with RowNumber less than 3 are returned. Recall from our previous query that RowNumber is reset to 1 for each manufacturer; so to get just the top 2 rows for each manufacturer we need to get rows where RowNumber is 1 and 2 (&lt; 3). The result is the list of 2 rows with highest savings for each manufacturer… simple really. </p>
<p>P.S. If you prefer Common Table Expressions then you can rewrite the query to: </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">WITH</span> InnerTable <span style="color:#0000ff;">AS</span>(
    <span style="color:#0000ff;">SELECT</span>
        ROW_NUMBER() <span style="color:#0000ff;">OVER</span>(PARTITION <span style="color:#0000ff;">BY</span> P.MfgCode <span style="color:#0000ff;">ORDER</span> <span style="color:#0000ff;">BY</span> (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">DESC</span>) <span style="color:#0000ff;">AS</span> RowNumber,
        P.ProductId, 
        P.MfgPartNumber,
        P.DescriptionText,
        P.MfgListPrice,
        PR.SellPrice,
        (P.MfgListPrice - PR.SellPrice) / P.MfgListPrice <span style="color:#0000ff;">AS</span> SavingsPercentage
    <span style="color:#0000ff;">FROM</span>    Product P
    <span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    Price PR
        <span style="color:#0000ff;">ON</span>    P.ProductId = PR.ProductId
    <span style="color:#0000ff;">INNER</span> <span style="color:#0000ff;">JOIN</span>    SpecialPricingXRef SP
        <span style="color:#0000ff;">ON</span>    PR.PriceGroupId = SP.PriceGroupId
    <span style="color:#0000ff;">WHERE</span>    SP.PricingType = <span style="color:#006080;">'Promo'</span>
        <span style="color:#0000ff;">AND</span>    P.MfgListPrice &gt; PR.SellPrice
) 

<span style="color:#0000ff;">SELECT</span>    ProductId,
    MfgPartNumber,
    DescriptionText,
    MfgListPrice,
    SellPrice,
    SavingsPercentage
<span style="color:#0000ff;">FROM</span>    InnerTable
<span style="color:#0000ff;">WHERE</span>    RowNumber &lt;= 3
<span style="color:#0000ff;">ORDER</span> <span style="color:#0000ff;">BY</span>    SavingsPercentage <span style="color:#0000ff;">DESC</span>;

</pre>
</div>
<p>the query plan for sub query vs CTE is the same so its all a matter of choice and readability. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!366.entry"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!366.entry" /></a></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=5&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2009/03/06/select-top-n-rows-from-a-table-for-each-group/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!366.entry" medium="image" />
	</item>
		<item>
		<title>Caching Application Block and database backing store</title>
		<link>http://itworksonmymachine.wordpress.com/2009/02/06/caching-application-block-and-database-backing-store/</link>
		<comments>http://itworksonmymachine.wordpress.com/2009/02/06/caching-application-block-and-database-backing-store/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 04:31:46 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Enterprise Library]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2009/02/06/caching-application-block-and-database-backing-store</guid>
		<description><![CDATA[Caching can help to overcome some of the challenges associated with enterprise-scale distributed web applications: Performance &#8211; Caching improves application performance by storing relevant data as close as possible to the data consumer. This avoids repetitive data creation, processing and transportation Scalability &#8211; Storing information in a cache helps save resources and increases scalability as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=6&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!344" class="bvMsg">
<p>Caching can help to overcome some of the challenges associated with enterprise-scale distributed web applications: </p>
<ul>
<li>Performance &#8211; Caching improves application performance by storing relevant data as close as possible to the data consumer. This avoids repetitive data creation, processing and transportation
<li>Scalability &#8211; Storing information in a cache helps save resources and increases scalability as the demands on the application increase
<li>Availability &#8211; By storing data in a local cache, the application may be able to survive system failures such as network latency, web service problems, and hardware failures</ul>
<p>Out of the box ASP.NET provides three primary forms of caching: </p>
<ul>
<li>Page Level output caching &#8211; A copy of the HTML that was sent in response to a request is kept in memory and subsequent request are then sent the cached output until the cache expires. This can result in large performance gains as sending the cached output is always very fast and fairly constant
<li>User Control level output caching (fragment caching) &#8211; Page level output caching may not be feasible in cases where certain parts of the page are customized for the user. Yet, there may be other parts of the page e.g. menus and layout elements which are common to the entire application. The cached controls can be configured to vary based on some set property or any of the variations supported by page level caching. All pages using the same controls share the same cached entries for these controls.
<li>And the Cache API &#8211; The real power of caching is exposed via the Cache object. ASP.NET includes an easy-to-use caching mechanism that can be used to store objects in memory that require a lot of server resources. The .NET Framework includes the ASP.NET cache in the System.Web namespace which can be accessed through the System.Web.HttpContext.Cache object. WinForm applications can also make use of this Cache object by referencing the System.Web assembly and can access it through the System.Web.HttpRuntime.Cache object. Instances are private to each application and the lifetime is tied to the corresponding application.</li>
</ul>
<p>By using the Caching Application Block we can write a consistent form of code to implement caching in any application component, be it the web UI, a Windows service, a WinForm desktop application, or a web service. The Caching Application Block is optimized for performance and is both thread safe and exception safe. </p>
<p>The Caching Application Block works with ASP.NET cache and provides a number of features that are not available to the ASP.NET cache such as: </p>
<ul>
<li>The ability to use a persistent backing store &#8211; both isolated storage and database backing store
<li>The ability to encrypt a cache item&#8217;s data &#8211; this works only when using a persistent backing store
<li>Multiple methods of setting expiration times &#8211; absolute time, sliding time, extended time format, file dependency, or never expires
<li>The core settings are described in configuration files and can be changed without recompilation of the project
<li>Can be extended to create your own expiration policies and storage mechanisms</ul>
<p>To use the Caching Application Block you need to add references of the following assemblies to your project: </p>
<ul>
<li>Microsoft.Practices.EnterpriseLibrary.Common
<li>Microsoft.Practices.EnterpriseLibrary.Caching</ul>
<p>The following namespaces need to  be included in the classes that use the Caching Block: </p>
<ul>
<li>Microsoft.Practices.EnterpriseLibrary.Caching
<li>Microsoft.Practices.EnterpriseLibrary.Caching.Expirations
<li>Microsoft.Practices.EnterpriseLibrary.Common</li>
</ul>
<p>If there is a requirement for a persistent backing store then the data access block needs to be included: </p>
<ul>
<li>Microsoft.Practices.EnterpriseLibrary.Data
<li>Microsoft.Practices.EnterpriseLibrary.Caching.database</ul>
<p>If  there is a requirement to encrypt data in the persistent backing store then the encryption block needs to be included: </p>
<ul>
<li>Microsoft.Practices.EnterpriseLibrary.Security.Cryptography</ul>
<h2>Configuration the Cache Block </h2>
<h3>In Memory Cache </h3>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">configSections</span><span style="color:#0000ff;">&gt;</span> 

         <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">section</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;cachingConfiguration&quot;</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">configSections</span><span style="color:#0000ff;">&gt;</span> 

<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">cachingConfiguration</span><span style="color:#0000ff;">&gt;</span> 

          <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">cacheManagers</span><span style="color:#0000ff;">&gt;</span> 

                    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">expirationPollFrequencyInSeconds</span><span style="color:#0000ff;">=&quot;60&quot;</span> <span style="color:#ff0000;">maximumElementsInCacheBeforeScavenging</span><span style="color:#0000ff;">=&quot;10&quot;</span> <span style="color:#ff0000;">numberToRemoveWhenScavenging</span><span style="color:#0000ff;">=&quot;5&quot;</span> <span style="color:#ff0000;">backingStoreName</span><span style="color:#0000ff;">=&quot;Null Storage&quot;</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;Prices&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

          <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">cacheManagers</span><span style="color:#0000ff;">&gt;</span> 

          <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">backingStores</span><span style="color:#0000ff;">&gt;</span> 

                    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">encryptionProviderName</span><span style="color:#0000ff;">=&quot;&quot;</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations .NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;Null Storage&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

          <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">backingStores</span><span style="color:#0000ff;">&gt;</span> 

<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">cachingConfiguration</span><span style="color:#0000ff;">&gt;</span> 
</pre>
</div>
<h3>Cache Using Backing Store</h3>
<p>Use the database backing store provider when deploying your application on a web farm on multiple computers or on multiple processes on the same machine scenario. To use the database backing store you need to first create the cache database on SQL Server. The script to do this can be found in &lt;Enterprise Library Source Dir&gt;\App Blocks\Src\Caching\Database\Scripts. </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">configSections</span><span style="color:#0000ff;">&gt;</span> 

         <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">section</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;dataConfiguration&quot;</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

         <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">section</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;cachingConfiguration&quot;</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">configSections</span><span style="color:#0000ff;">&gt;</span> 

<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">dataConfiguration</span> <span style="color:#ff0000;">defaultDatabase</span><span style="color:#0000ff;">=&quot;Northwind&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">connectionStrings</span><span style="color:#0000ff;">&gt;</span> 

         <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;CacheDSN&quot;</span> <span style="color:#ff0000;">connectionString</span><span style="color:#0000ff;">=&quot;Data Source=(local);Initial Catalog=Caching;Integrated Security=True;User Instance=False&quot;</span> <span style="color:#ff0000;">providerName</span><span style="color:#0000ff;">=&quot;System.Data.SqlClient&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;Northwind&quot;</span> <span style="color:#ff0000;">connectionString</span><span style="color:#0000ff;">=&quot;Data Source=(local);Initial Catalog=Northwind;Integrated Security=True&quot;</span> <span style="color:#ff0000;">providerName</span><span style="color:#0000ff;">=&quot;System.Data.SqlClient&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">connectionStrings</span><span style="color:#0000ff;">&gt;</span> 

<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">cachingConfiguration</span> <span style="color:#ff0000;">defaultCacheManager</span><span style="color:#0000ff;">=&quot;Customers&quot;</span><span style="color:#0000ff;">&gt;</span> 

         <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">cacheManagers</span><span style="color:#0000ff;">&gt;</span> 

                 <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">expirationPollFrequencyInSeconds</span><span style="color:#0000ff;">=&quot;60&quot;</span> <span style="color:#ff0000;">maximumElementsInCacheBeforeScavenging</span><span style="color:#0000ff;">=&quot;11000&quot;</span> <span style="color:#ff0000;">numberToRemoveWhenScavenging</span><span style="color:#0000ff;">=&quot;10&quot;</span> <span style="color:#ff0000;">backingStoreName</span><span style="color:#0000ff;">=&quot;DataStorage&quot;</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;Customers&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

         <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">cacheManagers</span><span style="color:#0000ff;">&gt;</span> 

         <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">backingStores</span><span style="color:#0000ff;">&gt;</span> 

                 <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">databaseInstanceName</span><span style="color:#0000ff;">=&quot;CacheDSN&quot;</span> <span style="color:#ff0000;">partitionName</span><span style="color:#0000ff;">=&quot;MyFirstCacheApp&quot;</span> <span style="color:#ff0000;">encryptionProviderName</span><span style="color:#0000ff;">=&quot;&quot;</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.EnterpriseLibrary.Caching.Database.DataBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;DataStorage&quot;</span> <span style="color:#0000ff;">/&gt;</span> 

         <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">backingStores</span><span style="color:#0000ff;">&gt;</span> 

<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">cachingConfiguration</span><span style="color:#0000ff;">&gt;</span> 
</pre>
</div>
<h2>Cache Application Block Class Reference </h2>
<p><strong>CacheFactory Class</strong> &#8211; The CacheFactory uses the supplied configuration information to determine the type of cache object to construct </p>
<p><strong>GetCacheManager</strong> &#8211; The GetCacheManager method returns a CacheManager object determined by the configuration information </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;">ICacheManager myCache = CacheFactory.GetCacheManager(); <span style="color:#008000;">//uses the default cache specified in configuration </span>

ICacheManager myCustomerCache = CacheManager.GetCacheManager(<span style="color:#006080;">&quot;Customers&quot;</span>); <span style="color:#008000;">//overload creates the name cache CustomerData </span>
</pre>
</div>
<p><strong>CacheManager Class</strong> &#8211; The CacheManger class acts as the interface between the application and the rest of the caching block. It provides all the methods required to manage the applications </p>
<p><strong>GetData</strong> &#8211; The GetData method returns an object from the cache containing the data that matches the supplied ID. If the data does not exist or if it has expired Null is returned </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;">Customer oCustomer = myCustomerCache.GetData(<span style="color:#006080;">&quot;CustomerID&quot;</span>); </pre>
</div>
<p><strong>Add</strong> &#8211; The Add method will add an item to the cache </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;">myCustomerCache.Add(<span style="color:#006080;">&quot;CustomerID&quot;</span>, oCustomer); 

myCustomerCache.Add(<span style="color:#006080;">&quot;CustomerID&quot;</span>, oCustomer, scavengingPriority, refreshAction, cacheExpirations); 

</pre>
</div>
<p><strong>Contains</strong> &#8211; The Contains method returns true if the item exists in the cache </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">bool</span> dataExists = myCustomerCache.Contains(<span style="color:#006080;">&quot;CustomerID&quot;</span>); </pre>
</div>
<p><strong>Remove</strong> &#8211; The Remove method will delete an item from the cache </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;">myCustomerCache.Remove(<span style="color:#006080;">&quot;CustomerID&quot;</span>); </pre>
</div>
<p><strong>Flush</strong> &#8211; The Flush method removes all items from the cache. If an error occurs during the flush the cache is left unchanged </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;">myCustomerCache.Flush(); </pre>
</div>
<h2>Monitoring Your Cache Performance </h2>
<p>Monitoring your cache usage and performance can help you understand whether your cache is performing as expected and helps you to fine tune your cache solution. You can use the Windows performance monitor application (Perfmon) to view and analyze your cache performance data when it is not delivering the expected performance. </p>
<p>To monitor cache performance </p>
<ul>
<li>Monitor the Cache Insert and Cache Retrieve Times under different cache loads (for example, number of items and size of cache) to identify where your performance problem is coming from. These two performance counters should be as low as possible for your cache to be more responsive to the application. You should note that the cache insert time and retrieve time should be constant regardless of the number of items in cache.
<li>Check your Cache Hit/Miss ratio. A cache hit occurs when you request an item from the cache and that item is available and returned to you. A cache miss occurs when you request an item from the cache and that item is not available. If this is low, it indicates that items are rarely in cache when you need them. Possible causes for this include:
<ul>
<li>Your cache loading technique is not effective.
<li>Your maximum allowed cache size is too small, causing frequent scavenging operations, which results in cached items being removed to free up memory. </li>
</li>
</ul>
<li>Check your Cache Turnover rate. The cache turnover rate refers to the number of insertions and deletions of items from the cache per second. If this is high, it indicates that items are inserted and removed from cache at a high rate. Possible causes for this include:
<ul>
<li>Your maximum allowed cache size is too small, causing frequent scavenging operations which result in cached items being removed to free up memory.
<li>Faulty application design, resulting in improper use of the cache. </li>
</ul>
<li>Additionally you can also monitor the Cache Entries and Cache Size counters. Although the Cache Entries counter does not provide enough information regarding your cache performance it can be used with other counters to provide valuable information. </li>
</li>
</li>
</ul>
<p>Regular monitoring of your cache should highlight any changes in data use and any bottlenecks that these might introduce. This is the main management task associated with the post-deployment phase of using a caching system. </p>
<h2>Synchronizing Caches in a Server Farm </h2>
<p>A common problem for distributed applications developers is how you synchronize cached data between all servers in the farm. Generally speaking, if you have a situation in which your cache needs to be synchronized in your server farm, it almost always means that your original design is faulty. You should design your application with clustering in mind and avoid such situations in the first place. </p>
<p>You can configure the Cache Application Block to share the backing store between servers in a web farm. All machines in the farm can have the same cache instance and partition and can read/write to the store. But the in-memory version of the cache is always unique to each server in the farm. </p>
<p>However, if you have one of those rare situations where such synchronization is absolutely required, you should use file dependencies to invalidate the cache when the information in the main data store changes. </p>
<p>To create file dependencies for cache synchronization </p>
<ul>
<li>Create a database trigger that is activated when a record in your data store is changed.
<li>Implement this trigger to create an empty file in the file system to be used for notification. This file should be placed either on the computer running SQL Server, a Storage Area Network (SAN), or another central server.
<li>Use Application Center replication services to activate a service that copies the file from the central server to all disks in the server farm.
<li>Make the creation of the file on each server trigger a dependency event to expire the cached item in the ASP.NET cache on each of the servers in the farm. </li>
</li>
</li>
</ul>
<p>NOTE: because replicating a file across the server farm can take time, it is inefficient in cases where the cached data changes every few seconds. </p>
<p>The Caching Application Block should not be used if: </p>
<ul>
<li>The ASP.NET cache provides all the caching functionality that the application requires
<li>If security is an issue. While the persistent cache allows data to be encrypted there is no support to encrypt the in memory cache. If a malicious user could gain access to the system they can potentially retrieve cached data. Do not store sensitive information such as passwords and credit numbers in the cache if this is an issue for the application.
<li>If multiple applications need to share the cache or the cache and application need to reside on separate systems.
<li>The cache should ideally be used to store data that is either expensive to create or expensive to transport and that is at least semi-static in nature. It is generally not a good idea to cache transactional data</li>
</li>
</li>
</li>
</ul>
<p><ul></ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!344.entry"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!344.entry" /></a></p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=6&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2009/02/06/caching-application-block-and-database-backing-store/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!344.entry" medium="image" />
	</item>
		<item>
		<title>Microsoft AntiXSS Library</title>
		<link>http://itworksonmymachine.wordpress.com/2009/01/11/microsoft-antixss-library/</link>
		<comments>http://itworksonmymachine.wordpress.com/2009/01/11/microsoft-antixss-library/#comments</comments>
		<pubDate>Sun, 11 Jan 2009 18:54:13 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AntiXSS]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2009/01/11/microsoft-antixss-library</guid>
		<description><![CDATA[Cross site scripting (XSS) is the most common web application vulnerability and is listed in the Top 10 web application vulnerabilities on OWASP. XSS can also be called HTML injection attack, it occurs when un-validated user input is inserted into HTML output. This allows the attacker to construct a URL with HTML input and get [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=7&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!332" class="bvMsg">
<p>Cross site scripting (XSS) is the most common web application vulnerability and is listed in the <a href="http://www.owasp.org/index.php/Top_10_2007">Top 10 web application vulnerabilities on OWASP</a>. XSS can also be called HTML injection attack, it occurs when un-validated user input is inserted into HTML output. This allows the attacker to construct a URL with HTML input and get it executed on the browser in the user&#8217;s context. This attack can be used to extract cookie information, steal sessions, write new html tags, invoke ActiveX controls, etc. Essentially, anything that can be done with a browser can be done with this attack without the user&#8217;s knowledge. </p>
<h1>Microsoft AntiXSS Library</h1>
<p>Microsoft recently released the v3.0 beta for AntiXSS library which helps you to protect your current applications from cross-site scripting attacks, at the same time helping you to protect your legacy application with its Security Runtime Engine. The Microsoft Anti-Cross Site Scripting Library is an encoding library, provided by the ASP.NET and Application Consulting &amp; Engineering (ACE) teams at Microsoft, designed to help developers protect their Web-based applications from XSS attacks. </p>
<p>AntiXSS 3.0 is a powerful tool in the Microsoft toolbox that mitigates XSS risks and provides a consistent level of security allowing you to focus on solving business problems and not on security problems. </p>
<h1>Whats new in AntiXSS 3.0: </h1>
<ul>
<li>Improved Performance &#8211; AntiXSS 3.0 has been completely rewritten with performance in mind, and yet retains the fundamental protection from XSS attacks that you have come to rely on for your applications
<li>Secure Globalization &#8211; The web is a global market place, and cross-site scripting is a global issue. An attack can be coded anywhere, and Anti-XSS 3.0 now protects against XSS attacks coded in dozens of languages
<li>Standards Compliance &#8211; AntiXSS 3.0 is written to comply with modern web standards. You can protect your web application without adversely affecting its UI</ul>
<p>This library differs from most encoding libraries in that it uses the principle-of-inclusions technique to provide protection against XSS attacks. This approach works by defining a valid or allowed set of characters, treating anything outside this set as invalid characters or potential attacks and encoding it. </p>
<p>Cross-site scripting (XSS) attacks exploit vulnerabilities in Web-based applications that fail to properly validate and/or encode input that is embedded in response data. Malicious users can then inject client-side script into response data causing the unsuspecting user&#8217;s browser to execute the script code. The script code will appear to have originated from a trusted site and may be able to bypass browser protection mechanisms such as security zones. </p>
<p>These attacks are platform and browser independent, and can allow malicious users to perform undesired actions such as gaining unauthorized access to client data like cookies or hijacking sessions entirely. </p>
<p>In order for a malicious user to conduct an XSS attack against the application, they first need to find a page where all of the following are true: </p>
<ul>
<li>The application is not validating input
<li>The application is not encoding output that contains untrusted inputs</ul>
<p>A malicious user can easily exploit this by tricking a user into visiting the page while passing script such as &lt;script&gt;alert(&#8216;Virus Alert!&#8217;)&lt;/script&gt; into one of the parameters. The script injected by the malicious user gets executed in the unsuspecting user&#8217;s Web browser. </p>
<p>To protect our application from XSS attacks we first need to understand the methods that malicious users can use to conduct such attacks. We can do using the following steps: </p>
<ol>
<li>
<h2>Review ASP.NET code that generates output</h2>
<p>Remember that in order for an XSS attack to succeed, malicious users must find a way to embed their input as part of the response data from the application; therefore, we need to identify code in the application that generates output. This might not always be an easy task, especially for large applications, and some output may not necessarily require encoding. </p>
<li>
<h2>Determine if output could contain untrusted input</h2>
<p>Any of the output identified in the previous step could contain untrusted user inputt; if you&#8217;re unsure if the output contains untrusted input, err on the side of caution and assume it does. </p>
<li>
<h2>Determine encoding method to use</h2>
<p>Understand which encoding method we need to use to encode our web response data. Output will require encoding if all of the following conditions are true: </p>
<ul>
<li>Input is not trusted
<li>Output contains untrusted input
<li>Output is used in a web response data context</li>
</ul>
<p>Following will be helpful in determining which encoding method to use: </p>
<p><strong>HtmlEncode &#8211; </strong>Untrusted input is used in HTML output except when assigning to an HTML attribute<br />&lt;a href=&quot;<a href="http://dotnethitman.spaces.live.com&quot;&gt;click/">http://dotnethitman.spaces.live.com&quot;&gt;Click</a> Here [Untrusted input]&lt;/a&gt; </p>
<p><strong>HtmlAttributeEncode &#8211; </strong>Untrusted input is used as an HTML attribute<br />&lt;hr size=[Untrusted input]&gt; </p>
<p><strong>JavaScriptEncode &#8211; </strong>Untrusted input is used within a JavaScript context<br />&lt;script type=&quot;text/javascript&quot;&gt;<br />…<br />[Untrusted input]<br />…<br />&lt;/script&gt; </p>
<p><strong>UrlEncode &#8211; </strong>Untrusted input is used in a URL (such as a value in a querystring)<br />&lt;a href=&quot;<a href="http://search.msn.com/results.aspx?q=[Untrusted-input]">Click&quot;&gt;http://search.msn.com/results.aspx?q=[Untrusted-input]&quot;&gt;Click</a> Here!&lt;/a&gt; </p>
<p><strong>VisualBasicScriptEncode &#8211; </strong>Untrusted input is used within a Visual Basic Script context<br />&lt;script type=&quot;text/vbscript&quot; language=&quot;vbscript&quot;&gt;<br />…<br />[Untrusted input]<br />…<br />&lt;/script&gt; </p>
<p><strong>XmlEncode &#8211; </strong>Untrusted input is used in XML output, except when assigning to an XML attribute<br />&lt;xml_tag&gt;[Untrusted input]&lt;/xml_tag&gt; </p>
<p><strong>XmlAttributeEncode &#8211; </strong>Untrusted input is used as an XML attribute<br />&lt;xml_tag attribute=[Untrusted input]&gt;Some Text&lt;/xml_tag&gt; </p>
<li>
<h2>Encode output</h2>
<p>Now that we&#8217;ve determined which scenarios require encoding, all that&#8217;s left to do is add the Microsoft Anti-Cross Site Scripting Library to our project and encode the untrusted input as it is embedded in response data. </p>
<p><p>After you&#8217;ve installed the Microsoft Anti-Cross Site Scripting Library, you can add the reference to the library in your ASP.NET using the following steps: </p>
<ol>
<li>Right-click the project name
<li>Select Add Reference … option
<li>Under Browse, look in the library installation directory and add the reference to AntiXSSlibrary.dll</li>
</ol>
<p><p>After we&#8217;ve added the reference to the Anti-Cross Site Scripting Library, we encode the output generated by the our page. To do this: </p>
<ol>
<li>Add the directive using Microsoft.Security.Application
<li>In the output method encode using one of the encoding methods: <br />AntiXss.HtmlEncode(Request.QueryString[&quot;SomeParam&quot;]);
<li>Rebuild the Web application</li>
</ol>
</p>
</p>
</li>
</ol>
<h1>Additional Steps</h1>
<p>To make malicious users&#8217; jobs even harder, there are some additional layers of defense that can be implemented to further prevent XSS attacks in the our application. </p>
<ul>
<li>Set the ASP.NET validateRequest attribute to true: <br />&lt;%@ Page Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot; CodeFile=&quot;PreventXSS.aspx.cs&quot; Inherits=&quot;PreventXSS&quot; validateRequest=&quot;true&quot; %&gt;
<li>Perform input validation on all inputs to the application. <br />see <a href="http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000001.asp">How To: Use Regular Expressions to Constrain Input in ASP.NET</a><br />and <a href="http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!158.entry">Validation Application Block and ASP.NET</a> </li>
</ul>
<h1>Conclusion</h1>
<p>XSS attacks are easily one of the most common encountered by IT teams, and with the number of Web applications increasing each day, that number is expected to continue growing. Developers need to protect their application users from such attacks by: </p>
<ul>
<li>Validating and constraining input
<li>Encoding output</li>
</li>
</ul>
<p>NOTE: remember, a common mistake is to encode untrusted input more than once, which can result in outputs being displayed incorrectly. </p>
<p>For more information on XSS attacks, some good references are: </p>
<ul>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/PAGHT000004.asp?_r=1">Microsoft Patterns &amp; Practices</a>
<li><a href="http://en.wikipedia.org/wiki/Cross_site_scripting">Wikipedia.com</a></li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!332.entry"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!332.entry" /></a></p>
</p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=7&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2009/01/11/microsoft-antixss-library/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!332.entry" medium="image" />
	</item>
		<item>
		<title>Creating a generic CLR audit trigger</title>
		<link>http://itworksonmymachine.wordpress.com/2008/11/09/creating-a-generic-clr-audit-trigger/</link>
		<comments>http://itworksonmymachine.wordpress.com/2008/11/09/creating-a-generic-clr-audit-trigger/#comments</comments>
		<pubDate>Sat, 08 Nov 2008 20:35:27 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Audit]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[CONTEXT_INFO]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2008/11/09/creating-a-generic-clr-audit-trigger</guid>
		<description><![CDATA[There’s an interesting article at SqlJunkies http://sqljunkies.com/Article/4CD01686-5178-490C-A90A-5AEEF5E35915.scuk which shows how to create a generic CLR audit trigger. The audit trigger works great and includes tracking of: insertions of new records deletions of existing records and modifications of fields in existing records. But there is just one small problem with this trigger code. The PerformedBy column [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=28&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!304" class="bvMsg">
<p>There’s an interesting article at SqlJunkies <a href="http://sqljunkies.com/Article/4CD01686-5178-490C-A90A-5AEEF5E35915.scuk">http://sqljunkies.com/Article/4CD01686-5178-490C-A90A-5AEEF5E35915.scuk</a> which shows how to create a generic CLR audit trigger. The audit trigger works great and includes tracking of: </p>
<ul>
<li>insertions of new records
<li>deletions of existing records
<li>and modifications of fields in existing records.</ul>
<p>But there is just one small problem with this trigger code. The PerformedBy column of the Audit table in the sample code is set to the UserID of the connection string which in most applications would be the same UserID for all connections because of connection pooling. This means the trigger will log all operations performed by the application but it will not log the real user (application user) who made the change. </p>
<p>So the first step was to make sure that the application logged in user’s UserID is passed in to all the CRUD stored procedures from my web application. </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">CREATE</span> <span style="color:#0000ff;">PROCEDURE</span> spSomeProc(
    ...
    @PerformedByUserId <span style="color:#0000ff;">VARCHAR</span>(32))
<span style="color:#0000ff;">AS</span>
<span style="color:#0000ff;">BEGIN</span>
    <span style="color:#0000ff;">SET</span> NOCOUNT <span style="color:#0000ff;">ON</span>;
    ...
    <span style="color:#0000ff;">RETURN</span>;
<span style="color:#0000ff;">END</span>
GO</pre>
</div>
<p>You can get the application logged in user’s UserID from HttpContext.Current.User.Identity.Name or Thread.CurrentPrincipal.Identity.Name and pass this value from the application to the CRUD stored procedure. </p>
<p>Now that we have a way to pass in the UserID to our stored procedures, we need to somehow pass this parameter value to the trigger code. Although there is no direct way of passing a parameter down to the trigger, the forums at SqlJunkies suggested to create a temporary table in your procedure, insert the UserID as the only row in the temporary table and then retrieve this value in the CLR trigger by executing a query against this temporary table. Since the trigger uses the same connection session we don&#8217;t need to create a global temporary table. </p>
<p>This solution works fine but it uses the tempdb which is a bit of a concern as a load test scenario performing CRUD operations could easily bloat up the tempdb. </p>
<p>Another option is to pass in the UserID via the CONTEXT_INFO, which frees up tempdb for other tasks. We can do so with the following code snippet added at the beginning of every CRUD stored procedure </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">CREATE</span> <span style="color:#0000ff;">PROCEDURE</span> spSomeProc(
    ...
    @PerformedByUserId    <span style="color:#0000ff;">VARCHAR</span>(32))
<span style="color:#0000ff;">AS</span>
<span style="color:#0000ff;">BEGIN</span>
    <span style="color:#0000ff;">SET</span> NOCOUNT <span style="color:#0000ff;">ON</span>;

    <span style="color:#0000ff;">DECLARE</span> @BinaryUserId VARBINARY(128);
    <span style="color:#0000ff;">SET</span> @BinaryUserId = <span style="color:#0000ff;">CAST</span>(@PerformedByUserId <span style="color:#0000ff;">AS</span> VARBINARY(128));

    <span style="color:#0000ff;">SET</span> CONTEXT_INFO @BinaryUserId;

    ...

    <span style="color:#0000ff;">SET</span> CONTEXT_INFO 0x0;
    <span style="color:#0000ff;">RETURN</span>;
<span style="color:#0000ff;">END</span>
GO</pre>
</div>
<p>and in the CLR trigger you can get the CONTEXT_INFO as: </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;">...
oCmd.CommandText  = <span style="color:#006080;">&quot;SELECT CAST(CONTEXT_INFO() AS VARCHAR(128))&quot;</span>;
<span style="color:#0000ff;">string</span> userid = (<span style="color:#0000ff;">string</span>)oCmd.ExecuteScalar();
... </pre>
</div>
<p>We can also add an additional check here to get the UserID from “SELECT CURRENT_USER” just to make sure that if the CONTEXT_INFO is not set or returns NULL as in the case where some DBA made a change to any of the tables directly (for production support issue or whatever). </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;">SqlCommand CurrentUserCmd = <span style="color:#0000ff;">new</span> SqlCommand(<span style="color:#006080;">&quot;SELECT CAST(CONTEXT_INFO() AS VARCHAR(128))&quot;</span>, Connection);
<span style="color:#0000ff;">string</span> CurrentUser = CurrentUserCmd.ExecuteScalar().ToString();
<span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">string</span>.IsNullOrEmpty(CurrentUser))
&#123;
    CurrentUserCmd.CommandText = <span style="color:#006080;">&quot;SELECT CURRENT_USER&quot;</span>;
    CurrentUser = CurrentUserCmd.ExecuteScalar().ToString();
&#125;</pre>
</div>
<p>The full source code from the original article and modified as described above (converted to C#) is given below </p>
<div style="border-bottom:gray 1px solid;border-left:gray 1px solid;line-height:12pt;background-color:#f4f4f4;width:97.5%;font-family:consolas, 'Courier New', courier, monospace;font-size:8pt;overflow:auto;border-top:gray 1px solid;cursor:text;border-right:gray 1px solid;margin:20px 0 10px;padding:4px;">
<pre style="line-height:12pt;background-color:#f4f4f4;width:100%;font-family:consolas, 'Courier New', courier, monospace;color:black;font-size:8pt;overflow:visible;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">using</span> System;
<span style="color:#0000ff;">using</span> System.Data;
<span style="color:#0000ff;">using</span> System.Data.SqlClient;
<span style="color:#0000ff;">using</span> System.Data.SqlTypes;
<span style="color:#0000ff;">using</span> Microsoft.SqlServer.Server; 

<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">partial</span> <span style="color:#0000ff;">class</span> Triggers
&#123;
    <span style="color:#008000;">//This is the original template for Trigger metadata. Note that it is table-specific (i.e. it suggests that the trigger should apply to one table only).</span>
    <span style="color:#008000;">//&lt;Microsoft.SqlServer.Server.SqlTrigger(Name:=&quot;Trigger1&quot;, Target:=&quot;Table1&quot;, Event:=&quot;FOR UPDATE&quot;)&gt; _ </span>

    <span style="color:#008000;">//This is our actual declaration. Note that it does not specify any particular table. We don't know if it is Microsoft's intention to allow table-agnostic trigger code, but this works and we hope that it keeps working.</span>
    <span style="color:#008000;">//GENERIC AUDIT TRIGGER: AuditCommon</span>
    [Microsoft.SqlServer.Server.SqlTrigger(Name = <span style="color:#006080;">&quot;AuditCommon&quot;</span>, Event = <span style="color:#006080;">&quot;FOR UPDATE, INSERT, DELETE&quot;</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> AuditCommon()
    &#123;
        <span style="color:#0000ff;">try</span>
        &#123;
#<span style="color:#0000ff;">if</span>(DEBUG)
            EmitDebugMessage(<span style="color:#006080;">&quot;Enter Trigger&quot;</span>);
<span style="color:#cc6633;">#endif</span> 

            <span style="color:#008000;">//Grab the already-open Connection to use as an argument</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
            EmitDebugMessage(<span style="color:#006080;">&quot;Open Connection&quot;</span>);
<span style="color:#cc6633;">#endif</span>
            SqlTriggerContext Context = SqlContext.TriggerContext;
            SqlConnection Connection = <span style="color:#0000ff;">new</span> SqlConnection(<span style="color:#006080;">&quot;CONTEXT CONNECTION=TRUE&quot;</span>);
            Connection.Open(); 

            <span style="color:#008000;">//Load the &quot;inserted&quot; table</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
            EmitDebugMessage(<span style="color:#006080;">&quot;Load INSERTED&quot;</span>);
<span style="color:#cc6633;">#endif</span>
            SqlDataAdapter TableLoader = <span style="color:#0000ff;">new</span> SqlDataAdapter(<span style="color:#006080;">&quot;SELECT * FROM INSERTED&quot;</span>, Connection);
            DataTable InsertedTable = <span style="color:#0000ff;">new</span> DataTable();
            TableLoader.Fill(InsertedTable); 

            <span style="color:#008000;">//Load the &quot;deleted&quot; table</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
            EmitDebugMessage(<span style="color:#006080;">&quot;Load DELETED&quot;</span>);
<span style="color:#cc6633;">#endif</span>
            TableLoader.SelectCommand.CommandText = <span style="color:#006080;">&quot;SELECT * FROM DELETED&quot;</span>;
            DataTable DeletedTable = <span style="color:#0000ff;">new</span> DataTable();
            TableLoader.Fill(DeletedTable); 

            <span style="color:#008000;">//Prepare the &quot;audit&quot; table for insertion</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
            EmitDebugMessage(<span style="color:#006080;">&quot;Load AUDIT schema for insertion&quot;</span>);
<span style="color:#cc6633;">#endif</span>
            SqlDataAdapter AuditAdapter = <span style="color:#0000ff;">new</span> SqlDataAdapter(<span style="color:#006080;">&quot;SELECT * FROM AUDIT WHERE 1 = 0&quot;</span>, Connection);
            DataTable AuditTable = <span style="color:#0000ff;">new</span> DataTable();
            AuditAdapter.FillSchema(AuditTable, SchemaType.Source);
            SqlCommandBuilder AuditCommandBuilder = <span style="color:#0000ff;">new</span> SqlCommandBuilder(AuditAdapter);
            <span style="color:#008000;">//Create DataRow objects corresponding to the trigger table rows.</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
            EmitDebugMessage(<span style="color:#006080;">&quot;Create internal representations of trigger table rows&quot;</span>);
<span style="color:#cc6633;">#endif</span>
            <span style="color:#0000ff;">string</span> TableName = <span style="color:#006080;">&quot;&quot;</span>;
            DataRow InsertedRow = <span style="color:#0000ff;">null</span>;
            <span style="color:#0000ff;">if</span> (InsertedTable.Rows.Count &gt; 0)
            &#123;
                InsertedRow = InsertedTable.Rows[0];
                TableName = DeriveTableNameFromKeyFieldName(InsertedTable.Columns[0].ColumnName);
            &#125;
            DataRow DeletedRow = <span style="color:#0000ff;">null</span>;
            <span style="color:#0000ff;">if</span> (DeletedTable.Rows.Count &gt; 0)
            &#123;
                DeletedRow = DeletedTable.Rows[0];
                TableName = DeriveTableNameFromKeyFieldName(DeletedTable.Columns[0].ColumnName);
            &#125; 

            <span style="color:#008000;">//get the current database user</span>
            SqlCommand CurrentUserCmd = <span style="color:#0000ff;">new</span> SqlCommand(<span style="color:#006080;">&quot;SELECT CAST(CONTEXT_INFO() AS VARCHAR(128))&quot;</span>, Connection);
            <span style="color:#0000ff;">string</span> CurrentUser = CurrentUserCmd.ExecuteScalar().ToString();
            <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">string</span>.IsNullOrEmpty(CurrentUser))
            &#123;
                CurrentUserCmd.CommandText = <span style="color:#006080;">&quot;SELECT CURRENT_USER&quot;</span>;
                CurrentUser = CurrentUserCmd.ExecuteScalar().ToString();
            &#125;
            <span style="color:#008000;">//Perform different audits based on the type of action.</span>
            <span style="color:#0000ff;">switch</span> (Context.TriggerAction)
            &#123;
                <span style="color:#0000ff;">case</span> TriggerAction.Update:
                    <span style="color:#008000;">//Ensure that both INSERTED and DELETED are populated. If not, this is not a valid update.</span>
                    <span style="color:#0000ff;">if</span> (InsertedRow != <span style="color:#0000ff;">null</span> &amp;&amp; DeletedRow != <span style="color:#0000ff;">null</span>)
                    &#123;
                        <span style="color:#008000;">//Walk through all the columns of the table.</span>
                        <span style="color:#0000ff;">foreach</span> (DataColumn Column <span style="color:#0000ff;">in</span> InsertedTable.Columns)
                        &#123;
                            <span style="color:#008000;">//ALTERNATIVE CODE to compare values and record only if they are different:</span>
                            <span style="color:#008000;">//If Not DeletedRow.Item(Column.Ordinal).Equals(InsertedRow.Item(Column.Ordinal)) Then</span>
                            <span style="color:#008000;">//This code records any attempt to update, whether the new value is different or not.</span>
                            <span style="color:#0000ff;">if</span> (Context.IsUpdatedColumn(Column.Ordinal))
                            &#123;
                                <span style="color:#008000;">//DEBUG output indicating field change</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
                                EmitDebugMessage(<span style="color:#006080;">&quot;Create UPDATE Audit: Column Name = &quot;</span> + Column.ColumnName + <span style="color:#006080;">&quot;, Old Value = '&quot;</span> + DeletedRow[Column.Ordinal].ToString() + <span style="color:#006080;">&quot;'&quot;</span> + <span style="color:#006080;">&quot;, New Value = '&quot;</span> + InsertedRow[Column.Ordinal].ToString() + <span style="color:#006080;">&quot;'&quot;</span>);
<span style="color:#cc6633;">#endif</span>
                                <span style="color:#008000;">//Create audit record indicating field change</span>
                                DataRow AuditRow = AuditTable.NewRow(); 

                                <span style="color:#008000;">//populate fields common to all audit records</span>
                                <span style="color:#0000ff;">long</span> RowId = (<span style="color:#0000ff;">long</span>)InsertedRow[0]; 

                                <span style="color:#008000;">//use &quot;Inserted.TableName&quot; when Microsoft fixes the CLR to supply it</span>
                                WriteCommonAuditData(AuditRow, TableName, RowId, CurrentUser, <span style="color:#006080;">&quot;UPDATE&quot;</span>); 

                                <span style="color:#008000;">//write update-specific fields</span>
                                AuditRow[<span style="color:#006080;">&quot;FieldName&quot;</span>] = Column.ColumnName;
                                AuditRow[<span style="color:#006080;">&quot;OldValue&quot;</span>] = DeletedRow[Column.Ordinal].ToString();
                                AuditRow[<span style="color:#006080;">&quot;NewValue&quot;</span>] = InsertedRow[Column.Ordinal].ToString(); 

                                <span style="color:#008000;">//insert the new row into the audit table</span>
                                AuditTable.Rows.InsertAt(AuditRow, 0);
                            &#125;
                        &#125;
                    &#125;
                    <span style="color:#0000ff;">break</span>; 

                <span style="color:#0000ff;">case</span> TriggerAction.Insert:
                    <span style="color:#008000;">//If the INSERTED row is not populated, then this is not a valid insertion.</span>
                    <span style="color:#0000ff;">if</span> (InsertedRow != <span style="color:#0000ff;">null</span>)
                    &#123;
                        <span style="color:#008000;">//DEBUG output indicating row insertion</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
                        EmitDebugMessage(<span style="color:#006080;">&quot;Create INSERT Audit: Row = '&quot;</span> + InsertedRow[0].ToString() + <span style="color:#006080;">&quot;'&quot;</span>);
<span style="color:#cc6633;">#endif</span>
                        <span style="color:#008000;">//Create audit record indicating field change</span>
                        DataRow AuditRow = AuditTable.NewRow();
                        <span style="color:#008000;">//populate fields common to all audit records</span>
                        <span style="color:#0000ff;">long</span> RowId = (<span style="color:#0000ff;">long</span>)InsertedRow[0];
                        <span style="color:#008000;">//use &quot;Inserted.TableName&quot; when Microsoft fixes the CLR to supply it</span>
                        WriteCommonAuditData(AuditRow, TableName, RowId, CurrentUser, <span style="color:#006080;">&quot;INSERT&quot;</span>);
                        <span style="color:#008000;">//insert the new row into the audit table</span>
                        AuditTable.Rows.InsertAt(AuditRow, 0);
                    &#125;
                    <span style="color:#0000ff;">break</span>;
                <span style="color:#0000ff;">case</span> TriggerAction.Delete:
                    <span style="color:#008000;">//If the DELETED row is not populated, then this is not a valid deletion.</span>
                    <span style="color:#0000ff;">if</span> (DeletedRow != <span style="color:#0000ff;">null</span>)
                    &#123;
                        <span style="color:#008000;">//DEBUG output indicating row insertion</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
                        EmitDebugMessage(<span style="color:#006080;">&quot;Create DELETE Audit: Row = '&quot;</span> + DeletedRow[0].ToString() + <span style="color:#006080;">&quot;'&quot;</span>);
<span style="color:#cc6633;">#endif</span>
                        <span style="color:#008000;">//Create audit record indicating field change</span>
                        DataRow AuditRow = AuditTable.NewRow();
                        <span style="color:#008000;">//populate fields common to all audit records</span>
                        <span style="color:#0000ff;">long</span> RowId = (<span style="color:#0000ff;">long</span>)DeletedRow[0];
                        <span style="color:#008000;">//use &quot;Inserted.TableName&quot; when Microsoft fixes the CLR to supply it</span>
                        WriteCommonAuditData(AuditRow, TableName, RowId, CurrentUser, <span style="color:#006080;">&quot;DELETE&quot;</span>);
                        <span style="color:#008000;">//insert the new row into the audit table</span>
                        AuditTable.Rows.InsertAt(AuditRow, 0);
                    &#125;
                    <span style="color:#0000ff;">break</span>;
            &#125; 

            <span style="color:#008000;">//update the audit table</span>
            AuditAdapter.Update(AuditTable);
            <span style="color:#008000;">//finish</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
            EmitDebugMessage(<span style="color:#006080;">&quot;Exit Trigger&quot;</span>);
<span style="color:#cc6633;">#endif</span>
        &#125;
        <span style="color:#0000ff;">catch</span> (Exception ex)
        &#123;
            <span style="color:#008000;">//Put exception handling code here if you want to connect this to your database-based error logging system. Without this Try/Catch block, any error in the trigger routine will stop the event that fired the trigger. This is early-stage development and we're not expecting any exceptions, so for the moment we just need to know about them if they occur.</span>
            <span style="color:#0000ff;">throw</span>;
        &#125;
    &#125; 

    <span style="color:#008000;">//Write data into the fields of an Audit table row that is common to all types of audit activities.</span>
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> WriteCommonAuditData(DataRow auditRow, <span style="color:#0000ff;">string</span> tableName, <span style="color:#0000ff;">long</span> rowId, <span style="color:#0000ff;">string</span> currentUser, <span style="color:#0000ff;">string</span> operation)
    &#123;
        auditRow[<span style="color:#006080;">&quot;TableName&quot;</span>] = tableName;
        auditRow[<span style="color:#006080;">&quot;RowId&quot;</span>] = rowId;
        auditRow[<span style="color:#006080;">&quot;OccurredAt&quot;</span>] = DateTime.Now;
        auditRow[<span style="color:#006080;">&quot;PerformedBy&quot;</span>] = currentUser;
        auditRow[<span style="color:#006080;">&quot;Operation&quot;</span>] = operation;
    &#125; 

    <span style="color:#008000;">//SQL CLR does not deliver the proper table name from either InsertedTable.TableName or DeletedTable.TableName, so we must use a substitute based on our key naming convention. We assume that in each table, the KeyFieldName = TableName + &quot;Id&quot;. Remove this routine and its uses as soon as we can get the table name from the CLR.</span>
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">string</span> DeriveTableNameFromKeyFieldName(<span style="color:#0000ff;">string</span> keyFieldName)
    &#123;
        <span style="color:#0000ff;">return</span> keyFieldName.Substring(0, keyFieldName.Length - 2); <span style="color:#008000;">//assumes KeyName = TableName &amp; &quot;Id&quot;</span>
    &#125; 

    <span style="color:#008000;">//Emit debug messages. This function gives us the option to turn off debugging messages by changing one value (here).</span>
#<span style="color:#0000ff;">if</span>(DEBUG)
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> EmitDebugMessage(<span style="color:#0000ff;">string</span> message)
    &#123;
        SqlContext.Pipe.Send(message);
    &#125;
<span style="color:#cc6633;">#endif</span>
&#125;</pre>
</div>
<p><div style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a href="http://technorati.com/tags/CLR" rel="tag">CLR</a>,<a href="http://technorati.com/tags/Trigger" rel="tag">Trigger</a>,<a href="http://technorati.com/tags/Audit" rel="tag">Audit</a>,<a href="http://technorati.com/tags/SQLServer" rel="tag">SQLServer</a>,<a href="http://technorati.com/tags/C%23" rel="tag">C#</a></div>
<p><p><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!304.entry"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!304.entry" /></a></p>
</p>
</p>
</p>
</p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/28/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=28&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2008/11/09/creating-a-generic-clr-audit-trigger/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!304.entry" medium="image" />
	</item>
		<item>
		<title>Unity – Dependency Injection and Inversion of Control Container</title>
		<link>http://itworksonmymachine.wordpress.com/2008/09/08/unity-dependency-injection-and-inversion-of-control-container/</link>
		<comments>http://itworksonmymachine.wordpress.com/2008/09/08/unity-dependency-injection-and-inversion-of-control-container/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 14:02:36 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Enterprise Library]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2008/09/08/unity-dependency-injection-and-inversion-of-control-container</guid>
		<description><![CDATA[The Dependency Injection PatternDependency injection is a programming technique to reduce component coupling. Dependency injection is also commonly known as “inversion of control” or IoC or sometimes as The Hollywood Principle &#8211; &#34;Don’t call us, we’ll call you”. The goal of dependency injection is to separate the concerns of how a dependency is obtained from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=8&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!267" class="bvMsg">
<p><strong>The Dependency Injection Pattern<br /></strong>Dependency injection is a programming technique to reduce component coupling. Dependency injection is also commonly known as “inversion of control” or IoC or sometimes as The Hollywood Principle &#8211; &quot;Don’t call us, we’ll call you”. The goal of dependency injection is to separate the concerns of how a dependency is obtained from the core concerns of a boundary. This improves reusability by enabling components to be supplied with dependencies which may vary depending on context. </p>
<p><strong>The Old Way<br /></strong>Following is an example of how you might write code if not using dependency injection</p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> WebApp
&#123;
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> WebApp()
    &#123;
        quotes </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> StockQuotes();
        authenticator </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> Authenticator();
        database </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> Database();
        logger </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> Logger();
        errorHandler </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> ErrorHandler();
    &#125;
&#125; </span></div></pre>
</div>
<p><strong>Problem</strong> </p>
<ul>
<li>What about the child objects?
<li>How does the StockQuotes find the Logger?
<li>How does the Authenticator find the database?
<li>Suppose you want to use a TestingLogger instead? Or a MockDatabase? </li>
</li>
</li>
</li>
</ul>
<p><p>Service Locator pattern attempts to solve some of the problems mentioned above by providing a dictionary of objects. The objects are all stored in this dictionary and the Get method simply returns the object to the caller. </p>
<p><strong>Service Locator Example<br /></strong></p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">interface</span><span style="color:#000000;"> ILocator
&#123;
    TObject Get</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">TObject</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
&#125;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> MyLocator : ILocator
&#123;
    </span><span style="color:#0000ff;">protected</span><span style="color:#000000;"> Dictionary</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Type, </span><span style="color:#0000ff;">object</span><span style="color:#000000;">&gt;</span><span style="color:#000000;"> dict </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> Dictionary</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Type,</span><span style="color:#0000ff;">object</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> MyLocator()
    &#123;
        dict.Add(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(ILogger), </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> Logger());
        dict.Add(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(IErrorHandler), </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> ErrorHandler(</span><span style="color:#0000ff;">this</span><span style="color:#000000;">));
        dict.Add(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(IQuotes), </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> StockQuotes(</span><span style="color:#0000ff;">this</span><span style="color:#000000;">));
        dict.Add(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(IDatabase), </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> Database(</span><span style="color:#0000ff;">this</span><span style="color:#000000;">));
        dict.Add(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(IAuthenticator), </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> Authenticator(</span><span style="color:#0000ff;">this</span><span style="color:#000000;">));
        dict.Add(</span><span style="color:#0000ff;">typeof</span><span style="color:#000000;">(WebApp), </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> WebApp(</span><span style="color:#0000ff;">this</span><span style="color:#000000;">));
    &#125;
&#125;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> StockQuotes
&#123;
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> StockQuotes(ILocator locator)
    &#123;
        errorHandler </span><span style="color:#000000;">=</span><span style="color:#000000;"> locator.Get</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">IErrorHandler</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
        logger </span><span style="color:#000000;">=</span><span style="color:#000000;"> locator.Get</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
    &#125;
&#125; </span></div></pre>
</div>
<p><p><strong>Pros</strong> </p>
<ul>
<li>Classes are decoupled from explicit implementation types
<li>Easy to externalize the config</li>
</li>
</ul>
<p><p><strong>Cons</strong> </p>
<ul>
<li>Everyone takes a dependency on the ILocator
<li>Hard to store constants and other useful primitives
<li>Creation order is still a problem </li>
</li>
</li>
</ul>
<p><p><strong>Dependency Injection Containers<br /></strong>The dependency injection container is a component responsible for assigning dependencies to a recipient component. Containers are generally implemented using the Factory Pattern to allow creation of the recipient and dependency components. Containers are often implemented to allow existing objects to be registered for use as a dependency, or to create new instances when required. Using a dependency injection container with our StockQuotes example provides the following benefits: </p>
<ul>
<li>Gets rid of the dependency on the ILocator
<li>Object is no longer responsible for finding its dependencies
<li>The container does it for you </li>
</li>
</ul>
<p>
<p>In a nutshell, dependency injection just means that a given class or system is no longer responsible for instantiating their own dependencies. In this case “Inversion of Control” refers to moving the responsibility for locating and attaching dependency objects to another class or a DI tool. That might not sound that terribly profound, but it opens the door for a lot of interesting scenarios.<br />Benefits of Dependency Injection: </p>
<ul>
<li>Dependency Injection is an important pattern for creating classes that are easier to unit test in isolation
<li>Promotes loose coupling between classes and subsystems
<li>Adds potential flexibility to a codebase for future changes
<li>Can enable better code reuse </li>
</li>
</ul>
<p><p><strong>Unity Application Block <br /></strong>Unity Application Block is a lightweight Inversion of Control container which supports constructor, property and method call injection. Unity sits on top of another framework called ObjectBuilder, but is different from the ObjectBuilder which has been a part of Enterprise Library 3.1 and earlier. Unity is based on v2 of the Objectbuilder and has been optimized for performance quite a bit. Unity is available both as a standalone and part of Enterprise Library 4.0 on codeplex at <a href="http://www.codeplex.com/unity">http://www.codeplex.com/unity</a> and <a href="http://www.codeplex.com/entlib">http://www.codeplex.com/entlib</a>. Unity 1.1 is not part of Enterprise Library 4.0 but the good thing about it is that it will update the Unity dlls/libraries in Enterprise Library 4.0 installed folder to 1.1 during installation. </p>
<p>The Unity Application Block includes the following features: </p>
<ul>
<li>It provides a mechanism for building (or assembling) instances of objects, which may contain other dependent object instances.
<li>It exposes RegisterType methods that support configuring the container with type mappings and objects (including singleton instances) and Resolve methods that return instances of built objects that can contain any dependent objects.
<li>It provides inversion of control (IoC) functionality by allowing injection of preconfigured objects into classes built by the application block. Developers can specify an interface or class type in the constructor (constructor injection), or apply attributes to properties and methods to initiate property injection and method call injection.
<li>It supports a hierarchy for containers. A container may have child container(s), allowing object location queries to pass from the child out through the parent container(s).
<li>It can read configuration information from standard configuration systems, such as XML files, and use it to configure the container.
<li>It makes no demands on the object class definition. There is no requirement to apply attributes to classes (except when using property or method call injection), and there are no limitations on the class declaration.
<li>It supports custom container extensions that developers can implement; for example, methods to allow additional object construction and container features such as caching. </li>
</li>
</li>
</li>
</li>
</ul>
<p><p>Unity has no dependency on Enterprise Library core and can be used without having to install Enterprise Library on the host system. To use Unity in your application you need to add reference to the following dlls in your project<br />    Microsoft.Practices.ObjectBuilder2<br />    Microsoft.Practices.Unity </p>
<p>The Unity container can be configured through configuration files or you can use code to register dependencies dynamically at run time. To use Unity with configuration files you need to add reference to the following dll<br />    Microsoft.Practices.Unity.Configuration </p>
<p>Steps when using Dependency Injection </p>
<ul>
<li>Write your objects the way you want
<li>Setup the container
<li>Ask the container for objects
<li>The container creates objects for you and fulfills dependencies </li>
</li>
</li>
</li>
</ul>
<p>
<p><strong>Setup the container<br /></strong>The ideal place to setup the Unity container for ASP.NET applications is in the Application_Start method of the global.asax file. We would like to have a persistent container that hold it’s state during the execution of the application. The right place to put this is in the Global.asax file as a property of the current application. </p>
<p>We create a simple interface for the container property so that we can access our container using this interface</p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">interface</span><span style="color:#000000;"> IContainerAccessor
&#123;
    IUnityContainer Container &#123; </span><span style="color:#0000ff;">get</span><span style="color:#000000;">; &#125;
&#125;
</span></div></pre>
</div>
<p>class in the Global.asax file:</p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">private</span><span style="color:#000000;"> </span><span style="color:#0000ff;">static</span><span style="color:#000000;"> UnityContainer _container;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">static</span><span style="color:#000000;"> UnityContainer Container
&#123;
    </span><span style="color:#0000ff;">get</span><span style="color:#000000;">
    &#123;
        </span><span style="color:#0000ff;">return</span><span style="color:#000000;"> _container;
    &#125;
    </span><span style="color:#0000ff;">set</span><span style="color:#000000;">
    &#123;
        _container </span><span style="color:#000000;">=</span><span style="color:#000000;"> value;
    &#125;
&#125;
</span><span style="color:#0000ff;">protected</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> Application_Start(</span><span style="color:#0000ff;">object</span><span style="color:#000000;"> sender, EventArgs e)
&#123;
    BuildContainer();
&#125;
</span><span style="color:#0000ff;">protected</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> Application_End(</span><span style="color:#0000ff;">object</span><span style="color:#000000;"> sender, EventArgs e)
&#123;
    CleanUp();
&#125;
</span><span style="color:#0000ff;">private</span><span style="color:#000000;"> </span><span style="color:#0000ff;">static</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> BuildContainer()
&#123;
    IUnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
    </span><span style="color:#008000;">//</span><span style="color:#008000;">TODO: Register the relevant types for the container here through classes or configuration</span><span style="color:#008000;">
</span><span style="color:#000000;">    Container </span><span style="color:#000000;">=</span><span style="color:#000000;"> container;
&#125;
</span><span style="color:#0000ff;">private</span><span style="color:#000000;"> </span><span style="color:#0000ff;">static</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> CleanUp()
&#123;
    </span><span style="color:#0000ff;">if</span><span style="color:#000000;"> (Container </span><span style="color:#000000;">!=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">null</span><span style="color:#000000;">)
    &#123;
        Container.Dispose();
    &#125;
&#125; </span></div></pre>
</div>
<p>The BuildContainer method is where we will setup our container and register our types for dependency injection. The RegisterType&lt;TFrom, TTo&gt;() method tells Unity that whenever someone asks for a dependency on TFrom give them Tto. In the example code below the statement container.RegisterType&lt;ILogger, EventLogLogger&gt;() tells Unity that whenever someone has a dependency on type ILogger go ahead and create an object of type EventLogLogger. </p>
<p>There are a couple of different flavors of Dependency Injection </p>
<ul>
<li>Constructor Injection – Attach the dependencies through a constructor function at object creation
<li>Setter Injection – Attach the dependencies through setter properties
<li>Service Locator – Use a well known class that knows how to retrieve and create dependencies. Not technically DI, but this is what most DI/IoC container tools really do </li>
</li>
</li>
</ul>
<p><p><strong>Constructor Injection<br /></strong></p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">interface</span><span style="color:#000000;"> ILogger
&#123;
    </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> LogEvent(</span><span style="color:#0000ff;">string</span><span style="color:#000000;"> message);
&#125;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> FileLogger : ILogger
&#123;
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> LogEvent(</span><span style="color:#0000ff;">string</span><span style="color:#000000;"> message)
    &#123;
        ...
    &#125;
&#125;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> EventLogLogger : ILogger
&#123;
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> LogEvent(</span><span style="color:#0000ff;">string</span><span style="color:#000000;"> message)
    &#123;
        ...
    &#125;
&#125;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> StockQuotes
&#123;
    </span><span style="color:#0000ff;">private</span><span style="color:#000000;"> Ilogger _logger;
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> StockQuotes(ILogger logger)
    &#123;
        _logger </span><span style="color:#000000;">=</span><span style="color:#000000;"> logger;
    &#125;
&#125; 

UnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
...
contianer.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger, EventLogLogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
StockQuotes quotes </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">StockQuotes</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(); 

</span></div></pre>
</div>
<p>If a class that developers instantiate using the Resolve method of the Unity container has a constructor that defines one or more dependencies on other classes, the Unity container will automatically create the dependent object instance specified in parameters of the constructor. In the above example StockQuotes has a dependency on ILogger. When we create an instance of the StockQuotes class using the Resolve method of the Unity container, Unity will automatically create an instance of EventLogLogger and pass it to the constructor of StockQuotes class. </p>
<p>The benefit of using constructor injection is that the constructor function now explicitly declares the dependencies of a class. Constructor injection is often recommended as it eliminates chatty calls to the object and creates a valid object in as few steps as possible. </p>
<p><strong>Setter Injection<br /></strong></p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> OracleDatabase : IDatabase
&#123;
    Public </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> ExecuteQuery(</span><span style="color:#0000ff;">string</span><span style="color:#000000;"> query)
    &#123;
        ...
    &#125;
&#125;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> SqlDatabase : IDatabase
&#123;
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">void</span><span style="color:#000000;"> ExecuteQuery(</span><span style="color:#0000ff;">string</span><span style="color:#000000;"> query)
    &#123;
        ...
    &#125;
&#125;
</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> Authenticator
&#123;
    </span><span style="color:#0000ff;">private</span><span style="color:#000000;"> IDatabase _database;
    [Dependency]
    </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> IDatabase DB
    &#123;
        </span><span style="color:#0000ff;">get</span><span style="color:#000000;">&#123;</span><span style="color:#0000ff;">return</span><span style="color:#000000;"> _database;&#125;
        </span><span style="color:#0000ff;">set</span><span style="color:#000000;">&#123;_database </span><span style="color:#000000;">=</span><span style="color:#000000;"> value;&#125;
    &#125;
&#125; 

UnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
...
contianer.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">IDatabase, SqlDatabase</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
Authenticator auth </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Authenticator</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(); 

</span></div></pre>
</div>
<p>To force dependency injection of the dependent object, developers must apply the [Dependency] attribute to the property declaration. Many would argue that setter injection is really useful when legacy code needs to be upgraded and provides a smooth transition from legacy code to the new model. Making sure that any new code that depends on undesirable legacy code uses Dependency Injection leaves an easier migration path to eliminate the legacy code later with all new code.  </p>
<p><strong>As a service locator</strong></p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#000000;">UnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
contianer.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger, NullLogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
…
ILogger logger </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(); </span></div></pre>
</div>
<p>Here we are just telling unity to give us the ILogger interface which is already registered with the container. Using the container in this manner makes it a service locator. </p>
<p>Unity Dependency injection provides a number of ways to configure the container. As described above you use the RegisterType method to inform the container about dependencies. But Unity can also manage the object lifetime e.g. </p>
<p><strong>Dependencies as singleton<br /></strong></p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#000000;">UnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
container.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database, SqlDatabase</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new</span><span style="color:#000000;"> ContainerControlledLifetimeManager()); </span></div></pre>
</div>
<p>The above code  tells Unity that whenever someone asks for type Database give them type SqlDatabase and return the same object every time instead of creating a new one for each dependency. </p>
<p><strong>Named Instance</strong></p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#000000;">UnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
contianer.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database, SqlDatabase</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">SQL</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">);
container.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database, OracleDatabase</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">Oracle</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">);
IEnumerable</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database</span><span style="color:#000000;">&gt;</span><span style="color:#000000;"> databases </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.ResolveAll</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
Database database </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">SQL</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">); </span></div></pre>
</div>
<p>Named instance allows you to configure Unity with multiple dependencies for the same type but assign them different names. Thi s allows you to do fancy stuff where you want a default type mapping but also want to override the mapping by providing a name during object creation. </p>
<p><strong>Registering an existing object instance<br /></strong>So far all the examples above show how a type can be registered with Unity and the Unity container creates the object for you whenever requested. But what if you already have the object created and want to register this object in Unity. </p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#000000;">UnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
contianer,RegisterInstance</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new</span><span style="color:#000000;"> SqlDatabase());
contianer.RegisterInstance</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">Oracle</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">, </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> OracleDatabase());
Database database </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">();
Database oracleDatabase </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">Database</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">Oracle</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">); </span></div></pre>
</div>
<p>When using RegisterIntance Unity will automatically make the objects singletons. </p>
<p><strong>Configuring Unity via config file</strong><br />The Unity container can be configured through configuration files. To use Unity with configuration files you need to add reference to the following dll<br />    Microsoft.Practices.Unity.Configuration </p>
<p>Use following code to read the container setup from configuration file:</p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#000000;">UnityContainer container </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
UnityConfgurationSection section </span><span style="color:#000000;">=</span><span style="color:#000000;"> (UnityConfigurationSection)ConfigurationManager.GetSection(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">unity</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">);
Section.Containers.Default.GetConfigCommand().Configure();
ILogger logger </span><span style="color:#000000;">=</span><span style="color:#000000;"> container.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(); </span></div></pre>
</div>
<p>.config file:</p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">configSections</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">section </span><span style="color:#ff0000;">name</span><span style="color:#0000ff;">=&quot;unity&quot;</span><span style="color:#ff0000;"> type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration&quot;</span><span style="color:#ff0000;"> </span><span style="color:#0000ff;">/&gt;</span><span style="color:#000000;">
</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">configSections</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
</span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">unity</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">typeAliases</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
    </span><span style="color:#008000;">&lt;!--</span><span style="color:#008000;"> Lifetime manager types </span><span style="color:#008000;">--&gt;</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">typeAlias </span><span style="color:#ff0000;">alias</span><span style="color:#0000ff;">=&quot;singleton&quot;</span><span style="color:#ff0000;"> type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity&quot;</span><span style="color:#ff0000;"> </span><span style="color:#0000ff;">/&gt;</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">typeAlias </span><span style="color:#ff0000;">alias</span><span style="color:#0000ff;">=&quot;external&quot;</span><span style="color:#ff0000;"> type</span><span style="color:#0000ff;">=&quot;Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,Microsoft.Practices.Unity&quot;</span><span style="color:#ff0000;"> </span><span style="color:#0000ff;">/&gt;</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">typeAliases</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">containers</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
        </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">container</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
            </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">types</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
                </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">type </span><span style="color:#ff0000;">type</span><span style="color:#0000ff;">=&quot;ConsoleApplication1.Database, ConsoleApplication1&quot;</span><span style="color:#ff0000;"> mapTo</span><span style="color:#0000ff;">=&quot;ConsoleApplication1.SqlDatabase, ConsoleApplication1&quot;</span><span style="color:#ff0000;"> lifetime</span><span style="color:#0000ff;">=&quot;Singleton&quot;</span><span style="color:#ff0000;"> </span><span style="color:#0000ff;">/&gt;</span><span style="color:#000000;">
                </span><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">type </span><span style="color:#ff0000;">type</span><span style="color:#0000ff;">=&quot;ConsoleApplication1.ILogger, ConsoleApplication1&quot;</span><span style="color:#ff0000;"> mapTo</span><span style="color:#0000ff;">=&quot;ConsoleApplication1.EvnetLogLogger, ConsoleApplication1&quot;</span><span style="color:#ff0000;"> lifetime</span><span style="color:#0000ff;">=&quot;Singleton&quot;</span><span style="color:#ff0000;"> </span><span style="color:#0000ff;">/&gt;</span><span style="color:#000000;">
            </span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">types</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
        </span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">container</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">containers</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;">
</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">unity</span><span style="color:#0000ff;">&gt;</span><span style="color:#000000;"> </span></div></pre>
</div>
<p><strong>Nested Containers<br /></strong>Unity supports nested containers, which allows the parent container to create child containers. This provides the ability to override parent type mappings with child type mappings. Parent-Child relationship between Unity containers. What this means is that the parent-child relationship between Unity containers will search the child container to the resolve the type mapping, and if not found, will navigate up to the parent container to resolve the type. </p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#000000;">UnityContainer parentContainer </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> UnityContainer();
IUnityContainer childContainer1 </span><span style="color:#000000;">=</span><span style="color:#000000;"> parentContainer.CreateChildContainer();
IUnityContainer childContainer2 </span><span style="color:#000000;">=</span><span style="color:#000000;"> parentContainer.CreateChildContainer(); 

parentContainer.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger, FileLogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new</span><span style="color:#000000;"> ContainerControlledLifetimeManager());
childContainer1.RegisterType</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger, EventLogLogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#0000ff;">new</span><span style="color:#000000;"> ContainerControlledLifetimeManager()); 

ILogger logger </span><span style="color:#000000;">=</span><span style="color:#000000;"> childContainer2.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(); </span><span style="color:#008000;">//</span><span style="color:#008000;"> should return FileLogger from parentContainer</span><span style="color:#008000;">
</span><span style="color:#000000;">ILogger logger2 </span><span style="color:#000000;">=</span><span style="color:#000000;"> childContainer1.Resolve</span><span style="color:#000000;">&lt;</span><span style="color:#000000;">ILogger</span><span style="color:#000000;">&gt;</span><span style="color:#000000;">(); </span><span style="color:#008000;">//</span><span style="color:#008000;">should return EventLogLogger from childContainer1 </span><span style="color:#008000;">
</span></div></pre>
</div>
<p>While registering types with Unity there is a certain risk of introducing unintentional circular references, which are not easy to detect or prevent. <br />For example, the following code shows two classes that reference each other in their constructors.</p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre style="word-wrap:break-word;white-space:pre-wrap;"><div><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> Class1
&#123;
  </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> Class1(Class2 test2)
  &#123; ... &#125;
&#125; 

</span><span style="color:#0000ff;">public</span><span style="color:#000000;"> </span><span style="color:#0000ff;">class</span><span style="color:#000000;"> Class2
&#123;
  </span><span style="color:#0000ff;">public</span><span style="color:#000000;"> Class2(Class1 test1)
  &#123; ... &#125;
&#125; 

</span></div></pre>
</div>
<p>It is the responsibility of the developer to prevent this type of error by ensuring that the members of classes they use with dependency injection do not contain circular references. </p>
<p><strong>References<br /></strong></p>
<ul>
<li>Martin Fowler on <a href="http://martinfowler.com/articles/injection.html">Inversion of Control and the Dependency Injection Pattern</a>
<li>David Hayden’s <a href="http://www.pnpguidance.net/Post/UnityIoCASPNETScreencastDependencyInjectionWebPages.aspx">screen cast on Unity</a>.
<li>Gil Fink on <a href="http://blogs.microsoft.co.il/blogs/gilf/archive/2008/07/01/how-to-use-unity-container-in-asp-net.aspx">How to use Unity Container in ASP.NET</a>
<li>Jeremy D. Miller on <a href="http://codebetter.com/blogs/jeremy.miller/archive/2005/10/06/132825.aspx">Dependency Injection Pattern</a></li>
</li>
</li>
</li>
</ul>
<p><div style="display:inline;margin:0;padding:0;">Technorati Tags: <a href="http://technorati.com/tags/Unity" rel="tag">Unity</a>,<a href="http://technorati.com/tags/Dependency Injection" rel="tag">Dependency Injection</a>,<a href="http://technorati.com/tags/Inversion of Control" rel="tag">Inversion of Control</a></div>
<p><div style="display:inline;margin:0;padding:0;"><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!267.entry"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!267.entry" /></a></div>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
</div>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/itworksonmymachine.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/itworksonmymachine.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=8&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2008/09/08/unity-dependency-injection-and-inversion-of-control-container/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!267.entry" medium="image" />
	</item>
		<item>
		<title>I Hate Bug Reports</title>
		<link>http://itworksonmymachine.wordpress.com/2008/08/26/i-hate-bug-reports/</link>
		<comments>http://itworksonmymachine.wordpress.com/2008/08/26/i-hate-bug-reports/#comments</comments>
		<pubDate>Tue, 26 Aug 2008 02:12:00 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2008/08/26/i-hate-bug-reports</guid>
		<description><![CDATA[I hate bug reports not because I have an ego and I think I write excellent code which can never have bugs or that I don&#8217;t want to fix them but because they often leave crucial information to reproduce the bug and/or what was the expected result and why the results are wrong and I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=9&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!258" class="bvMsg">
<p>I hate bug reports not because I have an ego and I think I write excellent code which can never have bugs or that I don&#8217;t want to fix them but because they often leave crucial information to reproduce the bug and/or what was the expected result and why the results are wrong and I end up in a wild goose chase hunting the testers for answers. </p>
<p>If the tester is not reporting the bug correctly, the developer will most likely reject this bug stating as not reproducible and assign it back the tester. The tester would most probably argue that the bug is there and it can be reproduced and a whole mess ensnares where the developer and tester both end up kicking the ball back and forth at each other. Not only is this time lost in non productivity but it gets pretty frustrating pretty fast. </p>
<p>If you want a bug to be fixed you need to report the bug effectively. So here are just a few pointers to our testers: </p>
<ul>
<li>The bug title should describe the issue completely. Bug title will help developers to quickly analyze the bug nature. It saves time when we don’t need to open the whole bug report to know what the problem is. Keep in mind bug title is used as a reference to search the bug in the bug tracking tool so add in any keywords in the title which you think might help in finding the bug.
<li>If your bug is not reproducible it will never get fixed. You should clearly mention the steps to reproduce the bug in the minimalist steps possible. Developers need to be able to get to the problem in the shortest time. Do not assume or skip any reproducing step. Always step through the steps yourself and make sure you don&#8217;t leave a step. Make sure your steps are robust enough to reproduce the bug without any ambiguity. Don&#8217;t assume that the developers can read your mind &#8211; don&#8217;t assume that they will do a few extra steps you think are obvious.
<li>Never include more than one issue per report. If you have multiple issues, post separate bug reports for each and mark them as related. Reporting multiple bugs in one report will most likely cause your report to be closed when only part of it is implemented.
<li>Do not post new bug or feature requests about the same bug or feature. Doing so takes a lot of time for us to merge your reports. The search feature of the bug tracking system is everyone&#8217;s friend.
<li>Report the problem immediately. If you find any bug while testing, do not wait to write detail bug report later. Instead write the bug report immediately. This will ensure a good and reproducible bug report. If you decide to write the bug report later on then chances are high to miss the important steps in your report.
<li>To create the highest quality bug report which will save developers time and increase the likelihood the bug is fixed, a little extra work goes a long way:
<ul>
<li>Is the bug tied to a single setting or is there a small range of cases? Identify the range.
<li>What other user actions cause the error to occur?
<li>Does the error occur with different settings or options selected?</ul>
<li>Attachments are extremely helpful
<ul>
<li>Screenshots with comments really help understand the problem. A picture is worth 1000 words.
<li>At the same time a picture should not be there to replace reproduce steps. The bug should still be captured in text even if a screenshot is attached.</ul>
<li>A bug report should always contain the expected and observed results. Often times the developers don&#8217;t think that the bug is a real bug so it helps to explicitly list the expected and observed results. It is the testers duty to explain to the developers what went wrong.
<li>Don&#8217;t use the bug report as a stepping stone &#8211; we have enough politics in the office already.</ul>
<p>No doubt that your bug report should be a high quality document. Focus on writing good bug reports, spend some time on this task because this is main communication point between tester, developer and manager. Mangers should make aware to their team that writing a good bug report is primary responsibility of any tester. Your efforts towards writing good bug report will not only save company resources but also create a good relationship between you and developers. </p>
<p>Oh and one final note; just because the system performs differently that what was expected does not necessarily mean it is a bug. Remember &quot;The best tester is the one who gets the most bugs fixed&quot; &#8211; <a href="http://www.kaner.com/" target="_blank">Cem Kaner</a> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!258.entry"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!258.entry" border="0" /></a></div>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/itworksonmymachine.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/itworksonmymachine.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=9&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2008/08/26/i-hate-bug-reports/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!258.entry" medium="image" />
	</item>
		<item>
		<title>Visual Studio 2008 and .NET Framework 3.5 SP1 RTM is here</title>
		<link>http://itworksonmymachine.wordpress.com/2008/08/12/visual-studio-2008-and-net-framework-3-5-sp1-rtm-is-here/</link>
		<comments>http://itworksonmymachine.wordpress.com/2008/08/12/visual-studio-2008-and-net-framework-3-5-sp1-rtm-is-here/#comments</comments>
		<pubDate>Mon, 11 Aug 2008 18:47:46 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[VisualStudio 2008]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2008/08/12/visual-studio-2008-and-net-framework-3-5-sp1-rtm-is-here</guid>
		<description><![CDATA[RTM SP1 for Visual Studio 2008 and .NET Framework 3.5 is out and available for download http://msdn.microsoft.com/en-us/vstudio/products/cc533448.aspx Visual Studio 2008 SP1 and .NET Framework 3.5 SP1 significantly improve the developer experience during the development process, and at runtime. These improvements address top issues reported by customers. For more information, see Visual Studio 2008 SP1 and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=10&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!255" class="bvMsg">
<p>RTM SP1 for Visual Studio 2008 and .NET Framework 3.5 is out and available for download <a title="http://msdn.microsoft.com/en-us/vstudio/products/cc533448.aspx" href="http://msdn.microsoft.com/en-us/vstudio/products/cc533448.aspx">http://msdn.microsoft.com/en-us/vstudio/products/cc533448.aspx</a> </p>
<p>Visual Studio 2008 SP1 and .NET Framework 3.5 SP1 significantly improve the developer experience during the development process, and at runtime. These improvements address top issues reported by customers. For more information, see <a href="http://msdn.microsoft.com/vstudio/products/cc533447.aspx">Visual Studio 2008 SP1 and .NET Framework 3.5 SP1</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!255.entry"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!255.entry" border="0" /></a> </div>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/itworksonmymachine.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/itworksonmymachine.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=10&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2008/08/12/visual-studio-2008-and-net-framework-3-5-sp1-rtm-is-here/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!255.entry" medium="image" />
	</item>
		<item>
		<title>Table-Valued parameter in SQL Server 2005</title>
		<link>http://itworksonmymachine.wordpress.com/2008/08/03/table-valued-parameter-in-sql-server-2005/</link>
		<comments>http://itworksonmymachine.wordpress.com/2008/08/03/table-valued-parameter-in-sql-server-2005/#comments</comments>
		<pubDate>Sat, 02 Aug 2008 23:05:45 +0000</pubDate>
		<dc:creator>M</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[SQL Server 2005]]></category>
		<category><![CDATA[T-SQL]]></category>
		<category><![CDATA[Table-Valued Parameters]]></category>

		<guid isPermaLink="false">http://itworksonmymachine.wordpress.com/2008/08/03/table-valued-parameter-in-sql-server-2005</guid>
		<description><![CDATA[In pre-SQL Server 2005 in order to pass in a set of values one had to create a temporary table, populate it with data using INSERT, and then just use it in the procedure or function since they are created for the current session and are available to all processes in that session. I did [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=11&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div id="msgcns!E149A8B1E1C25B14!222" class="bvMsg">
<p>In pre-SQL Server 2005 in order to pass in a set of values one had to create a temporary table, populate it with data using INSERT, and then just use it in the procedure or function since they are created for the current session and are available to all processes in that session. </p>
<p>I did a blog on how to pass in Table-Value Parameters in SQL Server 2008 but what if we have a need to pass in multiple rows of data to a T-SQL statement, or a routine such as stored procedure or function in SQL Server 2005? </p>
<p>Turns out the same can be done in SQL Server 2005 without using temporary tables. By using the XML data type you can pass user-defined sets between queries and also between the client and the server. </p>
<p>The following code shows how you can create and use XML parameters.
<pre style="word-wrap:break-word;"><div style="display:inline;float:none;margin:0;padding:0;"><pre style="word-wrap:break-word;"><div><span style="color:#0000ff;">USE</span><span style="color:#000000;"> AdventureWorks;
</span><span style="color:#0000ff;">GO</span><span style="color:#000000;">

</span><span style="color:#0000ff;">CREATE</span><span style="color:#000000;"> </span><span style="color:#0000ff;">PROCEDURE</span><span style="color:#000000;"> uspEmployeeList(<span style="color:#008000;">@EmployeeList</span> <span style="color:#0000ff;">XML</span>)
</span><span style="color:#0000ff;">AS</span><span style="color:#000000;">
</span><span style="color:#0000ff;">BEGIN</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">SET</span><span style="color:#000000;"> NOCOUNT </span><span style="color:#0000ff;">ON</span><span style="color:#000000;">;

    </span><span style="color:#0000ff;">SELECT</span><span style="color:#000000;">    E.</span><span style="color:#808080;">*</span><span style="color:#000000;">
    </span><span style="color:#0000ff;">FROM</span><span style="color:#000000;">    HumanResources.Employee E
    </span><span style="color:#0000ff;">INNER</span><span style="color:#000000;"> </span><span style="color:#808080;">JOIN</span><span style="color:#000000;">    </span><span style="color:#008000;">@EmployeeList</span><span style="color:#000000;">.nodes(</span><span style="color:#ff0000;">'</span><span style="color:#ff0000;">/Root/E</span><span style="color:#ff0000;">'</span><span style="color:#000000;">) </span><span style="color:#0000ff;">AS</span><span style="color:#000000;"> Tbl(C)
        </span><span style="color:#0000ff;">ON</span><span style="color:#000000;">    E.EmployeeID </span><span style="color:#808080;">=</span><span style="color:#000000;"> Tbl.C.value(</span><span style="color:#ff0000;">'</span><span style="color:#ff0000;">@EmployeeID</span><span style="color:#ff0000;">'</span><span style="color:#000000;">, </span><span style="color:#ff0000;">'</span><span style="color:#ff0000;">INT</span><span style="color:#ff0000;">'</span><span style="color:#000000;">);

    </span><span style="color:#0000ff;">RETURN</span><span style="color:#000000;">;
</span><span style="color:#0000ff;">END</span><span style="color:#000000;">
</span></div></pre>
</div>
<div> </div>
<p>How are XML parameters supported in .NET? ADO.NET allows full support using SqlDbType.Xml type. Adding a XML as a parameter to the stored procedure from C# would have something like: </p>
<div style="display:inline;float:none;margin:0;padding:0;">
<pre><div style="display:inline;float:none;margin:0;padding:0;"><pre style="word-wrap:break-word;"><div><span style="color:#0000ff;">//string</span><span style="color:#000000;"> EmployeeXml </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#800000;">&quot;</span><span style="color:#800000;">&lt;Root&gt;&lt;E EmployeeID=\&quot;1\&quot; /&gt;&lt;E EmployeeID=\&quot;3\&quot; /&gt;&lt;E EmployeeID=\&quot;5\&quot; /&gt;&lt;E EmployeeID=\&quot;7\&quot; /&gt;&lt;E EmployeeID=\&quot;11\&quot; /&gt;&lt;/Root&gt;</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">;</span></div><div><span style="color:#000000;"></span> </div><div><span style="color:#000000;"></span><span style="color:#000000;"><font color="#008000">// Create the data table</font></span></div><div><span style="color:#000000;"><font color="#008080">DataTable</font><font> dt = <font color="#0000ff">new </font><font color="#008080">DataTable</font>(<font color="#800000">&quot;E&quot;</font>);</font><div><font face="Courier New"><font color="#008080"><font face="Courier New"><font color="#0000ff"><font color="#008000">// Create the table schema</font></font></font></font></font></div><div><font face="Courier New"><font color="#008080"><font>DataColumn</font></font><font> dc = dt.Columns.Add(<font color="#800000">&quot;EmployeeID&quot;</font>, <font color="#0000ff">typeof</font>(<font color="#0000ff">string</font>));</font></font></div><div><font face="Courier New"><font color="#0000ff"><font face="Courier New"><font color="#0000ff"><font color="#008000">// Add a few records to the data table.</font></font></font></font></font></div><div><font>for</font><font> (<font color="#0000ff">int</font> i = 1; i &lt;= 10; i++)</font></div><div><font face="Courier New"><font>&#123;</font></font></div><div><font face="Courier New"><font color="#008080"><font face="Courier New"><font color="#0000ff"><div><font color="#008000">      // create a new row</font></div><font>   </font><font face="Courier New"><font><font color="#0000ff">   </font></font></font></font></font><font>DataRow</font></font><font> dr = dt.NewRow();</font></font></div><div><font face="Courier New"><font face="Courier New"><font color="#008080"><font face="Courier New"><font color="#0000ff"><div><font color="#008000"><font><font color="#0000ff">   <font face="Courier New">   </font></font>// populate the fields</font></font></div><font>   </font><font face="Courier New"><font><font color="#0000ff">   </font></font></font></font></font></font></font><font>dr[0] = </font><font>i.ToString();</font></font></div><div><font face="Courier New"><font face="Courier New"><font color="#008080"><font face="Courier New"><font color="#0000ff"><div><font color="#008000"><font><font face="Courier New"><font face="Courier New"><font color="#008080"><font face="Courier New"><font color="#0000ff">   <font face="Courier New"><font color="#0000ff">   </font></font></font></font></font></font></font>// add the row to the table</font></font></div><font>   </font><font face="Courier New"><font><font color="#0000ff">   </font></font></font></font></font></font></font><font>dt.Rows.Add(dr);</font></font></div><div><font face="Courier New"><font>&#125;</font></font></div></span><span style="color:#000000;"></span></div><div><span style="color:#000000;">
...
System.Data.SqlClient.SqlCommand cmd </span><span style="color:#000000;">=</span><span style="color:#000000;"> </span><span style="color:#0000ff;">new</span><span style="color:#000000;"> System.Data.SqlClient.SqlCommand(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">uspEmployeeList</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">, sqlConn);
cmd.Parameters.Add(</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">@EmployeeList</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">, System.Data.SqlDbType.Xml);
//cmd.Parameters[</span><span style="color:#800000;">&quot;</span><span style="color:#800000;">@EmployeeList</span><span style="color:#800000;">&quot;</span><span style="color:#000000;">].Value </span><span style="color:#000000;">=</span><span style="color:#000000;"> EmployeeXml;
...</span></div><div><span style="color:#000000;"><span style="color:#000000;"><font color="#008000">// Create a temporary MemoryStream to hold the output</font><font color="#008000"> of the WriteXml method of the DataTable</font><div><div><font><font color="#0000ff">using</font> (<font color="#008080">MemoryStream</font> memoryStream = <font color="#0000ff">new </font><font color="#008080">MemoryStream</font>())</font><font></font></div><div><font>&#123;</font><font></font></div><div><font>	dt.WriteXml(memoryStream);</font><font></font></div><div><font><font color="#008080">         UTF8Encoding</font> encoding = <font color="#0000ff">new </font><font color="#008080">UTF8Encoding</font>();</font><font></font></div><div><font>         cmd.Parameters[<font size="2"><span style="color:#800000;">&quot;</span><span style="color:#800000;">@EmployeeList</span><span style="color:#800000;">&quot;</span></font>].Value = encoding.GetString(memoryStream.ToArray());</font><font></font></div><div><font>&#125;</font><font></font></div></div></span></span></div></pre>
</div>
</div>
<p>Now that's cool. This is much better than passing in a comma separated list and using a dynamic query in our procedure or function. </p>
<p>
<div style="display:inline;margin:0;padding:0;">Technorati Tags: <a href="http://technorati.com/tags/XML Data Type" rel="tag">XML Data Type</a>,<a href="http://technorati.com/tags/SqlDbType.Xml" rel="tag">SqlDbType.Xml</a>,<a href="http://technorati.com/tags/SQL Server 2005" rel="tag">SQL Server 2005</a></div>
<p><div style="display:inline;margin:0;padding:0;"><a href="http://www.dotnetkicks.com/kick/?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!222.entry"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!222.entry" border="0" /></a></div>
</p>
</div>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/itworksonmymachine.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/itworksonmymachine.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/itworksonmymachine.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/itworksonmymachine.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=itworksonmymachine.wordpress.com&#038;blog=17478847&#038;post=11&#038;subd=itworksonmymachine&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://itworksonmymachine.wordpress.com/2008/08/03/table-valued-parameter-in-sql-server-2005/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/5f655eac348da5fb8e349f7e47c83e0c?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">misbaharefin</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!222.entry" medium="image" />
	</item>
	</channel>
</rss>
