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

Installing Java into an Azure Worker Role

1. Download Java.

2. Add a reference to the installation package (e.g. jre-6u26-windows-x64.exe) to your worker role. In the properties, set Copy to Output Directory = Copy always.

3. Create and add a Startup.bat to your worker role. Set Copy to Output Directory = Copy always. This batch file is one line long:

jre-6u26-windows-x64.exe /s /L %RoleRoot%/approot/java-install.log

This will silently install Java and create a log in your root directory (which has been E:\approot every time I have ever remoted in to any instance).

4. Add a startup task to ServiceDefinition.csdef that will run the batch file during deployment:

<WorkerRole name="WorkerRole1">

<Startup>
    <Task commandLine="Startup.bat" executionContext="elevated" taskType="background" />
</Startup>

</WorkerRole>

5. Before you publish, you need to make sure you have an x.509 certificate added to your worker role. Upload the certificate to your hosted service via the Azure Management Portal. Also, add the certificate to your configuration settings.

6. Now it’s time to publish. Make sure you select Configure Remote Desktop connections. You will want to log into your role remotely (at least once) to verify that Java was installed).

7. After the worker role has been deployed, you should be able to remote into the machine. Once you are in, navigate to E:\approot. The installation log should be there if you need to look at it. If you just need to verify that Java is installed, try D:\Program Files\Java.

Running NUnit in the Windows Azure Emulator

Download Test Project Here

If there is an easier way to do what I am about to describe, someone please me. I am guessing there is some clever way to use cspack and csrun to allow me to run NUnit in the Azure emulator, but for the life of me I can’t get it to work. Therefore, I am using this admittedly goofy approach.

Disclaimer: The approach is tailored to a web role. The sample code is really a proof of concept.

"I think I have NUnit running"

Basic Approach

My basic approach is to copy the output from my test project into a subdirectory beneath the bin folder of my main web role (bin/test). Instead of using a test runner – in my case TestDriven .NET – I run my web role. There is a page on my site that will run NUnit and output the test results to the browser. If I need to, I can put break points in my tests and the debugger will let me step into the code.

Initial Setup

1. In the bin directory of your web role, create a sub-directory called test. In my case this is /TestSiteWebRole/bin/test.

2. Add a post-build event to your test project (replacing TestSiteWebRole with your project):

copy “$(TargetDir)*.*” “$(SolutionDir)TestSiteWebRole\bin\test”

3. In your web role add references to nunit.core.dll and nunit.core.interfaces.dll.

Adding a Test Runner Page (or Running NUnit from Code)

4. Add a page to your web role. In the example code, this is NUnit.aspx. There are several horrors to behold here. One, my example code is using WebForms. Two, there are a bunch of hardcoded references in it. I’m leaving it up to you to take this code beyond a POC.

public partial class NUnit : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RunTests();

    }

    private void RunTests()
    {
        CoreExtensions.Host.InitializeService();

        string testPath = Server.MapPath("bin/test");
        string testAssemblyPath = Path.Combine(testPath, "TestSite.Tests.dll");
        var package = new TestPackage(testAssemblyPath);
        var builder = new TestSuiteBuilder();
        var suite = builder.Build(package);
        var result = suite.Run(new MyListener(Response), TestFilter.Empty);
    }

5. The NUnit page uses another class called MyListener. This is just a class that implements NUnit.Core.EventListener (which is an interface). My implementation is about as simple as you can get. I am sure you can do much better.

public class MyListener : EventListener
{
    private readonly HttpResponse _response;

    public MyListener(HttpResponse response)
    {
        _response = response;
    }

    public void RunStarted(string name, int testCount)
    {
        _response.Write(name);
    }

    public void RunFinished(TestResult result)
    {
    }

    public void RunFinished(Exception exception)
    {
    }

    public void TestStarted(TestName testName)
    {
        Print("<p/>");
        Print("{0}", testName.Name);
    }

    public void TestFinished(TestResult result)
    {
        if (result.ResultState == ResultState.Failure)
        {
            Print("FAILED");
            Print(result.StackTrace);
        }
        else if (result.ResultState == ResultState.Success)
        {
            Print("SUCCESS");
        }
        else
        {
            // do something phenomenal here
        }
        Print(result.Message);
    }

    public void SuiteStarted(TestName testName)
    {
    }

    public void SuiteFinished(TestResult result)
    {
    }

    public void UnhandledException(Exception exception)
    {
    }

    public void TestOutput(TestOutput testOutput)
    {
    }

    private void Print(string msg)
    {
        _response.Write(msg);
        _response.Write("<br />");
    }

    private void Print(string msg, params string[] args)
    {
        _response.Write(string.Format(msg, args));
        _response.Write("<br />");
    }
}

The test project contains one test:

[Test]
public void role_environment_is_available()
{
    Assert.IsTrue(RoleEnvironment.IsAvailable);
}

If everything is set up correctly. You should get the following output when you run the NUnit page:

role_environment_is_available
SUCCESS

Managing Azure Configuration Settings

I thought I would share a simple class that I am using to manage configuration settings in Azure. The class provides access to configuration settings much like the traditional ConfigurationManager class:

string connectionString = AzureSettings.GetValue(“DataConnectionString”);

However, this will return a different value depending upon where I am running (emulator vs. actual cloud).


I accomplish this with a little convention.

For emulator settings, I prefix the setting name with dev_. If I am running in the emulator and I ask for “DataConnectionString”, AzureSettings will look for “dev_DataConnectionString” instead. If it can’t find that setting it will try “DataConnectionString”. If it still can’t find it, it will try to pull it from appSettings in the web/app.config.

In order to determine whether or not I am running in the emulator I am resorting to a hack (gasp!). RoleEnvironment.DeploymentId will be something like “deployment(42)” in the emulator but in the cloud it’s a Guid. Yeah, it’s not official, but I can live with it. MS doesn’t provide a way to check for the existence of configuration settings so I already have to potentially swallow two exceptions just to get a setting. So, the whole thing is filthier than toilet seat anyway.

using System;
using System.Configuration;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace SoftwareCraftsman
{
    public static class AzureSettings
    {
        public static bool InEmulator { get; private set; }

        static AzureSettings()
        {
            if (RoleEnvironment.IsAvailable)
            {
                Guid deploymentId;
                InEmulator = !Guid.TryParse(RoleEnvironment.DeploymentId, out deploymentId);
            }

        }

        public static string GetValue(string key)
        {
            if (RoleEnvironment.IsAvailable)
            {
                if (InEmulator)
                {
                    try
                    {
                        return RoleEnvironment.GetConfigurationSettingValue("dev_" + key);
                    }
                    catch
                    {
                         /* swallow */
                    }

                }

                try
                {
                    return RoleEnvironment.GetConfigurationSettingValue(key);
                }
                catch
                {
                     /* swallow */
                }
            }

            return ConfigurationManager.AppSettings[key];
        }

    }
}

 

Domain Oriented NLayered .NET 4.0 Architecture Guide

MSDN Architecture Spain just released Domain Driven Design in .NET 4.0 guide. I haven’t had a chance to read it but it’s in my queue.

The old blog is dead. This is the new one.

using System;

namespace NewBlog
{
    class FirstPost
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello,World!");
        }
    }
}