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!

Monday, September 30, 2013

Exploring Entity Systems

I am always interested in exploring ways of writing code. Lately, I have been trying to break the monotony of writing "business apps" and decided to take a look at writing a few games. It has been a long time since I have written a non-web app so I started up by doing a little research. Since I am a fan of CQRS/DDD/event sourcing/etc, I wanted to learn more about writing systems that do not require giant object graphs and "god objects." My previous exposure to game systems (a long time ago) seemed to run on magic, duct tape, and a lot of luck. But, maybe that was just programming in general.

In my research, what I have come across has been pretty interesting. I ran across a way of developing using "Entity Systems." It is like an OOP-less way of writing applications with the added benefit of built-in Aspect Oriented Programming (AOP). There are plenty of blog posts covering introductory information, so I won't rehash it here. (I may leave that to another blog post later.)

One of my favorite ways of exploring new ideas is to write up a quick spike. In that fashion, I have written a simple little test app that throws around some colored dots on the screen. It's not perfect, doesn't do everything I would want in a real system, but was fun to write. Entity systems will definitely remain on my radar for a while. Well, without further ado, here is my quick little app (in C#).

Links

For a nice overview of entity systems, check out the following links:

(While these are "old," they still contain some really good information.)

Monday, September 23, 2013

Placing Objects Where They Belong

Incorrect object graphs

It is very convenient, under the guise of Object Oriented Programming (OOP) to build out some pretty extensible object graphs because we try to mimic "the real world." I find this idea to be faulty, at best, because we usually find we are not modeling the real world but, instead, pushing a mixture of relational database and OOP design into a giant ball of mud. To give an example, think about any business application where we want a customer service rep to be able to leave a note on a customer's account. With the advent of Object Relational Mappers (ORMs), I see a tendency to construct giant object graphs. Take, for example, the following:

public class Note
{
    public int Id { get; set; }
    public int CsrId { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public DateTime Created { get; set; }
}

public class Customer
{
    public List Notes { get; set; }

    public Customer()
    {
        Notes = new List();
    }
}

So, on the customer's page we can load up their notes and display them nicely to make informed business decisions. But, is this correct? Do customers really have notes? We're modeling a "Has-A" relationship here and, while it is easier for small-ish apps, this can cause a lot of headache. Inevitably, when we show that we can leave a note behind, somebody in the business is going to want to leave behind an automated note. Now, for our contrived example, this isn't too bad, but we will find, suddenly, that almost every part of our app must consume an IRepository<Customer> just to get access to its notes. Ew.

A better way

Let's look at this problem for a different point of view. How would we solve this issue without a computer? Would a CSR have to call up a customer and ask them for all the notes we are currently keeping on them? Would we do some work, call up the customer, and then ask them to keep a note for us? If not, why in the world do we treat our objects the same way? It would be a painful business process to have to involve the customer for everything we do for them so they can keep track of our notes. Instead, we would put the notes where they belong. The customer doesn't own the notes we hold on them, something else does. (In other, nerdy, words, think of it as a bard in your system.)

Projections

I am a great fan of modeling my applications using a CQRS approach. It practically saves us from the headache above, if done correctly. For the initial CSR note-taking example, we can put a command in the system that the CSR object handles. It is, after-all, the CSR that cares about the notes, not the customer. But, why are we leaving a note about the customer? Is there some interesting business information that we are hiding because we have a generic note-taking command? If so, then we have effectively diluted our system with a generic CRUD-like command and we lose a lot of information.

Continuing down the CQRS approach, what if, instead of having a property on either the CSR or the customer class, we just used a projection? This projection could be a collection of all the notes and give us a view of interesting information, all contained in a nice, clean, place. By listening to events, we can create automated notes, informing the CSR of information that might otherwise be hidden or lost.

public class CustomerNotesProjection : IRespondTo<CustomerJoined>,
                                       IRespondTo<CustomerChangedServices>,
                                       IRespondTo<ManuallyEnteredCsrNoteCreated>
{
    public void RespondTo(CustomerJoined e)
    {
        // Load up the view and add a note...
    }

    public void RespondTo(CustomerChangedServices e)
    {
        // Same as above...
    }

    public void RespondTo(ManuallyEnteredCsrNoteCreated e)
    {
        // I sense a theme here...
    }
}

Now we have a single place to which we can turn when we need to capture some event and add a new note. The best part about using this sort of system, especially if you're using Event Sourcing, is that you can capture a lot more interesting information almost for free. On a current project, we have an event store setup that will automatically rebuild our views if it detects a change. All of the events get replayed and thus we can come back, later, and ask the system questions we hadn't thought about in the first place and the information is all there.

public class CustomerNotesProjection : IRespondTo<CustomerJoined>,
                                       IRespondTo<CustomerChangedServices>,
                                       IRespondTo<ManuallyEnteredCsrNoteCreated>,
                                       IRespondTo<CustomerSubscriptionCancelled>
{
    // ...

    public void RespondTo(CustomerSubscriptionCancelled e)
    {
        // yada, yada, yada...
    }
}

Easier to test

One of the problems with the extremely large object graph approach is we now have an excuse not to test our code. It is painful. Really painful.

When we want to test a piece of our code that might leave behind an automated note, we now have to access the customer object directly. Given our analysis that this is probably not the best place for notes to live, we can't even argue that, in a domain driven design approach, that the customer is an aggregate. When we ignore this, though, we are now passing around a customer repository (because we can mock it, right?) and then have to build up the mock to make it all work. This adds so much more complexity to our testing that we decide it's just not worth it. It's so much easier to test simpler cod so we bulk up on those tests to make our test coverage look good, overall.

Instead, we should listen to that pain and re-think our approach. (Even if not on this project, certainly the next, right?) Using a projection approach, we can easily test the projection. Given this event, I expect this note to be added to the view. Simple. And, all of the note testing is in one spot! Need a new automated note to be left behind? We have one test file to open with all of the examples of how this was done in the past. No more searching around the code base to find out how it has been done before. An added benefit is it makes refactoring much easier and even something like code reviews.

Conclusion

While OOP and object graphs are a great tool, it would seem that this is definitely a situation in which we have had a hammer pounding in screws. It takes a little bit more work to find areas in your code where something like this can be cleaned up, but it is well worth it. Having a single place that handles one thing, really, really, well will pay off handsomely. By actually adhering to the Single Responsibility Principle (SRP)—instead of just giving it lip-service—we can actually simplify a task that otherwise can be a painful experience.

The example given here might seem trivial, but it is something that can quickly tank a project. A bunch of little situations like this one can cause a maintenance nightmare or cripple the ability to add new features. Not every project requires the extra little bit of up-front complexity that is required by a CQRS or event sourcing approach, obviously. But it is often good to think and reason about our code before solidifying into a painful object graph in the name of "Object Oriented Programming."

Thursday, August 15, 2013

Stable Hash Codes and Abstract Base Classes

I like to use abstract base classes for my value objects. One of my most used is for identities:

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

    /* ... */

    protected Identity(string value, string prefix)
        : this(prefix)
    {
        Value = value;
    }

    // So we can deserialize and have access to the prefix
    protected Identity(string prefix)
    {
        _prefix = prefix; 
    }
}

Since the identities are value objects, we need to make sure that any two identities of the same type with the same values are considered equal.

public abstract class Identity<TId> : IEquatable<TId>
    where TId : Identity<TId>
{
    private readonly string _prefix;
    public abstract string Value { get; protected set; }

    public bool Equals(TId other)
    {
        if (ReferenceEquals(null, other)) return false;
        return ReferenceEquals(this, other) || Equals(Value, other.Value);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, other)) return false;
        return ReferenceEquals(this, obj) || Equals(obj as TId);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hash = 17;
            hash += hash * 23 + Value.GetHashCode();
            hash += hash * 23 + GetType().GetHashCode();
            return hash;
        }
    }

    public override string ToString() { return string.Format("{0}/{1}", _prefix, Value); }

    protected Identity(string value, string prefix)
        : this(prefix)
    {
        Value = value;
    }

    // So we can deserialize and have access to the prefix
    protected Identity(string prefix)
    {
        _prefix = prefix; 
    }
}

