LP on .NET

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!

August 14, 2011

Writing Testable Code

Filed under: .NET,C#,Software Development — Larry Parker @ 5:59 pm

About a year ago, my idea of unit testing included anything that could be tested no matter how heavy the setup.  This included having an available test database, available web services, and other external resources (like the file system) that were needed to test my code.

While this kind of test environment is useful, it’s more along the lines of an integrated test environment that QA would have set up.  Test likes these can really be categorized as integration tests and not unit tests.

If you want to really unit test your code, you don’t want any of the aforementioned dependencies to be part of your tests.  Unit tests should be fast and should just test a single piece of code – not your entire application’s runtime environment.

Let’s take a look at both of these approaches.  Consider the following code that registers a user with your application:

public class UserManager 
{
    public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
    {
        try 
        {
            String connString = "...";

            using (var connection = new SqlConnection(connString))
            using (var cmd = new SqlCommand())
            {
                cmd.CommandText = @"
INSERT INTO User (LastName, FirstName, EmailAddress)
VALUES (@LastName, @FirstName, @EmailAddress)
";

                cmd.Parameters.Add("LastName", SqlDbType.NVarChar).Value = lastName;
                cmd.Parameters.Add("FirstName", SqlDbType.NVarChar).Value = firstName;
                cmd.Parameters.Add("EmailAddress", SqlDbType.NVarChar).Value = emailAddress;

                connection.Open();
                cmd.Connection = connection;
                cmd.ExecuteNonQuery();
            }

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

Now let’s write a test for the RegisterUser method.

[TestMethod()]
public void RegisterUserTest()
{
    UserManager target = new UserManager();
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

This test attempts to register a user named Bert Smith and verifies that the registration succeeded (i.e. we assert that the RegisterUser method returned true).

The test is simple enough, but in order to run it we need a database and also a User table in it.  It’s possible to set up a test database like this and ensure that the connection string is supplied for the test.  But now we have a heavy dependency that probably needs to be in a certain state every time we run the test (e.g. we probably don’t already want the user Bert Smith in the database before we run the test).

Let’s step back a second and ask ourselves exactly what we want to test in our RegisterUser test.  Do we want to test that ADO.NET works?  Hopefully Microsoft has already tested that well enough.  Do we want to test that we can write SQL that inserts a row into our User table?  At some point, but not right now.

The job of the RegisterUser method is to register a user with our system.  This probably involves some data validation (like ensuring the email address was supplied and is in a valid format), adding the user to persistent storage (like in a User table in a SQL database), and possibly sending an email to the user to let him know the registration succeeded.

All of these things are possible tasks that the RegisterUser method might need to execute, but we don’t necessarily want to test the tasks themselves – we only want to test that the tasks were called in the expected way.

Consider the email step.  How would we test that anyway?  We could use .NET’s SmtpClient class and have RegisterUser send the registration email to ourselves via our company’s email server (if we had rights to do so) and verify that we did indeed receive the email in our inbox.

The problem with this is that you need to verify that the email arrived in your inbox by looking at your inbox.  But when you run this test along with hundreds of other tests, you are not going to do this.  And neither is an automated test system.

So how do we write our RegisterUser test so we can test what we need without having all of these external dependencies?

The answer is:  dependency injection.

Dependency injection is a pattern whereby dependencies are supplied (or injected) into a system.  There are plenty of discussions about this (Martin Fowler, Wikipedia, etc.), but in a nutshell you simply hand the dependencies (typically as interfaces) to your class or method which then works with them in an abstract way.  In other words, instead of working directly with ADO.NET, your method works with an interface responsible for adding the user to persistent storage.

Let’s revisit the RegisterUser method with a couple of dependencies injected into the UserManager class’s constructor.

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

    private IUserPersistence _userPersistence;
    private IEmailManager _emailManager;

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

            if (_userPersistence.AddUser(lastName, firstName, emailAddress))
                result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                    emailAddress);

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

Notice that our constructor takes two parameters that are interfaces that define our tasks.

public interface IUserPersistence 
{
    Boolean AddUser(String lastName, String firstName, String emailAddress);
    // Other interface members... 
}

public interface IEmailManager 
{
    Boolean SendUserRegistrationEmail(String lastName, String firstName, String emailAddress);
    // Other interface members... 
}

As for the RegisterUser method, what happened to the SQL that will add the user to the User table in our database?  The short answer is, “Who cares?”

Persisting the user to the database is now farmed out to an interface called IUserPersistence that has a method called AddUser.  The SQL will probably be in there, but as far as the RegisterUser method is concerned, it doesn’t care.  Our RegisterUser method just works with the interfaces:

        if (_userPersistence.AddUser(lastName, firstName, emailAddress))
            result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                emailAddress);

This is dependency injection at work.  Our code is now testable and our test can now inject dependencies into the UserManager class without having to have a database and email server set up to run the test!

Let’s rewrite our test and inject some home-grown dependencies.

public class UserPersistenceStub : IUserPersistence 
{
    public Boolean AddUser(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

public class EmailManagerStub : IEmailManager 
{
    public Boolean SendUserRegistrationEmail(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

[TestMethod()]
public void RegisterUserTest()
{
    var userPersistenceStub = new UserPersistenceStub();
    var emailManagerStub = new EmailManagerStub();

    UserManager target = new UserManager(userPersistenceStub, emailManagerStub);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

We simply created two stub classes that implement our interfaces and then injected instances of those classes into our UserManager instance.

Now our test runs without the need for a database or an email server.  We were able to achieve this because we rewrote our UserManager class and RegisterUser method as testable code using dependency injection.

Our unit test can be improved (e.g. by using tools like Moq), but I will save that for another post.  For now, the main takeaway of this post is that code can be written to be testable using dependency injection.

It took me a while to realize the importance of writing testable code.  The fact that testable code can be unit tested without needing external resources like databases opens up the door to writing a slew of tests to thoroughly test your code, and this gets you into the area of code coverage and even test-driven development.

More to come on this…

August 3, 2011

Case-invariant String Comparisons

Filed under: .NET,C# — Larry Parker @ 8:23 am

String comparisons are one of those things done fairly frequently in a programmer’s day job.  The fact that our alphabet has upper-case and lower-case versions of each letter makes our job a little harder since we sometimes need to perform case-invariant comparisons.  For example, we may not care about the case of the user’s last name when performing a customer lookup (although that sometimes gets resolved at the SQL level, but that’s another topic).

A simple way to compare strings without regard to case is to simply convert them to the same case.  For example:

String a = "Antwerp";
String b = "ANTWERP";

Boolean areEqual = (a.ToLower() == b.ToLower());

There’s nothing wrong with this approach (we could have used ToUpper as well), but let’s take a deeper look at what’s going on here.

The String.ToLower method has the following signature:

public string ToLower();

This means that it returns a string.  So we start off with our original string, apply the ToLower method to it, and return a new string with all characters lower case.

In our original example, we’re actually doing two ToLower operations, so two strings are returned and finally compared for equality.

Again, there’s nothing really wrong with this approach except that under the covers it seems to be doing a bit more than we need.  What we really want is to simply compare two strings for equality without regard to case.

Fortunately, there is a more efficient way.  The .NET String class provides an overload of the Equals method that lets us specify how we want to compare our string with another string.

public bool Equals(string value, StringComparison comparisonType);

One of the members of the StringComparison enum gives us just what we want, and we can rewrite our code as such:

String a = "Antwerp";
String b = "ANTWERP";

Boolean areEqual = a.Equals(b, StringComparison.OrdinalIgnoreCase);

This performs a string comparison between the two strings by using ordinal sort rules and ignoring case, and the Equals method simply returns a boolean value indicating if the comparison succeeded.  We didn’t have to convert our strings to lower-case, return the new string, and compare with the other converted string.

As a disclaimer, I have not performed benchmark tests on the two approaches to see which one is faster, nor have I inspected the .NET IL code under the covers.

But it just seems more intuitive that comparing existing strings using a designated set of rules would be a more optimal approach.

I find as I continue to work with .NET I start to think about these things a bit more.

August 2, 2011

.NET Fusion Log Viewer 101

Filed under: .NET,C# — Larry Parker @ 9:15 pm

The .NET Framework provides a utility called the Assembly Binding Log Viewer (Fuslogvw.exe) that lets you configure the CLR to log and view assembly binding and probing information for your .NET apps.  This can be very helpful in tracking down why assemblies cannot be loaded (e.g. you’ve got the wrong version installed, a version from the GAC is loading unexpectedly, etc.).

You can run Fuslogvw.exe by opening up a Visual Studio command prompt and typing “fuslogvw”, or by running it from the Microsoft Windows SDK Tools menu under the Visual Studio 2010 program group.

Here’s a screenshot of the Fusion Log Viewer’s main screen:

image

To set things up, click the Settings button and fill out the Log Settings dialog box accordingly.  For example:

image

Once you’ve enabled logging, the CLR will start sending assembly binding information to the output directory whenever you run a .NET application.  Fusion’s logging output is created in folders for each app you run, and separate HTML files are created for each assembly.  For example:

image

You can view the contents of each HTML file by double-clicking them from Windows Explorer, or by selecting them in the Fusion Log Viewer and clicking the View Log button (or double-clicking the grid row).

Note that you might need to click the Refresh button to see any data.

image

Each HTML file shows detailed information about the CLR’s success (or failure) in attempting to load an assembly:

image

Important Tip

All this assembly binding logging is useful, but don’t forget to turn it off!  The CLR will continue to log information even after you exit the Fusion Log Viewer!  I actually left it on without realizing it, and one day found over 18,000 HTML files in the output directory!

So make sure you disable logging in the Log Settings dialog when you no longer need it:

image

Well those are the basics of this useful (although potentially verbose) utility.  For more information, see MSDN here, as well as an excellent blog post on the subject here.

Hope this helps.

Create a free website or blog at WordPress.com.