Friday 11 October 2013

The ExpandoObject Stringified

I had a requirement to output some data as part of a number of pages in an e-commerce site. This data would change from page to page and typically get richer as a user would go through an order path in the application. The data needed to be in JSON format and was going to be used by the marketing guys to help track information about user behaviour across the order process. The data was also subject to change regularly depending on what the marketing team wanted to track. In short, I had to construct a JSON string on the server side in C#.

I had seen something like this done before where a StringBuilder was used to construct a large JSON string which was then pushed out in the response with the rest of the page markup. This approach seemed messy and difficult to maintain. I did a bit of research on some approaches to constructing a potentially complex and changing JSON object using C# and came across the ExpandoObject class. MSDN has a nice succinct explanation of ExpandoObject:
"Represents an object whose members can be dynamically added and removed at run time."
You can find this class in .NET 4 in the System.Dynamic namespace. ExpandoObject lets you effectively "model" an object on the fly with properties that don't really exist (just like using the ViewBag in ASP.NET MVC). In my case, it saved me from writing a number of classes or complex strings just to hold data that was to be output in page responses. Instead, I could use ExpandoObject and then use a JSON serializer to stringify the object.

The example below shows how easy and flexible it is to use ExpandoObject with the Newtonsoft .NET JSON library (available as a NuGet package):
dynamic orderInfo = new ExpandoObject();

orderInfo.OrderDate = DateTime.Today;

orderInfo.ProductTypesAdded = new List<dynamic>();
orderInfo.ProductTypesAdded.Add("Radio");
orderInfo.ProductTypesAdded.Add("Television");
orderInfo.ProductTypesAdded.Add("Recorder");

orderInfo.ReachedCheckout = true;
orderInfo.PaymentMethod = "Card";
            
orderInfo.DeliveryInfo = new ExpandoObject();
orderInfo.DeliveryInfo.Method = "First";
orderInfo.DeliveryInfo.Country = "UK";

var json = JsonConvert.SerializeObject(orderInfo);
The resulting JSON is:
{
    "OrderDate":"2013-10-11T00:00:00+01:00",
    "ProductTypesAdded":[
        "Radio",
        "Television",
        "Recorder"
    ],
    "ReachedCheckout":true,
    "PaymentMethod":"Card",
    "DeliveryInfo":{
        "Method":"First",
        "Country":"UK"
    }
}

Sunday 1 September 2013

C# MongoDB Repository Implementation

