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

Unity Singleton / Unit testing / Mocking

It’s been a while since I did a blog post (that is something I aim to fix), but just for now here is a small one.

The other day, I was confronted with a class that I had to test/mock, and it had this hardcoded dependency on a IOC container item (we are using the Unity application block) in its constructor

public interface ISecurityProvider
{
    IList Privileges { get; }
}

public class SecurityProvider : ISecurityProvider
{
    private SecurityContext context;

    public SecurityProvider()
    {
        context = IOCManager.Instance.Container.Resolve();
    }

    public IList Privileges
    {
        get { return context.Privileges; }
    }
}

Where the SecurityContext class looks like this

public class SecurityContext
{
    public SecurityContext(List privileges)
    {
        this.Privileges = privileges;
    }

    public List Privileges { get; set; }
}

And the IOC manager looks somethi

public class IOCManager
{
    private static Lazy instance = new Lazy(()=> new IOCManager());

    private IOCManager()
    {
            Container = new UnityContainer();
    }

    static IOCManager()
    {

    }

    public static IOCManager Instance
    {
        get { return instance.Value; }
    }

    public UnityContainer Container { get; set; }
}

And the IOC configuration looks like this

List privileges = new List();
privileges.Add("CanTrade");
privileges.Add("CanPrice");

SecurityContext sc = new SecurityContext(privileges);

IOCManager.Instance.Container.RegisterInstance(sc, new ContainerControlledLifetimeManager());
IOCManager.Instance.Container.RegisterType<ISecurityProvider, SecurityProvider>();

Now the question is, how do you get the singleton instance to ever return anything other than the “CanTrade” and “CanPrice”?????

The trick to this is the ContainerControlledLifetimeManager. By holding an instance of this we can use the SetValue(..) method to set a new singleton value.

Here is a full source dump

class Program
{
    static void Main(string[] args)
    {
        ContainerControlledLifetimeManager manager = new ContainerControlledLifetimeManager();

        List privileges = new List();
        privileges.Add("CanTrade");
        privileges.Add("CanPrice");

        SecurityContext sc = new SecurityContext(privileges);

        IOCManager.Instance.Container.RegisterInstance(sc, manager);
        IOCManager.Instance.Container.RegisterType<ISecurityProvider, SecurityProvider>();

        //1st singleton, should show 2 privileges
        Console.WriteLine("1st singleton");
        Console.WriteLine(IOCManager.Instance.Container.Resolve()
                            .Privileges.Aggregate((x, y) => string.Format("-{0} -{1}", x, y)));

        privileges = new List();
        privileges.Add("CanTrade");
        privileges.Add("CanPrice");
        privileges.Add("CanAutoBook");

        sc = new SecurityContext(privileges);
        manager.SetValue(sc);

        //new singleton, should show 3 privileges
        Console.WriteLine("\r\n");
        Console.WriteLine("new singleton");
        Console.Write(IOCManager.Instance.Container.Resolve()
                            .Privileges.Aggregate((x, y) => string.Format("-{0} -{1}", x, y)));
        Console.ReadLine();
    }
}

When this is run you should see the following output:

1st singleton
-CanTrade -CanPrice

new singleton
-CanTrade -CanPrice -CanAutoBook

As always here is a small demo app:

demo project.zip

SignalR Self Hosting With .NET Client

If you have not heard of SignalR, you can think of it as a kind of RPC (remote procedure call), but it is much more advanced than that, where clients may be called by server code, and clients may call server code.

 

Here is what the SignalR web site has to say about itself:

 

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It’s the ability to have your server-side code push content to the connected clients as it happens, in real-time.

You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques and technologies when it isn’t, while your application code stays the same.

SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients’ browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

http://signalr.net/

 

I first wrote about SignalR a while back when I wrote this article with my partner in crime Richard King (Kingo to those that know him) :

http://www.codeproject.com/Articles/324841/EventBroker

