Dependency Injection with Unity: passing runtime parameters

Today, I had a problem of how to construct an object passing a specific date into the constructor. Normally, this is not an issue encountered frequently as only “services” are passed via constructor injection. This time however, I needed to make sure a date was passed when the object was created, and this date needs to be evaluated each time.

I’m not a fan of the “initialise” pattern, so that was out. Here is how I solved the problem using Unity DI Container.

First, I defined a dependency and an implementation:

    public interface IService
    {
        void DoSomething();
    }


    public class Service : IService
    {
        private readonly DateTime date;

        public Service(DateTime date)
        {
            this.date = date;
        }        

        public void DoSomething()
        {
            Console.WriteLine(date);
        }
    }

Then, configure the container, and attempt to make some calls:

IUnityContainer container = new UnityContainer();
container.RegisterType<IService, Service>(
  new InjectionConstructor(
    new InjectionParameter<DateTime>(DateTime.Now)
  ));

var dateService = container.Resolve<IService>();
// prints datetime container was configured
dateService.DoSomething(); 

Console.Read();
// still datetime container was configured
dateService.DoSomething(); 

Ok, so this is not doing what I wanted. The DateTime is being captured. This is not surprising, as the value is copied into the constructor.

If we resolve the item from the container again, we still get the same value:

dateService = container.Resolve<IService>();
// still datetime container was configured with
dateService.DoSomething();

This was annoying, it seems we need some sort of factory or delegate that is resolved each time the object is constructed:

    public interface IDateFetchingFactory
    {
        DateTime GetDate();
    }

    public class DateFetchingFactory : IDateFetchingFactory
    {
        public DateTime GetDate()
        {
            return DateTime.Now;
        }
    }

    public class Service2 : IService
    {
        private readonly IDateFetchingFactory dateFetchingFactory;        

        public Service2(IDateFetchingFactory dateFetchingFactory)
        {
            this.dateFetchingFactory = dateFetchingFactory;
        }

        public void DoSomething()
        {
            Console.WriteLine(dateFetchingFactory.GetDate());    
        }
    }

Now we can register our new type:

container.RegisterType<IService, Service2>("Service2");
container.RegisterType<IDateFetchingFactory, DateFetchingFactory>();

and each time we make a call, we get the behaviour we wanted:

dateService.DoSomething(); // datetime when method call was made via factory
Console.Read();

dateService.DoSomething(); // a different datetime from factory

There must be other ways of achieving this, is there a better way?

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Dependency Injection with Unity: passing runtime parameters

Flexible layout with WPF GridSplitter

Here is a quick sample showing how it is possible to create a flexible resizeable layout in WPF with a GridSplitter. Here we see how you can change the size of panes in a vertical and horizontal direction.

And the Xaml:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Grid>
      <Grid.RowDefinitions>
         <RowDefinition Height="*"/>
         <RowDefinition Height="Auto"/>
         <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
      <Grid Grid.Row="0">
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
         </Grid.ColumnDefinitions>
         <Label Grid.Column="0">Row 0, Column 0</Label>
         <GridSplitter
            Width="5"
            Grid.Column="0"
            Background="Blue"
            ShowsPreview="True"/>
         <Label Grid.Column="2">Row 0 Column 2</Label>
      </Grid>
      <GridSplitter
         Height="5"
         Grid.ColumnSpan="3"
         Grid.Row="1"
         HorizontalAlignment="Stretch"
         VerticalAlignment="Stretch"
         Background="Black"
         ResizeDirection="Rows"
         ShowsPreview="true"/>
      <Grid Grid.Row="2">
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
         </Grid.ColumnDefinitions>
         <Label Grid.Column="0">Row 2, Column 0</Label>
         <GridSplitter
            Width="5"
            Grid.Column="0"
            Background="Blue"
            ShowsPreview="True"/>
         <Label Grid.Column="2">Row 2 Column 2</Label>
      </Grid>
   </Grid>
</Page>
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Flexible layout with WPF GridSplitter

NUnit Constraints

For some reason, I have ignored the NUnit syntax around Assert.That up to now. I thought it was one of these experiments around a fluent interface which didn’t offer any advantages over the existing API.

I wanted to write a test that tested whether a value was as expected, but within a certain range. I had previously used Assert.Equals with the overload that takes a delta.

Here is an alternative implementation:

[Test]
public void MinValue_IsCloseToMinimum_OfAllBids()
{
var lowPrice = new Price(10, 20);
var otherPrice = new Price(11, 20);

var priceViewModel =
new PriceViewModel(new List {lowPriceTolerance, otherPriceTolerance});

//old api
Assert.AreEqual(10, Convert.ToDouble(priceViewModel.MinValue), 0.2);

// new api
Assert.That(priceViewModel.MinValue, Is.EqualTo(10).Within(0.2));
}

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on NUnit Constraints

Javascript Learning Resources

I am making a concerted effort to really *learn* javascript at the moment.
There are a load of great resources out there.

Here is the beginnings of a list:

Douglas Crockford’s Home Page
JavaScript Garden – advanced topics
Learn JavaScript by making tests pass
Mozilla JavaScript reference
JQuery Guide
Run JavaScript in your browser with jsfiddle
Another online IDE

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Javascript Learning Resources

Contrawhatywho – nicer generics in C# 4.0

