<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Blog</title><link>http://www.litemedia.info:80/</link><description>Blog</description><item><title>Failure of the dynamic keyword</title><link>http://www.litemedia.info:80/failure-of-the-dynamic-keyword</link><description>&lt;p&gt;I would consider the dynamic keyword that was introduced in C# 4, a failure. It was really a hack to integrate dynamic languages with the CLR, a venture that Microsoft seems to have abondoned. The only two uses I know of it today is in Razor View Engine and Massive ORM.&lt;/p&gt;
&lt;p&gt;I think that most C# developers has not even encountered dynamic at all.&lt;/p&gt;
&lt;p&gt;The difference between the dynamic and the anonymous type, is that the anonymous type is actually compiled, and the dynamic is resolved during runtime. The real problem with anonymous types is they aren't easily returned from method calls. Consider the following.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private static object GetEmployee()
{
    return new { Name = "John", Profession = "Santa" };
}

object employee = GetEmployee();&lt;/pre&gt;
&lt;p&gt;The object employee contains the properties Name and Profession, but how do we get the data out? How do we cast the employee to the anonymous type? We have two options here&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Use reflection to get the data&lt;/li&gt;
&lt;li&gt;Use an ugly generics hack to cast the type (see line 208 of &lt;a href="https://bitbucket.org/bokmal/episerver-cms-pagetypes-t4-template/src/tip/GeneratePageTypes.tt"&gt;GeneratePageTypes.tt&lt;/a&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;None of these are very convenient, and for this purpose we could use dynamic.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private static dynamic GetEmployee()
{
    dynamic employee = new { Name = "John", Profession = "Santa" };
    return employee;
}

var employee = GetEmployee();
Console.WriteLine("Employee of the month: {0}, {1}", employee.Name, employee.Profession);&lt;/pre&gt;
&lt;p&gt;This works because the compiler will always accept a call to a member on a dynamic type, but if that member does not exist during runtime, it will fail. Is it good, or bad? Your choice. This is the basics of dynamic keyword in C#.&lt;/p&gt;
&lt;h2&gt;The practical application&lt;/h2&gt;
&lt;p&gt;Have you ever been working with regular expressions? Your code probably would look like this.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;string time = "12:00";
var match = Regex.Match(time, @"(?&amp;lt;Hour&amp;gt;\d{2}):(?&amp;lt;Minute&amp;gt;\d{2})");
if (match.Success)
{
    var hour = match.Groups["Hour"].Value;
    var minute = match.Groups["Minute"].Value;
    Console.WriteLine("The time is {0}.{1}", hour, minute);
}&lt;/pre&gt;
&lt;p&gt;By making the result of the regular expression dynamic we could be looking at code like this.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;string time = "12:00";
var match = new DynamicRegex(@"(?&amp;lt;Hour&amp;gt;\d{2}):(?&amp;lt;Minute&amp;gt;\d{2})").Match(time);
if (match.Success)
{
    Console.WriteLine("The time is {0}.{1}", match.Hour, match.Minute);
}&lt;/pre&gt;
&lt;p&gt;It's less code, so it must be better - right? Let's take a look at the DynamicRegex class. It's just a wrapper around System.Text.RegularExpressions.Regex.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class DynamicRegex
{
    private readonly Regex expression;
    public DynamicRegex(string expression)
    {
        this.expression = new Regex(expression);
    }

    public dynamic Match(string input)
    {
        return new DynamicMatch(expression.Match(input));
    }
}&lt;/pre&gt;
&lt;p&gt;Nothing exciting here. The match method returns a dynamic which is created by wrapping System.Text.RegularExpressions.Match in a class called DynamicMatch. And what does that look like?&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class DynamicMatch : DynamicObject
{
    private readonly Match match;

    public DynamicMatch(Match match)
    {
        this.match = match;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        var prop = match.GetType().GetProperty(binder.Name);

        // Match instance property
        if (prop != null)
        {
            result = prop.GetValue(match, null);
            return true;
        }

        // Group value
        Group group;
        if ((group = this.match.Groups[binder.Name]) != null)
        {
            result = group.Value;
            return true;
        }

        result = null;
        return false;
    }
}&lt;/pre&gt;
&lt;p&gt;Here it becomes interesting. We can create our own dynamic object by implementing the IDynamicMetaObjectProvider interface, or inherit from System.Dynamic.DynamicObject as I've done here. There are a lot of fun methods to override, to specify what should happen when calling a method on a dynamic object. This is very much as the missing_method in Ruby.&lt;/p&gt;
&lt;p&gt;My code is very simple. Go check if there is a property on the Match object that we're trying to call. If not, it must be a matching group we're after. This is why we can call match.Success and match.Hour, match.Minute on the same instance. So, if we have a matching group called Success, we might not get the result we're after. That is the price we pay for syntactic sugar.&lt;/p&gt;
&lt;h2&gt;What's the point?&lt;/h2&gt;
&lt;p&gt;This is just the kind of problem where we could use the dynamic keyword. Another is representing data from an IDataReader when we don't want a typed schema. We could use dynamic to get properties out of a JSON document or XML for that matter.&lt;/p&gt;
&lt;p&gt;But these applications are things for framework developers and not mere mortals. I would say it is easier to make a mistake when you mix static types and dynamic, and you shouldn't if you don't know what you're doing. C# is a static language and as "Joe developer", you just don't have to care.&lt;/p&gt;</description><pubDate>Sun, 18 Dec 2011 11:39:18 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/failure-of-the-dynamic-keyword</guid></item><item><title>Alive v0.2 is released</title><link>http://www.litemedia.info:80/alive-v0.2-is-released</link><description>&lt;p&gt;During my commuting, I've been able to pick up the most critical issues with Alive and fix them. Sadly, there's no easy fix to support any other browsers than Chrome at the moment. I'm just going to say it out loud.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Alive v0.2 is Chrome only. I will attend to this issue in v0.3.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;Here comes a list of changes. Note that &lt;strong&gt;configuration is a breaking change&lt;/strong&gt;, and you will have to address it if you're upgrading.&lt;/div&gt;
&lt;h2&gt;The release may be downloaded from&lt;/h2&gt;
&lt;p&gt;&lt;a href="http://code.google.com/p/litemedia-alive/"&gt;Google Code&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://code.google.com/p/litemedia-alive/downloads/detail?name=Alive-0.2-x64-net20.zip" title="Alive-0.2-x64-net20.zip"&gt;Alive-0.2-x64-net20.zip&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://code.google.com/p/litemedia-alive/downloads/detail?name=Alive-0.2-x64-net40.zip" title="Alive-0.2-x64-net40.zip"&gt;Alive-0.2-x64-net40.zip&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://code.google.com/p/litemedia-alive/downloads/detail?name=Alive-0.2-x86-net20.zip" title="Alive-0.2-x86-net20.zip"&gt;Alive-0.2-x86-net20.zip&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://code.google.com/p/litemedia-alive/downloads/detail?name=Alive-0.2-x86-net40.zip" title="Alive-0.2-x86-net40.zip"&gt;Alive-0.2-x86-net40.zip&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a href="https://nuget.org/packages/LiteMediaAlive/0.2.1"&gt;NuGet - LiteMedia Alive&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Changes&lt;/h2&gt;
&lt;h3&gt;New configuration schema&lt;/h3&gt;
&lt;p&gt;The configuration schema of version 1.1 didn't make much sense, so I sharpened it a bit. These are the major changes&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;No section groups, but only one section handler.&lt;/li&gt;
&lt;li&gt;Configuration section handler name has become lower case.&lt;/li&gt;
&lt;li&gt;Previous "group" element has been renamed to "chart".&lt;/li&gt;
&lt;li&gt;Previous "groups" element has been renamed to "group.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here's an example of the new schema.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;  &amp;lt;alive&amp;gt;
    &amp;lt;settings columns="3" /&amp;gt;
    &amp;lt;counters&amp;gt;
      &amp;lt;group name="Hardware"&amp;gt;
        &amp;lt;chart name="CPU" updateLatency="1000"&amp;gt;
          &amp;lt;counter name="CPU" categoryName="Processor" counterName="% Processor Time" instanceName="_Total" /&amp;gt;
        &amp;lt;/chart&amp;gt;
		&amp;lt;chart name="Memory Activity" updateLatency="1000"&amp;gt;
		  &amp;lt;counter name="Memory" categoryName="Memory" counterName="Pages/sec" /&amp;gt;
		&amp;lt;/chart&amp;gt;
        &amp;lt;chart name="Memory Usage" updateLatency="5000"&amp;gt;
          &amp;lt;counter name="RAM" categoryName="Memory" counterName="% Committed Bytes In Use" /&amp;gt;
          &amp;lt;counter name="Page file" categoryName="Paging File" counterName="% Usage" instanceName="_Total" /&amp;gt;
        &amp;lt;/chart&amp;gt;
	  &amp;lt;/group&amp;gt;
	  &amp;lt;group name="IIS"&amp;gt;
        &amp;lt;chart name="ASP.NET Performance" updateLatency="1000"&amp;gt;
          &amp;lt;counter name="Requests/sec" categoryName="ASP.NET Applications" counterName="Requests/Sec" instanceName="__Total__" /&amp;gt;
        &amp;lt;/chart&amp;gt;
		&amp;lt;chart name="Session state server" updateLatency="5000"&amp;gt;
		  &amp;lt;counter name="Active" categoryName="ASP.NET" counterName="State Server Sessions Active" /&amp;gt;
		&amp;lt;/chart&amp;gt;
      &amp;lt;/group&amp;gt;
    &amp;lt;/counters&amp;gt;
  &amp;lt;/alive&amp;gt;&lt;/pre&gt;
&lt;h3&gt;Scaling 100, 250, 500, 1000&lt;/h3&gt;
&lt;p&gt;When a data point reaches above the limit, the chart will scale itself, to be able to display all the values. In previous version it would scale from 100 directly to 500 which made smaller values very hard to intepret if some data point was 101. That is why 101 now scales the chart to a max value of 250. This makes the chart easier to read.&lt;/p&gt;
&lt;h3&gt;Writing 1000 as 1K and 1000000 as 1M&lt;/h3&gt;
&lt;p&gt;Some performance counters may have very large values. In order to make it easier to read, we're now writing 1000 as 1K and 1 million as 1M.&lt;/p&gt;
&lt;h3&gt;Define max value on chart element&lt;/h3&gt;
&lt;p&gt;In the configuration you can specify the default max value for a chart. When the chart loads, it will have this as its highest value until a data point forces it to scale. This is useful when you know that you will only have values below 10.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;chart name="Shopping Cart" updateLatency="1000" max="10"&amp;gt;
  ...
&amp;lt;/chart&amp;gt;&lt;/pre&gt;
&lt;h3&gt;Remote performance counters&lt;/h3&gt;
&lt;p&gt;This is a major feature. You may track counters on other computers. You do this by adding "machine" to the counter element in configuration. Here's an example.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;group name="SQL Server"&amp;gt;
	&amp;lt;chart name="CPU" updateLatency="1000"&amp;gt;
		&amp;lt;counter name="CPU" categoryName="Processor" counterName="% Processor Time" instanceName="_Total" machine="SQLSERVER1" /&amp;gt;
	&amp;lt;/chart&amp;gt;
&amp;lt;/group&amp;gt;&lt;/pre&gt;
&lt;p&gt;That was the easy part. Now you need to make sure that your application pool identity has the required permissions to read that performance counter.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Make sure that the remote machine is running "remote registry service".&lt;/li&gt;
&lt;li&gt;Add the application pool identity to the "Performance Monitor Users" group on the remote machine.&lt;/li&gt;
&lt;li&gt;Use regedt32.exe to give your application pool identity read access to following keys&lt;br /&gt;HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg&lt;br /&gt;HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib&lt;/li&gt;
&lt;li&gt;Also give your application pool identity read access to the following files&lt;br /&gt;%SystemRoot%\System32\Perfc009.dat&lt;br /&gt;%SystemRoot%\System32\Perfh009.dat&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;</description><pubDate>Fri, 16 Dec 2011 19:52:22 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/alive-v0.2-is-released</guid></item><item><title>Secure your Alive Dashboard</title><link>http://www.litemedia.info:80/secure-your-alive-dashboard</link><description>&lt;p&gt;What kind of security is implemented in Alive?&lt;/p&gt;
&lt;p&gt;- None&lt;/p&gt;
&lt;p&gt;But it is essential that you don't expose Alive publicly. There are no guarantees that a hacker won't use Alive against you. So, how do you go ahead securing Alive? Easiest is to use the security model in asp.net and add the following to your web.config.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;location path="Alive.axd"&amp;gt;
	&amp;lt;system.web&amp;gt;
		&amp;lt;authorization&amp;gt;
			&amp;lt;allow users="?"/&amp;gt;
			&amp;lt;deny users="*"/&amp;gt;
		&amp;lt;/authorization&amp;gt;
	&amp;lt;/system.web&amp;gt;
&amp;lt;/location&amp;gt;&lt;/pre&gt;
&lt;p&gt;This will allow only authenticated users, and deny anonymous. How to turn that "Access Denied" into a proper authentication can be read on MSDN.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/eeyk640h.aspx"&gt;http://msdn.microsoft.com/en-us/library/eeyk640h.aspx&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description><pubDate>Wed, 14 Dec 2011 20:09:54 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/secure-your-alive-dashboard</guid></item><item><title>Custom Performance Counters in Alive</title><link>http://www.litemedia.info:80/custom-performance-counters-in-alive</link><description>&lt;p&gt;If you've missed previous posts about Alive, you can read more about it at&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://litemedia.info/introducing-alive"&gt;Introducing Alive&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://litemedia.info/alive-demo"&gt;Alive demo&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The real power of Alive, is when it comes to custom performance counters. In your application you have events that would be nice to track in real time. A new order is put, someone paid with their credit card, a user logged in. &amp;nbsp;For this you can create custom performance counters.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/custom-performance-counters-in-alive/custom_counter_test_application.png" alt="Test application for creating custom performance counters" width="585" height="408" /&gt;&lt;/p&gt;
&lt;h2&gt;Create a new performance counter&lt;/h2&gt;
&lt;p&gt;It is easy to create a new performance counter on your development machine. Open up server explorer in Visual Studio. Right click on Performance Counters and select "Create New Category".&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/custom-performance-counters-in-alive/server_explorer.png" alt="Create a new performance counter category in Server Explorer" width="483" height="389" /&gt;&lt;/p&gt;
&lt;p&gt;This gives you a slick interface where you can create your new counter.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/custom-performance-counters-in-alive/create_new_countery_category.png" alt="Create a new performance counter category interface" width="546" height="517" /&gt;&lt;/p&gt;
&lt;p&gt;Create a new web application and include Alive.&lt;/p&gt;
&lt;pre class="brush:plain;gutter:false"&gt;PM&amp;gt; Install-Package LiteMediaAlive&lt;/pre&gt;
&lt;p&gt;Edit your web.config so Alive configuration looks like following.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;  &amp;lt;Alive&amp;gt;
    &amp;lt;settings columns="3" /&amp;gt;
    &amp;lt;counters&amp;gt;
      &amp;lt;groups&amp;gt;
        &amp;lt;group name="Test" updateLatency="1000"&amp;gt;
          &amp;lt;counter name="Test" categoryName="Test Category" counterName="Test Increment" /&amp;gt;
        &amp;lt;/group&amp;gt;
      &amp;lt;/groups&amp;gt;
    &amp;lt;/counters&amp;gt;
  &amp;lt;/Alive&amp;gt;&lt;/pre&gt;
&lt;p&gt;Create a new ASPX page.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="LiteMedia.Alive.Web.Test.Index" %&amp;gt;
&amp;lt;!DOCTYPE html5&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;title&amp;gt;Alive custom performance counter&amp;lt;/title&amp;gt;
        &amp;lt;style&amp;gt;
            div { display: block; }
            iframe { width: 100%; height: 500px; border: none; }
        &amp;lt;/style&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;form runat="server"&amp;gt;
        &amp;lt;div&amp;gt;
            &amp;lt;h1&amp;gt;Press the button to increment the counter&amp;lt;/h1&amp;gt;
            &amp;lt;asp:ScriptManager runat="server"&amp;gt;
            &amp;lt;/asp:ScriptManager&amp;gt;
            &amp;lt;asp:UpdatePanel runat="server"&amp;gt;
                &amp;lt;ContentTemplate&amp;gt;
                    &amp;lt;asp:Button runat="server" Text="Press me" OnClick="IncreaseCounter" /&amp;gt;
                &amp;lt;/ContentTemplate&amp;gt;
            &amp;lt;/asp:UpdatePanel&amp;gt;
            &amp;lt;iframe src="/Alive.axd/" /&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;
&lt;p&gt;We bind the button to a method in code behind that increases the counter.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;protected void IncreaseCounter(object sender, EventArgs e)
{
    using (var counter = new PerformanceCounter("Test Category", "Test Increment", readOnly: false))
    {
        counter.Increment();
    }
}&lt;/pre&gt;
&lt;p&gt;Bam! You're done! You can download the whole example from here.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://litemedia.info/media/Default/BlogPost/blog/custom-performance-counters-in-alive/LiteMedia.Alive.CustomPerformanceCounter.zip"&gt;LiteMedia.Alive.CustomPerformanceCounter.zip&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There are a lot of &lt;a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountertype.aspx"&gt;performance counter types&lt;/a&gt; to explore. There's an &lt;a href="http://www.codeproject.com/KB/dotnet/perfcounter.aspx"&gt;excellent article on The Code Project&lt;/a&gt; about performance counters.&lt;/p&gt;
&lt;h2&gt;Create performance counters in your production environment&lt;/h2&gt;
&lt;p&gt;It is a common scenario that you can't reach the production environment from your development machine. In that case I use this piece of F# to create my performance counters.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;open System.Diagnostics

let args = System.Environment.GetCommandLineArgs()

printf "LiteMedia, Mikael Lundin\n"
printf "Create performance counters\n"

if args.Length &amp;lt;&amp;gt; 3 then
  printf "Usage: CreatePerfmon [category name] [category description] "

else
  let name = args.[1]
  let description = args.[2]
  
  let counterCreation = new CounterCreationDataCollection()

  let create name description counterType =
    new CounterCreationData(name, description, counterType)

  create "# operations executed" "Number of total operations executed" PerformanceCounterType.NumberOfItems32
    |&amp;gt; counterCreation.Add
    |&amp;gt; ignore

  create "# operations / sec" "Number of operations executed per second" PerformanceCounterType.RateOfCountsPerSecond32 
    |&amp;gt; counterCreation.Add 
    |&amp;gt; ignore

  create "average time per operation" "Average duration per operation execution" PerformanceCounterType.AverageTimer32
    |&amp;gt; counterCreation.Add
    |&amp;gt; ignore

  create "average time per operation base" "Average duration per operation execution base" PerformanceCounterType.AverageBase
    |&amp;gt; counterCreation.Add
    |&amp;gt; ignore
  
  PerformanceCounterCategory.Create(name, description, PerformanceCounterCategoryType.MultiInstance, counterCreation) |&amp;gt; ignore&lt;/pre&gt;
&lt;p&gt;Compile it into a runnable exe and execute on your production environment like this.&lt;/p&gt;
&lt;pre class="brush:plain;gutter:false"&gt;CreateCounter.exe "New orders" "Increments when new orders are added to the system"&lt;/pre&gt;
&lt;p&gt;This will give you a performance category on the server called "New orders" and it will contain the following counters.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;# operations executed&lt;/li&gt;
&lt;li&gt;# operations / sec&lt;/li&gt;
&lt;li&gt;average time per operation&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is a really simple way to keep an eye on the production environment and that you're recieving new orders in the rate that you should.&lt;/p&gt;</description><pubDate>Sun, 11 Dec 2011 11:53:58 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/custom-performance-counters-in-alive</guid></item><item><title>Alive demo</title><link>http://www.litemedia.info:80/alive-demo</link><description>&lt;p&gt;I'm currently working on version 0.2 of Alive, but not announcing anything just yet. Expect an update in a couple of weeks. Until then I urge you to take a look at my &lt;a href="http://alive.litemedia.se/Alive.axd/"&gt;live demo&lt;/a&gt;. Open it up in your favorite Chrome browser (Firefox is ok to).&lt;/p&gt;
&lt;p&gt;&lt;a href="http://alive.litemedia.se/Alive.axd/"&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/alive-screenshot.png" alt="Alive screenshot" width="460" height="303" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;You have to be a bit patient with my server, because it is a very old crappy machine in my closet, I mostly use as an development environment.&lt;/p&gt;</description><pubDate>Thu, 08 Dec 2011 06:21:16 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/alive-demo</guid></item><item><title>Database change management</title><link>http://www.litemedia.info:80/database-change-management</link><description>&lt;p&gt;I thought I would get started with database change management and &lt;a href="http://code.google.com/p/tarantino/wiki/DatabaseChangeManagement"&gt;Tarantino&lt;/a&gt;, but after spending a day trying to figure it out, I eventually decided that it would go much faster to just roll my own.&lt;/p&gt;
&lt;h2&gt;What is database change management?&lt;/h2&gt;
&lt;p&gt;Most developers today are familiar with source version control. Even if some use it only for backups only, the main idea is for you to go back in history when needed or to try out different approaches in other branches. Using SVC &lt;em&gt;(software version control)&lt;/em&gt; has become a standard in the industry, but very few apply the same idea on databases even though they also are a major part of most application development.&lt;/p&gt;
&lt;h3&gt;How not to version control databases&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Check in the database to source control&lt;/strong&gt; It works as long as you are only one developer to check in the binary database file to your repository. You will however not be able to merge changes from different developers and you will have to do manual updates of your production environment when the time comes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Share database with team members on a central server &lt;/strong&gt; The most common way to handle database development is not to version control at all, but to setup the database on a shared central server. This fails when you need to revert to a previous version, but it also makes it harder to work as a team. When you make changes to the database you will affect your team members because they don't have your code to support the database changes. In worst case the whole team will halt production until you've checked in your code to support the database change.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Why should I care?&lt;/h2&gt;
&lt;p&gt;If you manage to version control your database development, you will not only be able to revert to old revisions, work in branches but also automatically get old databases up to date within your release process. This is much more efficient than manually merging the databases at every release, and also less error prone.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You bring stability to your release cycle&lt;/li&gt;
&lt;li&gt;You reduce hold ups in the production line for your team&lt;/li&gt;
&lt;li&gt;You bring greater control to your database development process&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;How do I get started?&lt;/h2&gt;
&lt;p&gt;If you use NAnt or MsBuild as build script you should probably &lt;a href="http://code.google.com/p/tarantino/wiki/DatabaseChangeManagement"&gt;head over to Tarantino&lt;/a&gt; and download their software since it has excellent support for your environment. If not, you may keep on reading. Since I'm using &lt;a href="http://code.google.com/p/psake/"&gt;psake&lt;/a&gt; at the moment, I decided to implement my database change management in &lt;a href="http://support.microsoft.com/kb/968929"&gt;PowerShell v2&lt;/a&gt;. The concept is very simple. You keep a directory in your source control where you store database creation/update scripts. The key component is that you never ever change any of these scripts after their first commit. When you need to change something in the database you create a new script. That way you will always be able to create a new database and bring it up to &lt;a href="http://stackoverflow.com/questions/2057941/tortoisesvn-what-is-head-revision"&gt;head revision&lt;/a&gt; at any time.&lt;/p&gt;
&lt;p&gt;&lt;img class="alignnone size-full wp-image-605" title="database_change_management" src="http://litemedia.info/media/Default/Mint/database_change_management.png" alt="database_change_management" width="330" height="65" /&gt;&lt;/p&gt;
&lt;p&gt;The naming convention here is very important. Next thing you need is a database where you have a table and a column that tells you what version this database is. As you've already guessed, this is exactly up to what revision the change scripts has been applied.&lt;/p&gt;
&lt;p&gt;&lt;img class="alignnone size-full wp-image-607" title="database" src="http://litemedia.info/media/Default/Mint/database1.png" alt="database" width="266" height="200" /&gt;&lt;/p&gt;
&lt;p&gt;All you need now is one function that can look at your database, decide what version it is and apply those changes that has not yet been applied. Actually, I do it in three functions and they look like this.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Update-Database $connection_string $database_directory&lt;/strong&gt; Connects to the database and get the version number. Finds all change scripts in the database directory that are above the specific version and applies them to the database. Last it updates the database with the current version number.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Build-Database $sql_server $database_name&lt;/strong&gt; Connects to the DBMS and creates an empty database. In this database it adds the necessary table and column to keep track of database versions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Drop-Database $sql_server $database_name&lt;/strong&gt; Removes the database from the DBMS.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Example usage&lt;/h3&gt;
&lt;p&gt;In my current project I want to run integration tests on a fresh database every time I check in code. That means I will have the following build process executed.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Compile&lt;/li&gt;
&lt;li&gt;Drop-Database "MAIA\SQLEXPRESS" "IntegrationTests"&lt;/li&gt;
&lt;li&gt;Build-Database "MAIA\SQLEXPRESS" "IntegrationTests"&lt;/li&gt;
&lt;li&gt;Update-Database "Data Source=MAIA\SQLEXPRESS;Initial Catalog=IntegrationTests;Integrated Security=True;" ".\Database"&lt;/li&gt;
&lt;li&gt;Run integration tests&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When I check in code I will rebuild the database and execute my integration tests on it. That way I will not only test my code, but also verify that my change scripts are working. When it is time for release I will be able to run Update-Database on my production database, because I know that those build scripts has been thoroughly tested. Here is my PowerShell script if you're interested. I still see myself as a novice in PowerShell scripting, but it works and is quite minimalistic.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://litemedia.info/media/Default/Mint/database-change-management.ps1"&gt;database-change-management.ps1&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;&lt;span color="red" style="color: red;"&gt;&lt;strong&gt;An update to this database script has been posted &lt;a href="http://litemedia.info/database-versioning-updated"&gt;here&lt;/a&gt;.&lt;/strong&gt;&lt;/span&gt;&lt;/div&gt;</description><pubDate>Sun, 04 Dec 2011 17:03:23 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/database-change-management</guid></item><item><title>Database versioning updated</title><link>http://www.litemedia.info:80/database-versioning-updated</link><description>&lt;p&gt;I have been getting some feedback on my blog post about &lt;a href="http://litemedia.info/database-change-management" title="Database change management"&gt;database change management&lt;/a&gt;, and I thought it was about time to make some updates to the database change management powershell script that I posted there.&amp;nbsp;Let's go through this, step by step.&lt;/p&gt;
&lt;p&gt;My change management procedure means that I will rebuild the database from scratch for each build. Before building the database, I need to drop the old one.&lt;/p&gt;
&lt;pre class="brush:powershell"&gt;# Will drop the database if it exists
Function Drop-Database ([string]$sql_server, [string]$database_name)
{
	try {
		[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')  | out-null
		$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $sql_server
		$s.Refresh();
		$s.KillDatabase($database_name);
		Write-Host "Killed database $databaseName"
	}
	catch {
		Write-Error "Tried to delete database $databaseName but failed, probably because it did not exist"
	}
}&lt;/pre&gt;
&lt;p&gt;We could check if the database exists before we try to drop.&lt;/p&gt;
&lt;pre class="brush:powershell"&gt;# Determine if database exists
Function Exists-Database ([string]$sql_server, [string]$database_name)
{
	$exists = $FALSE
	try {
		# Connect and run a command using SMO 
		[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
		
		# Get server reference
		$s = new-object ("Microsoft.SqlServer.Management.Smo.Server") $sql_server
		
		foreach($db in $s.databases) 
		{
			# Database exists?
			if ($db.name -eq $database_name) {
				$exists = $TRUE
			}
		}
	}
	catch {
		Write-Error "Failed to connect to $sql_server"
	}

	# Return
	$exists
}&lt;/pre&gt;
&lt;p&gt;Start by creating a new database and add a versioning table to it, where we keep track of the database version.&lt;/p&gt;
&lt;pre class="brush:powershell"&gt;# Will create a new database and add table to manage versions
Function Build-Database ([string]$sqlServer, [string]$databaseName)
{
	# http://sqlblog.com/blogs/allen_white/archive/2008/04/28/create-database-from-powershell.aspx
	[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')  | out-null
	$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $sqlServer
	$dbname = $databaseName
	
	# Instantiate the database object and create database
	$db = new-object ('Microsoft.SqlServer.Management.Smo.Database') ($s, $dbname)
	$db.Create()
	
	# Create table and column for handling database version
	$db.ExecuteNonQuery("CREATE TABLE [$databaseName].[dbo].[Settings] ([DatabaseVersion] int NOT NULL)");
	$db.ExecuteNonQuery("INSERT INTO [$databaseName].[dbo].[Settings] ([DatabaseVersion]) VALUES (0)");
}&lt;/pre&gt;
&lt;p&gt;And now we can look through the directory that contains the change scripts and execute them on the database, one by one.&lt;/p&gt;
&lt;pre class="brush:powershell"&gt;# Will update the database to the most current version in the database directory
Function Update-Database ([string]$connection_string, [string]$database_directory)
{

	$databaseVersion = Get-Database-Version $connection_string
	
	# Get all source files that have higher database version number
	$files = Get-ChildItem "$database_directory\*.sql" | Where { [int]::Parse($_.name.Substring(0, 4)) -gt $databaseVersion }
	
	# For each of those files, run query on database
	foreach ($file in $files)
	{
		$fileName = $file.name
		Write-Host "Apply update script: $fileName"
		
		# Get-Content returns a string array of all the lines. We join that into a single string
		$fileContents = Get-Content "$file"
		$sql = [string]::Join([Environment]::NewLine, $fileContents);
		Execute-Sql-Query $connectionString $sql
		
		# Get this version number
		$version = [int]::Parse($fileName.Substring(0, 4))
	
		# Update the settings database with current version number
		Execute-Sql-Query $connectionString "UPDATE [Settings] SET [DatabaseVersion] = $version"
	}
}&lt;/pre&gt;
&lt;p&gt;Last, there's some helper functions for the functions used above.&lt;/p&gt;
&lt;pre class="brush:powershell"&gt;Function Get-Database-Version ([string]$connectionString)
{
	[System.Data.SqlClient.SqlConnection]::ClearAllPools()

	$sql = "SELECT TOP 1 [DatabaseVersion] FROM [Settings]"
	## Connect to the data source and open it
	$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
	$connection.Open()

	$command = New-Object System.Data.SqlClient.SqlCommand $sql,$connection
	$version = $command.ExecuteScalar();
	
	$connection.Close()
	$version
}

Function Validate-Connection ([string]$connectionString)
{
	[System.Data.SqlClient.SqlConnection]::ClearAllPools()
	
	try	{
		## Connect to the data source and open it
		$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
		$connection.Open()
		$connection.Close()
		$TRUE
	}
	catch {
		$FALSE
	}
}

Function Execute-Sql-Query ([string]$connectionString, [string]$sql)
{
	[System.Data.SqlClient.SqlConnection]::ClearAllPools()
	
	## Connect to the data source and open it
	$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
	$connection.Open()

	$server = New-Object Microsoft.SqlServer.Management.Smo.Server($connection)
	$server.ConnectionContext.ExecuteNonQuery($sql) | out-null
	
	$connection.Close()
}&lt;/pre&gt;
&lt;p&gt;Thanks to Gary Murphy for his contribution to Execute-Sql-Query, and getting it to work properly with GO-statements. You will find his blog at &lt;a href="http://garyjmurphy.com/"&gt;http://garyjmurphy.com/&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The whole script can be found in &lt;a href="https://bitbucket.org/bokmal/litemedia.databaseversioning" title="LiteMedia.DatabaseVersioning"&gt;its repository on bitbucket&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sun, 04 Dec 2011 17:00:47 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/database-versioning-updated</guid></item><item><title>Introducing Alive</title><link>http://www.litemedia.info:80/introducing-alive</link><description>&lt;p&gt;Alive is a performance counter monitor for ASP.NET. You install it in an IIS application and can view it from anywhere. It's free, it's open source and it's happy pappy.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/litemedia-alive.png" alt="" width="905" height="342" /&gt;&lt;/p&gt;
&lt;h2&gt;Prerequesits&lt;/h2&gt;
&lt;p&gt;Alive should work on any of the following.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;IIS 6.0, IIS 7.0, IIS 7.5 and IIS Express&lt;/li&gt;
&lt;li&gt;CLR 2.0, CLR 4&lt;/li&gt;
&lt;li&gt;Web browser client: Firefox, Chrome (not IE)&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Installation&lt;/h2&gt;
&lt;p&gt;There are several ways to install Alive described below. After the installation you should go to the Alive url.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;http://yoursite/Alive.axd/&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Project NuGet Installation&lt;/h3&gt;
&lt;p&gt;The NuGet package is designed to work well with Cassini, the build debug webserver in Visual Studio. That is why the NuGet package version is compiled for x86. This will probably not work well on your server, as most servers today is x64, but it was a design decision based on most developers are using Cassini as their primary web server during development.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://nuget.org/List/Packages/LiteMediaAlive"&gt;http://nuget.org/List/Packages/LiteMediaAlive&lt;/a&gt;&lt;/p&gt;
&lt;pre class="brush:plain"&gt;PM&amp;gt; Install-Package LiteMediaAlive&lt;/pre&gt;
&lt;p&gt;&lt;span class="Apple-style-span" style="font-size: 12px; font-weight: bold;"&gt;Server installation&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Go download the appropriate package from&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://code.google.com/p/litemedia-alive/downloads/list"&gt;http://code.google.com/p/litemedia-alive/downloads/list&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;The architecture x86/x64 has to match your server, and CLR version must match the application pool.&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Copy Alive.dll into your bin directory.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;Alive works through an HttpHandler. This means that you need to add a reference to the handler in your web.config.&lt;/div&gt;
&lt;h4&gt;IIS 6.0&lt;/h4&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;!-- IIS 6.0 Configuration --&amp;gt;
&amp;lt;system.web&amp;gt;
  &amp;lt;httpHandlers&amp;gt;
	&amp;lt;add path="Alive.axd" verb="*" type="LiteMedia.Alive.Handler, Alive"/&amp;gt;
  &amp;lt;/httpHandlers&amp;gt;
&amp;lt;/system.web&amp;gt;&lt;/pre&gt;
&lt;h4&gt;IIS 7.0+&lt;/h4&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;!-- IIS 7+ Configuration --&amp;gt;
&amp;lt;system.webServer&amp;gt;
  &amp;lt;handlers&amp;gt;
	&amp;lt;add name="Alive" path="Alive.axd" verb="*" type="LiteMedia.Alive.Handler, Alive"/&amp;gt;
  &amp;lt;/handlers&amp;gt;
&amp;lt;/system.webServer&amp;gt;&lt;/pre&gt;
&lt;h4&gt;Authorize your web application user to read performance counters&lt;/h4&gt;
&lt;p&gt;Before Alive can read performance counters off your system you need to grant it access. This means that&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;You need to run your application pool as a custom user&lt;/li&gt;
&lt;li&gt;You need to add that user to the group "Performance Monitor Users" on the local machine.&lt;br /&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/introducing-alive/alive-user-rights.png" alt="Alive user rights help image" width="777" height="416" /&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;em&gt;Installation scripts will be added to the project when I got the time.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;Configuration&lt;/h2&gt;
&lt;p&gt;Different installations of Windows might have different performance counters. Here's a default configuration to start from.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;configuration&amp;gt;
	&amp;lt;configSections&amp;gt;
		&amp;lt;sectionGroup name="alive" type="LiteMedia.Alive.Configuration, Alive"&amp;gt;
			&amp;lt;section name="settings" type="LiteMedia.Alive.SettingsSection, Alive"/&amp;gt;
			&amp;lt;section name="counters" type="LiteMedia.Alive.CountersSection, Alive"/&amp;gt;
		&amp;lt;/sectionGroup&amp;gt;
	&amp;lt;/configSections&amp;gt;	
	
  &amp;lt;alive&amp;gt;
    &amp;lt;settings columns="3" /&amp;gt;
    &amp;lt;counters&amp;gt;
      &amp;lt;groups&amp;gt;
        &amp;lt;group name="Hardware" updateLatency="1000"&amp;gt;
          &amp;lt;counter name="CPU" categoryName="Processor" counterName="% Processor Time" instanceName="_Total" /&amp;gt;
          &amp;lt;counter name="Memory" categoryName="Memory" counterName="Pages/sec" /&amp;gt;
        &amp;lt;/group&amp;gt;
        &amp;lt;group name="Memory" updateLatency="5000"&amp;gt;
          &amp;lt;counter name="RAM" categoryName="Memory" counterName="% Committed Bytes In Use" /&amp;gt;
          &amp;lt;counter name="Page file" categoryName="Paging File" counterName="% Usage" instanceName="_Total" /&amp;gt;
        &amp;lt;/group&amp;gt;
        &amp;lt;group name="ASP.NET Performance" updateLatency="1000"&amp;gt;
		  &amp;lt;counter name="Queued req." categoryName="ASP.NET" counterName="Requests Queued" /&amp;gt;
		  &amp;lt;counter name="Rejected req." categoryName="ASP.NET" counterName="Requests Rejected" /&amp;gt;
          &amp;lt;counter name="Requests/sec" categoryName="ASP.NET Applications" counterName="Requests/Sec" instanceName="__Total__" /&amp;gt;
        &amp;lt;/group&amp;gt;
		&amp;lt;group name="IIS" updateLatency="5000"&amp;gt;
		  &amp;lt;counter name="App Restarts" categoryName="ASP.NET" counterName="Application Restarts" /&amp;gt;
		  &amp;lt;counter name="Recycles" categoryName="ASP.NET" counterName="Worker Process Restarts" /&amp;gt;
		&amp;lt;/group&amp;gt;
		&amp;lt;group name="Errors" updateLatency="5000"&amp;gt;
		  &amp;lt;counter name="ASP.NET" categoryName="ASP.NET Applications" counterName="Errors Total" instanceName="__Total__" /&amp;gt;
		&amp;lt;/group&amp;gt;
		&amp;lt;group name="Session state server" updateLatency="5000"&amp;gt;
		  &amp;lt;counter name="Active" categoryName="ASP.NET" counterName="State Server Sessions Active" /&amp;gt;
		&amp;lt;/group&amp;gt;
      &amp;lt;/groups&amp;gt;
    &amp;lt;/counters&amp;gt;
  &amp;lt;/alive&amp;gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;
&lt;p&gt;Every group element is a chart. You can place several counters in each chart. You specify the counters with the following attributes&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;name = name of the counter in the chart&lt;/li&gt;
&lt;li&gt;categoryName = name of the performance counter category, called "Object" in the image below&lt;/li&gt;
&lt;li&gt;counterName = name of the performance counter, called "Counter" in the image below&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;(optional)&lt;/strong&gt; instanceName = name of the specific instance of this counter, called "Instance" in the image below&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Easiest way to find performance counters is through the performance monitor in Windows. Just type "perfmon" in Start/Run and you will get the following interface.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/introducing-alive/perfmon.png" alt="" width="880" height="429" /&gt;&lt;/p&gt;
&lt;h2&gt;Troubleshooting&lt;/h2&gt;
&lt;p&gt;Most common problem is that no counters are showing. When that happens, open up perfmon on the servern and verify that the counters aren't actually zero on the server. Now, this problem might relate to any of the following&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You're not running under full trust. Performance counters won't work under medium trust, period.&lt;/li&gt;
&lt;li&gt;Your IIS application pool identity is not a member of group "Performance Monitor Users" on the local machine.&lt;/li&gt;
&lt;li&gt;Your machine architecture x86/x64 does not match the compiled DLL Alive.dll. Exchange it with the correct one from here&lt;br /&gt;&lt;a href="http://code.google.com/p/litemedia-alive/downloads/list"&gt;http://code.google.com/p/litemedia-alive/downloads/list&lt;/a&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you've verified all these, you need to turn on application logging.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;Copy &lt;a href="http://netcommon.sourceforge.net/"&gt;Common.Logging.dll&lt;/a&gt;. &lt;a href="http://netcommon.sourceforge.net/"&gt;Common.Logging.Log4Net.dll&lt;/a&gt; and &lt;a href="http://logging.apache.org/log4net/"&gt;Log4Net.dll&lt;/a&gt; to your bin directory. Edit your web.config with the following additions.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;configuration&amp;gt;
  &amp;lt;configSections&amp;gt;
    &amp;lt;sectionGroup name="common"&amp;gt;
      &amp;lt;section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /&amp;gt;
    &amp;lt;/sectionGroup&amp;gt;
    &amp;lt;section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/&amp;gt;
  &amp;lt;/configSections&amp;gt;
  
  &amp;lt;common&amp;gt;
    &amp;lt;logging&amp;gt;
      &amp;lt;factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net"&amp;gt;
        &amp;lt;arg key="configType" value="INLINE" /&amp;gt;
      &amp;lt;/factoryAdapter&amp;gt;
    &amp;lt;/logging&amp;gt;
  &amp;lt;/common&amp;gt;

  &amp;lt;log4net&amp;gt;
    &amp;lt;appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"&amp;gt;
      &amp;lt;file value="logs\log.txt" /&amp;gt;
      &amp;lt;appendToFile value="true" /&amp;gt;
      &amp;lt;rollingStyle value="Size" /&amp;gt;
      &amp;lt;maximumFileSize value="1MB" /&amp;gt;
      &amp;lt;maxSizeRollBackups value="10" /&amp;gt;
      &amp;lt;layout type="log4net.Layout.PatternLayout"&amp;gt;
        &amp;lt;conversionPattern value="%date %-5level %logger - %message%newline" /&amp;gt;
      &amp;lt;/layout&amp;gt;
    &amp;lt;/appender&amp;gt;

    &amp;lt;appender name="AuditFileAppender" type="log4net.Appender.RollingFileAppender"&amp;gt;
      &amp;lt;file value="logs\activity.txt" /&amp;gt;
      &amp;lt;appendToFile value="true" /&amp;gt;
      &amp;lt;rollingStyle value="Size" /&amp;gt;
      &amp;lt;maximumFileSize value="1MB" /&amp;gt;
      &amp;lt;maxSizeRollBackups value="10" /&amp;gt;
      &amp;lt;layout type="log4net.Layout.PatternLayout"&amp;gt;
        &amp;lt;conversionPattern value="%date %-5level %logger - %message%newline" /&amp;gt;
      &amp;lt;/layout&amp;gt;
    &amp;lt;/appender&amp;gt;

    &amp;lt;logger name="alive-debug"&amp;gt;
      &amp;lt;level value="ALL" /&amp;gt;
      &amp;lt;appender-ref ref="LogFileAppender" /&amp;gt;
    &amp;lt;/logger&amp;gt;
    &amp;lt;logger name="alive-activity"&amp;gt;
      &amp;lt;level value="ALL" /&amp;gt;
      &amp;lt;appender-ref ref="AuditFileAppender" /&amp;gt;
    &amp;lt;/logger&amp;gt;
  &amp;lt;/log4net&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/pre&gt;
&lt;h2&gt;Credits&lt;/h2&gt;
&lt;p&gt;Alive is open source (&lt;a href="http://www.apache.org/licenses/LICENSE-2.0"&gt;Apache License&lt;/a&gt;) hosted on &lt;a href="http://code.google.com/p/litemedia-alive/"&gt;Google Code&lt;/a&gt;. It was created by me, &lt;a href="http://litemedia.info/about"&gt;Mikael Lundin&lt;/a&gt;, and written in F# server side and CoffeScript on the client. Comments and bug reports are more than welcome.&lt;/p&gt;</description><pubDate>Sun, 04 Dec 2011 11:19:15 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/introducing-alive</guid></item><item><title>Application logging for F#</title><link>http://www.litemedia.info:80/application-logging-for-fsharp</link><description>&lt;p&gt;Using existing log frameworks with F# is easy enough. Here's an example with log4net.&lt;/p&gt;
&lt;pre class="brush:fsharp;gutter:false"&gt;let log = log4net.LogManager.GetLogger("litemedia")
log.DebugFormat("Hello {0}, you are {1} years old", [|"Mikael", 30|])&lt;/pre&gt;
&lt;p&gt;Not very F#-ish now, is it. Looks like I've written C# in F# syntax. I would like to have a more Printf style of my logging messages.&lt;/p&gt;
&lt;pre class="brush:fsharp;gutter:false"&gt;Log.debug "Hello %s, you are %i years old" "Mikael" 30&lt;/pre&gt;
&lt;p&gt;We can easily accomplish this by wrapping the logging functionality in a module.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;module Log =
  let private _log = log4net.LogManager.GetLogger("litemedia")
  let debug format = Printf.ksprintf _log.Debug format&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/ee370231.aspx"&gt;ksprintf&lt;/a&gt; sends the result of &lt;a href="http://msdn.microsoft.com/en-us/library/ee370455.aspx"&gt;sprintf&lt;/a&gt; into the _log.Debug method. This is pretty simple stuff, but useful when you know how.&lt;/p&gt;</description><pubDate>Fri, 02 Dec 2011 05:46:27 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/application-logging-for-fsharp</guid></item><item><title>Debug SOAP request and response in WCF</title><link>http://www.litemedia.info:80/debug-soap-request-and-response-in-wcf</link><description>&lt;p&gt;Often while working with SOAP service integrations I would like to see the actual SOAP envelope that is passed around. This is not trivial while working with WCF, because it effectivly hide the implementation details. You'll will have to turn on WCF message debugging.&lt;/p&gt;
&lt;p&gt;That is done in web.config.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;
&amp;lt;configuration&amp;gt;
  &amp;lt;system.diagnostics&amp;gt;
    &amp;lt;sources&amp;gt;
      &amp;lt;source name="System.ServiceModel.MessageLogging"&amp;gt;
        &amp;lt;listeners&amp;gt;
          &amp;lt;add name="xml"/&amp;gt;
        &amp;lt;/listeners&amp;gt;
      &amp;lt;/source&amp;gt;
    &amp;lt;/sources&amp;gt;
    &amp;lt;sharedListeners&amp;gt;
      &amp;lt;add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="Traces.svclog" /&amp;gt;
    &amp;lt;/sharedListeners&amp;gt;
  &amp;lt;/system.diagnostics&amp;gt;

  &amp;lt;system.serviceModel&amp;gt;
    &amp;lt;diagnostics wmiProviderEnabled="true"&amp;gt;
      &amp;lt;messageLogging
           logEntireMessage="true"
           logMalformedMessages="true"
           logMessagesAtServiceLevel="true"
           logMessagesAtTransportLevel="true"
           maxMessagesToLog="3000"
       /&amp;gt;
    &amp;lt;/diagnostics&amp;gt;
  &amp;lt;/system.serviceModel&amp;gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;
&lt;p&gt;When you run your code a file called Traces.svclog should be created in your output directory. In a website this would be root of the site, and in a native application, this would be the bin folder.&lt;/p&gt;
&lt;p&gt;You can open it in &lt;a href="http://litemedia.info/wcf-the-connection-was-closed-unexpectedly"&gt;Microsoft Service Trace Viewer&lt;/a&gt; or just an ordinary text editor.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/mstv.png" alt="Microsoft Services Trace Viewer" width="763" height="728" /&gt;&lt;/p&gt;
&lt;p&gt;I find this very useful when dealing with services from other companies, where as I can really say - I'm sending this SOAP request and I'm recieving this response. That's not expected, is it?&lt;/p&gt;
&lt;p&gt;If you're having trouble getting this to work, you may look at &lt;a href="http://litemedia.info/media/Default/BlogPost/blog/LiteMedia.WCFDebugging.zip"&gt;my sample application&lt;/a&gt;, that fetches the currency conversion rate from an open webservice at&amp;nbsp;&lt;a href="http://www.webservicex.net/"&gt;http://www.webservicex.net&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Fri, 04 Nov 2011 06:13:11 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/debug-soap-request-and-response-in-wcf</guid></item><item><title>There were build errors. Would you like to continue and run the last successful build?</title><link>http://www.litemedia.info:80/there-were-build-errors.-would-you-like-to-continue-and-run-the-last-successful-build</link><description>&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/dialog.png" alt="Visual Studio error dialog" width="454" height="169" /&gt;&lt;/p&gt;
&lt;p&gt;No.&lt;/p&gt;
&lt;p&gt;Let me say that again.&lt;/p&gt;
&lt;p&gt;No.&lt;/p&gt;
&lt;p&gt;I can't believe how many times I've pushed "No" on this dialog. I really can't remember any time that I've pressed 'Yes'. Why is it even there? Is there somone that chooses to press 'Yes' on in this dialog? If you've changed something in the source code, and try to start the site in Debug mode, wouldn't you be interested in the changes? Wouldn't the ability to test the changes be the sole reason for you to start this site in Debug mode?&lt;/p&gt;
&lt;p&gt;I learned recently that you can turn this dialog off, globally in Visual Studio, and not just the solution that you're in.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Go to menu Tools/Options&lt;/li&gt;
&lt;li&gt;Project and Solutions / Build and Run&lt;/li&gt;
&lt;li&gt;On Run, when build or deployment errors occur&lt;br /&gt;=&amp;gt; Select Do not launch&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/options_dialog.png" alt="Visual studio options dialog" width="757" height="440" /&gt;&lt;/p&gt;
&lt;p&gt;Away with you, evil stupid dialog.&lt;/p&gt;</description><pubDate>Thu, 03 Nov 2011 16:58:22 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/there-were-build-errors.-would-you-like-to-continue-and-run-the-last-successful-build</guid></item><item><title>Git productive in TFS</title><link>http://www.litemedia.info:80/git-productive-in-tfs</link><description>&lt;p&gt;Have you ever used TFS (Microsoft Team Foundation System) in a day to day basis? I'm sure its all fine and dandy for managers, but as a developer the revision control system of TFS gives me headaches. One or two reasons for this are...&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Workspaces, where TFS will make all files readonly until you 'touch' them in Visual Studio 2010, trigger a 'check out for edit' which make your files writable. Works fine except...&lt;/li&gt;
&lt;li&gt;TFS makes working in Visual Studio terrible slow. When you want to change a file it must first be checked out for edit by TFS (syncronously), and this does not happen on save - but on actual edit.&lt;/li&gt;
&lt;li&gt;You accidently check out files for edit when you didn't intend to edit the file, or save your changes.&lt;/li&gt;
&lt;li&gt;Edit files outside Visual Studio means manually doing a 'check out for edit' in the Source Control Manager to get rid of the readonly attribute to files.&lt;/li&gt;
&lt;li&gt;The readonly attribute also has a way of finding itself in build servers, and production environment after copy operations. This can be a pain during continuous integration.&lt;/li&gt;
&lt;li&gt;Sometimes you find yourself working offline, but you're not able to commit your changes without connection to your TFS. That's ok, but if you forget to press "Go Offline" before you loose connection, you will have Visual Studio crashing all over the place. Imagine working over cellular network where the connection comes and goes - it's impossible with TFS.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Nice to get that off my chest.&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;But TFS11 will solve those problems?&lt;/h2&gt;
&lt;p&gt;Yes, you will be able to have local workspaces in TFS11, but this will not be a DVCS as you will not be able to commit changes or merge branches while offline. All the work you'll do in your local workspace has to be synced with the TFS from time to time. I can imagine the headaches of merging local workspace with online workspace after a long period of offline work.&lt;/p&gt;
&lt;h2&gt;How to get going with git&lt;/h2&gt;
&lt;p&gt;The solution to the TFS problem is not using it for revision control, but only as centralized storage for Git.&amp;nbsp;Here I will describe how to install git and explain my workflow with git and tfs.&lt;/p&gt;
&lt;h3&gt;Installation&lt;/h3&gt;
&lt;p&gt;Head over to the git homepage and install git itself. This will give you the binaries that you need to use git.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://git-scm.com/"&gt;http://git-scm.com/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You need to install the Git-Tfs gateway in order to push and pull commits between Git and Tfs.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/spraints/git-tfs/"&gt;https://github.com/spraints/git-tfs/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The latest version at the time of writing this blog post is 0.12, and it has a defect of not being able to handle files with filenames not in ASCII. If you need to handle filenames with characters not in ASCII you should instead download the code from github and compile head version yourself. They've fixed it in there. Any version of Git-Tfs after 0.12 should have this problem fixed.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;In order to get git to recognize the git-tfs extension they both need to be in the global environment path. The following figure explains where to find and edit this path variable.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/git-productive-in-tfs/gitpath.png" alt="Go edit your environment variable PATH" width="640" height="425" style="border-style: initial; border-color: initial;" /&gt;&lt;/p&gt;
&lt;p&gt;I've added this value to the variable.&lt;/p&gt;
&lt;pre class="brush:plain"&gt;C:\Dev\Console2;C:\cygwin\bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\GitTfs&lt;/pre&gt;
&lt;p&gt;I use Cygwin and Console2 to enlighten my git experience.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.cygwin.com/"&gt;http://www.cygwin.com/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://sourceforge.net/projects/console/files/console-devel/2.00/"&gt;http://sourceforge.net/projects/console/files/console-devel/2.00/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For those that find console applications intimidating, should try the graphical tool called TortoiseGit. I've not tried it myself, but heard from colleages that it gives you an almost as good experience as working directly with the console.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://code.google.com/p/tortoisegit/"&gt;http://code.google.com/p/tortoisegit/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/git-productive-in-tfs/tortoise_log_dialog.jpg" alt="tortoise git log dialog" width="400" height="327" /&gt;&lt;/p&gt;
&lt;h3&gt;Workflow&lt;/h3&gt;
&lt;p&gt;Working with git is not the same as working with TFS. You need to rethink the way you normaly do version control. Git is about versioning your code. Tfs is as much about centralizing your code, storing it all in one place.&lt;/p&gt;
&lt;p&gt;When I was working with TFS, I would check in my work when I was done with a feature. Now when I work with Git, I will commit every change I do to the source code. I still push my completed user stories to TFS when they are done, so the frequency of my TFS checkins are not depleted, but I commit to git for every little change, giving me a complete history of 'fixing that bug' or 'completing that function'.&lt;/p&gt;
&lt;p&gt;First you clone your TFS repository.&lt;/p&gt;
&lt;pre class="brush:plain"&gt;git tfs clone http://tfsserver:8080/DefaultCollection/ $/Path/In/Source/Control ProjectPath&lt;/pre&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/git-productive-in-tfs/gitwf1.png" alt="git workflow clone" width="346" height="92" /&gt;&lt;/p&gt;
&lt;p&gt;This will give you a complete copy of the whole TFS history for that TFS path into ProjectPath. If you have a lot of history, and a lot of files, you need to be patient while all this is downloading. Thankfully you'll only have to do this once.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;STOP!&lt;/strong&gt; Yes, you have the code, but don't start coding just yet. You have a git repository and a master branch. The thing is, you never code directly into master branch. Instead you create a branch for every user story or bug you need to fix. Do it like this.&lt;/p&gt;
&lt;p&gt;git checkout &amp;ndash;b my_new_feature&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/git-productive-in-tfs/gitwf2.png" alt="git workflow checkout new branch" width="657" height="165" /&gt;&lt;/p&gt;
&lt;p&gt;This will create a new branch called "my_new_feature" and make it active. Now you can start development of your feature.&lt;/p&gt;
&lt;p&gt;The three most important commands while developing your feature are status, add and commit.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;git status = display what has changed&lt;/li&gt;
&lt;li&gt;git add = stage changes for commit&lt;/li&gt;
&lt;li&gt;git commit = commit staged changes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let's commit a change to our new branch.&lt;/p&gt;
&lt;pre class="brush:plain"&gt;git commit -a -m "Test: Should do awesome when condition is satisfied"&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/git-productive-in-tfs/gitwf3.png" alt="git workflow commit" width="657" height="263" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;What did happen during development of my_new_feature is that a coworker checked in his changes to TFS. Now we want to pull them out and update our branch with his changes. We du this with a tfs pull and rebase.&lt;/p&gt;
&lt;pre class="brush:plain"&gt;git checkout master
git tfs pull
git checkout my_new_feature
git rebase master&lt;/pre&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/git-productive-in-tfs/gitwf4.png" alt="git workflow rebase" width="516" height="275" /&gt;&lt;/p&gt;
&lt;p&gt;What happens when you rebase a branch is that you rewind all commits, rebase the branch on the new version in master, and then reapply your commits to that branch. You will get conflicts if you have made commits to the same stuff as what you pulled from tfs. A great aspect of this workflow is that the conflict will arise in a local branch where it won't affect other development if you would need to create a new branch before solving the conflict.&lt;/p&gt;
&lt;p&gt;When you're done with your new feature, you should merge it to master and from there we could push it back into TFS, which is effectivly a TFS checkin.&lt;/p&gt;
&lt;pre class="brush:plain"&gt;git checkout master
git merge my_new_feature
git tfs checkintool --build-default-comment&lt;/pre&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/git-productive-in-tfs/gitwf5.png" alt="git workflow merge push" width="566" height="536" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2&gt;What are the benefits of working with git?&lt;/h2&gt;
&lt;p&gt;This workflow seems to give you a lot of overhead. Should it be this hard to just manage versioning of software. Do you really get back all the time you invest in creating branches and merging back and forth?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You always have a clean master. When the customer comes to you with "drop everything you're doing, we need to do 'this' instead", you'll actually be able to do just that.&lt;/li&gt;
&lt;li&gt;You're actually doing versioning, and not 'checkin at end of the day to keep a backup of your code' as I've seen many developers treat TFS&lt;/li&gt;
&lt;li&gt;You work completely offline and may still do versioning. This has been a real issue for me while developing on the commute train.&lt;/li&gt;
&lt;li&gt;You can branch, commit and do versioning without disturbing build server or colleages with your checkins.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Using git with TFS is probably the closest you can get, having a decent experience with TFS version source control, even if that means taking away 'version' and 'control' from the Team Foundation System.&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:03 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/git-productive-in-tfs</guid></item><item><title>Using TDD to test file system operations</title><link>http://www.litemedia.info:80/unit-test-file-system-operations</link><description>&lt;p&gt;&lt;em&gt;I will refer to SUT during this article, meaning "System Under Test". In this case it will be the synchronize functionality in the FileSystemSynchronizer class.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A friend of mine asked me how I would unit test file system operations. The answer is that System.IO is not very test friendy and you will have to implement wrappers around it. This is not very hard, only time consuming and it gives you an additional layer of complexity. I would do this if I had to do a lot of file operations that needed testing, or if those file operations where important enough.&lt;/p&gt;
&lt;p&gt;First we need a purpose. Let's say that we're going to build an application that's going to synchronize files in two file folders by pushing changes from source to target.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class FileSystemSynchronizer
{
    public void Synchronize(string source, string destination)
    {
    }
}&lt;/pre&gt;
&lt;p&gt;Before we do anything else we should ask ourselves what we need this routine to accomplish. We do this by defining tests.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class FileSystemSynchronizerSpecification
{
    [Fact]
    public void ShouldCreateTargetFolderIfDoesNotExist()
    {
    }

    [Fact]
    public void ShouldCopyAnyFilesFromSourceFolderToTargetFolder()
    {
    }

    [Fact]
    public void ShouldCopyAnyDirectoriesFromSourceFolderToTargetFolder()
    {
    }

    [Fact]
    public void ShouldCopyFilesAndFoldersRecursivlyFromSourceToTargetFolder()
    {
    }

    [Fact]
    public void ShouldNotCopySourceFileIfSameFileExistInTargetFolder()
    {
    }

    [Fact]
    public void ShouldCopySourceFileIfNewerThanFileInTargetFolder()
    {
    }

    [Fact]
    public void ShouldRemoveFilesFromTargetFolderNotPresentInSourceFolder()
    {
    }
}&lt;/pre&gt;
&lt;p&gt;Now we could just implement these tests and the wrapper situation should resolve itself?&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;[Fact]
public void ShouldCreateTargetFolderIfDoesNotExist()
{
    const string SourcePath = @"C:\FolderA";
    const string TargetPath = @"C:\FolderB";

    /* Setup */
    var factory = MockRepository.GenerateMock&amp;lt;IFileSystemFactory&amp;gt;();
    var sut = new FileSystemSynchronizer(factory);

    /* Arrange */
    factory.Expect(f =&amp;gt; f.PathExists(TargetPath)).Return(false);

    /* Test */
    sut.Synchronize(SourcePath, TargetPath);

    /* Assert */
    factory.AssertWasCalled(f =&amp;gt; f.MakeDirectory(TargetPath));
}&lt;/pre&gt;
&lt;p&gt;Do you find it hard to write tests before writing the code? Well, it is meant to be hard, because you should consider why you write the code in the first place.&lt;/p&gt;
&lt;p&gt;I've created something I call the IFileSystemFactory and that class knows how to check if a path exists and it knows how to create directories. In this test I expect PathExists to be called and return false from it, and then I verify that a directory is created.&lt;/p&gt;
&lt;p&gt;As you run this test it will turn red, but as you write the implementation it should turn green.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class FileSystemSynchronizer
{
    private readonly IFileSystemFactory fsFactory;

    public FileSystemSynchronizer(IFileSystemFactory fsFactory)
    {
        this.fsFactory = fsFactory;
    }

    public void Synchronize(string sourcePath, string targetPath)
    {
        if (!fsFactory.PathExists(targetPath))
        {
            fsFactory.MakeDirectory(targetPath);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/unit-test-file-system-operations/unittest.png" alt="" width="539" height="245" /&gt;&lt;/p&gt;
&lt;p&gt;The last step is to refactor, but I think I will wait until I have something to refactor. This code is still quite simple and clean.&lt;/p&gt;
&lt;p&gt;Let's implement that next test.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;[Fact]
public void ShouldCopyAnyFilesFromSourceFolderToTargetFolder()
{
    /* Setup */
    var factory = MockRepository.GenerateMock&amp;lt;IFileSystemFactory&amp;gt;();
    var sut = new FileSystemSynchronizer(factory);

    var targetDirectory = MockRepository.GenerateStub&amp;lt;IDirectory&amp;gt;();

    var file1 = MockRepository.GenerateMock&amp;lt;IFile&amp;gt;();
    file1.Name = "first.txt";

    var file2 = MockRepository.GenerateMock&amp;lt;IFile&amp;gt;();
    file2.Name = "second.txt";

    var fileList = new[] { file1, file2 };

    /* Arrange */
    factory.Expect(f =&amp;gt; f.PathExists(TargetPath)).Return(true);
    factory.Expect(f =&amp;gt; f.GetDirectory(SourcePath)).Return(targetDirectory);
    targetDirectory.Files = fileList;

    /* Test */
    sut.Synchronize(SourcePath, TargetPath);

    /* Assert */
    foreach (var file in fileList)
    {
        file.AssertWasCalled(f =&amp;gt; f.CopyTo(TargetPath));
    }
}&lt;/pre&gt;
&lt;p&gt;And the SUT to make it green.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class FileSystemSynchronizer
{
    private readonly IFileSystemFactory fsFactory;

    public FileSystemSynchronizer(IFileSystemFactory fsFactory)
    {
        this.fsFactory = fsFactory;
    }

    public void Synchronize(string sourcePath, string targetPath)
    {
        if (!fsFactory.PathExists(targetPath))
        {
            fsFactory.MakeDirectory(targetPath);
        }

        foreach (var file in fsFactory.GetDirectory(sourcePath).Files)
        {
            file.CopyTo(targetPath);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;And we're green, but .... THIS IS CRAP!&lt;/p&gt;
&lt;h2&gt;Overspecification is the hell of unit testing&lt;/h2&gt;
&lt;p&gt;What I did just now was not testing the function, but specifying the internals of the function. This is very dangerous, because I can't refactor without changing my tests. You should always try to test only the public api, and you should not bother with the internals. Instead you should look at the output after SUT has been run.&lt;/p&gt;
&lt;p&gt;That means that we'll have to rethink and refactor our tests.&lt;/p&gt;
&lt;p&gt;Let's create a virtual simulation of our file system instead, and fill it with files. Our virtual directory as source should be replicated into our virtual target path. This means a bit more implementation in the test, but we can limit the testing to Input/Output without overspecifying internals.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class VirtualFileSystemFactory : IFileSystemFactory
{
    public static readonly IDirectory FolderA;
    public static readonly IDirectory FolderB;

    private const string FolderAPath = @"C:\FolderA";
    private const string FolderBPath = @"C:\FolderB";

    private readonly IDictionary&amp;lt;string, IDirectory&amp;gt; fileSystem = new Dictionary&amp;lt;string, IDirectory&amp;gt;
        {
            { FolderAPath, FolderA },
            { FolderBPath, FolderB },
        };

    static VirtualFileSystemFactory()
    {
        FolderA = new VirtualFolder(FolderAPath);
        FolderB = new VirtualFolder(FolderBPath);
    }

    public bool PathExists(string targetPath)
    {
        return fileSystem.ContainsKey(targetPath);
    }

    public void MakeDirectory(string targetPath)
    {
        fileSystem.Add(targetPath, new VirtualFolder(targetPath));
    }

    public IDirectory GetDirectory(string sourcePath)
    {
        if (!this.PathExists(sourcePath))
        {
            throw new DirectoryNotFoundException("Folder was not registered in VirtualFileSystemFactory: " + sourcePath);
        }

        return fileSystem[sourcePath];
    }

    public void Copy(IFile file, string targetPath)
    {
        this.GetDirectory(targetPath).Add(file);
    }
}

public class VirtualFile : IFile
{
    public VirtualFile(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}

public class VirtualFolder : IDirectory, IEnumerable&amp;lt;IFileSystemItem&amp;gt;
{
    private readonly string path;
    private readonly IList&amp;lt;IFileSystemItem&amp;gt; items;

    public VirtualFolder(string path)
    {
        this.path = path;
        items = new List&amp;lt;IFileSystemItem&amp;gt;();
    }

    public IEnumerable&amp;lt;IFile&amp;gt; Files
    {
        get { return items.Where(f =&amp;gt; f is IFile).Cast&amp;lt;IFile&amp;gt;(); }
    }

    public void Add(IFile file)
    {
        items.Add(file);
    }

    public IEnumerator&amp;lt;IFileSystemItem&amp;gt; GetEnumerator()
    {
        return items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return items.GetEnumerator();
    }
}
&lt;/pre&gt;
&lt;p&gt;That is a lot of code, but it is testing code. This will actually give us the power to not overspecify our tests, but work with the results of the method we're testing.&lt;/p&gt;
&lt;p&gt;Look how this beautified the tests that where previously a mocking hell.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;[Fact]
public void ShouldCreateTargetFolderIfDoesNotExist()
{
    const string UnknownTargetPath = @"C:\FolderC";

    /* Setup */
    var factory = new VirtualFileSystemFactory();
    var sut = new FileSystemSynchronizer(factory);

    /* Test */
    sut.Synchronize(SourcePath, UnknownTargetPath);

    /* Assert */
    Assert.True(factory.PathExists(UnknownTargetPath), "Target path should be created if it does not exist");
}

[Fact]
public void ShouldCopyAnyFilesFromSourceFolderToTargetFolder()
{
    /* Setup */
    var factory = new VirtualFileSystemFactory();
    var sut = new FileSystemSynchronizer(factory);

    // Create files in source folder
    var sourceFolder = factory.GetDirectory(SourcePath);
    sourceFolder.Add(new VirtualFile("first.txt"));
    sourceFolder.Add(new VirtualFile("second.txt"));

    /* Test */
    sut.Synchronize(SourcePath, TargetPath);

    /* Assert */
    var targetFolder = factory.GetDirectory(TargetPath);
    foreach (var file in sourceFolder.Files)
    {
        Assert.Contains(file, targetFolder.Files);
    }
}&lt;/pre&gt;
&lt;p&gt;These tests are great, because they won't break when we refactor our SUT. They are great because they are readable and you don't have to be Ayende to figure out how the mocking works.&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;What about wrapping the file system?&lt;/h2&gt;
&lt;p&gt;If I &lt;a href="http://litemedia.info/media/Default/BlogPost/blog/unit-test-file-system-operations/LiteMedia.FileSync.zip"&gt;finish writing my tests and implementing my system&lt;/a&gt;, I will end up with a file system wrapping that looks like this.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/unit-test-file-system-operations/ClassDiagram1.png" alt="" width="619" height="446" /&gt;&lt;/p&gt;
&lt;p&gt;We did wrap the file system. The wrapping layer grew fourth from what my tests needed. This means that it would probably not look the same if we had a different problem to solve. Then the wrapping layer would be suited for that problem instead.&lt;/p&gt;
&lt;p&gt;Originating from the problem description and let the API grow from our tests, gave us a wrapping layer that both looks and feels natural to the problem at hand. I could never have anticipated this design, it has to be hand grown and it has to be done with TDD.&lt;/p&gt;
&lt;p&gt;You can &lt;a href="http://litemedia.info/media/Default/BlogPost/blog/unit-test-file-system-operations/LiteMedia.FileSync.zip"&gt;download the complete sample from here&lt;/a&gt;. Do I need to mention that it worked flawless on the first run?&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:03 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/unit-test-file-system-operations</guid></item><item><title>Coverage is a broken metric</title><link>http://www.litemedia.info:80/coverage-is-a-broken-metric</link><description>&lt;p&gt;In the backwaters of previous blog entry, &lt;a href="http://litemedia.info/unit-test-file-system-operations"&gt;Using TDD to test file system operations&lt;/a&gt;, I've been thinking alot about test coverage. This is the metric you use to measure how many lines of code % you traverse with your tests.&lt;/p&gt;
&lt;p&gt;This metric is meant to tell you&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;How much of the application you've tested&lt;/li&gt;
&lt;li&gt;If you need to write more tests&lt;/li&gt;
&lt;li&gt;When you're done testing&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Unfortunatly it does not do these things.&lt;/p&gt;
&lt;p&gt;Our dear Uncle Bob propagates 100% coverage at all times. This is not very sane. Some tests are just useless. Take my previous blog post as an example. What would it gain us to test the following implementation of the file system wrapper?&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public bool PathExists(string targetPath)
{
    return Directory.Exists(targetPath);
}&lt;/pre&gt;
&lt;p&gt;In a matter of tests "driving the design", we're already done with that part. In a matter of regression testing, don't even go there. The only thing you would test here is that System.IO is doing what it is supposed to, and that is not your job. That is up to Microsoft to verify.&lt;/p&gt;
&lt;p&gt;Every test you write must give you more value, compared to the cost of writing the test. This means that doing focused testing on the following things is just creating waste.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Wrapper classes&lt;/li&gt;
&lt;li&gt;Constructors&lt;/li&gt;
&lt;li&gt;Generated proxy classes (WCF services)&lt;/li&gt;
&lt;li&gt;Trivial property setters and getters&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;If you accidently traverse these while running specifications that's fine. That takes us on to the real topic here.&lt;/div&gt;
&lt;h2&gt;What to test?&lt;/h2&gt;
&lt;p&gt;You should not test how your application operates, but confirm that it does what it is supposed to.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Test the 'what' not the 'how'.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;Why? Because if you focus on testing 'what', your tests won't break when you refactor your code, because you changed how to do things. As long as your program &lt;strong&gt;behavior&lt;/strong&gt; stays the same your tests will stay green. This is incredible valuable as test maintenance is an incredible waste. Your tests should do two things&lt;/div&gt;
&lt;div&gt;&lt;ol&gt;
&lt;li&gt;Drive the design&lt;/li&gt;
&lt;li&gt;Verify system behavior&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;Everything else is a waste.&lt;/div&gt;
&lt;h2&gt;Testing system behavior&lt;/h2&gt;
&lt;p&gt;This means that we don't have tests called "CalculatorTest" or "NamePropertyShouldGetSameValueAsWasSet" because this does not test system behavior. Instead our tests looks like this.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;CreateTargetFolderIfDoesNotExist&lt;/li&gt;
&lt;li&gt;CopyAnyFilesFromSourceFolderToTargetFolder&lt;/li&gt;
&lt;li&gt;CopyAnyDirectoriesFromSourceFolderToTargetFolder&lt;/li&gt;
&lt;li&gt;CopyFilesAndFoldersRecursivlyFromSourceToTargetFolder&lt;/li&gt;
&lt;li&gt;NotCopySourceFileIfSameFileExistInTargetFolder&lt;/li&gt;
&lt;li&gt;CopySourceFileIfNewerThanFileInTargetFolder&lt;/li&gt;
&lt;li&gt;RemoveFilesFromTargetFolderNotPresentInSourceFolder&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;p&gt;All in all I have a coverage of 34%. Why? Because I have a wrapping layer that enables me to test the system without hitting the file system. I'm not testing that the wrapping layer is correclty mapped against System.IO, because that is not a part of the system specification, it is just a side effect of testing and a waste to test.&lt;/p&gt;
&lt;h2&gt;Coverage does not prove the code to be correct&lt;/h2&gt;
&lt;p&gt;Complete coverage does not mean that you're done testing.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public double Divide(int a, int b)
{
    return a / b;
}

[Fact]
public void DivideTest()
{
    Assert.Equal(2, this.Divide(4, 2));
}&lt;/pre&gt;
&lt;p&gt;Yes, this gives you 100% coverage, but the question stands, is the code correct? Is Divide(5, 2) == 2 expected behavior? We write specifications to decide what behavior to expect from the system.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;ShouldDivideNumbersWithAnIntegerResult&lt;/li&gt;
&lt;li&gt;ShouldDivideNumbersWithFloatNumberResult&lt;/li&gt;
&lt;li&gt;ShouldReturnZeroOnDivideWithZero&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Two last specifications were not proven with our previous test and might cause unexpected behavior from our program. Implementing these specifications would mean that we have 300% coverage on Divide, but does that mean that it is fully covered? &lt;strong&gt;Still no.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Even Uncle Bob &lt;a href="http://twitter.com/#!/unclebobmartin/status/55979248879538176"&gt;admits it&lt;/a&gt;. "100% code coverage does not mean your code is correct. It _does_ mean that you tried."&lt;/p&gt;
&lt;h2&gt;Conclusions about test coverage&lt;/h2&gt;
&lt;p&gt;Focus on verifying that your system does what it is supposed to do. Don't worry about coverage, it will not tell you if you're done testing. It can't tell you if you've proven your program to be correct and it will not tell you the quality of your tests.&lt;/p&gt;
&lt;p&gt;Instead you should&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Write a specification (red)&lt;/li&gt;
&lt;li&gt;Implement that specification (green)&lt;/li&gt;
&lt;li&gt;Refactor!&lt;/li&gt;
&lt;/ul&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:03 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/coverage-is-a-broken-metric</guid></item><item><title>Infinite sequence of primes</title><link>http://www.litemedia.info:80/infinite-sequence-of-primes-by-sequence-expressions</link><description>&lt;p&gt;I've been writing algorithms for calculating primes since high school. Most of those algorithms have looked the same, but in different languages with that language's specific quirks. It was when I read up on F# sequence expressions that my mind was blown, and I went &lt;strong&gt;holy bananas&lt;/strong&gt;&amp;nbsp;as I could see the solution to a prime calculation problem I've had since I started.&lt;/p&gt;
&lt;h2&gt;Is 15485867 a prime?&lt;/h2&gt;
&lt;p&gt;Yes, it is. How would I know that? I must decide that the number is not evenly divisible by any prime number up to the square root of that number (3935). Here comes the problem. I would have to know every prime up to 3935, to make sure that 15485867 is a prime.&lt;/p&gt;
&lt;p&gt;For every number up to 3935 I have to divide by any prime up to the square root of that number. It looks like I would have to carry around a list of prime numbers in order to calculate any other prime number.&lt;/p&gt;
&lt;p&gt;(you could also use the &lt;a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes"&gt;sieve of eratosthenes&lt;/a&gt; for getting primes up to a certain top limit)&lt;/p&gt;
&lt;h2&gt;Sequences&lt;/h2&gt;
&lt;p&gt;Instead I was going to use sequences. What is a sequence? It could be numbers where you would say "give me next" and you would get the next number until you reach the end. The thing about sequences is that you always move next. So when you want the third element, you would have to take next element three times.&lt;/p&gt;
&lt;p&gt;What's so special about sequences is that they can be infinite. If you have a function that calculates the next element, the sequence does not have to have an end. If you calculate the sequence lazily, you would also be able to pass the infinite sequence around like any other object reference.&lt;/p&gt;
&lt;p&gt;Sequence in C#&lt;/p&gt;
&lt;pre class="brush:csharp;gutter:false"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/pre&gt;
&lt;p&gt;Sequence in F#&lt;/p&gt;
&lt;pre class="brush:fsharp;gutter:false"&gt;seq&amp;lt;'a&amp;gt;&amp;nbsp;&lt;/pre&gt;
&lt;h2&gt;Creating sequences&lt;/h2&gt;
&lt;p&gt;In F# you use sequence expressions to create sequences.&lt;/p&gt;
&lt;pre class="brush:fsharp;gutter:false"&gt;seq { for n in 0..100 do yield n }&lt;/pre&gt;
&lt;p&gt;This creates a simple sequence ranging from 0 to 100. You can do the same in C#.&lt;/p&gt;
&lt;pre class="brush:csharp;gutter:false"&gt;Enumerable.Range(0, 100)&lt;/pre&gt;
&lt;p&gt;But sequence expressions are a bit more powerful than that. You can use yield! (bang!) to bind together sequences.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;  seq { 
    yield 0
    yield! [1; 2; 3]
    yield! [4; 5; 6]
    yield! [7; 8; 9]
  }&lt;/pre&gt;
&lt;p&gt;So what about this?&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;  let rec alternating = 
    seq {
      yield true
      yield false
      yield! alternating
    }&lt;/pre&gt;
&lt;pre&gt;val it : seq&amp;lt;bool&amp;gt; = seq [true; false; true; false; ...]&lt;/pre&gt;
&lt;p&gt;Not very surprising, this code generates an infinite sequence of alternating true/false. But why doesn't it stuck and loop forever generating the sequence? Because yield! is lazy and won't generate next true/false until you request it.&lt;/p&gt;
&lt;h2&gt;Infinitive sequence of primes&lt;/h2&gt;
&lt;p&gt;As I was reading about recursive sequence expressions my mind went, &lt;em&gt;"could I create an infinite sequence of prime numbers?"&lt;/em&gt;. It took me a good part of a day, but here's my solution.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;let rec primes = 
  let isPrime number primes =
    let sqrtn = float &amp;gt;&amp;gt; sqrt &amp;gt;&amp;gt; int
    primes
  	  |&amp;gt; Seq.takeWhile (fun n -&amp;gt; n &amp;lt;= (sqrtn number))
  	  |&amp;gt; Seq.exists (fun n -&amp;gt; number % n = 0)
	  |&amp;gt; not

  let rec primes' current =
    seq {
  	  if primes |&amp;gt; isPrime current then
	    yield current
	  yield! primes' (current + 2)
    }
  seq {
    yield 2
    yield! primes' 3
  } |&amp;gt; Seq.cache&lt;/pre&gt;
&lt;p&gt;Let's break it down. We have an outer and inner sequence.&lt;/p&gt;
&lt;pre class="brush:fsharp;first-line:15"&gt;  seq {
    yield 2
    yield! primes' 3
  } |&amp;gt; Seq.cache&lt;/pre&gt;
&lt;p&gt;The outer sequence yields the number 2 as the first prime and then calls inner function to generate primes 3 and up.&lt;/p&gt;
&lt;pre class="brush:fsharp;first-line:9"&gt;  let rec primes' current =
    seq {
  	  if primes |&amp;gt; isPrime current then
	    yield current
	  yield! primes' (current + 2)
    }
&lt;/pre&gt;
&lt;p&gt;The inner function yields current number if it is prime. If it is not prime it will recurse by adding current number with 2. (next test is 5)&lt;/p&gt;
&lt;pre class="brush:fsharp;first-line:2"&gt;  let isPrime number primes =
    let sqrtn = float &amp;gt;&amp;gt; sqrt &amp;gt;&amp;gt; int
    primes
  	  |&amp;gt; Seq.takeWhile (fun n -&amp;gt; n &amp;lt;= (sqrtn number))
  	  |&amp;gt; Seq.exists (fun n -&amp;gt; number % n = 0)
	  |&amp;gt; not&lt;/pre&gt;
&lt;p&gt;The inner isPrime function is not very complicated. It takes number to be tested as argument, as well as a sequence of primes up to this number. If the number is not divisible with any prime up to square root of itself, this should also be a prime.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;But hey!&lt;/strong&gt; Where does that sequence of primes come from? As you can see on line 11, the sequence of primes are actually a recursive call to the sequence we're about to create.&lt;/p&gt;
&lt;h3&gt;Crazy talk&lt;/h3&gt;
&lt;p&gt;As long as we don't try to check primeness of the same number in the recursion as we try to test for isPrime, we won't get into an infinite recursion. We make sure of that by only divide current number up to &lt;strong&gt;the square root&lt;/strong&gt; of that number.&lt;/p&gt;
&lt;p&gt;This becomes extremely ineffective since we need to recalculate the sequence and every prime up to square root of the number on recursion. That is why I've added &lt;strong&gt;Seq.cache&lt;/strong&gt; on line 18. This will cache already calculated primes in the sequence and return them directly. This makes the code, not only beautiful to look at, but also pretty fast.&lt;/p&gt;
&lt;h2&gt;Is 15485867 a prime?&lt;/h2&gt;
&lt;p&gt;It is actually the 1 millionth and 1 prime.&lt;/p&gt;
&lt;pre class="brush:fsharp;gutter:false"&gt;primes |&amp;gt; Seq.nth(1000000)&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(zero based indexer)&lt;/em&gt;&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:02 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/infinite-sequence-of-primes-by-sequence-expressions</guid></item><item><title>Dependency Injection in ASP.NET WebForms</title><link>http://www.litemedia.info:80/dependency-injection-in-asp.net-webforms</link><description>&lt;p&gt;To me, any webforms solution is legacy code. Sadly, most of my consultancy happens to be maintenance of these webforms behemoths. Even so, that doesn't stop me from trying to improve my own work process and the applications that I'm working with.&lt;/p&gt;
&lt;p&gt;One huge improvement have been dependency injection into webforms page object. This has made the asp pages much easier to unit test.&amp;nbsp;Here's a small guide on how to do dependency injection in a legacy webforms application with Unity.&lt;/p&gt;
&lt;h2&gt;Unity HttpModule&lt;/h2&gt;
&lt;p&gt;The trick is to hook into ASP.NET life cycle when the page tree structure is built up. We can do this with an HttpModule.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class UnityHttpModule : IHttpModule
{
	private const string NamespacePrefix = "DIWebFormsExample";
	
	public void Init(HttpApplication context)
	{
		context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
	}

	public void Dispose()
	{
		// Nothing to dispose
	}

	// Get the controls in the page's control tree excluding the page itself
	private static IEnumerable GetControlTree(Control root)
	{
		foreach (Control child in root.Controls)
		{
			yield return child;
			foreach (Control c in GetControlTree(child))
			{
				yield return c;
			}
		}
	}

	private static void OnPreRequestHandlerExecute(object sender, EventArgs e)
	{
		/* Static content */
		if (HttpContext.Current.Handler == null)
		{
			return;
		}

		var handler = HttpContext.Current.Handler;
		Unity.Instance.Container.BuildUp(handler.GetType(), handler);

		// User Controls are ready to be built up after the page initialization is complete
		var page = HttpContext.Current.Handler as Page;
		if (page != null)
		{
			page.InitComplete += OnPageInitComplete;
		}
	}

	// Build up each control in the page's control tree
	private static void OnPageInitComplete(object sender, EventArgs e)
	{
		var page = (Page)sender;
		foreach (Control c in GetControlTree(page))
		{
			var typeFullName = c.GetType().FullName ?? string.Empty;
			var baseTypeFullName = c.GetType().FullName ?? string.Empty;

			// Filter on namespace to avoid build up of System.Web components
			if (typeFullName.StartsWith(NamespacePrefix) || 
				baseTypeFullName.StartsWith(NamespacePrefix))
			{
				Unity.Instance.Container.BuildUp(c.GetType(), c);
			}
		}
	}
}&lt;/pre&gt;
&lt;p&gt;Please notice that we define the namespace on line 3 as a filter, because we don't want to have Unity build up controls that belongs to the .NET Framework.&lt;/p&gt;
&lt;p&gt;We register this module in web.config as following.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;configuration&amp;gt;
	&amp;lt;!-- IIS 6.0 and below --&amp;gt;
    &amp;lt;system.web&amp;gt;
      &amp;lt;httpModules&amp;gt;
        &amp;lt;add name="UnityHttpModule" type="DIWebFormsExample.Lib.UnityHttpModule, DIWebFormsExample.Lib"/&amp;gt;
      &amp;lt;/httpModules&amp;gt;
    &amp;lt;/system.web&amp;gt;

	&amp;lt;!-- IIS 7.0 and above --&amp;gt;
    &amp;lt;system.webServer&amp;gt;
      &amp;lt;modules&amp;gt;
        &amp;lt;remove name="UnityHttpModule"/&amp;gt;
        &amp;lt;add name="UnityHttpModule" type="DIWebFormsExample.Lib.UnityHttpModule, DIWebFormsExample.Lib"/&amp;gt;
      &amp;lt;/modules&amp;gt;
    &amp;lt;/system.webServer&amp;gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;
&lt;p&gt;This simply allows us to inject our dependencies through property injection. Here's our product page.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;form id="form1" runat="server"&amp;gt;
&amp;lt;div&amp;gt;
    &amp;lt;h1&amp;gt;Products&amp;lt;/h1&amp;gt;
    &amp;lt;h2&amp;gt;Electronics&amp;lt;/h2&amp;gt;
    &amp;lt;asp:DataGrid 
        runat="server" 
        DataSource='&amp;lt;%# GetByType("Electronics") %&amp;gt;' 
        AutoGenerateColumns="true" OnLoad="DataBind" /&amp;gt;
    &amp;lt;h2&amp;gt;Candy&amp;lt;/h2&amp;gt;
    &amp;lt;asp:DataGrid 
        runat="server" 
        DataSource='&amp;lt;%# GetByType("Candy") %&amp;gt;' 
        AutoGenerateColumns="true" OnLoad="DataBind" /&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;/form&amp;gt;&lt;/pre&gt;
&lt;pre class="brush:csharp"&gt;public partial class ProductList : System.Web.UI.Page
{
	[Dependency]
	public IRepository&amp;lt;Product&amp;gt; Repository { get; set; }

	protected void Page_Load(object sender, EventArgs e)
	{
	}

	protected IEnumerable&amp;lt;Product&amp;gt; GetByType(string type)
	{
		return Repository.Get(p =&amp;gt; p.Type == type);
	}

	protected void DataBind(object sender, EventArgs e)
	{
		((Control) sender).DataBind();
	}
}&lt;/pre&gt;
&lt;p&gt;On line 4 we inject our dependency through property injection by adding the attribute [Dependency] to the property. Unity will then resolve this dependency during BuildUp. I have registered this to my container as following:&lt;/p&gt;
&lt;pre class="brush:csharp;gutter:false"&gt;container.RegisterType&amp;lt;IRepository&amp;lt;Product&amp;gt;, ProductRepository&amp;gt;();&lt;/pre&gt;
&lt;h2&gt;Testing&lt;/h2&gt;
&lt;p&gt;How does this relate to testing? It makes it much easier to unit test our webforms code behind.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;[TestFixture]
public class ProductListCodeBehindShould
{
	private class Template : ProductList
	{
		public Template()
		{
			Repository = new StubRepository();
		}

		public new IEnumerable&amp;lt;Product&amp;gt; GetByType(string type)
		{
			return base.GetByType(type);
		}

		private class StubRepository : IRepository&amp;lt;Product&amp;gt;
		{
			public IEnumerable&amp;lt;Product&amp;gt; Get(Func&amp;lt;Product, bool&amp;gt; criteria)
			{
				return new[]
				{
					new Product("Stereo", 120.0, "Electronics"),
					new Product("Candy bar", 1.2, "Candy"),
					new Product("Soda", 1.8, "Candy"),
					new Product("Deep fried snickers bar", 0.2, "Candy")
				}.Where(criteria);
			}
		}
	}

	[TestCase("Electronics", 120.0)]
	[TestCase("Candy", 3.2)]
	public void GetProductsBySpecifiedType(string type, double totalPrice)
	{
		/* Setup */
		var template = new Template();

		/* Test */
		var products = template.GetByType(type);

		/* Assert */
		Assert.That(products.Sum(p =&amp;gt; p.Price), Is.EqualTo(totalPrice));
	}
}&lt;/pre&gt;
&lt;p&gt;What happens here? I create an sub class to the ASP.NET page code behind that I want to test, because I want to reach protected methods like GetByType(string type). My test makes sure that type is properly translated into a correct lambda expression, without touching the real ProductRepository. This is exactly what we need in order to test our code behind properly.&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;What I like about this approach is...&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It's unobtrusive. Most testing approaches require you to apply a pattern like MVP in order to reap benefits of testing your UI layer. This might require you to rewrite a large part of your application. My DI module will not affect old code, but enable testability of any new code you write. Later on, you may refactor old code with dependency injection to improve testability.&lt;br /&gt;&lt;br /&gt;This means that the initial cost is very small.&lt;/li&gt;
&lt;li&gt;It works also for ASCX (user controls) and ASHX (handlers).&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Go &lt;a href="http://litemedia.info/media/Default/BlogPost/blog/DIWebFormsExample.zip"&gt;download a full sample here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:02 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/dependency-injection-in-asp.net-webforms</guid></item><item><title>Dealing with dependencies in functional programming</title><link>http://www.litemedia.info:80/dealing-with-dependencies-in-functional-programming</link><description>&lt;p&gt;What is a dependency?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Some entity that your unit depends on. (too abstract description)&lt;/li&gt;
&lt;li&gt;Something that you want to replace while unit testing (too concrete description)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In OO programming you will use a dependency injection framework to build dependency chains. You use it to inject dependencies into constructors, methods and parameters. That is all very cool and enables testability, but not very useful in functional programming.&lt;/p&gt;
&lt;h3&gt;Why do we need to think about dependencies in functional programming?&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Testing your units are still important, and to enable that you need to stub away your dependencies&lt;/li&gt;
&lt;li&gt;Coupling also exists in functional programming and should be considered an evil&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Function argument dependency injection&lt;/h2&gt;
&lt;p&gt;The most obvious way to handle dependencies is to send them into the function as an argument.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;// Model object
type Person = { Name : string; BirthDate : System.DateTime }

// age: get the age of a person from name
// string -&amp;gt; (string -&amp;gt; Person) -&amp;gt; int
let age name (fn_getPerson : string -&amp;gt; Person) =

    // Get birthdate from dependency
    let birthDate = (fn_getPerson name).BirthDate 

    // Calculate
    (DateTime.Now - birthDate).Days / 365&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;val age : string -&amp;gt; (string -&amp;gt; Person) -&amp;gt; int&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The dependency is a function that knows how to get a person from the database by calling with its name. While unit testing we really want to get rid of that dependency and that is why we send it in as a function, instead of calling it directly from where we need its result.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;age "Mikael Lundin" DataAccess.GetPerson
// or maybe
DataAccess.GetPerson |&amp;gt; age "Mikael Lundin"&lt;/pre&gt;
&lt;p&gt;Testing would look like this. Here I'm using &lt;a href="http://xunit.codeplex.com/"&gt;xUnit&lt;/a&gt; and &lt;a title="unquote A library for writing unit test assertions as F# quoted expressions" href="http://code.google.com/p/unquote/"&gt;Unqoute&lt;/a&gt; for testing.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;open Xunit
open Swensen.Unquote

[&amp;lt;Fact&amp;gt;]
let ``send dependency into the function as an argument`` () =
    // Setup: In our test we return a Person directly
    let dependency (s : string) = { Name = s; BirthDate = new DateTime(1982, 7, 15) }

    // Assert
    test &amp;lt;@ 29 = age "Mikael" dependency  @&amp;gt;&lt;/pre&gt;
&lt;p&gt;Unit testing with Xunit and Unquote is a blast. I love the expressiveness that Unquote gives us. If we where to run this with Resharper as testrunner, and fail the test - we get this great test failure.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://litemedia.info/media/Default/BlogPost/blog/dealing-with-dependencies-in-functional-programming/fsharp_unit_test.png" alt="F# unit test with xunit, unquote and Resharper" width="794" height="480" /&gt;&lt;/p&gt;
&lt;p&gt;Oh, I love it!&lt;/p&gt;
&lt;h2&gt;Partial function application injection&lt;/h2&gt;
&lt;p&gt;This is a very scary title, but another functional way to deal with dependencies. Instead of accepting the dependency as an argument, you return a function that have to be completed with the dependency to run.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;// Dependency through partial function
let age name : ((string -&amp;gt; Person) -&amp;gt; int) =
    // Return a function
    (fun (getPerson : string -&amp;gt; Person) -&amp;gt; 
        // Get birthdate
        let birthDate = getPerson(name).BirthDate

        // Return age
        (DateTime.Now - birthDate).Days / 365
    )&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;val age : string -&amp;gt; (string -&amp;gt; Person) -&amp;gt; int&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;This is indeed a bit harder to read and makes the function signature a bit messy. I return a function that will accept the dependency as an argument. Anyway I do like this method better than the previous.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;age "Mikael" DataAccess.GetPerson
// this also works
DataAccess.GetPerson |&amp;gt; age "Mikael"&lt;/pre&gt;
&lt;p&gt;And here's a test.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;[&amp;lt;Fact&amp;gt;]
let ``using a partial function result to insert the dependency to`` () =
    // Setup: Our dependency is called on the function result
    let dependency s = { Name = s; BirthDate = new DateTime(1982, 7, 15) }

    // Assert
    test &amp;lt;@ 28 = (age "Mikael") dependency @&amp;gt;&lt;/pre&gt;
&lt;h2&gt;Interface dependency injection&lt;/h2&gt;
&lt;p&gt;Since F# has object literals, it is very easy to stub out interfaces, and when talking to OO libraries you might have to resort to this method. Consider our dependency.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public interface IUserRepository
{
    IEnumerable&amp;lt;User&amp;gt; GetUsers();
}

public class User
{
    public string UserName { get; set; }

    public string Password { get; set; }
}&lt;/pre&gt;
&lt;p&gt;We would like to write an authenticate method in F#. How should we handle our dependency? Here's some F# equivalient of what we would do in OOP.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;let authenticate username password (rep : IUserRepository) =
    rep.GetUsers() |&amp;gt; Seq.exists (fun u -&amp;gt; u.UserName = username &amp;amp;&amp;amp; u.Password = password)&lt;/pre&gt;
&lt;p&gt;When calling this from a test, we can use object literals to change the implementation of the interface members.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;[&amp;lt;Fact&amp;gt;]
let ``using an interface as dependency`` () =
    // GetUsers() result
    let users = [| new User(UserName = "mlu", Password = "secret") |]

    // Fake repository
    let repository = { 
        new IUserRepository with
            member x.GetUsers() = users |&amp;gt; Seq.ofArray
    }

    // Assert
    test &amp;lt;@ true = authenticate "mlu" "secret" repository @&amp;gt;&lt;/pre&gt;
&lt;p&gt;But a more functional approach would be, not to use the interface as a dependency, but focus on the actual function as we did on the first two patterns. Let the caller of this function worry about on what object instance the dependent function lives.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;let authenticate username password : ((unit -&amp;gt; seq&amp;lt;User&amp;gt;) -&amp;gt; bool) =
    (fun (getUsers : unit -&amp;gt; seq&amp;lt;User&amp;gt;) -&amp;gt;
        getUsers() |&amp;gt; Seq.exists 
            (fun user -&amp;gt; user.UserName = username &amp;amp;&amp;amp; user.Password = password)
&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;val authenticate : string -&amp;gt; string -&amp;gt; (unit -&amp;gt; seq&amp;lt;User&amp;gt;) -&amp;gt; bool&lt;/code&gt;&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;(authenticate "mlu" "secret") (new UserRepository()).GetUsers&lt;/pre&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:01 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/dealing-with-dependencies-in-functional-programming</guid></item><item><title>Orchard: Alternative content on start page</title><link>http://www.litemedia.info:80/orchard-alternative-content-on-homepage</link><description>&lt;p&gt;It took me a lot of time to figure out how to tell Orchard to render something different on the start page. One way is to define a layout that is specific for the start page url.&lt;/p&gt;
&lt;p&gt;&lt;img height="126" width="292" alt="Orchard theme view folder" src="http://litemedia.info/media/Default/BlogPost/blog/orchard_view_templates.png" /&gt;&lt;/p&gt;
&lt;p&gt;If you want to use placement.info to move things around or hide the title on start page you can match on the ~/ url.&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;!-- HIDE TITLE ON START PAGE --&amp;gt;
&amp;lt;Place Parts_RoutableTitle="Content:5" /&amp;gt;
&amp;lt;Match Path="~/"&amp;gt;
  &amp;lt;Place Parts_RoutableTitle="" /&amp;gt;
&amp;lt;/Match&amp;gt;&lt;/pre&gt;
&lt;p&gt;This tells Orchard to display page title in Content, unless the page has url ~/. Then you should not display it at all. Hope this will help someone else out there looking for an answer to this.&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:01 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/orchard-alternative-content-on-homepage</guid></item><item><title>About and Contact</title><link>http://www.litemedia.info:80/about</link><description>&lt;p&gt;Do you recognize the content on this site? That is because it was earlier called Mint and located at http://mint.litemedia.se. I decided to move the blog to its own domain, because it has such importance to me. I update it nearly every week and it deserves more attention. I also choose to move it away from .se, since all my blog posts is in English I don't want this blog to be associated as a Swedish blog.&lt;/p&gt;
&lt;p&gt;My name is Mikael Lundin and I'm the author of the content here. Any problem solved is worth little more than nothing unless you choose to share the problem solution. That is why most of my posts here are problems that I run into in my day to day work and the solution to those problems. I will also share content that I create for seminars and research on new languages and development platforms.&lt;/p&gt;
&lt;p&gt;As of now I'm a .NET developer tired of the .NET community. What that means for the future, I don't know but I'm not going to label this as a .NET blog anymore, as I did when it was located at mint.litemedia.se. We'll just have to wait and see where the most interesting system developing is at, and I will be found there.&lt;/p&gt;
&lt;h2&gt;Contact&lt;/h2&gt;
&lt;p&gt;If you have any questions or ideas, please contact &lt;a rel="me" href="https://profiles.google.com/mikael.lundin82/"&gt;me&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://mint.litemedia.se/wp-content/uploads/contact.png"&gt;&lt;img class="alignleft size-full wp-image-887" title="contact" src="http://mint.litemedia.se/wp-content/uploads/contact.png" width="317" height="80" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:01 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/about</guid></item><item><title>Extending types in F#</title><link>http://www.litemedia.info:80/extending-types-in-fsharp</link><description>&lt;p&gt;Just as you can extend existing types in C# with extension methods you can do the same in F# with &lt;a href="http://msdn.microsoft.com/en-us/library/dd233211.aspx" title="MSDN Type Extensions (F#)"&gt;type extensions&lt;/a&gt;. The difference is that extending types in F# helps you work in a functional matter with object orientation. Consider the following discriminated union that could be used for a card game.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;type Suit = | Spades | Hearts | Diamonds | Clubs

type Card =
    | ValueCard of Suit * int
    | Knave of Suit
    | Queen of Suit
    | King of Suit
    | Ace of Suit&lt;/pre&gt;
&lt;p&gt;We would like to expose a hand as a type. In this type we can do all the object oriented behavior things like limiting number of cards in hand to 5, making sure that we don't have duplicate cards and so on. Great, but the problem is working with the type members we always need to reevaluate the type as we're changing member functions.&amp;nbsp;&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;type Hand (cards : Card list) =
    member this.Cards = cards&lt;/pre&gt;
&lt;p&gt;So we keep the Hand type as simple as possible, and then we extend with functionality.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;let isRoyalStraightFlush (cards : Card list) = 
    match cards with
    | Ace suit_1 :: King suit_2 :: Queen suit_3 :: Knave suit_4 :: ValueCard (suit_5, 10) :: [] 
        when suit_1 = suit_2 &amp;amp;&amp;amp; suit_2 = suit_3 &amp;amp;&amp;amp; suit_3 = suit_4 &amp;amp;&amp;amp; suit_4 = suit_5 
        -&amp;gt; true
    | _ -&amp;gt; false&lt;/pre&gt;
&lt;p&gt;The function isRoyalStraightFlush can be written and tested individually without any connection to the Hand object, and then we can extend the hand with this functionality like this.&lt;/p&gt;
&lt;pre class="brush:fsharp"&gt;type Hand with
    member x.IsRoyalStraightFlush = isRoyalStraightFlush x.Cards&lt;/pre&gt;
&lt;p&gt;I really like this way of working with object orientation in a functional manner.&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 11:41:01 GMT</pubDate><guid isPermaLink="true">http://www.litemedia.info:80/extending-types-in-fsharp</guid></item></channel></rss>
