Archive for the ‘C#’ Category.

When the Overlords Demand WebForms You Can Still Do MVC

I have worked for several clients that seem reluctant to use ASP.NET MVC for whatever reason. I’m sure you can imagine all of them and come up with counter-arguments…I know I have. If I am forced to use WebForms I have a simple MVC pattern that I like to use that allows me to write testable code (always my main concern). The following code should be considered a start point. I have used it on two projects, but I have had to make additions to suit each. I am only showing you enough to demonstrate how everything is hooked together.

Note: IContainer (not listed) represents an IoC container. In my case, I am implementing it with Unity.

The View

public interface IView
{
    IList<string> Errors { get; set; }
    void RedirectToRoute(string route, object routeParameters);
}

public abstract class PageBase<T> : Page where T : ControllerBase
{
    protected T Controller { get; private set; }
    protected IContainer Container { get; private set; }

    protected PageBase()
    {

    }

    public void RedirectToRoute(string route, object routeParameters)
    {
        Response.RedirectToRoute(route, routeParameters);
    }

    protected abstract bool NeedToAuthenticate();
    protected abstract void Authenticate();

    protected override void OnLoad(EventArgs e)
    {
        if (NeedToAuthenticate())
        {
            Authenticate();
            return;
        }

        Container = Application.GetContainer();
        Controller = Container.Resolve<T>();

        if (Controller == null)
        {
            throw new Exception("Could not resolve controller for " + typeof(T));
        }

        Controller.PageData = (Page.RouteData != null) ? Page.RouteData.Values : new RouteValueDictionary();

        Controller.SetView(this);

        if (IsPostBack)
        {
            Controller.PostBack();
        }
        else
        {
            Controller.Load();
        }

        Controller.SubscribeToEvents();

        base.OnLoad(e);

    }

}

The Controller

public abstract class ControllerBase<TView> : ControllerBase where TView : IView
{
    public TView View { get; set; }

    public override void SetView(object view)
    {
        View = (TView)view;
    }
}

public abstract class ControllerBase : IPageController
{
    public IDictionary<string, object> PageData { get; set; }

    protected ControllerBase()
    {
        PageData = new Dictionary<string, object>();
    }

    public object this[string key]
    {
        get
        {
            if (PageData != null && PageData.ContainsKey(key))
            {
                return PageData[key];
            }

            return null;
        }
    }

    /// <summary>
    /// Called during initial request.
    /// </summary>
    public virtual void Load()
    {
        // See PageBase
    }

    /// <summary>
    /// Called during a postback
    /// </summary>
    public virtual void PostBack()
    {
        // See PageBase
    }

    public virtual void SetView(object view)
    {
        // See PageBase
    }

    public virtual void SubscribeToEvents()
    {
        // See PageBase
    }
}

The Model

Not shown. The model will be a data type that corresponds to the UI. Typically, the View interface will contain a Model property that allows the Controller to get/set this information.

Hooking it up

What makes it happen is the following line of code (in PageBase.cs):

Controller = Container.Resolve<T>();

This allows the Controller to be created via IoC which allows you to inject dependencies through the constructor.

This is basically all there is to it, but I think an example might be in order. So, say I need a page that allows an admin to view system errors, I will create the following 4 files:

  • SystemErrorsView.aspx (WebForm)
  • ISystemErrorsView.cs (View interface)
  • SystemErrorsController.cs (the Controller)
  • SystemErrorsModel.cs (optional, may not be needed)
public interface ISystemErrorsView : IView
{
    void SetSystemErrors(IList<string> systemErrors);
}

public partial class SystemErrorsView : PageBase<SystemErrorsController>, ISystemErrorsView
{
    public void SetSystemErrors(IList<string> systemErrors)
    {
        // display the errors somehow
    }
}

public class SystemErrorsController : ControllerBase<ISystemErrorsView>
{
    public SystemErrorsController(/* inject stuff here using IoC */)
    {
        // injected members
    }

    public override void Load()
    {
        // use stuff that you injected to get data for the view
        var systemErrors = ...
        View.SetSystemErrors(systemErrors);
    }

    public override void SubscribeToEvents()
    {
        // see below
    }

}

Events

As you can see from above, Controller-to-View communication occurs directly through the ISystemErrorsView interface. View-to-Controller communication happens using events.

Let’s continue the example. We will add a Clear button to the View that allows an admin to clear all system errors.

The first thing we do is add an event to the View interface:

public interface ISystemErrorsView : IView
{
    event EventHandler WhenCleared;
    void SetSystemErrors(IList<string> systemErrors);
}

Now, we need to implement this in the code-behind for the View. Assume we have a button on the page called btnClear. We are going to intercept the buttons click event and then raise the WhenCleared event that we defined on the View interface:

public partial class SystemErrorsView : PageBase<SystemErrorsController>, ISystemErrorsView
{
    public event EventHandler WhenCleared;

    private void btnClear_Clicked(object sender, EventArgs e)
    {
        if (WhenCleared != null)
        {
            WhenCleared(sender, e);
        }
    }
}

Lastly, we need to subscribe to the event in our Controller:

public class SystemErrorsController : ControllerBase<ISystemErrorsView>
{
    public override void SubscribeToEvents()
    {
        View.WhenCleared += WhenCleared;
    }

    public void WhenCleared(object sender, EventArgs e)
    {
         // update database
         // refresh view
    }

}

Conclusion

I don’t like writing conclusions. That’s all I have. All typical warnings and caveats apply.

Windows Azure and Object-Oriented Testable Code

I am currently working on an Azure application that makes heavy use of blob storage (think raw data storage), table storage (think object database) and queues (think queues). From a high level point of view, these are constructs that could be useful to many enterprise applications being built today.

With that said, I’ve had to do a little work to make Azure more friendly to my way of building software. Let me deviate for a moment…

Lately, I have tried to distill everything that I know about object-oriented programming down to one statement: If I can test it, it’s good enough for now. There’s code readability and things like that which must be considered, but when I say this I am really referring to the structural elements of the application. Good enough for now means that everything is in a state that can be easily refactored later (if need be) and it means that the code is testable in an automated way (NUnit). My designs tend to rely on dependency injection, inversion of control and make heavy use of abstractions.

The Azure Storage API (what I’m mostly familiar with in the world of Azure) seems to be a throwback to older MS designs: sealed classes based on no abstractions (interfaces, abstract base classes). In other words, it’s an all or nothing black box approach. So forget about mocking. Granted, MS makes stuff easy to use but at the same time doesn’t seem to understand that that how I connect everything together is important, too.

Fortunately, it has been trivial to get around this using Bridge/Adapter-ish patterns.

My approach to blob storage has been something along these lines (THIS IS NOT PRODUCTION READY CODE – EXAMPLE ONLY):

public interface IBlob
{
    void UploadFile(string fileName);
    // just a few more methods here
    // not exposing every method on CloudBlob
}

public interface IBlobContainer
{
    IBlob GetBlobReference(string blobAddress);
}

public interface IBlobStorage
{
    IBlobContainer GetContainer(string name);
}

public class BlobStorage : IBlobStorage
{
    private readonly CloudBlobClient _client;

    public BlobStorage()
    {
        var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        _client = account.CreateCloudBlobClient();
    }

    public IBlobContainer GetContainer(string name)
    {
        return new BlobContainer(_client, name);
    }
}

public class BlobContainer : IBlobContainer
{
    private readonly CloudBlobClient _client;
    private readonly string _containerName;

    public BlobContainer(CloudBlobClient client, string containerName)
    {
        _client = client;
        _containerName = containerName;
    }

    public IBlob GetBlobReference(string blobAddress)
    {
        var container = _client.GetContainerReference(_containerName);
        container.CreateIfNotExist();
        var blob = container.GetBlobReference(blobAddress);
        return new Blob(blob);
    }
}

public class Blob : IBlob
{
    private readonly CloudBlob _cloudBlob;

    public Blob(CloudBlob cloudBlob)
    {
        _cloudBlob = cloudBlob;
    }

    public void UploadFile(string fileName)
    {
        _cloudBlob.UploadFile(fileName);
    }
}

This gives me IBlob, IBlobContainer and IBlobStorage….my own interfaces, which can easily be mocked and improves my testability.

I am doing something similar with queues. Again, this is an example only (I say this over and over in an attempt to keep “nitpicking” type comments to a minimum). Rest assured, my production code is a little more rich than this.

public interface IQueueMessage
{
    object Content { get; }
    string AsString { get; }
}

public interface IQueue
{
    void AddMessage(IQueueMessage message);
    IQueueMessage GetMessage();
    void DeleteMessage(IQueueMessage message);
}

public interface IQueueLocator
{
    IQueue GetQueue(string queueName);
}

public class QueueMessage : IQueueMessage
{
    internal CloudQueueMessage CloudQueueMessage { get; private set; }

    public QueueMessage(CloudQueueMessage cloudQueueMessage)
    {
        CloudQueueMessage = cloudQueueMessage;
    }

    public QueueMessage(byte[] content)
    {
        CloudQueueMessage = new CloudQueueMessage(content);
    }

    public QueueMessage(string content)
    {
        CloudQueueMessage = new CloudQueueMessage(content);
    }