Almost...

This works for most situations but, recently, I found out that there's a little bit of a bug with the implementation of GetHashCode(). The overall algorithm is pretty sound for most cases, minus one little piece: GetType().GetHashCode(). The way I found out this doesn't work is by having to persist the hash between uses of an app. Bringing the app down and back up caused GetType().GetHashCode() to return a different value. Whoops!

(The reason for GetType().GetHashCode() was so that two identities of different types with the same .Value; would return different hashes.)

I switched it up, for now, to use GetType().Name. Fixed the issue for me.

public abstract class Identity<TId> : IEquatable<TId>
    where TId : Identity<TId>
{
    /* ... */
    public override int GetHashCode()
    {
        unchecked
        {
            var hash = 17;
            hash += hash * 23 + Value.GetHashCode();
            hash += hash * 23 + GetType().Name.GetHashCode();
            return hash;
        }
    }
    /* ... */
}

And, to wrap up the use of this class, here's a sample of how to use it (fully serializable, too):

[DataContract(Namespace = "my-namespace")]
public abstract class ProductId : Identity<ProductId>
{
    [DataMember(Order = 1)]
    public override string Value { get; protected set; }

    public ProductId(long id)
        : base(id.ToString(CultureInfo.InvariantCulture), "product") { }

    private ProductId()
        : base("product") { }
}

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.