Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, November 5, 2013

Tricky LINQ ToDictionary Where Action is the Value

This is going to be a quick one, but something I wanted to jot down before I forgot it. I needed a Dictionary<MyEnum, Action> and figured I would use LINQ's awesome ToDictionary<,>() method. I've used this plenty of times before and so I figured this would be a snap:

    private readonly Dictionary<MyEnum, Action> _actions;

    public Keyboard()
    {
        _actions = Enum.GetValues(typeof(MyEnum))
                       .Cast<MyEnum>()
                       .ToDictionary(x => x, x => () => { });
    }

Feeling good about my awesome LINQ statement, I went to move on when I noticed that my precious had red squigglies under it. Ah, probably just a typo or something. I mean, I am susceptible to those sometimes, I suppose. Upon further inspection, it was not a typo but a fun little error:

Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer<Foo.Bar.MyEnum>' because it is not a delegate type

Even more fun, this method was insisting I was trying to create a Dictionary<MyEnum, MyEnum>. No I'm not! What the heck!

Just Breathe...

Ah yes, it is easy to forget that there are four overloads for ToDictionary. Three of which are ToDictionary<TSource, TKey>, all of which an Action perfectly conflicts, and fourth which is ToDictionary<TSource, TKey, TElement>. So, my implementation, above, caused the compiler to become confused since it thought I was trying to pull off passing in an Action as an IEqualityComparer. So, we need to force the compiler to pick the last overload by specifying all the Ts:

        _actions = Enum.GetValues(typeof(MyEnum))
                       .Cast<MyEnum>()
                       .ToDictionary<MyEnum, MyEnum, Action>(x => x, x => () => { });

Simple really.

Thursday, October 31, 2013

I Hate Null References. I Hate Them!

I have been thinking hard about how to introduce my hatred for "null" references without sounding like it was just complaining. We'll see how this goes.

Null references, for the (lucky) unacquainted, occur when one dereferences a pointer that does not point to anything. Instead of swallowing the "error" or providing some default behavior, we get an exception. When not caught and handled, this will cause big problems. The fun part (for various definitions of fun) is that these exceptions are a pain to hunt down. So, most of the time, we do checks at the beginning of code blocks to check for null references. Thus, our code is sprinkled with things like:

void Foo(Bar bar, Baz baz)
{
    if(bar == null) throw new ArgumentNullException("bar");
    if(baz == null) throw new ArgumentNullException("baz");
    // if we get here, we're ok.
}

which doesn't remove the exception. Ugh. I really wish C# would implement non-nullables or something like C++'s references. There has been some talk about how to introduce this into C# but, as of today, we do not have this capability. I'm really looking forward to any sort of implementation!

Doing some learning