Everyone probably knows this already, but it’s probably easy to miss as *stuff now just works*. Contravariance, or covariance is now improved to make working with generics that little bit simpler.

The following code now compiles fine in .net 4, but won’t compile against .net 3.5:

class Program
{
static void Main(string[] args)
{
Animal a = new Animal();
Bear b = new Bear();
IList<Bear> bears = new List<Bear>();
bears.Add(b);
IEnumerable<IAnimal> animals = bears;
}

class Animal : IAnimal
{
public override string ToString()
{
return “I am an animal”;
}
}

   class Bear : IAnimal
   {
       public override string ToString()
       {
           return "I am a bear";
       }
    } 

    internal interface IAnimal
    {
    }
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Contrawhatywho – nicer generics in C# 4.0

Console2 and Cygwin – how to setup

So, I’ve set up my console how Scott Hanselman recommended.

This is how I managed to get Cygwin to work correctly as a shell.

You just need to set your shell to:

%cygwin-path%\bin\bash.exe --login -i
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Console2 and Cygwin – how to setup

XCopy your dependencies in a pre-build step

Ok, again – this isn’t really ground breaking or anything, but if you have a load of dependencies that you need to copy at build time to your bin folder, this is a nice script that goes into the pre-build events section of visual studio.

xcopy ..\..\..\lib\whateverframework\*.* . /E /D

The really neat part, is the /D switch  – this only copies files that have changed since they were last modified.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on XCopy your dependencies in a pre-build step

Distinct in Linq

Sometimes, in .net it can get a bit confusing about which interface you need to implement for to get object equality to work correctly. When using the Distinct extension method in Linq, IEqualityComparer<T> is very useful

var items = new List<Cheese>();
items.Add(new Cheese { Name = "Cheddar" });	
items.Add(new Cheese { Name = "Cheddar" });	
items.Add(new Cheese { Name = "Red Leicester" });	
items.Add(new Cheese { Name = "Stilton" });	
var distinct = items.Distinct();	

foreach (var item in distinct) {	
    Console.WriteLine (item.Name);	
}

//outputs
// Cheddar
// Cheddar
// Red Leicester
// Stilton

The key part is implementing GetHashCode so that the two objects will return the same hash code.

An example implementation:

class CheeseNameComparer : IEqualityComparer<Cheese> {	

 public bool Equals (Cheese x, Cheese y)	{ 
  return x.Name == y.Name;		
 }

 public int GetHashCode (Cheese obj) {
  return obj.Name.GetHashCode();
 }
}

distinct = items.Distinct(new CheeseNameComparer());
foreach (var item in distinct) {
  Console.WriteLine (item.Name);
} 
//outputs
// Cheddar
// Red Leicester
// Stilton
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Distinct in Linq

Finding Stuff

A little bit of unix command knowledge can often save a stack of time even on a windows box. This little snippet was really useful when I was trying to find out which file a function was declared in:

find . -name "*.h" | xargs grep textToSearchFor
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Finding Stuff

Batch Updates in .Net

Some rough notes about my investigations into different techniques to perform batch database updates.

It’s not efficient to send individual queries from an application to the database server. What techniques can be used from .net to send batch updates?

ETL

Most ETL processes probably uses either Bulk Insert, BCP, SSIS, or some fun third party product.

ADO.NET Options

Array and function

Use an Sql function to convert to table variable, and join on the table variable.
Old but nice explanantion of this technique – http://odetocode.com/code/365.aspx
Pass delimited list of “things” you wish to update. e.g. customer id’s “1|2|14|42”.

Table variable

Construct a table variable in code using SqlDbType.Structured and specify the table type
Pass to stored procedure or inline sqlCreate a User Defined Table Type
http://msdn.microsoft.com/en-us/library/bb675163.aspx

ADO.NET batch size

Set an UpdateBatchSize. Configure, update, insert, delete behaviour
http://msdn.microsoft.com/en-us/library/aadf8fk2.aspx

SqlBulkCopy

Like the name suggests copy only. Sql Server only.
Microsoft describe functionality as a managed equivalent to the bcp utility.
http://www.sqlteam.com/article/use-sqlbulkcopy-to-quickly-load-data-from-your-client-to-sql-server

ORM Tools

Generally, ORM tools are not built to handle batch processing. As an illustration, Rhino ETL exists, rather than the author using NHibernate as you might expect – http://ayende.com/Blog/archive/2008/01/16/Rhino-ETL-2.0.aspx

As a rule of thumb, the techniques available in ORM tools are suitable for “small” batch updates that occur in an application, not for creating ETL processes.

NHibernate

Can pass HQL across or set batch size – http://stackoverflow.com/questions/780940/batch-update-in-nhibernate

Linq 2 Sql

Nothing out of the box. Normally fire insert/update/delete statement for each object you wish to update. Can create extension methods to get batch like behaviour. http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx

Simple.Data

Need to explore:
Can use dynamic api – db.Foo.UpdateByX(X: “Bar”, Y: “Quux”, Z: 42) updates all Foo where X = “Bar”, sets Y and Z.

Entity Framework

Nothing out of the box. Can specify SQL to run – http://stackoverflow.com/questions/1781175/entity-framework-4-multiple-object-deleteremoveall

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Posted in Uncategorized | Comments Off on Batch Updates in .Net