Serialization in one line

I have this neat static helper class, which makes it easy to serialize an instance of a class marked with [DataContract] and [DataMember]. E.g.

var xml = DataContractSerialization.Serialize(instance);

Where instance is an instance of any class which is serializable with DataContractSerializer.

Deserialization is equally easy:

var instance = DataContractSerialization.Deserialize(typeof(MyClass), xml);

or:

var instance = DataContractSerialization.Deserialize<MyClass>(xml);

The code for that class, which also can be found on GitHub:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace SoftwarePassion.Common.Core.Serialization
{
    /// <summary>
    /// One-liners for the DataContractSerializer class.
    /// </summary>
    public static class DataContractSerialization
    {
        /// <summary>
        /// Serializes the specified value.
        /// </summary>
        /// <typeparam name="TType">The type of the value.</typeparam>
        /// <param name="value">The value.</param>
        /// <param name="knownTypes">The known types.</param>
        /// <returns>A string (xml) with the serialized value.</returns>
        public static string Serialize<TType>(TType value, params Type[] knownTypes)
        {
            if (knownTypes == null)
            {
                knownTypes = new Type[] { };
            }

            var serializer = new DataContractSerializer(typeof(TType), knownTypes);
            var stringBuilder = new StringBuilder(1024);
            using (var stream = XmlWriter.Create(stringBuilder))
            {
                serializer.WriteObject(stream, value);
                stream.Flush();
            }

            return stringBuilder.ToString();
        }

        /// <summary>
        /// Deserializes the specified XML into an instance of the given TType.
        /// </summary>
        /// <typeparam name="TType">The type of the data expected to have be serialized in the given xml.</typeparam>
        /// <param name="xml">The XML.</param>
        /// <param name="knownTypes">The known types.</param>
        /// <returns>A deserialized instance of the given TType.</returns>
        public static TType Deserialize<TType>(string xml, params Type[] knownTypes) where TType : class
        {
            if (string.IsNullOrEmpty(xml))
                return null;

            if (knownTypes == null)
            {
                knownTypes = new Type[] { };
            }

            var serializer = new DataContractSerializer(typeof(TType), knownTypes);

            using (var reader = new StringReader(xml))
            {
                var stream = XmlReader.Create(reader);
                return serializer.ReadObject(stream) as TType;
            }
        }

        /// <summary>
        /// Deserializes the specified XML into an instance of the given dataType.
        /// </summary>
        /// <param name="dataType">The type of the data expected to have be serialized in the given xml.</param>
        /// <param name="xml">The XML.</param>
        /// <param name="knownTypes">The known types.</param>
        /// <returns> A deserialized instance of the given dataType. </returns>
        public static object Deserialize(Type dataType, string xml, params Type[] knownTypes)
        {
            if (string.IsNullOrEmpty(xml))
                return null;

            if (knownTypes == null)
            {
                knownTypes = new Type[] { };
            }

            var serializer = new DataContractSerializer(dataType, knownTypes);

            using (var reader = new StringReader(xml))
            {
                var stream = XmlReader.Create(reader);
                return serializer.ReadObject(stream);
            }
        }
    }
}

Testable Time

I was inspired by Mark Seeman’s TimeProvider class from Dependency Injection in .NET which is an Ambient Context for resolving the current date and time, but without the most prevalent shortcoming of DateTime.Now and DateTime.UtcNow: The lack of testability.

If you need to test how a class reacts to changes in date and/or time there is no way around having a testable TimeProvider. For this purpose I created a set of four classes, which interact nicely to allow for faking the time during a test. The most prominent is the TimeProvider class itself, because its the one that allows you to query the time, simply by calling UtcNow:

var now = TimeProvider.UtcNow;

It is possible to change what TimeProvider returns from UtcNow by changing its Current TimeProvider with the help of the TimeSetter class:

using (new TimeSetter(new DateTime(2012, 12, 12, 12, 12, 12)))
{

    // interesting test code…  
TimeProvider
.UtcNow // will now return 2012-12-12 12:12.12
}
TimeProvider
.UtcNow // will now return whatever the actual current date and time is.