At the time SignalR was very novel (even  though that article was only written a year ago) and the only option at that time was a JavaScript client with a ASP .NET hosted Hub. Things have obviously come on leaps and bounds since then. Now there are all sorts of options for using SignalR, here are some options available to you now

  • .NET client (OWIN) client (OWIN was new to me, here is what it means : Open Web Interface for .NET which you can read about more here : OWIN)
  • Azure client
  • Javascript client
  • Redis client

There is also the possibility to self host the Hub which was of particular interest to me for a new side project I wanted to work on. To this end I decided to give the following scenario a go:

 

  • A simple echo hub that would receive messages as strings, which would be reversed and sent to ALL connected clients. Now the clients could be .NET or JavaScript or any of the other supported hubs. For my requirements .NET was all I cared about.
  • A .NET client that would send messages to the server (via the console standard input), and would print out any messages from the server (via the console standard output)

 

The reason I decided to give this a go is that I could not find a single source which had a running demo example of self hosting, and using .NET as a client. So I hope this helps someone.

 

So without further ado, lets look at some code

 

SERVER

The most relevant parts of the server are shown below:

 

Program (main entry point)


public class Program
{
    static void Main(string[] args)
    {
        using (WebApplication.Start<Startup>("http://localhost:8080/"))
        {
            Console.WriteLine("Server running at http://localhost:8080/");
            Console.ReadLine();
        }
    }
}

 

Startup

This is the code that will initiate a connection


public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapConnection<RawConnection>("/raw", new ConnectionConfiguration { EnableCrossDomain = true });
        app.MapHubs();
    }
}

 

The Hub

This is what clients will talk to


public class MessageRecievingHub : Hub
{
    public void SendMessage(string message)
    {
        Console.WriteLine(message);
        string it = new string(message.Reverse().ToArray());
        Clients.All.broadCastToClients(it);
    }
}

 

.NET CLIENT

So how about the client, well that is as simple as this:


class Program
{
    static void Main(string[] args)
    {
        var hubConnection = new HubConnection("http://localhost:8080/");
        var serverHub = hubConnection.CreateHubProxy("MessageRecievingHub");
        serverHub.On("broadCastToClients", message => System.Console.WriteLine(message));
        hubConnection.Start().Wait();
        string line = null;
        while ((line = System.Console.ReadLine()) != null)
        {
            // Send a message to the server
            serverHub.Invoke("SendMessage", line).Wait();
        } 

        System.Console.Read();
    }
}

 

As always here is a small demo project : https://dl.dropbox.com/u/2600965/SignalRClientServer.zip

WCF And the : “Your process does not have access rights to“ PITA

image

 

No matter how many times I create a new WCF service, I seem to always end up with this error.  I know the answer its to do with the UAC in machines Vista and above, and there are various tools to fix this. And there is also some web site that you used to get redirected to. For anyone else that has this issue running a Command Line as Administrator and running a command line similar to this should fix the issue

 

netsh http add urlacl url=http://+:PORT/WCF_SERVICE_NAME/ user=MACHINE\USERNAME

 

 

Hope that helps someone.

 

PS : for some free tools that do the same, have a look here:

 

Barbarian IOC

At work I have used a variety of IOC Containers including

And I have used others such as Unity/StructureMap/AutoFac. They are all very  good and very rich.

For those of you who don’t know what IOC stands for, it stands for Inversion  Of Control. Which is described as follows:

In software engineering, inversion of control (IoC) is a programming  technique, expressed here in terms of object-oriented programming, in which  object coupling is bound at run time by an assembler object and is typically not  known at compile time using static analysis.

In traditional programming, the flow of the business logic is determined  by objects that are statically assigned to one another. With inversion of  control, the flow depends on the object graph that is instantiated by the  assembler and is made possible by object interactions being defined through  abstractions. The binding process is achieved through dependency injection,  although some argue that the use of a service locator also provides inversion of  control.