    public object Content
    {
        get { return CloudQueueMessage; }
    }

    public string AsString
    {
        get { return CloudQueueMessage.AsString; }
    }
}

public class Queue : IQueue
{
    private readonly CloudQueue _cloudQueue;

    public Queue(CloudQueue cloudQueue)
    {
        _cloudQueue = cloudQueue;
    }

    public void AddMessage(IQueueMessage message)
    {
        if (_cloudQueue == null)
            return;
        _cloudQueue.AddMessage((CloudQueueMessage)message.Content);
    }

    public IQueueMessage GetMessage()
    {
        if (_cloudQueue != null)
        {
            var content = _cloudQueue.GetMessage();
            return new QueueMessage(content);
        }

        return null;
    }

    public void DeleteMessage(IQueueMessage message)
    {
        if (_cloudQueue != null)
        {
            var content = (CloudQueueMessage)message.Content;
            _cloudQueue.DeleteMessage(content);
        }
    }
}

public class QueueLocator : IQueueLocator
{
    private static CloudQueueClient _queueStorage;

    public IQueue GetQueue(string queueName)
    {
        if (_queueStorage == null)
        {
            CreateQueueStorage();
        }

        if (_queueStorage != null)
        {
            var cloudQueue = _queueStorage.GetQueueReference(queueName);
            cloudQueue.CreateIfNotExist();
            return new Queue(cloudQueue);
        }

        return null;
    }

    private static void CreateQueueStorage()
    {
        var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        _queueStorage = storageAccount.CreateCloudQueueClient();
    }
}

Conclusion

Not perfect, I know, but it’s good enough for now. I have hidden the fact that there are CloudStorageAccount’s and CloudBlobClient’s and CloudQueueClient’s. This may or may not work for you. My main concern is that I have something that I can mock. I can use dependency injection and inversion of control and I am able to see how my application interacts with Azure in my unit tests.

A few extension methods that I have loved

Ever since extension methods were introduced into C# (and I don’t exactly remember when that was because my memory totally sucks) I have found uses for them. In my opinion, the initial fears surrounding extension methods have proved false. I do not feel they make code difficult or hard to follow. They have allowed me organize my “utility” classes and write some very expressive code (in most cases). Also, extension methods allow you to do some convenient things because you can call them on null references (under the covers its a static method after all).

String Extensions

Here are a few string extension methods that I use. The one I will probably get flack for is the F method. The name is not very expressive but it is very compact, which is what I was going for. I really dislike using string.Format and this provides a compact alternative. Any suggestions for another name would be welcome, though.

string result = “Hello, {0}!”.F(userName);

Note, I express the positive “HasValue” as well as the negative “IsNullOrEmpty”. I think most people know that it’s good to be consistent with the code you write. However, I have both of these methods because I have found that context matters. If I am writing a guard clause for instance, I might use IsNullOrEmpty. If I am writing “bidness rulez” I might use HasValue….well, maybe.

public static class StringExtensions
{
    public static string F(this string format, params object[] args)
    {
        return format == null ? string.Empty : string.Format(format, args);
    }

    public static bool IsNullOrEmpty(this string input)
    {
        return (input == null) || input.All(char.IsWhiteSpace);
    }

    public static bool HasValue(this string input)
    {
        return !input.IsNullOrEmpty();
    }

}

Enumerable and Enumerable<T> Extensions

When all you have is an IEnumerable or an IEnumerable it’s pretty convenient to be able to call Count and ForEach. I have found that having the notion of “is null or empty” on any time of enumerable class is also very convenient at times.

public static class EnumerableExtensions
{
    public static int Count(this IEnumerable input)
    {
        int count = 0;

        var enumerator = input.GetEnumerator();
        while(enumerator.MoveNext())
        {
            count++;
        }

        return count;
    }

    public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
    {
        if (list == null)
            return;

        foreach(var item in list)
        {
            action(item);
        }
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list)
    {
        return (list == null || list.Count() == 0);
    }
}

IList Extension Methods

Similar to my IEnumerable extension methods, here are a few I have found convenient to have for IList. The Remove method which takes a Predicate has been particularly useful to me.

public static class ListExtensions
{
    public static void AddRange<T>(this IList<T> list, IEnumerable<T> values)
    {
        foreach (T value in values)
        {
            list.Add(value);
        }
    }

    public static void Remove<T>(this IList<T> list, Predicate<T> predicate)
    {
        if (list.Count == 0)
            return;

        var deletes = list.Where(value => predicate(value)).ToList();

        foreach (var delete in deletes)
        {
            list.Remove(delete);
        }
    }

