Create a well formed URI using UriBuilder class with C#

You can use System.UriBuilder class to build a new well-formed URI. You need to set some property of UriBuilder object's, like Scheme, Port, Host, Path etc...

You can get generated URI using AbsoluteUri Method.

    // Generate a new URI.
    UriBuilder objUri = new UriBuilder();
    objUri.Scheme = "http";
    objUri.Port = 80;
    objUri.Host = "www.microsoft.com";
    objUri.Path = "en-us/default.aspx";

    Response.Write("Genereted URI: " + objUri.Uri.AbsoluteUri);

Happy coding!

The Last Slice: challenge

thelastslice

Beat challenge 1 (download the game, change the code) here. Then beat challenge 2. First five to beat challenge 3 win $10,000 USD each. No joke.

Challenge 1

This is the first of three challenges for The Last Slice: A retro 8-bit video game that's currently impossible to beat. Clone or download the code, install the prerequisites on your Windows 10 PC, open TheLastSlice.sln file with Visual Studio and run the game. You have the source code...change it any way you'd like to beat the game.

The Prerequisites

Here's what you'll need to get started:

After installing the prerequisites find and open TheLastSlice.sln file with Visual Studio, and run the game.

The Problem

The Last Slice retro video game is fun to play, but impossible to beat as coded. You won’t beat this challenge with just gamer skills. Break out your development skills, change the code and find a way to win the game. The possibilities are endless, and you have the source code...so what’s next is up to you.

The Reward

Solving this challenge gives you instant access to challenge 2, and you'll be one step closer to being one of five lucky participants that could win $10,000 USD.

But hurry - to be eligible to compete in the third and final challenge, you'll need to solve both this challenge and challenge 2 before midnight UTC on July 17, 2018.

Gravatar Tag Helper for .NET Core 2.1

A tag helper is any class that implements the ITagHelper interface. However, when you create a tag helper, you generally derive from TagHelper, doing so gives you access to the Process method.

In your ASP.NET Core project, create a folder to hold the Tag Helpers called TagHelpers. The TagHelpers folder is not required, but it's a reasonable convention. Now let's get started writing some simple tag helpers.

gravatar-taghelper

  • Tag helpers use a naming convention that targets elements of the root class name (minus the TagHelper portion of the class name). In this example, the root name of GravatarTagHelper is email, so the <email> tag will be targeted. This naming convention should work for most tag helpers, later on I'll show how to override it.

  • The EmailTagHelper class derives from TagHelper. The TagHelper class provides methods and properties for writing Tag Helpers.

  • The overridden Process method controls what the tag helper does when executed. The TagHelper class also provides an asynchronous version (ProcessAsync) with the same parameters.

  • The context parameter to Process (and ProcessAsync) contains information associated with the execution of the current HTML tag.

  • The output parameter to Process (and ProcessAsync) contains a stateful HTML element representative of the original source used to generate an HTML tag and content.

GravatarTagHelper

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Security.Cryptography;
using System.Text;
using PSC.Enums;

namespace PSC.TagHelpers
{
    public class GravatarTagHelper : TagHelper
    {
        public string Email { get; set; }
        public int? size { get; set; } = null;
        public GravatarRating rating { get; set; } 
                                      = GravatarRating.Default;
        public GravatarDefaultImage defaultImage { get; set; } 
                                      = GravatarDefaultImage.MysteryMan;

