<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Steves Coding Blog &#187; Articles</title>
	<atom:link href="http://stevescodingblog.co.uk/category/articles/feed/" rel="self" type="application/rss+xml" />
	<link>http://stevescodingblog.co.uk</link>
	<description>Musings on software development, .Net platform and other stuff</description>
	<lastBuildDate>Wed, 02 May 2012 18:19:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Fun with action filters</title>
		<link>http://stevescodingblog.co.uk/fun-with-action-filters/</link>
		<comments>http://stevescodingblog.co.uk/fun-with-action-filters/#comments</comments>
		<pubDate>Wed, 02 May 2012 18:19:54 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[action filter]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=561</guid>
		<description><![CDATA[I was fortunate enough to be able to attend the brilliant DevWeek developer&#8217;s conference in London this year, and even more lucky to attend a lecture by Dino [..]]]></description>
			<content:encoded><![CDATA[<p>I was fortunate enough to be able to attend the brilliant <a title="Dev Week" href="http://www.devweek.com" target="_blank">DevWeek </a>developer&#8217;s conference in London this year, and even more lucky to attend a lecture by <a href="http://weblogs.asp.net/despos/" target="_blank">Dino Esposito</a> (please check out his brilliant <a href="http://www.amazon.com/Microsoft%C2%AE-NET-Architecting-Applications-PRO-Developer/dp/073562609X/ref=pd_sim_b_7" target="_blank">Architecting Applications for the Enterprise</a> book) on Asp.Net Action Filters. The purpose of his session was to demonstrate the importance of Action Filters and how we should all be using them much more than we normally do. I will be the first to admin that action filters are not the first possible solution that comes to mind when trying to solve a particular architectural problem in my Asp.Net MVC application.</p>
<p>I must say though, I was inspired. Yes, I realise I had <a title="AjaxOnly actions and controllers in Asp.Net MVC" href="http://stevescodingblog.co.uk/ajaxonly-actions-and-controllers-in-asp-net-mvc/" target="_blank">previously posted about one particular useful action filter</a>, but I really haven&#8217;t done too much with them until now. Dino put forth some uses for them, which I believe are discussed in more detail in his MVC book:</p>
<ul>
<li>Using an action filter to figure out which button was pressed (on a multi-button form) and compartmentalise the resulting code path</li>
<li>An action filter which automatically populates generic data on a view model (imagine a list of countries or some other static data required by your view)</li>
</ul>
<p>We&#8217;ve all had some grief with the first scenario at some stage or another. It&#8217;s just not quite as easy to do as one would expect. The second allows you to abstract away some data population code and generally keep things a bit tidier than they otherwise would.</p>
<p>Today I created another action filter which takes a CSV list of data, parses it, and gives you a strongly-typed list of values. It looks like this:</p>
<pre class="brush: csharp; title: Code:; notranslate">
[SplitString(Parameter=&quot;contentItemKeys&quot;, Delimiter=&quot;,&quot;)]
public virtual ActionResult GetItemInfo(IEnumerable&lt;Guid&gt; contentItemKeys)
{
}
</pre>
<p>So imagine that I have POSTed a comma-delimited list of GUIDs to this action. Normally, if there is one GUID then Asp.Net MVC should be able to resolve that properly and give you a list with one thing in it. However, if you have more than one GUID in that comma-delimited list, then you will have an empty list given to you. Why? Because the framework doesn&#8217;t know how to parse that list properly.</p>
<p>You could use a custom model binder to achieve the desired effect, but creating an action filter to do the same thing is much neater and much more flexible.</p>
<p>I&#8217;ve created an action filter called &#8216;SplitString&#8217; and it works like this:</p>
<ul>
<li>The filter accepts a couple of arguments: the parameter you want to act on, and the delimiter to use.</li>
<li>It overrides the <em>OnActionExecuting</em> method and looks for the specified parameter, first in the routing data, then in request data.</li>
<li>It then finds the type that each item should be, using a little reflection.</li>
<li>It then parses the list, converts each item in the parsed string to the desired type, and spits out the full list.</li>
</ul>
<p>First, the class definition:</p>
<pre class="brush: csharp; title: Code:; notranslate">
[AttributeUsage(AttributeTargets.Method)]
public class SplitStringAttribute : ActionFilterAttribute
{
    public string Parameter { get; set; }
    public string Delimiter { get; set; }

    public SplitStringAttribute()
    {
        Delimiter = &quot;,&quot;;
    }
</pre>
<p>Inside <em>OnActionExecuting</em>, lets find the value we need to work with:</p>
<pre class="brush: csharp; title: Code:; notranslate">
string value = null;
HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;

if (filterContext.RouteData.Values.ContainsKey(this.Parameter)
	&amp;&amp; filterContext.RouteData.Values[this.Parameter] is string)
{
	value = (string)filterContext.RouteData.Values[this.Parameter];
}
else if (request[this.Parameter] is string)
{
	value = request[this.Parameter] as string;
}
</pre>
<p>Next we need to find the type to convert to. Specifically, we need to find the type of the generic argument which forms the type of the parameter we&#8217;re interested in. So if our parameter is <em>IEnumerable&lt;T&gt;</em>, I want to know what type <em>T</em> is. I&#8217;ve wrapped this up in a method:</p>
<pre class="brush: csharp; title: Code:; notranslate">
Type listArgType = GetParameterEnumerableType(filterContext);
</pre>
<p>&nbsp;</p>
<pre class="brush: csharp; title: Code:; notranslate">
private Type GetParameterEnumerableType(ActionExecutingContext filterContext)
{
	var param = filterContext.ActionParameters[this.Parameter];
	Type paramType = param.GetType();
	Type interfaceType = paramType.GetInterface(typeof(IEnumerable&lt;&gt;).FullName);
	Type listArgType = null;

	if (interfaceType != null)
	{
		var genericParams = interfaceType.GetGenericArguments();
		if (genericParams.Length == 1)
		{
			listArgType = genericParams[0];
		}
	}

	return listArgType;
}
</pre>
<p>Here we simply:</p>
<ul>
<li>Find the type of the parameter using the <em style="line-height: 18px;">filterContext</em></li>
<li>Check to see if the type is <em style="line-height: 18px;">IEnumerable&lt;&gt;</em>. We do this simply by getting the interface and checking if it is not null</li>
<li>Finally we get any generic arguments, check that there is exactly one, and then return that type. This is the type that we will convert each item in our CSV list to.</li>
</ul>
<p>Next, we process our CSV string and create our container list:</p>
<pre class="brush: csharp; title: Code:; notranslate">
string[] values = value.Split(Delimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

Type listType = typeof(List&lt;&gt;).MakeGenericType(listArgType);
dynamic list = Activator.CreateInstance(listType);
</pre>
<p>We just split the string according to the delimiter that we need to use, then create a new generic list with the type we procured earlier. I&#8217;ve used a <em>dynamic</em> type here to make it much easier and more efficient to work with.</p>
<p>Next, we run through each value in our CSV list and add it to this new generic list:</p>
<pre class="brush: csharp; title: Code:; notranslate">
foreach (var item in values)
{
	try
	{
		dynamic convertedValue = TypeDescriptor.GetConverter(listArgType).ConvertFromInvariantString(item);
		list.Add(convertedValue);
	}
	catch (Exception ex)
	{
		throw new ApplicationException(string.Format(&quot;Could not convert split string value to '{0}'&quot;, listArgType.FullName), ex);
	}
}
</pre>
<p>The real magic here is the type converter. We can simply pass it a type and an item to convert and it will just do it for you, in a nice generic way. This means you don&#8217;t have to manually support a known list of types &#8211; let the framework handle that for you!</p>
<p>Finally, and the real cherry on top, is that to make all this work, we simply substitute the original action parameter value with this new list that we&#8217;ve just created:</p>
<pre class="brush: csharp; title: Code:; notranslate">
filterContext.ActionParameters[this.Parameter] = list;
</pre>
<p>The result is, your action parameter will now be populated correct with the parsed list of values, in a strongly typed fashion.</p>
<p><a href="http://dl.dropbox.com/u/5229980/scb/code/StringSplitFilterAttribute.zip" target="_blank">Download the full code file</a> if you wish to inspect it further, or to use as you like.</p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Fun with action filters - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/fun-with-action-filters/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/fun-with-action-filters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asp.Net Bundling, minification and convention</title>
		<link>http://stevescodingblog.co.uk/asp-net-bundling-minification-and-convention/</link>
		<comments>http://stevescodingblog.co.uk/asp-net-bundling-minification-and-convention/#comments</comments>
		<pubDate>Thu, 23 Feb 2012 18:32:06 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[bundling]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=527</guid>
		<description><![CDATA[The new &#8220;bundling&#8221; support in Asp.Net MVC 4 looks massively appealing to .Net web developers &#8211; finally, an integrated way to dynamically package up multiple Javascript/CSS files into [..]]]></description>
			<content:encoded><![CDATA[<p>The new <a href="http://weblogs.asp.net/scottgu/archive/2011/11/27/new-bundling-and-minification-support-asp-net-4-5-series.aspx" target="_blank">&#8220;bundling&#8221; support in Asp.Net MVC 4</a> looks massively appealing to .Net web developers &#8211; finally, an integrated way to dynamically package up multiple Javascript/CSS files into one request, and minify them on your behalf. Not only that, the results can be cached and reused until the files change. What&#8217;s not to like?</p>
<p>Today me and <a href="http://davidferguson.me.uk/" target="_blank">@evadi</a> discovered another little sparkle to this already very useful feature. I&#8217;ll highlight this specially to try and get across its importance:</p>
<p><strong>The bundling framework (by default) will automatically favour JS files which end in <em>.min.js</em>.</strong></p>
<p>This means that, when you enable default bundling in global.asax:</p>
<pre class="brush: csharp; title: Code:; notranslate">
BundleTable.Bundles.EnableDefaultBundles();
</pre>
<p>Then you put some scripts in a folder:</p>
<p><img class="alignnone size-full wp-image-540 colorbox-527" title="MyScripts" src="http://stevescodingblog.co.uk/wp-content/uploads/2012/02/scripts.png" alt="" width="158" height="55" /></p>
<p>And <em>then</em> you reference the bundle (as-per the new syntax) from your page:</p>
<pre class="brush: xml; title: Code:; notranslate">
&lt;script src=&quot;@System.Web.Optimization.
BundleTable.Bundles.ResolveBundleUrl(&quot;~/MyScripts/js&quot;)&quot;&gt;&lt;/script&gt;
</pre>
<p>Only <em>script.min.js</em> is actually returned in the request; <em>script.js</em> is completely ignored. I tried changing the filename of the former to <em>script-min.js</em> and I found that <strong>both</strong> scripts were being included in the returned script, so there is definitely some logic going on to try to make use of existing minified scripts if they are available, provided they follow this convention.</p>
<p>Not only that, but files with a <em>debug.js</em> extension are completely ignored.</p>
<h3>Controlling this behaviour</h3>
<p>To begin with, you can turn this behaviour off by setting the <em>EnableFileExtensionReplacements</em> property on <em>Bundle</em> to <em>false:</em></p>
<pre class="brush: csharp; title: Code:; notranslate">
Bundle bundle = new Bundle(&quot;~/myscripts/js&quot;, new JsMinify());
bundle.EnableFileExtensionReplacements = false;
</pre>
<p>After doing this, all the scripts in the specified folder which match the file mask will be loaded. This flag does not seem to affect files with a <em>debug.js</em> extension, they are still ignored.</p>
<p>You can also have influence over <em>which</em> extensions get treated as &#8220;special&#8221;. For example&#8217;s sake, say your convention is to have all minified Javascript files have the extension of <em>.minified.js</em>, then you can register this extension by adding it to the <em>FileExtensionReplacementList</em> collection on the Bundle table:</p>
<pre class="brush: csharp; title: Code:; notranslate">BundleTable.Bundles.FileExtensionReplacementList.Add(&quot;minified&quot;);</pre>
<p>It gets a bit sticky now because this opens up the possibility of including multiple minified files, especially if you have a mix of conventions in one directory. So what else can you do?</p>
<h3>Build a custom bundle type</h3>
<p>You can also create a new Bundle type which inherits from <em>System.Web.Optimization.Bundle</em> and alter the behaviour there. Luckily, a method named <em>EnumerateFiles</em> can be overridden, and a new implementation supplied. As another example, imagine that I wanted to filter out anything that contained the word &#8216;min&#8217; in order to make sure that my Javascript files were processed by a funky custom minifier that I had just written, and I didn&#8217;t want to use files that had already been minified by some other process:</p>
<pre class="brush: csharp; title: Code:; notranslate">
// CustomBundle.cs
public class CustomBundle : Bundle
{
  public CustomBundle(string vpath, IBundleTransform transform)
    : base(vpath, transform)
  {
  }

  public override IEnumerable&lt;System.IO.FileInfo&gt; EnumerateFiles(BundleContext context)
  {
    var files = base.EnumerateFiles(context);

    // select only non-minified files (according to naming convention)
    files = files.Where(c =&gt; c.Name.Contains(&quot;min&quot;) == false).ToList();

    return files;
  }
}

// global.asax.cs
Bundle bundle = new CustomBundle(&quot;~/myscripts/js&quot;, new JsMinify());
bundle.AddDirectory(&quot;~/myscripts&quot;, &quot;*.js&quot;);
BundleTable.Bundles.Add(bundle);
</pre>
<p>Unfortunately even at this stage any files which end with <em>debug.js</em> are filtered out for us &#8211; so far I haven&#8217;t found a way to extend the framework to prevent this behaviour. I&#8217;m keeping in mind that this isn&#8217;t a final release, and that some work may be done in this area before the final version appears.</p>
<p>In conclusion, this certainly eases my mind when throwing the default bundler at a folder which contains a mix of minified and unminified libraries, knowing that &#8211; provided the filenames follow convention &#8211; it will pick out the correct one and minify it if necessary. Also, if needed I can provide implementations which can select the files I want to bundle up without having to manually add each individual file manually; for a large project, this can easily become unwieldy.</p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Asp.Net Bundling, minification and convention - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/asp-net-bundling-minification-and-convention/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/asp-net-bundling-minification-and-convention/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>ScriptSharp: Taking care of &#8216;this&#8217;</title>
		<link>http://stevescodingblog.co.uk/scriptsharp-taking-care-of-this/</link>
		<comments>http://stevescodingblog.co.uk/scriptsharp-taking-care-of-this/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 19:22:12 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[script#]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=514</guid>
		<description><![CDATA[Making sure &#8216;this&#8217; points to exactly what you think it does in Javascript is one of the challenges that a new programmer to the language has to overcome. [..]]]></description>
			<content:encoded><![CDATA[<p>Making sure &#8216;this&#8217; points to exactly what you think it does in Javascript is one of the challenges that a new programmer to the language has to overcome. <a title="ScriptSharp" href="http://projects.nikhilk.net/ScriptSharp" target="_blank">Script#</a> makes this somewhat easy for us because it tries to make sure it points to exactly what we&#8217;d expect it to if we were writing a normal C# app.</p>
<p>Take this snippet, for example:</p>
<pre class="brush: csharp; title: Code:; notranslate">
jQueryObject buttons = jQuery.Select(&quot;.homepageCreateButton&quot;);

buttons.MouseOver(delegate(jQueryEvent e)
{
	jQueryObject button = jQuery.This;
});
</pre>
<p>Here I&#8217;m selecting some buttons and applying a click handler. The generated code here is as you would expect, where jQuery. This clearly translates to $(this):</p>
<pre class="brush: jscript; title: Code:; notranslate">
var buttons = $('.homepageCreateButton');

buttons.mouseover(function(e) {
    var button = $(this);
});
</pre>
<p>What happens though when I start using the C# keyword &#8216;this&#8217; in my delegate?</p>
<pre class="brush: csharp; title: Code:; notranslate">
jQueryObject buttons = jQuery.Select(&quot;.homepageCreateButton&quot;);

buttons.MouseOver(delegate(jQueryEvent e)
{
	jQueryObject button = jQuery.This;

	object a = this;
});
</pre>
<p>This gets compiled to:</p>
<pre class="brush: jscript; title: Code:; notranslate">
var buttons = $('.homepageCreateButton');
buttons.mouseover(ss.Delegate.create(this, function(e) {
    var button = $(this);
    var a = this;
}));
</pre>
<p>.. which is not quite the same thing. As soon as the Script# compiler has detected that I am making use of the &#8216;this&#8217; pointer it wraps the delegate call in a method and changes the context of the code inside the delegate so that &#8216;this&#8217; points to the current instance of the class. This is of course the exact behaviour we would expect and love in C#, and for the most part this is also a good thing in Javascript. By the way, <strong>this transformation also happens if you implicitly access a class-level member without using the &#8216;this&#8217; keyword</strong>.</p>
<p><em>However,</em> look at what it has done to our jQuery selector; we expected &#8216;this&#8217; to be the current element that we are handling the &#8216;mouseover&#8217; event for, but now that has changed and we are effectively selecting the current instance of the class through a jQuery selector, which of course is nonsense.</p>
<p>To get around this and make sure that you&#8217;re accessing the actual object that you want inside the delegate, you should make use of the <a title="jQuery CurrentTarget" href="http://api.jquery.com/event.currentTarget/" target="_blank">CurrentTarget property on jQueryEvent</a>:</p>
<pre class="brush: csharp; light: true; title: Code:; notranslate">jQueryObject button = jQuery.FromElement(e.CurrentTarget)</pre>
<p>Just be careful when you intend to use &#8216;this&#8217; and &#8216;jQuery.This&#8217; together in a delegate, as they will not behave as you would expect in this case.</p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="ScriptSharp: Taking care of 'this' - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/scriptsharp-taking-care-of-this/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/scriptsharp-taking-care-of-this/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UK Techdays 2011 in London</title>
		<link>http://stevescodingblog.co.uk/uk-techdays-2011-in-london/</link>
		<comments>http://stevescodingblog.co.uk/uk-techdays-2011-in-london/#comments</comments>
		<pubDate>Fri, 27 May 2011 13:23:58 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[techdays]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=451</guid>
		<description><![CDATA[I was able to get along to the UK Techdays event this year in Fulham (it&#8217;s a free event &#8211; if you can make the time, it&#8217;s worth [..]]]></description>
			<content:encoded><![CDATA[<p><a href="http://stevescodingblog.co.uk/wp-content/uploads/2011/05/blog-1.jpg"><img class="alignleft size-medium wp-image-456 colorbox-451" style="margin: 0 10px 10px 0;" title="Techdays 1" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/05/blog-1-300x225.jpg" alt="" width="300" height="225" /></a>I was able to get along to the <a href="http://uktechdays.cloudapp.net/home.aspx" target="_blank">UK Techdays</a> event this year in Fulham (it&#8217;s a free event &#8211; if you can make the time, it&#8217;s worth the trip) to hear about the latest developments in the Windows Azure platform and also Windows Phone 7.</p>
<p>The first day concerned Azure, and it was interesting to hear from the Microsoft techies and evangelists (<a href="http://blogs.msdn.com/b/david_gristwood/" target="_blank">David Gristwood</a>, <a href="http://blogs.msdn.com/b/ericnel/" target="_blank">Eric Nelson</a>, <a href="http://blogs.msdn.com/b/plankytronixx/" target="_blank">Steve Plank</a> and <a href="http://blogs.msdn.com/b/keithbu/" target="_blank">Keith Burns</a> amongst others) , giving us the low-down on features and also running through some brief tutorials which showed us how to accomplish specific tasks, like deploying new web roles and administering our platform instances via the control panel. Steve Plank took us through some more interesting aspects like connecting your local Active Directory to your virtual network in the Cloud, and also spoke a bit about AppFabric and the various components which it concerns.</p>
<p>It was also interesting to hear from external businesses which have based their products on Azure, or had at least implemented a solution based on the technology. The general theme is that, if you can move your infrastructure to the Cloud and get rid of your existing hardware, it really is a no-brainer. If anyone is thinking of implementing a high-volume scalable solution, then they can use this technology at a fraction of the price. One of the speakers mentioned that they were able to turn their six-figure annual costs into a three-figure monthly payment!</p>
<p>Keith Burns later gave a talk on the Sql Azure platform, and the differences between it and Sql Server. To be honest, the differences are fairly small (no full-text indexing or non-clustered indexes yet) but the sizes and costs seem a little prohibitive to me. There&#8217;s a maximum of 50Gb per database (which is a LOT of storage anyway, but you still have that limit whereas the Table Storage and Blob Storage technologies are vastly larger) and there&#8217;s a cost of £6.06 per Gb of data. There are of course data transfer costs, but these only apply when your data leaves the data centre &#8211; having an Sql Azure database which is used by a Web Role (for example) located within the same data centre will not occur any costs.</p>
<p>The second and third days were completed engulfed by Windows Phone 7 announcements, demos and more case studies from external developers (including <a href="http://cocktailflow.com/" target="_blank">Cocktail Flow</a> and <a href="http://www.verysoftware.co.uk/" target="_blank">Very Software</a>). They demonstrated how their applications were put together, design decisions they made and also presented demos of their applications running.</p>
<p><span id="more-451"></span></p>
<p><a href="http://brandonwatson.sys-con.com/" target="_blank">Brandon Watson</a> was there as the keynote speaker and gave some insight to the progress of the phone at the application repository which seems to be growing at some rate (1000+ new apps every month?). He also outlined some of the changes coming with the new &#8220;Mango&#8221; phone update and the new developer tools (which were released a couple of days ago).</p>
<p><a href="http://www.nachmore.com/" target="_blank">Oren Nachman</a> gave some great talks and demos surrounding performance on the phone, and highlighted the quite obvious issues with the standard list box and how slow it was with any decent size list. He walked through a simple broken application and attempted to fix it by using the proper debugging tools and applying the appropriate fixes. He also (on the second day) gave an account of the differences between Silverlight 4 on the desktop, and the forthcoming Silverlight 4 for the phone.</p>
<p><a href="http://stevescodingblog.co.uk/wp-content/uploads/2011/05/blog-2.jpg"><img class="alignright size-medium wp-image-457 colorbox-451" style="margin: 0 0 10px 10px;" title="Techdays 2" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/05/blog-2-300x225.jpg" alt="" width="300" height="225" /></a>Later, <a href="http://andywigley.sys-con.com/" target="_blank">Andy Wigley</a> (Appamundi) was on hand to give a complete demo of the new Sql CE for WP7, and set about converting an existing Xml-based phone app into one which makes use of Sql and Linq. By the looks of it, it&#8217;s almost exactly the same as the LinqToSql technology which is available on the desktop, except there is no designer. So all your entity classes and contexts must be created manually (including specifying all of the appropriate attributes and making sure you fire the usual PropertyChanging/PropertyChanged event pair for the change tracking to work. You could see during the demo that this is all very manual, and it will be a good day when some designer tools for this technology are released.</p>
<p>There was also a run-through of Expression Blend 4 by Brennon Williams, who showed us some design issues and how to create a functional prototype of an application using Sketchflow. No discredit to Brennon at all, because his talk and the presentation was excellent, but the topic missed the mark a little for me as a developer. I would have liked to have seen more about how to use Blend from the point of view of the developer &#8211; creating your application code in Visual Studio and then applying some gloss using Blend (which is what I understood the workflow to be). Nevertheless, I did enjoy it and hopefully such a topic will be part of next year&#8217;s event.</p>
<p>All in all, a good three days and would definitely attend next year. They do give out freebies and prizes and such, including geeky T-shirts, tokens for <a href="http://create.msdn.com/en-US/" target="_blank">AppHub </a>subscriptions (yours truly being the recipient of one such token!) and even phones!</p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="UK Techdays 2011 in London - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/uk-techdays-2011-in-london/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/uk-techdays-2011-in-london/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency Injection: A Beginner&#8217;s Guide</title>
		<link>http://stevescodingblog.co.uk/dependency-injection-beginners-guide/</link>
		<comments>http://stevescodingblog.co.uk/dependency-injection-beginners-guide/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 16:41:00 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[nuget]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=379</guid>
		<description><![CDATA[This article intends to outline the concept of Dependency Injection and its uses within a software engineering project. From Wikipedia.org: “it is a design pattern that separates behaviour [..]]]></description>
			<content:encoded><![CDATA[<p>This article intends to outline the concept of Dependency Injection and its uses within a software engineering project. From Wikipedia.org:</p>
<blockquote><p>“it is a design pattern that separates behaviour from dependency resolution, thus decoupling highly dependent components”.</p></blockquote>
<p>Later, I demonstrate the use of Dependency Injection within the context of an Asp.Net MVC 3 application.</p>
<p>Dependency Injection (or DI) allows us to provide implementations and services to other classes for consumption in a very loosely-coupled way. The key tenet is that such implementations can be swapped out for other implementations by changing a minimal amount of code, as the implementation and the consumer are linked by <em>contract</em> only.</p>
<p>In C#, this means that your service implementations should adhere to an interface, and when creating consumers for your services you should program against the <em>interface</em> and not the <em>implementation</em>, and require that the implementation is provided for you, or <em>injected</em> rather than having to create instances yourself. Doing this allows your classes to not worry about how dependencies are create nor where they come from; all that matters is the contract.</p>
<p><span id="more-379"></span></p>
<h2>Dependency Injection by Example</h2>
<p>Let’s go through a simple example where DI could be useful. First, let’s create an interface (the <em>contract</em>) which will allow us to perform some task, say logging a message:</p>
<pre class="brush: csharp; title: Code:; notranslate">public interface ILogger
{
  void LogMessage(string message);
}
</pre>
<p>Notice that nothing about this interface describes how the message is logged and where it is logged to; it simply has the intention of recording a string to some repository. Next, lets create something which uses this interface. Say we create a class which watches a particular directory on disk, and logs a message whenever the directory is changed:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class DirectoryWatcher
{
  private ILogger _logger;
  private FileSystemWatcher _watcher;

  public DirectoryWatcher(ILogger logger)
  {
    _logger = logger;
    _watcher = new FileSystemWatcher(@&quot;C:\Temp&quot;);
    _watcher.Changed += new FileSystemEventHandler(Directory_Changed);
  }

  void  Directory_Changed(object sender, FileSystemEventArgs e)
  {
    _logger.LogMessage(e.FullPath + &quot; was changed&quot;);
  }
}
</pre>
<p>The key thing to notice is that the constructor, we require that something which implements <em>ILogger</em> is given to us, but again notice that we don’t care about where the log goes or how it is created. We can just program against the interface and not worry about it.</p>
<p>This means that in order to create an instance of our <em>DirectoryWatcher</em> we must also have an implementation of <em>ILogger</em> ready. Let’s go ahead and create one which logs messages to a text file:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class TextFileLogger : ILogger
{
  public void LogMessage(string message)
  {
    using (FileStream stream = new FileStream(&quot;log.txt&quot;, FileMode.Append))
    {
      StreamWriter writer = new StreamWriter(stream);
      writer.WriteLine(message);
      writer.Flush();
    }
  }
}
</pre>
<p>Let’s create another which logs messages to the Windows Event Log:</p>
<pre class="brush: csharp; title: Code:; notranslate">
public class EventFileLogger : ILogger
{
  private string _sourceName;

  public EventFileLogger(string sourceName)
  {
    _sourceName = sourceName;
  }

  public void LogMessage(string message)
  {
    if (!EventLog.SourceExists(_sourceName))
    {
      EventLog.CreateEventSource(_sourceName, &quot;Application&quot;);
    }
    EventLog.WriteEntry(_sourceName, message);
  }
}
</pre>
<p>Now we have two separate implementations which log messages in very different ways, but both implement <em>ILogger</em>, which means that either one can be used where an instance of <em>ILogger</em> is required. Now we can create an instance of <em>DirectoryWatcher</em> and have it use one of our loggers:</p>
<pre class="brush: csharp; title: Code:; notranslate">ILogger logger = new TextFileLogger();
DirectoryWatcher watcher = new DirectoryWatcher(logger);
</pre>
<p>Or, by just changing the right-hand side of the first line we can use our other implementation:</p>
<pre class="brush: csharp; title: Code:; notranslate">ILogger logger = new EventFileLogger();
DirectoryWatcher watcher = new DirectoryWatcher(logger);
</pre>
<p>This happens without any changes to the implementation of <em>DirectoryWatcher</em>, and this is the key concept. We are <em>injecting</em> our logger implementation into the consumer, so that the consumer doesn’t have to create this instance on its own. The example shown is trivial, but imagine using this in a large-scale project where you have several dependencies which need to be used by many times more consumers, and then suddenly a requirement comes along which means that the method of logging a message must change (say  the messages are required to be logged into Sql Server for auditing purposes). Without some form of dependency injection, you will have to carefully examine the code and change anything which actually creates an instance of a logger and then uses it. In a large project this can be painful and error prone. With DI, you would just have to change the dependency in one place, and the rest of your application will effectively absorb the change and immediately start using the new logging method.</p>
<p>Essentially, it solves the classic software problem of high-dependency and allows you to create a loosely-couple system which is extremely agile and easy to change.</p>
<h2>Dependency Injection Containers</h2>
<p>Many DI frameworks which you can download and use go a step further and employ the use of a Dependency Injection Container. This is essentially a class which stores a mapping of types and returns the registered implementation for that type. In our simple example we would be able to query the container for an instance of <em>ILogger</em> and it would return an instance of TextFileLogger, or whichever instance we had initialised the container with.</p>
<p>This has the advantage that we can register all of our type mappings in one place, usually in an “Application Start” event, and that gives us quick and clear visibility as to what dependencies we have in the system. Also, many professional frameworks allow us to configure the lifetime of such objects, either creating fresh instances every time we ask for one, or re-using instances across calls.</p>
<p>The container is usually created in such a way that we can get access to the ‘Resolver’ (the thing which allows us to query for instances) from anywhere in the project.</p>
<p>Finally, professional frameworks usually support the concept of “sub-dependencies”, where a dependency has itself one or more dependencies to other types also known to the container. In this case, the resolver can fulfil these dependencies too, giving you back a full chain of correctly created dependencies according to your type mappings.</p>
<p>Let’s create ourselves a very simple DI container to see how the concept works. This implementation doesn’t support nested dependencies, but does allow you to map an interface to an implementation and then query for that implementation later:</p>
<pre class="brush: csharp; title: Code:; notranslate">
public class SimpleDIContainer
{
  Dictionary&lt;Type, object&gt; _map;

  public SimpleDIContainer()
  {
    _map = new Dictionary&lt;Type, object&gt;();
  }

  /// &lt;summary&gt;
  /// Maps an interface type to an implementation of that interface, with optional arguments.
  /// &lt;/summary&gt;
  /// &lt;typeparam name=&quot;TIn&quot;&gt;The interface type&lt;/typeparam&gt;
  /// &lt;typeparam name=&quot;TOut&quot;&gt;The implementation type&lt;/typeparam&gt;
  /// &lt;param name=&quot;args&quot;&gt;Optional arguments for the creation of the implementation type.&lt;/param&gt;
  public void Map&lt;TIn, TOut&gt;(params object [] args)
  {
    if (!_map.ContainsKey(typeof(TIn)))
    {
      object instance = Activator.CreateInstance(typeof(TOut), args);
      _map[typeof(TIn)] = instance;
    }
  }

  /// &lt;summary&gt;
  /// Gets a service which implements T
  /// &lt;/summary&gt;
  /// &lt;typeparam name=&quot;T&quot;&gt;The interface type&lt;/typeparam&gt;
  public T GetService&lt;T&gt;() where T : class
  {
    if (_map.ContainsKey(typeof(T)))
      return _map[typeof(T)] as T;
    else
      throw new ApplicationException(&quot;The type &quot; + typeof(T).FullName + &quot; is not registered in the container&quot;);
  }
}
</pre>
<p>Then, we can construct a small program which creates a container, maps the types, and then queries for a service. Again a simple compact example but imagine what this would look like in a much larger application:</p>
<pre class="brush: csharp; title: Code:; notranslate">
class Program
{
  static SimpleDIContainer Container = new SimpleDIContainer();

  static void Main(string[] args)
  {
    // Map ILogger to TextFileLogger
    Container.Map&lt;ILogger, TextFileLogger&gt;();

    // Create a DirectoryWatcher using whatever implementation for ILogger contained in the DI container
    DirectoryWatcher watcher = new DirectoryWatcher(Container.GetService&lt;ILogger&gt;());
  }
}
</pre>
<h2>Dependency Injection with Asp.Net MVC 3 and Ninject</h2>
<p>Asp.Net MVC 3 is very well suited to dependency injection as it provides hooks and the framework for any DI vendor to create a suitable container. Whenever any controllers or views are created, they pass through the DI container for dependency resolution. It also provides a global way to retrieve dependencies from anywhere within the project.</p>
<p>Ninject (<a href="http://ninject.org/">http://ninject.org/</a>) is a DI container especially written for .Net and now has code to specifically make use of the new DI features in MVC 3. Coupled with the latest versions of MVC 3, VS2010 and the popular Nuget Package Manager, it is extremely easy to get up and running with DI using Ninject within an Asp.Net MVC 3 project.</p>
<p>Let’s run through an example of using Ninject with MVC 3 to implement our small logging framework. This tutorial requires a few bits and pieces which you should install if you haven’t done so already:</p>
<ul>
<li>VS2010 (Professional or Express editions)</li>
<li>Asp.Net MVC 3 (<a href="http://www.asp.net/mvc/mvc3">http://www.asp.net/mvc/mvc3</a>)</li>
<li>Nuget Package Manager for VS2010 (<a href="http://nuget.codeplex.com/">http://nuget.codeplex.com/</a>)</li>
</ul>
<p>If you wish, you can download the <a href="http://dl.dropbox.com/u/5229980/scb/code/MvcNinjectExample.zip">complete project source</a> to follow along with.</p>
<h2><span style="font-size: 13px; font-weight: normal;">Once the above has been installed, let’s begin:</span></h2>
<h2><span style="font-size: 13px; font-weight: normal;">1) Open up VS2010 and create a new MVC 3 Web Application (I’ve called mine MvcNinjectExample):</span></h2>
<p><a href="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial1.png"><img class="alignnone size-medium wp-image-390 colorbox-379" title="DI MVC 1" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial1-300x207.png" alt="" width="300" height="207" /></a></p>
<p>After this screen you will get a dialog asking you to choose an Empty application or an Internet Application – just choose “Empty”.</p>
<p>2) Once the project has loaded, right-click ‘References’ in solution explorer and choose “Add library package reference..” (this is Nuget in action):</p>
<p><img class="alignnone size-full wp-image-391 colorbox-379" title="tutorial2" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial2.png" alt="" width="401" height="219" /></p>
<p>3) On the left, choose “Online” then search for Ninject. In the search results, you should be able to see “Ninject.Mvc3”. Select this and click the ‘Install’ button:</p>
<p><a href="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial-3.png"><img class="alignnone size-medium wp-image-389 colorbox-379" title="DI MVC 3" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial-3-300x200.png" alt="" width="300" height="200" /></a></p>
<p>This will download Ninject and all the other things it needs in order to work, including the WebActivator library, which gives us a place to create our dependencies.</p>
<p>4) Once everything has installed, look for the ‘AppStart_NinjectMVC3.cs’ file which has now appeared in your solution and open it:</p>
<pre class="brush: csharp; title: Code:; notranslate">namespace MvcNinjectExample {
  public static class AppStart_NinjectMVC3 {

    public static void RegisterServices(IKernel kernel)
    {
      //kernel.Bind&lt;IThingRepository&gt;().To&lt;SqlThingRepository&gt;();
    }

    public static void Start() {
      // Create Ninject DI Kernel
      IKernel kernel = new StandardKernel();

      // Register services with our Ninject DI Container
      RegisterServices(kernel);

      // Tell ASP.NET MVC 3 to use our Ninject DI Container
      DependencyResolver.SetResolver(new NinjectServiceLocator(kernel));
    }
  }
}
</pre>
<p>You can see here how the Ninject Kernel is created, which is responsible for resolving our types. In RegisterServices() is where we would bind our contracts to our implementations. The DependencyResolver is used to register Ninject for type injection, which means that Ninject is used to resolve dependencies whenever they are needed by MVC.</p>
<p>Let’s have a quick look at how we can apply our logger to this and get our controllers using our logging framework.</p>
<p>5) Add a new folder called ‘Logging’ to the solution and create a new class called <em>ILogger</em>, and copy this code into it (overwrite the class which has been generated for you):</p>
<pre class="brush: csharp; title: Code:; notranslate">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcNinjectExample.Logging
{
  public interface ILogger
  {
    void LogMessage(string message);
  }
}
</pre>
<p>Create another class called TextFileLogger and copy this code into it, again overwriting the class which was generated for you:</p>
<pre class="brush: csharp; title: Code:; notranslate">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Hosting;

namespace MvcNinjectExample.Logging
{
  public class TextFileLogger : ILogger
  {
    public void LogMessage(string message)
    {
      string path = Path.Combine(HostingEnvironment.MapPath(&quot;~/app_data&quot;), &quot;log.txt&quot;);
      using (FileStream stream = new FileStream(path, FileMode.Append))
      {
        StreamWriter writer = new StreamWriter(stream);
        writer.WriteLine(message);
        writer.Flush();
      }
    }
  }
}
</pre>
<p>You will need to include a using statement for System.IO at the top of the file to get access to the FileStream class. Once all done, you should end up with your code and solution looking like this:</p>
<p><a href="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial5.png"><img class="alignnone size-medium wp-image-393 colorbox-379" title="DI MVC 5" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial5-300x236.png" alt="" width="300" height="236" /></a></p>
<p>Note that I have also created the App_Data directory (which is needed by the TextFileLogger) so that the log file has somewhere to go.</p>
<p>6) Now, head back to your “AppStart_NinjectMVC3.cs” file and set up the binding for this class:</p>
<pre class="brush: csharp; title: Code:; notranslate">public static void RegisterServices(IKernel kernel)
{
  kernel.Bind&lt;ILogger&gt;().To&lt;TextFileLogger&gt;();
}
</pre>
<p>7) Finally, lets create a controller which uses it. Right-click on the ‘Controllers’ folder in Solution Explorer, select ‘Add &gt;’ and choose the ‘Controller…’ option at the very top. Give it a name of “HomeController” and press enter.</p>
<p>Inside this controller, we create a constructor which takes a parameter of <em>MvcNinjectExample.Logging.ILogger</em>, and we’ll save that into a class-level private variable for later. Ninject is going to give us the actual implementation of that in accordance with the bindings we set up in the last step. I’ve also modified the index view so that is just returns a piece of content rather than looking for a view; this is just to prevent exceptions from being thrown as I’m not creating a view for this example. Finally, I’ve also called into the logger from the index view to log a message for us. After we run the page, we should get a log.txt file in the App_Data directory containing our message.</p>
<p>After my modifications, the controller now looks like this:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class HomeController : Controller
{
  MvcNinjectExample.Logging.ILogger _logger;

  public HomeController(MvcNinjectExample.Logging.ILogger logger)
  {
    _logger = logger;
  }

  public ActionResult Index()
  {
    _logger.LogMessage(&quot;Running index page!&quot;);

    return Content(&quot;Message logged&quot;);
  }
}
</pre>
<p>This is the general pattern you will use with Dependency Injection in MVC; including your dependency contracts in your controller’s constructor, having Ninject fulfil the dependencies for you then consuming them from within the controller actions.</p>
<p>Let’s put a breakpoint in the constructor and see what we get when we run the project:</p>
<p><a href="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial6.png"><img class="alignnone size-medium wp-image-394 colorbox-379" title="DI MVC 6" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial6-300x25.png" alt="" width="300" height="25" /></a></p>
<p>As we intended, without doing any additional code than what I’ve presented here, we now have an instance of <em>ILogger</em> passed to us when the controller was created. This has happened because MVC has effectively asked Ninject to create this controller for us. During creation, Ninject has noticed that it requires an implementation of <em>ILogger</em> in order to create this controller. Since we registered a binding to <em>ILogger</em> in AppStart_NinjectMVC3, it knows how to create one of these and so it can go ahead and completely fulfil the dependency on this controller. Hence we have Dependency Injection.</p>
<p>If I let the solution run again, we should hit the Index action and the text file will be created with the log message inside it:</p>
<p><img class="alignnone size-full wp-image-395 colorbox-379" title="DI MVC 7" src="http://stevescodingblog.co.uk/wp-content/uploads/2011/02/tutorial7.png" alt="" width="531" height="345" /></p>
<p>If you were to change this to use our EventFileLogger implementation as in one of the earlier examples, you will see that all you would have to do is create the implementation, make it implement <em>ILogger</em> and then register it in your kernel bindings. No changes to any controllers which use it are necessary.</p>
<p>You should now follow this pattern when adding more dependencies to your project, and as your project scales in size you will see how easy it is to manage components in a loosely-coupled fashion even within a web project such as this. It gives you lots of flexibility and ultimately makes your projects a lot more maintainable and easy to change and adapt.</p>
<p><a href="http://dl.dropbox.com/u/5229980/scb/code/MvcNinjectExample.zip">Download project source code</a></p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Dependency Injection: A Beginner's Guide - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/dependency-injection-beginners-guide/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/dependency-injection-beginners-guide/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Data Caching with .Net 4.0 and Asp.Net MVC – part 3</title>
		<link>http://stevescodingblog.co.uk/net4-caching-with-mvc-3/</link>
		<comments>http://stevescodingblog.co.uk/net4-caching-with-mvc-3/#comments</comments>
		<pubDate>Tue, 16 Nov 2010 14:14:39 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[.net 4.0]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[memorycache]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=295</guid>
		<description><![CDATA[Welcome to part 3 of this short data caching series. In the previous parts we had a look at how we can employ smart in-memory data caching to [..]]]></description>
			<content:encoded><![CDATA[<p>Welcome to part 3 of this short data caching series. In the previous parts we had a look at how we can employ smart in-memory data caching to avoid round-trips back to the database when using Sql Server and the Entity Framework, set in an Asp.Net MVC context. I showed you how you can seamlessly query from cached or non-cached data, how to update cache items on inserts and updates, and wrapped this up in an extensible framework to keep everything nice and clean. In case you missed those parts, you can view them here:</p>
<ul>
<li><a href="http://stevescodingblog.co.uk/net4-caching-with-mvc/">Part 1</a></li>
<li><a href="http://stevescodingblog.co.uk/net4-caching-with-mvc-2/">Part 2</a></li>
</ul>
<p>I received some emails and comments asking a couple of different questions. How can this concept be applied to Sql Server without using EF? How can we create a dependency between Sql Server and our framework? This article is an attempt at answering these two questions, and as it turns out is also a great showcase for just how extensible our little framework is.. because I&#8217;m just about to <em>hack it to bits</em>. This article starts from where part 2 left off, so I strongly recommend you download the code from part 2 if you haven&#8217;t coded it to that point yourself.</p>
<p><a href="http://dl.dropbox.com/u/5229980/scb/code/CachingDemo.Web%202.zip">Download source code from part 2</a></p>
<h2>How can this concept be applied to Sql Server without using the Entity Framework?</h2>
<p>In case you haven&#8217;t guessed by now, the answer to this is fairly simple &#8211; essentially we just create a new implementation of <em>IVehicleRepository</em> and utilise the normal Ado.Net objects to interact with our database. My solution in this article deals with the following:</p>
<ul>
<li>Refactoring <em>VehicleRepository</em> and moving some common code and methods into an abstract base class so that we can utilise some common bits and pieces in our new repository class</li>
<li>Creating a new repository class <em>SqlVehicleRepository</em>, which uses Ado.Net to retrieve data from the database</li>
<li>A crud<em>e</em> <strong>Unit of Work</strong> implementation with transaction support</li>
</ul>
<p>So, to being with lets set about refactoring our current repository class into a common base class. The main reason for doing this is because the code surrounding the cache and opting to do a database read is fairly common to any repository. Since we&#8217;ve already abstracted away the actual implementation of our cache, this refactoring is a fairly simple affair.</p>
<p><span id="more-295"></span></p>
<p>Our base class looks like this:</p>
<pre class="brush: csharp; title: Code:; notranslate">
public abstract class VehicleRepositoryBase : IVehicleRepository
{
  public VehicleRepositoryBase()
    : this(new DefaultCacheProvider())
  {
  }

  public VehicleRepositoryBase(ICacheProvider cacheProvider)
  {
    this.Cache = cacheProvider;
  }

  /// &lt;summary&gt;
  /// Gets the key used to store vehicle data in the cache
  /// &lt;/summary&gt;
  protected virtual string CacheKey
  {
    get { return &quot;vehicles&quot;; }
  }

  /// &lt;summary&gt;
  /// Gets the cache provider instance
  /// &lt;/summary&gt;
  public ICacheProvider Cache { get; protected set; }

  /// &lt;summary&gt;
  /// Gets the vehicle data.
  /// &lt;/summary&gt;
  public virtual IEnumerable&lt;Vehicle&gt; GetVehicles()
  {
    // First, check the cache
    var vehicleData = GetCachedData();

    // If it's not in the cache, we need to read it from the repository
    if (vehicleData == null)
    {
      // Get the data
      vehicleData = LoadData().ToDictionary(v =&gt; v.Id);

      if (vehicleData.Any())
      {
        // Put this data into the cache for 30 minutes
        Cache.Set(CacheKey, vehicleData, 30);
      }
    }

    return vehicleData.Values;
  }

  /// &lt;summary&gt;
  /// Loads the data from the data store
  /// &lt;/summary&gt;
  protected abstract IEnumerable&lt;Vehicle&gt; LoadData();

  /// &lt;summary&gt;
  /// Inserts a new vehicle
  /// &lt;/summary&gt;
  public abstract void Insert(Vehicle vehicle);

  /// &lt;summary&gt;
  /// Updates a vehicle
  /// &lt;/summary&gt;
  public abstract void Update(Vehicle vehicle);

  /// &lt;summary&gt;
  /// Saves the data changes.
  /// &lt;/summary&gt;
  public abstract void SaveChanges();

  /// &lt;summary&gt;
  /// Clears the data from the cache.
  /// &lt;/summary&gt;
  public void ClearCache()
  {
    Cache.Invalidate(this.CacheKey);
  }

  protected Dictionary&lt;Guid, Vehicle&gt; GetCachedData()
  {
    var cacheData = Cache.Get(CacheKey) as Dictionary&lt;Guid, Vehicle&gt;;
    return cacheData;
  }
}
</pre>
<p>Note that it still implements <em>IVehicleRepository</em> for us, and simply marks most of the available methods as <em>asbtract</em> so that we can implement later. The key thing though is the concept surrounding <em>GetVehicles()</em> and <em>LoadData()</em>. The former is the consumer&#8217;s entry point to getting some data, where the latter is <strong>only</strong> concerned with actually reading the data from the data source.  This means that our base class can be concerned with all the caching stuff that we don&#8217;t want to have to worry about every time we create a new repository, and all we have to do with our specific repository implementations is actually load the data.</p>
<p>This leaves our<em> VehicleRepository</em> implementation without a <em>GetVehicles()</em> implementation, but instead has a <em>LoadData()</em> implementation:</p>
<pre class="brush: csharp; title: Code:; notranslate">
public class VehicleRepository : VehicleRepositoryBase
{
  protected CachingDemoEntities DataContext { get; private set; }

  public VehicleRepository()
    : this(new DefaultCacheProvider())
  {
  }

  public VehicleRepository(ICacheProvider cacheProvider)
    : base(cacheProvider)
  {
    this.DataContext = new CachingDemoEntities();
  }

  /// &lt;summary&gt;
  /// Load the data from the data source
  /// &lt;/summary&gt;
  protected override IEnumerable&lt;Vehicle&gt; LoadData()
  {
    return DataContext.Vehicles.OrderBy(v =&gt; v.Name).ToList();
  }

  /// &lt;summary&gt;
  /// Updates a vehicle
  /// &lt;/summary&gt;
  public override void Update(Vehicle vehicle)
  {
    if (vehicle.EntityState == EntityState.Detached)
    {
      DataContext.AttachTo(&quot;Vehicles&quot;, vehicle);
    }
    DataContext.ObjectStateManager.ChangeObjectState(vehicle, EntityState.Modified);
  }

  /// &lt;summary&gt;
  /// Inserts a vehicle
  /// &lt;/summary&gt;
  public override void Insert(Vehicle vehicle)
  {
    DataContext.AddToVehicles(vehicle);
  }

  /// &lt;summary&gt;
  /// Saves data changes to the data store
  /// &lt;/summary&gt;
  public override void SaveChanges()
  {
    // Update or add new/existing entities from the changeset
    var changeset = DataContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified);

    DataContext.SaveChanges();

    var cacheData = GetCachedData();

    if (cacheData != null)
    {
      foreach (var item in changeset)
      {
        var vehicle = item.Entity as Vehicle;
        cacheData[vehicle.Id] = vehicle;
      }
    }
  }
}
</pre>
<p>In addition to removing <em>GetVehicles()</em> and adding <em>LoadData()</em>, I&#8217;ve just provided some constructor overloads so that we can still pass through implementations of <em>ICacheProvider</em> to our base class, since that is handling the caching mechanisms now. The rest of the class remains basically the same; remember to mark each method with the <em>override</em> keyword also.</p>
<h3>Implementing SqlVehicleRepository</h3>
<p>This is where things get more interesting. Now that we have a solid base class which abstracts away the management of the cache, we can go ahead and implement our Ado.Net version of our repository. <strong>Note </strong>that since I have an Entity Framework model set up with my <em>Vehicle</em> class and I&#8217;m just about to demonstrate a new implementation using the same database table, I&#8217;m just going to use that same generated class here also, even though it has some extra EF junk on it that we don&#8217;t really need for this implementation. If you want to separate the two out and create a completely separate plain entity for this step, feel free as long as you feel able to follow along with the following.</p>
<p>The main bulk of the work here is to implement <em>LoadData()</em>. We&#8217;re simply going to use all the old Ado.Net objects here, so if you&#8217;ve used them before there should be no surprises here. Lets load the data:</p>
<pre class="brush: csharp; title: Code:; notranslate">
protected override IEnumerable&lt;Vehicle&gt; LoadData()
{
  var connection = CreateConnection();
  var command = new SqlCommand()
  {
    Connection = connection,
    CommandType = System.Data.CommandType.Text,
    CommandText = VEHICLE_SELECT
  };

  List&lt;Vehicle&gt; vehicles = new List&lt;Vehicle&gt;();

  using (connection)
  {
    connection.Open();

    var reader = command.ExecuteReader();

    if (reader.HasRows)
    {
      while (reader.Read())
      {
        var vehicle = new Vehicle()
        {
          Id = (Guid)reader[&quot;Id&quot;],
          Name = (string)reader[&quot;Name&quot;],
          Price = (decimal)reader[&quot;Price&quot;]
        };

        vehicles.Add(vehicle);
      }
    }
  }

  return vehicles;
}
</pre>
<p>As you can see, we&#8217;re simply reading the data in using normal Ado.Net objects and spitting out a list of <em>Vehicle</em>. The only thing I haven&#8217;t shown you is the <em>VEHICLE_SELECT</em> constant, which I have defined at the top of my class. I&#8217;ve also defined constants for inserting and updating (which I will use in a moment), where the actual values to be inserted/updated will go in the place of the parameter names defined in the constant:</p>
<pre class="brush: csharp; title: Code:; notranslate">#region Query Constants

private const string VEHICLE_SELECT = @&quot;Select * From Vehicle&quot;;
private const string VEHICLE_INSERT = @&quot;Insert Into Vehicle (Id, Name, Price) Values (@Id, @Name, @Price)&quot;;
private const string VEHICLE_UPDATE = @&quot;Update Vehicle Set Name=@Name, Price=@Price Where Id=@Id&quot;;

#endregion
</pre>
<p>We also need an implementation of <em>CreateConnection()</em>, which is as simple as it sounds. It reads the connection string from the application configuration file, and returns us a new instance of <em>SqlConnection</em>:</p>
<pre class="brush: csharp; title: Code:; notranslate">
/// &lt;summary&gt;
/// Creates the SqlConnection instance
/// &lt;/summary&gt;
private SqlConnection CreateConnection()
{
  return new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;DemoConnectionString&quot;].ConnectionString);
}
</pre>
<p><em>DemoConnectionString</em> is a connection string entry which I have defined in my web.config file. You will need to add this entry and configure it to point to your own data store appropriately:</p>
<p>Since we are inheriting this class from <em>VehicleRepositoryBase</em>, this data is now automatically cached for us in the same way as the Entity Framework version was, thanks to our smart little framework. We&#8217;re not quite done yet though, as we still need to implement our inserting and updating.</p>
<h3>Inserts, updates and units of work</h3>
<p>The main thing to notice about the Entity Framework version is, thanks to the EF object context all the items to be inserted, updated and deleted are recorded and actioned later in a batch, rather than at the time we actually make the call to insert, update or delete something. This is the <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html" target="_blank">Unit of Work pattern</a> in action, and we will implement a basic version of it here. The basic idea is to keep a list of things we want to insert and update for later, and when <em>SaveChanges()</em> is invoked, run through these lists and perform the database actions.</p>
<p>To start, I&#8217;ve created two lists at the top of my class to hold these changes, and also gone ahead and implemented the methods for inserting and updating:</p>
<pre class="brush: csharp; title: Code:; notranslate">
private HashSet&lt;Vehicle&gt; _inserts;
private HashSet&lt;Vehicle&gt; _updates;

public override void Insert(Vehicle vehicle)
{
  if (!_inserts.Contains(vehicle))
    _inserts.Add(vehicle);
}

public override void Update(Vehicle vehicle)
{
  if (!_updates.Contains(vehicle))
    _updates.Add(vehicle);
}
</pre>
<p><strong>Note:</strong> I haven&#8217;t shown the code here, but I&#8217;ve just initialised these lists in my constructor &#8211; I recommend you do the same.</p>
<p><em>SaveChanges()</em> is where the real action happens. We&#8217;re going to run through each list in turn, build up the correct SQL statements, and then execute them against the server. We&#8217;re also going to update our cached values, clear the Unit of Work lists, and wrap the whole thing inside a transaction to keep us from getting erroneous data if something goes wrong.</p>
<pre class="brush: csharp; title: Code:; notranslate">
public override void SaveChanges()
{
  var cached = GetCachedData();
  List&lt;Vehicle&gt; itemsToRecache = new List&lt;Vehicle&gt;();

  using (var connection = CreateConnection())
  {
    connection.Open();

    using (TransactionScope scope = new TransactionScope())
    {
      // Process inserts
      foreach (var vehicle in _inserts)
      {
        var command = new SqlCommand() { Connection = connection, CommandType = System.Data.CommandType.Text };

        command.CommandText = VEHICLE_INSERT;
        command.Parameters.Add(CreateParameter(&quot;Id&quot;, SqlDbType.UniqueIdentifier, vehicle.Id));
        command.Parameters.Add(CreateParameter(&quot;Name&quot;, SqlDbType.VarChar, vehicle.Name));
        command.Parameters.Add(CreateParameter(&quot;Price&quot;, SqlDbType.Decimal, vehicle.Price));

        command.ExecuteNonQuery();

        // Insert this vehicle into our cache
        itemsToRecache.Add(vehicle);
      }

      // Process updates:
      foreach (var vehicle in _updates)
      {
        var command = new SqlCommand() { Connection = connection, CommandType = CommandType.Text };

        command.CommandText = VEHICLE_UPDATE;
        command.Parameters.Add(CreateParameter(&quot;Id&quot;, SqlDbType.UniqueIdentifier, vehicle.Id));
        command.Parameters.Add(CreateParameter(&quot;Name&quot;, SqlDbType.VarChar, vehicle.Name));
        command.Parameters.Add(CreateParameter(&quot;Price&quot;, SqlDbType.Decimal, vehicle.Price));

        command.ExecuteNonQuery();

        itemsToRecache.Add(vehicle);
      }

      scope.Complete();
    }
  }

  itemsToRecache.ForEach(item =&gt;
  {
    cached[item.Id] = item;
  });

  _inserts.Clear();
  _updates.Clear();
}

private SqlParameter CreateParameter(string name, SqlDbType type, object value)
{
  var param = new SqlParameter(name, type);
  param.Value = value;
  return param;
}
</pre>
<p>I&#8217;ve added a method which is just a wrapper for creating a basic <em>SqlParameter</em>, as it can be a bit fiddly to do inline otherwise. A hidden mechanic at work here is the updating of the cache; we keep a list of items to be re-cached, instead of just updating the cache directly while iterating through the items of work, because we don&#8217;t want the cache to be updated if for some reason the transaction doesn&#8217;t complete while processing later items. If an error occurs, we just want the data to remain as it was, both in the cache and from the database.</p>
<p>Remember to clear the lists once the work has been completed, or else the same items will be processed again when you next call <em>SaveChanges() </em>using the same instance<em>.</em></p>
<p>This wraps up the <em>SqlVehicleRepository</em> implementation. The final thing to do is change your controller to use this implementation of the repository instead of the EF version we created in previous articles, like so:</p>
<pre class="brush: csharp; title: Code:; notranslate">
public HomeController()
  : this(new SqlVehicleRepository())
{
}
</pre>
<p>So now, without any further change to the presentation layer you should have your data coming through your <em>SqlVehicleRepository</em> code path instead of your EF implementation, and it should all be cached appropriately. What we&#8217;ve effectively done is abstracted our caching code to a level where we can easily add new cached data stores to our application without too much work, and proved the concept by creating such a data store. You should be able to see now how you could easily add an Xml-based store to the application, for example.</p>
<h2>How can we create a dependency between Sql Server and our framework?</h2>
<p>As I mentioned at the top of the article, there were two pertinent questions about this work, and this is the second. Unfortunately, the answer is not as straight-forward as the first. As I discovered during my research for this article and through my own development tests, it&#8217;s actually very difficult to implement an Sql cache dependency between the application and Sql Server using the new caching framework provided by the .Net Framework 4. I never actually got it working, and I had to jump through quite a few hoops just to reach dead-ends where nothing would be cached.</p>
<p>In my mind, this is no bad thing as really I would not want to implement such a dependency. Whenever a record in the database changes, the whole cache is dropped and recreated. This does not scale well and as your dataset (and your user count!) grows, you will find that the cache will be constantly dropped and re-created, making it completely inefficient and pointless. A <em>far</em> better solution is to implement a smart caching strategy which does not create a live dependency against the database, and just accept that if for any reason your data changes through actions which do not route through your application, you will encounter stale data.</p>
<h3>However..</h3>
<p>That said, I changed tact and got a working solution, and as it turns out is yet another example of how flexible our little framework can be &#8211; although you might not like it..</p>
<p>My solution for this problem is to fall back to the original <em>System.Web.Caching</em> framework to implement our in-memory cache. We already have an interface set up from previous articles which allow us to abstract away an implementation of the cache, and so here we can just implement another one which uses the old framework.</p>
<p>If you&#8217;ve looked into doing this yourself, you&#8217;ve probably seen many arguments which form for and against using <em>System.Web.Caching</em>, mainly because of the namespace name. The &#8216;Web&#8217; part of the namespace has unruly connotations in the context of our quest for abstraction and a layered approach to developing applications. The truth is the namespace is the only part which should cause concern; the actual cache works fine outside of a web context and can be used as normal.</p>
<p>My implementation here is specifically geared towards using the cache in conjunction with our Sql data implementation, and uses <em>SqlCacheDependency</em> to create the dependency between our data code and the database itself.</p>
<p>The <em>dbEntryName</em> parameter you see in the constructor is actually the name of the cache dependency element in our web.config file (I cover this in a moment), rather than the name of the database. It just so happens I&#8217;ve named it the same as my database.</p>
<p>Here is the implementation:</p>
<pre class="brush: csharp; title: Code:; notranslate">
public class SqlDependancyCacheProvider : ICacheProvider
{
  private Cache _cache;

  public string DbEntryName { get; set; }

  public string TableName { get; set; }

  public SqlDependancyCacheProvider(string dbEntryName, string tableName)
  {
    _cache = System.Web.HttpRuntime.Cache;
    DbEntryName = dbEntryName;
    TableName = tableName;
  }

  public object Get(string key)
  {
    return _cache[key];
  }

  public void Set(string key, object data, int cacheTime)
  {
    SqlCacheDependency dep = new SqlCacheDependency(DbEntryName, TableName);
    _cache.Add(key, data, dep, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(cacheTime), System.Web.Caching.CacheItemPriority.Normal, null);
  }

  public bool IsSet(string key)
  {
    return (_cache[key] != null);
  }

  public void Invalidate(string key)
  {
    _cache.Remove(key);
  }
}
</pre>
<p>They key thing to note here is that it implements our <em>ICacheProvider</em> interface. Because of this, we can just plug it into our <em>SqlVehicleRepository</em> instance to start using it!</p>
<pre class="brush: csharp; title: Code:; notranslate">
public SqlVehicleRepository()
  : this(new SqlDependancyCacheProvider(&quot;CachingDemo&quot;, &quot;Vehicle&quot;))
{
}
</pre>
<p>You can of course pass it through to the constructor from the controller. &#8220;CachingDemo&#8221; in this case is the name of the caching dependency entry from the web.config file (more on this in a minute), and &#8220;Vehicle&#8221; is the name of the table that I want to create a dependency on.</p>
<p>There are a couple of things we need to take care of in order for the caching to actually work.</p>
<h3>1. Enabling cache notification on the database tables</h3>
<p>To set up the tables so that they can notify the cache when the data has changed, you need to run a couple of commands on your database and the table. Open up your Visual Studio Command Prompt from your start menu to run these.</p>
<p>These commands are:</p>
<pre class="brush: plain; title: Code:; notranslate">
aspnet_regsql.exe -S &lt;server&gt; -U &lt;user&gt; -P &lt;password -d &lt;database&gt; -ed
aspnet_regsql.exe -S &lt;server&gt; -U &lt;user&gt; -P &lt;password&gt; -E -d &lt;database&gt; -t &lt;tablename&gt; -et
</pre>
<p>The first command will install the necessary tables and stored procedures which are required in order the change notification to work. In the command above, you will need to replace <em>server, user</em>, <em>password </em>and <em>database</em> with your own settings. If you connect to your database using Windows Authentication you can leave out the -U and -P parameters altogether.</p>
<p>The second command installs the triggers which effectively cause the cache to invalidate when ever the data is altered. This command is run against a specific table, so you will need to run it against every table you wish to enable caching on. Again, configure the parameters according to your own connection to Sql Server.</p>
<p>Run these commands now.</p>
<h3>2. Web configuration for caching</h3>
<p>The second part to getting all of this working is to add an entry into the web.config which tells the caching framework how to connect to your database, and other parameters like poll time and so on. Place the following inside your web.config file somewhere inside the <em>system.web</em> element:</p>
<pre class="brush: xml; title: Code:; notranslate">
&lt;caching&gt;
  &lt;sqlCacheDependency enabled=&quot;true&quot; pollTime=&quot;1000&quot; &gt;
  &lt;databases&gt;
    &lt;add name=&quot;CachingDemo&quot; connectionStringName=&quot;DemoConnectionString&quot; /&gt;
  &lt;/databases&gt;
  &lt;/sqlCacheDependency&gt;
&lt;/caching&gt;
</pre>
<p>The important thing is to make sure that <em>connectionStringName</em> points to a valid connection string setting within your configuration file. The &#8216;name&#8217; attribute is just an arbitrary symbol given to this cache dependency element, so that it can be reference by name when you create instances of <em>SqlCacheDependency</em>.</p>
<p>And that&#8217;s all there is to it. You should now be able to load up your page, verify that data is coming from our new cache provider (using the power of debugging and breakpoints) and also change the database data and have the application reload the data from the data store and rehydrate the in-memory cache.</p>
<p>Hopefully those who enquired about these issues have found this useful!</p>
<p><a href="http://dl.dropbox.com/u/5229980/scb/code/CachingDemo.Web%203.zip">Download the source code for part 3</a></p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Data Caching with .Net 4.0 and Asp.Net MVC – part 3 - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/net4-caching-with-mvc-3/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/net4-caching-with-mvc-3/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Asp.Net and Colorbox: Creating a &#8216;delete&#8217; confirmation dialog</title>
		<link>http://stevescodingblog.co.uk/asp-net-colorbox-delete-dialog/</link>
		<comments>http://stevescodingblog.co.uk/asp-net-colorbox-delete-dialog/#comments</comments>
		<pubDate>Fri, 17 Sep 2010 13:37:41 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[colorbox]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=220</guid>
		<description><![CDATA[This article was inspired by a friend of mine who wanted to implement a delete confirmation dialog in his website, and I thought it might be a useful [..]]]></description>
			<content:encoded><![CDATA[<p>This article was inspired by a <a href="http://twitter.com/hawkpie" target="_blank">friend of mine</a> who wanted to implement a delete confirmation dialog in his website, and I thought it might be a useful little tutorial to write about.</p>
<p>These days, I like to use the excellent <a href="http://colorpowered.com/colorbox/" target="_blank">Colorbox </a>for this sort of thing. In case you haven&#8217;t heard of it or used it before, it&#8217;s simply a brilliant jack-of-all-trades Javascript pop-up library based on the even more awesome <a href="http://jquery.com" target="_blank">jQuery</a>. It can display anything in a pop-up, from arbitrary Html content, flash video and an image gallery depending on how you set it up. In the past I&#8217;ve used Thickbox for this sort of thing, but as it&#8217;s not maintained any more (not to mention Colorbox looks <em>a lot</em> nicer) I prefer this.</p>
<p>For this tutorial, imagine the following scenario:</p>
<ul>
<li>You have some sort of form you use to add/edit some data</li>
<li>This form has the usual &#8216;Save&#8217;, &#8216;Cancel&#8217; and &#8216;Delete&#8217; buttons hanging off the bottom of it</li>
<li>When the user clicks &#8216;Delete&#8217;, you want to show them a dialog asking the user if the <em>really</em> want to delete</li>
</ul>
<p>For the delete confirmation you could just redirect the user to another page and show the confirmation there, but this method is cooler, not to mention ludicrously easy. Best of all, it doesn&#8217;t interfere <em>too</em> much with the .Net code you would have had to write anyway. So let&#8217;s get going.</p>
<p><img class="alignnone size-full wp-image-249 colorbox-220" title="Dialog" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/09/Dialog.png" alt="" width="346" height="273" /></p>
<p><span id="more-220"></span></p>
<h2>1. Creating the Visual Studio Project</h2>
<p>For this tutorial I am using the Asp.net Website project template from Visual Studio 2010. If you&#8217;re using VS2008, the website project template in there will also do fine, but you won&#8217;t get all the jQuery files you need. You can download them separately using the links below.</p>
<p>Create a standard Web Site project, choose a location to save your files and hit &#8216;Ok&#8217;:</p>
<p><img class="alignnone size-full wp-image-233 colorbox-220" title="Create a website project" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/09/Project.png" alt="" width="636" height="221" /></p>
<h2>2. Grab Colorbox &amp; jQuery</h2>
<p>Grab the latest version of Colorbox from their site (1.3.9 at the time of writing). Extract the archive to somewhere temporary on your hard-drive &#8211; the file structure inside the .zip file isn&#8217;t <em>quite</em> suited to just being plonked into a website, so we&#8217;ll need to sort that out first.</p>
<p>Basically for the purposes of this demo you will want to create a simple file layout for this stuff. As I&#8217;m using Visual Studio 2010 and the &#8216;Website&#8217; project template, I already have a &#8216;Scripts&#8217; folder set up for me. I&#8217;m just going to shove my Colorbox files in there in a sub-folder named &#8216;Colorbox&#8217;. I&#8217;ll put all the images and css files in there also. So, just grab the relevant files and folders from the archive you just downloaded and copy them into your website project so that you end up with a structure that looks like this:</p>
<p><strong><img class="alignnone size-full wp-image-234 colorbox-220" title="Colorbox demo file structure" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/09/FileStructure.png" alt="" width="265" height="377" /></strong></p>
<p>You will also need to <a href="http://docs.jquery.com/Downloading_jQuery#Download_jQuery" target="_blank">download jQuery</a>, although if you&#8217;re using Visual Studio 2010 you will already have the appropriate libraries there ready for you when you create a new website project. If you need to download it, just save in the &#8216;Scripts&#8217; folder as in the image above.</p>
<h2>3. Register jQuery and Colorbox on the page</h2>
<p>Now to register jQuery and Colorbox on our page. For now, I&#8217;m going to work entirely within <strong>Default.aspx</strong>, so we will just register our scripts in there instead of the master page (which is where this might normally go). Include jQuery, Colorbox and the Colorbox css files at the top of Default.aspx. Again, because I&#8217;ve used the new VS2010 website templates, it has already created me a nice project with a master page and so on. On Default.aspx, it&#8217;s also created references to content placeholders, including a HeadContent which will end up in the &lt;head&gt; tag on the page when it is rendered. I&#8217;m going to include my JS references in there, but really at the end of the day they just need to go somewhere on your page:</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;asp:Content ID=&quot;HeaderContent&quot; runat=&quot;server&quot; ContentPlaceHolderID=&quot;HeadContent&quot;&gt;

&lt;script src=&quot;/Scripts/jquery-1.4.1.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script src=&quot;/Scripts/Colorbox/jquery.colorbox-min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;link href=&quot;/Scripts/Colorbox/colorbox.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;

&lt;/asp:Content&gt;</pre>
<p><strong>By the way</strong>, the paths here assume that you&#8217;re running the website outside of a virtual directory &#8211; Visual Studio has a habit of creating website projects in virtual directories and not at the root of the URL. If you fire up the article source code, load it into VS and find that none of the scripts can be found when you test it out, that&#8217;s probably why. Simply click on the website project node in Solution Explorer, hit the F4 key to bring up the properties window and set the <em>VirtualPath</em> setting to just &#8216;/&#8217; (without the quotes).</p>
<p><img class="alignnone size-full wp-image-250 colorbox-220" title="Virtual Path setting" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/09/VirtualPath.png" alt="" width="321" height="165" /></p>
<h2>4. Create the dummy form</h2>
<p>Imagine here that we have a form which is set up to edit the details of a piece of fruit from market (for the sake of the demo). I&#8217;m going to have a field which allows the user to edit the name of the fruit, and two buttons which perform a <strong>Save</strong> and a <strong>Delete</strong> operation. The only thing which is of importance to this demo is the <em>Delete</em> button; the rest of it is just fluff that I&#8217;m adding to give more ambience to the demo.</p>
<p>The form which I have created looks like this (I just created this under all the stuff that VS2010 gives you by default on <strong>default.aspx</strong> when you create a new web site project):</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;div&gt;
  &lt;asp:Label runat=&quot;server&quot; AssociatedControlID=&quot;FruitNameTextbox&quot;&gt;Fruit name:&lt;/asp:Label&gt;
  &lt;asp:TextBox runat=&quot;server&quot; ID=&quot;FruitNameTextbox&quot; /&gt;
&lt;/div&gt;

&lt;div&gt;
  &lt;asp:Button Text=&quot;Save&quot; ID=&quot;SaveButton&quot; runat=&quot;server&quot; /&gt;
  &lt;asp:Button Text=&quot;Delete&quot; ID=&quot;DeleteButton&quot; runat=&quot;server&quot; ClientIDMode=&quot;Static&quot; /&gt;
&lt;/div&gt;</pre>
<h2>5. Create the Colorbox dialog</h2>
<p>Now for the first meaty parts of the demo. To create the dialog which will be shown by Colorbox, we simply define an area of Html which is to be shown <em>inside</em> the dialog when it is opened, and wrap the whole thing inside a <em>div</em> tag with <em>display: none</em> defined as its style. This is so that the dialog will not be displayed when the page is being viewed under normal circumstances. Furthermore, we attribute this area of Html with an <em>Id</em> so that Colorbox can pick it out.</p>
<p>For our dialog demo, we&#8217;re just going to ask the user to make sure that they <em>really</em> want to delete this item of fruit:</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;div style=&quot;display: none;&quot;&gt;
  &lt;div id=&quot;dialog&quot;&gt;

    &lt;h1&gt;Are you sure?&lt;/h1&gt;
    &lt;p&gt;Are you sure you want to delete this fruit?&lt;/p&gt;
    &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; This cannot be undone!&lt;/p&gt;

    &lt;asp:Button Text=&quot;Delete&quot; ID=&quot;ConfirmDeleteButton&quot; runat=&quot;server&quot; ClientIDMode=&quot;Static&quot; /&gt;
    &lt;asp:Button Text=&quot;Cancel&quot; Id=&quot;CancelDeleteButton&quot; runat=&quot;server&quot; ClientIDMode=&quot;Static&quot; /&gt;

  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>In here you&#8217;ll notice that we&#8217;ve put another two buttons &#8211; one for <em>actually</em> deleting something, and one for cancelling the dialog. We&#8217;ve also given the inner <em>div</em> tag an ID of &#8216;dialog&#8217; so that we can reference it when setting up Colorbox.</p>
<h2>6. Making the buttons work!</h2>
<p>Now that (almost!) everything is in place, we can work on the client-side stuff which will actually show the dialog and enable us to cancel out of it. First of all, showing the dialog takes only a few lines. Underneath the above code, we&#8217;ll open a new <em>script</em> tag and handle the click event of the <em>DeleteButton</em> to show the dialog box:</p>
<pre class="brush: jscript; title: Code:; notranslate">&lt;script type=&quot;text/javascript&quot;&gt;
  $(function ()
  {
    // 1. Wire up the delete button to show Colorbox:
    $(&quot;#DeleteButton&quot;).colorbox({ inline: true, href: &quot;#dialog&quot; });

    // 2. Handle the 'actual' delete button:
    $(&quot;#ConfirmDeleteButton&quot;).click(function()
    {
      $.fn.colorbox.close();
    });

    // 3. Handle the dialog cancel button:
    $(&quot;#CancelDeleteButton&quot;).click(function()
    {
      $.fn.colorbox.close();
      return false;
    });
  });
&lt;/script&gt;</pre>
<p>Here I am using some jQuery to pick up the page&#8217;s &#8216;load&#8217; event using the short-hand <em>$(function() {} );</em>. Next, I&#8217;m using the selector of <em>#DeleteButton</em> to assign Colorbox to, so when that button is clicked, it will activate the Colorbox dialog. You can see as one of the parameters I&#8217;m passing the ID of our dialog code and I&#8217;m also setting the <em>inline</em> property to &#8216;true&#8217;, meaning that we want Colorbox to display content which is inline with our page, and not a piece of content hosted elsewhere (another URL for example).</p>
<p>Next, in step 2 we&#8217;re wiring up the dialog&#8217;s <em>Delete</em> and <em>Cancel</em> buttons. The two handlers look very similar in that all they really do is close Colorbox. However, the <em>fundamental</em> difference is that the handler for the <em>Cancel </em>button returns &#8216;false&#8217;, preventing the default action from happening. The <em>ConfirmDeleteButton</em> however will continue on and the page will post back as normal and fire the click handler for that button (we will create this in a moment), whilst still closing the dialog.</p>
<h3>A Quick Note</h3>
<p>You&#8217;ll notice that the buttons are attributed with <em>ClientIdMode=&#8221;Static&#8221;</em>. In case you haven&#8217;t seen it before, this is a new feature in .Net 4 which allows us to ensure that the Html output for a .Net control will have the same ID value as the one we give it when writing the code. This means that .Net won&#8217;t &#8216;mangle&#8217; the name when used inside naming containers any more, and we can safely use the control ID from client-side code. Scott Guthrie has <a href="http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx" target="_blank">a detailed account ClientIdMode</a> on his tech blog.</p>
<p>If you are using .Net 3.5, change the jQuery selector to instead:</p>
<pre class="brush: jscript; title: Code:; notranslate">$(&quot;input[id$=_DeleteButton]&quot;)</pre>
<p>.. which basically says &#8220;Select any input element whose ID attribute value ends with _DeleteButton&#8221;, and you will get the same reliable result. You will also need to follow this for the buttons in the next section, which deal with cancelling and closing the dialog. <a href="http://www.west-wind.com/Weblog/posts/42319.aspx" target="_blank">Rick Strahl writes more about thi</a>s on his blog.</p>
<h2>7. The <em>ConfirmDeleteButton</em> handler</h2>
<p>The last thing we need to do is wire up a server-side event handler for the actual delete button. This is done as normal in your code-behind (or inline if you prefer) and is no different to how you would normally handle this elsewhere. For my demo, I don&#8217;t actually have anything to delete, but I will handle it just the same way.</p>
<p>If we step back to the <em>ConfirmDeleteButton</em> for a second, and modify the mark-up to add in the name of the click handler:</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;asp:Button Text=&quot;Delete&quot; ID=&quot;ConfirmDeleteButton&quot; runat=&quot;server&quot;
ClientIDMode=&quot;Static&quot; OnClick=&quot;ConfirmDeleteButton_Click&quot; /&gt;</pre>
<p>Then include the appropriate server-side handler in the code-behind:</p>
<pre class="brush: csharp; title: Code:; notranslate">protected void ConfirmDeleteButton_Click(object sender, EventArgs e)
{
  Response.Write(&quot;Fruit deleted!&quot;);
}</pre>
<p>In my case I&#8217;m not deleting anything, but in <em>your</em> case this would be the place to kick off any database deletes or file modifications/changes required, then redirect the user somewhere useful.</p>
<p>Now, if you run the application you should be able to click on the initial delete button, have the dialog appear to reveal another delete button and a cancel button. Clicking this delete button will close the dialog but also display a message at the top of the screen (thanks to the click handler being executed). Clicking the cancel button will also close the dialog but should not refresh the page or perform any server-side postback (thanks to the &#8216;return false;&#8217; in the Javascript click handler.</p>
<p><a href="http://dl.dropbox.com/u/5229980/scb/code/ColorboxDemo.zip" target="_blank">Download article source code</a></p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Asp.Net and Colorbox: Creating a 'delete' confirmation dialog - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/asp-net-colorbox-delete-dialog/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/asp-net-colorbox-delete-dialog/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Machine-specific Asp.Net configuration settings</title>
		<link>http://stevescodingblog.co.uk/machine-specific-asp-net-configuration-settings/</link>
		<comments>http://stevescodingblog.co.uk/machine-specific-asp-net-configuration-settings/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 15:19:27 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=177</guid>
		<description><![CDATA[One of the first things we noticed when we began to use version control to manage our source code is that configuration settings across multiple machines became unmanageable. [..]]]></description>
			<content:encoded><![CDATA[<p>One of the first things we noticed when we began to use version control to manage our source code is that configuration settings across multiple machines became unmanageable. For starters, different people checked out projects to different locations on their hard-drives, had different connection string settings depending on whether or not they were in the office or at home, and other people wanted different email settings than other developers, amongst a few other things.</p>
<p>What we needed was a per-machine configuration solution which could allow different settings for different developers, which should fall-back to reading the standard web.config if a setting wasn&#8217;t available in the custom file. This would effectively allow the developer to override settings as they see fit without affecting other developers. The following class to handle this is what we came up with. Most developers have the proverbial &#8220;toolbox&#8221; of code which they will utilise in most projects, and this is a good one for your collection.</p>
<p>The requirements that we would like to fulfil with our implementation are:</p>
<ul>
<li>Allows the developer to request an application setting or connection string by key</li>
<li>Should try to read the setting from an XML file from the root of the website. The file name should include the local machine name.</li>
<li>If the setting or connection string cannot be found, the class should attempt to read it from the web.config using the standard <em>ConfigurationManager</em> framework.</li>
<li>Because the machine-specific settings and connection strings should <em>override</em> the common settings from the web.config, an exception should be thrown if a setting which is defined in the host settings file does not also exist in the common settings file.</li>
<li>For performance reasons, the settings file should be cached in memory to keep from reading from disk every time a setting is read.</li>
</ul>
<p><a rel="nofollow" href="http://dl.dropbox.com/u/5229980/scb/code/ConfigSettingsProxy.zip">Download the source code to accompany this article</a></p>
<p>For starters then, I&#8217;ve called my implementation the <em>ConfigSettingsProxy</em>. Here&#8217;s the model we&#8217;ll end up with by the time we&#8217;ve finished this article:</p>
<p><img class="alignnone size-full wp-image-193 colorbox-177" title="ConfigSettingsProxy model" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/Configuration.png" alt="ConfigSettingsProxy model" width="617" height="603" /></p>
<p>Let&#8217;s just go through each of the objects and define their purpose.</p>
<p><span id="more-177"></span></p>
<h3>ConfigSettingsProxy</h3>
<p>This is the main public interface for our configuration framework. The two methods <em>GetAppSetting</em> and <em>GetConnectionString</em> simply allow us to retrieve application settings and connection strings respectively. It knows about two instances of ISettingsReader &#8211; a <em>HostSettingsReader</em>, which reads settings and connection strings specific to the host machine, and a <em>CommonSettingsReader</em>, which reads settings and connection strings which are common to all hosts (read: all developers). In actual fact, <em>ConfigSettingsProxy</em> only knows about the interface <em>ISettingsReader</em>, but it&#8217;s how it deals with the idea of host settings and common settings which is the real purpose, as we shall see in the next section.</p>
<h3>ISettingsReader</h3>
<p>This is the interface which defines what a settings reader can do. In this case, it can at least read <em>settings</em> and <em>connection strings</em>.</p>
<h3>HostSettingsReader</h3>
<p>This is the first implementation class which implements <em>ISettingsReader</em>, and this deals with the reading of host-specific settings and connection strings. It knows to look for a specific file name containing the host machine&#8217;s name and it knows about the format the file is in. It also performs caching and cache invalidation for us.</p>
<h3>CommonSettingsReader</h3>
<p>This is the second implementation of <em>ISettingsReader</em>, which knows how to read settings which are common to all machines. This simply reads from the appropriate sections from the web.config via the standard ConfigurationManager.</p>
<p>Lets dive into some code, starting with <em>ConfigSettingsProxy</em>:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class ConfigSettingsProxy
  {
    ISettingsReader _commonSettingsReader = null;
    ISettingsReader _hostSettingsReader = null;

    public ConfigSettingsProxy()
      : this(new HostSettingsReader(), new CommonSettingsReader())
    {
    }

    public ConfigSettingsProxy(ISettingsReader hostSettingsReader, ISettingsReader commonSettingsReader)
    {
      if (commonSettingsReader == null)
        throw new ArgumentNullException(&quot;commonSettingsReader&quot;);

      if (hostSettingsReader == null)
        throw new ArgumentNullException(&quot;hostSettingsReader&quot;);

      _commonSettingsReader = commonSettingsReader;
      _hostSettingsReader = hostSettingsReader;
    }

    public string GetAppSetting(string key)
    {
      var hostValue = _hostSettingsReader.GetSetting(key);
      var commonValue = _commonSettingsReader.GetSetting(key);

      if (hostValue == null)
        return commonValue;
      else
      {
        if (commonValue == null)
          throw new InvalidOperationException(&quot;Settings key '&quot; + key + &quot;' does not override a common setting&quot;);

        return hostValue;
      }
    }

    public string GetConnectionString(string name)
    {
      var hostValue = _hostSettingsReader.GetConnectionString(name);
      var commonValue = _commonSettingsReader.GetConnectionString(name);

      if (hostValue == null)
      {
        return commonValue;
      }
      else
      {
        if(commonValue == null)
          throw new InvalidOperationException(&quot;Connection string name '&quot; + name + &quot;' does not override a common connection string&quot;);

        return hostValue;
      }
    }
  }</pre>
<p>This class takes care of calling into the correct settings reader for us. For both <em>GetAppSetting</em> and <em>GetConnectionString</em> methods, it reads the value from both the host settings and the common settings readers. If the host setting has not been specified, it returns the common setting. Otherwise, it returns the host setting <em>only if</em> the common setting has also been specified. This check is in place to reinforce the mechanism of <em>overriding common settings</em>. Imagine what would happen if a developer was able to program against his own host settings without the same keys also being available to the other developers who didn&#8217;t know about these settings?</p>
<p>Just to finish this class off, the default constructor just initialises the class with the default implementations for host and common settings, but also allows you to specify new implementations if your solution requires it, or for unit testing. I haven&#8217;t covered it here but the sample project for this post contains unit tests which demonstrates this.</p>
<p>This class only knows about the <em>ISettingsReader</em> interface, so lets define exactly what that is:</p>
<pre class="brush: csharp; title: Code:; notranslate">public interface ISettingsReader
{
  string GetSetting(string key);
  string GetConnectionString(string connectionStringName);
}</pre>
<p>Simple stuff; it merely defines a contract for a class to retrieve settings and connection strings. The real power is in the following two implementation classes; <em>HostSettingsReader</em> and <em>CommonSettingsReader</em>.</p>
<h3>HostSettingsReader</h3>
<pre class="brush: csharp; title: Code:; notranslate">public class HostSettingsReader : ISettingsReader
{
  public string SettingsFilePath { get; private set; }

  public HostSettingsReader()
  {
    string machineName = Environment.MachineName;
    string fileName = string.Format(&quot;~/Settings_{0}.xml&quot;, machineName);
    string path = HostingEnvironment.MapPath(fileName);

    this.SettingsFilePath = path;
  }

  public HostSettingsReader(string path)
  {
    if (string.IsNullOrEmpty(path))
      throw new ArgumentNullException(&quot;path&quot;);
    this.SettingsFilePath = path;
  }

  public string GetSetting(string key)
  {
    XDocument settingsDocument = GetDocument();

    var query = from n in settingsDocument.Descendants(&quot;appSettings&quot;)
          from k in n.Elements()
          where k.Attribute(&quot;key&quot;).Value == key
          select k.Attribute(&quot;value&quot;).Value;

    return query.FirstOrDefault();
  }

  public string GetConnectionString(string name)
  {
    XDocument settingsDocument = GetDocument();

    var query = from n in settingsDocument.Descendants(&quot;connectionStrings&quot;)
          from k in n.Elements()
          where k.Attribute(&quot;name&quot;).Value == name
          select k.Attribute(&quot;connectionString&quot;).Value;

    return query.FirstOrDefault();
  }

  private XDocument GetDocument()
  {
    XDocument doc = MemoryCache.Default[&quot;LocalSettingsDocument&quot;] as XDocument;

    if (doc == null)
    {
      if (!File.Exists(this.SettingsFilePath))
      {
        XElement element = new XElement(&quot;settings&quot;,
                    new XElement(&quot;appSettings&quot;),
                    new XElement(&quot;connectionStrings&quot;));

        doc = new XDocument(element);
        doc.Save(SettingsFilePath);
      }
      else
      {
        doc = XDocument.Load(this.SettingsFilePath);
      }

      var policy = new CacheItemPolicy();
      policy.AbsoluteExpiration = DateTime.Now.AddYears(1);
      policy.ChangeMonitors.Add(new HostFileChangeMonitor(new string[] { this.SettingsFilePath }));

      MemoryCache.Default.Add(&quot;LocalSettingsDocument&quot;, doc, policy);
    }

    return doc;
  }
}</pre>
<p>The main things to note about this implementation are:</p>
<ul>
<li>By default, it looks for an Xml file in the root of the site called &#8220;Settings_&lt;machine name&gt;.xml&#8221;</li>
<li>It does assume you&#8217;re using a web site. For other project types where a web context is unavailable, a new implementation could be provided to get the file from elsewhere (or use the second constructor which takes a path name)</li>
<li>Settings are retrieved by simply opening up the file and looking for specific Xml nodes with the specified keys as attributes. If you think about it, the settings and connection strings in this file are specified in exactly the same way as you would in the web.config normally, meaning that they can just be copied out and pasted without further change in order to override a setting or connection string.</li>
<li>Caching is provided by the <a href="http://stevescodingblog.co.uk/category/caching" target="_blank">new caching objects in the .Net Framework since version 4.0</a>. Here the Xml setting files are cached for a year, but also specify a <em><a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.hostfilechangemonitor.aspx" target="_blank">HostFileChangeMonitor</a></em><a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.hostfilechangemonitor.aspx" target="_blank"> </a>so that when the settings are changed, the cache is invalidated and the new settings read on the next request.</li>
</ul>
<p>The other implementation we have is for common settings. These are simply read from the configuration file as normal, but wrapped up in an implementation of <em>ISettingsReader</em>:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class CommonSettingsReader : ISettingsReader
{
  public string GetSetting(string key)
  {
    return ConfigurationManager.AppSettings[key];
  }

  public string GetConnectionString(string connectionString)
  {
    if (ConfigurationManager.ConnectionStrings[connectionString] != null)
      return ConfigurationManager.ConnectionStrings[connectionString].ConnectionString;
    else
      return null;
  }
}</pre>
<p>As you can see, it&#8217;s nothing more complex than the standard code you would normally write in order to retrieve settings from the configuration file.</p>
<p>That then is the complete implementation. A sample host settings file would look like the following. As mentioned, the Xml has been formatted deliberately so that keys can be copied in and out of the web.config file without change.</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;settings&gt;
  &lt;appSettings&gt;
  &lt;add key=&quot;TestSetting&quot; value=&quot;This is a test setting from the local settings file!&quot; /&gt;
  &lt;/appSettings&gt;
  &lt;connectionStrings&gt;
  &lt;add name=&quot;TestConnectionString&quot; connectionString=&quot;This is a test connection string from the local settings file!&quot;/&gt;
  &lt;/connectionStrings&gt;
&lt;/settings&gt;</pre>
<p>Included in the downloadable source code for this project is a test website which contains the previous Xml settings file, plus this web page which demonstrates it working:</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;%@ Page Language=&quot;C#&quot; %&gt;

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;script runat=&quot;server&quot;&gt;

  public void Page_Load(object sender, EventArgs e)
  {
    var proxy = new ConfigurationProxy.ConfigSettingsProxy();

    ConfigurationSettingLiteral.Text = proxy.GetAppSetting(&quot;TestSetting&quot;);
    ConnectionStringLiteral.Text = proxy.GetConnectionString(&quot;TestConnectionString&quot;);
  }

&lt;/script&gt;

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head runat=&quot;server&quot;&gt;
  &lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
  &lt;div&gt;

    &lt;p&gt;Config setting: &lt;asp:Literal runat=&quot;server&quot; ID=&quot;ConfigurationSettingLiteral&quot; /&gt;&lt;/p&gt;
    &lt;p&gt;Connection string: &lt;asp:Literal runat=&quot;server&quot; ID=&quot;ConnectionStringLiteral&quot; /&gt;&lt;/p&gt;

  &lt;/div&gt;
  &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>In our production environment, we would create a class with static properties to match the configuration keys we had in our web.config file, using <em>ConfigSettingsProxy</em> to actually read the settings. This gave us hard-typed access to configuration whilst making them effectively override-able to match our own individual environments.</p>
<p><a rel="nofollow" href="http://dl.dropbox.com/u/5229980/scb/code/ConfigSettingsProxy.zip">Download the article source code</a></p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Machine-specific Asp.Net configuration settings - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/machine-specific-asp-net-configuration-settings/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/machine-specific-asp-net-configuration-settings/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Data Caching with .Net 4.0 and Asp.Net MVC – part 2</title>
		<link>http://stevescodingblog.co.uk/net4-caching-with-mvc-2/</link>
		<comments>http://stevescodingblog.co.uk/net4-caching-with-mvc-2/#comments</comments>
		<pubDate>Mon, 16 Aug 2010 20:16:49 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[memorycache]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[objectcache]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=127</guid>
		<description><![CDATA[This is the second article in a series about using the .Net 4.0 Caching objects in Asp.Net MVC &#8211; catch up first with part 1 of the series, [..]]]></description>
			<content:encoded><![CDATA[<p>This is the second article in a series about using the <strong>.Net 4.0 Caching objects in Asp.Net MVC</strong> &#8211; catch up first with<a href="http://stevescodingblog.co.uk/net4-caching-with-mvc/" target="_self"> part 1 of the series</a>, in case you missed it.</p>
<p>In this post I&#8217;m going to cover how we can invalidate our repository cache in a more fine-grained, efficient way; instead of simply dropping and re-creating the cache every time something is written to the database, we&#8217;re essentially going to replace updated items directly into the cache just after we write them to the database. This will involved hooking into Entity Framework&#8217;s change-set and picking out the entities we&#8217;re interested in.  I&#8217;m not going to cover the use of SqlDependancy here and the new wrappers within .Net 4.0.</p>
<p>If you <a href="http://dl.dropbox.com/u/5229980/scb/code/CachingDemo.Web%202.zip">download the sample project now</a>, you can follow along with the article. The sample project (and this article) continue on from where <a href="http://stevescodingblog.co.uk/net4-caching-with-mvc/">part 1 in this series</a> left off.</p>
<p>Over the course of this article, we&#8217;re going to do the following:</p>
<ul>
<li>Retrieve the objects which are being inserted, modified or deleted whenever we save changes</li>
<li>Use the changeset to identify entities which need to be added, updated or removed from the cache</li>
<li>Create a form to add and edit entities from the UI</li>
</ul>
<p>So this means we&#8217;re basically doing our own invalidation, and the only way the cache will be updated is to update entities through our UI. Any changes made to the data outside of the UI (for example, in Management Studio) will not be picked up unless the cache is explicitly invalidated.</p>
<p>Lets start by making the changes to our <em>IVehicleRepository</em> class.</p>
<p><span id="more-127"></span></p>
<p>Here we add support for updating an entity, adding a new entity and persisting the changes to the data store. The new interface looks like this:</p>
<pre class="brush: csharp; title: Code:; notranslate">public interface IVehicleRepository
{
	void ClearCache();
	IEnumerable GetVehicles();
	void Insert(Vehicle vehicle);
	void Update(Vehicle vehicle);
	void SaveChanges();
}</pre>
<p>We then add the implementation methods. Inserts and updates are fairly standard implementations. For updates, we have to mark the entity as being changed and attach it to the context. For inserts, we simply insert the entity into the Vehicles entity set.</p>
<pre class="brush: csharp; title: Code:; notranslate">public void Update(Vehicle vehicle)
{
	if (vehicle.EntityState == EntityState.Detached)
	{
		DataContext.AttachTo(&quot;Vehicles&quot;, vehicle);
	}
	DataContext.ObjectStateManager.ChangeObjectState(vehicle, EntityState.Modified);
}

public void Insert(Vehicle vehicle)
{
	DataContext.AddToVehicles(vehicle);
}</pre>
<p>For the implementation of <em>SaveChanges()</em> to work efficiently, we need to make a small change to <em>GetVehicles()</em>. The change is essentially to store a <em>Dictionary</em> of vehicles into the cache instead of a plain list. We can (and should) still return a flat list from the method however to satisfy the interface contract. Here&#8217;s the method containing this revision:</p>
<pre class="brush: csharp; title: Code:; notranslate">public IEnumerable&amp;lt;Vehicle&amp;gt; GetVehicles()
{
	// First, check the cache
	var vehicleData = Cache.Get(&quot;vehicles&quot;) as IDictionary&amp;lt;Guid, Vehicle&amp;gt;;

	// If it's not in the cache, we need to read it from the repository
	if (vehicleData == null)
	{
		// Get the repository data
		vehicleData = DataContext.Vehicles.ToDictionary(v =&amp;gt; v.Id);

		if (vehicleData.Any())
		{
			// Put this data into the cache for 30 minutes
			Cache.Set(&quot;vehicles&quot;, vehicleData, 30);
		}
	}

	return vehicleData.Values;
}</pre>
<p>Note also that the previous version placed the sorting code here, at the point when the data is read from the database. I&#8217;ve simply moved the sorting code outside to the controller, since any entities which are added to the cache could cause it to become unsorted again.</p>
<p>Next, <em>SaveChanges()</em>. Here we simply retrieve the list of changed entities (updated or added), then call <em>SaveChanges()</em> on the underlying data context. Then, we run through the list of changed entities and update the cache directly with the changes. Because the cache now stores a Dictionary, we can simply update or add entities by indexing the dictionary with the ID of the vehicle. The dictionary itself will work out whether or not the entity needs to be added or updated depending on whether it is already in the dictionary or not.</p>
<pre class="brush: csharp; title: Code:; notranslate">public void SaveChanges()
{
	// Update or add new/existing entities from the changeset
	var changeset = DataContext.ObjectStateManager
                .GetObjectStateEntries(EntityState.Added | EntityState.Modified);

	DataContext.SaveChanges();

	var cacheData = Cache.Get(&quot;vehicles&quot;) as Dictionary&amp;lt;Guid, Vehicle&amp;gt;

	if (cacheData != null)
	{
		foreach (var item in changeset)
		{
			var vehicle = item.Entity as Vehicle;
			cacheData[vehicle.Id] = vehicle;
		}
	}
}</pre>
<p>There are a couple of important things to note here:</p>
<ul>
<li>By calling <em>SaveChanges()</em> on the data context, we basically wipe out the changed entities. Therefore we need to get the list of changes entities before we actually process them and commit them to the data store.</li>
<li>We call <em>SaveChanges()</em> before updating the cache because, if the data commit was to fail for whatever reason (validation or some other connection problem) then the cache will still reflect our unchanged data. We didn&#8217;t update the cache whenever <em>Update()</em> or <em>Insert()</em> is called for this reason also. We only want the cache to update when the data is actually persisted.</li>
</ul>
<h2>Updating the user interface</h2>
<p>All of our code changes regarding data access is now complete. Turning our attention to the UI, we need to create a way to allow the user to insert and update entities via the site. To this end, I am going to create a MVC partial view containing the form, and use it from both the <em>Create</em> and <em>Edit</em> action views.</p>
<p>Firstly, create actions within in the <em>HomeController</em> class called <em>Create</em> and <em>Edit</em>. Note here that we actually create two methods for each action &#8211; a <em>GET</em> and a <em>POST</em> action. The actions which have been attributed with <em>[HttpPost]</em> will be called when the form posts back after the submit button has been clicked.</p>
<pre class="brush: csharp; title: Code:; notranslate">public ActionResult Edit(Guid id)
{
	var vehicle = Repository.GetVehicles().Single(v =&amp;gt; v.Id == id);

	return View(vehicle);
}

[HttpPost]
public ActionResult Edit(Vehicle vehicle)
{
	Repository.Update(vehicle);
	Repository.SaveChanges();

	return RedirectToAction(&quot;Index&quot;);
}

public ActionResult Create()
{
	var newVehicle = new Vehicle() { Id = Guid.NewGuid() };

	return View(newVehicle);
}

[HttpPost]
public ActionResult Create(Vehicle vehicle)
{
	Repository.Insert(vehicle);
	Repository.SaveChanges();

	return RedirectToAction(&quot;Index&quot;);
}</pre>
<p>These actions do pretty much as you would expect &#8211; when creating, we simply create a new instance of <em>Vehicle</em> and pass it to the view. When editing, we ask the repository to retrieve an instance of <em>Vehicle</em> for us, which in turn uses the cache if available.</p>
<p>Next we need to create the two views; one for creating and one for editing. Create each view by right-clicking on the GET action (the action without the HttpPost attribute) and use the dialogs to create your views. Remember to make them strongly-typed and accept a type of <em>CachingDemo.Web.Models.Vehicle</em>, as we&#8217;d like to pass instances of <em>Vehicle</em> to the views and be able to use them in a strongly-typed way from inside the view.</p>
<p>Open the <em>Create</em> view and put in some code to call a partial view named <em>VehicleForm</em> (created next) and pass it the model. If you&#8217;ve left the site using the standard template with the master page, the following code should appear within the <em>MainContent</em> placeholder:</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;h2&gt;Create&lt;/h2&gt;

&lt;% Html.RenderPartial(&quot;VehicleForm&quot;, Model); %&gt;

&lt;p&gt;&lt;%: Html.ActionLink(&quot;Back to list&quot;, &quot;Index&quot;) %&gt;&lt;/p&gt;</pre>
<p>Open the <em>Edit</em> view next copy in exactly the same code as the <em>Create</em> view. The partial view we create next is going to do all the work for us.</p>
<p>Create a partial view inside the /Views/Home folder called &#8220;VehicleForm&#8221;:</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;%@ Control Language=&quot;C#&quot;
Inherits=&quot;System.Web.Mvc.ViewUserControl&lt;CachingDemo.Web.Models.Data.Vehicle&gt;&quot; %&gt;

&lt;% using (Html.BeginForm()) {%&gt;
    &lt;%: Html.ValidationSummary(true) %&gt;

	&lt;%: Html.HiddenFor(m =&gt; m.Id) %&gt;

    &lt;div&gt;
        &lt;%: Html.LabelFor(model =&gt; model.Name) %&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;%: Html.TextBoxFor(model =&gt; model.Name) %&gt;
        &lt;%: Html.ValidationMessageFor(model =&gt; model.Name) %&gt;
    &lt;/div&gt;

    &lt;div&gt;
        &lt;%: Html.LabelFor(model =&gt; model.Price) %&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;%: Html.TextBoxFor(model =&gt; model.Price, String.Format(&quot;{0:F}&quot;, Model.Price)) %&gt;
        &lt;%: Html.ValidationMessageFor(model =&gt; model.Price) %&gt;
    &lt;/div&gt;

    &lt;p&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
    &lt;/p&gt;

&lt;% } %&gt;</pre>
<p>You can also achieve this of course by right-clicking the folder, selecting &#8216;View&#8217; and then creating a partial view using the dialog. Just remember to make it strongly-typed as we&#8217;re going to be passing it an instance of Vehicle as its model from the parent view.</p>
<p>When you&#8217;re done, you should now be able to debug the application and watch as single items are retrieved from the cache and replaced in-situ when they are updated. This is more efficient than simply invalidating the whole cache and will scale better when dealing with more users and more data.</p>
<p><a href="http://dl.dropbox.com/u/5229980/scb/code/CachingDemo.Web%202.zip">Download the sample project</a></p>
<p>Until next time..</p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Data Caching with .Net 4.0 and Asp.Net MVC – part 2 - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/net4-caching-with-mvc-2/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/net4-caching-with-mvc-2/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Data Caching with .Net 4.0 and Asp.Net MVC &#8211; part 1</title>
		<link>http://stevescodingblog.co.uk/net4-caching-with-mvc/</link>
		<comments>http://stevescodingblog.co.uk/net4-caching-with-mvc/#comments</comments>
		<pubDate>Sat, 14 Aug 2010 11:23:43 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[.net 4.0]]></category>
		<category><![CDATA[.net4]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[memorycache]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[objectcache]]></category>

		<guid isPermaLink="false">http://stevescodingblog.co.uk/?p=88</guid>
		<description><![CDATA[Learn how to implement data caching using .Net4's new ObjectCache, in an Asp.Net MVC environment. <a href="http://stevescodingblog.co.uk/net4-caching-with-mvc/"><span class="read-more">Read more <span class="meta-nav">&#187;</span></span></a>]]></description>
			<content:encoded><![CDATA[<p>The purpose of this article is to demonstrate a sort-of real-world example of how to use the new <a href="http://msdn.microsoft.com/en-us/library/dd997357.aspx" target="_blank">.Net 4 Caching Framework</a>, utilising some good extensible programming practises. This isn&#8217;t specifically targeted at MVC programmers, but I am using Asp.Net MVC as the host to show the results of fetching data via the cache. If you want, you can <a href="http://dl.dropbox.com/u/5229980/scb/code/CachingDemo.Web.zip">download the demonstrate app</a> and walk through it with me.</p>
<p>First of all, an overview of the structure of the application and what we&#8217;re going to be doing. The example application and the code snippets below are written in C#.</p>
<ul>
<li>Creating a bog-standard MVC 2 application</li>
<li>Use the Entity Framework to read our data from the database, and utilise a repository pattern to wrap up this database interaction</li>
<li>Wrap up the new .Net 4.0 caching objects <em>ObjectCache</em> and <em>MemoryCache</em> to give ourselves another extensibility point, and aid unit testing</li>
<li>Tie all this together using the MVC front-end</li>
</ul>
<p>By the way &#8211; the tools I am using here are <a href="http://www.microsoft.com/express/downloads/" target="_blank">Visual Studio 2010</a> Professional (Express would work too, although I haven&#8217;t tested it), <a href="http://www.asp.net/mvc" target="_blank">Asp.Net MVC 2</a>, <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992&amp;displaylang=en" target="_blank">.Net Framework 4</a> and <a href="http://www.microsoft.com/express/database/" target="_blank">Sql Server 2008 Express Edition</a>. Although I&#8217;ve mentioned it above, there isn&#8217;t any unit testing being done in the downloadable demo application (as it&#8217;s not the <em>real</em> focus of this article) but, as you will see, the techniques we will implement lend itself very well to being unit testable and you are free to carry out this testing if you wish.</p>
<p>First of all, let&#8217;s set up the database and our entities!</p>
<p><span id="more-88"></span></p>
<p>I&#8217;ve created a simple test database with one table to store some information about Vehicles, and it looks like this:</p>
<p><img class="alignnone size-full wp-image-103 colorbox-88" title="Caching Database" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/Database.png" alt="The schema for the caching demo" width="302" height="167" /></p>
<p>Create a new Asp.Net MVC2 project (not the &#8216;empty&#8217; one) &#8211; I&#8217;ve called mine <em>CachingDemo.Web</em>. We&#8217;re going to use the Entity Framework to interact with this database, so go ahead and add a new Entity Data Model item to the project. I&#8217;ve chosen to create this data model in the <em>Models </em>folder, inside a new folder I&#8217;ve created called <em>Data </em>which, after we&#8217;re done, will give us this sort of structure:</p>
<p><img class="alignnone size-full wp-image-110 colorbox-88" title="MVC2 project" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/Proj1.png" alt="MVC2 project" width="218" height="257" /></p>
<p>Right-click on the <em>Data </em>folder and add a new ADO.NET Entity Data Model:</p>
<p><img class="alignnone size-full wp-image-106 colorbox-88" title="Entity Framework Step 1" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/EF1.png" alt="Adding a new Entity Data Model to the project" width="392" height="388" /></p>
<p>Create your connection to the database. Here I&#8217;ve used my own local instance of SqlExpress:</p>
<p><img class="alignnone size-full wp-image-107 colorbox-88" title="Entity Data Model step 2" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/EF2.png" alt="EF2" width="447" height="657" /></p>
<p>Keep all the default names and options for saving the connection and entity objects:</p>
<p><img class="alignnone size-full wp-image-108 colorbox-88" title="Storing the connection string" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/EF3.png" alt="EF3" width="628" height="561" /></p>
<p>Choose the test database and again just select all the default options for now:</p>
<p><img class="alignnone size-full wp-image-109 colorbox-88" title="Choosing the database and default generation options" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/EF4.png" alt="EF4" width="594" height="353" /></p>
<p>Just click &#8216;OK&#8217; through the rest of the options until the wizard is complete and you&#8217;re faced with the entity model designer. It should only have the Vehicle entity on it, which exactly maps to our database schema.</p>
<p><img class="alignnone size-full wp-image-115 colorbox-88" title="The Vehicle entity on our entity designer" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/EntityDesigner.png" alt="Vehicle" width="165" height="183" /></p>
<p>That&#8217;s all for the Entity Framework stuff for now. Next we need to start creating some objects to help us retrieve this data and actually perform the caching. This next step is where the main focus of the article is, as it actually uses the caching objects and wraps it up into a neat repository class.</p>
<p>We&#8217;re also going to wrap up the Cache objects so that we can swap it out later, with either a Mock caching object for unit testing, or to implement a 3rd-party caching framework such as <a href="http://memcached.org/" target="_blank">Memcached</a>. Start by creating the interface for our cache provider:</p>
<pre class="brush: csharp; title: Code:; notranslate">public interface ICacheProvider
{
	object Get(string key);
	void Set(string key, object data, int cacheTime);
	bool IsSet(string key);
	void Invalidate(string key);
}</pre>
<p>Next, we will provide a default implementation which uses the .Net 4 ObjectCache and MemoryCache objects to provide caching support. In order to do this, you will need to add a reference <em>System.Runtime.Caching</em> assembly:</p>
<p><img class="alignnone size-full wp-image-105 colorbox-88" title="CacheRef" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/CacheRef.png" alt="" width="800" height="460" /></p>
<p>This default implementation looks like the following:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class DefaultCacheProvider : ICacheProvider
{
	private ObjectCache Cache { get { return MemoryCache.Default; } }

	public object Get(string key)
	{
		return Cache[key];
	}

	public void Set(string key, object data, int cacheTime)
	{
		CacheItemPolicy policy = new CacheItemPolicy();
		policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);

		Cache.Add(new CacheItem(key, data), policy);
	}

	public bool IsSet(string key)
	{
		return (Cache[key] != null);
	}

	public void Invalidate(string key)
	{
		Cache.Remove(key);
	}
}</pre>
<p>The main points to note here are:</p>
<ul>
<li>We&#8217;ve created a private property which allows us to retrieve the actual cache object. This just returns the static .Net4 MemoryCache object. Because it&#8217;s static, you will receive the same cache object back every time you call it, and other users using the cache will also be served the same cache object. This is key &#8211; once the data is in the cache, it is cached <strong>for all users</strong>.</li>
<li>In our simple implementation of the <strong>Set</strong> method, we create a cache policy which caches the item for the following 30 minutes. Once the 30 minutes has passed, the item is dropped from the cache.</li>
<li>We have another couple of utility methods which allow consumers to check that an item has been cached, and also one which allows us to force the removal of a cached object.</li>
</ul>
<p>Now that we have an interface for our cache and that the .Net Caching objects are wrapped up, we can go ahead and create our data repository. For our simple demo application we&#8217;re just going to use this repository straight from the MVC Controller. For more advanced or complex applications you will probably want to create another business layer on top of this repository which contains more coarse-grained business methods.</p>
<p>Again, we will have an interface for our repository and then implement it, making use of our Entity Framework objects we created earlier. The interface looks like this:</p>
<pre class="brush: csharp; title: Code:; notranslate">public interface IVehicleRepository
{
	void ClearCache();
	IEnumerable GetVehicles();
}</pre>
<p>Pretty simply, it defines contract which allows us to get vehicles. It also allows us to clear it&#8217;s data cache, which may not be needed in a real application but I&#8217;ve included it here for convenience. The implementation of this interface looks like the following:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class VehicleRepository : IVehicleRepository
{
	protected CachingDemoEntities DataContext { get; private set; }

	public ICacheProvider Cache { get; set; }

	public VehicleRepository()
		: this(new DefaultCacheProvider())
	{
	}

	public VehicleRepository(ICacheProvider cacheProvider)
	{
		this.DataContext = new CachingDemoEntities();
		this.Cache = cacheProvider;
	}

	public IEnumerable GetVehicles()
	{
		// First, check the cache
		IEnumerable vehicleData = Cache.Get(&quot;vehicles&quot;) as IEnumerable;

		// If it's not in the cache, we need to read it from the repository
		if (vehicleData == null)
		{
			// Get the repository data
			vehicleData = DataContext.Vehicles.OrderBy(v =&amp;gt; v.Name).ToList();

			if (vehicleData.Any())
			{
				// Put this data into the cache for 30 minutes
				Cache.Set(&quot;vehicles&quot;, vehicleData, 30);
			}
		}

		return vehicleData;
	}

	public void ClearCache()
	{
		Cache.Invalidate(&quot;vehicles&quot;);
	}
}</pre>
<p>Note that we have a constructor which allows us to specify an implementation of <em>ICacheProvider </em>(our caching interface), but that also the default constructor just passes it an instance of our <em>DefaultCacheProvider</em>. Now we can easily create our repository with all the default dependencies but at the same time we have the flexibility to provide another implementation when we need one.</p>
<p><em>GetVehicles()<strong> </strong><span style="font-style: normal;">is where the main bulk of the work is done. There is a specific pattern at work where which makes working with the cache easy and robust:</span></em></p>
<ol>
<li>Try and retrieve the vehicle data from the cache using our &#8216;vehicles&#8217; key.</li>
<li>If the data is not there, we re-create the data from the database (our entity data model). Note that we store the data into the same <em>vehicleData</em> variable from when we tried to read the cache.</li>
<li>If there is any data to store, we set it into the cache using the same &#8216;vehicles&#8217; key, and set the timeout as 30 minutes.</li>
<li>Return the vehicle data</li>
</ol>
<p>Our <em>ClearCache()</em> implementation is also there, which simply invalidates our &#8216;vehicles&#8217; data.</p>
<p>Now we have all we need to go ahead and create the controller and the interface to display and invalidate this data. First we will set up the constructors on our controller &#8211; here I have just made use of the Home controller rather than creating a new one. The constructors follow a similar pattern which allow us to specify an implementation of <em>IVehicleRepository</em>, or provide another one for unit testing:</p>
<pre class="brush: csharp; title: Code:; notranslate">public class HomeController : Controller
{
	public IVehicleRepository Repository { get; set; }

	public HomeController()
		: this(new VehicleRepository())
	{
	}

	public HomeController(IVehicleRepository repository)
	{
		this.Repository = repository;
	}</pre>
<p>Continue with the Index action, and retrieve the data from the repository. This is all the data access code we need to write as far as the controller is concerned &#8211; because we&#8217;ve abstracted all the actual caching code away, we no longer need to worry about whether the data is being cached or not; our controller code will work regardless:</p>
<pre class="brush: csharp; title: Code:; notranslate">public ActionResult Index()
{
	ViewData[&quot;Message&quot;] = &quot;Welcome to my caching demo!&quot;;
	return View(Repository.GetVehicles());
}</pre>
<p>I&#8217;ve just left in the ViewData message which was there from the project creation, but changed it slightly. The main point about this code is the call to <em>Repository.GetVehicles()</em>, and the fact that we are passing it as the model to the Index view. I also have another Index action here which acts on form post &#8211; as you&#8217;ll see in a moment, I have a button on my form which allows us to invalidate the cache from the page for convenience, so we can test that the cache is being dumped and re-created properly. This action looks like the following:</p>
<pre class="brush: csharp; title: Code:; notranslate">[HttpPost]
public ActionResult Index(FormCollection form)
{
	Repository.ClearCache();
	return RedirectToAction(&quot;Index&quot;);
}</pre>
<p>On to the view next. The resulting view I have simply writes out the data into a table, with a button underneath allowing us to invalidate the cache. I&#8217;ve already put some sample data into my database, which you might also want to do now:</p>
<p><img class="alignnone size-full wp-image-111 colorbox-88" title="UI1" src="http://stevescodingblog.co.uk/wp-content/uploads/2010/08/UI1.png" alt="" width="462" height="197" /></p>
<p>The code for this view (which I have just put into the Index view) looks like this:</p>
<pre class="brush: xml; title: Code:; notranslate">&lt;h2&gt;Car data:&lt;/h2&gt;

&lt;table cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; border=&quot;0&quot;&gt;
	&lt;tr&gt;
		&lt;th&gt;Id&lt;/th&gt;
		&lt;th&gt;Name&lt;/th&gt;
		&lt;th&gt;Price&lt;/th&gt;
	&lt;/tr&gt;

	&lt;% foreach (var vehicle in Model) { %&gt;

		&lt;tr&gt;
			&lt;td&gt;&lt;%: vehicle.Id.ToString() %&gt;&lt;/td&gt;
			&lt;td&gt;&lt;%: vehicle.Name %&gt;&lt;/td&gt;
			&lt;td&gt;&lt;%: string.Format(&quot;{0:c0}&quot;, vehicle.Price) %&gt;&lt;/td&gt;
		&lt;/tr&gt;

	&lt;% } %&gt;

&lt;/table&gt;

&lt;% using (Html.BeginForm()) {  %&gt;
	&lt;input type=&quot;submit&quot; value=&quot;Invalidate Cache&quot; id=&quot;InvalidateButton&quot; name=&quot;InvalidateButton&quot; /&gt;
&lt;% } %&gt;</pre>
<p>Now we have completed the code for the application. Test the application by performing the following steps (make sure you have put in some test data):</p>
<ol>
<li>Load the page. You should see your test data appear</li>
<li>Alter the data directly on the database using Sql Server Management Studio or some other means which allows you to directly alter the table</li>
<li>Refresh the page. Your changes should <strong>not</strong> appear, because on this page load the old data is coming from the cache, not the database.</li>
<li>Press the button to invalidate the cache. The page will reload and your database changes will now be shown.</li>
</ol>
<p>To dive further into the mechanics, when debugging the application, you can place breakpoints around the caching code to see the data going into and being retrieved from the cache. After the first page load, you will notice that the data is coming straight from the cache and is not hitting the entity framework code at all. If you click the button to invalidate the cache, you will notice that the cache is now empty and that it has to go back to the database to update the cache.</p>
<p>Stale data is an issue when employing the use of any caching framework, and we will be dealing with this in two ways over the next two parts of this series: using the new SqlDependency wrapper, and also using a more code-centric technique in the third part. In the project source code I have included the full MVC project and the Sql file which allows you to install the demo database into your own Sql Server instance.</p>
<p><a href="http://dl.dropbox.com/u/5229980/scb/code/CachingDemo.Web.zip">Download the project source code</a></p>

	<div style="">
		<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="Data Caching with .Net 4.0 and Asp.Net MVC - part 1 - Steves Coding Blog" data-url="http://stevescodingblog.co.uk/net4-caching-with-mvc/"  data-via="@elkdanger">Tweet</a>
	</div>
	<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>]]></content:encoded>
			<wfw:commentRss>http://stevescodingblog.co.uk/net4-caching-with-mvc/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

