<?xml version="1.0"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
    <title>Stuart Blackler's Tech Blog</title>
    <link>http://sblackler.net/</link>
    <atom:link href="http://domain/rss.xml" rel="self" type="application/rss+xml" />
    <description></description>
    <language>en-au</language>
    <pubDate>Sat, 04 Jan 2014 10:24:19 -0800</pubDate>
    <lastBuildDate>Sat, 04 Jan 2014 10:24:19 -0800</lastBuildDate>

    
    <item>
      <title>Developer Links (Jan 2014)</title>
      <link>http://sblackler.net/2014/01/05/Developer-Links-Jan-2014</link>
      <pubDate>Sun, 05 Jan 2014 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2014/01/05/Developer-Links-Jan-2014</guid>
      <description>&lt;p&gt;Here are the things that I have found most interesting during the last month.&lt;/p&gt;

&lt;h2&gt;Code&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://blogs.msdn.com/b/csharpfaq/archive/2013/12/16/throwing-the-big-switch-on-roslyn-matt-gertz-vs-managed-languages-development-manager.aspx&quot;&gt;Throwing the Big Switch on Roslyn&lt;/a&gt; - C# FAQ&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Dev Tools&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://hanselman.com/tools&quot;&gt;Ultimate Developer and Power Tool List for Windows&lt;/a&gt; - Scott Hanselman&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://chocolatey.org/&quot;&gt;Chocolatey&lt;/a&gt; - Chocolatey&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://boxstarter.org/&quot;&gt;Boxstarter&lt;/a&gt; - Boxstarter&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;HTML/CSS&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://updates.html5rocks.com/2013/12/DevTools-Digest-December-2013&quot;&gt;Dev Tools Digest December 2013&lt;/a&gt; - HTML5Rocks&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tobiasahlin.com/blog/css-trick-animating-link-underlines/&quot;&gt;Animating Link Underlines&lt;/a&gt; - Tobias Ahlin&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://css-tricks.com/line-menu-icon-menu/&quot;&gt;Line Menu Icon&lt;/a&gt; - CSS Tricks&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.thecssninja.com/javascript/pointer-events-60fps&quot;&gt;60fps scrolling using pointer-events: none&lt;/a&gt; - The CSS Ninja&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://updates.html5rocks.com/2013/12/300ms-tap-delay-gone-away&quot;&gt;300ms tap delay, gone away&lt;/a&gt; - HTML5Rocks&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Projects/Frameworks&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://tobiasahlin.com/spinkit/&quot;&gt;SpinKit&lt;/a&gt; - Tobias Ahlin&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://momentjs.com/&quot;&gt;Moment.js&lt;/a&gt; - Momentjs&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://linqjs.codeplex.com/&quot;&gt;LINQ.js&lt;/a&gt; - Linqjs&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;SQL&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://www.brentozar.com/archive/2013/12/keep-it-constrained/&quot;&gt;Keep it Constrained&lt;/a&gt; - Brent Ozar&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.brentozar.com/archive/2013/12/video-the-secrets-of-tempdb/&quot;&gt;The Secrets Of TempDB&lt;/a&gt; - Brent Ozar&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>2014 - A year ahead</title>
      <link>http://sblackler.net/2014/01/04/2014-A-year-ahead</link>
      <pubDate>Sat, 04 Jan 2014 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2014/01/04/2014-A-year-ahead</guid>
      <description>&lt;p&gt;Every new year its common for a fresh start, resolutions get made and subsequently broken. This year, I have decided to remodel certain aspects of my life for both personal and professional gain.&lt;/p&gt;

&lt;p&gt;To start with, I have begun the process of being more selective in what I read. This allows me to find more relevant things and helps me keep up to date on the latest techniques. This process has started with unsubscribing from newsletters and unnecessary notifications in my inbox. Half the things I receive head straight to the trash, so it&#39;s kinder to the internet and not have that email delivered to me.&lt;/p&gt;

&lt;p&gt;The next step is to make my lunch hour, a learning hour. By maintaining a small set of approximately 15 blogs, I can keep up-to-date on the latest tech and news. Reading blogs is only half of the story, writing is the other half. It becomes a two pronged attack on my skills:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Improving my writing and language skills&lt;/li&gt;
&lt;li&gt;Improving technically by using the technologies I&#39;m writing about&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;My learning does not stop there. During the next year, I plan to attempt two full MSCD qualifications. The first being MSCD: Web Applications, which I already have begun studying for (see my previous posts on the first exam). The second qualification is MCSA: SQL Server 2012. This two pronged approach leads me nicely into more of a devops developer. I can build the websites and craft a scalable backend, something that I have always been interested in.&lt;/p&gt;

&lt;p&gt;A vital part of my 2014 plan is to take better care of my health. I am looking into devices such as
FitBit, altering my lunchtime routine to remove non-essential foods (crisps and chocolate for example) and being more active. The healthier I am, the better I will be able to concentrate and work.&lt;/p&gt;

&lt;p&gt;The contents of this post only represents a small part of what plan for the year. Although not written here, I have set realistic time frames for each and how I plan to measure. Every month I will review my progress and set a plan for the forthcoming month. These plans might be to learn technology X or to try activity Y.&lt;/p&gt;

&lt;p&gt;So if this is my plan for the year, my resolution should be:&lt;/p&gt;

&lt;p&gt;Be better, do better.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>HTML 5 API&#39;s 3/5 - Drag and Drop API (Exam 70-480 Prep)</title>
      <link>http://sblackler.net/2013/11/23/HTML5-APIs-Drag-and-Drop-API-exam-70-480-prep</link>
      <pubDate>Sat, 23 Nov 2013 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/11/23/HTML5-APIs-Drag-and-Drop-API-exam-70-480-prep</guid>
      <description>&lt;p&gt;As part of my preparation for the &quot;Programming in HTML5 with JavaScript and CSS3&quot; exam, I will be writing about the key areas that I am focusing on as part of my learning. In terms of the HTML5 javascript API&#39;s, I will be covering the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2013/11/05/HTML5-APIs-History-API-exam-70-480-prep/&quot;&gt;History API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2013/11/10/HTML5-APIs-Geolocation-API-exam-70-480-prep/&quot;&gt;Geo-location API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Drag n Drop API (this article)&lt;/li&gt;
&lt;li&gt;MIME Type Registration API&lt;/li&gt;
&lt;li&gt;Application Cache API&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Drag and Drop Background&lt;/h2&gt;

&lt;p&gt;After a long time, drag and drop has finally been made a part of HTML&#39;s Javascript API&#39;s. For years, developers have had to contend with the likes of JQuery and DOJO to perform common tasks. For something that has been around natively since 1995 thanks to IE5, the web has had a lot of catching up to do in this area. Current implementations of the Drag and Drop API contain numerous inconsistancies and quirks to negotiate.&lt;/p&gt;

&lt;h2&gt;Querying for compatibility&lt;/h2&gt;