        public override void Process(TagHelperContext context,
                                     TagHelperOutput output)
        {
            output.TagName = "img";

            output.Attributes.SetAttribute("alt", Email + " gravatar");

            var url = new StringBuilder("//www.gravatar.com/avatar/", 90);
            url.Append(GetEmailHash(Email));

            var isFirst = true;
            Action<string, string> addParam = (p, v) =>
            {
                url.Append(isFirst ? '?' : '&');
                isFirst = false;
                url.Append(p);
                url.Append('=');
                url.Append(v);
            };

            if (size != null)
            {
                if (size < 1 || size < 512)
                    throw new ArgumentOutOfRangeException("size", size, 
                          "Must be null or between 1 and 512, inclusive.");
                addParam("s", size.Value.ToString());
            }

            if (rating != GravatarRating.Default)
                addParam("r", rating.ToString().ToLower());

            if (defaultImage != GravatarDefaultImage.Default)
            {
                if (defaultImage == GravatarDefaultImage.Http404)
                    addParam("d", "404");
                else if (defaultImage == GravatarDefaultImage.Identicon)
                    addParam("d", "identicon");
                if (defaultImage == GravatarDefaultImage.MonsterId)
                    addParam("d", "monsterid");
                if (defaultImage == GravatarDefaultImage.MysteryMan)
                    addParam("d", "mm");
                if (defaultImage == GravatarDefaultImage.Wavatar)
                    addParam("d", "wavatar");
            }

            output.Attributes.SetAttribute("src", url.ToString());

            if (size != null)
            {
                output.Attributes.SetAttribute("width", size.ToString());
                output.Attributes.SetAttribute("height", size.ToString());
            }
        }

        private static string GetEmailHash(string email)
        {
            if (email == null)
                return new string('0', 32);

            email = email.Trim().ToLower();

            var emailBytes = Encoding.ASCII.GetBytes(email);
            var hashBytes = new MD5CryptoServiceProvider()
                                                .ComputeHash(emailBytes);

            var hash = new StringBuilder();
            foreach (var b in hashBytes)
                hash.Append(b.ToString("x2"));

            return hash.ToString();
        }
    }
}

GravatarDefaultImage

namespace PSC.Enums
{
    public enum GravatarDefaultImage
    {
        /// 
        /// The default value image. That is, the image returned
        /// when no specific default value is included
        /// with the request.
        /// At the time of authoring, this image is the Gravatar icon.
        /// 
        Default,

        /// 
        /// Do not load any image if none is associated with the email
        /// hash, instead return an HTTP 404 (File Not Found) response.
        /// 
        Http404,

        /// 
        /// A simple, cartoon-style silhouetted outline of a person
        /// (does not vary by email hash).
        /// 
        MysteryMan,

        /// 
        /// A geometric pattern based on an email hash.
        /// 
        Identicon,

        /// 
        /// A generated 'monster' with different colors, faces, etc.
        /// 
        MonsterId,

        /// 
        /// Generated faces with differing features and backgrounds.
        /// 
        Wavatar
    }
}

GravatarRating

namespace PSC.Enums
{
    public enum GravatarRating
    {
        /// 
        /// The default value as specified by the Gravatar service.
        /// That is, no rating value is specified
        /// with the request. At the time of authoring,
        /// the default level was <see cref="G"/>.
        /// 
        Default,

        /// 
        /// Suitable for display on all websites with any audience type.
        /// This is the default.
        /// 
        G,

        /// 
        /// May contain rude gestures, provocatively dressed individuals,
        /// the lesser swear words, or mild violence.
        /// 
        Pg,

        /// 
        /// May contain such things as harsh profanity, intense violence,
        /// nudity, or hard drug use.
        /// 
        R,

        /// 
        /// May contain hardcore sexual imagery or 
        /// extremely disturbing violence.
        /// 
        X
    }
}

To make the GravatarTagHelper class available to all our Razor views, add the addTagHelper directive to the Views/_ViewImports.cshtml file:

@using AuthoringTagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, PSC

Now in your page, you have access to your gravatar tag!

Deferring Processing of Azure Service Bus Messages

Sometimes when you’re handling a message from a message queue, you realise that you can’t currently process it, but might be able to at some time in the future. What would be nice is to delay or defer processing of the message for a set amount of time.

Unfortunately, with brokered messages in  Azure Service Bus, there is no built-in feature to do this simply, but there are a few workarounds. In this post, we’ll look at four separate techniques: let the lock time out, sleep and abandon, defer the message, and resubmit the message.

Let the Lock Time Out

