Uncategorized

Unity Messabout

Untitled 1

In the past I have used a few IOC containers such as

  • Castle
  • MEF

Where I work now they are using Unity which is not something I have looked at in
earnest before, so I decided to have a quick look at it, and post a small demo
project. So lets have a look at some samples code shall we. So here are the demo
classes that I will inject/inject into

public class Foo
{
    public int Age { get; set; }
}


public interface IFooController
{
    void Start();
}

public class FooController : IFooController
{
    private readonly Foo foo;

    public FooController(Foo foo)
    {
        this.foo = foo;
    }

    public void Start()
    {
        Console.WriteLine(string.Format("Foo.Age={0}", foo.Age));
    }
}


public class CompositeFoo
{
    [InjectionConstructor]
    public CompositeFoo(IEnumerable<IFoo> foos, Func<Foo> fooFactory, 
          Func<Foo, IFooController> fooControllerFactory)
    {
        var foo = fooFactory();
        var fooController = fooControllerFactory(foo);
        fooController.Start();
    }
}


public class CompositeFooBase
{
    [InjectionConstructor]
    public CompositeFooBase(IEnumerable<FooBase> foos)
    {

    }
}


public class CompositeFooBaseArrayCtor
{
    public CompositeFooBaseArrayCtor(FooBase[] foos)
    {

    }
}

public interface IFoo
{
        
}

public abstract class FooBase
{
        
}



public class FooI1 : IFoo
{
        
}
public class FooI2 : IFoo
{

}
public class FooI3 : IFoo
{

}

public class FooB1 : FooBase
{

}
public class FooB2 : FooBase
{

}
public class FooB3 : FooBase
{

}

That should be enough to give us enough variety to show of a few of the Unity
application blocks tricks, such as

  1. How to use named instances
  2. How to resolve single instances
  3. How to resolve mutiple instances
  4. How to resolve multiple instances using IEnumerable
  5. How to pick the constructor to inject
  6. How to inject a Func
  7. How to inject a Func and override its own constructor arguments

So those are the areas I have a code sample for, I think the best way it to just
list the code, so without further ado here is the code that demonstrates the
points above:

UnityContainer container = new UnityContainer();
container.RegisterInstance<FooBase>("NonDefaultFooBaseInstanceB1",new FooB1());
container.RegisterInstance<FooBase>("NonDefaultFooBaseInstanceB2", new FooB2());
container.RegisterType<FooBase, FooB1>("NonDefaultFooB1");
container.RegisterType<FooBase, FooB2>("NonDefaultFooB2");
container.RegisterType<IFoo, FooI1>();
container.RegisterType<IFoo, FooI2>("NonDefaultIFoo2");
container.RegisterType<IFoo, FooI3>("NonDefaultIFoo3");

container.RegisterInstance<Foo>("NamedFoo", new Foo() { Age = 23});
container.RegisterType<IFooController, FooController>();

container.RegisterType<Func<Foo>>(
    new InjectionFactory(c => new Func<Foo>(()=> c.Resolve<Foo>("NamedFoo"))));

container.RegisterType<Func<Foo, IFooController>>(
    new InjectionFactory(c =>
        new Func<Foo, IFooController>(
            foo => c.Resolve<FooController>(new DependencyOverride<Foo>(foo)))));

//can just register this to get around the fact that unity doesn't like IEnumerable in Ctor out of the box
container.RegisterType<IEnumerable<IFoo>, IFoo[]>();
container.RegisterType<CompositeFoo>();
container.RegisterType<CompositeFooBase>();
container.RegisterType<CompositeFooBaseArrayCtor>();

var x = container.RegisterType<CompositeFooBase>(new InjectionConstructor(container.ResolveAll<FooBase>()));

var fooBases = container.ResolveAll<FooBase>().ToList();
var iFoos = container.ResolveAll<IFoo>().ToList();
var iFoo = container.Resolve<IFoo>();
var iFooNamed = container.Resolve<IFoo>("NonDefaultIFoo2");
var compositeFoo = container.Resolve<CompositeFoo>();
var compositeFooBase = container.Resolve<CompositeFooBase>();
var compositFooBaseArray = container.Resolve<CompositeFooBaseArrayCtor>();

As alawys here is a small demo project so you can try this out for yourself

https://dl.dropboxusercontent.com/u/2600965/Blogposts/2013/UnityTest.zip

Advertisements
Uncategorized

Expression API Messabout

