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.