TimeSetter implements IDisposable to allow for an easy way to reset which TimeProvider is used by UtcNow. The default provider is:

    /// <summary>
    /// DefaultTimeProvider implementation, which simply wraps a standard DateTime.UtcNow.
    /// </summary>
    internal class DefaultTimeProvider : TimeProvider
    {
        private DefaultTimeProvider()
        {
        }

        public static DefaultTimeProvider Instance
        {
            get { return DefaultTimeProvider.instance; }
        }

        protected override DateTime RetrieveUtcNow()
        {
            return DateTime.UtcNow;
        }

        private static readonly DefaultTimeProvider instance = new DefaultTimeProvider();
    }

TimeSetter has a method – SetNow – for changing the DateTime returned:

    /// <summary>
    /// Used for encapsulating a change of the DefaultTimeProvider. Very useful in tests.
    /// </summary>
    /// <remarks>
    /// Implements IDisposable so it figures out to restore the DefaultTimeProvider after use.
    /// Example:
    /// <code>
    ///   var timeProviderMock = new TimeProviderMock();
    ///   using (var timeSetter = new TimeSetter(timeProviderMock)
    ///   {
    ///     timeProviderMock.Now = new DateTime(2010, 1, 1);
    /// 
    ///     var now = TimeProvider.UtcNow; // Returns 2010-01-01.
    ///   }
    /// </code>
    /// </remarks>
    public sealed class TimeSetter : IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TimeSetter"/> class.
        /// </summary>
        /// <param name="timeProvider">The time provider to set as current TimeProvider.</param>
        public TimeSetter(TimeProvider timeProvider)
        {
            if (timeProvider == null)
            {
                throw new ArgumentNullException("timeProvider");
            }

            previousProvider = TimeProvider.Current;
            TimeProvider.Current = timeProvider;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TimeSetter" /> class with a TimeProviderMock as the
        /// provider.
        /// </summary>
        /// <param name="currentTime">The current time.</param>
        public TimeSetter(DateTime currentTime)
        {
            previousProvider = TimeProvider.Current;
            TimeProvider.Current = new TimeProviderMock(currentTime);
        }

        /// <summary>
        /// Restores the previous TimeProvider.
        /// </summary>
        public void Dispose()
        {
            TimeProvider.Current = this.previousProvider;
        }

        /// <summary>
        /// Sets the current time, if the provider is a TimeProviderMock.
        /// </summary>
        public static void SetNow(DateTime now)
        {
            var mock = TimeProvider.Current as TimeProviderMock;
            if (mock != null)
                mock.DateTime = now;
        }

        private readonly TimeProvider previousProvider;
    }

The mock class used by TimeSetter:

    /// <summary>
    /// Convenience class for testing scenarios. Use TimeSetter to encapsulate it in a using statement.
    /// </summary>
    public class TimeProviderMock : TimeProvider
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TimeProviderMock" /> class, setting the DateTime to DateTime.UtcNow.
        /// </summary>
        public TimeProviderMock()
        {
            DateTime = DateTime.UtcNow;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TimeProviderMock" /> class, setting the DateTime to the given value.
        /// </summary>
        public TimeProviderMock(DateTime now)
        {
            DateTime = now;
        }

        /// <summary>
        /// Gets or sets the date time.
        /// </summary>
        public DateTime DateTime { get; set; }

        protected override DateTime RetrieveUtcNow()
        {
            return DateTime;
        }
    }

