C#

Design Patterns: Dependency Injection

Dependency injection is one of the most useful patterns I have learned since becoming a professional developer.  In my opinion it makes code easier to read and enforces me to make reusable code with the ability to unit test at very granular level.

“Dependency injection” sounds really complicated, but the idea behind dependency injection is simple.

For any objects a particular class is dependent on, rather than creating them explicitly in that class, the dependencies should be injected by becoming parameters of the constructor or properties which are assignable after the object is created.

This is a somewhat simple example, let’s say we have a class named FordTaurus.  In every FordTaurus there is an engine(unless it’s in a junk yard). Let’s say I have a specific model of car and decide that it should have a V6 block in it. So when in the Ctor, I naturally assign the V6Engine to the EngineBlock property.

public class FordTaurus {
	public Engine EngineBlock { get; private set; }

	public FordTaurus() {
		EngineBlock = new V6Engine();
	}
}

public class Engine { /* ... */ }		
public class V6Engine : Engine { /* ... */ }

While this does work, I’ve made my Taurus dependent on the Engine. Let’s say the V6Engine required a parameter, how would I pass that in to the V6Engine? I would have to pass it in to the FordTaurus class itself somehow.

Well using a dependency injection paradigm, I would change my code to be something like this.

public class FordTaurus {
	public Engine EngineBlock { get; private set; }

	public FordTaurus(Engine e) {
		EngineBlock = e;
	}
}

Now that the dependency has been moved to be passed into the constructor, I no longer need to worry about what parameters are required to build the engine. I also have made the class more flexible as I could create a new engine say an Inline4Engine class and pass it into my FordTaurus class to use.

As dependencies are moved to the constructor of code, this can also tend to clutter up the constructor. However, if a class depends on too many other classes, it’s likely violating the single-responsibility principle for SOLID code.

A step further would be to use an interface to abstract the engine. Then I could use techniques such as mocking to unit test the FordTaurus without having to test any functionality in the Engine or it’s sub-classes. I’ll post on that at some future time.

Another common technique used with dependency injection is to inject the dependencies with an IOC (inversion of control) container such as Castle Windsor or Unity. These containers allow the dependencies to be injected at run time based on a set of predefined rules. Using these two patterns in conjunction can be extremely powerful. However, I will examine IOC containers in another post as well.

Using Custom Commands with Windows Services and PowerShell

A feature I recently came across when reading through the MSDN documentation was the ability to implement “custom commands” for windows services.  After reading about it, I wish I would have known about it sooner.

A custom command is a way to essentially send a signal to a service that you want it to process a command.  The command can be any integer from 128 to 255, but has no parameters, and returns no value.

There are a few situations where I immediately thought this may be useful.

1. A service health check.  I’ve seen in several scenarios in the past where at definite intervals a windows service will do something to say it is still alive.  This could be used to immediately force the service to do a health check, log out to a file, etc.

2. A service wake up.  For some windows services, they will just poll some sort of queue to see if work is available.  If it is not they will sleep for a given amount of time.  While this works, if someone is trying to get something done, the service may not respond to the request for due to the wait time.  Implementing a command to wake up the service could have it check the queue for work to process immediately.

Implementing a custom command on a service is very simple.  In a service class that inherits from ServiceBase, simply override the OnCustomCommand method.

Here’s a very simple bit sample code I wrote to demonstrate this functionality.

public enum CustomCommands
{
    WakeUp = 128,
}

private void Log(string text)
{
    File.AppendAllLines("C:\\wakeupservice.log", new[] { string.Format("[{0:yyyy-MM-dd HH:mm:ss}] - {1}", DateTime.Now, text) });
}

protected override void OnCustomCommand(int command)
{
    switch ((CustomCommands)command)
    {
        case CustomCommands.WakeUp:
            Log("Wake up!");
            break;
    }
}

Now to actually execute the command.  This can be done through the ServiceController class, or if you prefer to do it through the command line, can be done through PowerShell as well.

(Get-Service "CustomCommandService").Start()
(Get-Service "CustomCommandService").ExecuteCommand(128)
(Get-Service "CustomCommandService").Stop()

My log file now shows the following:

[2013-07-19 23:34:31] - Started!
[2013-07-19 23:35:04] - Wake up!
[2013-07-19 23:35:12] - Stopped!

That’s all there is to this post.  I hope you find this useful!