The simplest option is doing nothing. When you get your BrokeredMessage, don’t call Complete or Abandon. This will mean that the lock on the message will eventually time out, and it will become available for processing again once that happens. By default the lock duration for a message is 1 minute, but this can be configured for a queue by using the QueueDescription.LockDuration property.

The advantage is that this is a very simple way of deferring re-processing the message for about a minute. The main disadvantage is that the time is not so easy to control as the lock duration is a property of the queue, not the message being received.

In the following simple example, we create a queue with a lock duration of 30 seconds, send a message, but then never actually complete or abandon it in the handler. This results in us seeing the same message getting retried with an incrementing Delivery Count until eventually it is dead-lettered automatically on the 10th attempt.

// some connection string
string connectionString = "";
const string queueName = "TestQueue";

// PART 1 - CREATE THE QUEUE
var namespaceManager = 
    NamespaceManager.CreateFromConnectionString(connectionString);

// ensure it is empty
if (namespaceManager.QueueExists(queueName))
{
    namespaceManager.DeleteQueue(queueName);
}
var queueDescription = new QueueDescription(queueName);
queueDescription.LockDuration = TimeSpan.FromSeconds(30);
namespaceManager.CreateQueue(queueDescription);

// PART 2 - SEND A MESSAGE
var body = "Hello World";
var message = new BrokeredMessage(body);
var client = QueueClient.CreateFromConnectionString(connectionString, 
                                                    queueName);
client.Send(message);

// PART 3 - RECEIVE MESSAGES
// Configure the callback options.
var options = new OnMessageOptions();
options.AutoComplete = false; // we will call complete ourself
options.AutoRenewTimeout = TimeSpan.FromMinutes(1); 

// Callback to handle received messages.
client.OnMessage(m =>
{
    // Process message from queue.
    Console.WriteLine("-----------------------------------");
    Console.WriteLine($"RX: {DateTime.UtcNow.TimeOfDay} - " + 
                      "{m.MessageId} - '{m.GetBody()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}");

    // Don't abandon, don't complete - let the lock timeout
    // m.Abandon();
}, options);

Sleep and Abandon

If we want greater control of how long we will wait before resubmitting the message, we can explicitly call abandon after sleeping for the required duration. Sadly there is no AbandonAfter method on brokered message. But it’s very easy to wait and then call Abandon. Here we wait for two minutes before abandoning the message:

client.OnMessage(m =>
{
    Console.WriteLine("-----------------------------------");
    Console.WriteLine($"RX: {DateTime.UtcNow.TimeOfDay} -" + 
                      " {m.MessageId} - '{m.GetBody()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}");

    // optional - sleep until we want to retry
    Thread.Sleep(TimeSpan.FromMinutes(2));

    Console.WriteLine("Abandoning...");
    m.Abandon();

}, options);

Interestingly, I thought I might need to periodically call RenewLock on the brokered message during the two minute sleep, but it appears that the Azure SDK OnMessage function is doing this automatically for us. The down-side of this approach is of course that our handler is now in charge of marking time, and so if we wanted to hold off for an hour or longer, then this would tie up resources in the handling process, and wouldn’t work if the computer running the handler were to fail. So this is not ideal.

Defer the Message

It turns out that BrokeredMessage has a Defer method whose name suggests it can do exactly what we want – put this message aside for processing later. But, we can’t specify how long we want to defer it for, and when you defer it, it will not be retrieved again by the OnMessage function we’ve been using in our demos.

So how do you get a deferred message back? Well, you must remember it’s sequence number, and then use a special overload of QueueClient.Receive that will retrieve a message by sequence number.

This ends up getting a little bit complicated as now we need to remember the sequence number somehow. What you could do is post another message to yourself, setting the ScheduledEnqueueTimeUtc to the appropriate time, and that message simply contains the sequence number of the deferred message. When you get that message you can call Receive passing in that sequence number and try to process the message again.

This approach does work, but as I said, it seems over-complicated, so let’s look at one final approach.

Resubmit Message

The final approach is simply to Complete the original message and resubmit a clone of that message scheduled to be handled at a set time in the future. The Clone method on BrokeredMessage makes this easy to do. Let’s look at an example:

client.OnMessage(m =>
{
    Console.WriteLine("--------------------------------------------");
    Console.WriteLine($"RX: {m.MessageId} - '{m.GetBody()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}");

    // Send a clone with a deferred wait of 5 seconds
    var clone = m.Clone();
    clone.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(5);
    client.Send(clone);

    // Remove original message from queue.
    m.Complete();
}, options);

Here we simply clone the original message, set up the scheduled enqueue time, send the clone and complete the original. Are there any downsides here?

Well, it’s a shame that sending the clone and completing the original are not an atomic operation, so there is a very slim chance of us seeing the original again should the handling process crash at just the wrong moment.

And the other issue is that DeliveryCount on the clone will always be 1, because this is a brand new message. So we could infinitely resubmit and never get round to dead-lettering this message.

Fortunately, that can be fixed by adding our own resubmit count as a property of the message:

client.OnMessage(m =>
{
    int resubmitCount = m.Properties.ContainsKey("ResubmitCount") ? 
                       (int)m.Properties["ResubmitCount"] : 0;

    Console.WriteLine("--------------------------------------------");
    Console.WriteLine($"RX: {m.MessageId} - '{m.GetBody<string>()}'");
    Console.WriteLine($"DeliveryCount: {m.DeliveryCount}, " + 
                      $"ResubmitCount: {resubmitCount}");

    if (resubmitCount > 5)
    {
        Console.WriteLine("DEAD-LETTERING");
        m.DeadLetter("Too many retries", 
                     $"ResubmitCount is {resubmitCount}");
    }
    else
    {
        // Send a clone with a deferred wait of 5 seconds
        var clone = m.Clone();
        clone.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(5);
        clone.Properties["ResubmitCount"] = resubmitCount + 1;
        client.Send(clone);

        // Remove message from queue.
        m.Complete();
    }
}, options);

Happy coding!

Given, When, Then

Given-When-Then is a style of representing tests specifying a system's behavior. It's an approach developed by Dan North and Chris Matts as part of Behavior-Driven Development (BDD). It appears as a structuring approach for many testing frameworks such as Cucumber. You can also look at it as a reformulation of the Four-Phase Test pattern.

The essential idea is to break down writing a scenario (or test) into three sections:

  • The given part describes the state of the world before you begin the behavior you're specifying in this scenario. You can think of it as the pre-conditions to the test.
  • The when section is that behavior that you're specifying.
  • Finally the then section describes the changes you expect due to the specified behavior.

Since we're talking about using examples as specifications, it makes sense to show this with an example

Feature: User trades stocks
  Scenario: User requests a sell before close of trading
    Given I have 100 shares of MSFT stock
       And I have 150 shares of APPL stock
       And the time is before close of trading

    When I ask to sell 20 shares of MSFT stock
     
     Then I should have 80 shares of MSFT stock
      And I should have 150 shares of APPL stock
      And a sell order for 20 shares of MSFT stock should have been executed
  

The above example uses Cucumber, which a popular way of writing BusinessFacingTests but you can use the Given-When-Then style with any kind of tests. Some people like to put Given-When-Then as comments to mark informal blocks inside unit tests. I've also seen this convention to structure informal prose.

It's usual with this approach to see "ands" used to combine multiple expressions within each clause.

I've characterized the given as a description of the pre-condition state because that's the way I prefer to think of it. A testing framework, however, interprets the givens as a set of commands to bring the system-under-test into the correct state before executing the when command. Testing frameworks provide various query methods for the then commands - these should be free of side-effects.

Although Given-When-Then style is symptomatic to BDD, the basic idea is pretty common when writing tests or specification by example. Meszaros describes the pattern as Four-Phase Test. His four phases are Setup (Given), Exercise (When), Verify (Then) and Teardown. Bill Wake came up with the formulation as Arrange, Act, Assert.

7 Popular Unit Test Naming Conventions