I recently started a small project with a friend and we opted for MongoDB as our data store. One of the initial tasks was to write a repository class that allowed us to store, retrieve, update and search for entities in MongoDB. In the past, I've worked on codebases where there was one repository per entity, it didn't take long to discover that this resulted in a lot of code duplication across the data layer. So the goal here was to write the repository generically enough so that we only have one implementation that can be reused for any entity within our application. This meant that each entity would have its own MongoDB collection (if you're not familiar with MongoDB, a collection can be thought of as a table in the relational world - see this page for a comparison).

One of the first steps in this task was to write an interface for the repository - this is in case we decide to use a different data store in the future. A while back, I found a repository interface on the Redmondo blog which covers everything I'd want from a repository, so we'll use a slightly modified version of that interface (I've removed comments for brevity, you can download the code using a link further below and that'll contain the comments):
public interface IRepository<TEntity> where TEntity : EntityBase
{
    bool Insert(TEntity entity);
    bool Update(TEntity entity);
    bool Delete(TEntity entity);
    IList<TEntity>
        SearchFor(Expression<Func<TEntity, bool>> predicate);
    IList<TEntity> GetAll();
    TEntity GetById(Guid id);
}
To paraphrase the code, this is a generic repository interface for an entity of type TEntity that must derive from a base class called EntityBase. The EntityBase class is a very simple abstract class and contains just one property, the identifier property:
/// <summary>
/// A non-instantiable base entity which defines 
/// members available across all entities.
/// </summary>
public abstract class EntityBase
{
    public Guid Id { get; set; }
}
The idea is for any entity that we want to manage in our data store, that entity must derive from EntityBase. So the infrastructure is all in place for our "MongoDbRepository". I used the official 10gen MongoDB C# driver (available as a NuGet package) and arrived at the following repository implementation:
/// <summary>
/// A MongoDB repository. Maps to a collection with the same name
/// as type TEntity.
/// </summary>
/// <typeparam name="T">Entity type for this repository</typeparam>
public class MongoDbRepository<TEntity> :
    IRepository<TEntity> where
        TEntity : EntityBase
{
    private MongoDatabase database;
    private MongoCollection<TEntity> collection;

    public MongoDbRepository()
    {
        GetDatabase();
        GetCollection();
    }

    public bool Insert(TEntity entity)
    {
        entity.Id = Guid.NewGuid();
        return collection.Insert(entity).Ok;
    }

    public bool Update(TEntity entity)
    {
        if (entity.Id == null)
            return Insert(entity);
       
        return collection
            .Save(entity)
                .DocumentsAffected > 0;
    }

    public bool Delete(TEntity entity)
    {
        return collection
            .Remove(Query.EQ("_id", entity.Id))
                .DocumentsAffected > 0;
    }

    public IList<TEntity>
        SearchFor(Expression<Func<TEntity, bool>> predicate)
    {
        return collection
            .AsQueryable<TEntity>()
                .Where(predicate.Compile())
                    .ToList();
    }

    public IList<TEntity> GetAll()
    {
        return collection.FindAllAs<TEntity>().ToList();
    }

    public TEntity GetById(Guid id)
    {
        return collection.FindOneByIdAs<TEntity>(id);
    }

    #region Private Helper Methods
    private void GetDatabase()
    {
        var client = new MongoClient(GetConnectionString());
        var server = client.GetServer();

        database = server.GetDatabase(GetDatabaseName());
    }

    private string GetConnectionString()
    {
        return ConfigurationManager
            .AppSettings
                .Get("MongoDbConnectionString")
                    .Replace("{DB_NAME}", GetDatabaseName());
    }

    private string GetDatabaseName()
    {
        return ConfigurationManager
            .AppSettings
                .Get("MongoDbDatabaseName");
    }

    private void GetCollection()
    {
        collection = database
            .GetCollection<TEntity>(typeof(TEntity).Name);
    }
    #endregion
}
In case you're interested, a while ago I wrote a separate blog post on how to perform CRUD operations against MongoDB using the C# driver. To use the repository implementation, you'll need two application configuration settings defined - one that stores the name of the MongoDB database and the other that contains the MongoDB connection string (with a placeholder for the database name). You should have something like:
<appSettings>
  <add key="MongoDbDatabaseName" value="MyCarsDatabase" />
  <add key="MongoDbConnectionString"
         value="mongodb://localhost/{DB_NAME}?safe=true" />
</appSettings>
Hopefully this repository is useful to someone else who is working with MongoDB in C#. Any questions or suggestions for improvements are always welcome via comments. The source code is available on GitHub - https://github.com/rsingh85/MongoDbRepository.

Thursday 8 August 2013

Project Euler

I came across the Project Euler site the other day. If you enjoy solving mathematical/programming problems then I recommend this site. You're given a number of problems to solve with each problem in the series getting progressively more difficult. If you sign up, you can submit your answer and if your answer is correct then you'll get access to the message boards for the problem you worked on. The problem message boards are where you can share your solution and see solutions by other people who may have used a different programming language. It's interesting to see the C# solutions compared to the solutions in other languages. Worth a look if you have time!

Sunday 28 July 2013

Implicit/Explicit Conversion Operators

I saw some code yesterday which at first glance looked odd. A method was accepting a parameter of a custom type named Money and the calling code was passing in a double value. After a bit of confusion I recalled that the C# language natively supports conversion operators.

If you have a custom type, you have the option to define conversion operators on your type which let you convert from your custom type to a target type and from the target type back to the custom type. Conversion can be implicit or explicit. Implicit conversion means that users of your custom type can convert to the target type without having to perform a type cast operation. Explicit conversion forces a type cast to be performed.

To demonstrate this, we'll use the case I came across. Imagine we have a Money class which is composed of a currency and a value that the money represents. We may initially decide that we want the Money class to be flexible so that users of the class can treat it is a value (a double type in this case). This means that when a double is expected (e.g. as an argument to a method), the user of the class can pass the Money instance which will implicitly be converted to its value form. Moreover, we can also make the conversion from double to Money implicit, meaning that whenever a Money instance is expected, we can pass in a double. Our initial attempt at the Money class implementation would therefore look something like:
public class Money
{
    public string Currency { get; set; }
    public double Value { get; set; }

    // Implicit conversion from Money to double
    public static implicit operator double(Money money)
    {
        return money.Value;
    }

    //  Implicit conversion from double to Money
    public static implicit operator Money(double @double)
    {
        return new Money { Value = @double };
    }
}
With the above class, the following code would therefore compile:
var money = new Money() { Currency = "GBP", Value = 10.5 };
            
// Implicitly convert Money to a double
double moneyValue = money;

// Convert a double to Money (Money.Currency will be null!)
Money moneyInstance = moneyValue;
Notice that when converting a Money instance to a double, we would lose information on the Money instance (the currency in this case). Also, when converting a double to a Money, the currency is never set. It would therefore make more sense in this scenario to use explicit conversion operators so that the user is forced to be aware that they could lose information in the conversion or have a partially initialised Money instance (it isn't a straight-forward conversion). To define explicit conversion on the Money class, the only change required would be to replace the "implicit" keyword with the "explicit" keyword on the two conversion methods. The Money class would now look like:
public class Money
{
    public string Currency { get; set; }
    public double Value { get; set; }

    // Explicit conversion from Money to double
    public static explicit operator double(Money money)
    {
        return money.Value;
    }

    //  Explicit conversion from double to Money
    public static explicit operator Money(double @double)
    {
        return new Money { Value = @double };
    }
}
After making this change, the example calling code above would fail to compile with the following two compile-time error messages:

Cannot implicitly convert type 'ConversionOperators.Money' to 'double'. An explicit conversion exists (are you missing a cast?)
Cannot implicitly convert type 'double' to 'ConversionOperators.Money'. An explicit conversion exists (are you missing a cast?)

As the errors point out, we now need to explicitly cast between the types - as demonstrated in the code below.
var money = new Money() { Currency = "GBP", Value = 10.5 };
            
double moneyValue = (double) money;

Money moneyInstance = (Money) moneyValue;

You can download the example code by clicking here.

Sunday 7 July 2013

C# How To: Implement the Soundex Algorithm

I caught the end of a conversation about the Soundex algorithm at work the other day which inspired me to write an implementation of it in C#. If you are not familiar with what Soundex is then the Wikipedia article on Soundex is a good place to start. I first came across this algorithm in a Natural Language Processing module during my university education. In a nutshell, when the Soundex algorithm is applied to a word, a Soundex Code is produced as output. Words that differ in spelling but sound the same (homophones) should produce the same Soundex Codes. For instance, "to" and "two" are spelt differently, but sound the same and therefore produce the same Soundex Code of "T000".

This is a useful little algorithm and I particularly like it for its simplicity and the fact that the heuristics used in the algorithm work well in most cases (one limitation of Soundex is that it falls short of covering words that sound the same but have a different first letter, e.g. "site" and "cite" produce different Soundex codes). Soundex is useful when writing search functionality where you want to account for misspellings in the users query. It's worth pointing out that SQL Server natively supports Soundex (see the Soundex function in T-SQL, for example).

My C# implementation is below - I opted to implement it in a static class that exposes one public method "For". The example source code is available on GitHub - https://github.com/rsingh85/SoundexExample

public static class Soundex
{
    public static string For(string word)
    {
        const int MaxSoundexCodeLength = 4;

        var soundexCode = new StringBuilder();
        var previousWasHOrW = false;

        word = Regex.Replace(
            word == null ? string.Empty : word.ToUpper(),
                @"[^\w\s]",
                    string.Empty);

        if (string.IsNullOrEmpty(word))
            return string.Empty.PadRight(MaxSoundexCodeLength, '0');

        soundexCode.Append(word.First());

        for (var i = 1; i < word.Length; i++)
        {
            var numberCharForCurrentLetter =
                GetCharNumberForLetter(word[i]);

            if (i == 1 &&
                    numberCharForCurrentLetter ==
                        GetCharNumberForLetter(soundexCode[0]))
                continue;

            if (soundexCode.Length > 2 && previousWasHOrW &&
                    numberCharForCurrentLetter ==
                        soundexCode[soundexCode.Length - 2])
                continue;

            if (soundexCode.Length > 0 &&
                    numberCharForCurrentLetter ==
                        soundexCode[soundexCode.Length - 1])
                continue;

            soundexCode.Append(numberCharForCurrentLetter);

            previousWasHOrW = "HW".Contains(word[i]);
        }

        return soundexCode
                .Replace("0"string.Empty)
                    .ToString()
                        .PadRight(MaxSoundexCodeLength, '0')
                            .Substring(0, MaxSoundexCodeLength);
    }

    private static char GetCharNumberForLetter(char letter)
    {
        if ("BFPV".Contains(letter)) return '1';
        if ("CGJKQSXZ".Contains(letter)) return '2';
        if ("DT".Contains(letter)) return '3';
        if ('L' == letter) return '4';
        if ("MN".Contains(letter)) return '5';
        if ('R' == letter) return '6';

        return '0';
    }
}
Example:

// Both lines below output R100
Console.WriteLine(Soundex.For("Ravi"));
Console.WriteLine(Soundex.For("Ravee"));

Sunday 9 June 2013

C# Set Implementation (pre-.NET 3.5)

I was recently working on a .NET 3.0 project and found that this version of the framework didn't have any support for a mathematical Set collection. As of .NET 3.5 there is the System.Collections.Generic.HashSet implementation, however, I was working on a WinForms project and updating the framework on the client machines was out of scope for this piece of work.

I had some spare time available and thought it would be a good exercise to write a custom generic Set collection. The first step was to define an interface:

using System.Collections.Generic;

...

public interface ISet<T> : ICollection<T>
{
    void UnionWith(ISet<T> set);
    void IntersectWith(ISet<T> set);
}

By inheriting from ICollection, we get all of the generally useful collection-based methods included in the ISet interface (e.g. Add, Clear, Contains etc.). I just had two methods to add to those, these were the set union and set intersection operations.

The next step was the implementation of the set. To keep things simple, I opted for a list-based implementation. I used the adapter pattern to map the ISet interface to a list interface. Therefore, the internal representation of the Set was actually an instance of System.Collections.Generic.List. By using this approach, I could delegate a lot of the method logic to use the list method implementations (i.e. Clear, Contains, CopyTo and Remove). The only custom logic I needed to write was the Add method (to avoid adding items already within the set), UnionWith method, IntersectWith method, ToString method and the readonly indexer. The implementation is below:

/// <summary>
/// A list-based implementation of a mathematical set.
/// </summary>
public sealed class ListBasedSet<T> : ISet<T>
{
    private IList<T> _thisSet = new List<T>();

    /// <summary>
    /// Gets the number of elements contained in this set.
    /// </summary>
    public int Count { get { return _thisSet.Count; } }

    /// <summary>
    /// Gets a value indicating whether this set is readonly.
    /// </summary>
    public bool IsReadOnly { get { return false; } }

    /// <summary>
    /// Gets the item at the specified index in the set.
    /// </summary>
    /// <param name="i">
    /// Index of the item to retrieve from the set.
    /// </param>
    /// <returns>Item at the specified index</returns>
    public T this[int i] { get { return _thisSet[i]; } }

    /// <summary>
    /// Adds item into the set if this set does not already
    /// contain the item.
    /// </summary>
    /// <param name="item">Item to add to the set.</param>
    public void Add(T item)
    {
        if (!Contains(item))
            _thisSet.Add(item);
    }

    /// <summary>
    /// Clears the items from the set resulting in an empty set.
    /// </summary>
    public void Clear()
    {
        _thisSet.Clear();
    }

    /// <summary>
    /// Determines if the specified item is within the set.
    /// </summary>
    /// <param name="item">
    /// The object to locate in the set.
    /// </param>
    /// <returns>
    /// true if item is found in the set; false otherwise.
    /// </returns>
    public bool Contains(T item)
    {
        return _thisSet.Contains(item);
    }

    /// <summary>
    /// Copies the entire set to a one-dimensional array, 
    /// starting at the specified target index of the target 
    /// array.
    /// </summary>
    /// <param name="array">
    /// The one-dimensional array to copy to.
    /// </param>
    /// <param name="arrayIndex">
    /// The zero-based index in array at which copying begins.
    /// </param>
    public void CopyTo(T[] array, int arrayIndex)
    {
        _thisSet.CopyTo(array, arrayIndex);
    }

    /// <summary>
    /// Removes the specified item from the set.
    /// </summary>
    /// <param name="item">Item to remove.</param>
    /// <returns>
    /// true if item is successfully removed; otherwise, false. 
    /// This method also returns false if item was not found 
    /// in the set.
    /// </returns>
    public bool Remove(T item)
    {
        return _thisSet.Remove(item);
    }

    /// <summary>
    /// Returns an enumerator that iterates through the set.
    /// </summary>
    /// <returns>
    /// An IEnumerator object that can be used to iterate 
    /// through the set.
    /// </returns>
    public IEnumerator<T> GetEnumerator()
    {
        return _thisSet.GetEnumerator();
    }

    /// <summary>
    /// Returns an enumerator that iterates through the set.
    /// </summary>
    /// <returns>
    /// An IEnumerator object that can be used to iterate 
    /// through the set.
    /// </returns>
    System.Collections.IEnumerator 
        System.Collections.IEnumerable.GetEnumerator()
    {
        return _thisSet.GetEnumerator();
    }

    /// <summary>
    /// Modifies this set to contain all elements that are 
    /// present in itself, the specified collection, or both.
    /// </summary>
    /// <param name="otherSet">The set to union with.</param>
    public void UnionWith(ISet<T> otherSet)
    {
        foreach (var item in otherSet)
            Add(item);
    }

    /// <summary>
    /// Modifies this set to contain only the elements that are 
    /// present in it and in the specified collection.
    /// </summary>
    /// <param name="otherSet">The set to intersect with.</param>
    public void IntersectWith(ISet<T> otherSet)
    {
        var itemsToRemove = new List<T>();

        for (int i  = 0; i < Count; i++)
        {
            T item = this[i];

            if (!otherSet.Contains(item))
                itemsToRemove.Add(item);
        }

        foreach (var itemToRemove in itemsToRemove)
            Remove(itemToRemove);
    }

    /// <summary>
    /// Returns a string representation of this set
    /// </summary>
    /// <returns>A string representation of this set</returns>
    public override string ToString()
    {
        var setStringBuilder = new StringBuilder();
        setStringBuilder.Append("{");

        foreach (var item in _thisSet)
            setStringBuilder.Append(
                string.Format(" {0},", item));
            
        return string.Format("{0} }}"
            setStringBuilder.ToString().TrimEnd(','));
    }
}

Example usage:
ISet<string> set = new ListBasedSet<string
    { "Mars""Earth""Pluto" };
ISet<string> otherSet = new ListBasedSet<string
    { "Jupiter""Earth""Pluto""Venus" };
ISet<string> earthSet = new ListBasedSet<string
    { "Earth" };
ISet<string> emptySet = new ListBasedSet<string>();

set.UnionWith(otherSet);
Console.WriteLine("set UNION otherset = {0}", set);

Console.WriteLine("|set| (cardinality of set) = {0}", set.Count);

set.IntersectWith(earthSet);
Console.WriteLine("set INTERSECTION earthSet = {0}", set);

set.UnionWith(emptySet);
Console.WriteLine("set UNION emptySet = {0}", set);

set.IntersectWith(emptySet);
Console.WriteLine("set INTERSECTION emptySet = {0}", set);

You can download the source files for the ISet interface and the ListBasedSet class from here.

Monday 6 May 2013

Aspect-Oriented Programming in C# with PostSharp - Logging Aspect Example

I was looking at some code in a class library project with a colleague recently. One thing that stood out was that a lot of methods across the various classes in the library were using a "Logger" class to persist runtime information (things like actual parameters and exception messages). There was a clear pattern in how these methods were structured, they logged the fact that they were called (with parameter information) and then had logic specific to what they were supposed to do. Any exceptions raised by the main logic of the methods were also logged. The "Logger" instance was not being injected into each of these classes, it was a concrete implementation without an interface. In the end, we came to the conclusion that we could improve this code as follows:

  • We could de-couple the logger from all the classes by using dependency injection. This would involve creating an interface for the logger, ensuring the current logging class implements this interface and then rearchitecting the classes that use the logger so that they are IoC friendly. An IoC container such as Ninject could then be used to inject a specific implementation of the logger into the various classes at runtime.
  • Or, we can make use of Aspect-Oriented Programming (AOP)

The latter of these points is the subject of this blog post. AOP is a programming paradigm just like Object-Oriented Programming (OOP). But instead of focusing on classes, objects and methods - AOP focuses more on separating concerns through "aspects". AOP typically deals with concerns that "cross-cut" a codebase. Luckily for us, the most popular example of a cross-cutting concern seems to be logging. As my colleague and I witnessed in the class library project, logging was being applied across a number of classes, therefore tightly coupling the logger with these classes. Furthermore, it was clear that each method that was logging wasn't adhering to the single responsibility principle.

The goal was therefore to seperate these concerns in a clean way. AOP enables this by letting you implement cross-cutting concerns as aspects which are then applied to existing code through aspect weaving. The C# programming language doesn't have any first-class support for AOP as it is primarily an OOP language. But there are libraries that allow you to apply AOP concepts using existing C# language constructs. One such library is PostSharp, which makes it easy to write an aspect and then apply the aspect to existing code. In the example below, we'll make use of PostSharp to write an aspect for logging method call information to the debug output.

PostSharp Logging Aspect Example

The PostSharp library allows you to define aspects as standard C# attributes. You can do this by deriving from one of the aspect classes from the library and override the methods that are of interest to your aspect. In the logging aspect example below, we derive from the PostSharp.Aspects.OnMethodBoundaryAspect class and override the OnEntry, OnExit and OnException methods.

[Serializable]
public class LogAspectAttribute : OnMethodBoundaryAspect
{
    private Guid _methodCallIdentifier;
               
    public override void OnEntry(MethodExecutionArgs args)
    {
        _methodCallIdentifier = Guid.NewGuid();

        Debug.WriteLine("{0} - Entering method {1} with arguments: {2}",
            _methodCallIdentifier,
            args.Method.Name,
            string.Join(", ", args.Arguments));
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        Debug.WriteLine("{0} - Exited method {1}",
            _methodCallIdentifier,
            args.Method.Name);
    }

    public override void OnException(MethodExecutionArgs args)
    {
        Debug.WriteLine("{0} - Method {1} raised exception with message: {2}",
            _methodCallIdentifier,
            args.Method.Name,
            args.Exception.Message);
    }
}

Note that PostSharp contains a number of predefined aspect classes that you can derive from depending on your particular use case. For instance, the class PostSharp.Aspects.MethodInterceptionAspect is particularly useful for implementing security on methods (i.e. you can decide in your aspect whether to allow the intercepted call to proceeed through).

Back to the example above, the OnEntry method is called just before the target method (the method that we'll annotate with this attribute) is called. The OnExit method is called once the target method completes executing and the OnException method is called if the target method raises an exception. Each of these three methods provide useful points for us to do some logging. The MethodExecutionArgs instance passed to each method also contains some useful context information for us to add to the log.

To now use this aspect, it's a simple case of annotating the methods you want to log with the [LogAspect] attribute, as shown below.

[LogAspect]
void SayHelloToWithoutException(string name)
{
    Console.WriteLine("Hello, {0}!", name);
}

[LogAspect]
void SayHelloToWithException(string name)
{
    Console.WriteLine("Hello, {0}!", name);
    throw new Exception("Oops! Something went wrong...");
}

The logging logic is now neatly encapsulated in one location. If we call the two methods above, one after the other, we'll get the debug output:

Saturday 6 April 2013

10 C#/.NET Features You May Not Know About

I thought it would be useful to document some of the typically lesser known features of the C# programming language and the .NET framework as a series of posts. Some of these features I've found useful and others I probably just haven't found a suitable use case for yet.

1. Anonymous Code Scopes in Methods

It's possible to have anonymous inner scopes within your method definitions. (I'm yet to come across a non-contrived use case for this!)
void MethodWithAnonymousScope()
{
    var helloPart = "Hello";

    {
        var worldPart = "world";
        Console.WriteLine("{0} {1}", helloPart, worldPart);
    }

    // "worldPart" doesn't resolve in this scope
}

2. Increment/Decrement Operator Position Significance

The position of the increment (++) and decrement (--) operators is significant. In the example below, when the increment operator is used as a postfix, it returns the value of 'number' before it has been incremented. Conversely, the prefix increment operator returns the value after it has been incremented. The decrement operator works with the same logic but decrements the number.
void PlusPlusOperator()
{
    var number = 0;

    Console.WriteLine(number++); // Outputs zero
    Console.WriteLine(++number); // Outputs two
}

3. The Default Keyword

The default keyword is a neat way to get the default value for a specified type. It's especially useful when working in a generic context.
void DefaultKeyword()
{
    var intDefault = default(int); // default(int) == 0
    var boolDefault = default(bool); // default(bool) == false

    // default(string) == null (as for all reference types)
    var stringDefault = default(string); 
}

4. Null-Coalescing Operator

The null-coalescing operator (??) provides a succinct way of returning a default value if your reference or nullable-value type is null. In the following example, if myNullableInteger (left operand) is not null, then it's returned, else the default value for int is returned (right operand).
int NullCoalescingOperator()
{
    int? myNullableInteger = SomeMethodThatCouldReturnNull();
    return myNullableInteger ?? default(int);
}

5. Short-Circuit Evaluation with Boolean Operators

The logical AND (&&) and OR (||) operators are short-circuit evaluated (left to right). For example, if the left operand of a logical AND is false, the right operand is not evaluated (as the whole condition will always be false). Similarly, if the left operand of a logical OR is true, the right operand is not evaluated. This can be demonstrated by observing the output of:
void ShortCircuitEvaluation()
{
    bool result;
            
    result = LeftOperand(true) || RightOperand(false);
    result = LeftOperand(false) || RightOperand(true);
    result = LeftOperand(true) && RightOperand(false);
    result = LeftOperand(false) && RightOperand(true);
}

bool LeftOperand(bool value)
{
    Console.WriteLine("Left operand evaluated");
    return value;
}

bool RightOperand(bool value)
{
    Console.WriteLine("Right operand evaluated");
    return value;
}
It's useful to know this so that you can safely perform multiple tests in a single if statement. In the example below, if myObject is null, the right operand is not evaluated (which is good because it'd cause a NullReferenceException).
if (myObject != null && myObject.SomeProperty == SomeValue)
    ...
Also note that if you use a single '&' and single '|' you bypass short-circuit evaluation and force the entire condition to be evaluated.

6. Aliases for Generic Types

You can assign an alias to a namespace but you can also assign an alias to a specific generic type to save yourself from typing the awkward generic syntax over and over again (especially useful when working with key/value pair based generic types where the value may also be a key/value pair!).
using StringList = System.Collections.Generic.List<string>;
...
void GenericAliases()
{
    // Can use the alias "StringList"
    // instead of List<string> 

    var stringList = new StringList();
    stringList.Add("Hello");
    stringList.Add("World");
    stringList.ForEach(Console.WriteLine);
}

7. Extension Methods on Dynamic Types

I came across this one when working with the dynamic ViewBag in ASP.NET MVC. As the title states, you cannot invoke an extension method on a type (that has the extension method defined for it and is in scope) which is dynamically typed. I have documented this one in this post (click to view). As the post shows, you have to call your extension method in the same fashion as you would call a standard static method, then pass your dynamically typed variable in as a parameter to the extension method.

8. System.String supports an Indexer

The string class has a readonly (get) char indexer defined on it, thus allowing you to access characters in the string using a zero-based index.
void StringIndexer()
{
    string message = "Hello, world!";

    for (int i = 0; i < message.Length; i++)
    {
        Console.WriteLine(message[i]); 
    }
}

9. Using foreach with System.String

The string class implements the IEnumerable<char> interface, which means that you can use the foreach statement on a string to enumerate through each character.
void ForeachWithString()
{
    string message = "Hello, world!";

    foreach (char character in message)
    {
        Console.WriteLine(character);
    }
}

10. Introspecting Code with Expression Trees

The System.Linq.Expressions.Expression class enables you to represent a code expression in a tree-based data structure that can then be used for introspection. This is a powerful feature which also then enables code modification in the expression tree (at runtime) and then subsequent compilation and execution.

The following example shows how we can wrap a simple lambda expression into an Expression, introspect the expression, compile the expression (in this case returning a Func<int, int, int>) and then execute the expression.
void Expressions()
{
    Expression<Func<intintint>> addExpression = (a, b) => a + b;

    foreach (var param in addExpression.Parameters)
    {
        Console.WriteLine(
            "Func Param Name: {0}, Param Type: {1}"
            param.Name, 
            param.Type);
    }

    Console.WriteLine("Func return type: {0}"
        addExpression.ReturnType);

    Console.WriteLine("10 + 20 = {0}"
        addExpression.Compile()(10, 20));
                        
    // Can also use the Invoke method on the returned Func<...>
    // to aid readability
    // e.g. addExpression.Compile().Invoke(10, 20);
}
You may have indirectly used expression trees if you're an ASP.NET MVC developer. The HTML helper classes make extensive use of them, for example, the Html.TextBoxFor method has an overload that accepts a single parameter of type Expression<Func<dynamic, dynamic>>. An example call to this method would be @Html.TextBoxFor(m => m.FirstName) where 'm' is an instance of your view model. The TextBoxFor method uses the supplied expression (a lambda) to construct the HTML that is put back into the view. In this case it outputs an input element with an id and name attribute value of "FirstName" - which was retrieved using introspection (made possible with expression trees).

Saturday 30 March 2013

Dependency Resolution in ASP.NET MVC3/4 with Ninject

The topic for this post is setting up the Ninject Inversion of Control (IoC) container in your ASP.NET MVC3/4 applications. I'm assuming the reader has familiarity with the following concepts:

  • Programming to an interface (or contract)
  • The IoC programming technique
  • Dependency injection
  • IoC containers

The intention is for this post to serve as a useful reference for ASP.NET MVC developers who want to get an IoC container (specifically Ninject) up and running swiftly with the MVC framework.

When working on a new MVC project, one of my first steps usually involves setting up an IoC container. I've typically used Ninject as my IoC container due to its ease of setup and intuitive fluent API. As of ASP.NET MVC3, there is the option of using the Ninject extension for MVC3 (wrapped up in a NuGet package called Ninject.MVC3). This option is simple to setup and you'll typically have little reason to use another approach. Another option is to write your own implementation of the IDependencyResolver interface. In this scenario, you'll implement this interface (which again is quite simple with Ninject) and then hook your custom resolver into the framework for it to use. In a nutshell, the MVC framework will use your custom IDependencyResolver implementation as a first port of call to resolve any required dependencies.

In this post, we'll go with the former option.

Using the Ninject.MVC3 NuGet Package

As mentioned, the Ninject.MVC3 NuGet package is an easy way to get Ninject up and running in your project. The first step is to get the package installed in your solution. I'm using Visual Studio 2012 so the steps may differ slightly depending on what version of the IDE you're running on. Right click your MVC solution node in Solution Explorer. Select the "Manage NuGet Packages for Solution" option in the context menu.



This will bring up the NuGet package manager dialog. In the top right, you should see a text box with the watermark "Search Online". Type "Ninject" and hit enter. In the middle pane, you'll see the Ninject.MV3 package, select it and click the Install button.



At this point, the NuGet package manager will have done all of the hard work. If you expand the App_Start folder in your solution, you'll find a new file called NinjectWebCommon.cs.



This file contains a static class definition and a number of static methods. The methods that you're interested in are the CreateKernal and the RegisterServices methods. If you have had experience with Ninject in the past, then you'll be at home with what the CreateKernal method is doing. It creates an instance of the StandardKernal (the default implementation of Ninjects IKernal interface). The StandardKernel is the class you'll use to map (or in Ninject terminology "bind") interfaces to the implementations that you want to use. This is done by using the generic methods Bind and To on the kernel object, where you pass your interface and implementation, respectively, as type parameters. You'll notice that the CreateKernal method makes a call to a method named RegisterServices. This is the method where you'll register your bindings with Ninject.

private static void RegisterServices(IKernel kernel)
{
    // Register your ninject bindings here!
}
Now that Ninject is setup in the project, we'll try and inject a dependency through a controller constructor. In this example, imagine you have a simple logging interface, defined as:

public interface ILogService
{
    void Log(string message);
}
We then have an implementation of this interface:

public class DebugLogService : ILogService
{
    public void Log(string message)
    {
        System.Diagnostics.Debug.WriteLine(message);
    }
}
Imagine further that we now wanted various actions in our HomeController to log to the debug output. With dependency injection, one way to inject our DebugLogService implementation into our HomeController would be through the constructor - as follows:

public class HomeController : Controller
{
    private readonly ILogService _logService;

    public HomeController(ILogService logService)
    {
        _logService = logService;
    }

    public ActionResult Index()
    {
        _logService.Log(
            string.Format("Index() called at {0}", 
                DateTime.Now));

        return View();
    }
}
If you're following the steps and you now run your web application, you'll get a runtime exception stating that there was an error activating ILogService. This is good, as it tells you that Ninject tried to create an instance of the HomeController, but failed in doing so because the HomeController has no default constructor. The constructor that it does have, however, has one required parameter (logService) that Ninject has no type bindings for. We'll now go back to the static RegisterServices method in the NinjectWebCommon class and add the binding as shown below:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ILogService>().To<DebugLogService>();
}
If you now run the application, you'll find that the HomeController is successfully being instantiated with Ninject passing an instance of the DebugLogService class through to the constructor. You can verify this by looking at the output window for the log entry.