In order for the assembler to bind objects to one another, the objects  must possess compatible abstractions. For example, class A may delegate behavior  to interface I which is implemented by class B; the assembler instantiates A and  B then injects B to A.

In practice, inversion of control is a style of software construction  where reusable code controls the execution of problem-specific code. It carries  the strong connotation that the reusable code and the problem-specific code are  developed independently, which often results in a single integrated application.  Inversion of control as a design guideline serves the following purposes:

  • There is a decoupling of the execution of a certain task from  implementation.
  • Every module can focus on what it is designed for.
  • Modules make no assumptions about what other systems do but rely on  their contracts.
  • Replacing modules has no side effect on other modules.
  • Inversion of control is sometimes facetiously referred to as the  "Hollywood Principle: Don’t call us, we’ll call you", because program logic  runs against abstractions such as callbacks.

Wikipedia : up on date 25/02/2013

Thing is I have always wanted to try and make one of these  myself, just to see what is involved. I did not want to go too nuts on this, and  just wanted the following really:

  1. Instance configuration : singleton / transient
  2. Simple registration process, maybe some sort of fluent interface
  3. Use the Expression API to compile into delegates for quick creation of  objects
  4. Constructor / property injection
  5. Provide the ability to accept non IOC held constructor parameters

So those couple of points are ALL I wanted to get working. As I say there are  a whole slew of full fledged IOC containers out there (where I have named a few  above), this articles container is more of a learning exercise, that I thought  I would share, in case anyone else is interested in this sort of thing.

I am calling my container BarbarianIOC as the existing  containers all seems to have these short snappy names, and it’s kind of play on  my name, and if you saw me without a shave I do kinda look a bit like a  barbarian.

 

 

If you want to read more you can grab the rest of the article and the source over at codeproject : http://www.codeproject.com/Articles/552514/BarbarianIOC-A-simple-IOC-Container

Unable to obtain public key for StrongNameKeyPair

Yesterday I had to build our entire application on a box that is not my own. Sounds easy enough, just

  1. Grab all code from source control
  2. Grab any 3rd party libs
  3. Build

All went ok until I tried to build a project that used the Castle Windsor IOC container, and I got this  :

System.ArgumentException: Unable to obtain public key for StrongNameKeyPair..