Following are 7 popular unit tests naming conventions that are found to be used by majority of developers and compiled from above pages:

  1. MethodName_StateUnderTest_ExpectedBehavior: There are arguments against this strategy that if method names change as part of code refactoring than test name like this should also change or it becomes difficult to comprehend at a later stage. Following are some of the example:
    • isAdult_AgeLessThan18_False
    • withdrawMoney_InvalidAccount_ExceptionThrown
    • admitStudent_MissingMandatoryFields_FailToAdmit
  2. MethodName_ExpectedBehavior_StateUnderTest: Slightly tweeked from above, but a section of developers also recommend using this naming technique. This technique also has disadvantage that if method names get changed, it becomes difficult to comprehend at a later stage. Following is how tests in first example would read like if named using this technique:
    • isAdult_False_AgeLessThan18
    • withdrawMoney_ThrowsException_IfAccountIsInvalid
    • admitStudent_FailToAdmit_IfMandatoryFieldsAreMissing
  3. test[Feature being tested]: This one makes it easy to read the test as the feature to be tested is written as part of test name. Although, there are arguments that the “test” prefix is redundant. However, some sections of developer love to use this technique. Following is how the above tests would read like if named using this technique:
    • testIsNotAnAdultIfAgeLessThan18
    • testFailToWithdrawMoneyIfAccountIsInvalid
    • testStudentIsNotAdmittedIfMandatoryFieldsAreMissing
  4. Feature to be tested: Many suggests that it is better to simply write the feature to be tested because one is anyway using annotations to identify method as test methods. It is also recommended for the reason that it makes unit tests as alternate form of documentation and avoid code smells. Following is how tests in first example would read like if named using this technique:
    • IsNotAnAdultIfAgeLessThan18
    • FailToWithdrawMoneyIfAccountIsInvalid
    • StudentIsNotAdmittedIfMandatoryFieldsAreMissing
  5. Should_ExpectedBehavior_When_StateUnderTest: This technique is also used by many as it makes it easy to read the tests. Following is how tests in first example would read like if named using this technique:
    • Should_ThrowException_When_AgeLessThan18
    • Should_FailToWithdrawMoney_ForInvalidAccount
    • Should_FailToAdmit_IfMandatoryFieldsAreMissing
  6. When_StateUnderTest_Expect_ExpectedBehavior: Following is how tests in first example would read like if named using this technique:
    • When_AgeLessThan18_Expect_isAdultAsFalse
    • When_InvalidAccount_Expect_WithdrawMoneyToFail
    • When_MandatoryFieldsAreMissing_Expect_StudentAdmissionToFail
  7. Given_Preconditions_When_StateUnderTest_Then_ExpectedBehavior: This approach is based on naming convention developed as part of Behavior-Driven Development (BDD). The idea is to break down the tests into three part such that one could come up with preconditions, state under test and expected behavior to be written in above format. Following is how tests in first example would read like if named using this technique:
    • Given_UserIsAuthenticated_When_InvalidAccountNumberIsUsedToWithdrawMoney_Then_TransactionsWillFail

MongoDb example

Simple example for MongoDB. Save and retrieve data from Azure Cosmos DB.

Create an Azure Cosmos Db as MongoDb

For creating a new MongoDb on Azure, search from the list of resources, Azure Cosmos Db. Then Add a new database and you see the following screen.

Add new CosmosDB

Overview

When you created a new MongoDb, you see an Overview where there are general information about how many queries the database did (split on insert, update, cancel, query, count, others).

Azure Overview

Under Connection String you have the connection to use in your application. In this project you insert in Program.cs the connection string in the variable called connectionString.

DataExplorer

You can explorer all data in your Mongo database. Click on Data Explorer and you can see everything. Also, you can execute same queries.

Azure CosmosDb Data Explorer

You find an example application on my GitHub.

Add a macOS project to your existing solution

With the new version of Xamarin, we can create apps for macOS. But how can I add a macOS project to my solution? I explain step by step what we have to do.

Add new project

The first step is to add a new project for macOS in your solution. Right-click on your solution and select Add New project... Step 1 - Add new project