    public static bool IsNullOrEmpty<T>(this IList<T> list)
    {
        return (list == null || list.Count() == 0);
    }

    public static bool HasValues<T>(this IList<T> list)
    {
        return !IsNullOrEmpty(list);
    }

}

Some Admittedly Dangerous Extension Methods

I will openly admit that extension methods like the following can be dangerous. I consider these “white box” extension methods, because you need to know some things before you can call them. These fall into the category of pure convenience for me.

Object Extension Methods

public static class ObjectExtensions
{
    // for type casting
    public static T As<T>(this object obj) where T:class
    {
        return obj as T;
    }

}

byte[] Extension Methods

public static class ByteArrayExtensions
{
    public static T Deserialize<T>(this byte[] bytes)
    {
        var formatter = new BinaryFormatter();
        var stream = new MemoryStream(bytes);
        return (T)formatter.Deserialize(stream);
    }
}

Additional String Extensions

public static class StringExtensions
{
    // Deserialize XML
    public static T FromXml<T>(this string input) where T:class
    {
        var xs = new XmlSerializer(typeof(T));
        var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(input));
        var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        var result = xs.Deserialize(memoryStream) as T;
        return result;
    }

}

Conclusion

OK, the end. I have shown you a few extension methods that I have found particularly useful. I know many of you are chomping at the bit to offer me your opinions and what not. No shortage of those out there. So, have a good day. Hope you got a few ideas.

Adding fluent interfaces to .NET framework classes

If you are going to blog, I think it’s important to blog regularly (I say this after taking about a year off). The drawback is that you might not always have “big bang” articles. Still, I think this is kind of cool. Here’s a fluent interface that I added to System.Thread. I think this is a good example of adding a simple fluent interface to an existing .NET framework class.

For the record, I want to say that I often do experiments like this in my day to day work. I find that I am continually trying to find ways to make the code that I write more readable (within the context I am writing it).

public class ThreadWaitFor
{
    private readonly Thread _thread;
    private readonly int _value;

    public ThreadWaitFor(Thread thread, int value)
    {
        _thread = thread;
        _value = value;
    }

    public void Milliseconds()
    {
        _thread.Join(_value);
    }

    public void Seconds()
    {
        _thread.Join(_value * 1000);
    }

    public void Minutes()
    {
        _thread.Join((_value * 1000) * 60);
    }
}

public static class ThreadExtensions
{
    public static ThreadWaitFor WaitFor(this Thread thread, int value)
    {
        return new ThreadWaitFor(thread, value);
    }
}

This allows me to do this:

Thread.CurrentThread.WaitFor(30).Seconds();
Thread.CurrentThread.WaitFor(5).Minutes();
Thread.CurrentThread.WaitFor(1000).Milliseconds();

Template Method Pattern without Inheritance

I go back and forth with Template Method. I find it convenient, but sometimes I think it can be too confusing if it is overused. I feel like the best code requires the least knowledge in order to use it. Template Method has always felt like white box re-use. Another problem I have is that it requires me to inherit in order to plug in my functionality. Well, I think I have an alternative.

I independently discovered (along with thousands of others I’m sure) a way to do Template Method without inheritance. To be honest, I don’t really know if this pattern has another name. I suspect it does. And I certainly won’t make any claims as whether or not it is good OO. I do know that I find it very convenient to be able to override behavior without having to inherit from a base class.

Here’s the relevant part of a class that I am using to call WCF services (look at the ConfigureBinding property):

public class WcfProxy<TService, TBinding> : IDisposable
    where TService : class
    where TBinding : Binding, new()
{
    public Action<TBinding> ConfigureBinding { get; set; }

    public WcfProxy()
    {
        ConfigureBinding = (binding) => { };
    }

    private ChannelFactory<TService> CreateChannelFactory(string serviceUri)
    {
        // doing some stuff here

        // create and configure binding
        var binding = new TBinding();
        ConfigureBinding(binding);

        // creating and returning ChannelFactory here

    }

    // ... more stuff is down here
}

In this example, I want to use WSHttpBinding internally but I need a way to allow the caller to configure the binding. For instance, maybe the caller needs to set send and receive timeout’s or message size limits.

In order to accomplish this, I have defined a public Action delegate property called ConfigureBinding. In the constructor of the class I initialize it to an empty method. ConfigureBinding is called right after the binding is created by my class.

In this way, the caller can provide new behavior:

var proxy = new WcfProxy<IMyService, WSHttpBinding>(uri);

proxy.ConfigureBinding = (binding) =>
                                {
                                    binding.Security.Mode = SecurityMode.Transport;
                                    binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
                                    binding.SendTimeout = TimeSpan.FromMinutes(10);
                                };

// make call on the proxy here