After digging around some (and being heavily inspired by Eric Lippert's posts on monads), I have been using the Maybe "pattern" and decided to share my implementation. As an aside, there are 13 posts to that link, but they are all great reads and I highly recommend checking them out. I am, in no way, an expert on Monads, but felt like sharing what I have learned up to this point. Before we move on, here is the code.

public struct Maybe<T>
{
    public static readonly Maybe<T> Nothing = new Maybe<T>();

    public readonly bool HasValue;
    public readonly T Value;

    public override string ToString()
    {
        return ToString(string.Empty);
    }

    public string ToString(string nothing)
    {
        return HasValue ? Value.ToString() : nothing;
    }

    public static implicit operator Maybe<T>(T value)
    {
     return new Maybe<T>(value);
    }

    public Maybe(T value)
    {
        Value = value;
        HasValue = ReferenceEquals(null, value);
    }
}

There is nothing really fancy going on here, but using a struct for the wrapper ensures that we won't have to worry about null references. I have allowed for the implicit conversion from "T" to Maybe<T> so we can keep the "Maybe"s contained.

public class Foo
{
    public static void Bar(Maybe<string> baz)
    {
        // Use baz
    }
}

public void Main()
{
    var myString = "Some string, not a maybe.";
    Foo.Bar(myString); // No explicit cast required.
}

Let's make it better

This helps with arguments, but we can take this a step further and use some LINQ trickery to allow some short-circuiting logic to (appear to) dereference the maybe safely and any properties it may have. Let's say we have a (poorly) written object graph that looks like this:

public class X { }
public class Y { public X X { get; set; } }
public class Z { public Y Y { get; set; } }

and we need to use the properties in a method. Without our special maybe, we might have something like this:

public class Foo(Z z)
{
    if(z == null) throw ArgumentNullException("z");

    if(z.Y != null)
    {
        if(z.Y.X != null)
        {
            var x = z.Y.X; // finally...
        }
    }
}

What if the idea of nothing (null, in this case) is ok? We're throwing an exception but might not mean it. And then we have the nested if-statements to finally get to the value we're after. For fun, we can use some extension methods to get some LINQ goodness and remove the explicit null checks. (This portion was greatly inspired by this post by Mike Hadlow.)

public static class MaybeExtensions
{
    public static Maybe<T> ToMaybe<T>(this T value)
    {
        return value;
    }

    public static Maybe<R> Select<T, R>(this T value, Func<T, Maybe<R>> func)
    {
        Maybe<T> maybe = value;
        return maybe.HasValue ? func(value) : Maybe<R>.Nothing;
    }

    public static Maybe<R> Select<T, R>(this T value, Func<T, R> func)
    {
        Maybe<T> maybe = value;
        return maybe.HasValue ? func(value) : Maybe<R>.Nothing;
    }

    public static Maybe<R> Select<T, R>(this Maybe<T> value, Func<T, R> func)
    {
        return value.HasValue ? func(value.Value) : Maybe<R>.Nothing;
    }

    public static Maybe<V> SelectMany<T, U, V>(this Maybe<T> maybe, Func<T, Maybe<U>> k, Func<T, U, V> s)
    {
        // This could be cleaned up with a "Bind" method, but I wanted to leave it off for now
        if(value.HasValue == false) return Maybe<Vgt;.Nothing;
        var kMaybe = k(value.Value);
        return kMaybe.HasValue ?
            s(value.Value, kMaybe.Value) :
            Maybe<V>.Nothing;
    }
}

We can now chain the maybes, using LINQ, without fear of a null references exception.

class X { }
class Y { public X X { get; set; } }
class Z { public Y Y { get; set; } }

void Foo(Z z)
{
    var x = from z in z.ToMaybe()
            from y in z.Y.ToMaybe()
            from x in y.X.ToMaybe()
            select x;

    // Or

    x = z.ToMaybe()
         .Select(z => z.Y)
         .Select(y => y.X); // Same thing as above
}

No matter if Z, Y, or X is null, we will get a Maybe<X> from this. Other than having to invoke the extension method ToMaybe(), I like this code much better than a bunch of null checks. Maybe that's just me. This means we can either keep the Maybe<T> internal and use the ToMaybe() extension method, or we can take in a Maybe<T>. As long as this doesn't turn into a check on HasValue that requires us to throw an exception, it seems ok. Of course, there are times when a null reference just is not an acceptable "pre-condition" and an exception is (because our hands are tied) acceptable. What are your thoughts?

Wednesday, October 23, 2013

Zip with LINQ

I really love LINQ. In fact, LINQ, mixed with extension methods, is really enjoyable and makes it hard to leave C#. (Among other things.) At any rate, one of my favorite LINQ functions is Zip and I got to use it the last few days to solve a problem that would have been annoying otherwise. The basic idea of Zip is to take two collections (IEnumerable) and combine their elements with a selection function. Zip's signature is:

public static IEnumerable<TResult> Zip<T, U, TResult>(
    this IEnumerable<T> first,
    IEnumerable<U> second,
    Func<T, U, TResult> selector)

Sometimes extension methods can be hard to read. Basically, this method is invoked on an IEnumerable of some type U. The first parameter is the other IEnumerable you want to "zip" together with the first. The final parameter, Func<T, U, TResult>, basically says it takes a method which takes in two parameters (of type U and T, respectively) and returns something of TResult. Since U and T are the types defined by the two IEnumerables we're zipping together, one can think of it as a method that takes the one of each of these collections and returns something else. Anything, really.

As a web developer, I have created myriad collections of items that have an associated count with each item. I don't know how many times I wrote something like (using Razor syntax here):

@int counter = 1;
foreach(var elem in Elements)
{
    <div>@elem.SomeProp - @counter++</div>
}

Too easy

Sure, this is a pretty trivial example, but my views have sometimes become jam-packed with this sort of "logic." (You know, cause this is "view" stuff, right?) But, had I given it some though, I could have created a better view model that had this information in it. (And, in turn, kept my view a bit cleaner.)

One of the things to note about Zip is that it will only join items up to the length of the shortest collection and nothing more. We can use this to our power for situations like our previous pretend view. Let's say we want to take a collection of strings and list them out in a console app. We could do something like:

public void Main()
{
    val names = new[] { "Tom", "Dick", "Jane" };

    for (int i = 0; i < names.Length; ++i)
    {
        Console.WriteLine("{0}-{1}", i + 1, names[i]);
    }

    // or

    int counter = 1;
    foreach(var name in names)
    {
        Console.WriteLine("{0}-{1}", counter++, name);
    }
}

Again, this is trivial so it doesn't seem too painful. But let's look at how we can do it with Zip:

public void Main()
{
    var names = new[] { "Tom", "Dick", "Jane" };
    var counts = new[] { 1, 2, 3 };
    var strings = names.Zip(counts, (x, y) => string.Format("{0}={1|", x, y);

    foreach(var val in strings)
    {
        Console.WriteLine(val);
    }
}

A little more

So, the same results as above with a little bit more typing (in this trivial case). But, since we know that Zip will only combine items up to the length of the smaller collection, we can do some interesting things. Since counting items has been a theme for this post, I'll stick with it. Let's say we want to take a collection of strings of variable length and get the same effect as the previous two examples. Well, we could use a for-loop in every spot, or we can use a functional approach and create a generic method that will let us accomplish this. The Enumerable static class has a helper function on it called Count. It returns an IEnumerable that counts from N to M (whatever you input). Since we are iterating an IEnumerable, it is not loaded into memory all at once so we can do something like this:

public static IEnumerable<TResult> ZipWithCounter<T, TResult>(
    this IEnumerable<T> first,
    Func<T, int, TResult> selector)
{
    return first.Zip(Enumerable.Range(0, int.MaxValue), selector);
}

// And its use:

var names = new[] { "Tom", "Dick", "Jane" };
var zipped = names.ZipWithCounter((name, i) => string.Format("{0} {1}", i, name));

(This is of course simplified and skimps on error checking for brevity.)

There are a lot of use cases for Zip that clean up how we join two collections together into some arbitrary third collection. It definitely follows more of a functional style of programming than using a looped counter and can make code much easier to read by centralizing repeated logic. Zip is one of those underutilized tools in the LINQ tool belt.

Tuesday, October 15, 2013

EStroids - An Entity System Game

After having stumbled upon entity systems, I have been a little bit infatuated with the design concept. I decided to spike out a little game for fun and brush off my math skills; thus EStroids was born. It is just a quick and dirty little game, doesn't have all the defensive programming checks that would normally go into an app or game, but was pretty fun to write. (It also has things that will make a mathematician cry, such as multiplying a 4✗4 matrix and a vector3.)

I have the little project hosted on GitHub in case I decide to poke around it some more. Overall, it was just fun and nice to see how easily it is to put little games together. I have absolutely no real-world experience that tells me this sort of approach is scalable, but I do see merits to the approach.

And without further ado, the link: https://github.com/jjvdangelo/EStroids

Systems

Each of the systems inherit from SystemBase that just takes in a manager. (Like I said, just quick and dirty.)

public abstract class SystemBase
{
    private readonly EntityManager _manager;
    protected EntityManager Manager { get { return _manager; } }

    public virtual void Initialize() { }
    public virtual void Shutdown() { }
    public abstract void Frame(double dt);

    protected SystemBase(EntityManager manager)
    {
        _manager = manager;
    }
}

Here's the "lifetime" system that manages objects that have a timed lifespan:

public class LifetimeSystem : SystemBase
{
    public override void Frame(double dt)
    {
        var toDestroy = new List();
        foreach (var entity in Manager.GetEntitiesWithComponent())
        {
            var expiration = entity.GetComponent();
            expiration.TimeAlive += dt;

            if (expiration.TimeAlive < expiration.MaxLifetime) continue;

            toDestroy.Add(entity);
        }

        toDestroy.ForEach(x => Manager.DestroyEntity(x));
    }

    public LifetimeSystem(EntityManager manager)
        : base(manager) { }
}

So much cleaner than trying to shove this into some base class and figure out where this behavior should live within an object oriented hierarchy.

Components

And this is a simple component (the Expiration component) used by the LifetimeSystem:

public class Expiration
{
    public double TimeAlive { get; set; }
    public double MaxLifetime { get; set; }
}

Basically, we work to separate the data away from the behavior and away from the entities themselves. This the complete opposite type of work that I've done for so many years trying to efficiently pull all of these things together. It is almost always a code smell when you have "Manager" objects, quickly leading to an anemic object model.

Make Sense?

For anybody who may experience with entity systems, does this make sense? Am I interpreting the intention of entity systems? I feel like I'm picking up the idea but it's always good to have a sanity check here and there!

Thursday, August 8, 2013

Registering Open Generics to a Factory Method with StructureMap Using Expression Trees

I have been working with a system lately that requires a factory method to create a lot of open generics. To keep it simple, at the beginning, I registered each type of instance with something like the following:

var singletonFactory = new OpenGenericFactory();

StructureMap.ObjectFactory.Configure(cfg =>
{
    cfg.For<IOpenGeneric<int, int>>().Use(OpenGenericFactory.GetGeneric<int, int>());
    cfg.For<IOpenGeneric<int, long>>().Use(OpenGenericFactory.GetGeneric<int, long>());
    cfg.For<IOpenGeneric<long, long>>().Use(OpenGenericFactory.GetGeneric<long, long>());
    cfg.For<IOpenGeneric<long, int>>().Use(OpenGenericFactory.GetGeneric<long, int>());
});

The actual classes don't matter much, other than it is an open generic with two generic arguments and there would be a lot of registering. Not fun at all, especially because it is easy to forget to go register them and it's a really boring manual task. I fairly simple solution is to bind the open generic like so:

var singletonFactory = new OpenGenericFactory();
var getGenericMethod = singletonFactory.GetType().GetMethod("GetGeneric");

StructureMap.ObjectFactory.Configure(cfg =>
{
    cfg.For(typeof(IOpenGeneric<,>).Use(x =>
    {
        var requestedType = x.BuildStack.Current.RequestedType;
        var genericArgs = requestedType.GetGenericArguments();
        var genericMethod = getGenericMethod.MakeGenericMethod(genericArgs);
        return genericMethod.Invoke(singletonFactory, null);
    });
});

This turns out to be orders of magnitude slower than registering each type by hand. One could go ahead and cache the "genericMethod" in a dictionary, but it is still pretty slow. Instead, we can create a Func out of the method and cache that. This one time compile of an expression tree (cached, of course) makes everything much faster.

using System.Linq.Expressions; // This is where the Expression tools live

var singletonFactory = new OpenGenericFactory();
var factoryType = singletonFactory.GetType();
var getGenericMethod = factoryType.GetMethod("GetGeneric");
var cache = new ConcurrentDictionary<Type, Func<OpeGenericFactory, object>>();

StructureMap.ObjectFactory.Configure(cfg =>
{
    cfg.For(typeof(IOpenGeneric<,>).Use(x =>
    {
        var requestedType = x.BuildStack.Current.RequestedType;
        var func = cache.GetOrAdd(requestedType, type =>
        {
            var genericArgs = type.GetGenericArguments();
            var genericMethod = getGenericMethod.MakeGenericMethod(genericArgs);
            var input = Expression.Parameter(factoryType, "input");
            return Expression.Lambda<Func<OpenGenericFactory, object>>(Expression.Call(input, genericMethod), input).Compile();
        }
        return func(singletonFactory);
    });
});

So, after a one-time reflection payment, we can use the method as if we were calling it directly. Fun!

Tuesday, July 30, 2013

Using protobuf-net with Inheritance

I have been doing some work with Google's Protocol Buffers using Marc Gravel's protobuf-net. It is a very easy to use package and has proven to be lightning fast in both serializing and deserializing my objects. As much as I have enjoyed it, this post is not a sales pitch about the goodness of protocol buffers but is, instead, to show an issue I ran across and how I got around it.

I was having a problem with inheritance and deserializing my objects. Basically, I have a value object generic that I use for identities and they were not deserializing properly.

[ProtoContract]
public abstract class Identity<TId> : IIdentity
    where TId : Identity<TId>
{
    [ProtoMember(1)]
    public string Value { get; private set; }

    protected Identity(string value)
    {
        Value = value;
    }
}

When the identity object would be deserialized, the Value property was always null. So, after some reading, I found out why. It was because I had to let protobuf-net know about my inheritance chain. One way of doing it is with attributes. (Specifically the ProtoInheritanceAttribute.)

[ProtoContract]
public class FooId : Identity<FooId>
{
    private FooId() { /* Just for serialization */ }
    public FooId(string value)
        : base(value) { }
}

[ProtoContract]
[ProtoInheritance(2, typeof(FooId))]
public abstract class Identity<TId> : IIdentity
    where TId : Identity<TId>
{
    [ProtoMember(1)]
    public string Value { get; private set; }

    protected Identity(string value)
    {
        Value = value;
    }
    protected Identity() { /* Just for serialization */ }
}

For one, it through me off that the inheritance attribute goes on the base class. DataContractSerializer and XmlSerializer come with the same issue with attributes and inheritance so I should have seen it coming. For one-off inheritance chains, this really isn't too bad of a trade-off especially for what you get. For me, though, I would have had to append an uncountable number of ProtoInheritanceAttributes on my Identity class. It was not going to work. Luckily, there is a little trick to make the serialization work the way I wanted it to. Since this is an abstract class, we can make the exposed property abstract and move up the ProtoMember attribute to the child class. (Be sure to note the change to from private to protected on the Value property.)

[ProtoContract]
public class FooId : Identity<FooId>
{
    [ProtoMember(1)]
    public override string Value { get; protected set; }

    private FooId() { /* Just for serialization */ }
    public FooId(string value)
        : base(value) { }
}

public abstract class Identity<TId> : IIdentity
    where TId : Identity<TId>
{
    public abstract string Value { get; protected set; }

    protected Identity(string value)
    {
        Value = value;
    }
    protected Identity() { /* Just for serialization */ }
}

It also cleans up the base class and rids it of the attributes.

Sunday, July 21, 2013

Fun With IDisposable and Action

IDisposable is a pretty neat tool in the .NET framework. For those that don't know what it is, a class that implements IDisposable can be wrapped in a using statement. When the code exits the block created by the using statement, the object's Dispose method is guaranteed to be called, automatically. (This includes the block being exited because of an exception.)

Every now and then I need to create some Razor extension methods (especially to avoid re-typing HTML wrappers around articles, or what-not). If you use Razor with ASP.NET MVC, you are probably familiar with Html.BeginForm(). It allows us to wrap an HTML form and emits the form's opening and closing tags around our elements.

@model MyNameSpace.MyModel
@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.SomeProperty)
}

While I won't get into specifics of what extensions I have created in the past in this post, I wanted to discuss a way of cleaning up our code if we have a bunch of these extensions. Let's say we have two extension methods that make use of IDisposable. I have seen—and written myself—a few implementations like the following.

public static class HtmlHelperExtensions
{
    public static FooCloser Foo(this HtmlHelper helper)
    {
        // Do work
        return new FooCloser(helper);
    }

    public static void CloseFoo(this HtmlHelper helper)
    {
        // Finish up
    }

    public static BarCloser Bar(this HtmlHelper helper)
    {
        // Do work
        return new BarCloser(helper);
    }

    public static void CloseBar(this HtmlHelper helper)
    {
        // Finish up
    }
}

public class FooCloser : IDisposable
{
    private readonly HtmlHelper _helper;

    public void Dispose ()
    {
        _helper.CloseFoo();
    }

    public FooCloser (HtmlHelper helper)
    {
        _helper = helper;
    }
}

public class BarCloser : IDisposable
{
    private readonly HtmlHelper _helper;

    public void Dispose ()
    {
        _helper.CloseBar();
    }

    public BarCloser (HtmlHelper helper)
    {
        _helper = helper;
    }
}

After a while, all those "Closer" classes build up. But, there is a pattern that emerges that we can take advantage of. Instead of each set of helper methods getting their own IDisposable "closer," we can merge them all into one and refactor our code a bit by making use of Action.

public static class HtmlHelperExtensions
{
    public static IDisposable Foo(this HtmlHelper helper)
    {
        // Do work
        return new Closer(helper.CloseFoo);
    }

    public static void CloseFoo(this HtmlHelper helper)
    {
        // Finish up
    }

    public static IDisposable Bar(this HtmlHelper helper)
    {
        // Do work
        return new Closer(helper.CloseBar);
    }

    public static void CloseBar(this HtmlHelper helper)
    {
        // Finish up
    }
}

public class Closer : IDisposable
{
    private readonly Action _action;

    public void Dispose ()
    {
        _action();
    }

    public Closer (Action action)
    {
        _action = action;
    }
}

Now we have one universal "closer" that we can use anywhere we want to return an IDisposable to use this little trick—and not just with Razor extensions.

Simple.Web - Extending Handler Behaviors

I have continued working with Simple.Web and recently integrated a project with Azure Active Directory. To my surprise it was actually pretty easy to provision AD on Azure and then use Windows Identity Foundation (WIF) to integrate it into the project. Since I can run Simple.Web with ASP.NET, it all "Just Works." There are some annoying things about Azure AD (that go above an beyond the annoyances of AD itself) but I'll save that for another post.

At any rate, the reason for this post is to talk about extending the behaviors that come packaged in Simple.Web. When I first got Azure AD integrated, it was easy to slap on an IRequireAuthentication behavior on my handler, run the app, and then get redirected to the Azure AD login page. My project, though, is a multi-tenant app and I need the tenant id as well and the user's id. I could easily create a new behavior and slap it onto my handlers without much thought but I wanted to avoid the situation where there are a million-and-one interfaces on each handler since they're all required. So, I tried extending the IRequireAuthorization behavior and, to my surprise, it worked like a charm.

So, the first thing to do was create the interface:

using System;
using Simple.Web.Behaviors;

public interface IRequireTenant : IRequireAuthentication
{
    Guid TenantId { set; }
}

The next step was to create the "implementation":

using System;
using System.Security.Claims;
using Simple.Web.Http;

public static class SetTenant
{
    public static bool Impl(IRequireTenant handler, IContext context)
    {
        var cp = ClaimsPrincipal.Current;
        Guid tenantId;
        if (Guid.TryParse("http://schemas.microsoft.com/identity/claims/tenantid").Value, out tenantId))
        {
            handler.TenantId = tenantId;
            return true;
        }

        return false;
    }
}

And then go back and decorate the interface with the implementation:

[RequestBehavior(typeof(SetTenant))]
public interface IRequireTenant : IRequireAuthentication { ... }

Simple.Web still treats the handler as though it has the IRequireAuthentication behavior (it still triggers the AuthenticationProvider and redirects if needed) and I don't need to have a bunch of interfaces all over my handlers.

Wednesday, May 8, 2013

Asynchronous Command Handlers, Object Identity, and CQRS

I have been working on a (closed-source, unfortunately) project in my spare time and have been using the Command Query Responsibility Separation (CQRS) pattern. In most places, it is pretty easy to utilize asynchronous command handlers, but there was one part that tripped me up a little bit. When a user creates a new aggregate root via, say, a web page, how do we handle the asynchronous nature of the command handler?

At one point, I thought about making these creation-type command handlers synchronous so the user could be warned if the creation has failed or if there were errors. I was not very happy with this because it meant that I couldn't just place the command on a bus and move on. It meant I cannot offload that work somewhere else and the user has to sit and wait for this thing to go on. Basically, an all around uncomfortable situation.

Why?

So, what made me care about this? Why is it important to think about? Well, it has some implications. First off, it makes one consider how an object's identity is created. If we have the domain create the id, then we have to sit around and wait for it to complete. (Hence, my dilemma.) Overall, this could work, but I was not satisfied with it. After all, my goal was to allow the web application to do as little processing as possible, other than serving up pages and communicating with the service bus.

Were do we go from here? I was a bit stumped and almost gave in to the idea that I would have to accept this band-aid fix as a permanent solution. Luckily, after some thought, and drawing some pictures, I realized I was looking at the problem from the wrong point of view. Shifting my thinking, the answer seemed pretty obvious and I wasn't sure why I didn't see it in the first place!

The First Step

The first step to my clarity was deciding that the domain did not need to be in charge of creating an identity. Instead, why can't we pass in, say a globally unique id (GUID) and tell the domain that we expect something to be created with this id? Now, we don't have to sit around and wait on some database to assign and id and filter it back to the user. So, as part of our command, we can create a new identity and pass it into the domain from the web server. Now, since the server has the targeted identity, we can forward the user to a "Success!" page with the new identity as a hidden field. We can either set a timer to forward the user to the read only model or provide a link on which the user can click.

But, what if it fails?

What if the creation fails? Well? Who cares? What does that actually mean in the domain? For me, in my current project, it didn't matter. We can display an "Oops! We screwed up!" page with a link back the creation page. We could go so far as to reload the creation page with the data passed in (since we have the command, after all). Even if the user cheats the system and tries to re-use an identity to create an aggregate to maybe cheat the system, we can detect it (the aggregate cannot be created when it has already been created!) and show the user an error page.

Wait, create what was already created?

Let's say a malicious user wants to try to trick the system into recreating an aggregate in hopes to gaining access to it. Well, we have to be careful here. In my solution, aggregates are made by newing up the target type, loading the event stream from the backing store, re-running the events, and then calling some method on the aggregate. This include "create" methods. The constructor doesn't actually put the object in a created state. So, instead, we have something like:

public abstract class Aggregate
{
    public void ReplayEvents(EventStream stream) { ... }
    protected void PlayEvent(Event target) { ... }
}

public class Foo : Aggregate
{
    private bool _created;

    public Foo()
    {
        // Just get the underlying code ready,
        // but don't set the state to created.
    }

    public void Create(FooCreateParams params)
    {
        // Validate the params and all that fun stuff
        // and, if all is well, fire a created event.
        // If this has already been created, throw an
        // exception or, maybe, fire an error event.

        if (_created) { /* Blow up! */ }

        PlayEvent(new CreatedEvent(params.Id)); // You get the gist.
    }

    private void PlayEvent(CreatedEvent target)
    {
        // React to the event here.
        _created = true;
    }
}

So, if the object has already been created, we don't want to mess with the state. Depending on your domain and the context of your application, you could either fail silently, fire an error event, or even throw an exception. No matter what you do, though, if a user somehow messes with the system (or you happen to have an identity clash) and tries to execute a Create on an already created object, we do not want to hint that the user actually hit upon an actual id.

Conclusion

With a little bit of thought, we are able to clear up a seemingly complex operation down to a pretty easy solution that allows us to keep our asynchronous operations. Now we have a pretty clean set of operations: User hits submit, we load the command on the bus with a new id, redirect the user to a "success" page with some way of referencing the new object, and then let the user move from there. On error, regardless of why, we let the user know an error happened, and provide them with some information to make a decision on how to move forward.

Tuesday, May 7, 2013

Refactoring? Or Rewriting?

I was recently asked in an interview what it meant to refactor code and what the prerequisite was to refactoring. I have to admit, I was a bit thrown off being asked what the "prerequisite" is, since it seems to me to be reflexive software development nowadays. To me, refactoring is an interesting concept in software development that a lot of other engineering-type professions don't get to leverage as freely as we do. But, I think it has become (incorrectly) synonymous with rewriting code. (Or maybe refactoring is instead used as a guise to rewrite.)

Refactoring is very simple and is akin to rewording the language in your code to express the same idea, or original intent, in a different statement. Rewriting your code is changing the intended behavior of the code—the opposite of refactoring. I have spent a lot of time refactoring some code on my current project lately, and I have run across a the following code a lot.

public List<Foo> GetFoos(SomethingElse[] somethingElses)
{
    var retval = new List<Foo>();

    foreach(var else in somethingElses)
    {
        retval.Add(new Foo() { Bar = else.Bar });
    }

    return retval;
}

So, this is a pretty trivial sample of code, but it is really easy to see what is going on and what the intent of the code is. Basically, it is mapping a collection of one type of object to a collection of another type. We create a list and then iterate through the original collection, appending a new instance of Foo, and then return it. Using LINQ, we can actually simplify this just a tad and even type less code to get the same effect. (Refactor it.)

using System.Linq;

public List<Foo> GetFoos(SomethingElse[] somethingElses)
{
    return somethingElses
        .Select(x => new Foo() { Bar = x.Bar })
        .ToList();
}

Again, this is a trivial example, but it shows how we can refactor our code, keep in tact the original desired behavior, but use different syntactic sugars to clean it up. (I prefer using LINQ, personally, over foreach, especially in nested situations.) But, besides this being a trivial situation, what confidence do we have that we did not silently introduce a bug into our system? What assurance do we have? Well, before refactoring our code, we should put barriers in place to help us reason about our code. In the simplest sense, we should have a unit test, in place, before we make our changes to assert that we did not introduce a bug. Of course, if we're good TDDers we would have this unit test in place already, and have a nice regression test to fall back on. If not, it would behoove us to get one in place, quickly.

[Test]
public void given_an_array_of_something_elses_it_should_return_a_list_of_foos()
{
    var somethingElses = Enumerable.Range(0, 5)
        .Select(i => new SomethingElse() { Bar = i })
        .ToArray()

    // Let's assume GetFoos is defined as a static method on Baz
    var result = Baz.GetFoos(somethingElses);

    for (int i = somethingElses.Length - 1; i >= 0; --i)
    {
        Assert.That(result[i].Bar, Is.EqualTo(somethingElses.ElementAt(i).Bar));
    }
}

Well, that's refactoring, but what about rewriting? If we look at our simple method, what happens when we pass in a null array of SomethingElse? At this point, our method doesn't care and will attempt to iterate over it anyway. This, of course, results in a null reference exception and we have to track down how this happened. But, let's say we decide to change the behavior of this method. We, instead, will throw an exception if the array is null because we the precondition has not been met. Since we are changing the method's behavior, we are rewriting our code. One hint that this is a rewrite is the fact that we need to introduce a new unit test.

[Test]
public void given_a_null_array_it_should_throw_an_argument_null_exception()
{
    var exception = Assert.Throws<ArgumentNullException>(() => Baz.GetFoos(null));
    Assert.That(exception.ParamName, Is.EqualTo("somethingElses"));
}

I have used NUnit-style syntax in this post, but it should be fairly clear what is being tested.

Now, why is this important? Well, as we're writing our code, we tend to learn a lot about it. We see new ways to implement things that allow us to, later, extend the behavior of something without changing the original meaning. It also allows us to nicely execute test driven development: "Red –> Green –> Refactor."

Friday, April 19, 2013

Using Strongly Typed Properties

When my team and I started to port a Web Forms application over to the MVC side of the ASP.NET stack, I specifically set out to solve an issue we continued to run into. We have these fields on the screen that tie back to some property on an underlying "program," usually exposed as some sort of primitive, such as an int, or string. There are many these properties are found in many programs and usually follow some sort of business rules. Let's say one of these properties is called a Foo. In the Web Forms implementation, we would see something such as the following.

public class SomeProgram : Program
{
    public string Foo { get; set; }
}

public class SomeOtherProgram : Program
{
    public string Foo { get; set; }
}

A "Foo" has a very specific meaning in the domain of the application. In implementation described above, it is very easy to accidentally pass the wrong string to a property because you don't get a red squiggly telling you that you just set that "Foo" with a "Bar" because they're both just strings.

Instead, in our rework, we created a base class called CommonType. (These are basically just value types in the domain driven design world, in that we don't care about their individual identity.) From that CommonType, we have created other "types" to represent our data. So, instead of our properties look like they did, above, we now have something else like this:

public class SomeProgram : Program
{
    public Foo Foo { get; set; }
}

public class SomeOtherProgram : Program
{
    public Foo Foo { get; set; }
}

Now we can't accidentally pass in a "Bar" to a "Foo" without some sort of conversion and we get the help of the compiler to tell us we're mapping things incorrectly. The other benefit of doing this is that these fields need to be represented the same way in the UI. Instead of having the same hand-coded (usually inline) styles, we can create editor templates, model binders, and tell MVC how to play nicely with our types.

@model X.Y.Z.Program
@using (Html.BeginForm())
{
    
}

Now we have one, and only one, place that defines what a "Foo" looks like in the application instead of relying on Find-All.

Tuesday, April 2, 2013

Introduction to the Decorator Pattern

One of my favorite software development patterns is the Decorator Pattern. After having taken on so-called brown-field projects, and discussing design patterns with others, I notice so many areas where this pattern could have saved a big ball of mud from forming. It happens very often, even when code starts off cleanly written, that new requirements are added. Without much thought, it is easy to go into the areas affected and edit the classes that have already been written. (Very quickly violating the Open/Closed and Single Responsibility (SRP) principles.)

We will start with something simple here just to get a feel for the pattern itself. So, without further ado, let's take a look at some code. Let's say we have a class called Handler and its job is to handle some command given to the system. We will avoid the use of generics for now to keep it simple.

namespace Patterns.Decorator
{
    public abstract class Handler
    {
        public abstract void Handle (object command);
    }
}

And let's say we have some concrete implementations of Handler that each talk to the database to update some record. (Null checks avoided to simplify the code.)

namespace Patterns.Decorator.Concrete
{
    public class FooUpdater : Handler
    {
        public override void Handle (object command)
        {
            // Foo is just some made-up class to give this method a bit of a body
            if (command is Foo)
            {
                var asFoo = (Foo)command;
                var record = database.Load(asFoo.Id) // get a record from the database
                record.Bar = asFoo.Bar;              // update the record
                database.Save(record);               // and save it
            }
        }
    }

    public class BazUpdater : Handler
    {
        public override void Handle (object command)
        {
            // Baz is just some made-up class, as well
            if (command is Baz)
            {
                var asBaz = (Baz)command;
                var record = // Okay, pretty much the same thing as above
                ...
            }
        }
    }
}

Everything is working well, but this was quickly implemented to get it in front of the customer. The functionality has been "blessed" and we realize we need to log exceptions. What I have seen, all too often, is something such as:

public class FooUpdater : Handler
{
    public override void Handle (object command)
    {
        try
        {
            if (command is Foo)
            {
                var asFoo = (Foo)command;
                var record = database.Load(asFoo.Id) // get a record from the database
                record.Bar = asFoo.Bar;              // update the record
                database.Save(record);               // and save it
            }
        }
        catch (Exception ex)
        {
            ErrorLogger.LogException(ex);
        }
    }
}

For a very simple system, this might work just fine. But this is not a maintainable solution. We have just broken the Open/Closed principle along with SRP. Our Handle method has taken a dependency on ErrorLogger (good luck testing this method now) and has to be changed every time we want to add some functionality. Even worse, that same boiler-plate code has to be copy-and-pasted all through our project. Yuck!

One way to fix this is to rewrite the Handler class:

public abstract class Handler
{
    protected abstract void HandleImpl (object command);

    public void Handle (object command)
    {
        try
        {
            this.HandleImpl(command);
        }
        catch(Exception ex)
        {
            ErrorLogger.LogException(ex);
        }
    }
}

But then our base class becomes flooded with all sorts of mixed behaviors (it tends to become a god object) and quickly becomes a maintenance nightmare. Imagine if we wanted to add some functionality that logged some information based on the type of command given. We would probably find ourselves with a nasty, brittle, switch statement. Once it was written, we would never want to add functionality because it would be too scary. You can't even test this mess to get some sort of regression tests without a bunch of pain. (No wonder some people don't like writing unit tests!)

Fear not! The Decorator Pattern is here to help save us from this unwieldy jumble of code. Let's think of each piece of functionality that we were trying to implement. They sort of wrap around each other and form a ball, kind of like decorating a cake. One layer of frosting, or functionality, at a time. We can easily achieve this same effect by pulling out the layers into their own classes that look like the original base class. But, instead of having a default constructor, they will take in a Handler, so we can layer functionality.

namespace Patterns.Decorator.Concrete
{
    public class FooUpdater : Handler
    {
        public override void Handle (object command)
        {
            if (command is Foo)
            {
                ... // Do the work like we originally did, above.
            }
        }
    }
}

namespace Patterns.Decorator.Logging
{
    public class Logger : Handler
    {
        private readonly Handler _decorated;

        public override void Handle (object command)
        {
            try
            {
                _decorated.Handle(command)
            }
            catch (Exception ex)
            {
                ErrorLogger.LogException(ex);
            }
        }

        public Logger(Handler decorated)
        {
            _decorated = decorated;
        }
    }
}

Now to add the logging functionality, we can leave the original FooUpdater class alone and just wrap it with new functionality. Easy as cake!

var handler = new Logger(new FooUpdater());

So, we have seen how to add functionality to a system without modifying the code we wrote originally. Of course, requirements change and we might need to modify the original code—but we have crafted our solution so that the original code only needs to be modified for one reason (the business rules have changed). Using the decorator pattern we can safely maintain the Open/Closed principle and SRP. Now we won't be so afraid to add that next layer of functionality.

Sunday, March 24, 2013

Applying Attributes to Tool-Generated Classes

Something I ran into a while back, using Linq to SQL (prior to EF Code First), was getting some meta-data onto the models generated by Visual Studio. If you add an Attribute to the generated code, there is a pretty good chance you are going to lose your hard work whenever you re-run the tool. I found this question, on Stack Overflow, asking about this exact problem and was able to help somebody out. I figured this would be a great place to share the code, as well, so I don't have to search for it later.

Most of the tool-generated code that we run into is going to be made out of a partial class. All we have to do is create a new class with the same name (partial as well, of course) and decorate it with the MetadataTypeAttribute. We supply the attribute with the type of a new class that looks like the class we want to extend with the attributes we want to apply. This probably sounds more complicated than it is. So, some sample code should help.

Let's say that our tool generated a class called "GeneratedByOurTool" and it has a string property "SomeProperty"—original, I know. Now we want to pass that directly to some MVC view (yuck, I know) and want to use the Razor helper methods to generate a label for our property. Well, in its current state, Razor is going to write out "SomeProperty" because it doesn't know that you really wanted a space in there.

namespace ExtendingGeneratedCode
{
    using System.ComponentModel.DataAnnotations;

    // This class is generated by a tool
    public partial class GeneratedBySomeTool
    {
        public string SomeProperty { get; set; }
    }


    // We hand wrote the following two
    [MetadataType (typeof (MyMetadataClass))]
    public partial class GeneratedBySomeTool { }

    public class MyMetadataClass
    {
        [Display (Name = "Some Property")]
        public string SomeProperty { get; set; }
    }
}

So, we create a new partial class (in a new file, otherwise it can be overwritten by the tool!) with the same name as the one generated by the tool. In our case, it is "GeneratedBySomeTool." We then decorate our new class with the MetadataTypeAttribute and point it to a third class that holds the metadata in which we are interested.

I will normally put the two hand-written classes into the same file to save from having to hunt them down. Also, note, the hand-written version of GeneratedBySomeTool is empty. You can put new properties or methods here, though, if you want to extend the tool-generated version of the class without using inheritance.

MetadataTypeAttribute resides in the System.ComponentModel.DataAnnotations assembly, in the same namespace as the assembly.

Thursday, March 21, 2013

Testing an ASP.NET MVC Controller

I am a fan of testing my code and have been using SpecsFor, written by Matt Honeycutt, for a lot of my BDD-style unit testing lately. It makes testing very clear and easy to read, comes baked-in with Moq, StructureMap, and a whole lot more goodness.

One of the pain-points of testing ASP.NET MVC is dealing with the controller context, request, response, server, etc. So, I have extended SpecsFor a little bit for my controllers (in both F# and C#).

C#

namespace SpecsForExtensions
{
    using System;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;

    public class ControllerSpecsFor<T> : DbSpecsFor<T>
        where T : Controller
    {
        protected override void InitializeClassUnderTest ()
        {
            base.InitializeClassUnderTest ();

            var context = GetMockFor<HttpContextBase> ();
            var session = GetMockFor<HttpSessionStateBase> ();
            var request = GetMockFor<HttpRequestBase> ();
            var response = GetMockFor<HttpResponseBase> ();
            var server = GetMockFor<HttpServerUtilityBase> ();
            var user = GetMockFor<IPrincipal> ();
            var identity = GetMockFor<IIdentity> ();
            var uri = new Uri ("http://localhost:12345");
            var requestContext = new RequestContext (context.Object, new RouteData ());

            context.Setup (x => x.Session).Returns (session.Object);
            context.Setup (x => x.Server).Returns (server.Object);
            context.Setup (x => x.Request).Returns (request.Object);
            context.Setup (x => x.Response).Returns (response.Object);
            context.Setup (x => x.User).Returns (user.Object);
            request.Setup (x => x.Url).Returns (uri);
            user.Setup (x => x.Identity).Returns (identity.Object);

            SUT.ControllerContext = new ControllerContext (context.Object, new RouteData (), SUT);
            SUT.Url = new UrlHelper (requestContext);
        }
    }
}

F#

namespace SpecsForExtensions

open System
open System.Security.Principal
open System.Web
open System.Web.Mvc
open System.Web.Routing
open SpecsFor

type ControllerSpecsFor<'a when 'a : not struct and 'a :> Controller>() =
    inherit SpecsFor<'a>()

    override this.InitializeClassUnderTest() =
        base.InitializeClassUnderTest()

        let context = this.GetMockFor<HttpContextBase>()
        let session = this.GetMockFor<HttpSessionStateBase>()
        let request = this.GetMockFor<HttpRequestBase>()
        let response = this.GetMockFor<HttpResponseBase>()
        let server = this.GetMockFor<HttpServerUtilityBase>()
        let user = this.GetMockFor<IPrincipal>()
        let identity = this.GetMockFor<IIdentity>()
        let uri = new Uri("http://localhost:1234")
        let requestContext = new RequestContext(context.Object, new RouteData())

        context.Setup<_>(fun x -> x.Session).Returns(session.Object) |> ignore
        context.Setup<_>(fun x -> x.Server).Returns(server.Object) |> ignore
        context.Setup<_>(fun x -> x.Request).Returns(request.Object) |> ignore
        context.Setup<_>(fun x -> x.Response).Returns(response.Object) |> ignore
        context.Setup<_>(fun x -> x.User).Returns(user.Object) |> ignore
        request.Setup<_>(fun x -> x.Url).Returns(uri) |> ignore
        user.Setup<_>(fun x -> x.Identity).Returns(identity.Object) |> ignore

        this.SUT.ControllerContext <- new ControllerContext (context.Object, new RouteData(), this.SUT)
        this.SUT.Url <- new UrlHelper(requestContext)