ServiceAPI permissions are null

Intro

One of the nice things about a service oriented approach is that, in theory, you can upgrade the server and all of the existing clients continue to work, simply ignoring any new features on the server. A post on the HPRM SDK forum highlighted a bug in our ServiceAPI .Net client which prevented this from working fully.

The problem

The Location object has a permissions property.  This is a dictionary with the UserPermissions enum as the key. Unfortunately the serializer fails to deserialize the entire dictionary if one of the keys is invalid.  This means that if we add new items to UserPermissions (which we do) then Location.Permissions will be null when de-serialized by an earlier version of the ServiceAPI .Net client library.

The solution

An upcoming release of the ServiceAPI will fix this.  In the meantime, if you wish to future proof your application, you can patch the .Net client library yourself.  Simply call the code below at the start of your program (maybe from a static constructor to ensure it is only called once.

JsConfig<PermissionsDictionary>.RawDeserializeFn = (val) =>
{
    PermissionsDictionary permissions = new PermissionsDictionary();

    JsonObject jObject = JsonObject.Parse(val);

    foreach (string key in jObject.Keys)
    {
        UserPermissions permission;
        if (System.Enum.TryParse<UserPermissions>(key, true, out permission))
        {
            permissions.Add(permission, Boolean.Parse(jObject[key]));
        }
    }

    return permissions;
};

What is happening

The framework upon which ServiceStack is built allows the de-serialization pipeline to be intercepted, allowing you to customise de-serialization (or serialization) for any object type.