TimeProvider itself has some convenience methods for creating DateTimes:

    /// <summary>
    /// Ambient TimeProvider with support for property injection to change the actual
    /// TimeProvider implementation, which is very useful in testing scenarios.
    /// </summary>
    public abstract class TimeProvider
    {
        /// <summary>
        /// Gets the current TimeProvider.
        /// </summary>
        public static TimeProvider Current
        {
            get
            {
                return TimeProvider.current;
            }

            internal set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }

                TimeProvider.current = value;
            }
        }

        /// <summary>
        /// Gets the current time in UTC.
        /// </summary>
        public static DateTime UtcNow
        {
            get
            {
                return TimeProvider.Current.RetrieveUtcNow();
            }
        }

        /// <summary>
        /// Creates a DateTime of DateTimeKind.Utc
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="month">The month.</param>
        /// <param name="day">The day.</param>
        /// <returns>The created DateTime.</returns>
        public static DateTime CreateUtc(int year, int month, int day)
        {
            return DateTime.SpecifyKind(new DateTime(year, month, day), DateTimeKind.Utc);
        }

        /// <summary>
        /// Creates a DateTime of DateTimeKind.Utc
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="month">The month.</param>
        /// <param name="day">The day.</param>
        /// <param name="hour">The hour.</param>
        /// <param name="minute">The minute.</param>
        /// <param name="second">The second.</param>
        /// <returns></returns>
        public static DateTime CreateUtc(int year, int month, int day, int hour, int minute, int second)
        {
            return DateTime.SpecifyKind(new DateTime(year, month, day, hour, minute, second), DateTimeKind.Utc);
        }

        /// <summary>
        /// Creates a DateTime of DateTimeKind.Utc
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="month">The month.</param>
        /// <param name="day">The day.</param>
        /// <param name="hour">The hour.</param>
        /// <param name="minute">The minute.</param>
        /// <param name="second">The second.</param>
        /// <param name="millisecond">The millisecond.</param>
        /// <returns></returns>
        public static DateTime CreateUtc(int year, int month, int day, int hour, int minute, int second, int millisecond)
        {
            return DateTime.SpecifyKind(new DateTime(year, month, day, hour, minute, second, millisecond), DateTimeKind.Utc);
        }

        /// <summary>
        /// Resets to using the default TimeProvider (which uses DateTime).
        /// </summary>
        public static void ResetToDefault()
        {
            TimeProvider.current = DefaultTimeProvider.Instance;
        }

        /// <summary>
        /// Override to implement the specific way to return a current DateTime of DateTimeKind.Utc.
        /// </summary>
        /// <returns>A DateTime.</returns>
        protected abstract DateTime RetrieveUtcNow();

        private static TimeProvider current = DefaultTimeProvider.Instance;
    }

These four classes together should solve most of the needs for testable time.

WCF Logging Configuration

WCF is a great framework, one the few really brilliant frameworks from Microsoft. It can be a bit hard, though, to figure out what goes wrong when it doesn’t work. One of the general drawbacks of high-level frameworks is that errors are typically swallowed deep down or at least very hard to understand.

 

Fortunately WCF has some great support for logging very detailed information about what happens. Unfortunately it is a bit like black magic to figure it out. That is why I here provide a simple logging configuration for reuse. It hasn’t failed yet to help me figure out what was wrong when WCF didn’t work.

 

It is divided into two parts, one in <system.serviceModel>:

 

  <system.serviceModel>

    <diagnostics>
      <messageLogging logEntireMessage="true"
                                logMalformedMessages="true"
                                logMessagesAtServiceLevel="true"
                                logMessagesAtTransportLevel="true"
                                maxMessagesToLog="50000"
                                maxSizeOfMessageToLog="2147483647" />
    </diagnostics>

  </system.serviceModel>

 

 

And one in <system.diagnostics>:

 

 

 

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" propagateActivity="true">
        <listeners>
          <add name="corr"/>
        </listeners>
      </source>

      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="corr"/>
        </listeners>
      </source>

      <source name="System.Net" tracemode="includehex" maxdatasize="1024">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>

      <source name="System.Net.Sockets">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>

      <source name="System.Net.Cache">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>

    </sources>

    <switches>
      <add name="System.Net" value="Verbose"/>
      <add name="System.Net.Sockets" value="Verbose"/>
      <add name="System.Net.Cache" value="Verbose"/>
    </switches>

    <sharedListeners>
      <add name="System.Net" initializeData="c:logApplicationName-network.log" type="System.Diagnostics.TextWriterTraceListener"/>
      <add name="corr" initializeData="c:logApplicationName.svclog" type="System.Diagnostics.XmlWriterTraceListener"/>
    </sharedListeners>

    <trace autoflush="true"/>
  </system.diagnostics>

Notice the paths to the two log files.

 

One of the neat things about this configuration is that it also logs messages on the network-level, which especially helps when looking into HTTP PUT/GET/POST problems.

 

The .svclog file can be read by the Microsoft Service Trace Viewer (simply double-click on the file and it opens automatically). If you have a .svclog-file on the client side and on the server side, this tool can correlate the two files, so the entire communation can be examined.

 

You have to have a little patience with the tool. The logs contain a lot of information and it can take a little time to learn to dig out the necessary data to fix a problem.

 

Also watch out for the size of the log files. They can grow very big, very fast (and will then take a long time to load in the log viewer). Don’t leave a configuration like this on a production server!

Review: Elemental Design Patterns