System.Reflection.StrongNameKeyPair.nGetPublicKey(Boolean exported, Byte[] array, String container) System.Reflection.StrongNameKeyPair.get_PublicKey() System.AppDomain.InternalDefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, StackCrawlMark& stackMark, IEnumerable`1 unsafeAssemblyAttributes) System.AppDomain.DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName) Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithStrongName() Castle.DynamicProxy.ModuleScope.ObtainDynamicModule(Boolean isStrongNamed) Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope, String name, Type (blah blah snip)

 

Massive sadness…..   <|:-(

Turns out that this is due to a permissions issue on the box I was using, where I did not have the correct privileges to create a new strong name key, due to to folder access rights. Boo

There is a special directory which has all the Crypto stuff in it :

C:\ProgramData\Microsoft\Crypto

  • DSS
  • Keys
  • RSA
  • SystemKeys

And it turns out you need to have full access to the C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder in particular.

One I found that folder and gave myself full read/write/delete access, my problem was solved.

Hope that helps someone else out. There was something like this on Stack Overflow which also helped me out : http://stackoverflow.com/questions/2425667/strongnamekeypair-problem-when-attempting-to-use-moq

Windows 8 : Fun With Sensors

It has been a while since I have written an article, and I thought it was about time that I wrote one. This one is a very small one (which is somewhat unusual for me). It is a very very simple one on using some of the Windows 8 sensors. I am lucky enough to own a Windows 8 laptop that has the full compliment of sensors. So what does it do I hear you ask? Sensors are all about stuff happening, so I thought it should be some code that is quite reactive to the sensors that I chose to use. With that in mind what I thought might be cool would be to host Google Earth and have that either displaying the Earth or the Sky depending on the value of the LightSensor. When the hosted Google Earth is flipped between Earth/Stars the skin of the application is also swapped. Hopefully by swapping these 2 visual elements in reaction to the LightSensor you can see how the LightSensor code is working.

I also thought it might be fun to have the Earth/Sky change Latitude/Longitude as you tilt the laptop which causes the inbuilt Gyrometer to push out new readings.

In a nutshell that is all this article does, its quite simple, anyway if you want to know more here is a link to the article : http://www.codeproject.com/Articles/536507/Windows-8-Fun-with-sensors

Node.Js / Express / Stylus / Jade / MongoDB / D3.js / Socket.IO

As the title states I have been messing around for a little while creating a small demo app that utilises some of the Node.js technology stack.

I have done this to get to try Node.js for myself. I can’t say I would swap to using it over ASP MVC and SignalR say. It has however been fun and quite intuitive for the most part, which I was surprised at. I have actually found the Node.js community to be quite lively and doing some good work.

Anyway if you fancy a read, here is a link to my article : http://www.codeproject.com/Articles/523451/Node-Js-And-Stuff

2013 Gift Horse : I’m An MVP For 2013

So I have been a bit quite on the old blog/article front of late, and I will be fixing that soon. Watch one for one on Node.Js which should be out very soon, where you can see it here/codeproject.

In the mean time I am very happy to announce that the nice people at Microsoft have seen fit to give me a MVP award for 2013. Cool. Thanks Microsoft

MVVM Diagram Designer

A while back a user called “sucram (real name Marcus)” posted a series of articles here about how to create a diagram designer using WPF. Sucrams original links are as follows:

I remember being truly blown away by this series of articles, as they showed you how to do the following things:

  • Toolbox
  • Drag and Drop
  • Rubber band selection using Adorners
  • Resizing items using Adorners
  • Rotating items using Adorners
  • Connecting items
  • Scrollable designer surface, complete with zoombox

WOW that sounds fantastic, sounds exactly like the sort of things you would need to create a fully functional diagram designer. Well Yeah, its was and still is, but……..the thing is I have used WPF a lot, and trying to use the code attached to sucrams series of article in WPF just wasn’t that great. He had taken a very control centric view, in that everything was geared around adding new controls and supplying static styles for said controls.

In reality it was more like working with a Win Forms application. Not that there is anything wrong with that, and I really truly do not mean to sound ungrateful, as that could not be further from the truth, without that original series of articles it would have taken me a lot longer to come up with a working diagram designer that I was happy with. So for that I am truly grateful, thanks sucram you rock.

Anyway as I say sucrams original codebase took a very control centric point of view, and added controls using code behind, and held collections of items directly in the diagram surface control. As I say if that is what you want cool, however, it was not what I wanted. What I wanted was

  • All of the features of curams original code (actually I didn’t want any rotating of items, or resizing of items)
  • A more MVVM driven approach, you know allow data binding of items, delete of items via ICommand etc. etc.
  • Allow me to control the creation of an entire diagram from within a single ViewModel
  • Allow for complex objects to be added to the diagram i.e. ViewModels that I could style using DataTemplate(s). Sucrams original code only allowed simply strings to be used as a DataContext which would control what ImageSource an Image would use to show for a diagram item. I needed my items to be quite rich and allow popups to be shown and associated with the diagram item, such that the data related to the diagram item could be manipulated
  • Allow me to save the diagram to some backing store
  • Allow me to load a previously saved diagram from some backing store

To this end I have pretty much completely re-written sucrams original code, I think there is probably about 2 classes that stayed the same, there is now more code, a lot more, however from an end user experience, I think it is now dead easy to control the creation of diagrams from a centralized ViewModel, which allows a diagram to be created via well known WPF paradigms like Binding/DataTemplating.

So I decided to give this a go, you can read more about it here : http://www.codeproject.com/Articles/484616/MVVM-Diagram-Designer

 

Hope its of some use to someone

Follow

Get every new post delivered to your Inbox.

Join 68 other followers