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

<channel>
	<title>antony_scott</title>
	<atom:link href="http://sixgun.co.uk/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://sixgun.co.uk/blog</link>
	<description>Daddy, Software Developer, Rower/Sculler, Grumpy Old Man.</description>
	<lastBuildDate>Tue, 14 Feb 2012 16:10:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>WCF Web Api MessageHandler Gotcha</title>
		<link>http://sixgun.co.uk/blog/2012/02/14/wcf-web-api-messagehandler-gotcha/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/14/wcf-web-api-messagehandler-gotcha/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 16:10:45 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[WCF Web Api]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=576</guid>
		<description><![CDATA[If you find yourself getting this error message when you change your URL in the test client between you different APIs &#8230; The HttpClient instance already started one or more requests. Properties can only be modified before sending the first request. You have fallen foul of a little WCF Web Api gotcha. Message handlers need [...]]]></description>
			<content:encoded><![CDATA[<p>If you find yourself getting this error message when you change your URL in the test client between you different APIs &#8230;</p>
<blockquote><p>The HttpClient instance already started one or more requests. Properties can only be modified before sending the first request.</p></blockquote>
<p>You have fallen foul of a little WCF Web Api gotcha. Message handlers need to be created each time they are required. I was using Castle Windsor to handle the lifetime of my message handlers</p>
<pre class="brush: csharp; title: ; notranslate">
    public class MessageHandlerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var path = Assembly.GetExecutingAssembly().GetDirectoryName();
            var filter = new AssemblyFilter(path, &quot;ByBox*.dll&quot;);

            container.Register(
                AllTypes
                    .FromAssemblyInDirectory(filter)
                    .Where(t =&gt; t.IsSubclassOf(typeof (DelegatingHandler)))
                    .Configure(c =&gt; c.LifeStyle.Custom(InstallerContext.LifestyleManager))
                );
        }
    }
</pre>
<p>So, I&#8217;m using my InstallerContext&#8217;s lifestyle, but what I actually needed was this &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
                    .Configure(c =&gt; c.LifeStyle.Transient)
</pre>
<p>I found this in a <a href="http://wcf.codeplex.com/discussions/279848">discussion</a> on the <a href="http://wcf.codeplex.com/">wcf codeplex site</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/14/wcf-web-api-messagehandler-gotcha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NUnit Assert extension to check any property of any object</title>
		<link>http://sixgun.co.uk/blog/2012/02/14/nunit-assert-extension-to-check-any-property-of-any-object/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/14/nunit-assert-extension-to-check-any-property-of-any-object/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 14:06:08 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[NUnit]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=570</guid>
		<description><![CDATA[I have just recently discovered the [TestCase] attribute of NUnit. With careful use it can drastically reduce the number of test methods you need to write. For my needs on a recent project I wanted to check field values which were being pulled from my database. What I&#8217;ve come up with is a simple extension [...]]]></description>
			<content:encoded><![CDATA[<p>I have just recently discovered the [TestCase] attribute of NUnit. With careful use it can drastically reduce the number of test methods you need to write. For my needs on a recent project I wanted to check field values which were being pulled from my database. What I&#8217;ve come up with is a simple extension to the NUnit Assert class which allows me to write test code such as &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
[TestCase(0, &quot;Forename&quot;, &quot;Antony&quot;)]
[TestCase(0, &quot;Surname&quot;, &quot;Scott&quot;)]
[TestCase(0, &quot;TwitterUserName&quot;, &quot;antony_scott&quot;)]
public void ExampleTest(int index, string fieldname, object expectedValue)
{
    var result = GetPersonDetails();
    var list = result.ToList();
    Assert.IsFieldEqual(list.ElementAt(index), fieldname, expectedValue);
}
</pre>
<p>This gives me a very compact and easy to understand test with great visibility of any fields which are being pulled from the database correctly. All this is nothing new, as I&#8217;ve blogged about it previously <a href="http://sixgun.co.uk/blog/2012/02/09/reflection-based-assert-with-nunit/">here</a>.</p>
<p>What I&#8217;ve added is the ability to dig into a structure like so &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
[TestCase(0, &quot;Forename&quot;, &quot;Antony&quot;)]
[TestCase(0, &quot;Surname&quot;, &quot;Scott&quot;)]
[TestCase(0, &quot;Twitter.UserName&quot;, &quot;antony_scott&quot;)]
public void ExampleTest(int index, string fieldname, object expectedValue)
{
    var result = GetPersonDetails();
    var list = result.ToList();
    Assert.IsFieldEqual(list.ElementAt(index), fieldname, expectedValue);
}
</pre>
<p>In case you can&#8217;t see any difference, it&#8217;s the &#8220;dot&#8221; in the 3rd test case.</p>
<p>Here is the &#8220;extension&#8221; of the Assert class which makes it possible &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
    public class Assert : NUnit.Framework.Assert
    {
        public static void IsFieldEqual(object obj, string propertyName, object expectedValue)
        {
            var type = obj.GetType();

            var dotIndex = propertyName.IndexOf('.');
            if (dotIndex != -1)
            {
                var innerObjName = propertyName.Substring(0, dotIndex);
                var innerPropName = propertyName.Substring(dotIndex + 1);
                var innerProp = type.GetProperty(innerObjName);
                var innerObj = innerProp.GetValue(obj, null);
                IsFieldEqual(innerObj, innerPropName, expectedValue);
            }
            else
            {
                var prop = type.GetProperty(propertyName);
                var actualValue = prop.GetValue(obj, null);
                AreEqual(expectedValue, actualValue);
            }
        }
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/14/nunit-assert-extension-to-check-any-property-of-any-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Json.NET to generate JsonSchema</title>
		<link>http://sixgun.co.uk/blog/2012/02/09/using-json-net-to-generate-jsonschema/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/09/using-json-net-to-generate-jsonschema/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 14:28:27 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=567</guid>
		<description><![CDATA[Actually generating the schema is pretty simple &#8230; then write it to a file &#8230; What took me a while to figure out was that MyClass needs to be decorated with specific attributes in order for the schema to be correctly generated. So, the JsonProperty attribute is your friend here! I took my a while [...]]]></description>
			<content:encoded><![CDATA[<p>Actually generating the schema is pretty simple &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
using Newtonsoft.Json.Schema;

var jsonSchemaGenerator = new JsonSchemaGenerator();
var myType = typeof(MyClass);
var schema = jsonSchemaGenerator.Generate(myType);
schema.Title = myType.Name; // this doesn't seem to get done within the generator
</pre>
<p>then write it to a file &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
var writer = new StringWriter();
var jsonTextWriter = new JsonTextWriter(writer);
schema.WriteTo(jsonTextWriter);
var prettyString = JsonPrettifier.Prettify(writer.ToString());
var fileWriter = new StreamWriter(&quot;MySchema.txt&quot;);
fileWriter.WriteLine(schema.Title);
fileWriter.WriteLine(new string('-', schema.Title.Length));
fileWriter.WriteLine(prettyString);
fileWrite.Close();
</pre>
<p>What took me a while to figure out was that <strong>MyClass</strong> needs to be decorated with specific attributes in order for the schema to be correctly generated.</p>
<pre class="brush: csharp; title: ; notranslate">
public class MyClass
{
    [JsonProperty(Required = Required.Always)]
    public string Forename { get; set; }

    [JsonProperty(Required = Required.Always)]
    public string Surname { get; set; }

    [JsonProperty(Required = Required.Always)]
    public string EmailAddress { get; set; }

    [JsonProperty(Required = Required.AllowNull)]
    public string MobilePhoneNumber { get; set; }
}
</pre>
<p>So, the <strong>JsonProperty</strong> attribute is your friend here! I took my a while to figure out, including some time stepping through the Json.NET source code in the debugger.</p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/09/using-json-net-to-generate-jsonschema/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reflection Based Assert with NUnit</title>
		<link>http://sixgun.co.uk/blog/2012/02/09/reflection-based-assert-with-nunit/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/09/reflection-based-assert-with-nunit/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 13:25:30 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[NUnit]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=564</guid>
		<description><![CDATA[I recently wrote about using reflection to check for null values in conjunction with the TestCase attribute. I&#8217;ve just taken this a step further by creating a derived Assert class &#8230; This allows me to write tests to check the value of each field in a result object and have the assert fail on the [...]]]></description>
			<content:encoded><![CDATA[<p>I recently wrote about using reflection to check for null values in conjunction with the <strong>TestCase</strong> attribute. I&#8217;ve just taken this a step further by creating a derived <strong>Assert</strong> class &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
public class Assert : NUnit.Framework.Assert
{
    public static void IsFieldEqual(object obj, string propertyName, object expectedValue)
    {
        var type = obj.GetType();
        var prop = type.GetProperty(propertyName);
        var actualValue = prop.GetValue(obj, null);
        AreEqual(expectedValue, actualValue);
    }
}
</pre>
<p>This allows me to write tests to check the value of each field in a result object and have the assert fail on the specific field, it also doesn&#8217;t stop the other field being tested. So, using the <strong>TestCase</strong> attribute I can write tests such as this &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
[TestCase(&quot;Forename&quot;, &quot;Antony&quot;)]
[TestCase(&quot;Surname&quot;, &quot;Scott&quot;)]
public void example_test(string fieldname, object expectedValue)
{
    // Arrange
    Context.AddPerson(new Person { ID = 1, Forename = &quot;Antony&quot;, Surname = &quot;Scott&quot; });

    // Act
    var result = Service.GetPerson(1);

    // Assert
    Assert.IsFieldEqual(result, fieldname, expectedValue);
}
</pre>
<p>Obviously this is an over-simplified example. But, the idea is that I can now have a complex object being loaded up by an integration test into my database. I then use a Service of some kind (what I&#8217;m testing) to query my database and I can then make sure all the correct details have been retrieved from the database.</p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/09/reflection-based-assert-with-nunit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Validation in WCF Web Api</title>
		<link>http://sixgun.co.uk/blog/2012/02/02/validation-in-wcf-web-api/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/02/validation-in-wcf-web-api/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 23:41:05 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Validation]]></category>
		<category><![CDATA[WCF Web Api]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=558</guid>
		<description><![CDATA[I&#8217;ve been working on a RESTful api recently using WCF Web Api (Preview 6). It&#8217;s like a breath of fresh air to work on something so uncluttered, I&#8217;ve come from working on a complex, multi-technology, web site. Working with a RESTful api is just so simple, but it presents its own challenges which I am [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working on a RESTful api recently using <a href="http://wcf.codeplex.com/">WCF Web Api</a> (Preview 6). It&#8217;s like a breath of fresh air to work on something so uncluttered, I&#8217;ve come from working on a complex, multi-technology, web site. Working with a RESTful api is just so simple, but it presents its own challenges which I am overcoming one by one. One such challenge is validating the resources coming in via a POST method. I found a very useful <a href="http://stackoverflow.com/a/7998564/62951">answer</a> on <a href="http://stackoverflow.com/">stack overflow</a> which got me some of the way there. I spent some time refining it a bit and eventually came up with this &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net.Http;
using ByBox.WebApi.HttpResponseMessages;
using Microsoft.ApplicationServer.Http.Dispatcher;

namespace WhateverYouWant
{
    public class ValidationHandler&lt;TResource&gt; : HttpOperationHandler&lt;TResource, HttpRequestMessage, HttpRequestMessage&gt;
    {
        public ValidationHandler() : base(&quot;response&quot;) { }

        protected override HttpRequestMessage OnHandle(TResource model, HttpRequestMessage requestMessage)
        {
            var results = new List&lt;ValidationResult&gt;();
            var context = new ValidationContext(model, null, null);
            Validator.TryValidateObject(model, context, results, true);

            if (results.Count == 0)
            {
                return requestMessage;
            }

            var errorMessages = results.Select(x =&gt; x.ErrorMessage).ToArray();

            var mediaType = requestMessage.Headers.Accept.FirstOrDefault();
            var response = new RestValidationFailure(errorMessages);
            if (mediaType != null)
            {
                response.Content = new ObjectContent(typeof(string[]), errorMessages, mediaType);
            }
            throw new HttpResponseException(response);
        }
    }
}
</pre>
<p>What I added to the answer on stack overflow was the ability to return a list of error messages in both the headers and the body of the response. The list of errors in the body are sent in the format the browser will &#8220;accept&#8221;. This helps keep everything simple on the client side. I have only checked if it works for xml and json. For the sake of completeness I have included a version of my <strong>RestValidationFailure</strong> class.</p>
<pre class="brush: csharp; title: ; notranslate">
using System.Net.Http;

namespace WhateverYouWant
{
    public class RestValidationFailure : HttpResponseMessage
    {
        public RestValidationFailure(string[] errorMessages)
        {
            StatusCode = HttpStatusCode.BadRequest;
            foreach (var errorMessage in errorMessages)
            {
                Headers.Add(&quot;X-Validation-Error&quot;, errorMessage);
            }
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/02/validation-in-wcf-web-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Castle Windsor with WCF Web Api (Preview 6)</title>
		<link>http://sixgun.co.uk/blog/2012/02/02/using-castle-windsor-with-wcf-web-api-preview-6/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/02/using-castle-windsor-with-wcf-web-api-preview-6/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 23:25:26 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[WCF Web Api]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=550</guid>
		<description><![CDATA[I&#8217;ve got used to treating everything as a service in recent years, since I started using Castle Windsor. I only ever instantiate my own classes in unit/integration tests these days. My latest project has been to write a RESTful service using preview 6 of the WCF Web Api framework. (Also available via nuget, just add [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve got used to treating everything as a service in recent years, since I started using Castle Windsor. I only ever instantiate my own classes in unit/integration tests these days. My latest project has been to write a RESTful service using preview 6 of the <a href="http://wcf.codeplex.com/">WCF Web Api</a> framework. (Also available via nuget, just add the WebApi.All package and you&#8217;re all set). It&#8217;s actually quite simple to make the web api use castle windsor.</p>
<p>From my <strong>Application_Start()</strong> method I call a <strong>ConfigureApi(RouteCollection routes)</strong> method. This create the config object and then sets up any routes &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
    private static void ConfigureApi(RouteCollection routes)
    {
        Container = CreateContainer();

        var config = new MyApiConfiguration(Container);
        routes.SetDefaultHttpConfiguration(config);

        routes.MapServiceRoute&lt;MyApi&gt;(&quot;myresource&quot;);
    }
</pre>
<p>I then set up <strong>CreateInstance</strong>, <strong>ErrorHandlers</strong>, and <strong>MessageHandlerFactory</strong> with anonymous methods which simply call the relevant Resolve methods on my container.</p>
<pre class="brush: csharp; title: ; notranslate">
public class MyApiConfiguration : WebApiConfiguration
{
    public MyApiConfiguration(IWindsorContainer container)
    {
        EnableTestClient = GetSetting(&quot;TestClient&quot;);
        IncludeExceptionDetail = GetSetting(&quot;IncludeExceptionDetail&quot;);

        CreateInstance = ((serviceType, context, request) =&gt; container.Resolve(serviceType));
        ErrorHandlers = (handlers, endpoint, description) =&gt; handlers.Add(container.Resolve&lt;GlobalErrorHandler&gt;());
        MessageHandlerFactory = () =&gt; container.ResolveAll&lt;DelegatingHandler&gt;();

        this.ValidateAllResourceTypes();
    }

    private static bool GetSetting(string settingName)
    {
        bool flag;
        bool.TryParse(ConfigurationManager.AppSettings[settingName] ?? &quot;false&quot;, out flag);
        return flag;
    }
}
</pre>
<p>And that&#8217;s all there is to it. Simple really.</p>
<p>&nbsp;</p>
<p><strong>ValidateAllResourceTypes</strong> is something I will blog about another time. It uses reflection to register all resource types for validation via data annotations.</p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/02/using-castle-windsor-with-wcf-web-api-preview-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integration Testing with Entity Framework</title>
		<link>http://sixgun.co.uk/blog/2012/02/02/integration-testing-with-entity-framework/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/02/integration-testing-with-entity-framework/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 23:11:16 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[CodeFirst]]></category>
		<category><![CDATA[EntityFramework]]></category>
		<category><![CDATA[NUnit]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=543</guid>
		<description><![CDATA[I&#8217;ve been writing a lot more integration tests for my recent projects in which I&#8217;ve made use of Entity Framework. I&#8217;m purely using code first as I never really got along with the whole draggy droppy designer affair. I came to realise recently that I was writing an awful lot of code to mock out [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been writing a lot more integration tests for my recent projects in which I&#8217;ve made use of Entity Framework. I&#8217;m purely using code first as I never really got along with the whole draggy droppy designer affair. I came to realise recently that I was writing an awful lot of code to mock out my data layer (using Moq). But all I was really doing was making sure that my Linq queries pulled back the correct data. Even after having gone to all the effort I was still getting problems with my code when it got to see a database for the first time. Usually to do with me doing things which cannot be converted in to T-SQL. So I&#8217;ve decided to ditch unit testing and mocking for any data layer stuff and go totally over the integration testing. Making the move to entity framework code first has made that very simple. First off I create a couple of &#8220;self-creating&#8221; properties for my Context and Repository.</p>
<pre class="brush: csharp; title: ; notranslate">
    private DomainContext _context;
    protected DomainContext Context
    {
        get { return _context ?? (_context = new DomainContext(ConfigurationManager.ConnectionStrings[&quot;ByBox&quot;].ConnectionString)); }
        private set { _context = value; }
    }

    private ConsumerRepository _repository;
    private ConsumerRepository Repository
    {
        get { return _repository ?? (_repository = new ConsumerRepository(Context)); }
        set { _repository = value; }
    }
</pre>
<p>Then I have some straight forward setup/teardown code. All this usually ends up in a base class of some kind which I re-use in all my different test source files.</p>
<pre class="brush: csharp; title: ; notranslate">
    [TestFixtureSetUp]
    public virtual void TestFixtureSetUp()
    {
        try
        {
            var seed = new DomainDataSeed();
            Database.SetInitializer(seed);
            Context.Database.Initialize(true);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            throw;
        }
    }

    [TestFixtureTearDown]
    public virtual void TestFixtureTearDown()
    {
        Repository.Dispose();
        Repository = null;
        Context.Dispose();
        Context = null;
    }
</pre>
<p>Another useful thing to do is to be able to reset the database to a know state. You may have noticed these 3 lines above &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
            var seed = new DomainDataSeed();
            Database.SetInitializer(seed);
            Context.Database.Initialize(true);
</pre>
<p>What these do is use a data seed class to initialise the database. By way of example, here is a snippet from my seed class &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
    public class DomainDataSeed : DropCreateDatabaseAlways&lt;DomainContext&gt;
    {
        protected override void Seed(DomainContext context)
        {
            AddWebServiceUsers(context);
            AddUserAccounts(context);

            context.SaveChanges();
        }

        private void AddWebServiceUsers(DomainContext context)
        {
            context.Database.ExecuteSqlCommand(&quot;CREATE TABLE [web_service_user] ( ... )&quot;);
            context.Database.ExecuteSqlCommand(&quot;CREATE TABLE [web_service_user_attribute] ( ... )&quot;);
            context.Database.ExecuteSqlCommand(&quot;INSERT INTO [web_service_user] ([username], [password]) values({0}, {1})&quot;, Username, Password);
        }
        private static void AddUserAccounts(DomainContext context)
        {
            context.UserAccounts.Add(
                new UserAccount
                    {
                        ...
                    });
        }
    }
</pre>
<p>If I wanted to I could put that code into the <strong>[SetUp]</strong> method rather than the <strong>[TestFixtureSetUp]</strong> method. Or, as I have done recently in a <strong>ResetDatabase()</strong> method, which I call from the <strong>[TestFixtureSetUp]</strong> and select tests as required. This particular seed class drops and re-creates the database every time it is called, thanks to this &#8211; <strong>DropCreateDatabaseAlways&lt;DomainContext&gt;</strong>. There are other options available, including only dropping and re-creating the database (and seeding it) when the model changes.</p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/02/integration-testing-with-entity-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NUnit TestCase attribute with reflection for checking null field handling</title>
		<link>http://sixgun.co.uk/blog/2012/02/02/nunit-testcase-attribute-with-reflection-for-checking-null-field-handling/</link>
		<comments>http://sixgun.co.uk/blog/2012/02/02/nunit-testcase-attribute-with-reflection-for-checking-null-field-handling/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 22:43:51 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[NUnit]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=539</guid>
		<description><![CDATA[I recently had a need to write some unit (actually integration) tests which would check how I handled field being null. Without using the [TestCase] attribute of NUnit my tests would have looked something like this &#8230; &#8230; and so on. BUT, by using a little reflection in conjunction with the [TestCase] attribute of NUnit, [...]]]></description>
			<content:encoded><![CDATA[<p>I recently had a need to write some unit (actually integration) tests which would check how I handled field being null. Without using the [TestCase] attribute of NUnit my tests would have looked something like this &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
    public void validation_failure_identifier_null_400_expected()
    {
        // Arrange
        var resource = CreateCompleteResource();
        resource.Identifier = null;
        var jsonString = JsonPrettifier.Prettify(resource);

        // Act
        var result = Service.Post(jsonString);

        // Assert
        result.Message.CheckForValidationError(&quot;Identifier&quot;);
    }

    public void validation_failure_forename_null_400_expected()
    {
        // Arrange
        var resource = CreateCompleteResource();
        resource.Forename = null;
        var jsonString = JsonPrettifier.Prettify(resource);

        // Act
        var result = Service.Post(jsonString);

        // Assert
        result.Message.CheckForValidationError(&quot;Forename&quot;);
    }
</pre>
<p>&#8230; and so on.</p>
<p>BUT, by using a little reflection in conjunction with the [TestCase] attribute of NUnit, I can do this &#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
    private string GenerateJsonAndSetFieldTo(string fieldName, string value)
    {
        var resource = CreateCompleteResource();
        var type = resource.GetType();
        var prop = type.GetProperty(fieldName);
        prop.SetValue(resource, value, new object[0]);
        var jsonString = JsonPrettifier.Prettify(resource);
        return jsonString;
    }

    [TestCase(&quot;Identifier&quot;)]
    [TestCase(&quot;Forename&quot;)]
    public void validation_failure_400_expected(string fieldName)
    {
        // Arrange
        var jsonString = GenerateJsonAndSetFieldTo(fieldName, null);

        // Act
        var result = Service.Post(jsonString);

        // Assert
        result.Message.CheckForValidationError(fieldName);
    }
</pre>
<p>Obviously I have more TestCase&#8217;s than shown here, I didn&#8217;t want to bore you all with them! Less tests to maintain, easier to add null checking for other fields and it also looks neater in my test runner of choice.</p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2012/02/02/nunit-testcase-attribute-with-reflection-for-checking-null-field-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatically Adding Entity Framework Config Classes to the Model Builder (Version 2)</title>
		<link>http://sixgun.co.uk/blog/2011/12/13/automatically-adding-entity-framework-config-classes-to-the-model-builder-version-2/</link>
		<comments>http://sixgun.co.uk/blog/2011/12/13/automatically-adding-entity-framework-config-classes-to-the-model-builder-version-2/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 16:55:43 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeFirst]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=530</guid>
		<description><![CDATA[I recently wrote about how to Automatically Add Framework Config Classes to the Model Builder. Since writing that post I have come across a situation where I was writing the exact same model class in a different application. That just didn&#8217;t smell right to me, since the other applications data access layer had been packaged [...]]]></description>
			<content:encoded><![CDATA[<p>I recently wrote about how to <a href="http://sixgun.co.uk/blog/2011/08/31/automatically-adding-entity-framework-config-classes-to-the-modelbuilder/" title="Automatically Adding Entity Framework Config Classes to the ModelBuilder">Automatically Add Framework Config Classes to the Model Builder</a>. Since writing that post I have come across a situation where I was writing the exact same model class in a different application. That just didn&#8217;t smell right to me, since the other applications data access layer had been packaged up by nuget I could simply add a reference to it. That&#8217;s all well and good, but I didn&#8217;t want to have to go to any special effort to add the model configuration classes I needed to my modelbuilder. So, I&#8217;ve created a fairly simple (although it&#8217;s taken me a while to get it working how I want it) base class from which I can derive my context classes.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Base.EntityFramework
{
    public abstract class BaseDbContext : DbContext
    {
        protected BaseDbContext() { }
        protected BaseDbContext(string connectionString) : base(connectionString) { }

        private IEnumerable&lt;Type&gt; GetTypes()
        {
            var type = typeof(EntityTypeConfiguration&lt;&gt;);
            return GetType()
                .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p =&gt; p.PropertyType.IsGenericType &amp;&amp;
                            p.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet&lt;&gt;))
                .Select(p =&gt; type.MakeGenericType(p.PropertyType.GetGenericArguments().First()))
                .ToArray();
        }

        private static void LoadAllEntityConfigurationsFromAllAssemblies(DbModelBuilder modelBuilder, IEnumerable&lt;Type&gt; types, string assemblyFilter, IEnumerable&lt;string&gt; namePartFilters)
        {
            var path = Path.GetDirectoryName((new Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath);
            new DirectoryCatalog(path, assemblyFilter)
                .LoadedFiles
                .Where(x =&gt;
                {
                    var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(x.ToLower());
                    if (fileNameWithoutExtension != null)
                    {
                        var parts = fileNameWithoutExtension.Split(&quot;.&quot;.ToCharArray());
                        return parts.Any(part =&gt; namePartFilters.Any(namePartFilter =&gt; part == namePartFilter.ToLower()));
                    }
                    return false;
                })
                .Select(Assembly.LoadFrom)
                .ToList()
                .ForEach(assembly =&gt; assembly.GetTypes()
                                         .Where(t =&gt; types.Contains(t.BaseType))
                                         .Select(Activator.CreateInstance)
                                         .ToList&lt;dynamic&gt;()
                                         .ForEach(instance =&gt; modelBuilder.Configurations.Add(instance)));
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var typesToLoad = GetTypes();
            LoadAllEntityConfigurationsFromAllAssemblies(modelBuilder, typesToLoad, &quot;*.dll&quot;, new[] { &quot;Data&quot;, &quot;Domain&quot; });
        }

    }
}
</pre>
<p>and in english &#8230;.</p>
<ol>
<li>Discover which classes for which I need to find and load the relevant <strong>EntityTypeConfiguration<></strong> class. This is done with a little bit of reflection in the <strong>GetTypes()</strong> method.</li>
<li>Use <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog.aspx" target="_blank">MEF</a> to find the assemblies the config classes might be in. In this case it&#8217;s all of them (*.dll), but that could be changed to whatever is best for your situation.</li>
<li>Use the <strong>namePartFilters</strong> to narrow down the list of assemblies further. In this case I&#8217;m looking for anything with &#8220;Data&#8221; or &#8220;Domain&#8221; in the filename (after it&#8217;s been split by periods).</li>
<li>Load each assembly.</li>
<li>Load any generic EntityTypeConfiguration types for the model classes used within my context class (the one which is derived from this base class).</li>
<li>Instantiate each config class.</li>
<li>Add it to the modelBuilder&#8217;s configurations.</li>
</ol>
<p>Since this is a base class I can get this behaviour whenever I derive from it &#8230;.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class DomainContext : BaseDbContext, IDomainContext
    {
        public IDbSet&lt;Employee&gt; Employees { get; set; }

        public DomainContext() { }
        public DomainContext(string connectionString) : base(connectionString) { }

        IQueryable&lt;Employee&gt; IDomainContext.Employees { get { return Employees; } }
    }
</pre>
<p>What this allows me to do is use models from any assembly I am referencing in my application and just add it to my Context. Any configuration class for it will then be automatically added to the model builder.</p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2011/12/13/automatically-adding-entity-framework-config-classes-to-the-model-builder-version-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I think it&#8217;s my destiny to be a grumpy old man!</title>
		<link>http://sixgun.co.uk/blog/2011/12/12/i-think-its-my-destiny-to-be-a-grumpy-old-man/</link>
		<comments>http://sixgun.co.uk/blog/2011/12/12/i-think-its-my-destiny-to-be-a-grumpy-old-man/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 13:16:11 +0000</pubDate>
		<dc:creator>antony</dc:creator>
				<category><![CDATA[Funny]]></category>

		<guid isPermaLink="false">http://sixgun.co.uk/blog/?p=519</guid>
		<description><![CDATA[This seemed appropriate to post as I will soon be entering my 40th year &#8230;. If you are 40, or older, you might think this is hilarious! When I was a kid, adults used to bore me to tears with their tedious diatribes about how hard things were. When they were growing up; what with [...]]]></description>
			<content:encoded><![CDATA[<p>This seemed appropriate to post as I will soon be entering my 40th year &#8230;.</p>
<blockquote><p>
If you are 40, or older, you might think this is hilarious! </p>
<p>When I was a kid, adults used to bore me to tears with their tedious<br />
diatribes about how hard things were. When they were growing up; what with<br />
walking twenty-five miles to school every morning&#8230;. Uphill&#8230; Barefoot&#8230;<br />
BOTH ways. yadda, yadda, yadda</p>
<p> And I remember promising myself that when I grew up, there was no way in<br />
 hell I was going to lay a bunch of crap like that on my kids about how hard<br />
 I had it and how easy they&#8217;ve got it! </p>
<p>But now that I&#8217;m over the ripe old age of forty, I can&#8217;t help but look<br />
around and notice the youth of today You&#8217;ve got it so easy! I mean,<br />
compared to my childhood, you live in a damn Utopia!<br />
And I hate to say it, but you kids today, you don&#8217;t know how good you&#8217;ve got it!</p>
<ol>
<li>I mean, when I was a kid we didn&#8217;t have the Internet. If we wanted to<br />
 know something, we had to go to the damn library and look it up ourselves,<br />
 in the card catalog!!</li>
<li>There was no email!! We had to actually write somebody a letter &#8211; with a<br />
 pen! Then you had to walk all the way across the street and put it in the<br />
 mailbox, and it would take like a week to get there! Stamps were 10 cents! </li>
<li>Child Protective Services didn&#8217;t care if our parents beat us. As a<br />
 matter of fact, the parents of all my friends also had permission to kick<br />
 our ass! Nowhere was safe!</li>
<li>There were no MP3&#8242;s or Napsters or iTunes! If you wanted to steal music,<br />
 you had to hitchhike to the record store and shoplift it yourself!</li>
<li>Or you had to wait around all day to tape it off the radio, and the DJ<br />
 would usually talk over the beginning and @#*% it all up! There were no CD<br />
 players! We had tape decks in our car. We&#8217;d play our favorite tape and<br />
 &#8220;eject&#8221; it when finished, and then the tape would come undone rendering it<br />
 useless. Cause, hey, that&#8217;s how we rolled, Baby! Dig?</li>
<li>We didn&#8217;t have fancy crap like Call Waiting! If you were on the phone<br />
 and somebody else called, they got a busy signal, that&#8217;s it!</li>
<li>There weren&#8217;t any freakin&#8217; cell phones either. If you left the house, you<br />
 just didn&#8217;t make a damn call or receive one. You actually had to be out of<br />
 touch with your &#8220;friends&#8221;. OH MY GOSH !!! Think of the horror&#8230; not being<br />
 in touch with someone 24/7!!! And then there&#8217;s TEXTING. Yeah, right.<br />
 Please! You kids have no idea how annoying you are.</li>
<li>And we didn&#8217;t have fancy Caller ID either! When the phone rang, you had<br />
 no idea who it was! It could be your school, your parents, your boss, your<br />
 bookie, your drug dealer, the collection agent&#8230; you just didn&#8217;t know!!!<br />
 You had to pick it up and take your chances, mister!</li>
<li>We didn&#8217;t have any fancy PlayStation or Xbox video games with<br />
 high-resolution 3-D graphics! We had the Atari 2600! With games like<br />
 &#8216;Space Invaders&#8217; and &#8216;Asteroids&#8217;. Your screen guy was a little square! You<br />
 actually had to use your imagination!!! And there were no multiple levels<br />
 or screens, it was just one screen&#8230; Forever! And you could never win.<br />
 The game just kept getting harder and harder and faster and faster until you<br />
 died! Just like LIFE!</li>
<li>You had to use a little book called a TV Guide to find out what was on!<br />
 You were screwed when it came to channel surfing! You had to get off your<br />
 ass and walk over to the TV to change the channel!!! NO REMOTES!!! Oh, no,<br />
 what&#8217;s the world coming to?!?!</li>
<li>There was no Cartoon Network either! You could only get cartoons on<br />
 Saturday Morning. Do you hear what I&#8217;m saying? We had to wait ALL WEEK for<br />
 cartoons, you spoiled little rat-bastards!</li>
<li>And we didn&#8217;t have microwaves. If we wanted to heat something up, we<br />
 had to use the stove! Imagine that!</li>
<li>And our parents told us to stay outside and play&#8230; all day long. Oh,<br />
 no, no electronics to soothe and comfort. And if you came back inside&#8230;<br />
 you were doing chores!</li>
<li>And car seats &#8211; oh, please! Mom threw you in the back seat and you hung on.<br />
 If you were lucky, you got the &#8220;safety arm&#8221; across the chest at the last<br />
 moment if she had to stop suddenly, and if your head hit the dashboard, well<br />
 that was your fault for calling &#8220;shot gun&#8221; in the first place!</li>
<p>See! That&#8217;s exactly what I&#8217;m talking about! You kids today have got it too<br />
 easy. You&#8217;re spoiled rotten! You guys wouldn&#8217;t have lasted five minutes<br />
 back in 1970 or any time before!</p>
<p>Regards,<br />
The Over 40 Crowd
</p></blockquote>
<p>Received via email from my Dad today!</p>
]]></content:encoded>
			<wfw:commentRss>http://sixgun.co.uk/blog/2011/12/12/i-think-its-my-destiny-to-be-a-grumpy-old-man/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