&lt;p&gt;To see whether or not the client supports the HTML5 Drag and Drop API, use the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var div = createElement(&#39;div&#39;);
if((&#39;draggable&#39; in div) || (&#39;ondragstart&#39; in div &amp;amp;&amp;amp; &#39;ondrop&#39; in div)){
    // Setup drag and drop
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is exactly the same as what is used in the &lt;a href=&quot;https://github.com/Modernizr/Modernizr/blob/master/feature-detects/draganddrop.js&quot;&gt;Modernizer Drag and Drop Feature Test&lt;/a&gt; so all kudos to them. I personally have a love/hate relationship with libraries in general so I prefer to learn how to do it myself before using one so that it&#39;s easier to fix bugs in my code. But that&#39;s a different story.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;By default, the &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;img&lt;/code&gt; elements are draggable. Other elements will need to have the following attribute set:  &lt;code&gt;draggable=&quot;true&quot;&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Drag and Drop Events&lt;/h2&gt;

&lt;p&gt;There are a number of different events to attach to for monitoring the entire drag and drop process:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dragstart&lt;/code&gt; : Occurs when the user starts dragging the element&lt;/li&gt;
&lt;li&gt;&lt;code&gt;drag&lt;/code&gt; : Occurs every time we move the mouse&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dragenter&lt;/code&gt; : Occurs when the draggable element is moved over the target element&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dragleave&lt;/code&gt; : Occurs when the draggable is no longer over the target element&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dragover&lt;/code&gt; : Occurs when the draggable is moved over an element during the drag&lt;/li&gt;
&lt;li&gt;&lt;code&gt;drop&lt;/code&gt; : Occurs when the actual drop is performed&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dragend&lt;/code&gt; : Occurs when the user releases the mouse while dragging the object&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;One thing that is very important when you are writing a web application that implements drag and drop; certain events such as &lt;code&gt;drag&lt;/code&gt; and &lt;code&gt;dragover&lt;/code&gt; should be performed very quickly. Your functions should contain the minimal amount of code as it will affect the users experience.&lt;/p&gt;

&lt;h2&gt;Registering the events&lt;/h2&gt;

&lt;p&gt;Assuming that our element is draggable and the browser supports drag and drop, we use the &lt;code&gt;element.addEventListener&lt;/code&gt; function to register each event for our draggable element(s).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var el = document.getElementById(&#39;id&#39;);
if(el){
    el.addEventListener(&#39;dragstart&#39;, onDragStart, false);
    el.addEventListener(&#39;dragover&#39;, onDragOver, false);
    el.addEventListener(&#39;drop&#39;, onDrop, false);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;onDragStart&lt;/code&gt; is the place where you would want to set any specific styling for the element that you are about to move. For instance:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function onDragStart(e){
    e.Target.style.opacity = 0.4;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;onDragOver&lt;/code&gt; is the place where you need to prevent the browser doing it&#39;s default behaviour, otherwise you will not be able to drop correctly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function onDragOver(e){
    if(e.preventDefault){
       e.preventDefault();
    }

    e.dataTransfer.dropEffect = &#39;move&#39;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above example, I have also used the &lt;code&gt;dataTransfer&lt;/code&gt; object to set the drop effect. I have included a small section about the &lt;code&gt;dataTransfer&lt;/code&gt; object a bit further down. Lastly, we need to fill the &lt;code&gt;onDrop&lt;/code&gt; function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function onDrop(e){
    if(e.stopPropagation){
        e.stopPropagation();
    }

    // do something with e.dataTransfer here....

    return false;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We use &lt;code&gt;e.stopPropagation()&lt;/code&gt; to prevent the browser from re-directing. Another words, we tell the browser we know what we are doing and this is where the event chain should end.&lt;/p&gt;

&lt;h3&gt;The dataTransfer object&lt;/h3&gt;

&lt;p&gt;This object holds the data that was sent by the drag operation. The data can be set and retrieved in various ways, the most important ones are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;dataTransfer.effectAllowed=value: this returns the types of action permitted, possible values are none, copy, copyLink, copyMove, link, linkMove, move, all and uninitialized.&lt;/li&gt;
&lt;li&gt;dataTransfer.setData(format, data): adds the specified data and its format.&lt;/li&gt;
&lt;li&gt;dataTransfer.clearData( format ): clears all the data for a specific format.&lt;/li&gt;
&lt;li&gt;dataTransfer.setDragImage(element, x, y): sets the image you wish to drag, the x and y values specify where the mouse cursor should be (0, 0 will place it top left).&lt;/li&gt;
&lt;li&gt;data = dataTransfer.getData(format) : As the name says it returns the data available for a specific format.&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Browser Compatibility&lt;/h2&gt;

&lt;p&gt;That is pretty much all there is that you need to know regarding the HTML5 Drag and Drop API. So in which browsers is it supported? I suggest checking the following &lt;a href=&quot;http://caniuse.com/#feat=dragndrop&quot;&gt;link&lt;/a&gt; for up-to-date information and further reading.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Codename RyuJit - The future of JIT compilation on .Net</title>
      <link>http://sblackler.net/2013/11/23/Codename-RyuJit-The-future-of-JIT-on-dot-net</link>
      <pubDate>Sat, 23 Nov 2013 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/11/23/Codename-RyuJit-The-future-of-JIT-on-dot-net</guid>
      <description>&lt;p&gt;As you may or may not know, the JIT compiler is part of the Common Language Runtime (CLR). It&#39;s job is to turn compiler output (MSIL) into code that can be run by a given computer. The current JIT complier, which is also responsible for NGEN, is spread across multiple code bases. This makes it harder for the product team to update for all the different architectures.&lt;/p&gt;

&lt;h2&gt;Introducing RyuJit&lt;/h2&gt;

&lt;blockquote&gt;&lt;p&gt;RyuJIT is based off of the same codebase as the x86 JIT. It’s a modern compiler that will be the basis of all our JIT compilers in the future: x86, ARM, MDIL and whatever else comes along. Having a single codebase means that .NET programs are more consistent between architectures—put another way, you generally get bug-for-bug compatibility. But having a single codebase also means we can innovate faster and bring you more code generation features more quickly.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;...&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;While all the code samples compile faster with RyuJIT, you should note the second line—RFC822 e-mail RegEx. It’s literally off the chart! That’s because regular expressions (a.k.a. RegEx) tend to perform especially badly on JIT64. Compiling this benchmark on JIT64 takes 60 seconds and consumes 1.4 GB of peak working set. With RyuJIT, it only takes 1.8 seconds and uses 199 MB of peak working set. &lt;em&gt;&lt;a href=&quot;http://blogs.msdn.com/b/dotnet/archive/2013/09/30/ryujit-the-next-generation-jit-compiler.aspx&quot;&gt;source&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;The official announcement certainly interested me and I will be installing on my development machines at home. However, since the initial release is a CTP, there are some limitations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You have to manually enable RyuJit through an environment variable change or registry edit&lt;/li&gt;
&lt;li&gt;It is only available for x64 architectures at the moment.&lt;/li&gt;
&lt;li&gt;It is only supported on Windows Server 2012R2 and Windows 8.1&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Enabling up RyuJit&lt;/h2&gt;

&lt;p&gt;If you are like me and want to take the plunge and help the CLR team, you will need to do one of the following to enable RyuJit. If you want to run RyuJit for a single application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;set an environment variable: &lt;code&gt;COMPLUS_AltJit=*&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;or, if you want to enable RyuJIT for your entire machine&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;,set the registry key &lt;code&gt;HKLM\SOFTWARE\Microsoft\.NETFramework\AltJit&lt;/code&gt; to the string &lt;code&gt;*&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Both methods cause the 64-bit CLR to use RyuJIT instead of JIT64. And both are temporary settings—installing RyuJIT doesn’t make any permanent changes to your machine.&lt;/p&gt;

&lt;h2&gt;How did they come up with the name RyuJit&lt;/h2&gt;

&lt;p&gt;As CLR development lead &lt;a href=&quot;http://social.msdn.microsoft.com/profile/kevin%20frei/&quot;&gt;Kevin Frei&lt;/a&gt; says:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;The short answer is http://en.wikipedia.org/wiki/Ryujin. Compiler devs will be familiar with the canonical compiler book, which is referred to as The Dragon Book. So, Dragon God, Dragon Book, JIT compiler: voila, RyuJIT. As a team, we’re all looking forward to yelling &quot;Hadouken!&quot; when we finally ship.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;Read more from the official announcement here: &lt;a href=&quot;http://blogs.msdn.com/b/dotnet/archive/2013/09/30/ryujit-the-next-generation-jit-compiler.aspx&quot;&gt;http://blogs.msdn.com/b/dotnet/archive/2013/09/30/ryujit-the-next-generation-jit-compiler.aspx&lt;/a&gt; and the follow up FAQ: &lt;a href=&quot;http://blogs.msdn.com/b/dotnet/archive/2013/11/18/ryujit-net-jit-compiler-ctp1-faq.aspx&quot;&gt;http://blogs.msdn.com/b/dotnet/archive/2013/11/18/ryujit-net-jit-compiler-ctp1-faq.aspx&lt;/a&gt;. Send feedback and questions to &lt;a href=&quot;mailto://ryujit@microsoft.com&quot;&gt;ryujit@microsoft.com&lt;/a&gt; and suggestions via &lt;a href=&quot;http://visualstudio.uservoice.com/forums/121579-visual-studio/category/31481-net&quot;&gt;http://visualstudio.uservoice.com/forums/121579-visual-studio/category/31481-net&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>HTML 5 API&#39;s 2/5 - Geolocation API (Exam 70-480 Prep)</title>
      <link>http://sblackler.net/2013/11/10/HTML5-APIs-Geolocation-API-exam-70-480-prep</link>
      <pubDate>Sun, 10 Nov 2013 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/11/10/HTML5-APIs-Geolocation-API-exam-70-480-prep</guid>
      <description>&lt;p&gt;As part of my preparation for the &quot;Programming in HTML5 with JavaScript and CSS3&quot; exam, I will be writing about the key areas that I am focusing on as part of my learning. In terms of the HTML5 javascript API&#39;s, I will be covering the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2013/11/05/HTML5-APIs-History-API-exam-70-480-prep/&quot;&gt;History API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Geo-location API (this article)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2013/11/23/HTML5-APIs-Drag-and-Drop-API-exam-70-480-prep/&quot;&gt;Drag n Drop API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;MIME Type Registration API&lt;/li&gt;
&lt;li&gt;Application Cache API&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Geolocation API Background&lt;/h2&gt;

&lt;p&gt;Geolocation is a set of technologies that allows services such as websites or phone apps to discover where in the world you are. There are two main ways that a location can be achieved. The geolocation API allows you to share your location with websites that ask for it.&lt;/p&gt;

&lt;p&gt;Firstly if you are on a mobile device or using a mobile dongle, then your location could be discovered by accessing nearby cell towers. This approach is fast and doesn&#39;t use that much power, but with the side effect of being inaccurate, sometimes up to 1km in distance.&lt;/p&gt;

&lt;p&gt;Secondly, an application can use the devices on board GPS chip. This results in a higher degree of accuracy at the cost of battery life. Talking to the satellites in the sky takes a great deal of power and accuracy can be affected by atmospheric conditions.&lt;/p&gt;

&lt;p&gt;It is important to note that a users location cannot be tracked without explicit permission as stated in the &lt;a href=&quot;http://www.w3.org/TR/geolocation-API/#security&quot;&gt;W3C Geolocation API specification&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;User Agents must not send location information to Web sites without the express permission of the user.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;Furthermore, it states:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;Recipients must only request location information when necessary. Recipients must only use the location information for the task for which it was provided to them. Recipients must dispose of location information once that task is completed, unless expressly permitted to retain it by the user. Recipients must also take measures to protect this information against unauthorized access. If location information is stored, users should be allowed to update and delete this information.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;This essentially means, that a browser should always ask for permission to determine your location and only keep your location for as long as you say it can track it.&lt;/p&gt;

&lt;h2&gt;Querying for compatibility&lt;/h2&gt;

&lt;p&gt;To see whether or not the client supports the HTML5 geolocation API, use the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if(typeof navigator.geolocation !== &quot;undefined&quot;){
    // The browser is compatible    
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above technique is the correct way of detecting an undefined object in javascript as described in &lt;a href=&quot;http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript&quot;&gt;this StackOverflow thread&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;One time location request&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;navigator.geolocation.getCurrentPosition&lt;/code&gt; is the first of two methods available in Javascript that determine a users location. As the title of this section suggests, this method only retrieves the location of the device once and no more. If there is a requirement to keep track of the devices location then developers should use the method described below.&lt;/p&gt;

&lt;h2&gt;Continuously tracking a devices location&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;navigator.geolocation.watchPosition&lt;/code&gt; is the second of the methods available to developers in Javascript. As the method name suggest, this method continuously watches the clients position and calls the success callback when the position is determined.&lt;/p&gt;

&lt;p&gt;This method returns an integer which uniquely identifies the tracking request. Developers can then use the &lt;code&gt;clearWatch&lt;/code&gt; method to cancel the continuous tracking, for example, when the user clicks a stop button.&lt;/p&gt;

&lt;h2&gt;Method Signatures&lt;/h2&gt;

&lt;p&gt;Both methods of determining the devices location have the same method signature:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;navigator.geolocation.getCurrentPosition(onSuccess, [onError], [options])
naviagtor.geolocation.watchPosition(onSuccess, [onError], [options])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first parameter &lt;code&gt;onSuccess&lt;/code&gt; is compulsory. This should a be a function telling the browser what to do when the location is received. The parameter that gets passed to the &lt;code&gt;onSucess&lt;/code&gt; function contains a property called coords which tells you the following information:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Guaranteed Properties&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;latitude : Decimal degrees of the latitude&lt;/li&gt;
&lt;li&gt;longitude : Decimal degress of the longitude&lt;/li&gt;
&lt;li&gt;accuracy : The accuracy in metres of the returned result. The value of this setting informs the application how useful the returned latitude/longitude value actually is.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&lt;strong&gt;Indeterminate Properties&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;These properties depend on the device and browser capabilities.&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;altitude : Height in metres of the position above the reference ellipsoid&lt;/li&gt;
&lt;li&gt;altitudeAccuracy : The accuracy in metres of the returned altitude&lt;/li&gt;
&lt;li&gt;heading : Direction of travel of the hosting device, clockwise from true north&lt;/li&gt;
&lt;li&gt;speed : The current ground speed of the hosting device in metres per second&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The second parameter &lt;code&gt;onError&lt;/code&gt; is optional. Like &lt;code&gt;onSuccess&lt;/code&gt;, &lt;code&gt;onError&lt;/code&gt; tells the browser what to do in the event of an error; such as when permission is denied. The &lt;code&gt;onError&lt;/code&gt; callback gets passed an instance of a &lt;code&gt;PositionError&lt;/code&gt; object. The &lt;code&gt;PositionError&lt;/code&gt; object has two properties:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;code (short)&lt;/li&gt;
&lt;li&gt;message (string)&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;The code is an enumerated value which can have one of three possible values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Permission_Denied (1). When the user has denied access&lt;/li&gt;
&lt;li&gt;Position_Unavailble (2). For example, when the satellites cannot be accessed.&lt;/li&gt;
&lt;li&gt;Timeout (3). When the network takes too long to calculate the devices position.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The last parameter &lt;code&gt;options&lt;/code&gt; is also optional. This data structure should contain three properties:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;enableHighAccuracy : a boolean that asks the device for the most accurate location it can provide&lt;/li&gt;
&lt;li&gt;timeout : How long the device should wait for a location before the timeout error is raised (in milliseconds)&lt;/li&gt;
&lt;li&gt;maximumAge : How old the location information can be before the device has to re-locate itself (in milliseconds)&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Complete example&lt;/h2&gt;

&lt;p&gt;When all of these parameters are combined, sample requests can look like the following example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var onSuccess = function(data){
    // log the coordinates data structure to the console
    console.log(data.coords)
};

var onError = function(err){
    // log the friendly message to the console
    console.log(err.message);
};

var options = {enableHighAccuracy: true, timeout: 100000, maximumAge: 60};

// calling samples
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);

navigator.geolocation.clearWatch(watchID);
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Browser Compatibility&lt;/h2&gt;

&lt;p&gt;That is pretty much all there is that you need to know regarding the HTML5 Geolocation API. So in which browsers is it supported? I suggest checking the following &lt;a href=&quot;http://caniuse.com/#feat=geolocation&quot;&gt;link&lt;/a&gt; for up-to-date information and further reading. Fallback to older devices can be achieved by using libraries such as &lt;a href=&quot;https://github.com/estebanav/javascript-mobile-desktop-geolocation&quot;&gt;geolocation.js&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Nokia Lumnia 1020 First Impressions</title>
      <link>http://sblackler.net/2013/11/09/Nokia-Lumnia-1020-First-Impressions</link>
      <pubDate>Sat, 09 Nov 2013 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/11/09/Nokia-Lumnia-1020-First-Impressions</guid>
      <description>&lt;p&gt;As a user of both the iPhone 5 and Omnia 7, I thought it would be a good idea to share my thoughts on the platforms in question. My upgrade path has gone from the Omnia 7 when it first came out, using it until the iPhone 5 was released in September 2012, through to the Lumnia 1020 which I upgraded to a few days ago.&lt;/p&gt;

&lt;h2&gt;Omnia 7 &amp;amp; iPhone 5&lt;/h2&gt;

&lt;p&gt;Personally, I loved the Omnia 7. I loved the keyboard on it; the ease of use and its overall quality in general. What ruined the platform for me, and others in turn, was the decision by Microsoft not to allow an upgrade to Windows Phone 8 on the older devices. Like all young platforms, it was hampered by the lack of apps in the app store which left many consumers reverting to the go to phone of the period, the iPhone 4/5.&lt;/p&gt;

&lt;p&gt;The iPhone 5 was the first Apple product that I had owned and it was clear to see why so many consumers had purchased one also. The build quality was excellent and served me very well until I lost it a few weeks ago. The main advantage of the iPhone/iOS platform is the amount of apps in the app store, this is partly due to the operating system being well established; with it now being in it&#39;s 7th incarnation. Once I lost the iPhone 5, I had two choices, re-purchase an iPhone or try one of the new Window&#39;s Phone 8&#39;s.&lt;/p&gt;

&lt;h2&gt;Nokia Lumnia 1020&lt;/h2&gt;

&lt;p&gt;Upon opening the packaging of the Lumnia 1020, the first thing that struck me was the size of the phone and the 41 megapixel camera on the rear. The size of the camera on the rear can make it a bit awkward to hold the phone comfortably, but it does depend on the size of your hand. I soon found a comfortable position to hold the phone. Typically, most modern smart phones tend to had a flat back which is why it was a tad surprising.&lt;/p&gt;

&lt;p&gt;Like the iPhone 5, the Lumnia 1020 has a pin-push sim card tray located on the top of the phone. The sim card tray is fully removable from the phone with Nokia supplying the necessary tool for its removal. The build quality of the device is impressive, superceeding that of Nokia&#39;s previous phones.&lt;/p&gt;

&lt;p&gt;The operating system started quickly, a huge improvement over the Omnia 7, finishing off installing a few apps during the process. The initial setup also gave me a chance to sync with my existing Microsoft account, encapsulating email and contact synchronisation.&lt;/p&gt;

&lt;p&gt;The main selling point of this phone is its camera. Admittidly, with work and graduation I haven&#39;t had the chance to fully test the phone or camera. Initially though, the amount of configurability on the camera through the Nokia camera app is impressive with the ability to adjust the White Balance, ISO, Exposure time and control the focus. This will give budding photographers plenty of options to play with and enjoy.&lt;/p&gt;

&lt;p&gt;One app that I can see my self using, is the Here Drive app. This has a handy my commute feature which updates you with the best route to take on a given day, based on the traffic on the roads. Overall, I am impressed with the platform, but there are a few things that I feel can be improved as part of the operating system.&lt;/p&gt;

&lt;h2&gt;Windows Phone 8&lt;/h2&gt;

&lt;p&gt;Like it&#39;s predecessor, the ability to close running apps leaves something to be desired. I have seen that I can have multiple message windows open at once and to close them I have to use the back arrow. This could be improved by having a closing system similar to the way the unpinning works on the start screen and would greatly improve the usability of the device.&lt;/p&gt;

&lt;p&gt;Some of the apps take a while to load. Whilst I haven&#39;t measured this, it is noticibly slower than an iPhone 5 running iOS 7. This could be due to the developers implementations or the underlying operating system. I will find this out when I begin writing apps for the platform next year.&lt;/p&gt;

&lt;p&gt;An example app is the Facebook app built by Microsoft, which has poor UI performance in my opinion. The scrolling doesn&#39;t feel that smooth, almost like the app is trying to do too much. The actual UI could do with a bit of a clean up as well. The icons at the top of the app are quiet hard to see and could do with being lightened up.&lt;/p&gt;

&lt;p&gt;My last gripe with the operating system is the keyboard on the phone. I dont remember the keyboard on the Omnia 7 being quiet so large. Although this could be part of my transfer from an iPhone 5. It takes up quiet a large portion of screen real estate making it hard to write a long SMS message for example.&lt;/p&gt;

&lt;h2&gt;Final Thoughts&lt;/h2&gt;

&lt;p&gt;Overall the phone and operating system are good, but there are definately some improvements to be had in the operating system. Developers need to be encouraged to write apps for the platform as first class citizens not as an after thought as seems to be the case at the moment. For me, the platform has more potential than the iOS platform, but it is still behind by quiet some distance in some aspects of the platform. I do intend to remain with the platform for the next year and see what the updates bring.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>HTML 5 API&#39;s 1/5 - History API (Exam 70-480 Prep)</title>
      <link>http://sblackler.net/2013/11/05/HTML5-APIs-History-API-exam-70-480-prep</link>
      <pubDate>Tue, 05 Nov 2013 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/11/05/HTML5-APIs-History-API-exam-70-480-prep</guid>
      <description>&lt;p&gt;As part of my preparation for the &quot;Programming in HTML5 with JavaScript and CSS3&quot; exam, I will be writing about the key areas that I am focusing on as part of my learning. In terms of the HTML5 javascript API&#39;s, I will be covering the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;History API (this article)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2013/11/10/HTML5-APIs-Geolocation-API-exam-70-480-prep/&quot;&gt;Geo-location API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2013/11/23/HTML5-APIs-Drag-and-Drop-API-exam-70-480-prep/&quot;&gt;Drag n Drop API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;MIME Type Registration API&lt;/li&gt;
&lt;li&gt;Application Cache API&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;History API background&lt;/h2&gt;

&lt;p&gt;The HTML5 History API is a standardized way to manipulate the browser history via javascript. Previous versions allowing manipulation of the the browsers history stack in terms of moving forward and backwards.&lt;/p&gt;

&lt;p&gt;With current trends of AJAX requests and single page applications, the HTML5 History API allows developers to change the visible URL in javascript without the need of a full request/response cycle with the server. In fact, no request has to be made at all. The HTML5 History API subverts any need for an application to have the hashbang work arounds as seen here (though graceful degregation is always recommended).&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;For the next part I will assume that you have the need for this and have the neccessary click handlers etc setup and just want to know how to use the API.&lt;/p&gt;&lt;/blockquote&gt;

&lt;h2&gt;Querying for compatibility&lt;/h2&gt;

&lt;p&gt;To see whether or not the users browser supports the HTML5 History API, use the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if(typeof history.pushState !== &quot;undefined&quot;){
    // The browser is compatible
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; *There has already been numerous discussions on the &lt;a href=&quot;http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript&quot;&gt;correct way to detect an undefined object property in Javascript&lt;/a&gt;. Thus, I will not add to the debate and suggest that you read the above thread.&lt;/p&gt;

&lt;h2&gt;Changing the URL of the browser/Saving the state&lt;/h2&gt;

&lt;p&gt;Now that we know that the browser supports the HTML5 history API, we can attempt to save the state of the current page (so after you have completed your request/response cycle etc).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;history.pushState()&lt;/code&gt; function takes three parameters:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;state&lt;/strong&gt; : This can be any JSON data structure which will be passed back to you on &lt;code&gt;window.onpopstate&lt;/code&gt; event which is discussed later. &lt;em&gt;null&lt;/em&gt; is also valid for this parameter.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;title&lt;/strong&gt;: This parameter is currently unused by major browsers. If you want to set the page title, you should store it in the state argument and set it manually in your &lt;code&gt;window.onpopstate&lt;/code&gt; callback.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;url&lt;/strong&gt;: The url that you want to appear in the users browser.&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;So the final definition is as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;history.pushState(state, title, url);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Calling the &lt;code&gt;history.pushState()&lt;/code&gt; function will immediately change the users in their browser and setup the browser stack. Nothing else.&lt;/p&gt;

&lt;h2&gt;Backwards navigation&lt;/h2&gt;

&lt;p&gt;Changing the url is one part of the puzzle, the other is letting the user navigate backwards correctly. If we did not implement this stage the user would remain on the same page until they hit a normal page again. To allow our users to navigate backwards correctly, we need to hook onto the &lt;code&gt;window.onpopstate&lt;/code&gt; event.&lt;/p&gt;

&lt;p&gt;In order to correctly register a function for this event, use the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;window.addEventListener(&quot;popstate&quot;, function(event){
    // Process the state here...
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The reasons for using &lt;code&gt;window.addEventListener&lt;/code&gt;  are as follows:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is the W3C DOM standard way of registering an event listener (&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener&quot;&gt;source&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;It allows multiple listeners to the event&lt;/li&gt;
&lt;li&gt;Any duplicate events are discarded&lt;/li&gt;
&lt;li&gt;Allows finer control over &lt;a href=&quot;http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing&quot;&gt;capturing vs bubbling&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;Going back to our example above, the event parameter that is being passed to us, will contain a property called &lt;code&gt;state&lt;/code&gt; (so &lt;code&gt;event.state&lt;/code&gt;). We can use this to re-setup the page in the exact same way that it was before the user navigated away.&lt;/p&gt;

&lt;h2&gt;Browser Compatibility&lt;/h2&gt;

&lt;p&gt;That is pretty much all there is that you need to know regarding the HTML5 History API. So in which browsers is it supported? I suggest checking the following &lt;a href=&quot;http://caniuse.com/#search=history&quot;&gt;link&lt;/a&gt; for up-to-date information and further reading.&lt;/p&gt;

&lt;h2&gt;Sample library&lt;/h2&gt;

&lt;p&gt;I am currently working on a sample library using the new HTML5 API&#39;s and will release the full library on my Github page once completed.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Becoming A Microsoft Certified Professional</title>
      <link>http://sblackler.net/2013/06/10/Becoming-An-MCP</link>
      <pubDate>Mon, 10 Jun 2013 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/06/10/Becoming-An-MCP</guid>
      <description>&lt;p&gt;As the title suggests, today I passed the 70-483 Programming in C# exam to offically become a Microsoft Certifed Professional.&lt;/p&gt;

&lt;p&gt;This is one of the things that has been in my sights for a very long time now, so I am extremly happy to have passed. I throughly recommend doing it for yourself if you haven&#39;t done so already. I know exams aren&#39;t everyones cup of tea, but even if you decide not to take the exam, I believe that the knownledge you gain during the study phase will prove invaluable to your day to day work.&lt;/p&gt;

&lt;p&gt;Since I already had 5 years programming experience with the .Net environment, the exam was mainly a tick in the box. That said, I would throughly recommend you read the &lt;a href=&quot;http://www.amazon.co.uk/CLR-via-Developer-Reference-ebook/dp/B00AA36R4U/ref=tmm_kin_title_0/277-8084778-0056569&quot;&gt;CLR via C# Forth Edition&lt;/a&gt;. The book gives a fantasic insight into the inner workings of the CLR and why some features are not supported by C#.&lt;/p&gt;

&lt;p&gt;I wish you all the best of luck if you decide to take this exam.&lt;/p&gt;

&lt;p&gt;Stu&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Correctly Raising Events in C#</title>
      <link>http://sblackler.net/2013/05/30/Correctly-Raising-Events-In-C-Sharp</link>
      <pubDate>Thu, 30 May 2013 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/05/30/Correctly-Raising-Events-In-C-Sharp</guid>
      <description>&lt;p&gt;In this small article, I will show you a method of raising events that prevents the associated race conditions. The first technique that I will show you is typical among many developers across all experiences. This method is the approach with the least thread safety:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if (MyEvent != null) MyEvent(this, MyEventArgs);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The problem with this approach is that between the calls to check &lt;code&gt;MyEvent&lt;/code&gt; for null and actually calling &lt;code&gt;MyEvent&lt;/code&gt;, a different thread could actually remove a delegate from the delegate chain; resulting in &lt;code&gt;MyEvent&lt;/code&gt; being null after we have checked it.&lt;/p&gt;

&lt;p&gt;In order to fix this and make it thread safe, developers often use this approach:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;EventHandler&amp;lt;MyEventArgs&amp;gt; temporaryEvent = MyEvent;
if (temporaryEvent != null) temporaryEvent(this, MyEventArgs);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In most scenarios, this approach is completely fine and makes the call thread safe. This is were most good developers stop. However, we can actually do better by removing a race condition.&lt;/p&gt;

&lt;p&gt;In the preceding code, a race condition exists but one that we can easily fix. Under some circumstances, which are unknown to me at present, the compiler may decided to re-write our thread safe code and convert it into the first approach. As we have limited control over what the compiler does and does not inline, we have to make another code change. Enter the &lt;code&gt;Volatile&lt;/code&gt; class, which contains methods for performing volatile memory (Read/Write) operations. Volatile memory operations are for special cases of synchronization, where normal locking is not an acceptable alternative.&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; On a multiprocessor system, a volatile write operation ensures that a value written to a memory location is immediately visible to all processors. A volatile read operation obtains the very latest value written to a memory location by any processor. These operations might require flushing processor caches, which can affect performance.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;In order to fix our code, when we set the variable &lt;code&gt;temporaryEvent&lt;/code&gt; we need to call the &lt;code&gt;Volatile.Read&lt;/code&gt; method which will ensure the thread safety of our method call. So we need to change the line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;EventHandler&amp;lt;MyEventArgs&amp;gt; temporaryEvent = MyEvent;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;EventHandler&amp;lt;MyEventArgs&amp;gt; temporaryEvent = Volatile.Read(ref MyEvent);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So now we have fixed our event code without worries. Be aware though, if you use the second approach, you may still call the event after it has been assigned null.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Using IDisposible correctly</title>
      <link>http://sblackler.net/2013/05/06/Using-IDisposible-correctly</link>
      <pubDate>Mon, 06 May 2013 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/05/06/Using-IDisposible-correctly</guid>
      <description>&lt;p&gt;&lt;em&gt;After a rather long period of absence thanks to Bournemouth University, I am back again. There are a few subtle changes happening on the website as and when I can get time to make the changes. If you notice a bug or would like to suggest an improvement please do via the comments section on every post or via the social media links in the about page.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In this article, I am going to show you how to use the &lt;code&gt;IDisposable&lt;/code&gt; interface correctly in your code. When I read others code, it is easy to pick up on subtle bugs. We need to begin to train ourselves to see the bugs and we do this by understanding what we are using. Before we begin, we need to make sure that we understand a core piece of computer science theory: Destructors.&lt;/p&gt;

&lt;h2&gt;Destructors&lt;/h2&gt;

&lt;p&gt;Generally speaking, destructors are the computers way of releasing resources from an application. In environments that contain a virtual machine with a garbage collection facility, the destructor is automatically called. In these environments however, the destructor is also called a &lt;code&gt;Finalizer&lt;/code&gt;. Although these environments are &lt;s&gt;good&lt;/s&gt; excellent at managing memory for us, we cannot guarantee when the &lt;code&gt;Finalizer&lt;/code&gt; is going to be called.&lt;/p&gt;

&lt;h2&gt;Enter Dispose&lt;/h2&gt;

&lt;p&gt;The purpose of the &lt;code&gt;Dispose&lt;/code&gt; is to guarantee when we are going to release resources. This might be at the end of a &lt;code&gt;foreach&lt;/code&gt; loop or at the end of a database connection. Either way, we have control of when we can release the resources. There are two types of resources that can be released: Managed and Unmanaged.&lt;/p&gt;

&lt;p&gt;Managed resources are typically objects that are run and controlled by the Common Language Runtime (CLR). Managed code supplies the metadata necessary for the CLR to provide services such as memory management and cross-language integration &lt;a href=&quot;http://stackoverflow.com/questions/334326/what-is-managed-unmanaged-code-in-c&quot;&gt;(Source)&lt;/a&gt;. Unmanaged resources are those outside the CLR such as Win32 API&#39;s. These can be called from within managed code allowing some serious memory leaks if we are not careful.&lt;/p&gt;

&lt;p&gt;The .Net libraries have some useful interfaces in them, one of them being the &lt;code&gt;IDisposable&lt;/code&gt; interface. This interface has just one method called &lt;code&gt;Dispose&lt;/code&gt; (the name seems standard from what I have seen). Here is the implementation of the interface:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public interface IDisposable
    {
       void Dispose()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we first implement the interface on our class, we are given the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public sealed class MyClass : IDisposable
    {
        public void Dispose()
        {
            /* Release resources here */
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While this implementation is fine if you don&#39;t mind waiting for the garbage collector to come and release the resources. What if your class has a large object inside (say ~250mb). Do you really want to wait for the garbage collector? Probably not.&lt;/p&gt;

&lt;p&gt;In order to fix our implementation, we need to do two things. Firstly, we need to implement a &lt;code&gt;Finalizer&lt;/code&gt; and then implement an overload to the original &lt;code&gt;Dispose&lt;/code&gt; method. The reason why we implement a &lt;code&gt;Finalizer&lt;/code&gt; is because we want to safe-guard ourselves if we forget to call the &lt;code&gt;Dispose&lt;/code&gt; method. For those that do not know what a &lt;code&gt;Finalizer&lt;/code&gt; looks like, here it is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public sealed class MyClass : IDisposable
    {
        public MyClass()
        {
            /* Constructor */
        }

        public ~MyClass()
        {
            /* Destructor */
        }

        public void Dispose()
        {
            /* Release resources here */
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to safe-guard ourselves as I just mentioned, our &lt;code&gt;Finalizer&lt;/code&gt; needs to call our &lt;code&gt;Dispose&lt;/code&gt; method like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public ~MyClass()
    {
        /* Destructor */
        Dispose();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You may have realised by now that we could, potentially, call the &lt;code&gt;Dispose&lt;/code&gt; twice. The user will call it once followed by the CLR calling it for us in case we forget (through the &lt;code&gt;Finalizer&lt;/code&gt;). This gives us the requirement for the overload of the &lt;code&gt;Dispose&lt;/code&gt; method I mentioned earlier. If &lt;strong&gt;we&lt;/strong&gt; call the &lt;code&gt;Dispose&lt;/code&gt; method then it is &lt;em&gt;safe&lt;/em&gt; for us to release managed resources. However, if the &lt;strong&gt;CLR&lt;/strong&gt; calls the &lt;code&gt;Dispose&lt;/code&gt; method then we cannot safely release managed resources because we do not know their current state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The CLR runs on a background thread, which we have no control over. Therefore, we cannot know any objects state on that thread.&lt;/p&gt;

&lt;p&gt;Now that we have identified that the &lt;code&gt;Dispose&lt;/code&gt; method can be called from two places, we can implement this into our code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public sealed class MyClass : IDisposable
    {
        public MyClass()
        {
            /* Constructor */
        }

        public ~MyClass()
        {
            /* Destructor */
            Dispose(false); // the CLR will call Dispose, so its an unsafe call
        }

        public void Dispose()
        {
            /* The interface implementation */
            Dispose(true); // WE are calling Dispose, so its a safe call
        }

        public void Dispose(bool safeToFreeManagedResources)
        {
            /* Free unmanaged resources */

            if (safeToFreeManagedResources)
            {
                /*  Free managed resources */
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Even though we have told the CLR that we are not to release managed resources twice, we will still release unmanaged resources twice. This is not only wasteful, but you could end up with an exception here which is something that &lt;strong&gt;SHOULD NEVER HAPPEN&lt;/strong&gt;. Luckily for us, the CLR has a neat way for us to tell it not to call the &lt;code&gt;Finalizer&lt;/code&gt; because we have already released all the resources necessary. Here is the one line magic fix:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public void Dispose()
    {
        /* The interface implementation */
        Dispose(true); // WE are calling Dispose, so its a safe call
        GC.SuppressFinalize(this); // WE have called dispose, there is no need to call it again Mr. GC.
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Best Practise&lt;/h2&gt;

&lt;p&gt;Now that we have our code fixed, without any issues or bugs, it&#39;s time to know a best practise. When an object implements the &lt;code&gt;IDisposable&lt;/code&gt; interface, we have the opportunity to use the &lt;code&gt;using&lt;/code&gt; statement. The idea of the &lt;code&gt;using&lt;/code&gt; statement is that once you have finished with the object, the CLR will call the &lt;code&gt;Dispose&lt;/code&gt; method for you. Note I said &lt;code&gt;Dispose&lt;/code&gt; not the &lt;code&gt;Finalizer&lt;/code&gt;. The &lt;code&gt;using&lt;/code&gt; statement is really easy to use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    static void Main(string[] args)
    {
        using (var myClass = new MyClass())
        {
            /* Do stuff here */
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When the compiler sees this code, it actually expands it to this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    static void Main(string[] args)
    {
        var myClass = new MyClass();
        try
        {
            /* Do stuff here */
        }
        finally
        {
            myClass.Dispose();
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So there it is. Hopefully now you can implement &lt;code&gt;IDisposable&lt;/code&gt; correctly according to your needs.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Semaphore vs SemaphoreSlim - A performance benchmark</title>
      <link>http://sblackler.net/2013/03/11/Semaphore-vs-SeamphoreSlim-Micro-Benchmark</link>
      <pubDate>Mon, 11 Mar 2013 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/03/11/Semaphore-vs-SeamphoreSlim-Micro-Benchmark</guid>
      <description>&lt;p&gt;In this post, I am going to show a small micro-benchmark to demonstrate the performance difference between the &lt;code&gt;Semaphore&lt;/code&gt; and &lt;code&gt;SemaphoreSlim&lt;/code&gt; classes in C#. A &lt;code&gt;Semaphore&lt;/code&gt; is often used to restrict the number of threads than can access some (physical or logical) resource. In this case, we want the restriction to be as little as possible.&lt;/p&gt;

&lt;p&gt;Semaphores are of two types: local semaphores and named system semaphores. If you create a Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name. Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create multiple Semaphore objects that represent the same named system semaphore, and you can use the OpenExisting method to open an existing named system semaphore. &lt;em&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/system.threading.semaphore.aspx&quot;&gt;Source&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A local semaphore exists only within your process. It can be used by any thread in your process that has a reference to the local Semaphore object. Each Semaphore object is a separate local semaphore. &lt;em&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/system.threading.semaphore.aspx&quot;&gt;Source&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The machine that I am using for this benchmark is a Intel core i3, clocked at 4ghz with 4GB DDR3 ram running Windows 7 x64 SP1 and .Net Framework 4.5.&lt;/p&gt;

&lt;p&gt;In order to begin the test, I created a new console application and imported the &lt;a href=&quot;http://sblackler.net/2013/03/11/Introducing-BMark-v1/&quot;&gt;BMark&lt;/a&gt; package from the &lt;a href=&quot;https://nuget.org/packages/BMark/&quot;&gt;NuGet&lt;/a&gt; repository. Next, I added the following code to the application as shown below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;const Int32 count = 106;

Semaphore regularSemaphore = new Semaphore(count, count);
SemaphoreSlim slimSemaphore = new SemaphoreSlim(count, count);

UInt64 amountToRun = (UInt64)(count - PerformanceTester.PreRunAmount - 2);

PerformanceTester.Run(&quot;Semaphore.WaitOne&quot;, amountToRun, () =&amp;gt; { regularSemaphore.WaitOne(); });
PerformanceTester.Run(&quot;Semaphore.Release&quot;, amountToRun, () =&amp;gt; { regularSemaphore.Release(); });
PerformanceTester.Run(&quot;SemaphoreSlim.WaitOne&quot;, amountToRun, () =&amp;gt; { slimSemaphore.Wait(); });
PerformanceTester.Run(&quot;SemaphoreSlim.Release&quot;, amountToRun, () =&amp;gt; { slimSemaphore.Release(); });

Console.WriteLine(PerformanceTester.GetResults());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By default, the &lt;code&gt;PerformanceTester&lt;/code&gt; will run each test 4 times before starting the actual timed test. Since we are dealing with a blocking resource, I added some extra capacity so that the test would not block at any point. When the code is run in release mode without the debugger, the output of the program is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Semaphore.WaitOne:         0.09ms    NumberOfSamples: 100
Semaphore.Release:         0.05ms    NumberOfSamples: 100
SemaphoreSlim.WaitOne:     0.01ms    NumberOfSamples: 100
SemaphoreSlim.Release:     0.01ms    NumberOfSamples: 100
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As the results show, the &lt;code&gt;SemaphoreSlim&lt;/code&gt; class is a tiny bit quicker. After testing this myself earlier, I thought that others could run this themselves and hopefully receive a small increase in performance in their applications. The reason for the performance increase is because the &lt;code&gt;SemaphoreSlim&lt;/code&gt; class provides a lightweight alternative to the &lt;code&gt;Semaphore&lt;/code&gt; class that doesn&#39;t use Windows kernel semaphores.&lt;/p&gt;

&lt;p&gt;In essence, if you do not need a named &lt;code&gt;Semaphore&lt;/code&gt;, use the &lt;code&gt;SemaphoreSlim&lt;/code&gt; class.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Introducing BMark Version 0.1 - A .Net Micro-Benchmarking package</title>
      <link>http://sblackler.net/2013/03/11/Introducing-BMark-v1</link>
      <pubDate>Mon, 11 Mar 2013 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/03/11/Introducing-BMark-v1</guid>
      <description>&lt;p&gt;This post is dedicated to the release of a small utility class that I have just released on &lt;a href=&quot;https://nuget.org/packages/BMark/&quot;&gt;NuGet&lt;/a&gt;. The aim of BMark is to provide a simple way of running multiple microbenchmarks. This is my first ever NuGet package so there is a chance that I have done something wrong. Please notify me ASAP if you do notice anything and I will sort it out when I can.&lt;/p&gt;

&lt;h2&gt;Using BMark&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;In order to use BMark, please make sure that you have NuGet package manager installed, or download the code from the &lt;a href=&quot;https://github.com/sblackler/BMark&quot;&gt;GitHub Project Page&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you are using the NuGet package manager to install packages, simply search for &lt;code&gt;BMark&lt;/code&gt; in the online sources and click install.&lt;/p&gt;

&lt;p&gt;Or, if you prefer to use the NuGet package console, simply type in the following command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Install-Package BMark
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you are ready to run some benchmarks. The core method &lt;code&gt;Run&lt;/code&gt; has three parameters which are the test name, the amount of times to run the test and the actual code to test. Here is a quick demonstration from a future blog post:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PerformanceTester.Run(&quot;SemaphoreSlim.Release&quot;, amountToRun, () =&amp;gt; { slimSemaphore.Release(); });

Console.WriteLine(PerformanceTester.GetResults());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&#39;s as easy as that. Feel free to contribute any modifications to the &lt;a href=&quot;https://github.com/sblackler/BMark&quot;&gt;GitHub Project Page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Happy benchmarking&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Implementing The Observer Pattern</title>
      <link>http://sblackler.net/2013/03/07/The-Observer-Pattern-In-CSharp-and-Java</link>
      <pubDate>Thu, 07 Mar 2013 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/03/07/The-Observer-Pattern-In-CSharp-and-Java</guid>
      <description>&lt;p&gt;The observer pattern is a way of defining a one-to-many relationship between two classes. Typically the pattern is used to provide push based notifications of changes from the observed subject to the subscribed listeners, much like you receive notifications on a mobile phone.&lt;/p&gt;

&lt;p&gt;For this pattern we need to two interfaces which classes will implement. First of all, we have &lt;code&gt;IObservable&lt;/code&gt; which, when implemented, is going to push any changes to the observers. Secondly, we have &lt;code&gt;IObserver&lt;/code&gt; which, when implemented, is going to listen to the &lt;code&gt;IObservable&lt;/code&gt; instance for changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; &lt;em&gt;I have made everything in this post as generic as possible with the aim of ease of use for you, dear reader.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;IObservable&amp;lt;T&amp;gt;&lt;/h2&gt;

&lt;p&gt;This interface needs to define a subscribe method and optionally an unsubscribe method, such as this Java implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IObservable&amp;lt;T&amp;gt; {
    void subscribe(IObserver&amp;lt;T&amp;gt; observer);
    void unsubscribe(IObserver&amp;lt;T&amp;gt; observer);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;IObserver&amp;lt;T&amp;gt;&lt;/h2&gt;

&lt;p&gt;This interface needs to define a method from which the &lt;code&gt;IObservable&lt;/code&gt; instance can call when it detects a change. A typical example, taken from the .Net implementation, is to define an &lt;code&gt;onNext&lt;/code&gt; method such as this implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IObserver&amp;lt;T&amp;gt; {
    void onNext(T value);
    void onCompleted();
    void onError(Exception e);      
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;onNext&lt;/code&gt; method takes the value added/changed in the &lt;code&gt;IObservable&lt;/code&gt; instance. I have also defined two additional methods for when an error is raised and when the observer should complete its work. This interface is already defined for .Net programmers.&lt;/p&gt;

&lt;h2&gt;The Headmaster Example&lt;/h2&gt;

&lt;p&gt;I am going to briefly show a full implementation using a school classroom. In this example, we are simply going to watch a &lt;code&gt;Lesson&lt;/code&gt; for any pupils enrolling onto the lesson and write their names to the console window. To make this clear, the example is in Java.&lt;/p&gt;

&lt;p&gt;To start off with, I am going to define an immutable (an object whose state cannot be modified after it is created) &lt;code&gt;Pupil&lt;/code&gt; class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Pupil {

    private String _name;
    private int _age;

    public Pupil(String name, int age)
    {
        _name = name;
        _age = age;
    }

    public String getName()
    {
        return _name;
    }

    public int getAge()
    {
        return _age;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next, I am going to implement a &lt;code&gt;Lesson&lt;/code&gt; class that implements &lt;code&gt;IObservable&lt;/code&gt; of the type &lt;code&gt;Pupil&lt;/code&gt;. If the concepts of generics confuses you, don&#39;t worry, I will explain this in a future post.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import java.util.ArrayList;
import java.util.List;

public class Lesson implements IObservable&amp;lt;Pupil&amp;gt; {

    List&amp;lt;IObserver&amp;lt;Pupil&amp;gt;&amp;gt; _subscribers = new ArrayList&amp;lt;IObserver&amp;lt;Pupil&amp;gt;&amp;gt;();

    @Override
    public void subscribe(IObserver&amp;lt;Pupil&amp;gt; observer) {
        // check the argument
        if(observer != null)
        {
            _subscribers.add(observer);
        }
        // if the argument is null throw the exception or something
    }

    @Override
    public void unsubscribe(IObserver&amp;lt;Pupil&amp;gt; observer) {
        // check the argument
        if(observer != null)
        {
            _subscribers.remove(observer);
        }
        // if the argument is null throw the exception or something
    }

    public void enrollPupil(Pupil p)
    {
        // do something with p here...
        for(IObserver&amp;lt;Pupil&amp;gt; observer : _subscribers)
        {
            // Notify the subscribers of the new pupil
            observer.onNext(p);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see from the implementation above, in order to implement &lt;code&gt;IObservable&lt;/code&gt; properly, we need to have a way of maintaining a collection of objects that are subscribed to changes. The easiest way of doing this is through a list as shown above. The &lt;code&gt;subscribe&lt;/code&gt; method adds to the list while the &lt;code&gt;unsubscribe&lt;/code&gt; method removes it from the list. When the &lt;code&gt;enrollPupil&lt;/code&gt; method is called, we perform an action with the &lt;code&gt;Pupil&lt;/code&gt; before iterating through the list and letting each observer know of the change.&lt;/p&gt;

&lt;p&gt;Penultimately, we need to implement the &lt;code&gt;IObserver&lt;/code&gt; interface in the form of a &lt;code&gt;LessonObserver&lt;/code&gt;. This is implemented as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class LessonObserver implements IObserver&amp;lt;Pupil&amp;gt; {
    @Override
    public void onNext(Pupil value) {
        System.out.println(value.getName() + &quot; has enrolled on the course.&quot;);
    }

    @Override
    public void onCompleted() {
        // This is fired when we stop listening
    }

    @Override
    public void onError(Exception e) {
        // This is fired when an error occurs (if the Observable throws it to us)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Lastly, we just need a simple way of testing the application which I have done for you:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Driver {
    public static void main(String[] args)
    {
        // create the objects
        Lesson l = new Lesson();
        LessonObserver lo = new LessonObserver();

        // subscribe to notifications
        l.subscribe(lo);

        // add some dummy data
        l.enrollPupil(new Pupil(&quot;Stueh&quot;, 18));
        l.enrollPupil(new Pupil(&quot;Jon&quot;, 18));
        l.enrollPupil(new Pupil(&quot;Kirsty&quot;, 18));

        // unsubscribe to finish off
        l.unsubscribe(lo);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All being well you should end up with the following output in your console window:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Stueh has enrolled on the course.
Jon has enrolled on the course.
Kirsty has enrolled on the course.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I hope that you now understand how simple the observer pattern is and how it can be useful.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>System Databases and Backups</title>
      <link>http://sblackler.net/2013/01/25/System-Databases-and-Backups</link>
      <pubDate>Fri, 25 Jan 2013 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2013/01/25/System-Databases-and-Backups</guid>
      <description>&lt;p&gt;In this post I am going to talk a little bit about the system databases, what they are used for and provide a few additional resources should you be interested in reading more about each database.&lt;/p&gt;

&lt;h2&gt;Master&lt;/h2&gt;

&lt;p&gt;The name of this database gives away its true purpose. It is the &lt;em&gt;master&lt;/em&gt; database for SQL Server. It is responsible for the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Instance wide metadata;&lt;/li&gt;
&lt;li&gt;Server configuration;&lt;/li&gt;
&lt;li&gt;Initialisation information; and&lt;/li&gt;
&lt;li&gt;Information about all databases in the instance.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Because of the reasons specified above, the &lt;em&gt;master&lt;/em&gt; database is very important to SQL Server. Therefore, it is extremely important that you backup the &lt;em&gt;master&lt;/em&gt; regularly in the event that the &lt;em&gt;master&lt;/em&gt; database becomes corrupted.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://blog.sqlauthority.com/2009/02/15/sql-server-reasons-to-backup-master-database-why-should-master-database-backedup/&quot;&gt;Reasons to Backup Master Database – Why Should Master Database Backed up&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://blog.sqlauthority.com/2009/08/12/sql-server-backup-master-database-interval-master-database-best-practices/&quot;&gt;Backup master Database interval&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;MSDB&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;msdb&lt;/em&gt; database stores configuration data for a number of resources including but not limited to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SQL Server Agent&lt;/li&gt;
&lt;li&gt;Database Mail&lt;/li&gt;
&lt;li&gt;Service Broker&lt;/li&gt;
&lt;li&gt;Backups&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;As this database contains alot of configuration data, it is vital that this database is backed up alongside the &lt;em&gt;master&lt;/em&gt; database. Simply backup this database when ever a configuration change is made to one of the above services.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://technet.microsoft.com/en-us/library/ms188274.aspx&quot;&gt;Considerations for Backing Up the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190749.aspx&quot;&gt;Considerations for Restoring the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Model&lt;/h2&gt;

&lt;p&gt;As the name suggests, the &lt;em&gt;model&lt;/em&gt; database is used as a template for every database that you create. For example, if you want a series of stored procedures in every database you create on the system from now on, you create the scripts in &lt;em&gt;model&lt;/em&gt;. It is not just limited to stored procedures though, other SQL objects such as custom data types can also be created inside of &lt;em&gt;model&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Depending on your businesses needs, this is also a vital database to backup as it may contain some code that should not be lost. As the database is small, Microsoft recommend creating a full database backup with backing up the log file deemed unnecessary.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://technet.microsoft.com/en-us/library/ms188274.aspx&quot;&gt;Considerations for Backing Up the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190749.aspx&quot;&gt;Considerations for Restoring the model and msdb Databases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Resource&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;resource&lt;/em&gt; database is a special database. For starters, it is read-only and hidden which would explain why we never see it in list of databases in SSMS. The purpose of this database is to hold the definitions of all system objects.&lt;/p&gt;

&lt;p&gt;When querying against a user database, it appears that the &lt;code&gt;sys&lt;/code&gt; schema belongs to the user database. In fact, the definitions of all &lt;code&gt;sys&lt;/code&gt; objects are held inside of the &lt;em&gt;resource&lt;/em&gt; database.&lt;/p&gt;

&lt;h2&gt;TempDB&lt;/h2&gt;

&lt;p&gt;The tempdb system database is a global resource that has been used since
the inception of SQL Server. It is available to all SQL Server users
connected to the SQL Server instance. It holds many types of data and
can often be the source of a performance bottleneck.&lt;/p&gt;

&lt;p&gt;For example, tempdb can hold the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Temporary user objects that are explicitly created, such as: global
or local temporary tables, temporary stored procedures, table
variables, or cursors.&lt;/li&gt;
&lt;li&gt;Internal objects that are created by the SQL Server Database Engine,
for example, work tables to store intermediate results for spools or
sorting&lt;/li&gt;
&lt;li&gt;Row versions that are generated by data modification transactions in
a database that uses read-committed using row versioning isolation
or snapshot isolation transactions&lt;/li&gt;
&lt;li&gt;Row versions that are generated by data modification transactions
for features, such as: online index operations, Multiple Active
Result Sets (MARS), and AFTER triggers&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;For more information about how you know whether &lt;em&gt;tempdb&lt;/em&gt; is a problem for your system, read a few of the following articles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://sblackler.net/2012/06/15/tempdb-health-check-queries/&quot;&gt;TempDB Health Check Queries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190768.aspx&quot;&gt;TempDB
(MSDN)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.brentozar.com/archive/2012/12/bob-dylan-explains-tempdb-video/&quot;&gt;Bob Dylan Explains TempDB&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Distribution&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;distribution&lt;/em&gt; database is not always created on a SQL server instance. This is because it has the important role of storing metadata and history data for all types of replication and transactions for transactional replication.&lt;/p&gt;

&lt;p&gt;Only when the server is configured as a distributor, link at the end of this section, is the database created. Because of the data stored in the &lt;em&gt;distribution&lt;/em&gt; database, Microsoft recommend that this database is backed up in the event of a disaster to the distribution instance.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://technet.microsoft.com/en-us/library/ms152531.aspx&quot;&gt;Types of Replication&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms151860.aspx&quot;&gt;Configuring Distribution DB&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms151152.aspx&quot;&gt;Backup and Restore Replicated Databases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Backups&lt;/h2&gt;

&lt;p&gt;As I have mentioned in the article so far, it is important to backup the system databases. Luckily, there is an excellent guide on MSDN for &lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms190190.aspx&quot;&gt;backing up our system databases&lt;/a&gt;. This guide covers what recovery options can be used and the implications as well. &lt;a href=&quot;http://msdn.microsoft.com/en-gb/library/ms189272.aspx&quot;&gt;This guide&lt;/a&gt; will provide you information on how to view or change your recovery model for a specific database, should you need the reminder.&lt;/p&gt;

&lt;p&gt;Hopefully that gives you a quick oversight on what each database is used for and resources to continue exploration if you would like to.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>SQL Server - Notes on SARGability</title>
      <link>http://sblackler.net/2012/12/13/Notes-on-Sargability</link>
      <pubDate>Thu, 13 Dec 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/12/13/Notes-on-Sargability</guid>
      <description>&lt;p&gt;Sargabliity is a term used to describe whether or not a query can leverage existing indexes in order to speed up query execution. SARGABLE means Search ARGument ABLE.&lt;/p&gt;

&lt;p&gt;Commonly, new or inexperienced SQL developers will often write queries such as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT col1, col2 FROM myTable WHERE YEAR(col3) &amp;gt;= 2008
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While this is perfectly valid SQL, having the function &lt;code&gt;YEAR()&lt;/code&gt;  on the left hand side of the condition will cause SQL Server to evaluate every single row of the table. This is fine for a small table but for a large table and multiple users, this approach will not scale very well at all as it will consume too many resources.&lt;/p&gt;

&lt;p&gt;In essence, if you ask the database server to manipulate the data in order to get the results, you will suffer a performance impact and reduce your ability to scale. Now we know this, we can re-write the query to perform a lot better:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT col1, col2 FROM myTable WHERE col3 &amp;gt;= &#39;2008-01-01 00:00:00&#39;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With our new query above, we can leverage our fictious index on &lt;code&gt;col3&lt;/code&gt; to quickly search and return all the results. This approach is much like you would go through a phonebook. You would not search through the phonebook, looking at every name to see whether they started with the letter S. Instead, you know that the phonebook is split into sections (much like our index in our database) so you can jump straight to the section that begins with S and begin searching from there. This is what we have just told SQL Server to do with a minor modification of our query.&lt;/p&gt;

&lt;h2&gt;Matching your data types&lt;/h2&gt;

&lt;p&gt;By matching the data types in your &lt;code&gt;WHERE&lt;/code&gt; statements you avoid implicit conversions (automatic conversions). There are two main reasons that we want to avoid implicit conversions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is an extra operation that we potentially don&#39;t need&lt;/li&gt;
&lt;li&gt;If the conversion is on the side of the data table, it will evaluate the conversion for every row in the table which is &lt;strong&gt;SLOW&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;Which side of the evaluation expression the conversion happens on depends on the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190309.aspx&quot;&gt;order of precedence&lt;/a&gt;. It is important to note the following from the article linked:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, an error is returned.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;a href=&quot;http://sqlblog.com/blogs/tibor_karaszi/&quot;&gt;Tibor Karaszi&lt;/a&gt; has a detailed post on the subject here: &lt;a href=&quot;http://sqlblog.com/blogs/tibor_karaszi/archive/2009/04/28/match-those-types.aspx&quot;&gt;Match Those Types&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Finding implicit conversions in the QPC&lt;/h2&gt;

&lt;p&gt;Jonathon Kehayias (&lt;a href=&quot;http://sqlblog.com/blogs/jonathan_kehayias/&quot;&gt;blog&lt;/a&gt;) has a great query to find queries that have implicate conversions that exist in the query plan cache. I have included the query below as a point-in-time snapshot of the query, but please check &lt;a href=&quot;http://sqlblog.com/blogs/jonathan_kehayias/archive/2010/01/08/finding-implicit-column-conversions-in-the-plan-cache.aspx&quot;&gt;the original&lt;/a&gt; link for updated versions of the query and additional comments.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

DECLARE @dbname SYSNAME 
SET @dbname = QUOTENAME(DB_NAME()); 

WITH XMLNAMESPACES 
   (DEFAULT &#39;http://schemas.microsoft.com/sqlserver/2004/07/showplan&#39;) 
SELECT 
   stmt.value(&#39;(@StatementText)[1]&#39;, &#39;varchar(max)&#39;), 
   t.value(&#39;(ScalarOperator/Identifier/ColumnReference/@Schema)[1]&#39;, &#39;varchar(128)&#39;), 
   t.value(&#39;(ScalarOperator/Identifier/ColumnReference/@Table)[1]&#39;, &#39;varchar(128)&#39;), 
   t.value(&#39;(ScalarOperator/Identifier/ColumnReference/@Column)[1]&#39;, &#39;varchar(128)&#39;), 
   ic.DATA_TYPE AS ConvertFrom, 
   ic.CHARACTER_MAXIMUM_LENGTH AS ConvertFromLength, 
   t.value(&#39;(@DataType)[1]&#39;, &#39;varchar(128)&#39;) AS ConvertTo, 
   t.value(&#39;(@Length)[1]&#39;, &#39;int&#39;) AS ConvertToLength, 
   query_plan 
FROM sys.dm_exec_cached_plans AS cp 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 
CROSS APPLY query_plan.nodes(&#39;/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple&#39;) AS batch(stmt) 
CROSS APPLY stmt.nodes(&#39;.//Convert[@Implicit=&quot;1&quot;]&#39;) AS n(t) 
JOIN INFORMATION_SCHEMA.COLUMNS AS ic 
   ON QUOTENAME(ic.TABLE_SCHEMA) = t.value(&#39;(ScalarOperator/Identifier/ColumnReference/@Schema)[1]&#39;, &#39;varchar(128)&#39;) 
   AND QUOTENAME(ic.TABLE_NAME) = t.value(&#39;(ScalarOperator/Identifier/ColumnReference/@Table)[1]&#39;, &#39;varchar(128)&#39;) 
   AND ic.COLUMN_NAME = t.value(&#39;(ScalarOperator/Identifier/ColumnReference/@Column)[1]&#39;, &#39;varchar(128)&#39;) 
WHERE t.exist(&#39;ScalarOperator/Identifier/ColumnReference[@Database=sql:variable(&quot;@dbname&quot;)][@Schema!=&quot;[sys]&quot;]&#39;) = 1
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Invertability&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://sqlblog.com/blogs/rob_farley&quot;&gt;Rob Farley&lt;/a&gt; has an &lt;a href=&quot;http://sqlblog.com/blogs/rob_farley/archive/2010/11/09/inverse-predicates-look-both-ways-before-you-cross.aspx&quot;&gt;excellent article&lt;/a&gt; on inverting the search predicates. I thought this is a must read and a technique that we could apply to our own development.&lt;/p&gt;

&lt;h2&gt;For the unavoidable situations&lt;/h2&gt;

&lt;p&gt;Sometimes you need to break the guidelines of SARGABILITY for various reasons. But there are ways in which you can still improve the performance of your queries. For instance, you can use an indexed view or a computed column.&lt;/p&gt;

&lt;p&gt;Remember these are only guidelines. Test, test and test some more for your specific scenario.&lt;/p&gt;

&lt;h2&gt;The Big 3&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Try to leave the manipulation of the data in the table alone where you can&lt;/li&gt;
&lt;li&gt;If you can not effectively do #1 explore other avenues such as computed columns or indexed views&lt;/li&gt;
&lt;li&gt;Make sure you know the data types in your system in order to avoid implicit conversions&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Further Reading&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://sqlbits.com/Sessions/Event7/Understanding_SARGability_to_make_your_queries_run_faster&quot;&gt;Understanding SARGability (to make your queries run faster)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msmvps.com/blogs/robfarley/archive/2010/01/22/sargable-functions-in-sql-server.aspx&quot;&gt;SARGable functions in SQL Server&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.brentozar.com/archive/2010/06/sargable-why-string-is-slow/&quot;&gt;Sargability: Why %string% Is Slow&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://sqlblog.com/blogs/rob_farley/archive/2010/02/02/a-case-study-in-sargability.aspx&quot;&gt;A CASE study in SARGability&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>DELETE vs TRUNCATE</title>
      <link>http://sblackler.net/2012/12/13/Delete-vs-truncate</link>
      <pubDate>Thu, 13 Dec 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/12/13/Delete-vs-truncate</guid>
      <description>&lt;p&gt;In this post, I continue my beginners series by looking at the difference between delete and truncate. As a developer it is an important to recognise the differences between the two and how they affect the recovery options you have should an error occur or a malicious user enters your system.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Like my previous posts, this information is specific to MSSQL but the concepts are similar in other RDBMS&#39;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;DELETE&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;DELETE&lt;/code&gt; keyword is the most common form of deletion that you will see in most environments. The basic syntax looks like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DELETE FROM &amp;lt;table&amp;gt; [WHERE &amp;lt;some boolean condition&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As the keyword &lt;code&gt;DELETE&lt;/code&gt; suggests, running this query against a relational database engine will delete the specified rows from the table. &lt;code&gt;DELETE&lt;/code&gt; effectively has two main modes of operation. Delete everything or delete specific rows.&lt;/p&gt;

&lt;p&gt;In order to delete specific values from a given table, the &lt;code&gt;WHERE&lt;/code&gt; clause must be specified. The &lt;code&gt;WHERE&lt;/code&gt; clause is exactly the same as the &lt;code&gt;WHERE&lt;/code&gt; clause for any &lt;code&gt;SELECT&lt;/code&gt; statement. If the &lt;code&gt;WHERE&lt;/code&gt; clause is not specified, the &lt;code&gt;DELETE&lt;/code&gt; reverts back to its delete everything mode of operation. Depending on the amount of rows being deleted, and the recovery scenario needed, &lt;code&gt;TRUNCATE&lt;/code&gt; may be a better option for your query, more on this later.&lt;/p&gt;

&lt;p&gt;As a best practise of mine, I always write my queries as a &lt;code&gt;SELECT&lt;/code&gt; statement first. There are many reasons for doing/not doing this but my reasoning is simple. I want to test that my &lt;code&gt;WHERE&lt;/code&gt; clauses functioned as I intended. By looking at the results from the &lt;code&gt;SELECT&lt;/code&gt; statement, I can tell whether or not the &lt;code&gt;DELETE&lt;/code&gt; will function correctly.&lt;/p&gt;

&lt;h2&gt;TRUNCATE&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;TRUNCATE&lt;/code&gt; keyword is rarely used in production environments purely for the main reason being that it is &lt;strong&gt;VERY DANGEROUS&lt;/strong&gt;. Maximum caution is advised. &lt;code&gt;TRUNCATE&lt;/code&gt; only has one mode of operation, delete everything. The syntax for truncating a table looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; TRUNCATE &amp;lt;table name&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As I said before, this will delete everything. But there are a number of reasons why you would choose to truncate over delete with the main reason being efficiency.&lt;/p&gt;

&lt;h2&gt;The Internals&lt;/h2&gt;

&lt;p&gt; &lt;em&gt;Warning: Information in this section is likely to be very MSSQL specific and advanced in nature&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To understand why &lt;code&gt;TRUNCATE&lt;/code&gt; is more efficient than &lt;code&gt;DELETE&lt;/code&gt;, you need to understand the internals how the two types of query work.&lt;/p&gt;

&lt;h3&gt;DELETE&lt;/h3&gt;

&lt;p&gt;When the database engine is asked to delete from a table, the database engine finds and removes the row from the relevant data pages and all index pages where the row is entered and adds an entry to the log file. The process of going through each index involves &lt;code&gt;SEEK&lt;/code&gt; operations as opposed to &lt;code&gt;SCAN&lt;/code&gt; operations (for better performance).&lt;/p&gt;

&lt;p&gt;In essence, the more indexes you have on your table, then longer your &lt;code&gt;DELETE&lt;/code&gt; statements will take. The same principal applies to &lt;code&gt;INSERT&lt;/code&gt; and &lt;code&gt;UPDATE&lt;/code&gt; statements.&lt;/p&gt;

&lt;p&gt;Depending on what recovery mode you have selected will depend on the information stored in the log file. However, all deletes are logged in the log file, it is just the information in the log file that changes. The log file stores the data in hexidecimal format and will need to be converted before any potential data recovery.&lt;/p&gt;

&lt;h3&gt;TRUNCATE&lt;/h3&gt;

&lt;p&gt;When the database engine is asked to &lt;code&gt;TRUNCATE&lt;/code&gt; a table, it simply removes all the table&#39;s data pages en mass. If the statement is encapsulated in a transaction then a &lt;code&gt;TRUNCATE&lt;/code&gt; operation has the potential to be rolled back.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;TRUNCATE&lt;/code&gt; is more efficient than &lt;code&gt;DELETE&lt;/code&gt;&#39;s because:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Fewer locks may be needed. Truncation typically requires only a single schema modification lock at the table level (and exclusive locks on each &lt;em&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190969.aspx&quot;&gt;extent&lt;/a&gt;&lt;/em&gt; deallocated). Deletion might acquire locks at a lower (row or page) granularity as well as exclusive locks on any pages deallocated.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Only truncation guarantees that all pages are deallocated from a heap table. Deletion may leave empty pages in a heap even if an exclusive table lock hint is specified (for example if a row-versioning isolation level is enabled for the database).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Truncation is &lt;a href=&quot;http://technet.microsoft.com/en-us/magazine/gg552991.aspx&quot;&gt;always minimally logged&lt;/a&gt; (regardless of the recovery model in use). Only page deallocation operations are recorded in the transaction log.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Truncation can use &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms177495.aspx&quot;&gt;deferred drop&lt;/a&gt; if the object is 128 extents or larger in size. Deferred drop means the actual deallocation work is performed asynchronously by a background server thread.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Replication&lt;/h2&gt;

&lt;p&gt;The main difference between &lt;code&gt;DELETE&lt;/code&gt; and &lt;code&gt;TRUNCATE&lt;/code&gt; in terms of replication is that Truncation is &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms177570.aspx&quot;&gt;not allowed&lt;/a&gt; on a table that is published using transactional or merge replication.  How deletions are replicated depends on the type of replication and how it is configured. For example, snapshot replication just replicates a point-in-time view of the table using bulk methods - incremental changes are not tracked or applied. Transactional replication works by reading log records and generating appropriate transactions to apply the changes at subscribers. Merge replication tracks changes using triggers and metadata tables.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;- Credit to SQLKiwi for &lt;a href=&quot;http://dba.stackexchange.com/a/30347/2334&quot;&gt;his answer&lt;/a&gt; on DBA.SE which explains more about the internals of the &lt;code&gt;DELETE&lt;/code&gt; and &lt;code&gt;TRUNCATE&lt;/code&gt; operations. I advise reading this and the links in the comments also. Here is Paul&#39;s &lt;a href=&quot;http://sqlblog.com/blogs/paul_white/default.aspx&quot;&gt;Blog&lt;/a&gt; &amp;amp; &lt;a href=&quot;https://twitter.com/SQL_Kiwi&quot;&gt;Twitter&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>SQL Joins for Beginners</title>
      <link>http://sblackler.net/2012/11/30/SQL-Joins-Beginners</link>
      <pubDate>Fri, 30 Nov 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/11/30/SQL-Joins-Beginners</guid>
      <description>&lt;p&gt;In this post I am going to focus on JOINs in SQL which is primarily aimed at beginners. I will also cover typical scenarios when you would use each type of join starting with an INNER JOIN.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This information has only been tested on SQL Server 2012, but the queries should easily transfer to Oracle and MySQL with very little modification. The only bit you may have to modify is the &lt;code&gt;CREATE TABLE&lt;/code&gt; statements in the sql fiddle&#39;s provided in the article.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;INNER JOIN&lt;/h2&gt;

&lt;p&gt;An INNER JOIN is one of the joins that I commonly use. The purpose of the join is to take the records from both tables where the join condition is met. For example, imagine that you have the following tables&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Table A&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;id      value
------------
 1      stuart
 2      sophia
 3      victoria
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Table B&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;id      value
------------
 2      sophia
 3      victoria
 4      andy
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we join the two tables on the &lt;code&gt;name&lt;/code&gt; field we should expect to get sophia and victoria as our results as they exist in both tables. The following &lt;a href=&quot;http://sqlfiddle.com/#!6/c6709/2&quot;&gt;query&lt;/a&gt; demonstrates this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
INNER JOIN tableB ON tableA.value = tableB.value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We get the following output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;| ID |    VALUE |
-----------------
|  2 | sophia |
|  3 | victoria |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The results for stuart and andy are not included as part of the results because they do not exist in the other table. For either one of them to be returned in the results, they would need a corresponding record in the other table.&lt;/p&gt;

&lt;h2&gt;LEFT/RIGHT (OUTER) JOIN&lt;/h2&gt;

&lt;p&gt;If we want to pull all of the results from one of the tables but not all of the results from the other table, we can use a LEFT/RIGHT join. Using the same tables as before, I want to pull all the results from TableA and only those records in TableB where it has a corresponding record in TableA. So I modify my query to be the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
LEFT JOIN tableB ON tableA.value = tableB.value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What I am expecting from this query is the rows for stuart, sophia and victoria to be returned. We can test this in the following &lt;a href=&quot;http://sqlfiddle.com/#!6/775bd/1&quot;&gt;query&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;| ID |    VALUE |
-----------------
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One thing that you may have noticed is that in the title for this section I included &lt;code&gt;OUTER&lt;/code&gt; in brackets. This is because the &lt;code&gt;OUTER&lt;/code&gt; keyword is optional for LEFT/RIGHT/FULL joins. So to make this clear, &lt;code&gt;LEFT JOIN&lt;/code&gt; is the exact same as &lt;code&gt;LEFT OUTER JOIN&lt;/code&gt;. I always omit the &lt;code&gt;OUTER&lt;/code&gt; keyword to save on the amount that I have to type, as do most SQL professionals.&lt;/p&gt;

&lt;p&gt;If we want all the rows from TableB and only the matching rows from TableA then we can modify the original query to look like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
RIGHT JOIN tableB ON tableA.value = tableB.value
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;FULL (OUTER) JOIN&lt;/h2&gt;

&lt;p&gt;A FULL JOIN is not one that you commonly see in beginner examples. This type of join returns both tables but any results that do not match the join condition will be replaced with &lt;code&gt;NULL&lt;/code&gt;. Put simpley, one way to think of a FULL JOIN is that is effectively a LEFT JOIN and a RIGHT JOIN merged together.  So if we modify our original query we should see all the rows returned, a total of four rows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;|     ID |    VALUE |
---------------------
|      1 |   stuart |
|      2 | sophia |
|      3 | victoria |
| (null) |   (null) |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this you will notice the last record is &lt;code&gt;NULL&lt;/code&gt;. This is because the &lt;code&gt;NULL&lt;/code&gt; record appears in TableB but not TableA. If we swapped TableA and TableB in our query, we would see the following result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;|     ID |    VALUE |
---------------------
|      2 | sophia |
|      3 | victoria |
|      4 |     andy |
| (null) |   (null) |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To test this out for yourself click &lt;a href=&quot;http://sqlfiddle.com/#!6/d99ca/1&quot;&gt;this link&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;CROSS JOIN&lt;/h2&gt;

&lt;p&gt;With a CROSS JOIN every row from TableA will be matched to every row of TableB. So if you had 5 rows in each table, the result would contain 25 rows (TableA&#39;s rows x TableB&#39;s rows). The result of the join is known as a Cartesian product. Unlike the other types of join that we have seen so far, a CROSS JOIN does not have a join condition (so it misses of the &lt;code&gt;on x = y&lt;/code&gt; part of the query). We can test this by modifying our query to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT *
FROM tableA
CROSS JOIN tableB
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which gives us the following result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;| ID |    VALUE |
-----------------
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
|  1 |   stuart |
|  2 | sophia |
|  3 | victoria |
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you would like to experiment with this more, use &lt;a href=&quot;http://sqlfiddle.com/#!6/d99ca/8&quot;&gt;this sql fiddle&lt;/a&gt;. In fact Cartesian products are formed for more than just CROSS JOIN&#39;s. I will go into detail on this in a later blog post.&lt;/p&gt;

&lt;p&gt;It is also possible to use a technique called &lt;code&gt;SELF JOINING&lt;/code&gt;, in which you would join say TableA to TableA. In other words you create a INNER/OUTER join to the same table. There are a few reasons why you would do this, which I will cover in a future blog post if necessary.&lt;/p&gt;

&lt;p&gt;Hopefully this will give the beginners a starting point to learn the basics of joins. I am going to add a few pictures in a few days to help explain for those who learn visually. Please do experiment with the code given in the article, it is honestly the best way of learning the concepts. If you have any feedback to give, please leave a comment or drop me an email.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Website Update - Almost there now</title>
      <link>http://sblackler.net/2012/11/29/Website-Almost-There</link>
      <pubDate>Thu, 29 Nov 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/11/29/Website-Almost-There</guid>
      <description>&lt;p&gt;Welcome to my newly updated website. In this post I am going to talk a little bit about the tools that I used to develop the website and the intuition behind it.&lt;/p&gt;

&lt;p&gt;The reason behind the update can be attributed to the following reasons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the old design dated very fast and was not flexible at all&lt;/li&gt;
&lt;li&gt;I wanted to remove the dependency on &lt;a href=&quot;https://posterous.com/&quot;&gt;posterous&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;I wanted to write my content in markdown&lt;/li&gt;
&lt;li&gt;the performance of the was not what I desired ( &gt; 1 second load time)&lt;/li&gt;
&lt;li&gt;I wanted to add more semantic markup to help google index my content more effectively&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The first step in my update process was to get a new, professional looking design in place. The result is what you are currently looking at. Overall, I am happy with the redesign as I focused on removing the clutter from the screen and making the text readability better.&lt;/p&gt;

&lt;p&gt;The next step was too remove the dependency on &lt;a href=&quot;https://posterous.com/&quot;&gt;posterous&lt;/a&gt;. Whilst &lt;a href=&quot;https://posterous.com/&quot;&gt;posterous&lt;/a&gt; is a good platform for bloggers to get started with, the end result is horribly slow and the markup less than ideal. During my research, I found &lt;a href=&quot;http://pages.github.com/&quot; title=&quot;GitHub Pages&quot;&gt;GitHub Pages&lt;/a&gt;. &lt;a href=&quot;http://pages.github.com/&quot; title=&quot;GitHub Pages&quot;&gt;GitHub Pages&lt;/a&gt; uses the &lt;a href=&quot;https://github.com/mojombo/jekyll&quot; title=&quot;Jekyll&quot;&gt;Jekyll&lt;/a&gt; static site generator and is compatible with the markdown format. By only serving static pages the performance of my website is going to improve dramatically. It also gives me complete control over the urls with &lt;a href=&quot;https://github.com/mojombo/jekyll&quot; title=&quot;Jekyll&quot;&gt;Jekyll&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To further help improve performance I reduced the amount of images being loaded using a technique known as CSS sprites which I will cover in a future post. I also removed the JQuery dependency to reduce my technical debt and improve perceived performance. The tools that I used to help me redesign the site are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://cleancss.com/&quot; title=&quot;Clean CSS&quot;&gt;CleanCSS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://code52.org/DownmarkerWPF/&quot; title=&quot;Markpad Download&quot;&gt;Markpad&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://notepad-plus-plus.org/&quot; title=&quot;Notepad ++ Download&quot;&gt;Notepad++&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/&quot; title=&quot;GitHub&quot;&gt;GitHub&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.webpagetest.org/&quot; title=&quot;Web Page Tester&quot;&gt;WebPageTest&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;There is still a lot to do such as fixing the markup for older posts, updating google etc. I have plans to do some beginner posts to help people at my university get started with SQL so it is going to be a long process.&lt;/p&gt;

&lt;p&gt;As ever, any feedback is welcome regarding any of my work or my website.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Website Update</title>
      <link>http://sblackler.net/2012/11/18/Website-Update</link>
      <pubDate>Sun, 18 Nov 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/11/18/Website-Update</guid>
      <description>&lt;p&gt;Just a quick message for today. I am in the process of transferring all of my blog posts to a new system. Unfortunately, this takes quiet a bit of work converting the html to the markdown format. More on this soon and about the re-design itself.&lt;/p&gt;

&lt;p&gt;Keep coding!&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Tempdb Health Check Queries</title>
      <link>http://sblackler.net/2012/06/15/tempdb-health-check-queries</link>
      <pubDate>Fri, 15 Jun 2012 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/06/15/tempdb-health-check-queries</guid>
      <description>&lt;h2&gt;What is tempdb?&lt;/h2&gt;

&lt;p&gt;The tempdb system database is a global resource that has been used since
the inception of SQL Server. It is available to all SQL Server users
connected to the SQL Server instance. It holds many types of data and
can often be the source of a performance bottleneck.&lt;/p&gt;

&lt;p&gt;For example, tempdb can hold the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Temporary user objects that are explicitly created, such as: global
or local temporary tables, temporary stored procedures, table
variables, or cursors.&lt;/li&gt;
&lt;li&gt;Internal objects that are created by the SQL Server Database Engine,
for example, work tables to store intermediate results for spools or
sorting&lt;/li&gt;
&lt;li&gt;Row versions that are generated by data modification transactions in
a database that uses read-committed using row versioning isolation
or snapshot isolation transactions&lt;/li&gt;
&lt;li&gt;Row versions that are generated by data modification transactions
for features, such as: online index operations, Multiple Active
Result Sets (MARS), and AFTER triggers&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;So everytime that you do a
&lt;code&gt;SELECT col1, col2 INTO #temptable FROM table&lt;/code&gt; you are going to be using
tempdb. As you write more complex queries, your need for tempdb will
grow. When setup correctly, tempdb performance can be greatly improved
without touching your queries.&lt;/p&gt;

&lt;h2&gt;How do I know if tempdb has performance issues?&lt;/h2&gt;

&lt;p&gt;One way that we can see if tempdb is suffering, is by checking the wait
stats of the server and looking for high levels of &lt;code&gt;PAGELATCH&lt;/code&gt;. A latch
is a short-term synchronisation lock that is used by SQL Server to
maintain the integrity of the physical pages of data structures in
memory. Unlike locks, you are not able to influence the behaviour of
latches as SQL Server manages this for us.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://sqlserverperformance.wordpress.com/&quot;&gt;Glenn Berry&lt;/a&gt; has created a
wonderful diagnostic script which is available from
&lt;a href=&quot;http://dl.dropbox.com/u/13748067/SQL%20Server%202008%20Diagnostic%20Information%20Queries%20(June%202012&quot;&gt;here&lt;/a&gt;.sql).
I have taken his wait stat query and modified it slightly so that the
column names and general formatting are more readable.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;WITH Waits AS
        (
                SELECT        wait_type                                                AS &#39;Wait_type&#39;
                ,        wait_time_ms / 1000.0                                        AS &#39;Wait_time_seconds&#39;
                ,        100.0 * wait_time_ms / SUM(wait_time_ms) OVER()                AS &#39;Percent_of_results&#39;
                ,        ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC)                AS &#39;Row_number&#39;
                FROM        sys.dm_os_wait_stats WITH (NOLOCK)
                WHERE        wait_type NOT IN (&#39;CLR_SEMAPHORE&#39;,&#39;LAZYWRITER_SLEEP&#39;,&#39;RESOURCE_QUEUE&#39;,&#39;SLEEP_TASK&#39;,&#39;SLEEP_SYSTEMTASK&#39;,&#39;SQLTRACE_BUFFER_FLUSH&#39;,&#39;WAITFOR&#39;, &#39;LOGMGR_QUEUE&#39;,&#39;CHECKPOINT_QUEUE&#39;,&#39;REQUEST_FOR_DEADLOCK_SEARCH&#39;,&#39;XE_TIMER_EVENT&#39;,&#39;BROKER_TO_FLUSH&#39;,&#39;BROKER_TASK_STOP&#39;,&#39;CLR_MANUAL_EVENT&#39;,&#39;CLR_AUTO_EVENT&#39;,&#39;DISPATCHER_QUEUE_SEMAPHORE&#39;, &#39;FT_IFTS_SCHEDULER_IDLE_WAIT&#39;,&#39;XE_DISPATCHER_WAIT&#39;, &#39;XE_DISPATCHER_JOIN&#39;, &#39;SQLTRACE_INCREMENTAL_FLUSH_SLEEP&#39;,&#39;ONDEMAND_TASK_QUEUE&#39;, &#39;BROKER_EVENTHANDLER&#39;, &#39;SLEEP_BPOOL_FLUSH&#39;)
        )
        SELECT                W1.wait_type                                                AS &#39;Wait_Type&#39;
        ,                CAST(W1.Wait_time_seconds AS DECIMAL(12, 2))                AS &#39;Wait_time_seconds&#39;
        ,                CAST(W1.Percent_of_results AS DECIMAL(12, 2))                AS &#39;Percent_of_results&#39;
        ,                CAST(SUM(W2.Percent_of_results) AS DECIMAL(12, 2))        AS &#39;Running_percentage&#39;
        FROM                Waits AS W1
        INNER JOIN        Waits AS W2 ON W2.[Row_number] &amp;lt;= W1.[Row_number]
        GROUP BY        W1.[Row_number], W1.wait_type, W1.wait_time_seconds, W1.Percent_of_results
        HAVING                SUM(W2.percent_of_results) - W1.Percent_of_results &amp;lt; 99 
        OPTION (RECOMPILE);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;The modified version of this query is available from here: &lt;a href=&quot;http://dl.sblackler.net/sql/diag/wait_stats.sql&quot;&gt;Wait Stats
Diagnostic Query Inlcuding BOL
explainations&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;When we run this query in SSMS, we would expect to see rising levels of
&lt;code&gt;PAGELATCH_UP&lt;/code&gt;, &lt;code&gt;PAGELATCH_EX&lt;/code&gt; and &lt;code&gt;PAGELATCH_SH&lt;/code&gt;. Note for this query,
I have not choosen to filter just by latches as this gives us a greater
oversight as what is going on in our servers. As a general rule of
thumb, if you do not see pagelatches in the top 3 of the results window,
then I would not worry yet. Instead, watch for a trend.&lt;/p&gt;

&lt;p&gt;Another way we can tell whether or not tempdb is becoming a problem, is
by looking at the virtual file statistics through this query:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT                DB_NAME(database_id)                                                        AS &#39;Database_Name&#39;
        ,                CASE WHEN file_id = 2 THEN &#39;Log&#39; ELSE &#39;Data&#39; END                        AS &#39;File_Type&#39;
        ,                ((size_on_disk_bytes/1024)/1024.0)                                        AS &#39;Size_On_Disk_in_MB&#39;
        ,                io_stall_read_ms / num_of_reads                                                AS &#39;Avg_Read_Transfer_in_Ms&#39;
        ,                CASE WHEN file_id = 2 THEN
                                CASE 
                                        WHEN io_stall_read_ms / num_of_reads &amp;lt; 5 THEN
                                                &#39;Good&#39;
                                        WHEN io_stall_read_ms / num_of_reads &amp;lt; 15 THEN 
                                                &#39;Acceptable&#39;
                                        ELSE 
                                                &#39;Unacceptable&#39;
                                END
                        ELSE
                                CASE 
                                        WHEN io_stall_read_ms / num_of_reads &amp;lt; 10 THEN
                                                &#39;Good&#39;
                                        WHEN io_stall_read_ms / num_of_reads &amp;lt; 20 THEN 
                                                &#39;Acceptable&#39;
                                        ELSE 
                                                &#39;Unacceptable&#39;
                                END                                                                                        
                        END                                                                        AS &#39;Average_Read_Performance&#39;
        ,                io_stall_write_ms / num_of_writes                                        AS &#39;Avg_Write_Transfer_in_Ms&#39;
        ,                CASE WHEN file_id = 2 THEN
                                CASE 
                                        WHEN io_stall_write_ms / num_of_writes &amp;lt; 5 THEN
                                                &#39;Good&#39;
                                        WHEN io_stall_write_ms / num_of_writes &amp;lt; 15 THEN 
                                                &#39;Acceptable&#39;
                                        ELSE 
                                                &#39;Unacceptable&#39;
                                END
                        ELSE
                                CASE 
                                        WHEN io_stall_write_ms / num_of_writes &amp;lt; 10 THEN
                                                &#39;Good&#39;
                                        WHEN io_stall_write_ms / num_of_writes &amp;lt; 20 THEN 
                                                &#39;Acceptable&#39;
                                        ELSE 
                                                &#39;Unacceptable&#39;
                                END                                                                                        
                        END                                                                        AS &#39;Average_Write_Performance&#39;
        FROM                sys.dm_io_virtual_file_stats(null,null) 
        WHERE                num_of_reads &amp;gt; 0 AND num_of_writes &amp;gt; 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This query inspects the &lt;code&gt;sys.dm_io_virtual_file_stats&lt;/code&gt; DMV and gives you
a quickview of IO subsystem performance. I have offset this against
Microsoft&#39;s recommendations for IO performance. Obviously, this all
depends on the subsystem you are running. If your running on SATA disks,
your performance isn&#39;t going to be as good as if you were running on
RAID&#39;d SAS disks. It&#39;s all about monitoring and data analysis. I have
included Microsoft&#39;s recommendations in the downloadable script located
&lt;a href=&quot;http://dl.sblackler.net/sql/diag/virtual_file_stats.sql&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;How many files should I create for temp db?&lt;/h2&gt;

&lt;p&gt;First of all, I would say that unless you have identified a performance
problem then you can actually cause more harm than good (with disk
contention etc). Assuming that you have a valid reason for creating more
than one tempdb file, Microsoft recommend that you have 1/4 or 1/2 files
to number of cores on your system, upto a maximum of 8. Microsoft&#39;s
internal research has showed that there is no performance gain from
having more than 8 tempdb files.&lt;/p&gt;

&lt;p&gt;For example, if you have an 8 core machine, you should have either 2 or
4 tempdb files.&lt;/p&gt;

&lt;h2&gt;How do I add an extra file to tempdb?&lt;/h2&gt;

&lt;pre&gt;&lt;code&gt;ALTER DATABASE tempdb
        ADD FILE
        (
                name = tempdb_secondary,
                filename = &#39;C:\databases\tempdb_secondary.ndf&#39;,
                size = 512 MB
        )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You will notice that I have set the size parameter in all of the
commands that I have shown above and consistantly set them to the same
size. The reasoning behind this is that by default, the main tempdb file
will get created at roughly 8mb (on my system) with an autogrowth of
10%. Setting the size prevents alot of unnecssary autogrowth from
happening.&lt;/p&gt;

&lt;p&gt;Admittidley, I don&#39;t know the best way of setting the autogrowth
property for tempdb. For this reason, I have asked the question on
Stackexchange - Database Administrators, located
&lt;a href=&quot;http://dba.stackexchange.com/questions/20914/tempdb-autogrowth-settings&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;How do I move tempdb?&lt;/h2&gt;

&lt;p&gt;Another common mis-configuration, is to leave tempdb in it&#39;s default
place. Luckily, this situation can be rectified by running the following
code and amending the size and file location properties to suit your
environment:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ALTER DATABASE tempdb
        MODIFY FILE
        (
                name = tempdev,
                filename = &#39;C:\databases\tempdb.mdf&#39;,
                size = 512 MB
        )

GO
2        
    ALTER DATABASE tempdb
        MODIFY FILE
        (
                name = templog,
                filename = &#39;C:\databases\tempdblog.ldf&#39;,
                size = 512 MB
        )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;Running this code will require a restart of the SQL Server
service. Please bare this in mind before running on any production
servers. Aim to run in a maintainence Window.&lt;/p&gt;

&lt;p&gt;Always be careful before modifying the tempdb files if you think you
have a problem. Use tools such as ostress to record and repeat your
workload in a test environment to see if performance can be improved via
configuration changes.&lt;/p&gt;

&lt;p&gt;Hopefully this will help someone else out as it did me, cheers.&lt;/p&gt;

&lt;h2&gt;References&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://sqlserverperformance.wordpress.com/&quot;&gt;Glenn Berry&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb522469.aspx&quot;&gt;ALTER DATABASE
(MSDN)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms190768.aspx&quot;&gt;Tempdb
(MSDN)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>SQL SERVER Fix - Token-based server access validation failed with an infrastructure error</title>
      <link>http://sblackler.net/2012/05/30/sql-server-fix-token-based-server-access-validation</link>
      <pubDate>Wed, 30 May 2012 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/05/30/sql-server-fix-token-based-server-access-validation</guid>
      <description>&lt;p&gt;This is an error that I have recieved numerous times in the past two
weeks. It is reported to the .Net Framework as &lt;em&gt;&quot;Login Failed for user
DOMAIN\USER&quot;&lt;/em&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Date                27/05/2012 15:37:05
Log                SQL Server (Current - 30/05/2012 11:15:00)

Source                Logon

Message
Login failed for user &#39;DOMAIN\USER&#39;. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors. [CLIENT: 192.168.0.0]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the previous error being, something similar to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Date                27/05/2012 15:37:05
Log                SQL Server (Current - 30/05/2012 11:15:00)

Source                Logon

Message
Error: 18456, Severity: 14, State: 11.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It seems this error message can have the following causes:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;NB:&lt;/strong&gt;This is not an exhustive list.&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The web suggest that UAC can cause this error. Try running the
application as an administrator and see if that fixes your issue.&lt;/li&gt;
&lt;li&gt;Another cause can be when a domain user is deleted from AD and
removed at the server level then re-created at in AD and SQL SERVER.
This causes a mis-match in the SID&#39;s at the database level and
throws the above error. Delete the user and re-add at the database
level to solve this.&lt;/li&gt;
&lt;li&gt;User is logging in as a local user that has the same name and
password as a domain user. Classic example: Administrator accounts.&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;If you know of any causes or resources that are associated with this
error, leave me a comment and i&#39;ll add it to the post.&lt;/p&gt;

&lt;p&gt;Hope this helps someone.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>SQL Server 2012 - Training and Update Kit Freebies</title>
      <link>http://sblackler.net/2012/05/22/sql-server-2012-training-update-kits-freebies</link>
      <pubDate>Tue, 22 May 2012 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/05/22/sql-server-2012-training-update-kits-freebies</guid>
      <description>&lt;p&gt;Just a quick post today to point out a two resources that I have found
today. These resources are based around SQL Server 2012 training and
upgrade plans. &lt;/p&gt;

&lt;p&gt;The first resource is the offical &lt;a href=&quot;http://www.microsoft.com/en-us/download/details.aspx?id=27721&quot; title=&quot;SQL Server 2012 Developer Training Kit&quot;&gt;SQL Server 2012 Developer Training
Kit&lt;/a&gt;.
This kit aims to teach you in the following areas:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduction to SQL Server 2012&lt;/li&gt;
&lt;li&gt;Introduction to SQL Server 2012 AlwaysOn&lt;/li&gt;
&lt;li&gt;Exploring and Managing SQL Server 2012 Database Engine Improvements&lt;/li&gt;
&lt;li&gt;SQL Server 2012 Database Server Programmability&lt;/li&gt;
&lt;li&gt;SQL Server 2012 Application Development&lt;/li&gt;
&lt;li&gt;SQL Server 2012 Enterprise Information Management&lt;/li&gt;
&lt;li&gt;Server 2012 Business Intelligence&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Combined with a few hands on labs including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SQL Server 2012 Database Engine&lt;/li&gt;
&lt;li&gt;Visual Studio 2010 and .NET 4.0&lt;/li&gt;
&lt;li&gt;SQL Server 2012 Enterprise Information Management&lt;/li&gt;
&lt;li&gt;SQL Server 2012 Business Intelligence&lt;/li&gt;
&lt;li&gt;Windows Azure and SQL Azure&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;I have installed this content but it is worth noting that one of the
dependancies is Sharepoint 2010. It&#39;s not essential as you can still
install the content. Click &lt;a href=&quot;http://www.microsoft.com/en-us/download/details.aspx?id=27721&quot; title=&quot;SQL Server 2012 Developer Training Kit&quot;&gt;this
link&lt;/a&gt; to
download the SQL Server 2012 Developer Training Kit.&lt;/p&gt;

&lt;p&gt;The other resource that I wanted to link you to today, is the &lt;a href=&quot;http://download.microsoft.com/download/9/5/3/9533501A-6F3E-4D03-A6A3-359AF6A79877/SQL_Server_2012_Upgrade_Technical_Reference_Guide_White_Paper.pdf&quot; title=&quot;SQL Server 2012 Upgrade Technical Whitepaper&quot;&gt;SQL
Server 2012 Upgrade Techincal Reference Guide White
Paper&lt;/a&gt;,
which can be dowloaded from
&lt;a href=&quot;http://download.microsoft.com/download/9/5/3/9533501A-6F3E-4D03-A6A3-359AF6A79877/SQL_Server_2012_Upgrade_Technical_Reference_Guide_White_Paper.pdf&quot; title=&quot;SQL Server 2012 Upgrade Technical Reference Whitepaper&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;This document takes you through the essential technical details for
planning and testing an upgrade of existing SQL Server 2005, 2008, and
2008 R2 instances to SQL Server 2012. You will be presented with best
practices for preparation, planning, pre- upgrade tasks, and
post-upgrade tasks. All the SQL Server components are covered, each in
its own chapter.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;Hopefully these resources will help you on your way to learning SQL
Server 2012.&lt;/p&gt;

&lt;p&gt;Cheers,&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Indexing SQL Server - Clustered Indexes</title>
      <link>http://sblackler.net/2012/04/06/indexing-sql-server-clustered-indexes</link>
      <pubDate>Fri, 06 Apr 2012 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/04/06/indexing-sql-server-clustered-indexes</guid>
      <description>&lt;p&gt;&lt;em&gt;For this post, I assume you have a basic understanding on how
&lt;a href=&quot;http://en.wikipedia.org/wiki/B-tree&quot;&gt;B-Tree&lt;/a&gt; indexes work. If you don&#39;t
I suggest that your read &lt;a href=&quot;http://stackoverflow.com/a/1130/315711&quot;&gt;This Stackoverflow
Answer&lt;/a&gt; by &lt;a href=&quot;http://chris.beckett.io/&quot;&gt;Chris
Beckett&lt;/a&gt; and &lt;a href=&quot;http://www.bluerwhite.org/btree/&quot;&gt;This detailed explaination on
B-Tree&#39;s&lt;/a&gt; by &lt;a href=&quot;http://www.bluerwhite.org/&quot;&gt;Peter
Neubauer&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;Clustered vs Non-Clustered Indexes&lt;/h3&gt;

&lt;p&gt;In SQL Server, there are two main types of index, Clustered and
Non-Clustered. With a clustered index, rows are physically stored in the
same order of the index so there can only ever be 1 clustered index per
table. Non-clustered indexes, on the other hand, maintain a pointer to
the physical location of the row therefore you can have multiple
non-clustered indexes on a given table. It is worth noting that the more
indexes there are on a table, the slower your insert, updates and
deletes are going to be since SQL Server has to modify each index.&lt;/p&gt;

&lt;p&gt;By default, there are no indexes created when you create a table which
is known as a heap. This means SQL Server has to do a bunch of work to
find the data on disk, so it is considered a best practise to create a
clustered index on all of your tables, which also helps with the
following types of operations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Slower Backup/Restores&lt;/li&gt;
&lt;li&gt;Slower DBCC Commands&lt;/li&gt;
&lt;li&gt;Slower Fragmentation Checks&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&lt;a href=&quot;http://www.jasonstrate.com/&quot;&gt;Jason Strate&lt;/a&gt; has
built the following script to check your database for tables without
clustered indexes. Please take a moment to find out how many tables in
your database do not have a clustered index.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT SCHEMA_NAME(o.schema_id) AS [schema]
        ,object_name(i.object_id ) AS [table]
    ,p.rows
    ,user_seeks
    ,user_scans
    ,user_lookups
    ,user_updates
    ,last_user_seek
    ,last_user_scan
    ,last_user_lookup
FROM sys.indexes i 
        INNER JOIN sys.objects o ON i.object_id = o.object_id
    INNER JOIN sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
    LEFT OUTER JOIN sys.dm_db_index_usage_stats ius ON i.object_id = ius.object_id AND i.index_id = ius.index_id
WHERE i.type_desc = &#39;HEAP&#39;
ORDER BY rows desc
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A table that has a clustered index on it is called a Clustered Table.
Non-clustered indexes &lt;strong&gt;DO NOT&lt;/strong&gt; affect the base table&#39;s structure like
a clustered index does. However, Non-Clustered Indexes are affected by
whether or not the table is clustered. Clustered indexes have their
physical order applied at the time of creation and then maintains that
order until they are managed (rebuilt etc) through the use of linked
lists. The Clustered Index key impacts the width (and therefore
efficiency of) Non-Clustered Indexes.&lt;/p&gt;

&lt;h3&gt;Choosing the correct Clustered Index&lt;/h3&gt;

&lt;p&gt;When we are looking at which column to use as our clustering key, we
have to bare in mind that we add overhead to all of our Non-Clustered
Indexes. So if we use a GUID, we are going to add 16 bytes of data to
each row of our Non-Clustered Index. This in turn will bloat our cache
and reduce overall system performance. There are alot of things that we
can do to help SQL Server perform optimimally.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NB:&lt;/strong&gt; &lt;em&gt;These are not hard and fast rules, they are guidelines for your
data. I always recommend trying things out in a test environment to see
what is best for your data. The values I use are approximate, I&#39;ve not
accounted for paging etc.&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;Keep the clustering key unique&lt;/h4&gt;

&lt;p&gt;By keeping our clustering key unique, we are preventing SQL Server
adding a uniquifier to our data. This uniquifier is a 4 byte integer
that is added to every duplicate in our index which also gets added to
every row of our Non-Clustered Index. When SQL Server adds this
uniquifier to our row, it first has to scan the relevant part of the
clustered index for duplicates and before adding 1 accordingly. 4 Bytes
might not sound alot per row, but that is 3.85MB per million rows in
your Clustered Index and then another 3.85MB per million rows in each
Non-Clustered Index. One thing to bare in mind is that the clustered
index does not have to be the primary key. The primary key can be
Non-Clustered by specifiying the NONCLUSTERED keyword.&lt;/p&gt;

&lt;h4&gt;Make sure the data is static&lt;/h4&gt;

&lt;p&gt;For me, this has to be one of the main points when I am choosing a
clustering key. If the data is not static, then each time I update the
key, I have to update the Clustered Index and all subsequent
Non-Clustered Indexes before attending to the foreign keys (if any).
Including all the background tasks that SQL Server completes, such as
page splits, this is an extordinary amount of work that we are asking it
to do. All of which could be avoided if we have another suitable key.&lt;/p&gt;

&lt;h4&gt;Keep the column fixed-width and non-nullable&lt;/h4&gt;

&lt;p&gt;Like keeping the key unique, this recommendation is to reduce the amount
of overhead that we are giving to SQL Server. If the column is not fixed
width, then we have to store the length of the value along side the
value for every row and every Non-Clustered index. Again, this is a
small amount when you think in terms of rows, but when you think in
terms of the overall scheme of things, it actually is quiet a bit of
extra/non-neccessary work.&lt;/p&gt;

&lt;p&gt;It is a similar situation for nullable columns. So we can add an
additional 4/8/12/16 bytes of data per row depending on what we are
choosing to store. The main point is that it all adds up. It will vary
in every environment so I suggest that you test this out. I will go more
into the math of this in a later blog post.&lt;/p&gt;

&lt;h4&gt;Generally, GUID&#39;s are bad&lt;/h4&gt;

&lt;p&gt;One way to get almost 100% fragmentation in a very short amount of time
is to use GUID&#39;s as your clustering key. Although the values are unique,
so we don&#39;t need to add a uniquifier to each row, we are adding 16 bytes
to each row in every Non-Clustered Index. Generally, values are
generated using the .Net framework or via the NEWID() function in SQL.
This is the cause of such high index fragmentation. A solution to this,
in the case that you have to use GUID&#39;s, would be to use the
NEWSEQUENTIALID() function in SQL. This function will keep the values
sequential for the most part but will get reseeded when certain events
happen, like a time zone change.&lt;/p&gt;

&lt;p&gt;In defense of GUID&#39;s, they might actually improve performance when you
are running on SSD&#39;s. &lt;a href=&quot;http://sqlblogcasts.com/blogs/tonyrogerson/archive/2011/07/18/use-guid-s-uniqueidentifier-for-keys-when-storing-data-on-ssd-s-part-1-ssd-backgrounder.aspx&quot;&gt;Tony
Rogerson&lt;/a&gt;
has done a lot of research on this and I suggest reading his blog for
finding out more.&lt;/p&gt;

&lt;h4&gt;Composite keys can also be ok&lt;/h4&gt;

&lt;p&gt;In some cases, the use of composite keys can also be ok. For example,
when a non-null date field is combined with an identity field you have a
relatively narrow, static and fixed-width key that can out perform some
other variations. It has to be said that date alone is rarely unique, so
I suggest adding an identity column along side so that you maintain your
uniqueness.&lt;/p&gt;

&lt;h4&gt;Other things to consider&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;The wider the key, in terms of bytes, the bigger the size of all
your indexes will be. This will effect disk space/backup-restore
times etc&lt;/li&gt;
&lt;li&gt;An ever-increasing key, such as an identity column, reduces the
amount of fragmentation in the system as they are naturally
unique/static/narrow/non-null.&lt;/li&gt;
&lt;/ul&gt;


&lt;h3&gt;References&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://www.sql-server-performance.com/2004/index-data-structures/&quot;&gt;Index Data
Structures&lt;/a&gt;
by G. Vijayakumar&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.brentozar.com/archive/2012/02/webcast-recording-dba-darwin-awards-index-edition/&quot;&gt;DBA Darwin Awards - Index
Edition&lt;/a&gt;
by &lt;a href=&quot;http://www.brentozar.com&quot;&gt;Brent Ozar&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://technet.microsoft.com/en-us/sqlserver/gg508879.aspx&quot;&gt;The Clustered Index
Debate&lt;/a&gt;
by &lt;a href=&quot;http://www.sqlskills.com/BLOGS/KIMBERLY/&quot;&gt;Kimberly Trip&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>Reflection vs Caching</title>
      <link>http://sblackler.net/2012/03/29/reflection-vs-caching</link>
      <pubDate>Thu, 29 Mar 2012 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/03/29/reflection-vs-caching</guid>
      <description>&lt;p&gt;It&#39;s well known throughout the development community that reflection is
slow when it comes to simple tasks such as getting property information
from a class. Reflection&#39;s fine for the odd call but when you are
needing those same properties over and over again, it pays to reduce the
amount of calls you use it for. However, that said some calls are
actually designed to be quick:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LightWeight Functions&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;typeof
Object.GetType
typeof == Object.GetType
Type equivalence APIs (including typehandle operator overloads)
get_Module
get_MemberType
Some of the IsXX predicate APIs
New token/handle resolution APIs in the .NET Framework 2.0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Costly Functions&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;GetXX  APIs (MethodInfo, PropertyInfo, FieldInfo, and so on)
GetCustomAttributes
Type.InvokeMember
Invoke APIs (MethodInfo.Invoke, FieldInfo.GetValue, and so on)
get_Name (Name property)
Activator.CreateInstance
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The lightweight functions shown above are made so by the framework teams
as they are heavily used throughout the base class library (or BCL).
Some of the costlier functions include Type.GetProperties and
Type.GetCustomAttributes.&lt;/p&gt;

&lt;p&gt;Whilst looking for performance gains in a library that I am building, I
noticed that I was using a lot of reflection. Take a look at how the
code looked before I started to make the changes:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private static T CreateObject(IDataReader row) where T : new()
        {
            Dictionary exec;
            if (!propCache.TryGetValue(typeof(T), out exec))
            {
                CreatePropertyInformation(typeof(T));
                exec = propCache[typeof(T)];
            }
            T item = Activator.CreateInstance();
            foreach (var property in typeof(T).GetProperties())
            {
                exec[property.Name](item, row.GetValue(row.GetOrdinal(property.Name)));
            }
            return item;
        }
        private static void CreatePropertyInformation(Type _type)
        {
            // This is the store for the setting methods
            Dictionary exec = new Dictionary();
            foreach (var el in _type.GetProperties())
            {
                exec[el.Name] = CreateSetHandler(_type, el);
            }
            //set the cache
            propCache[_type] = exec;
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Every time that I am calling the &lt;em&gt;CreateObject&lt;/em&gt; method, I am making a
call to &lt;em&gt;GetProperties&lt;/em&gt; on the type. OUCH! To quickly reduce this pain
and increase performance by approximately 3.8 times (on my machine), I
implement a quick dictionary which would cache the property information
for the given type. Although I am no where near finished refactoring the
code yet, here is a later version of the same two functions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private static T CreateObject(IDataReader row) where T : new()
        {
            Dictionary exec;

            PropertyInfo[] props = null;

            if (!TypePropertySetterCache.TryGetValue(typeof(T), out exec))
            {
                CreatePropertyInformation(typeof(T), out props);
                exec = TypePropertySetterCache[typeof(T)];
            }

            // props is null if we already have the setter methods built
            if (props == null)
            {
                // create the property structure
                props = typeof(T).GetProperties();
                TypePropertyCache.Add(typeof(T), props);
            }

            T item = Activator.CreateInstance();

            foreach (var property in props)
            {
                exec[property.Name](item, row.GetValue(row.GetOrdinal(property.Name)));
            }

            return item;
        }
        private static void CreatePropertyInformation(Type _type, out PropertyInfo[] _props)
        {
            // This is the store for the setting methods
            Dictionary exec = new Dictionary();

            PropertyInfo[] props;

            if (!TypePropertyCache.TryGetValue(_type, out props))
            {
                props = _type.GetProperties();
                TypePropertyCache.Add(_type, props);
            }

            // return the local copy of props as this saves a call later on...
            _props = props;

            foreach (var el in props)
            {
                exec[el.Name] = CreateSetHandler(_type, el);
            }
            //set the cache
            TypePropertySetterCache[_type] = exec;
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see this is a vast improvement by reducing the number of
calls to &lt;em&gt;GetProperties&lt;/em&gt;which helps the performance no end. I am by no
means finished optimising the code above, there are numerous calls that
can be saved by designing the functions better. That said, I am still
amazed that scanning a dictionary everytime is faster than calling via
reflection (only tested with a small dictionary size at the moment). To
prove this, I wrote a small test which can be seen in the code below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static void Main(string[] args)
        {
            const Int32 runs = 1000;
            Stopwatch sw = Stopwatch.StartNew();

            for (int i = runs; i &amp;gt;= 0; i--)
            {
                FindPropertiesSlow(new { DateFrom = DateTime.Now, SayHello = &quot;Hello World&quot;, IntType = 1 });
            }
            sw.Stop();
            TimeSpan anonSlow = sw.Elapsed;
            Console.WriteLine(&quot;Anon Slow: &quot; + anonSlow.ToString());

            sw = Stopwatch.StartNew();
            for (int i = runs; i &amp;gt;= 0; i--)
            {
                FindPropertiesSlow(new TestingClass());
            }
            sw.Stop();
            TimeSpan slow = sw.Elapsed;
            Console.WriteLine(&quot;Typed Slow: &quot; + slow.ToString());

            sw = Stopwatch.StartNew();
            for (int i = runs; i &amp;gt;= 0; i--)
            {
                FindPropertiesFast(new { DateFrom = DateTime.Now, SayHello = &quot;Hello World&quot;, IntType = 1 });
            }
            sw.Stop();
            TimeSpan anonFast = sw.Elapsed;
            Console.WriteLine(&quot;Anon Fast: &quot; + anonFast.ToString());

            sw = Stopwatch.StartNew();
            for (int i = runs; i &amp;gt;= 0; i--)
            {
                FindPropertiesFast(new TestingClass());
            }
            sw.Stop();
            TimeSpan fast = sw.Elapsed;

            Console.WriteLine(&quot;Typed Fast: &quot; + fast.ToString());
            Console.ReadKey();
        }

        public static void FindPropertiesSlow(Object anon)
        {
            PropertyInfo[] props = anon.GetType().GetProperties();
        }

        private static Dictionary TypePropertyCache = new Dictionary();
        public static void FindPropertiesFast(Object anon)
        {
            if (!TypePropertyCache.ContainsKey(anon.GetType()))
            {
                TypePropertyCache.Add(anon.GetType(), anon.GetType().GetProperties());
            }
            else
            {
                PropertyInfo[] props = TypePropertyCache[anon.GetType()];
            }
        }


        public class TestingClass
        {
            public String Test { get; set; }
            public String Test2 { get; set; }
            public String Test3 { get; set; }
            public String Test4 { get; set; }
            public String Test5 { get; set; }
            public String Test6 { get; set; }

        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which yielded the following results on my machine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Anon Slow:  00:00:00.0085983
Typed Slow: 00:00:00.0011167  (Faster)

Anon Fast:  00:00:00.0080640
Typed Fast: 00:00:00.0003329  (Faster)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, even over 1000 interations, caching the data is a lot
quicker than calling with reflection everytime. What are your
experiences with reflection? Hopefully I will finish all the
optimisations this weekend and see how much time per call I can save
with my utilities library. Until next time ;)&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Resetting the Windows Search service to default using Powershell</title>
      <link>http://sblackler.net/2012/03/25/resetting-the-windows-search-service-to-default</link>
      <pubDate>Sun, 25 Mar 2012 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/03/25/resetting-the-windows-search-service-to-default</guid>
      <description>&lt;p&gt;Every now and then I like to try and improve the performance and
usability of my machines. My latest exploit has been to attempt to
improve the search to include a few custom locations into the indexes. I
accidently removed too much and it has left me with a broken search
facility. After a quick google, I found a website to reset the
service: &lt;a href=&quot;http://brandonlive.com/2007/04/20/faq-how-to-completely-reset-wds-windows-search/&quot;&gt;http://brandonlive.com/2007/04/20/faq-how-to-completely-reset-wds-windows-search/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I didn&#39;t want to have to go through the regedit way manually, so I
decided to use powershell (built into Windows 7. Start &gt; Accessories &gt;
Windows PowerShell &gt; Powershell (Run As Admin)). Here is the resulting
script&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# set the path so we don&#39;t have to type it again, this can be used to test if you want
$path = &quot;HKLM:\Software\Microsoft\Windows Search&quot;

# Reset the Windows Search Key
set-itemproperty -path $path -name &quot;SetupCompletedSuccessfully&quot; -value 0

# Restart the Windows Search
Restart-Service wsearch
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which can also be downloaded from the following
link: &lt;a href=&quot;http://dl.dropbox.com/u/12121071/powershell/Reset_Windows_Search.ps1&quot;&gt;http://dl.dropbox.com/u/12121071/powershell/Reset_Windows_Search.ps1&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hopefully this will get someone else out of the black hole that I was
also in :)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Update (25/03/12):&lt;/strong&gt;This will only reset the locations that Windows
Search will index, not fix anything else (That I am aware of)&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Quick SQL Server research notes</title>
      <link>http://sblackler.net/2012/03/08/quick-sql-server-research-notes</link>
      <pubDate>Thu, 08 Mar 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/03/08/quick-sql-server-research-notes</guid>
      <description>&lt;p&gt;Over the past week I have been researching into query plans and seeing
what useful information could be gained from them. Here is a small
collection of the noteworthy things that I have found. These are only
intended as notes, future posts may cover these notes in more depth.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dictionary Lookups&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Key lookups are often candidates for covering indexes&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;They always have a nested loop to combine the two results sets&lt;/li&gt;
&lt;li&gt;It is a lookup on a clustered index&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;RID Lookup is a bookmark lookup on the heap (no clustered index on the
table)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rebind and Rewinds&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Only applicable within a loop join; which are only...&lt;/li&gt;
&lt;li&gt;Called on the init method (which sets up the required data
structures) of some physical operators (Nonclustered Index
Spool,Remote Query,Row Count Spool,Sort,Table Spool,Table-Valued
Function)&lt;/li&gt;
&lt;li&gt;Rebinds occur when parameters change and the inner result set needs
to be re-evaluated&lt;/li&gt;
&lt;li&gt;Rewinds occur when parameters do not change and the inner result set
can be re-used&lt;/li&gt;
&lt;li&gt;Assert and Filter also cause rebind/re-winds but only when the
StartupExpression is set to TRUE. We cannot change this at all.&lt;/li&gt;
&lt;li&gt;Higher values for rebind/rewind indicates more disk IO&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>MVC 4.0: Bundling and Minification Bug</title>
      <link>http://sblackler.net/2012/03/08/mvc-40-bundling-minification-bug</link>
      <pubDate>Thu, 08 Mar 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/03/08/mvc-40-bundling-minification-bug</guid>
      <description>&lt;p&gt;My roots are firmly within WinForms applications in VB and C#. As part
of my learning this year I am trying to get up to date with the latest
technologies including the updates that framework 4 brings, MVC and side
projects like SignalR.&lt;/p&gt;

&lt;p&gt;To push my self completely outside of my comfort zone, I have decided to
install the MVC4 beta on my laptop and attempt to re-create the
university site &lt;a href=&quot;http://yougo.co.uk&quot; title=&quot;yougo.co.uk&quot;&gt;yougo.co.uk&lt;/a&gt;. This
website appears to be a classic .net 2.0/3.5 web forms website. I plan
to use the newer technologies such as SignalR to achieve this. I started
off by grabbing a copy of
&lt;a href=&quot;http://necolas.github.com/normalize.css/&quot; title=&quot;Normalise.css&quot;&gt;normalise.css&lt;/a&gt;
from &lt;a href=&quot;http://github.com&quot; title=&quot;Github&quot;&gt;Github&lt;/a&gt; and placing this in a seperate
file. I heard that you could easily bundle and minify javascript and css
files on the fly with MVC4 so I thought I would try it.&lt;/p&gt;

&lt;p&gt;In the head section of my _Layout.cshtml file I placed the following
line of code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;link href=&quot;@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl(&quot;~/Content/css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;According to the video I remembered watching a few days ago (located
here: &lt;a href=&quot;http://weblogs.asp.net/scottgu/archive/2012/02/19/asp-net-mvc-4-beta.aspx&quot;&gt;http://weblogs.asp.net/scottgu/archive/2012/02/19/asp-net-mvc-4-beta.aspx&lt;/a&gt;),
that should have been all that I needed to get things going. It did
bundle and minimize one of the files for me, but it didn&#39;t include the
other files. After a quick &lt;a href=&quot;http://google.co.uk&quot; title=&quot;Google&quot;&gt;google&lt;/a&gt; with
&lt;a href=&quot;http://bing.com&quot; title=&quot;Bing&quot;&gt;bing&lt;/a&gt;, I added the following line to my
Application_Start in the global.asax:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BundleTable.Bundles.EnableDefaultBundles();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which made the whole function look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;protected void Application_Start()
    {

        // Remove all other view engines except razor:
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        BundleTable.Bundles.RegisterTemplateBundles();
        BundleTable.Bundles.EnableDefaultBundles();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I thought that this should have solved the problem, but it still did not
work. After a quick question on stackoverflow, it became apparent that
someone else had already solved this problem. For some reason this line
of code is causing the problem:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BundleTable.Bundles.RegisterTemplateBundles();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Commenting this line out appears to have solved the problem. For me,
they should both work side by side as these are what I believe to be the
definitions of the functions themselves (I haven&#39;t double checked myself
yet. Source):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void RegisterTemplateBundles()
        {
            Bundle bundle = new Bundle(&quot;~/Scripts/js&quot;, new JsMinify());
            bool searchSubdirectories = false;
            bool throwIfNotExist = false;
            bundle.AddDirectory(&quot;~/Scripts&quot;, &quot;jquery-*&quot;, searchSubdirectories, throwIfNotExist);
            bool flag3 = false;
            bool flag4 = false;
            bundle.AddDirectory(&quot;~/Scripts&quot;, &quot;jquery.mobile*&quot;, flag3, flag4);
            bool flag5 = false;
            bool flag6 = false;
            bundle.AddDirectory(&quot;~/Scripts&quot;, &quot;jquery-ui*&quot;, flag5, flag6);
            bool flag7 = false;
            bool flag8 = false;
            bundle.AddDirectory(&quot;~/Scripts&quot;, &quot;jquery.unobtrusive*&quot;, flag7, flag8);
            bool flag9 = false;
            bool flag10 = false;
            bundle.AddDirectory(&quot;~/Scripts&quot;, &quot;jquery.validate*&quot;, flag9, flag10);
            bool flag11 = false;
            bundle.AddFile(&quot;~/Scripts/MicrosoftAjax.js&quot;, flag11);
            bool flag12 = false;
            bundle.AddFile(&quot;~/Scripts/MicrosoftMvc.js&quot;, flag12);
            bool flag13 = false;
            bool flag14 = false;
            bundle.AddDirectory(&quot;~/Scripts&quot;, &quot;modernizr*&quot;, flag13, flag14);
            bool flag15 = false;
            bundle.AddFile(&quot;~/Scripts/AjaxLogin.js&quot;, flag15);
            this.Add(bundle);
            Bundle bundle2 = new Bundle(&quot;~/Content/css&quot;, new CssMinify());
            bool flag16 = false;
            bundle2.AddFile(&quot;~/Content/site.css&quot;, flag16);
            bool flag17 = false;
            bool flag18 = false;
            bundle2.AddDirectory(&quot;~/Content/&quot;, &quot;jquery.mobile*&quot;, flag17, flag18);
            this.Add(bundle2);
            Bundle bundle3 = new Bundle(&quot;~/Content/themes/base/css&quot;, new CssMinify());
            bool flag19 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.core.css&quot;, flag19);
            bool flag20 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.resizable.css&quot;, flag20);
            bool flag21 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.selectable.css&quot;, flag21);
            bool flag22 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.accordion.css&quot;, flag22);
            bool flag23 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.autocomplete.css&quot;, flag23);
            bool flag24 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.button.css&quot;, flag24);
            bool flag25 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.dialog.css&quot;, flag25);
            bool flag26 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.slider.css&quot;, flag26);
            bool flag27 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.tabs.css&quot;, flag27);
            bool flag28 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.datepicker.css&quot;, flag28);
            bool flag29 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.progressbar.css&quot;, flag29);
            bool flag30 = false;
            bundle3.AddFile(&quot;~/Content/themes/base/jquery.ui.theme.css&quot;, flag30);
            this.Add(bundle3);
        }
        public void EnableDefaultBundles()
        {
            this.Add(new DynamicFolderBundle(&quot;js&quot;, JsMinify.Instance, &quot;*.js&quot;));
            this.Add(new DynamicFolderBundle(&quot;css&quot;, CssMinify.Instance, &quot;*.css&quot;));
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I guess that there must be something underlying in the MVC engine that
will not let you have a DynamicFolderBundle and a set of defined
bundles. To my eyes, there is nothing in the above code to stop this. I
think it&#39;s a bug in the framework and I will submit it to MSFT connect
at some stage.&lt;/p&gt;

&lt;p&gt;At the time of writing, there is no explanation on my stackoverflow
question. The question is located here:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://stackoverflow.com/questions/9624047/resolvebundleurl-not-resolving-all-files&quot;&gt;http://stackoverflow.com/questions/9624047/resolvebundleurl-not-resolving-all-files&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is a detailed walkthough of the
feature: &lt;a href=&quot;http://weblogs.asp.net/scottgu/archive/2011/11/27/new-bundling-and-minification-support-asp-net-4-5-series.aspx&quot;&gt;http://weblogs.asp.net/scottgu/archive/2011/11/27/new-bundling-and-minification-support-asp-net-4-5-series.aspx&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Introduction to Functional Programming</title>
      <link>http://sblackler.net/2012/02/18/introduction-to-functional-programming</link>
      <pubDate>Sat, 18 Feb 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/02/18/introduction-to-functional-programming</guid>
      <description>&lt;p&gt;As part of my new year&#39;s
goals,
I tasked myself with learning a functional language. The first
difficultly is deciding which programming I should learn. Would it be
Erlang? Clojure? or Haskell? My first thoughts are that I wanted to run
cross platform, which can be done by all 3 languages. My next aim was to
learn a programming language which could be run natively, i.e. without
any virtual machines. This immediately took Erlang and Clojure out of
the equation.&lt;/p&gt;

&lt;p&gt;This wasn&#39;t a problem for me per se, as I was leaning towards the way
Haskell promoted it self as a &quot;pure functional programming language&quot;. If
it&#39;s pure, it&#39;s got to be good right? One thing that is going to be an
enormous culture shock to me, is the different style of programming
compared to the object oriented approach that I have been using since I
began programming some 6 years ago. Whilst I am downloading the Haskell
compiler from haskell.org, it would be a good time to learn about the
principals of functional programming. What better place to start than
the &lt;a href=&quot;http://www.haskell.org/haskellwiki/Functional_programming&quot; title=&quot;Haskell Website&quot;&gt;Haskell
Website&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;1. Higher-order functions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Higher-order functions (HOFs) are functions that take other functions
as their arguments. A basic example of a HOF is map which takes a
function and a list as its arguments, applies the function to all
elements of the list, and returns the list of its results. For
instance, we can write a function that subtracts 2 from all elements
of a list without using loops or recursion:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;subtractTwoFromList l = map (\x -&amp;gt; x - 2) l
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can generalize this function to subtract any given number:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;subtractFromList l y = map (\x -&amp;gt; x - y) l
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The function given to map then becomes a closure because &lt;code&gt;\x -&amp;gt; x - y&lt;/code&gt;
references a local variable y from outside its body.&lt;/p&gt;

&lt;p&gt;Higher-order functions are very useful for refactoring code and reduce
the amount of repetition. For example, typically most for loops can be
expressed using maps or folds. Custom iteration schemes, such as
parallel loops, can be easily expressed using HOFs.&lt;/p&gt;

&lt;p&gt;Higher-order functions are often used to implement domain-specific
languages embedded in Haskell as combinator libraries.&lt;/p&gt;

&lt;p&gt;Higher-order functions can be usually simulated in object-oriented
languages by functions that take function-objects, also called
functors (note that functor in Haskell is an entirely different
concept). Variables from the scope of the call can be bound inside the
function-object which acts as if it were a closure. This way of
simulating HOFs is, however, very verbose and requires declaring a new
class each time we want to use a HOF.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Purity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some functional languages allow expressions to yield actions in
addition to return values. These actions are called side effects to
emphasize that the return value is the most important outcome of a
function (as opposed to the case in imperative programming). Languages
that prohibit side effects are called pure. Even though some
functional languages are impure they often contain a pure subset that
is also useful as a programming language. It is usually beneficial to
write a significant part of a functional program in a purely
functional fashion and keep the code involving state and I/O to the
minimum as impure code is more prone to errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.1 Immutable data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Purely functional programs typically operate on immutable data.
Instead of altering existing values, altered copies are created and
the original is preserved. Since the unchanged parts of the structure
cannot be modified, they can often be shared between the old and new
copies, which saves memory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.2 Referential transparency&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Pure computations yield the same value each time they are invoked.
This property is called referential transparency and makes possible to
conduct equational reasoning on the code. For instance if y = f x and
g = h y y then we should be able to replace the definition of g with
&lt;code&gt;g = h (f x) (f x)&lt;/code&gt; and get the same result; only the efficiency might
change.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.3 Lazy evaluation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since pure computations are referentially transparent they can be
performed at any time and still yield the same result. This makes it
possible to defer the computation of values until they are needed,
that is, to compute them lazily. Lazy evaluation avoids unnecessary
computations and allows, for example, infinite data structures to be
defined and used.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.4 Purity and effects&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Even though purely functional programming is very beneficial, the
programmer might want to use features that are not available in pure
programs, like efficient mutable arrays or convenient I/O. There are
two approaches to this problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.4.1 Side effects in the language&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some functional languages extend their purely functional core with
side effects. The programmer must be careful not to use impure
functions in places where only pure functions are expected.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.4.2 Side effects through monads&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Another way of introducing side effects to a pure language is to
simulate them using monads. While the language remains pure and
referentially transparent, monads can provide implicit state by
threading it inside them. The compiler does not even have to &#39;know&#39;
about the imperative features because the language itself remains
pure, however usually the implementations do &#39;know&#39; about them due to
the efficiency reasons, for instance to provide O(1) mutable arrays.&lt;/p&gt;

&lt;p&gt;Allowing side effects only through monads and keeping the language
pure makes it possible to have lazy evaluation that does not conflict
with the effects of impure code. Even though lazy expressions can be
evaluated in any order, the monad structure forces the effects to be
executed in the correct order.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Recursion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Recursion is heavily used in functional programming as it is the
canonical and often the only way to iterate. Functional language
implementations will often include tail call optimisation to ensure
that heavy recursion does not consume excessive memory.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;Got that? I haven&#39;t yet either. I have the feeling it will take me a
long time to get used to style change more than anything. About the only
thing I think I could equate it to is jogging for 6 years, then suddenly
changing to sprinting. It&#39;s not a massive change but one that will take
you a long time to get used to. According to a tweat from &lt;a href=&quot;http://twitter.com/mfeathers/status/29581296216&quot;&gt;Michael
Feathers&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;OO makes code understandable by encapsulating moving parts. &lt;/p&gt;

&lt;p&gt;FP makes code understandable by minimizing moving parts.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;This does make perfect sense, however, until I can sit down and play
with the code, I will not find out for my self. From what I have read,
and seen, across the internet, there seems to be a common consensus that
functional programming allows you to test easier and experiment with new
ideas faster. I believe this is because of the interactive consoles that
the languages come with, not the full blown IDE&#39;s of C# and VB.Net
(from which my roots stem). I have also noticed that the languages tend
to be much less verbose and a lot cleaner and easier to read. This could
be a personal preference or something that the language designers
intended. Either way, I like it.&lt;/p&gt;

&lt;p&gt;I am looking forward diving into the code and will post about what I
have learnt as I go along. I plan to look at things in this order:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The type system&lt;/li&gt;
&lt;li&gt;Methods/Functions/Classes&lt;/li&gt;
&lt;li&gt;Generics&lt;/li&gt;
&lt;li&gt;Design Patterns&lt;/li&gt;
&lt;li&gt;GUI Programming&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;Until next time, happy coding ;)&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Basic Programming in Haskell</title>
      <link>http://sblackler.net/2012/02/18/basic-programming-in-haskell</link>
      <pubDate>Sat, 18 Feb 2012 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2012/02/18/basic-programming-in-haskell</guid>
      <description>&lt;p&gt;After reading up on functional programming more since my brief
&lt;a href=&quot;http://sblackler.net/2012/02/18/introduction-to-functional-programming/&quot;&gt;introduction to functional
programming&lt;/a&gt;
last time, I have a fully configured Haskell environment ready to
develop in. I am now going to take a look how data types work in
Haskell, compared to other languages that I am used too.&lt;/p&gt;

&lt;h3&gt;Basic Haskell operators&lt;/h3&gt;

&lt;p&gt;As in every programming language, one of the first things that you
should know is the basic operators and what each of them mean. Without
these operators, you will not be able to progress to more advanced
programming.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Comments:&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;--                -- Start of comment line
{-                -- Start of short comment. /* in CSharp
-}                -- End of short comment. */ in CSharp
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Basic Mathmatics:&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;+                -- Add
-                 -- Subtract/negate
*                 -- Multiply
/                 -- Division
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Boolean Operators:&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;amp;&amp;amp;                 -- And
||                 -- Or
&amp;lt;                 -- Less-than
&amp;lt;=                 -- Less-than-or-equal
==                 -- Equal
/=                 -- Not-equal
&amp;gt;=                 -- Greater-than-or-equal
&amp;gt;                 -- Greater-than
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One thing to note before moving on is that the &lt;em&gt;not equal to&lt;/em&gt; is
different to every other programming language that I know. For example,
most languages write the same operator as &lt;code&gt;!=&lt;/code&gt;. The reason for Haskell
taking the path of &lt;code&gt;/=&lt;/code&gt; is that it is closer to the mathmatical &lt;code&gt;?&lt;/code&gt;
notation.&lt;/p&gt;

&lt;h3&gt;Working with Booleans&lt;/h3&gt;

&lt;p&gt;Booleans work in pretty much identical ways to most programming. True
and True is True, False and False is False etc. The only real difference
between Haskell and the likes of C# is the casing of the words &lt;code&gt;true&lt;/code&gt;
and &lt;code&gt;false&lt;/code&gt;. I first noticed this when trying it out in the GCHi
interpreter. If you try and use a boolean such as &lt;code&gt;true&lt;/code&gt; instead of
&lt;code&gt;True&lt;/code&gt;, you will recieve the following error:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;\&amp;lt;interactive&gt;:1:1: Not in scope: `true&#39;&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;However, when you use the correct casing, you should have the following
result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ghci True
        True
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Try the following examples in your Haskell interpreter and to see the
results for yourself:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;True &amp;amp;&amp;amp; True                -- True
False || False                 -- False
1 &amp;lt; 0                        -- False
0 &amp;lt;= 0                        -- True
1 == 1                        -- True
1 /= 0                        -- True
1 &amp;gt;= 2                        -- False
0 &amp;gt; 1                        -- False
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Working with Numbers&lt;/h3&gt;

&lt;p&gt;Working with numbers is, again, pretty much the same as working with
numbers in other programming languages such as C# or Python. One
addition to the language which I have not come across before is the
ability to write in the inflix notation. Infix notation is the common
arithmetic and logical formula notation, in which operators are written
infix-style between the operands they act on (e.g. 2 + 2). It is not as
simple to parse by computers as prefix notation ( e.g. + 2 2 ) or
postfix notation ( e.g. 2 2 + ), but many programming languages use it
due to its familiarity
(&lt;a href=&quot;http://en.wikipedia.org/wiki/Infix_notation&quot;&gt;Source&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;For example, the following are valid ways of expression 2 plus 2:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(+) 2 2                -- Inflix notation
2 + 2                -- Normal notation
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When using the normal notation, you generally do not have to use white
space, which means &lt;code&gt;2*2&lt;/code&gt; is valid Haskell code. One caveat with this
approach is that is does not work well with negative numbers. For
example, try the following in your interpreter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;2*-2                -- Invalid
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If all has gone well, so to speak, it would have produced an error
similar to the following:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;\&amp;lt;interactive&gt;:1:2: Not in scope: `*-&#39;&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;Fixing the error is as simple as adding parenthesis arround the negative
number, like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;2*(-2)                -- Valid, result is -4
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Working with Lists and Tuples&lt;/h3&gt;

&lt;p&gt;A list is simplely a collection/sequence of objects, much like a
shopping list. However, in Haskell, lists are homogeneous, meaning that
they are all of the same type. An example being that your list will only
contain strings or integers. A list is signified by &lt;code&gt;[]&lt;/code&gt; with the
elements inside of the brackets. To produce a list of integers between 1
and 10, try the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[1..10]                                -- Valid Input
[1,2,3,4,5,6,7,8,9,10]                -- Result
[1,2,&#39;a&#39;,3,&#39;b&#39;,&#39;c&#39;,4]                -- Example of Invalid Input
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To make a variable assignment we use the &lt;code&gt;let&lt;/code&gt; keyword. To store our
list of 10 integers in the variable test, we use the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let test = [1..10]                -- Store list in the variable test. Type test on the next line to see the value of test
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that we know how to store variables and generate a list, we can move
to performing operations on lists. I will show some common functions
that Haskell programmers use which includes concatination, min and max.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let test = [1..10]                -- Store a list in the variable test
let test2 = [1,3..20]                -- Store a &quot;odd numbers&quot; list in the variable test2
test ++ test2                        -- Concatinates the list with itself
test -- test2                        -- Reverses the operation above
maximum test                        -- Returns the maximum value in the list 
minimum test                        -- Returns the minimum value in the list
sum test                        -- Adds every element in the list together
test !! 2                        -- Returns the element that is 3rd in the list
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Like most programming languages, lists in Haskell are 0 based, meaning
that they start at index 0 and end at the length of the list minus 1.
Strings can also be declared by using a list of individual char&#39;s. The
complier converts this is to a readable string object for us. Later on
we will see how to inspect each item in the list.&lt;/p&gt;

&lt;p&gt;Tuples got their name as an abstraction of a sequence: single, double,
triple, quadruple, quintuple, sextuple, septuple, octuple, ..., n-tuple,
..., where the prefixes are taken from the Latin names of the numerals
(&lt;a href=&quot;http://en.wikipedia.org/wiki/Tuple&quot;&gt;Adapted from here&lt;/a&gt;). So in some
respects they are like lists, except that a Tuple does not have to have
the same type for every object, i.e. they are not homogeneous. However,
you need to know how many and of what type of objects you would like to
collate. To define a Tuple you use &lt;code&gt;()&lt;/code&gt; instead of &lt;code&gt;[]&lt;/code&gt; used in lists.
Take this as an example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let myTuple = (1,2,&quot;testing&quot;)         -- Creates a Tuple of 1,2,&quot;testing&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Although I haven&#39;t tried it, the same functions that we used for lists
above should work on Tuples too. I&#39;ll leave that as an exercise for you
dear reader.&lt;/p&gt;

&lt;h3&gt;Conditional Statements&lt;/h3&gt;

&lt;p&gt;Conditional statements are a fundemental part of any programming
language. They are typically in the form &lt;em&gt;if - then - else&lt;/em&gt;. One major
difference in Haskell is that since &lt;code&gt;if&lt;/code&gt; is an expression, it must
evaluate to a result, thus the &lt;code&gt;else&lt;/code&gt; is required. To replicate that in
Haskell, we use the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if &amp;lt;condition&amp;gt; then &amp;lt;true-value&amp;gt; else &amp;lt;false-value&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you need to split an if expression across multiple lines then you
should indent it like one of these:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if &amp;lt;condition&amp;gt;        
        then &amp;lt;true-value&amp;gt;
        else &amp;lt;false-value&amp;gt;
if &amp;lt;condition&amp;gt;
        then
                &amp;lt;true-value&amp;gt;
        else
                &amp;lt;false-value&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One note about the above code, is the identation on the second example.
You will likely get compiler errors if you do not have the correct
indentiation because of the same reason that the &lt;code&gt;else&lt;/code&gt; statement must
be included.&lt;/p&gt;

&lt;p&gt;In the .Net framework, we have the &lt;code&gt;Select/switch&lt;/code&gt; statement which is an
alternative to the &lt;em&gt;if - then - else&lt;/em&gt; sequence of code. This is
replicated in Haskell by using the following syntax:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;case &amp;lt;input&amp;gt; of
        &amp;lt;value 1&amp;gt; -&amp;gt; &amp;lt;result 1&amp;gt;
        &amp;lt;value 2&amp;gt; -&amp;gt; &amp;lt;result 2&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once filled out with a colour picker, for example, the resulting code
will look similar to the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;data Colour = Black | White | RGB Int Int Int

describeColour :: Colour -&amp;gt; String
describeColour c = 
                &quot;This colour is &quot;
                ++ case c of
                        Black           -&amp;gt; &quot;black&quot;
                        White           -&amp;gt; &quot;white&quot;
                        RGB 0 0 0       -&amp;gt; &quot;black&quot;
                        RGB 255 255 255 -&amp;gt; &quot;white&quot;
                                        -&amp;gt; &quot;freaky, man, sort of in between&quot;
                ++ &quot;, yeah?&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href=&quot;http://en.wikibooks.org/wiki/Haskell/Control_structures#Equations_and_Case_Expressions&quot;&gt;Code
Source&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hopefully that will give you enough to start experimenting in Haskell.
Until next time ;)&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Flicker Free Forms and ListViews in .Net</title>
      <link>http://sblackler.net/2011/12/30/flicker-free-forms-and-listview-in-net</link>
      <pubDate>Fri, 30 Dec 2011 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2011/12/30/flicker-free-forms-and-listview-in-net</guid>
      <description>&lt;p&gt;On a project I have been working on recently, I came across a problem
where under Windows an Mdi Child form would flicker when it loads.
Trying to find information on what was the cause of this was near
impossible. I ended up trying a lot of code snippets that I found when
googling the problem and this is what I have come up with.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Before I continue, I would like to stress that this worked in a very
specific circumstance and I accept no responsibility for your use of any
of this code.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next up, the code. Following this I shall explain, to the best of my
ability what the code does:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&#39;  VB
    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            cp.ExStyle = cp.ExStyle Or &amp;amp;H2000000
            Return cp
        End Get
    End Property
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Apparently there are two causes for the flicker that happens to a
Windows form. Until writing this post I did not know of the reasons why.
&lt;em&gt;&lt;a href=&quot;http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/aaed00ce-4bc9-424e-8c05-c30213171c2c/&quot;&gt;Source MSDN
Forums&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt;&lt;em&gt;Windows sends a control two messages when a control needs to be
painted. The first one (&lt;code&gt;WM_ERASEBKGND&lt;/code&gt;) causes the background to be
painted (&lt;code&gt;OnPaintBackground&lt;/code&gt;), the second causes the foreground to be
painted (&lt;code&gt;WM_PAINT&lt;/code&gt;, firing &lt;code&gt;OnPaint&lt;/code&gt;). Seeing the background drawn
first, then the foreground is noticeable when the drawing is slow.
Windows Forms has a ready solution for this kind of flicker with
ControlStyles.OptimizedDoubleBuffer.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt;&lt;em&gt;A form that has a lot of controls takes a long time to paint.
Especially the Button control in its default style is expensive. Once
you get over 50 controls, it starts getting noticeable. The Form class
paints its background first and leaves &quot;holes&quot; where the controls need
to go. Those holes are usually white, black when you use the &lt;code&gt;Opacity&lt;/code&gt;
or &lt;code&gt;TransparencyKey property&lt;/code&gt;. Then each control gets painted, filling
in the holes. The visual effect is ugly and there&#39;s no ready solution
for it in Windows Forms. &lt;code&gt;Double-buffering&lt;/code&gt; can&#39;t solve it as it only
works for a single control, not a composite set of controls.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;CreateParams&lt;/code&gt; property should only be overridden when wrapping an
existing Windows control or when you need to set the style of the
control. Microsoft recommend that you inherit the problem control and
then override the &lt;code&gt;CreateParams&lt;/code&gt;, not the way that I actually used it.&lt;/p&gt;

&lt;p&gt;I applied this at the top of every form in my code, ran the code under
Windows 7 (my development machine) and Windows XP (the target machine)
and everything appeared to render a lot better with the nasty double
flicker gone. All I know about the code above, is that it overrides the
styling of the controls and waits until the form is fully painted before
showing the form.&lt;/p&gt;

&lt;p&gt;It wasn&#39;t until further testing of the code that I discovered that the
original code caused an MDI child form to max out the CPU and hang the
application. I tried commenting out all of the code, removing any
background threads that were running (including timers etc) and as soon
as I enabled the code, it would hang the application again. This left me
and my colleagues very stumped for a few hours. After this period of
time, I bit the bullet and decided to uncomment every section of my code
until I could find the problem.&lt;/p&gt;

&lt;p&gt;Eventually I found the code above to be the problem, which worked fine
under Windows 7. So the solution was quiet easy, detect what version of
the operating system we are on and only apply the style if we are on
Vista or higher.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&#39;  VB
    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            Dim OSVer As Version = System.Environment.OSVersion.Version()
            Select Case OSVer.Major
                Case Is &amp;lt;= 5
                Case 5
                    If OSVer.Minor &amp;gt; 0 Then
                        cp.ExStyle = cp.ExStyle Or &amp;amp;H2000000
                    End If
                Case Is &amp;gt; 5
                    cp.ExStyle = cp.ExStyle Or &amp;amp;H2000000
                Case Else
            End Select
            Return cp
        End Get
    End Property
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So I had finally fixed the problem with the CPU usage. Deployed the
version for the client to test and everything was ok. By this time, I
had a massive headache and it wasn&#39;t quiet the end of the day. What a
better way to end the day but by ending off with another rending issue.
Although I had fixed the issue with the CPU, I had noticed that when you
moved the form, and loading the form in some cases, a list view in
details mode would not render correctly.&lt;/p&gt;

&lt;p&gt;After reading around about the issue, I have merged from a number of
source&#39;s to create a flicker free list view. To use the code, place the
class into your project, open up the target form&#39;s designer code (&lt;em&gt;You
will need to show all files in VS&lt;/em&gt;) and replace the instances of
&lt;code&gt;ListView&lt;/code&gt; with &lt;code&gt;FlickerFreeListView&lt;/code&gt;. Here is the code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Public Class FlickerFreeListView
    Inherits System.Windows.Forms.ListView

    Public Sub New()

        MyBase.New()

        Me.SetStyle(ControlStyles.Opaque, True)
        Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
        Me.SetStyle(ControlStyles.ResizeRedraw, True)
        Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        Me.SetStyle(ControlStyles.EnableNotifyMessage, True)

    End Sub

    Protected Overrides Sub OnNotifyMessage(ByVal m As Message)
        If (m.Msg &amp;lt;&amp;gt; &amp;amp;H14) Then
            MyBase.OnNotifyMessage(m)
        End If
    End Sub

End Class
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code basically blocks the background from being re-drawn every time
an item is added into the &lt;code&gt;ListView&lt;/code&gt; control. It also sets the
&lt;code&gt;OptimizedDoubleBuffer&lt;/code&gt; to help prevent any issues, amongst other
things.&lt;/p&gt;

&lt;p&gt;I hope that this will help someone have less of a headache that I had
when I was looking around for a solution to this problem. Feel free to
try it at your own risk and notify me in the comments if you have any
troubles.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Extension Methods In .Net</title>
      <link>http://sblackler.net/2011/12/01/extension-methods-in-net</link>
      <pubDate>Thu, 01 Dec 2011 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2011/12/01/extension-methods-in-net</guid>
      <description>&lt;p&gt;In this article we will take a look at what extension methods are and
how to use them in .Net. Personally, they are one of the best things
that has been introduced into the .Net framework in terms of
readability. I will take you through what extension methods are, how to
create them (in c# and vb) then I will show you some of the extension
methods that I have created (in c# only, conversion is for you to try).&lt;/p&gt;

&lt;h2&gt;Contents&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;What are extension methods?&lt;/li&gt;
&lt;li&gt;How do we create extension methods?&lt;/li&gt;
&lt;li&gt;Examples of extension methods&lt;/li&gt;
&lt;li&gt;Related Links&lt;/li&gt;
&lt;/ul&gt;


&lt;h3&gt;What are extension methods?&lt;/h3&gt;

&lt;p&gt;Extension methods allow you to easily extend a type, such as an integer
or string, without re-compiling or modifying the type. In essence, they
are a type of &lt;code&gt;static&lt;/code&gt; (&lt;code&gt;shared&lt;/code&gt; in vb) method, but they are called as
if the method is native to the type. Extension methods are available
from the 3.5 version of the .Net Framework and can be implemented on any
type in the .Net framework or any custom type that you define.&lt;/p&gt;

&lt;p&gt;One downside to extension methods is if that you create an extension
method with the same name as another method in that type, the compiler
will bind the method call to the native method not any extension. An
extension method is only called when there is no native method found.&lt;/p&gt;

&lt;h4&gt;Warning&lt;/h4&gt;

&lt;p&gt;If you declare an extension method on the type Object, you will
effectively create the extension method for every type in the framework
including but not limited to String, Integer and Lists.&lt;/p&gt;

&lt;h3&gt;How do we create extension methods?&lt;/h3&gt;

&lt;p&gt;The basic outline of a creating extension methods goes something like
this:&lt;/p&gt;

&lt;p&gt;​1. Create a public &lt;code&gt;static&lt;/code&gt; class (&lt;code&gt;module&lt;/code&gt; in vb) \
 2. Define functions that you wish to perform\
 3. Make the functions an extension method&lt;/p&gt;

&lt;p&gt;Following through a complete example, I will now demonstrate how to
create an extension method that returns the first 3 characters of a
string. Using the list above, I must first create a &lt;code&gt;static class&lt;/code&gt; or
&lt;code&gt;module&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// C#
    public static class Extensions
    {

    }

    &#39; VB
    Module Extenstions

    End Module
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The next phase would be to write the function that we are going need,
which in this case is the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// C#
    public static class Extensions
    {
        public string GetFirstThreeCharacters(String str)
        {
            if(str.Length &amp;lt; 3)
            {
                return str;
            }
            else
            {
                return str.Substring(0,3);
            }
        }
    }

    &#39; VB
    Module Extenstions

    Public Function GetFirstThreeCharacters(Byval str As String) As String
        If (str.Length &amp;lt; 3) Then
            return str
        Else
            return str.SubString(0,3)
        End If
    End Function

    End Module
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So far, we have done nothing special. In the last phase is to make the
functions extension methods. It is slightly more complicated in VB but
not by much. I will deal with C# first.&lt;/p&gt;

&lt;p&gt;To make our C# version of our function an extension method we need to
mark the function as static (so that it can be accessed at any time with
out the need for declaring anything) and secondly, marking the first
paramter with the &lt;code&gt;this&lt;/code&gt; keyword. This keyword basically tells the CLR
that when this extension method is called, to use &quot;this&quot; parameter as
the source. See the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static class Extensions
    {
        public static string GetFirstThreeCharacters(this String str)
        {
            if(str.Length &amp;lt; 3)
            {
                return str;
            }
            else
            {
                return str.Substring(0,3);
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now for the VB version. Instead of using the &lt;code&gt;this&lt;/code&gt; keyword, we need to
do something slightly different. We need to mark the function with the
&lt;code&gt;System.Runtime.CompilerServices.Extension&lt;/code&gt; attribute like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;System.Runtime.CompilerServices.Extension&amp;gt; _
    Public Function GetFirstThreeCharacters(Byval str As String) As String
        If str.Length &amp;lt; 3 Then
                Return str
        Else
                Return str.Substring(0, 3)
        End If
    End Function
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you copy this code into any project, you should be able to call it
like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// C#
    String str = &quot;my new String&quot;;
    str = str.GetFirstThreeCharacters();

    &#39; VB
    Dim str as String = &quot;my new String&quot;
    str = str.GetFirstThreeCharacters()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As I explained for both languages above, the effective use of the &lt;code&gt;this&lt;/code&gt;
keyword, makes the CLR take what ever we are calling the extension
method from as the first parameter to our function.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hint: Try adding an additional &lt;code&gt;Integer&lt;/code&gt; parameter and using that as a
replacement for the 0 in the code above.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;Examples of extension methods&lt;/h3&gt;

&lt;p&gt;Here are a few of the extensions that I have found or created over time.
These are helpful to me and I hope they are to you as well. If you have
a question about any of these, drop me a comment below.&lt;/p&gt;

&lt;h4&gt;HasElements&lt;/h4&gt;

&lt;p&gt;Something that I often do is check a collection for a value. This method
is designed to prevent me constantly checking for a null value and
existance of any item in a given collection. This method will work on
any collection that implents the &lt;code&gt;ICollection&lt;/code&gt; interface.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Definition:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
    /// Determines whether the specified collection has any elements in the sequence. This method also checks for a null collection.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;items&quot;&amp;gt;The ICollection of items to check.&amp;lt;/param&amp;gt;
    public static bool HasElements(this ICollection items)
    {
        return items != null &amp;amp;&amp;amp; items.Count &amp;gt; 0;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Example usage:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;List&amp;lt;String&amp;gt; myList = new List&amp;lt;String&amp;gt;();
    if (myList.HasElements())
    {
        // do some code
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;IsBetween&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;IsBetween&lt;/code&gt; method returns a boolean and determins whether or not a
value is between an inclusive upper and lower boundry. This will only
work on types that implement the &lt;code&gt;IComparable&lt;/code&gt; interface.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Definition:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
    /// Determins whether a value is between a minimum and maximum value.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;typeparam name=&quot;T&quot;&amp;gt;The type of the value parameter.&amp;lt;/typeparam&amp;gt;
    /// &amp;lt;param name=&quot;value&quot;&amp;gt;The value that needs to be checked.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;low&quot;&amp;gt;The inclusive lower boundry.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;high&quot;&amp;gt;The inclusive upper boundry.&amp;lt;/param&amp;gt;
    public static bool IsBetween&amp;lt;T&amp;gt;(this T value, T low, T high) where T : IComparable&amp;lt;T&amp;gt;
    {
        return value.CompareTo(low) &amp;gt;= 0 &amp;amp;&amp;amp; value.CompareTo(high) &amp;lt;= 0;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Example usage:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Int32 myInt = 0;
    myInt.IsBetween(0, 5); // returns true
    myInt.IsBetween(1, 5); // returns false
&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Each&lt;/h4&gt;

&lt;p&gt;Quite often I have to perform a task on a collection of items. This is
just a shortcut way for saying for each element in the collection,
perform this action. This will work on any collection that implements
the &lt;code&gt;ICollection&lt;/code&gt; interface. The action that is parsed in can be a
lambda expression or a function/subroutine.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Definition:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
    /// Executes the given action against the given ICollection instance.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;typeparam name=&quot;T&quot;&amp;gt;The type of the ICollection parameter.&amp;lt;/typeparam&amp;gt;
    /// &amp;lt;param name=&quot;items&quot;&amp;gt;The collection the action is performed against.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;action&quot;&amp;gt;The action that is performed on each item.&amp;lt;/param&amp;gt;
    public static void Each&amp;lt;T&amp;gt;(this ICollection&amp;lt;T&amp;gt; items, Action&amp;lt;T&amp;gt; action)
    {
        foreach (T item in items)
        {
            action(item);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Example usage:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;List&amp;lt;String&amp;gt; myList = new List&amp;lt;String&amp;gt;();
    myList.Each(el =&amp;gt; 
    {
        // perform an action(s) on the item
        el.Substring(0,1);
        el = el;
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;In&lt;/h4&gt;

&lt;p&gt;Often it is neccessary to determine whether a value is in a set
collection. For example, I need to check whether a string is in an
allowed list. This method will allows us to check any value against an
array of values of the same type.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Definition:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
    /// Determines whether a parameter is in a given list of parameters. Eg. 11.In(1,2,3) will return false.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;typeparam name=&quot;T&quot;&amp;gt;The type of the source parameter.&amp;lt;/typeparam&amp;gt;
    /// &amp;lt;param name=&quot;source&quot;&amp;gt;The item that needs to be checked.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;list&quot;&amp;gt;The list that will be checked for the given source.&amp;lt;/param&amp;gt;
    public static bool In&amp;lt;T&amp;gt;(this T source, params T[] list)
    {
        if (null == source) throw new ArgumentNullException(&quot;source&quot;);
        return list.Contains(source);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Example usage:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Int32 myInt = 0;
    myInt.In(0, 0, 1, 2, 3); // returns true
    myInt.In(1, 5, 6, 7, 8); // returns false
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hopefully, you now have an understanding of how to implement extension
methods in both C# and VB.Net. If you need any help with your extension
methods or you would like to ask a question, drop me a comment below.&lt;/p&gt;

&lt;h3&gt;Related Links&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb383977.aspx&quot;&gt;MSDN: Extension Methods (C# Programming
Guide)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.extensionmethod.net/&quot;&gt;Example of extension methods
(&lt;/a&gt;&lt;a href=&quot;http://www.extensionmethod.net/&quot;&gt;http://www.extensionmethod.net/)&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>Using XML in SQL Server 2008</title>
      <link>http://sblackler.net/2011/11/15/using-xml-in-sql-server-2008</link>
      <pubDate>Tue, 15 Nov 2011 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2011/11/15/using-xml-in-sql-server-2008</guid>
      <description>&lt;p&gt;Extensible Markup Language, or XML, is a w3 recommendation for the
transportation and storage of data with a focus on the data. XML allows
you to define your own tags, unlike HTML, allowing you to create a
myriad of data structures. Whilst the next few documents will focus on
pulling the data out of SQL Server, I will write a post showing how to
make the most of this from your client application.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;From this point on, I will assume you have a basic understanding of XML
and know a bit about XML schemas.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Contents&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Prerequisites&lt;/li&gt;
&lt;li&gt;The XML Data Type&lt;/li&gt;
&lt;li&gt;Creating an XML Schema Collection&lt;/li&gt;
&lt;li&gt;Working With XML Columns&lt;/li&gt;
&lt;li&gt;References/Futher Reading&lt;/li&gt;
&lt;/ul&gt;


&lt;h3&gt;Prerequisites&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;SQL Server 2008 Express (or greater, available
&lt;a href=&quot;http://www.microsoft.com/express/Database/&quot;&gt;here&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Adventure Works Database (available
&lt;a href=&quot;http://msftdbprodsamples.codeplex.com/releases/view/37109&quot;&gt;here&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;


&lt;h3&gt;The XML Data Type&lt;/h3&gt;

&lt;p&gt;Since SQL Server 2005, SQL Server has natively supported XML querying
and a specific data type for XML. The new XML data type can either be
typed which is bound to an XML Schema, or untyped. If you use the XML
data type without a schema then you may store fragments of XML or XML
documents. However, if you use the XML data type with a schema you can
only store XML documents.&lt;/p&gt;

&lt;p&gt;Internally, SQL Server stores the XML data type as &lt;code&gt;varbinary(max)&lt;/code&gt;,
which is a binary representation of an XML fragment or document. Because
of this, there is an inherit problem when using typed XML columns. If
the schema is changed then you must first change all columns referencing
the schema to use untyped XML. Then you must drop the schema before
creating a new one with the changes that you have made, before altering
all the columns back to the new XML schema.&lt;/p&gt;

&lt;h3&gt;Creating an XML Schema Collection&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;This section is a pre-cursor to the next section&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;An XML schema is needed to validate XML entered into a typed XML data
column. An XML schema can be created using the following syntax:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE XML SCHEMA COLLECTION &amp;lt;insert schema name&amp;gt; AS &amp;lt;XML Schema&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this article, I will use example XML documents based around an
article with multiple attributes: Author, Title and rating. From the
example you see below, I have prepared an XML schema based upon my
documents.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE XML SCHEMA COLLECTION CodeProjectSchemaCollection

AS

N&#39;&amp;lt;?xml version=&quot;1.0&quot;?&amp;gt;

 &amp;lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;

 targetNamespace=&quot;http://samplewebsite.com/CodeProjectSchema&quot;

 xmlns=&quot;http://samplewebsite.com/CodeProjectSchema&quot;

 elementFormDefault=&quot;qualified&quot;&amp;gt;

 &amp;lt;xs:element name=&quot;Article&quot;&amp;gt;

 &amp;lt;xs:complexType&amp;gt;

 &amp;lt;xs:attribute name=&quot;Author&quot; type=&quot;xs:string&quot; /&amp;gt;

 &amp;lt;xs:attribute name=&quot;Title&quot; type=&quot;xs:string&quot; /&amp;gt;

 &amp;lt;xs:attribute name=&quot;Rating&quot; type=&quot;xs:decimal&quot; /&amp;gt;

 &amp;lt;/xs:complexType&amp;gt;

 &amp;lt;/xs:element&amp;gt;

 &amp;lt;/xs:schema&amp;gt;

&#39;;

GO
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To create the schema in SQL Server, I give this schema collection a
name, &quot;CodeProjectSchemaCollection&quot;, and place my schema with single
quotes. SQL Server will validate the schema that you place in between
the quotes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;em&gt;I found when writing this article that there must be no spaces
between the first quote and the start of the document. If you put a
space, you will recieve the following error:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Msg 9438, Level 16, State 1, Line 1

XML parsing: line 1, character 7, text/xmldecl not at the beginning of input
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the next section I will show you how to use the newly created schema
collection.&lt;/p&gt;

&lt;h3&gt;Working With XML Columns&lt;/h3&gt;

&lt;p&gt;There are three ways in which you can use the new XML data type within a
table. The first is to have it store any XML fragment or document
without being bound to a schema definition, or untyped XML. The next is
to have an XML fragment or document bound to a schema, or typed XML. The
last is to only have an XML document in the XML column.&lt;/p&gt;

&lt;h4&gt;Untyped Example&lt;/h4&gt;

&lt;p&gt;To create a new XML column, we specify the data type as XML. Simple :)&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE TABLE TestXMLTable

(

 [xml_ID] INT IDENTITY PRIMARY KEY,

 [xml_Name] NVARCHAR(50) NOT NULL,

 [xml_Data] XML NULL

)
&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Schema bound, document or fragment example&lt;/h4&gt;

&lt;p&gt;If we want our XML column to allow document&#39;s or fragments of XML, then,
in brackets, we specify the &lt;code&gt;XMLSchemaCollection&lt;/code&gt; that we created
earlier on in this article.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The change has been highlighted in italics&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE TABLE TestXMLTable2

(

 [xml_ID] INT IDENTITY PRIMARY KEY,

 [xml_Name] NVARCHAR(50) NOT NULL,

 [xml_Data] XML(CodeProjectSchemaCollection) NULL

)
&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Schema bound, document only example&lt;/h4&gt;

&lt;p&gt;Adding the document option to the declaration forces SQL Server to only
allow XML documents. It is worth noting at this point, that if you want
to change the schema, there is a fair bit of work the SQL Server has to
do. This is covered in a later section.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The change has been highlighted in italics&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE TABLE TestXMLTable3

(

 [xml_ID] INT IDENTITY PRIMARY KEY,

 [xml_Name] NVARCHAR(50) NOT NULL,

 [xml_Data] XML(DOCUMENT CodeProjectSchemaCollection) NULL

)
&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Inserting XML Data&lt;/h4&gt;

&lt;p&gt;Here is an example of inserting some XML data into the columns.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;INSERT INTO [AdventureWorks].[dbo].[TestXMLTable]

           ([xml_Name]

           ,[xml_Data])

     VALUES

           (&#39;Test 1&#39;,

           &#39;&amp;lt;?xml version=&quot;1.0&quot;?&amp;gt;

&amp;lt;Article xmlns=&quot;http://samplewebsite.com/CodeProjectSchema&quot; Author=&quot;Me&quot; Title=&quot;XMLPost1&quot; Rating=&quot;0.1&quot; /&amp;gt;&#39;)

GO
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What happens if I try and insert invalid XML to a schema bound column
like the following example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;INSERT INTO [AdventureWorks].[dbo].[TestXMLTable3]

           ([xml_Name]

           ,[xml_Data])

     VALUES

           (&#39;Test 2&#39;,

           &#39;&amp;lt;Article xmlns=&quot;http://samplewebsite.com/CodeProjectSchema&quot; Author=&quot;Me&quot; Title=&quot;XMLPost1&quot; Rating=&quot;Zero&quot; /&amp;gt;&#39;)

GO
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Well, the result is that you get a lovely SQL error and the XML data
fails to insert. Using the example above, you should get the following
error showing you where the error has occured and why it has occurred.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Msg 6926, Level 16, State 1, Line 1

XML Validation: Invalid simple type value: &#39;Zero&#39;. Location: /*:Article[1]/@*:Rating
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hopefully you now have a good idea of how XML schemas and the XML data
type works in SQL Server 2008+. In the next article, I will demonstrate
how to query XML data columns.&lt;/p&gt;

&lt;h3&gt;References/Futher Reading&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://www.w3schools.com/xml/xml_whatis.asp&quot;&gt;W3Schools - What is
XML&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms345117(v=sql.90&quot;&gt;XML Support in SQL Server
2005&lt;/a&gt;.aspx)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms176009.aspx&quot;&gt;(MSDN) Creating an XML
Schema&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>Asynchronous File IO in .Net</title>
      <link>http://sblackler.net/2011/11/12/Asynchronous-File-IO-In-Dot-Net</link>
      <pubDate>Sat, 12 Nov 2011 00:00:00 -0800</pubDate>
      <author>Author</author>
      <guid>http://domain/2011/11/12/Asynchronous-File-IO-In-Dot-Net</guid>
      <description>&lt;p&gt;In todays article I am going to go through how to make a re-usable and asynchrous class for file operations in the .Net platform. I will cover how the &lt;code&gt;FileStream&lt;/code&gt; works and why it actually executes synchronously unless you specify a certain flag. As this is part of my utilities library, this article will only be in C#.&lt;/p&gt;

&lt;h3&gt;Contents&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#fileStream&quot;&gt;The File Stream Class&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#reads&quot;&gt;Asynchronous Reads&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#writes&quot;&gt;Asynchronous Writes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#appends&quot;&gt;Asynchronous Appends&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#related&quot;&gt;Related Links&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;h3&gt;Source Code&lt;/h3&gt;

&lt;p&gt;The source code for this article is located &lt;a href=&quot;http://pastebin.com/GDGNT7u5&quot;&gt;here (clicky).&lt;/a&gt;&lt;/p&gt;


&lt;h3&gt;&lt;a name=&quot;fileStream&quot;&gt;The File Stream Class&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;Living in the &lt;code&gt;System.IO&lt;/code&gt; namespace, the &lt;code&gt;FileStream&lt;/code&gt; class provides both synchronous and asynchronous methods to perform various tasks on the file system such as read, write and security operations. In this article I will not cover how to implement the security side of the &lt;code&gt;FileStream&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;FileStream&lt;/code&gt; class has numerous constructors, most of which we do not need for this article. There are a few constructors that are marked as &lt;strong&gt;Obsolete&lt;/strong&gt; in the MSDN documentation. Here is a complete list of all the constructors from MSDN:&lt;/p&gt;

&lt;table class=&quot;newspaper&quot;&gt;

&lt;tbody&gt;&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms143395.aspx&quot;&gt;FileStream(IntPtr, FileAccess)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Obsolete. &lt;/strong&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class for the specified file handle, with the specified read/write permission.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/b6fz1x84.aspx&quot;&gt;FileStream(SafeFileHandle, FileAccess)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class for the specified file handle, with the specified read/write permission. &lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/47ek66wy.aspx&quot;&gt;FileStream(String, FileMode)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path and creation mode.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/xkd9t9eh.aspx&quot;&gt;FileStream(IntPtr, FileAccess, Boolean)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Obsolete. &lt;/strong&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class for the specified file handle, with the specified read/write permission and &lt;span&gt;&lt;span class=&quot;input&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; instance ownership.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/33b50d8h.aspx&quot;&gt;FileStream(SafeFileHandle, FileAccess, Int32)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class for the specified file handle, with the specified read/write permission, and buffer size.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/tyhc0kft.aspx&quot;&gt;FileStream(String, FileMode, FileAccess)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path, creation mode, and read/write permission.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/w4z40ebc.aspx&quot;&gt;FileStream(IntPtr, FileAccess, Boolean, Int32)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Obsolete. &lt;/strong&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class for the specified file handle, with the specified read/write permission, &lt;span&gt;&lt;span class=&quot;input&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; instance ownership, and buffer size.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/5h0z48dh.aspx&quot;&gt;FileStream(String, FileMode, FileAccess, FileShare)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path, creation mode, read/write permission, and sharing permission.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/0x1a0k7t.aspx&quot;&gt;FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Obsolete. &lt;/strong&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class for the specified file handle, with the specified read/write permission, &lt;span&gt;&lt;span class=&quot;input&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; instance ownership, buffer size, and synchronous or asynchronous state.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/f20d7x6t.aspx&quot;&gt;FileStream(String, FileMode, FileAccess, FileShare, Int32)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path, creation mode, read/write and sharing permission, and buffer size.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/sz7bz1s4.aspx&quot;&gt;FileStream(SafeFileHandle, FileAccess, Int32, Boolean)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/d0y914c5.aspx&quot;&gt;FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms143396.aspx&quot;&gt;FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms143397.aspx&quot;&gt;FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;/tbody&gt;&lt;/table&gt;


&lt;p&gt;Now I have purposely left the one we are going to use out as I think it deserves a bit more discussion before continuing.&lt;/p&gt;


&lt;table class=&quot;newspaper&quot;&gt;

&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/7db28s3c.aspx&quot;&gt;FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Initializes a new instance of the &lt;span&gt;&lt;span class=&quot;selflink&quot;&gt;FileStream&lt;/span&gt;&lt;/span&gt; class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;/tbody&gt;&lt;/table&gt;


&lt;p&gt;Out of the three constructors that allow you to set an asynchronous state, one of them is marked as obsolete so we should not use that one whilst the other constructor does not allow us to specify a &lt;code&gt;FileMode&lt;/code&gt; that we wish to use. Not only are we interested in the &lt;code&gt;FileMode&lt;/code&gt; we are also interested in the last parameter of the constructor, the &lt;code&gt;boolean&lt;/code&gt;. This &lt;code&gt;boolean&lt;/code&gt; tells the CLR to execute the request synchronously when &lt;code&gt;False&lt;/code&gt; and asynchronously when &lt;code&gt;True&lt;/code&gt;. &lt;a href=&quot;http://www.danielfortunov.com/software/$daniel_fortunovs_adventures_in_software_development/2010/05/10/asynchronous_file_io_in_net&quot;&gt;Daniel Fortunov&lt;/a&gt; explains this behaviour in his blog post.&lt;/p&gt;

&lt;h3&gt;&lt;a name=&quot;reads&quot;&gt;Asynchronous Reads&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;First of all, I need to define how our implementation method is going to look. Since we know that the constructor takes the following parameters &lt;code&gt;String&lt;/code&gt;, &lt;code&gt;FileMode&lt;/code&gt;, &lt;code&gt;FileAccess&lt;/code&gt;, &lt;code&gt;FileShare&lt;/code&gt;, &lt;code&gt;Int32&lt;/code&gt;, &lt;code&gt;Boolean&lt;/code&gt; we can create our method signiture to something similar. We know that we always need to set the &lt;code&gt;Boolean&lt;/code&gt; parameter to true to use the asynchronous methods so we do not need to pass that in as a parameter.&lt;/p&gt;

&lt;p&gt;In this case our method signature will look like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    private static void ReadAsyncImpl(String FilePath, Action&amp;lt;Byte[]&amp;gt; onComplete, FileShare ShareMode, Int32 BufferStartingOffset)
    {
            // TODO:: Write asynchronous code...        
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;FilePath&lt;/code&gt; parameter tells us where the file is located. The &lt;code&gt;onComplete&lt;/code&gt; parameter is a section of code that we will execute after the file has been read. The &lt;code&gt;ShareMode&lt;/code&gt; tells the &lt;code&gt;FileStream&lt;/code&gt; class what kind of lock it should place on the file (Enumeration shown below). Lastly, the &lt;code&gt;BufferStartingOffset&lt;/code&gt; is the position in the data array to start writing. This parameter is usually 0, I have not found a need for changing it, but you never know.&lt;/p&gt;

&lt;p&gt;Here is the &lt;code&gt;FileShare&lt;/code&gt; enumeration, for reference:&lt;/p&gt;

&lt;table class=&quot;newspaper&quot;&gt;

&lt;tbody&gt;&lt;tr&gt;
&lt;th style=&quot;&quot;&gt;Member name&lt;/th&gt; &lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;span class=&quot;selflink&quot;&gt;None&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;span class=&quot;selflink&quot;&gt;Read&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;span class=&quot;selflink&quot;&gt;Write&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;span class=&quot;selflink&quot;&gt;ReadWrite&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;span class=&quot;selflink&quot;&gt;Delete&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Allows subsequent deleting of a file.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;span class=&quot;selflink&quot;&gt;Inheritable&lt;/span&gt;&lt;/td&gt;
&lt;td&gt;&lt;span&gt;Makes the file handle inheritable by child processes. This is not directly supported by Win32.&lt;/span&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;/tbody&gt;&lt;/table&gt;


&lt;p&gt;The next thing to do before we write any asynchronous code, is check our arguments and make sure the file exists and the buffer offset is greater than the length of the file (as we use the length of the file as the buffer size).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    private static void ReadAsyncImpl(String FilePath, Action&amp;lt;Byte[]&amp;gt; onComplete, FileShare ShareMode, Int32 BufferStartingOffset)
    {
        if (File.Exists(FilePath))
        {
            FileInfo fi = new FileInfo(FilePath);
            if (BufferStartingOffset &amp;gt;= fi.Length)
            {
                throw new ArgumentException(&quot;The &#39;BufferStartingOffset&#39; cannot greater than or equal to the length of the file you are reading.&quot;);
            }
            long buffer_size = fi.Length;
            // TODO:: Write asynchronous code...
        }
        else
        {
            throw new ArgumentException(&quot;The specified file path does not exist&quot;);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;From looking at the &lt;code&gt;FileStream&lt;/code&gt; class on &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx&quot;&gt;MSDN&lt;/a&gt;, we can see that &lt;code&gt;FileStream&lt;/code&gt; inherits &lt;code&gt;Stream&lt;/code&gt; which is an abstract class that implements the &lt;code&gt;IDisposible&lt;/code&gt; interface. This means that we can wrap our code in a &lt;code&gt;using&lt;/code&gt; statement to automatically close any file handlers. So we set up the &lt;code&gt;FileStream&lt;/code&gt; like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    private static void ReadAsyncImpl(String FilePath, Action&amp;lt;Byte[]&amp;gt; onComplete, FileShare ShareMode, Int32 BufferStartingOffset)
    {
        if (File.Exists(FilePath))
        {
            FileInfo fi = new FileInfo(FilePath);
            if (BufferStartingOffset &amp;gt;= fi.Length)
            {
                throw new ArgumentException(&quot;The &#39;BufferStartingOffset&#39; cannot greater than or equal to the length of the file you are reading.&quot;);
            }
            long buffer_size = fi.Length;
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, ShareMode, Convert.ToInt32(buffer_size), true))
            {
                byte[] data = new byte[buffer_size];

            }
        }
        else
        {
            throw new ArgumentException(&quot;The specified file path does not exist&quot;);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;From the code above you can now see that I have created a &lt;code&gt;FileStream&lt;/code&gt; object called fs and inside the using statement I have created the array that will hold the data that we read from the file, which is needed in the next part. I will cover the &lt;code&gt;onComplete&lt;/code&gt; parameter a bit later on. Now comes the asynchronous part of the function.&lt;/p&gt;

&lt;p&gt;To make the call to the file asynchronous we use the &lt;code&gt;BeginRead&lt;/code&gt; method of the &lt;code&gt;FileStream&lt;/code&gt; object. I think that the parameters are fairly straight forward for this method. We need to first pass in the buffer that we want to hold the data; followed by the buffer offset and the length of the file minus the buffer offset. The last two parameters are to do with the way that the &lt;code&gt;BeginRead&lt;/code&gt; method implements its call back. The first one of the two being the callback itself (I am choosing to use a inline function) and any state. The state we need to pass in, is the &lt;code&gt;FileStream&lt;/code&gt; object (fs).&lt;/p&gt;

&lt;h4&gt;Warning&lt;/h4&gt;

&lt;p&gt;If we do not pass in the &lt;code&gt;FileStream&lt;/code&gt; object that we created we will get a null reference exception when we attempt to close the &lt;code&gt;FileStream&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;AsyncState&lt;/code&gt; property of the variable we use for the inline function (which is of type &lt;code&gt;IAsyncResult&lt;/code&gt;) holds the state that we passed in. If we convert this state back to a &lt;code&gt;FileStream&lt;/code&gt; object we can then call the &lt;code&gt;EndRead&lt;/code&gt; method. The MSDN documentation states:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;EndRead must be called exactly for every call to BeginRead. Failing to end a read process before beginning another read can cause undesirable behavior such as deadlock.&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;        fs.BeginRead(data, BufferStartingOffset, data.Length - BufferStartingOffset, ar =&amp;gt;
        {
            // Reader task: add exception checks here (hint: do not use try/catch)
            FileStream _fs = (FileStream)ar.AsyncState;
            _fs.EndRead(ar);
        }, fs);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we are almost there in completing our &lt;code&gt;ReadAsync&lt;/code&gt; method, the last bit of code we need to write is to call our &lt;code&gt;onComplete&lt;/code&gt; action. &lt;code&gt;Action&lt;T&gt;&lt;/code&gt; basically means, give me a function/method to perform that takes the given type &lt;code&gt;T&lt;/code&gt; as a parameter. So for the last bit of code for the read is to call this function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    if (onComplete != null)
    {
        onComplete(data);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is our final &lt;code&gt;ReadAsync&lt;/code&gt; implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    /// &amp;lt;summary&amp;gt;
    /// Reads a file asynchronously from the file system.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;FilePath&quot;&amp;gt;The path of the file to read.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;onComplete&quot;&amp;gt;The routine that processes the resulting byte array.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;ShareMode&quot;&amp;gt;The type of file sharing that will be allowed whilst the file is being read.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;BufferStartingOffset&quot;&amp;gt;The position in the buffer of which to start reading into.&amp;lt;/param&amp;gt;
    private static void ReadAsyncImpl(String FilePath, Action&amp;lt;Byte[]&amp;gt; onComplete, FileShare ShareMode, Int32 BufferStartingOffset)
    {
        if (File.Exists(FilePath))
        {
            FileInfo fi = new FileInfo(FilePath);
            if (BufferStartingOffset &amp;gt;= fi.Length)
            {
                throw new ArgumentException(&quot;The &#39;BufferStartingOffset&#39; cannot greater than or equal to the length of the file you are reading.&quot;);
            }
            long buffer_size = fi.Length;
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, ShareMode, Convert.ToInt32(buffer_size), true))
            {
                byte[] data = new byte[buffer_size];

                fs.BeginRead(data, BufferStartingOffset, data.Length - BufferStartingOffset, ar =&amp;gt;
                {
                    FileStream _fs = (FileStream)ar.AsyncState;
                    _fs.EndRead(ar);

                    if (onComplete != null)
                    {
                        onComplete(data);
                    }

                }, fs);
            }
        }
        else
        {
            throw new ArgumentException(&quot;The specified file path does not exist&quot;);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once this is done, I then create several wrappers around the implementation method that I call from code. Below is an example of one, with the rest in the attached source code.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    /// &amp;lt;summary&amp;gt;
    /// Reads a file asynchronously from the file system.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;FilePath&quot;&amp;gt;The path of the file to read.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;onComplete&quot;&amp;gt;The routine that processes the resulting byte array.&amp;lt;/param&amp;gt;
    public static void ReadAsync(String FilePath, Action&amp;lt;Byte[]&amp;gt; onComplete)
    {
        ReadAsyncImpl(FilePath, onComplete, FileShare.Read, 0);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So then calling the new code is as easy as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    AsyncIO.ReadAsync(@&quot;C:\text.txt&quot;, (data) =&amp;gt;
    {
        Console.WriteLine(Encoding.UTF8.GetString(data));
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;&lt;a name=&quot;writes&quot;&gt;Asynchronous Writes&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;This section can be pretty much copied from the previous section, as there are not too many differences in the code. The main differences are that we are using &lt;code&gt;BeginWrite&lt;/code&gt; and &lt;code&gt;EndWrite&lt;/code&gt; whilst we pass in the bytes that we would like to write to the file instead of an offset. This code will automatically create the file if it does not exist and overwrite the file if it does exist.&lt;/p&gt;

&lt;p&gt;To handle these changes we, change the &lt;code&gt;FileMode&lt;/code&gt; parameter to &lt;code&gt;FileMode.Create&lt;/code&gt; and the &lt;code&gt;FileAccess&lt;/code&gt; parameter to &lt;code&gt;FileAccess.Write&lt;/code&gt;. The code must have &lt;code&gt;FileAccess.Write&lt;/code&gt; in order to write to the file.&lt;/p&gt;

&lt;p&gt;After all of the changes, here is the final &lt;code&gt;WriteAsync&lt;/code&gt; implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    /// &amp;lt;summary&amp;gt;
    /// The internal implementation of writing to a file asynchronously, overridding the existing file (if any).
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;FilePath&quot;&amp;gt;The path of the file to write to.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;BytesToWrite&quot;&amp;gt;The bytes that are going to be written to the file.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;onComplete&quot;&amp;gt;The action (if any) to be executed when the operation completes.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;ShareMode&quot;&amp;gt;The sharing mode to use with the file stream object.&amp;lt;/param&amp;gt;
    private static void WriteAsyncImpl(String FilePath, Byte[] BytesToWrite, Action onComplete, FileShare ShareMode)
    {
        using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write, ShareMode, BytesToWrite.Length, true))
        {
            fs.BeginWrite(BytesToWrite, 0, BytesToWrite.Length, ar =&amp;gt;
                {
                    FileStream _fs = (FileStream)ar.AsyncState;
                    _fs.EndWrite(ar);

                    if (onComplete != null)
                    {
                        onComplete();
                    }
                }, fs);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again, I have helper methods around the outside of this to simplify the calling. Here is an example of one of them:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    /// &amp;lt;summary&amp;gt;
    /// Writes to a file asynchronously on the file system, overridding the existing file (if any).
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;FilePath&quot;&amp;gt;The path of the file to write to. This file is created if it does not exist.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;TextToWrite&quot;&amp;gt;The text to write to the file.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;onComplete&quot;&amp;gt;The action to be taken when the write is successful.&amp;lt;/param&amp;gt;
    public static void WriteAsync(String FilePath, String TextToWrite, Action onComplete)
    {
        Byte[] BytesToWrite = Encoding.UTF8.GetBytes(TextToWrite);
        WriteAsyncImpl(FilePath, BytesToWrite, onComplete, FileShare.Write);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which can easily be called like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    AsyncIO.WriteAsync(@&quot;C:\Cemoc\test.xml&quot;, &quot;Hello World&quot;, () =&amp;gt;
    {
        Console.WriteLine(&quot;Written to file...&quot;);
        Console.WriteLine(&quot;&quot;);
        Console.WriteLine(&quot;&quot;);
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;&lt;a name=&quot;appends&quot;&gt;Asynchronous Appends&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;For the last section of this article, we will implement the Asynchronous Append. Like the previous section much of it can be copied from above. There are two key differences in this section though&lt;/p&gt;

&lt;p&gt;First of all, we need to change the &lt;code&gt;FileMode&lt;/code&gt; to &lt;code&gt;FileMode.Append&lt;/code&gt; so we do not overwrite the file. Secondly, we need to make sure that the file actually exists before we open the file stream.&lt;/p&gt;

&lt;p&gt;Here is the final append version, with all the major changes marked in bold and italics so that they are easier to see:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    /// &amp;lt;summary&amp;gt;
    /// The internal implementation of appending to a file asynchronously.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;FilePath&quot;&amp;gt;The path of the file to write to.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;BytesToWrite&quot;&amp;gt;The bytes that are going to be written to the file.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;onComplete&quot;&amp;gt;The action (if any) to be executed when the operation completes.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;ShareMode&quot;&amp;gt;The sharing mode to use with the file stream object.&amp;lt;/param&amp;gt;
    private static void AppendAsyncImpl(String FilePath, Byte[] BytesToWrite, Action onComplete, FileShare ShareMode)
    {
        if (!File.Exists(FilePath))
        {
            FileStream newFile = File.Create(FilePath);
            newFile.Close();
            newFile.Dispose();
        }
        using (FileStream fs = new FileStream(FilePath, FileMode.Append, FileAccess.Write, ShareMode, BytesToWrite.Length, true))
        {
            fs.BeginWrite(BytesToWrite, 0, BytesToWrite.Length, ar =&amp;gt;
            {
                FileStream _fs = (FileStream)ar.AsyncState;
                _fs.EndWrite(ar);

                if (onComplete != null)
                {
                    onComplete();
                }
            }, fs);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Like we have done previously, I have created a helper method or two to ease calling like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    /// &amp;lt;summary&amp;gt;
    /// Appends to a file asynchronously on the file system.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;FilePath&quot;&amp;gt;The path of the file to write to. This file is created if it does not exist.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;TextToWrite&quot;&amp;gt;The text to write to the file.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;onComplete&quot;&amp;gt;The action to be taken when the write is successful.&amp;lt;/param&amp;gt;
    public static void AppendAsync(String FilePath, String TextToWrite, Action onComplete)
    {
        Byte[] BytesToWrite = Encoding.UTF8.GetBytes(TextToWrite);
        AppendAsyncImpl(FilePath, BytesToWrite, onComplete, FileShare.Write);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which can be called like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    AsyncIO.AppendAsync(@&quot;C:\Cemoc\test.xml&quot;, Environment.NewLine + &quot;Appending to the end of the file...&quot;, () =&amp;gt;
    {
        // callback
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hopefully by now you have a good understanding of how Read/Write/Append asynchronously in .Net.&lt;/p&gt;

&lt;p&gt;Thanks for reading&lt;/p&gt;

&lt;h3&gt;&lt;a name=&quot;related&quot;&gt;Related Links&lt;/a&gt;&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx&quot;&gt;System.IO.FileStream (MSDN)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.danielfortunov.com/software/$daniel_fortunovs_adventures_in_software_development/2010/05/10/asynchronous_file_io_in_net&quot;&gt;Explaination of the problems with Asynchronous File I/O in .NET (Daniel Fortunov)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://pastebin.com/GDGNT7u5&quot;&gt;Source Code&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    
    <item>
      <title>Protect Files and Folders Using HttpHandlers in ASP.NET</title>
      <link>http://sblackler.net/2011/11/01/protect-files-and-folders-using-httphandlers</link>
      <pubDate>Tue, 01 Nov 2011 00:00:00 -0700</pubDate>
      <author>Author</author>
      <guid>http://domain/2011/11/01/protect-files-and-folders-using-httphandlers</guid>
      <description>&lt;p&gt;&lt;a href=&quot;https://github.com/sblackler/IHttpHanderInAspNet&quot;&gt;Get the latest source code
(C#)&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this article, I will show you how you can effectively protect a file
or folder by using the &lt;code&gt;IHttpHandler&lt;/code&gt;. From this, I hope that people
will learn a bit more about HttpHandlers and why they should/should not
use them. I also hope that people will get a better understanding of how
to implement their own handler.&lt;/p&gt;

&lt;p&gt;This article will cover the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#what&quot;&gt;What is an HttpHandler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#creating&quot;&gt;Creating an HttpHandler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#getting&quot;&gt;Getting the domain name automagically&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#dealing&quot;&gt;Dealing with HttpMethods (POST/GET)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#adding&quot;&gt;Adding an HttpHandler to the &lt;em&gt;Web.config&lt;/em&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sessions&quot;&gt;Adding sessions to an HttpHandler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#protecting&quot;&gt;Protecting sub-folders&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#references&quot;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;What is an HttpHandler&lt;/h2&gt;

&lt;p&gt;ASP.NET uses HttpHandlers to interact with requests before a web page is
served. An HttpHandler must implement the two methods of the
&lt;code&gt;IHttpHandler&lt;/code&gt; interface. These methods are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;processRequest&lt;/code&gt; - This contains the logic required for processing a
request.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;IsReusable&lt;/code&gt; - This tells the .NET runtime whether or not the
HttpHandler can be used again for requests of a similar type.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Now that we know what HttpHandlers are, let&#39;s see how to implement them.&lt;/p&gt;

&lt;h2&gt;Creating an HttpHandler&lt;/h2&gt;

&lt;p&gt;To create an HttpHandler, start by opening up a new or existing web site
in the language of your choice. After you get yourself the setup, add a
class to your project and name it &lt;code&gt;FileprotectionHandler&lt;/code&gt;. (&lt;strong&gt;Note&lt;/strong&gt;:
you will be asked to put it in the &lt;em&gt;app_code&lt;/em&gt; folder, it is fine to do
so.)&lt;/p&gt;

&lt;p&gt;You should then see the following output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Collections.Generic;
using System.linq;
using System.Web;

/// &amp;lt;summary&amp;gt; 
/// Summary description for FileprotectionHandler
/// &amp;lt;/summary&amp;gt; 
public class FileprotectionHandler
{
    public FileprotectionHandler()
    {
        //
        // TODO: Add constructor logic here
        //
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next, we need to implement the &lt;code&gt;IHttpHandler&lt;/code&gt; interface before we can
add our logic. You should change the class decoration to the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class FileprotectionHandler: IHttpHandler
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, if you press Shift+Alt+F10 with your cursor on the &lt;code&gt;IHttpHandler&lt;/code&gt;,
you will see that Visual Studio will auto implement the required methods
for you (or you could type them in yourself). Making your code look
like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Collections.Generic;
using System.linq;
using System.Web;

public class FileprotectionHandler : IHttpHandler
{
    public FileprotectionHandler()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    bool IHttpHandler.IsReusable
    {
        get { throw new NotImplementedException(); }
    }

    void IHttpHandler.processRequest(HttpContext context)
    {
        throw new NotImplementedException();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you want to use this handler for every request, then you have to
change the implementation in the &lt;code&gt;IsReusable&lt;/code&gt; method to this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;bool IHttpHandler.IsReusable
{
    get { return true; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Alternatively, just change the &lt;code&gt;true&lt;/code&gt; to &lt;code&gt;false&lt;/code&gt;. We also need to add
some variables that we will need in the next section. These are a domain
name, a static folder, and the relative path to the image itself. These
are all strings.&lt;/p&gt;

&lt;h2&gt;Getting the domain name automagically&lt;/h2&gt;

&lt;p&gt;In order to get the domain name automatically, you need to add a new
Global Application Class to your project. We need this as we are
interested in the &lt;code&gt;Session_Start&lt;/code&gt; event.&lt;/p&gt;

&lt;p&gt;In this event, we shall loop through the URL that is requested and set
&lt;code&gt;Session[&quot;DomainName&quot;]&lt;/code&gt;. &lt;/p&gt;

&lt;h4&gt;Global.asax (C#)&lt;/h4&gt;

&lt;pre&gt;&lt;code&gt;void Session_Start(object sender, EventArgs e) 
{
    string strDomainName = HttpContext.Current.Request.Url.ToString.Replace(HttpContext.Current.Request.Url.PathAndQuery.ToString, &quot;&quot;) + &quot;/&quot;;
    Session[&quot;DomainName&quot;] = strDomainName ;}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can set the variables that we will need for the rest of the
program. These will be set in the &lt;code&gt;IHttpHandler.processRequest&lt;/code&gt; method,
as shown below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void IHttpHandler.processRequest(HttpContext context)
{
    // Define your Domain Name Here
    String strDomainName = context.Session[&quot;DomainName&quot;].ToString(); 
    // Add the RELATIVE folder where you keep your stuff here
    String strFolder = &quot;~/static/&quot;;
    // Add the RELATIVE PATH of your &quot;no&quot; image
    String strNoImage = &quot;~/static/no.jpg&quot;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Dealing with HttpMethods&lt;/h2&gt;

&lt;p&gt;Sometimes we may want to execute different code based on what the
request is. The two main types of requests we will deal with are HTTP
GET and HTTP pOST. Setting up the framework for this is pretty
straightforward. As with many things in computer programming, there are
many different ways to do things. In this article, I will use a &lt;code&gt;switch&lt;/code&gt;
statement, which should keep our code a little bit cleaner. To set the
&lt;code&gt;switch&lt;/code&gt; up to execute different code on events, use the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void IHttpHandler.processRequest(HttpContext context)
{
    // Define your Domain Name Here
    String strDomainName = context.Session[&quot;DomainName&quot;].ToString(); 
    // Add the RELATIVE folder where you keep your stuff here
    String strFolder = &quot;~/static/&quot;;
    // Add the RELATIVE PATH of your &quot;no&quot; image
    String strNoImage = &quot;~/static/no.jpg&quot;;
    switch (context.Request.HttpMethod)
    {
        case &quot;GET&quot;:
            // TODO :: Implement code for GET method.
            break;
        case &quot;POST&quot;:
            // TODO :: Implement code for POST method.
            break;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, we have deleted the not-implemented exception code.
&lt;code&gt;Request.HttpMethod&lt;/code&gt; returns a string from which we can compare against.
In this instance, the &lt;code&gt;HttpMethod&lt;/code&gt; is already in uppercase. Before we go
any further, I would like to show you part of the code that will be used
to return the content type to the browser.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public string GetContentType(string filename)
{
    // used to set the encoding for the reponse stream
    string res = null;
    FileInfo fileinfo = new System.IO.FileInfo(filename);
    if (fileinfo.Exists)
    {
        switch (fileinfo.Extension.Remove(0, 1).ToLower())
        {
            case &quot;png&quot;:
                res = &quot;image/png&quot;;
                break;
            case &quot;jpeg&quot;:
                res = &quot;image/jpg&quot;;
                break;
            case &quot;jpg&quot;:
                res = &quot;image/jpg&quot;;
                break;
            case &quot;js&quot;:
                res = &quot;application/javascript&quot;;
                break;
            case &quot;css&quot;:
                res = &quot;text/css&quot;;
                break;
        }
        return res;
    }
    return null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have already added the five main file extensions that I protect. It
will check to see if the file exists. If it does not, then the function
will automatically return &lt;code&gt;null&lt;/code&gt;. We are now ready to implement the code
for the POST method. In this article, I never want a user to POST to my
files in my folder. So, I will set the &lt;code&gt;ContentType&lt;/code&gt; and send the image
back to the user in the following function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
{
    context.Response.ContentType = GetContentType(strFile);
    context.Response.TransmitFile(strFile);
    context.Response.End();
    return context;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we have the basis to complete the rest of the method, checking to
see if the URL the request comes from is ours or not. It is completed
like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void IHttpHandler.processRequest(HttpContext context)
{
    // Define your Domain Name Here
    String strDomainName = context.Session[&quot;DomainName&quot;].ToString(); 
    // Add the RELATIVE folder where you keep your stuff here
    String strFolder = &quot;~/static/&quot;;
    // Add the RELATIVE pATH of your &quot;no&quot; image
    String strNoImage = &quot;~/static/no.jpg&quot;;
    switch (context.Request.HttpMethod)
    {
        case &quot;GET&quot;:
            String strRequestedFile = context.Server.Mappath(context.Request.Filepath);
            if (context.Request.UrlReferrer != null)
            { 
                String strUrlRef = context.Request.UrlReferrer.ToString();
                String strUrlimageFull = ResolveUrl(strFolder);
                if (strUrlRef.Contains(strUrlimageFull))
                {
                    context = SendContentTypeAndFile(context, strNoImage);
                }
                else if(strUrlRef.StartsWith(strDomainName))
                {
                    context = SendContentTypeAndFile(context, strRequestedFile);
                }
                else
                {
                    context = SendContentTypeAndFile(context, strNoImage);
                }
            }
            else
            {
                context = SendContentTypeAndFile(context, strNoImage);
            }
            break;
        case &quot;pOST&quot;:
            context = SendContentTypeAndFile(context, strNoImage);
            break;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Adding an HttpHandler to the Web.config&lt;/h2&gt;

&lt;p&gt;To get the ASP.NET runtime to recognize that you have an HttpHandler you
wish to implement, you will need to add the following line to your
&lt;em&gt;web.config&lt;/em&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;add verb=&quot;*&quot; path=&quot;*/static/*&quot; validate=&quot;true&quot;  type=&quot;FileprotectionHandler&quot;/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It needs to go in under the &quot;&lt;code&gt;HttpHandlers&lt;/code&gt;&quot; section and should be
placed underneath the second line. Following this, test your application
and all should be well :)&lt;/p&gt;

&lt;h2&gt;Adding sessions to an HttpHandler&lt;/h2&gt;

&lt;p&gt;Adding session state to the HttpHandler is easier than you may think.
First of all, you need to add the following statement to your &lt;code&gt;using&lt;/code&gt;
statements section:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System.Web.SessionState;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Following that, you need to change the class declaration to the
following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class FileprotectionHandler : IHttpHandler, IRequiresSessionState
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, in the &quot;&lt;code&gt;IHttpHandler.processRequest&lt;/code&gt;&quot; method, you can access the
Session state in two ways:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// 1) you can use this way so you do not have to write context.Session constantly
HttpSessionState Session = context.Session;
Session[&quot;SomeKey&quot;].ToString();
// 2) or you can just type it out in full
context.Session[&quot;SomeKey&quot;].ToString();
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Protecting sub-folders&lt;/h2&gt;

&lt;p&gt;To protect sub-folders, simply add a new &lt;em&gt;web.config&lt;/em&gt; file to the sub
folder and ensure that the contents of the file look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot;?&amp;gt;
&amp;lt;configuration&amp;gt;
    &amp;lt;appSettings/&amp;gt;
    &amp;lt;connectionStrings/&amp;gt;
    &amp;lt;system.web&amp;gt;
      &amp;lt;httpHandlers&amp;gt;
        &amp;lt;add verb=&quot;*&quot; path=&quot;*&quot; validate=&quot;true&quot; type=&quot;FileprotectionHandler&quot;/&amp;gt;
      &amp;lt;/httpHandlers&amp;gt;
    &amp;lt;/system.web&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hopefully, you now understand HttpHandlers a bit more. You can use the
code in any shape or form but it is provided &quot;As Is&quot; and I take
no responsibility for any damage or loss of data. &lt;/p&gt;

&lt;h2&gt;References&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://wiki.asp.net/page.aspx/687/http-handlers-to-handle-images/&quot;&gt;wiki.asp.net/page.aspx/687/http-handlers-to-handle-images/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.informit.com/articles/article.aspx?p=25339&amp;amp;seqNum=5&quot;&gt;informit.com/articles/article.aspx?p=25339&amp;amp;seqNum=5&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;History&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;20/08/09&lt;/strong&gt;: Added source code download as I forgot that
originally.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;05/10/09&lt;/strong&gt;: Changed to make more dynamic. Improved several code
features. Added automatic domain finding.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    

  </channel> 
</rss>