I have been using the Expression namespace in .NET for a while now, and at times it is truly useful, but whenever I look at it, I am always confused and wonder how to start with it. To this end I have decided to start this cheat sheet page, which shows how to do simple tasks using the Expression namespace. I will be adding to this over time.

Create a Delegate To Call A Method

This simple one creates a delegate that accepts an object argument, casts it to some type and calls a method on it, and returns the value from the delegate

If we were to do this with hardcoded code it would be something like this

(Object x) =>
{
 String target = x as String;
 return target.GetEnumerator();
}
string testString = "madness";
MethodInfo methInfo = typeof(string).GetMethod("GetEnumerator");
ParameterExpression param = Expression.Parameter(typeof(object), "target");

UnaryExpression cast = Expression.ConvertChecked(param, typeof(string));
Expression call = Expression.Call(cast, methInfo);
Func<object, CharEnumerator> executeAction = Expression.Lambda<Func<object, CharEnumerator>>(call, param).Compile();

//test it out
CharEnumerator enumerator = executeAction(testString);
while (enumerator.MoveNext())
{
Console.Write(enumerator.Current);
}

Running this code the output that I see in the Console is “madness”

Dynamic Where Clause

I often find that I have to build up a dynamic Where clause, and you either have to have lots of if/then else statements to build up pre-canned Func<T,TResult> or get clever with Expression Trees.

Suppose I have a simple Person class something like this

public class Person
{
 public string FirstName { get; set; }
 public string LastName { get; set; }

public Person(string firstName, string lastName)
 {
 this.FirstName = firstName;
 this.LastName = lastName;
 }

public override string ToString()
 {
 return String.Format("FirstName {0}, LastName {1}", FirstName, LastName);
 }
}

And that I wish to conduct the following dynamic filter on it at runtime

  • Find all Person objects that have a 1st name starting with “Ch”

If we were to do this with hardcoded code it would be something like this

