LP on .NET

September 6, 2011

Using a Collection Initializer with a Dictionary

Filed under: .NET,C#,Software Development — Larry Parker @ 10:39 pm
Tags: , ,

Collection initializers (introduced in C# 3.0) provide an easy way to initialize a collection of items.  For example, instead of doing this…

List<Color> colors = new List<Color>();
colors.Add(new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" });
colors.Add(new Color { Value = 0xFF9400D3, Name = "Dark Violet" });
colors.Add(new Color { Value = 0xFF708090, Name = "Slate Gray" });

…we can do this:

List<Color> colors = new List<Color>
{
    new Color { Value = 0xFFF0F8FF, Name = "Alice Blue" },
    new Color { Value = 0xFF9400D3, Name = "Dark Violet" },
    new Color { Value = 0xFF708090, Name = "Slate Gray" }
};

But what if we want to initialize a dictionary?  The traditional way would be like this:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>();
colors.Add(0xFFF0F8FF, "Alice Blue");
colors.Add(0xFF9400D3, "Dark Violet");
colors.Add(0xFF708090, "Slate Gray");

But how would we use a collection initializer?  When you iterate through a dictionary, each item is a KeyValuePair<TKey, TValue>.  But we can’t do this:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>
{
    new KeyValuePair<UInt32, String>(0xFFF0F8FF, "Alice Blue"),
    new KeyValuePair<UInt32, String>(0xFF9400D3, "Dark Violet"),
    new KeyValuePair<UInt32, String>(0xFF708090, "Slate Gray")
};

The solution is not entirely obvious, but it is succinct:

Dictionary<UInt32, String> colors = new Dictionary<UInt32, String>
{
    { 0xFFF0F8FF, "Alice Blue" },
    { 0xFF9400D3, "Dark Violet" },
    { 0xFF708090, "Slate Gray" }
};

This is not mentioned in the MSDN link shown above, but MSDN does discuss it here.

Hope this helps!

August 29, 2011

Dependency Injection and Delegates

Filed under: .NET,C#,Software Development — Larry Parker @ 10:46 pm
Tags: , ,

A couple of weeks ago I blogged about writing testable code using dependency injection.  This was done by injecting interface references into a class’s constructor:

public UserManager(IUserPersistence userPersistence, IEmailManager emailManager)
{
    _userPersistence = userPersistence;
    _emailManager = emailManager;
}

Assuming we have concrete classes called UserPersistence and EmailManager that implement these interfaces, we could simply inject the dependencies like this:

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), new EmailManager());
}

But what happens if the dependencies cannot actually be injected during construction because it’s too early to create them?  A good example of this is when the concrete classes themselves are constructed with a parameter that is not yet available.

Let’s say that when we register a user we get a guid back from our persistence layer that identifies the user.  Now let’s also say that our IEmailManager interface is written to apply to a single user at a time, and there’s a concrete class called EmailManager with a constructor that looks like this:

public class EmailManager : IEmailManager
{
    public EmailManager(Guid userId)
    {
        _userId = userId;
    }
...
}

Since we don’t know the guid until we register the user (via the UserManager class), we can’t inject an IEmailManager into the UserManager class’s constructor.

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), new EmailManager(<oops!  What’s the guid?>));
}

The solution is to change UserManager’s constructor to take a delegate instead of an interface:

public class UserManager
{
    public UserManager(IUserPersistence userPersistence,
        Func<Guid, IEmailManager> emailManagerFactory)
    {
        _userPersistence = userPersistence;
        _emailManagerFactory = emailManagerFactory;
    }