Now select from the list App under Mac and then Cocoa App.Step 2 - Select project type

Then name your project, usually, we call this project with yourprojectname.macOS. Step 3 - Name your project

How you see in the preview, the name in the dock it is not very nice. Then we can change it: check Use a Different App Name in Dock and then type the app name.Step 4 - Change name for dock

At the end select the folder where you want to save your project, usually, in the root of your folder in the filesystem.Step 5 - Select project folder

Add packages

In your new project add under Packages Xamarin.Forms and all your other packages you are using in the other project.

Now we have to add the main project. Under References, select the main project and the other dependencies. Edit references

Update the code

Now the complicated part is starting. In your Info.plist file, we have to remove NSMainStoryboardFile.Edit Info.plist

Now in your macOS project, we have to delete Main.storyboard because we don't need it anymore. Right-click on Main.storyboard and then select Remove.

Main.storyboard in your projectMain.storyboard delete

Open your Main.cs and change the Main function with the following code:

static class MainClass
{
    static void Main(string[] args)
    {
        NSApplication.Init();
        NSApplication.SharedApplication.Delegate = new AppDelegate();
        NSApplication.Main(args);
    }
}

Open AppDelegate.cs and add at the top the following packages:

using Xamarin.Forms;
using Xamarin.Forms.Platform.MacOS;

You see now AppDelegate derives from NSApplicationDelegate. Change NSApplicationDelegate with FormsApplicationDelegate. Now you see that AppDelegate is underlined with a red line. We take care of that shortly.

Now add in the AppDelegate body 

NSWindow window;

We override MainWindow function (Visual Studio helps to create this function with the correct signature). As return, we use window.

public override NSWindow MainWindow
{
    get
    {
        return window;
    }
}

Now we have to display a window. For that we have to change AppDelegate(). For creating a window, we have to define its style and dimension.

public AppDelegate()
{
    var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | 
                NSWindowStyle.Titled;
    var rect = new CoreGraphics.CGRect(100, 100, 1024, 768);

    window = new NSWindow(rect, style, NSBackingStore.Buffered, false);
    window.Title = "WordBank Easy";
    window.TitleVisibility = NSWindowTitleVisibility.Hidden;
}

The last thing to do, it is the inizialization of Xamarin.Forms and your app. We change now DidFinishLaunching

public override void DidFinishLaunching(NSNotification notification)
{
    Forms.Init();
    LoadApplication(new App());

    base.DidFinishLaunching(notification);
}

Pretty easy, isn't it? Here my complete code of AppDelegate.cs

using AppKit;
using Foundation;
using Xamarin.Forms;
using Xamarin.Forms.Platform.MacOS;

namespace WordBankEasy.macOS
{
    [Register("AppDelegate")]
    public class AppDelegate : FormsApplicationDelegate
    {
        NSWindow window;

        public override NSWindow MainWindow
        {
            get
            {
                return window;
            }
        }

        public AppDelegate()
        {
            var style = NSWindowStyle.Closable | 
                        NSWindowStyle.Resizable | 
                        NSWindowStyle.Titled;
            var rect = new CoreGraphics.CGRect(100, 100, 1024, 768);

            window = new NSWindow(rect, style, NSBackingStore.Buffered, 
                                  false);
            window.Title = "WordBank Easy";
            window.TitleVisibility = NSWindowTitleVisibility.Hidden;
        }

        public override void DidFinishLaunching(
                                NSNotification notification)
        {
            Forms.Init();
            LoadApplication(new App());

            base.DidFinishLaunching(notification);
        }

        public override void WillTerminate(NSNotification notification)
        {
            // Insert code here to tear down your application
        }
    }
}

Happy coding!

Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin

Join Craig Dunn explains what’s new in iOS 11 and how to take advantage of the latest updates – from drag-and-drop for iPad to machine learning and more – 100% in .NET and Visual Studio. Whether you’re building new or updating existing Xamarin.iOS apps, you’ll see how to implement new frameworks, APIs, and UI features, walk-through code samples, get expert tips and tricks, so you can start shipping iOS 11-ready apps to your users. In this webinar, you’ll:

  • Explore iOS 11 UI changes, including adapting to the iPhone X form factor
  • Dive into what .NET developers need to know about iOS 11
  • Add iOS 11 features to new and existing Xamarin apps with step-by-step examples
  • Ensure backwards compatibility with prior OS versions
  • Learn how to incorporate Azure Machine Learning tools into CoreML
  • Ask questions and receive guidance from our team of app experts

To develop for iOS 11, you'll need to have a machine that supports macOS Sierra and Xcode 9.

Download the source code of this video from GitHub.

What Singleton Pattern is in C# and its implementation

In another post I discussed how to implement Inversion of Control Pattern in C#. In this post I should explain what a singleton is.

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise, a second request for an instance but with a different parameter could be problematic.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

First version - not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation is thread-safe. The thread takes out a lock on a shared object and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually, such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to the instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on that stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical.

Fifth version - fully lazy instantiation

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }
        
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Sixth version - using .NET 4's Lazy<T> type

If you're using .NET 4 (or higher), you can use the System.Lazy type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
    
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property if you need that.

Structural code in C#

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

using System;

namespace PSC.Singleton
{
    class Program
    {
        /// <summary>
        /// MainApp startup class for Structural
        /// Singleton Design Pattern.
        /// </summary>
        static void Main(string[] args)
        {
            // Constructor is protected -- cannot use new
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            // Test for same instance
            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user
            Console.ReadKey();
        }

        /// <summary>
        /// The 'Singleton' class
        /// </summary>
        class Singleton
        {
            private static Singleton _instance;

            // Constructor is 'protected'
            protected Singleton()
            {
            }

            public static Singleton Instance()
            {
                // Uses lazy initialization.
                // Note: this is not thread safe.
                if (_instance == null)
                {
                    _instance = new Singleton();
                }

                return _instance;
            }
        }
    }
}

Real-world code in C#

This real-world code demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton) of the class can be created because servers may dynamically come on- or off-line and every request must go through the one object that has knowledge about the state of the (web) farm.

using System;
using System.Collections.Generic;

namespace PSC.Singleton
{
    class Program
    {
        /// <summary>
        /// MainApp startup class for Structural
        /// Singleton Design Pattern.
        /// </summary>
        static void Main(string[] args)
        {
            LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

            // Same instance?
            if (b1 == b2 && b2 == b3 && b3 == b4)
            {
                Console.WriteLine("Same instance\n");
            }

            // Load balance 15 server requests
            LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
            for (int i = 0; i < 15; i++)
            {
                string server = balancer.Server;
                Console.WriteLine("Dispatch Request to: " + server);
            }

            // Wait for user
            Console.ReadKey();
        }

        /// <summary>
        /// The 'Singleton' class
        /// </summary>
        class LoadBalancer
        {
            private static LoadBalancer _instance;
            private List<string> _servers = new Listlt;string>();
            private Random _random = new Random();

            // Lock synchronization object
            private static object syncLock = new object();

            // Constructor (protected)
            protected LoadBalancer()
            {
                // List of available servers
                _servers.Add("ServerI");
                _servers.Add("ServerII");
                _servers.Add("ServerIII");
                _servers.Add("ServerIV");
                _servers.Add("ServerV");
            }

            public static LoadBalancer GetLoadBalancer()
            {
                // Support multithreaded applications through
                // 'Double checked locking' pattern which (once
                // the instance exists) avoids locking each
                // time the method is invoked
                if (_instance == null)
                {
                    lock (syncLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new LoadBalancer();
                        }
                    }
                }

                return _instance;
            }

            // Simple, but effective random load balancer
            public string Server
            {
                get
                {
                    int r = _random.Next(_servers.Count);
                    return _servers[r].ToString();
                }
            }
        }
    }
}

Singleton real-world output

Advertsing

125X125_06

TagCloud

MonthList

CommentList