And that's it - you'll now follow this pattern for registering your bindings in the RegisterServices method and programming to your interfaces for which you have registered bindings. As all of your bindings are registered in a single location, swapping out your implementations with other implementations is an easy job. We can now easily switch all logging to a file by writing a new FileLogService (that implements ILogService) and then bind this to the ILogService in the RegisterServices method.

Sunday 17 March 2013

Binding to PasswordBox in WPF using MVVM

I'm currently working on a Windows Presentation Foundation (WPF) client application that adheres to the Model View ViewModel (MVVM) design pattern. Having had a lot of experience with .NET WinForms, the WPF learning curve wasn't so steep. The main areas I initially concentrated on were getting to grips with XAML, then concepts such as data binding, commands, dependency properties and attached properties. It's the last of these that helped in resolving the problem I had with the PasswordBox control and view model binding.

In WPF, data binding enables you to hook a specific property in your data context (in my case, the view model) to a property on a user interface control. For example, the following XAML markup shows how the Text property on a TextBox can be bound to the FirstName property on the view model:
<TextBox Height="23" 
         Width="120" 
         Text="{Binding Path=FirstName, Mode=TwoWay}" />
As the Mode is set to TwoWay, any text changes by the user will result in the FirstName property being updated in the view model, likewise, any programmatic change to the FirstName view model property will result in the user interface being updated (provided that your view model implements the INotifyPropertyChanged interface and the setter of the FirstName property raises the OnPropertyChanged event). In my case, I had a PasswordBox control in my XAML markup that needed binding to a view model string property named Password. Initially I tried this in XAML:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             Password="{Binding Path=Password, Mode=OneWay}" />
However, the Visual Studio XAML designer immediately underlined the 'Password="{Binding...' line and stated the error:
A 'Binding' cannot be set on the 'Password' property of type 'PasswordBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
As the binding error message alludes to, it turns out that the Password property on the PasswordBox control is a standard .NET CLR property and this was a deliberate security-based design decision by Microsoft to prevent plain text passwords from sitting around in memory. In my case however, having the password sit in memory wasn't an issue.