A full solution is available on my BitBucket samples repository.

Debugging a Windows Services

Have you ever had this message when writing a windows service in Visual Studio?

Cannot start service from the command line or a debugger.  A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.

I was a bit surprised the first time I hit the debug button in Visual Studio and ended up having to manually attach to the service every time I wanted to debug it.  After doing this over and over again, I learned a nice little trick. I like to put inside a lot of windows services I write as it easily enables me to get past that pesky error and debug straight from the IDE.

// If the debugger is attached, the program runs inline rather
// than it being run as a service.
MyService serviceToRun = new MyService();

#if DEBUG
if (Debugger.IsAttached)
{
    serviceToRun.Start(args);

    while (Debugger.IsAttached)
    {
        Thread.Sleep(1000);
    }
}
else
#endif
{
    ServiceBase.Run(new[] { serviceToRun });
}

Essentially after the program executes, it checks if the debugger is attached.  If it is, rather than running as a service it calls directly into the service to execute and continually checks for the debugger to detach.  Once it has the program ends. The conditional compile directive ensures that this behavior will no longer be possible once a Release build is made.

The Start method is a public method that simply calls to the overriden OnStart method for the service.

You can see a full VS solution on my BitBucket repository.

Creating backlog items for your scrum project in TFS 2012

In my last post, I showed how to programmatically create areas for a scrum team project in TFS 2012. In this post, I’m going to show how to add product backlog items.

Once you understand how retrieve services from a TfsTeamProjectCollection object, interacting with TFS is just a matter of knowing which services to use.  For adding work items into TFS this can be accessed through the WorkItemStore service.  This service gives you access to any work items in a team project and the ability to manipulate them.

In order to create a work item, it’s required to know what type of item it is.  In the scrum process template, items in the backlog are work items of the “Product Backlog Item” type.  It’s possible to also iterate through the work item types to see what’s available in your process as well.  If you’re working with a  different process template, there could be any variety of work item types.  After retrieving the type, it’s possible to finally create the product backlog item.

Now, in this example, I did not go through the work of actually validating the work item.  However, there is a Validate method.  When using the Validate method, if there is any validation problem with the WorkItem, it will return an error for exactly which field in the work item failed to validate.  Of course, the Save method will throw an exception if the WorkItem is invalid as well.

Here’s a sample set of code to add items to the product backlog.

public static void AddProductBacklog(TfsTeamProjectCollection projectCollection, 
    string projectName, string title, 
    string description, string areaPath=null)
{
    if (projectCollection == null)
        throw new ArgumentNullException("projectCollection");

    if (projectName == null)
        throw new ArgumentNullException("projectName");

    if (title == null)
        throw new ArgumentNullException("title");

    if (description == null)
        throw new ArgumentNullException("description");

    var collectionStores = projectCollection.GetService<WorkItemStore>();
    var store = collectionStores.Projects[projectName];

    if (!store.WorkItemTypes.Contains("Product Backlog Item"))
        throw new InvalidOperationException("The project " 
            + projectName + " does not support product backlog items.");

    WorkItem item = new WorkItem(store.WorkItemTypes["Product Backlog Item"]);
    item.Title = title;
    item.Description = description;

    if (areaPath != null)
        item.AreaPath = areaPath;

    item.Save();
}

I hope this helps, and get’s you a step closer to being able to use the scrum template in TFS.

Creating areas for your scrum project in TFS 2012

Organizing and dividing work into logical areas in your project can be a great way to track and add traceability to a process where certain changes are made.  Adding these areas one at a time can be a time consuming process.  In this post, we’ll set up a small method to make it easier to create the areas in the project.

The first step is getting a connection open to the team project collection.  I talked about that in my previous post. Once the connection is open, we need to obtain a reference to the ICommonStructureService.  Obtaining references to particular services in TFS is done through the GetService method on the TfsTeamProjectCollection object.

So, we will do the following:

var css = projectCollection.GetService<ICommonStructureService>();

I only mention this separately because this can also be used to get various other services to perform operations against the project collection.  For example, version control and work item services can be obtained through the GetServices method.

Now that we have a reference to the css, we’ll use a couple of methods to look up if nodes are already created or if they need to be created.  Now some of this is tricky and involves going through some of the paths in the node to determine what the correct path formats are.  However, once the infrastructure is in place, that will be relatively simple.