Jason McC. Smith has jotted down a few clever words, not so much about design patterns as about Elemental Design Patterns. There is quite a difference. If you haven’t read the original Design Patterns: Elements of Reusable Object-Oriented Software by the now so famous Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides) you really should. Its an important book.

 

Elemental Design Patterns is an important book, too. It may, eventually, end up being just as famous and having even more influence on development of object oriented software. I hope it will.

 

What is it about? The GoF book was about abstractions that could be hard to recognize in software without knowing what to look for. And even then it could be hard if the software was not built from the ground up using Design Patterns. Jason McC. Smith realized this difficulty while building a system aimed at finding Design Patterns in software. He finally figured out that something more, ehm elemental, was needed. Hence, Elemental Design Patterns.

 

Elemental Design Patterns can be something as simple as a method call, but it is important to acknowledge that we are talking about concepts here. The patterns are language independent (although they obviously feel really at home in object oriented languages). The neat thing about these patterns are the fact that you can use them to reason about structure in software on a conceptual level and all the higher abstracted design patterns can be built from the elementals.

 

Elemental design can even be used to reason about refactoring of code, which is one of the reasons I predict it will have a great influence in the years to come.

 

I can’t say that I think the book is a light read. It is very well written, though, but if you are a stranger to sigma and rho-calculus (I am), you will likely gain something from reading Jason McC. Smiths dissertation about the subject. And you’ll probably like to read the most important reference: A Theory of Objects by Martín Abadi and Luca Cardelli.

 

I say: If you have the slightest interest in the theoretical foundation of software development you should read this book.

Understanding Variable Scope in Workflow Foundation 4

When creating you own activities in WF4 you can sometimes be surprised at how the variable scope works. At times it seems dysfunctional. On thing that really bit me is that An activity cannot touch its own public variables. This seems strangely illogical but that is really how it is. Try creating a simple Activity like this:

 

using System.Activities;
using System.Collections.ObjectModel;

 

public class TestActivity : NativeActivity
{
    public InArgument<string> Value { get; set; }

    public Collection<Variable> Variables
    {
        get
        {
            if (variables == null)
                variables = new Collection<Variable>();

            return variables;
        }
    }

    protected override void Execute(NativeActivityContext context)
    {}

    private Collection<Variable> variables;
}

 

 

Drop it as the only activity in a workflow. Add a variable called test of type string on the activity. In properties try to use test variable for the Value property. You will get: Compiler error(s) encountered processing expression “test”. ‘test’ is not declared. It may be inaccessible due to its protection level.

 

image

 

The variable test is not in the scope of the activity on which it is declared!

 

An activity can, on the other hand, access the variables of its parents. To see this drop a Sequence and let TestActivity be a part of the Sequence. Then create test as a variable on Sequence instead. Again use test for the Value property. Now there is no problem. So an activity cannot access its own public variables but it can access its parent’s public variables.

 

image

Now hear this: Implementation children cannot access any public variables. At all. To see this, create an activity like this:

 

using System;
using System.Activities;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

[Designer(typeof(TestActivityDesigner))]
public class TestActivity : NativeActivity
{
    public InArgument<string> Value { get; set; }

    public Collection<Variable> Variables
    {
        get
        {
            if (variables == null)
                variables = new Collection<Variable>();

            return variables;
        }
    }

    public Activity Body { get; set; }

    protected override void CacheMetadata(NativeActivityMetadata metadata)
    {
        metadata.SetVariablesCollection(Variables);
        metadata.AddImplementationChild(Body);
    }

    protected override void Execute(NativeActivityContext context)
    {
        context.ScheduleActivity(Body);
    }

    private Collection<Variable> variables;
}

Also create an ActivityDesigner with this body:

    <sap:ActivityDesigner.Resources>
        <DataTemplate x:Key="Collapsed">
            <StackPanel>
                <TextBlock>Drop activity here...</TextBlock>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="Expanded">
            <StackPanel>
                <sap:WorkflowItemPresenter Item="{Binding Path=ModelItem.Body, Mode=TwoWay}"
                                        HintText="Drop activity here..." />
            </StackPanel>
        </DataTemplate>
        <Style x:Key="ExpandOrCollapsedStyle" TargetType="{x:Type ContentPresenter}">
            <Setter Property="ContentTemplate" Value="{DynamicResource Collapsed}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=ShowExpanded}" Value="true">
                    <Setter Property="ContentTemplate" Value="{DynamicResource Expanded}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </sap:ActivityDesigner.Resources>
    <Grid>
        <ContentPresenter Style="{DynamicResource ExpandOrCollapsedStyle}" Content="{Binding}" />
    </Grid>

 