Of course, if the application I was working on wasn't using MVVM, then I could easily have picked up the user entered password in the code-behind in a button click event handler (e.g. this.userPasswordBox.Password would return the plain password). But because the application was adhering to MVVM, the code-behind was pretty much empty (except for the usual constructor boilerplate code). Instead, all of the UI "events" were being handled by the view model via command objects exposed as public properties. This therefore made retrieving the password from the PasswordBox and assigning it to the view model Password property an annoyingly interesting problem!

After doing a bit of research on the web, I found a couple of solutions.

  • Pass the PasswordBox control to the view model: In this solution, the PasswordBox control itself is passed back to the view model via a command parameter (which is hooked up to the "OK" button). The method that handles the command then gets the PasswordBox instance via an object type parameter which can be cast back into a PasswordBox. You can then retrieve the password easily through the PasswordBox.Password property.
  • Use attached properties to enable binding: In this solution, attached properties (a special type of dependency property) are created, enabling you to use them on the PasswordBox control and bind to your view model property.

The first solution above works but I wasn't too happy with passing a UI component to my view model - it violates the MVVM design pattern principle of decoupling the view from the view model. I went for the second option as it enabled binding to the PasswordBox.Password property (albeit indirectly) and didn't violate the use of MVVM in the process.

To get this working, take a look at the static PasswordBoxAssistant class on Samuel Jack's interesting blog. The class defines the attached properties that you can then use in your XAML markup, in my case, it resulted in the following markup:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             ap:PasswordBoxAssistant.BindPassword="true"
             ap:PasswordBoxAssistant.BoundPassword=
                "{Binding Path=Password, 
                  Mode=TwoWay, 
                  UpdateSourceTrigger=PropertyChanged}"
 
