Closures leading to “Type not marked as serializable” exception

Today I faced a SerializationException that refered to some anonymous inner class stating it was not serializable, when IIS tried to store the session in the ASP.NET State Service:

Type ‘Xyz+<>c__DisplayClass10’ in Assembly ‘Xyz, Version=1.2.5429.24450, Culture=neutral, PublicKeyToken=null’ is not marked as serializable.

I looked for lambdas in my code and found quite a few, but most of them were not new and did never have any issues in serialization. But then I noticed that I had built in a new lambda expression that “happened” to build up a closure.

I have built a very simple example to confirm that closures are not serializable whereas “normal” functions are:

[TestFixture]
public class GeneralUnderstandingTests
{
    [Serializable]
    private class ASerializableType
    {
        private readonly Func thisIsAClosure;
        private readonly Func thisIsNotAClosure;

        public ASerializableType()
        {
            // Normal functions are allowed: The following
            // succeeds to serialize
            const int SomeConst = 12345;
            thisIsNotAClosure = () => SomeConst;

            // But closures are compiled to non-serializable
            // inner classes and break serialization:
            var someVariable = 12345;
            thisIsAClosure = () => someVariable;
        }
    }

    [Test]
    public void ASerializableType_CanBeSerialized()
    {
        var sessionState = SessionStateItemCollection();
        sessionState["sut"] = new ASerializableType();
        sessionState.Serialize(
            new BinaryWriter(new MemoryStream()));
    }
}

This test fails but goes green as soon as the line thisIsAClosure = … is commented out. The line thisIsNotAClosure = … however does not cause any issues as SomeConst is not a variable but a constant, that is, it does not build a closure but is inlined by the compiler.

Advertisements

Polymorph Razor Views

As an object-orientation-spoiled programmer, when you come to use an HTML rendering engine such as Razor you will soon start to wish for the same couple of design advantages that object orientation brings along.

Using polymorphism in “class-ic” object orientation, e.g., you can do things like that (simplified code snippet – don’t try copy-paste):

class Person
{
    string FirstName { get; set; }
    string LastName { get; set; }
    virtual string FormatName()
    {
        return FirstName + " " + LastName;
    }
}

class PersonWithMiddleName : Person
{
    string MiddleName { get; set; }
    override string FormatName()
    {
        return FirstName + " " + MiddleName + " " + LastName;
    }
}

That means, you can write some generic code that iterates over a couple of Person objects and prints their names without caring how they are actually built. By default a Person would yield their first and last name when invoking FormatName, but if you need to print a middle name, too, you can simply subclass Person and override FormatName. When invoking FormatName on an instance of PersonWithMiddleName, even when it is known as Person only, it will apply the most special implementation found, here the one including the middle name.

The good news – you can get that in Razor, too

Razor has a concept that reminds me of the same type of polymorphism. Using Display Templates and Editor Templates you can define a general template to render a Person:

@* ~/EditorTemplates/Person.cshtml *@
@model Person
<div class="Person">@Model.FirstName @Model.LastName</div>

This template applies each time you use EditorFor with a Person type property:

@* suppose a class Book { Person Author { get; set; } *@
@model Book
@Html.EditorFor(m => m.Author)

Now say we have a book with a PersonWithMiddleName author. Then the Person template is still applied, because PersonWithMiddleName inherits from Person. But we have the option to override the template for the special class:

@* ~/EditorTemplates/PersonWithMiddleName.cshtml *@
@model PersonWithMiddleName
<div class="Person">
@Model.FirstName @Model.MiddleName @Model.LastName
</div>

Now, whenever the book has a PersonWithMiddleName author, this template applies. For all other Person objects, the Person.cshtml applies.

We can take it a step further! “Base templates”

If you did not know of Editor Templates before, you might be so excited about them now that you want to try them out right away and cannot think clearly enough to head on reading. Just return later.

If you already did know Editor Templates you might have been wondering: Can we take it a step further? In C# the overriding method can call its base method to reuse the code of the base class:

class PersonWithMiddleName : Person
{
    string MiddleName { get; set; }
    override string FormatName()
    {
        return base.FormatName() + ", middle name: " + MiddleName;
    }
}

Can we do that with Editor Templates?

We can, making use of this helpful answer on stackoverflow.

@* ~/EditorTemplates/PersonWithMiddleName.cshtml *@
@Html.Partial("~/EditorTemplates/Person.cshtml", Model)
, middle name:
@MiddleName

At a first glance you might think it looks a bit clerky but it is not: Just as a subclass needs to reference its base class with its full class name including the namespace, we reference the “base template” using its full path. We simply pass that template the same model. Thus it also uses the exact same ViewData (e.g. the “HtmlFieldPrefix”). Thus we pass it the context, which is kind of analaguous to the “this” keyword in C#.

Template Method Pattern

Now we get to an even more interesting point: If we have inheritance and polymorphism at hand, can we use any of the popular object oriented design patterns?

I tried the template method pattern. It is very useful in this place because when you render a view it is pretty likely that you want to “inject” some additional HTML in the midst of the rendering output of the base template.

Taking the example from above, let us say we want to render FirstName + MiddleName + LastName again:

@* ~/EditorTemplates/Person.cshtml *@
@model Person
@{
    var extension1 = ViewData.ContainsKey("ExtensionPoint1")
        ? ViewData["ExtensionPoint1"] : string.Empty;
}
<div class="Person">
    @FirstName
    @Html.Raw(extension1)
    @LastName
</div>

The template basically renders FirstName + LastName but provides an “extension point” for inserting HTML between the two names. A pretty silly application of the pattern, but, you know, it is an example only.

The extension must be a string containing HTML. It is only rendered if you provide it.

@* ~/EditorTemplates/PersonWithMiddleName.cshtml *@
@model PersonWithMiddleName

@{
    var extension1 = @RenderMiddleName().ToString();
    ViewData["ExtensionPoint1"] = extension1;
}
@Html.Partial("~/EditorTemplates/Person.cshtml", Model)

@helper RenderMiddleName()
{
    @MiddleName
}

Our specialized template makes use of the Person.cshtml “base template” for rendering the parts that the base template already knows best how to render. But it combines that with its own specializd rendering by only injecting the part that is really different from the base template – the middle name.

We don’t define the extension1 string directly but use a Razor helper instead. This allows us to make use of the Razor syntax to define the part to inject rather than writing lenghy worms of plain HTML strings.

Conclusion

Using Editor Templates (and Display Templates) in a smart combination with Html.Partial and ViewData you can leverage a (maybe) unknown range of object-oriented techniques for building your web pages, allowing for a modular, clean design in this part of your web application just like in the rest of your application, thus improving code reuse and maintainability of your templates.

I think this is great news! What do you think? Have you been using this approach before? Do you have better ideas? Or do you see any issues with this approach?

Generic Types are prettier than Dictionaries

If you need to pass key-value-pairs to a method you can find many modern implementations prefer to take them as an “object” rather than a dictionary. This allows you to create a anonymous object which is prettier than a dictionary: It is a shorter notation, and it brings along some of the advantages of static typing:

var result = MyMethodThatTakesAnAnonymousObject(
    new { foo = "bar", baz = 1 };

 

The method then reflects on the object and uses the property names as keys and their values as the – values.

What you might not have been aware of: The same can be done for return objects. If the caller of the method knows what keys it expects, you can support it by taking this expectation as an anonymous object:

var result = PleaseReturnTheResultInAnObjectLikeThis(
    new { foo = "", bar = 0 });
Console.WriteLine(result.foo);

 

And this is how it works:

[TestClass]
public class LittleTest
{
    [TestMethod]
    public void Test_A_Little()
    {
        var t = PleaseReturnTheResultInAnObjectLikeThis(new { Foo = "" });
        Assert.AreEqual("hello", t.Foo);
    }
    private T PleaseReturnTheResultInAnObjectLikeThis<T>(T input)
    {
        // The following line simulates any logic that creates keys and
        // values in any form. You can use LINQ to transform them into
        // a dictionary as a pre-step to fill them into your T object.
        var values = new Dictionary<string, object> { { "Foo", "hello" } };

        // The next line brings us to the heart of the idea
        return MapToGenericType(input, values);
    }
    private static T MapToGenericType<T>(T input, IDictionary<string, object> values)
    {
        var constructorInfo = input.GetType().GetConstructors().Single();
        var parameterInfos = constructorInfo.GetParameters().ToArray();
        var parameters = new object[parameterInfos.Length];
        foreach (var parameterInfo in parameterInfos)
        {
            parameters[parameterInfo.Position] = values[parameterInfo.Name];
        }
        var output = (T) constructorInfo.Invoke(parameters);
        return output;
    }
}

The clue is that an anonymous object always brings along its anonymous type with a constructor whose parameters are 1:1 the properties that you defined for the anonymous object. You can use generics to transport knowledge of the type of any anonymous object beyond the scope where it was defined.

This way you kind of define an expectation to the results in a static-typed manner. Your compiler will not guarantee that the expectations hold true though, you will only find it by the time that MapToGenericType is executed.

Calling an Oracle Stored Proc with CLOB from System.Data.OracleClient

You might have stumbled upon this and it might have made you tear your hair just as it did to me. When you try to call a stored procedure from .NET using System.Data.OracleClient, you won’t be able to pass a CLOB parameter value > 4000 Bytes.

I got the following error message when trying to do so:

ORA-01460 – unimplemented or unreasonable conversion requested

This issue has been reported in lots of places on the web already. Unfortunately I wasn’t able to find the right hint to remedy this problem – until a fellow employee of mine saved my day!

In fact, the solution, or rather workaround, is quite simple and can be found on http://henbo.spaces.live.com/blog/cns!2E073207A544E12!332.entry:

Set the System.Data.OracleClient.OracleParameter.OracleDbType property to System.Data.OracleClient.OracleType.Clob.
– AND –
Set the parameter value when BeginTransaction has already been called on the DbConnection.

Don’t let the “OracleDbType” (implying that the guy speaks about Oracle’s version of the client) derange you: The trick works for the Microsoft client just as well!

Enterprise Architect: Beware of for-each loops!

While developing a C#-based add-in for Sparx Enterprise Architect, I just encountered a very nasty bug:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at VariantClear(tagVARIANT* pvarg)
at System.Runtime.InteropServices.CustomMarshalers
.EnumeratorViewOfEnumVariant.MoveNext()
at Foo.bar()

The exception only arises when I deploy the add-in as a compiled (Release build) DLL. When debugging the add-in from within Visual Studio, it worked fine. And this is the “evil” code in Foo.bar():

foreach (EA.Element element in package.Elements)
{
    doSomething();
}

A second glance to the exception stack trace and a reading of this thread made me clear that the translation of “foreach” to a COM operation fails in that specific case. Use the following workaround to get rid of the issue:

for (short i = 0; i < package.Elements.Count; i++)
{
    EA.Element element =
        (EA.Element) package.Elements.GetAt(i);
    doSomething();
}

Much thanks to R Henry who had the same problem and posted his findings in the above-mentioned thread!