Create a workflow with the new TestActivity, and put a test variable on the TestActivity. Place an Assign activity on the TestActivity as shown:

 

image

As you can see, the Body of TestActivity cannot access the public variable test. You can even try to enclose all of it in a Sequence and move the test variable to the Sequence scope:

 

image

 

So an implementation child cannot access a public variable. Period. If you change the line:

 

metadata.AddImplementationChild(Body);

 

to:

 

metadata.AddChild(Body);

 

It will work, because Body is now a public child instead.

 

You can then choose to create an implementation variable called test and it will now work:

 

protected override void CacheMetadata(NativeActivityMetadata metadata)
{
    metadata.SetVariablesCollection(Variables);
    metadata.AddImplementationChild(Body);
    testVariable = new Variable<string>("test", "42");
    metadata.AddImplementationVariable(testVariable);
}

The reason for the workflow foundation variable scope to work like this is probably that public variables are the means to pass values from one activity to another by using OutArgument and InArgument. This is actually a very flexible but at the same time a rather cumbersome approach. Not much flow in that.

A passionate dream

I know this will sound a bit aloof, but I have a dream. A dream that software can change the World. Change it to a better place.

For software to be able to do this, we need brilliant and passionate developers. I am not a brilliant developer, but I am good and I am very passionate, which makes me more than halfway there.

How do you become brilliant? I’m sorry to be harsh, but if you are not passionate, you will never become brilliant. You can be good, even better than good, but to really shine you have to be passionate. The problem with passion is (as anyone who has been in love will confirm) that it can devour and engulf you. It will take an inordinate amount of the available time of your life. And you may – like me – feel that you never have enough time, because what you do is simply SO exhilarating.

Besides being passionate you should also be open minded. Never (hardly) think that you have the only right solution to a problem, unless you really have it (you just might). Do not be weary about standing on the shoulders of others. As Knuth said: “Software is hard”. And it is no shame to build your work on top of the work of other brilliant minds.

Building on top of the work of others of course requires that you actually know of the work of these others. Today it has become widely used to blog about your knowledge. And blogs are a valuable tool to find specific technical information. It has become a necessary substitute for the often more than lacking documentation that the various frameworks suffer from.

Reading books can be another very good way to learn. There is so much precious information in books – and at times not so much information as just pages. A lot of computer science theory has been described in books, so if you – for some reason – skipped the computer science classes, you may be able to teach yourself by reading books.

Education and training is an obvious way to learn. I fought my way through university to get a Master’s in Computer Science. To me it was rough, but I am glad that I did it. I try to keep up to date by attending training classes – not as many as I would like – they tend to be expensive. But I like going.

For me there is no doubt that I learn best by doing. No doubt at all. But I also very much like to theorize about a lot of things. I just like thinking about stuff, trying to work it out in my head. Quite often the real solution comes out in a somewhat different looking way.

One of the amazing things with the field of software is that there are so many sub-fields in which you can immerse yourself, which means that more developers than you may think will be able to find an area in which they can be passionate and hopefully grow to become brilliant.

Your way towards brilliance may be long and windy and full of detours. At times tiresome, at times fun and exciting. On the way you will learn a lot about what you definitely should not focus on.

I know for a fact that I should not focus on mathematically intensive areas. I also know that I’m weak in the language areas – especially functional languages, which I, for some reason, always have had difficulties wrapping my brain around. I would like to improve my skills here, though. And may even get around to be doing something serious about it. I did start on “7 Programming Languages in 7 Weeks”, but a bit more than 7 weeks have now gone by. Eventually I will return to it, but I must say that Prolog is hard. At least as difficult for me as functional languages, of which I have spent the most time on F#.

To be honest I am not yet very focused in my efforts, although I do have some areas of particular interest (not necessarily to be confused with actual endeavors): I like databases, especially SQL Server, and I have an interest in development tools – that is: tools that help developers in their efforts to produce the brilliant software the world needs to be changed. I might end up focusing more on this area, but then again:

There is just so much exciting stuff going on in the world of software.

EDIT:

Dr. Dobbs has two articles along the same lines:

What Makes Great Programmers Different?

What Makes Bad Programmers Different?