/>
As shown in the markup above, you'll need to import the namespace that the PasswordBoxAssistant class is defined in and add an alias to it (in my case "ap"). Having done that, it's finally just a case of using the attached properties to wire up the binding to your view model property.

Friday 1 March 2013

The Generic Lazy Type

Lazy<T> is a monad type that was introduced in .NET 4 and provides an alternative mechanism for implementing lazy initialisation. Lazy initialisation is where you intentionally delay the creation of an object that is expensive to create.

You would typically want to use lazy initialisation in scenarios where the object (which is expensive to create) may or may not be used in the execution flow of your program. In this case, it makes sense to only initialise the object if it is required. One reliable place where you may have seen the lazy initialisation tactic being used is in an implementation of a singleton class - which will have a method or property that returns the singleton instance, for example:

public MySingletonClass GetInstance()
{
    if (_singleton == null)
        _singleton = new MySingletonClass();

    return _singleton;
}
The logic before the return statement is an example of lazy initialisation, where the singleton is only instantiated the first time GetInstance is called and never before it. Subsequent calls to GetInstance will then also return the same instance, hence we have an implementation of the singleton design pattern. In this particular case, we don't know if MySingletonClass is expensive to create, and we don't particularly care as we're using lazy initialisation to prevent multiple instances of MySingletonClass from being created.