The areas in a project are stored in a hierarchy structure in code with each node containing a reference to it’s parent and all it’s children.  So, in order to start building the areas, we need to find the root structure node for the areas. Once that’s found, we can begin adding areas.

The full set of code is here.

public static void AddArea(TfsTeamProjectCollection projectCollection, string projectName, params string[] areas) {

	if (projectCollection == null)
		throw new ArgumentNullException("projectCollection");

	if (projectName == null)
		throw new ArgumentNullException("projectName");

	// Get the structure service to define areas for the project. 
	var css = projectCollection.GetService<ICommonStructureService>(); 

	// Find the information for the project to add the area 
	var project = css.ListProjects().FirstOrDefault((proj) => proj.Name == projectName); 
	if (project == null) 
		throw new InvalidOperationException("Could not find project."); 

	// List all the structures available in the project. 
	var nodes = css.ListStructures(project.Uri); 
	var curNode = nodes.FirstOrDefault(node => node.StructureType == "ProjectModelHierarchy"); 
	if (curNode == null) 
		throw new InvalidOperationException("The project specified does not contain an Area structure."); 

	// Loop through the list of areas and create each one. 
	foreach (var area in areas) { 
		// After a null is included in the list, don't evaluate any more areas 
		// assume the list is completed. 
		if (string.IsNullOrWhiteSpace(area)) 
			break; 
		// Try find the node, if it doesn't exist, create it. 
		try { 
			curNode = css.GetNodeFromPath(curNode.Path + "\\" + area); 
		} 
		catch (CommonStructureSubsystemException csse) {
			// Not a very elegant way to deal with a node not existing, but the interface 
			// does not have a check for if something exists. 
			if (csse.Message.StartsWith("TF200014")) { 
				var curNodeUri = css.CreateNode(area, curNode.Uri); 
				curNode = css.GetNode(curNodeUri); 
				css.ClearProjectInfoCache(); 
			} else throw; 
		} 
	} 
}

The project can now be added in a simple line of code. This will create an area hello with a sub-area of world.

ScrumProjectBuilder.AddArea(projectCollectionHere, "example project", "hello", "world");

Enjoy!

Connect to Team Foundation Server 2012 via C#

Team foundation server is a great tool for managing projects.  However, sometimes working through the UI just isn’t efficient enough for large operations.  However, with new tooling comes the concern of how to port over all those work items from an older technology.  In the next few posts, I’ll be be showing some code to connect to TFS 2012, to add areas to the scrum template, and import information in the product backlog. It’s not complicated, but often time coming across the information in a single source is hard to do.

var projectCollection = new TfsTeamProjectCollection(
    new Uri("http://myserver:8080/tfs/DefaultCollection"), 
    new NetworkCredential("youruser", "yourpassword"));

projectCollection.Connect(ConnectOptions.IncludeServices);

At this point you’ll have a connection to TFS ready to go!  In the next posts, we’ll use the GetServices<> method on the projectCollection variable to retrieve specific services in order to make changes to the project collection.

C# Singleton Pattern

The singleton pattern is an effective way to limit the existence of a class to a single instance.  Example areas where this pattern are beneficial would be a global context for an application, global application settings, or a global logging solution.

1 public class Singleton { 2 3 // Constructor is made private in order to avoid 4 // other code from creating an instance of the 5 // class. 6 private Singleton() {} 7 8 // A private variable holds the single instance 9 // to the class. 10 private static Singleton m_instance; 11 public static Singleton Instance { 12 get { 13 // If the singleton private variable 14 // has not yet been initialized with 15 // an instance of the singleton class, 16 // the singleton should be created and 17 // returned. Otherwise, the previously 18 // created singleton should be returned. 19 if (m_instance == null) 20 m_instance = new Singleton(); 21 22 return m_instance; 23 } 24 } 25 }

A common misusage of this pattern would be a class filled with static methods and variables. While this is technically a singleton, if the object is required to keep state, it is best to be left as a non-static class with a single instance.  The primary advantage is is to allow for interfacing and potential future instancing if the class were to grow beyond it’s single instance.

Another common problem is instantiating the singleton class is by using a static constructor.  While this does effectively create a singleton, if the singleton where to throw an exception during creation, the static constructor would always throw the exception rendering any static variables or methods on the class useless.  So, care must be taken if a static constructor is to be used.