people.Where(x=> x.FirstName.StartsWith("Ch");

Here some code that does that

List<Person> people = new List<Person>();
people.Add(new Person("Bert", "Adams"));
people.Add(new Person("Bradley", "Lones"));
people.Add(new Person("Charley", "Chalk"));

string propertyNameToSearchBy = "FirstName";
string searchType = "StartsWith";
string searchValue = "Ch";

var paramStart = Expression.Parameter(typeof(Person), "x");
Expression<Func<Person, bool>> func = Expression.Lambda<Func<Person, bool>>(
 Expression.Call(Expression.Property(paramStart,
 typeof(Person).GetProperty(propertyNameToSearchBy).GetGetMethod()),
 typeof(String).GetMethod(searchType.ToString(), new Type[] { typeof(String) }),
 new Expression[] { Expression.Constant(searchValue, typeof(string)) }),
 new ParameterExpression[] { paramStart });

Func<Person, bool> funcComp = func.Compile();

//test it out
foreach (Person person in people.Where(funcComp))
{
 Console.WriteLine(person);
}
Console.ReadLine();

Running this code the output that I see in the Console is “FirstName Charley LastName Chalk”

This is an uber simple example, but the important thing to note in there is that you can create a Where filter on the fly and those filter values could  come from the user through a UI or the database, so we could potentially create quite a few distinct Where filters using that one bit of code. The alternative would be to have loads of pre-canned delegates one for FirstName StartsWith filter, one for LastName StartsWith filter, using this method you can just fill in the values and let this delegate do its work.

Getting A Property Value From An Object

This is another convenient one, which simply grabs the value of a property from a source object. I will use the same “Person” object we just used

If we were to do this with hardcoded code it would be something like this

Person p = New Person("Bert", "Adams");
string thePersonsFirstName = (string)p.GetType().GetProperty("Person").GetValue(p, null);

So lets looks for a generic method that will work for us, ok this example Reflection would work to since its all based around magic strings

class Program
{
 static void Main(string[] args)
 {
 Person p = new Person("Bert", "Adams");

Console.WriteLine(GetValue<Person, string>(p, "FirstName"));
 Console.ReadLine();

}
 public static TResult GetValue<T, TResult>(T incoming, string propertyName)
 {
 PropertyInfo property = typeof(T).GetProperty(propertyName);
 ParameterExpression param = Expression.Parameter(typeof(T), "x");
 Expression propertyAccess = Expression.Property(param, property);
 Expression convert = Expression.Convert(propertyAccess, typeof(object));
 Func<T, object> lambda =
 Expression.Lambda<Func<T, object>>(convert, param).Compile();
 return (TResult)lambda(incoming);
 }
 public class Person
 {
 public string FirstName { get; set; }
 public string LastName { get; set; }

public Person(string firstName, string lastName)
 {
 this.FirstName = firstName;
 this.LastName = lastName;
 }

public override string ToString()
 {
 return String.Format("FirstName {0}, LastName {1}", FirstName, LastName);
 }
 }
}

Running this code the output that I see in the Console is “Bert”

Get A Property Value

Say you had this class and you wanted to grab the SomeString value

public class SomeType
{
  public static string SomeString
  {
    get { return “I am a string” }
  }
}

We could just make a small Lambda like this

var exp = Expression.Lambda<Func<string>>(
                Expression.Property(null, typeof(SomeType), “SomeString”));

return exp.Compile();

Other Sources

I also wrote a dedicated article on Expression API recipes with a cool american chap (Ian you know who you are). This article covered the following things

Here is a list of the scenarios we will be covering

  • Change tracker
  • Convert
  • Generic object HashCode computation
  • If-Then-Else
  • Property get/set
  • Dynamic where

Want to know more please read the full article over here

http://www.codeproject.com/Articles/651464/Expression-API-Cookbook

 

 

C#, CodeProject

MsBuild and NUnit (A Simple example)

I have never really been to actively involved with the build part of setting up continuous deployment environment, as such I have not had too much exposure to MsBuild.exe, ok I have done a bit with Nant.exe before, but MsBuild is still pretty novel to me.

Anyway I decided I needed a small demo concept to see if I could get something up and running, and what I decided to have a go at was the following

  • Build entire solution
  • Run the unit tests

 

Solution File

The 1st issue I had was that solution files are not in MsBuild format. Mmmm
how strange. Thing is this doesn’t really matter, there is nothing to stop you
creating a custom MsBuild file, which just has to be a valid msbuild file.

Here is what my solution structure looked like

Like I say all I wanted to do was build the solution and run the tests.

So without further ado lets see what my msbuild file ended up looking like
shall we:

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Run">
<UsingTask AssemblyFile="$(MSBuildStartupDirectory)\Lib\MsBuildCommunityTasks\MSBuild.Community.Tasks.dll" TaskName="NUnit"/>
	<PropertyGroup> 
    <!-- After Compile: Result will be saved in OutDir -->
    <OutDir>$(MSBuildStartupDirectory)\OutDir\</OutDir>
    
    <!-- Configuration -->
    <Configuration>Release</Configuration>
    
    <!-- Solutionproperties-->
    <SolutionProperties>
      OutDir=$(OutDir);
      Platform=Any CPU;
      Configuration=$(Configuration)
    </SolutionProperties>
	</PropertyGroup>
	<ItemGroup>
		<Solution Include="NUnit.MsBuildDemo.sln">
			<Properties>
				$(SolutionProperties)
			</Properties>
		</Solution>
	</ItemGroup>
	<Target Name="Run">
    
    <CallTarget Targets="BuildSolution" />
    <CallTarget Targets="RunTests" />

  </Target>

  <PropertyGroup>
	<NUnitResultsFile>$(OutDir)\nunit-result.xml</NUnitResultsFile>
  </PropertyGroup>



  <Target Name="BuildSolution">
    <Message Text="BuildSolution called." />
    <MSBuild Projects="@(Solution)"/>
  </Target>


  <Target Name="RunTests">
    <CreateItem Include="$(OutDir)*.Tests.dll">
      <Output TaskParameter="Include" ItemName="TestAssembly" />
    </CreateItem>
    <NUnit 	Assemblies="@(TestAssembly)" 
		ToolPath="C:\Program Files (x86)\NUnit 2.6.2\bin"
		OutputXmlFile="$(NUnitResultsFile)"
	/>
  </Target>


</Project>

 

I did actually get this from someones blog, but I seem to have lost the link,
so if you think you know which one it was let me know, and I’ll put a link to it
here.

 

I don’t think that is too bad, and that hard to understand, we simply do
these things:

  1. Setup some solution properties
  2. Use the MsBuild msbuild task to build the solution
  3. Use the MsBuild Community Tasks to run Nunit (making sure we point to
    the version we want to use)
  4. The built files and test results will be in a folder names OutDir after
    we run this custom msbuild file

In order to run this custom msbuild file we simply use the following command
line:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
NUnit.MsBuildDemo.build /t:Run

 

MsBuild Community Tasks

The

MsBuild Community Tasks are awesome and they have many many useful MsBuild
tasks in them, I would encourage all of you to check them out at :


https://github.com/loresoft/msbuildtasks

 

As always here is a small demo project :

C#, CodeProject

Simple But Nice State Machine

As part of something that I was messing around with the other day I wanted to use a state machine, so decided to have a quick hunt around before reinventing the wheel. My search yielded a few interesting things, namely the following:

  • BBV Common : This is a pretty neat library for .NET which includes the following components to name a few
    • StateMachine
    • BootStrapper
    • EvaluationEngine
    • EventBroker
  • Stateless : This is a very easy to use state machine by Nicholas Blumhardt who is also responsible for AutoFac which is a very nice IOC Container. Nick also worked on MEF, so I think it is fair to say Nick knows his onions.

I opted for using Stateless for what I wanted to do, the documentation is pretty good and comes with a few samples. But for the sake of completeness lets go through a simple example now shall we.

Suppose we have a state machine that looks something like this

stateDemo

It is a simple state machine that actually models our JIRA work flow at work. So how might I implement that using Stateless? Well it is actually pretty easy, all we need to do is carry out  few steps

1. Create A State Machine

 StateMachine<state, Trigger> 

This allows us to create a StateMachine which will use a State object for its states, and a a Trigger for its triggers

The really nice thing about Stateless is that it allows you to create your own State types and trigger types. So we are free to create
our own state types, such as the following

public class State
{
    public string Name { get; private set; }

    ///
    /// Stateless has OnEntry/OnExit actions that can be run, but this just illustrates how you
    /// could go about creating your own states that run their own actions where good encapsulation is
    /// observed
    ///
    public Action OnEntryStateAction { get; private set; }

    ///
    /// Stateless has OnEntry/OnExit actions that can be run, but this just illustrates how you
    /// could go about creating your own states that run their own actions where good encapsulation is
    /// observed
    ///
    public Action OnExitStateAction { get; private set; }

    public State(string name, Action onEntryStateAction, Action onExitStateAction)
    {
        Name = name;
        OnEntryStateAction = onEntryStateAction;
        OnExitStateAction = onExitStateAction;
    }
}

2. Define some triggers

This can be any type you want, I opted for enum values, so for my example this look like this

 private enum Trigger { StartDevelopment, DevelopmentFinished, StartTest, TestPassed, TestFailed } 

3. Setup your statemachine

This is the major part of what you need to do, but it does boil down to a few simple steps

3.1 Initialise the statemachine

Ensure you state machine starts in the correct state

 jiraMachine = new StateMachine<state, Trigger>(states["ReadyForDevelopment"]); 

3.2 Configure all your states

Stateless provides an excellent API for setting up your states, and allows for many different configuration(s) to be expressed in code.

This is the biggest part of what you will need to do, in this step you configure the following elements of the state

  • OnEntry, which allows you to specify what you want done on entering of that state
  • OnExit, which allows you to specify what you want done on exiting of that state
  • Permit, which allows you to specify what triggers are permitted to allow this state to be transitioned to a new state
jiraMachine.Configure(states["ReadyForDevelopment"])
    .OnEntry(s => PrintStateOnEntry())
    .OnExit(s => PrintStateOnExit())
    .Permit(Trigger.StartDevelopment, states["InDevelopment"]);

3.3 Firing Triggers

Once you have your state machine setup you can simply fire triggers to transition from one state to another

Here is an example of that

Fire(jiraMachine, Trigger.StartDevelopment);

So I think that covers the basics, I think it’s time to see a fuller example, so lets look at a little sample. This sample follows the state machine diagram above. I have included one small imbellishment, which is a tiny bit of Reactive Extensions (Rx) to have a certain action performed (ok its a simple Console.Writeline but it could be anything you want) when you are within the “InDevelopment” state.

By using Rx we can simply Dispose of the IObservable subscription when we exit the state, which I think is nice

Anyway enough chat here is the full example

class Program
{
    private enum Trigger
    {
        StartDevelopment,
        DevelopmentFinished,
        StartTest,
        TestPassed,
        TestFailed
    }
    private Dictionary<string, State> states = new Dictionary<string, State>();
    private CompositeDisposable disposables = new CompositeDisposable();
    private StateMachine<State, Trigger> jiraMachine;

    //Toggle this to see the effect of states with multiple next states
    private bool simulateTestPassing = false;

    public Program()
    {
        states.Add("ReadyForDevelopment", new State("ReadyForDevelopment", null, null));
        states.Add("InDevelopment", new State("InDevelopment",
            (x) => Console.WriteLine(string.Format("Entered InDevelopment {0} State", x.Name)),
            (x) => Console.WriteLine(string.Format("Exited InDevelopment {0} State", x.Name))));
        states.Add("ReadyForTest", new State("ReadyForTest", null, null));
        states.Add("InTest", new State("InTest", null, null));
        states.Add("Closed", new State("Closed", null, null));
    }

    public void Run()
    {
        jiraMachine = new StateMachine<State, Trigger>(states["ReadyForDevelopment"]);

        jiraMachine.Configure(states["ReadyForDevelopment"])
            .OnEntry(s => PrintStateOnEntry())
            .OnExit(s => PrintStateOnExit())
            .Permit(Trigger.StartDevelopment, states["InDevelopment"]);

        jiraMachine.Configure(states["InDevelopment"])
            .OnEntry(s =>
                            {
                                disposables.Add(Observable.Interval(TimeSpan.FromSeconds(1))
                                .Subscribe(x => SendStyleCopNagEmail()));
                                jiraMachine.State.OnEntryStateAction(jiraMachine.State);
                            })
            .OnExit(s =>
                        {
                            disposables.Dispose();
                            jiraMachine.State.OnExitStateAction(jiraMachine.State);
                        })
            .Permit(Trigger.DevelopmentFinished, states["ReadyForTest"]);

        jiraMachine.Configure(states["ReadyForTest"])
            .OnEntry(s => PrintStateOnEntry())
            .OnExit(s => PrintStateOnExit())
            .Permit(Trigger.StartTest, states["InTest"]);

        jiraMachine.Configure(states["InTest"])
            .OnEntry(s => PrintStateOnEntry())
            .OnExit(s => PrintStateOnExit())
            .Permit(Trigger.TestFailed, states["InDevelopment"])
            .Permit(Trigger.TestPassed, states["Closed"]);

        jiraMachine.Configure(states["Closed"])
            .OnEntry(s => PrintStateOnEntry())
            .OnExit(s => PrintStateOnExit());

        Fire(jiraMachine, Trigger.StartDevelopment);

        Action completeTheRemainingStates = () =>
            {
                Fire(jiraMachine, Trigger.DevelopmentFinished);
                Fire(jiraMachine, Trigger.StartTest);
                if (simulateTestPassing)
                {
                    Fire(jiraMachine, Trigger.TestPassed);
                }
                else
                {
                    Fire(jiraMachine, Trigger.TestFailed);
                }
            };

        disposables.Add(Observable.Timer(TimeSpan.FromSeconds(5))
            .Subscribe(x =>
            {
                completeTheRemainingStates();
            }));

        Console.ReadKey(true);
    }

    static void SendStyleCopNagEmail()
    {
        Console.WriteLine("Don't forget to use StyleCop settings for any JIRA checkin");
    }

    static void Fire(StateMachine<State, Trigger> jiraMachine, Trigger trigger)
    {
        Console.WriteLine("[Firing:] {0}", trigger);
        jiraMachine.Fire(trigger);
    }

    void PrintStateOnEntry()
    {
        Console.WriteLine(string.Format("Entered state : {0}", jiraMachine.State.Name));
    }

    void PrintStateOnExit()
    {
        Console.WriteLine(string.Format("Exited state : {0}", jiraMachine.State.Name));
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        p.Run();
    }
}

When you run this you should see some output something like this

[Firing:] StartDevelopment
Exited state : ReadyForDevelopment
Entered InDevelopment InDevelopment State
Don’t forget to use StyleCop settings for any JIRA checkin
Don’t forget to use StyleCop settings for any JIRA checkin
Don’t forget to use StyleCop settings for any JIRA checkin
Don’t forget to use StyleCop settings for any JIRA checkin
Don’t forget to use StyleCop settings for any JIRA checkin
[Firing:] DevelopmentFinished
Exited InDevelopment InDevelopment State
Entered state : ReadyForTest
[Firing:] StartTest
Exited state : ReadyForTest
Entered state : InTest
[Firing:] TestFailed
Exited state : InTest
Entered InDevelopment InDevelopment State

So I think you will agree Stateless is pretty cool, and well worth a look. As always here is a small demo app

StatelessDemo.zip