    private IUserPersistence _userPersistence;
    private Func<Guid, IEmailManager> _emailManagerFactory;

Instead of the UserManager constructor directly taking an IEmailManager, it now takes a delegate that expects a guid and returns an IEmailManager.

Since the delegate is only supplied during UserManager’s construction and not executed, we don’t need to know the guid at this time:

public void DoIt()
{
    UserManager userManager = new UserManager(
        new UserPersistence(), o => new EmailManager(o));
}

Our delegate can be passed in several ways, but a lambda expression is a nice easy way to do it (“o” is a local variable of type Guid).

With this new approach, our RegisterUser method from our previous post now looks like this:

public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
{
    try
    {
        Boolean result = false;

        Guid userId = _userPersistence.AddUser(lastName, firstName, emailAddress);

        IEmailManager emailManager = _emailManagerFactory(userId);
        result = emailManager.SendLoginInfo();

        return result;
    }
    catch (Exception ex)
    {
        // Log the exception...

        return false;
    }
}

Note that when we execute our delegate (i.e. the _emailManagerFactory field) we pass in the user ID guid as a parameter (i.e. the value we just obtained from calling the AddUser method) and get back our IEmailManager interface reference.  Now we can call its methods and they will all act on the newly registered user.

Delegates are a great way to defer execution until needed, and this is a very useful technique to let you follow the dependency injection pattern even when you don’t have everything you need during object construction.

Hope this helps.

August 19, 2011

Serializing and Deserializing JSON Data

Filed under: .NET,C#,Software Development — Larry Parker @ 7:31 pm
Tags: , ,

My team is working on a web site that consumes JSON (JavaScript Object Notation) objects, and my job is to provide the back-end services for the data.

I hadn’t worked with JSON before but figured there was a simple way to serialize and deserialize JSON data.  A colleague pointed me to MSDN (always a good start) with this link, and a quick search pointed me to this site which had some nice JSON helpers.

After looking at the examples on both sites, I wrote some extension methods to make things easier.  Here’s what I came up with (after some suggestions on the method names by my team):

public static class JsonExtensionMethods
{
    /// <summary>
    /// Serializes an object to a JSON string.
    /// </summary>
    /// <typeparam name="T">The serializable class.</typeparam>
    /// <param name="entity">The object that will be serialized to JSON.</param>
    /// <returns>Returns a serialized representation of the object as a JSON string.</returns>
    public static String ToJson<T>(this T entity)
        where T : class
    {
        String result = null;

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, entity);
            result = Encoding.Default.GetString(ms.ToArray());
        }

        return result;
    }

    /// <summary>
    /// Deserializes a JSON string into an object.
    /// </summary>
    /// <typeparam name="T">The class to deserialize the JSON string into.</typeparam>
    /// <param name="jsonObject">The serialized object as a JSON string.</param>
    /// <returns>Returns an instance of the concrete class representing the JSON string.</returns>
    public static T FromJson<T>(this String jsonObject)
        where T : class
    {
        T entity = Activator.CreateInstance<T>();

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonObject)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            entity = (T)serializer.ReadObject(ms);
        }

        return entity;
    }
}

Here are some unit tests that show how they are used:

[TestMethod()]
public void SerializeTest()
{
    Customer customer = new Customer { FirstName = "Joe", LastName = "Smith" };

    String actual = customer.ToJson();

    Assert.AreEqual("{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}", actual);
}

[TestMethod()]
public void DeserializeTest()
{
    String jsonObject = "{\"FirstName\":\"Joe\",\"LastName\":\"Smith\"}";

    Customer actual = jsonObject.FromJson<Customer>();

    Assert.AreEqual("Joe", actual.FirstName);
    Assert.AreEqual("Smith", actual.LastName);
}

Both of the tests use a class called Customer that looks like this:

[DataContract]
public class Customer
{
    [DataMember]
    public String LastName { get; set; }

    [DataMember]
    public String FirstName { get; set; }
}

Notice that the ToJson extension method is applied to a class, while the FromJson extension method is applied to a string.  The extension methods are a nice touch because you don’t have to go through a static helper class in your code, but instead just use the applicable extension methods directly on your variable (depending if you’re serializing to JSON or deserializing from JSON).

Hope you like it!

Create a free website or blog at WordPress.com.