If we now go back to the mainstream use for lazy initialisation, where we want to delay instantiation of expensive-to-create objects, you could adopt the pattern above where you conditionally instantiate an instance of an object. However, since .NET 4, you have an alternative option with the use of Lazy<T>. An instance of Lazy<T> wraps around your expensive-to-create object, you pass this instance around in your code and when ever the underlying expensive-to-create object is required, you can call the Value property on Lazy<T> which will instantiate the object and return it to you.

The following contrived example should make it more clear. Imagine you have a Customer class and an Order class. A single customer can have many orders, so we'll make use of composition and have the Customer class support a List of Order objects. The Customer class has one constructor that accepts a customer ID. Using the supplied ID, the constructor then goes and retrieves the orders for the customer from an order repository. Note that in reality your entity classes will usually be dumb and just support getter and setter properties and it'll be the responsibility of your data access layer/framework (like Entity Framework) to instantiate and populate your entities appropriately. Continuing with our contrived example, our initial attempt may therefore look like:

public class Order { }

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        // Simulate getting lots of orders from an
        // order repository
        Orders = Enumerable
            .Repeat<Order>(new Order(), 200)
                .ToList();
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}
As the code indicates, it would be expensive to instantiate a Customer object if we didn't require the order information contained within it. This is where you would apply the concept of lazy initialisation. In this case, we'll make use of the Lazy<T> type. The following code shows how the Customer class would look if we lazily instantiate the Orders list using Lazy<T>.

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public Lazy<List<Order>> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        Orders = new Lazy<List<Order>>(() => {
            // Simulate getting lots of orders from an 
            // order repository 
            return Enumerable
                .Repeat<Order>(new Order(), 200)
                    .ToList();
            }
        );

        Debug.WriteLine(this);
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}
As you can see, the constructor of the Customer class instantiates an instance of Lazy<T> that wraps around the List of Order objects. The constructor of Lazy<T> is passed a lambda expression that expresses what needs to be returned when the list of orders is requested for (our expensive logic). Notice I've also put a call to Debug.WriteLine so you can observe the output of the following code and see how this behaves.

var customer = new Customer(1);
                       
Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

// Ok, we now want the orders...
var ordersForCustomer = customer.Orders.Value;

Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

Debug.WriteLine("Customer {0} has {1} order(s)", 
    customer.Id, ordersForCustomer.Count);
If you execute the code above using the updated Customer class, you'll find that instantiating a Customer object is no longer an expensive operation. The output you should see in your debug window is:

I'm customer with id 1
Are orders instantiated? False
Are orders instantiated? True
Customer 1 has 200 order(s)
Notice that when the Customer object was initialised, the runtime executed the constructor logic as expected (verifiable with the ToString output). We then check our Lazy objects IsValueCreated property to ensure it hasn't yet created an instance of the list and populated it. The property returned False as expected. On the next line, we explicitly call the Value property on the Orders property (our Lazy object) - this forces our lazy object to instantiate. We re-query the IsValueCreated property which now returns True and finally we output the order count to show that the orders have been successfully lazily-loaded.