Using var for implicitly typed variables in C#

I wanted to spend some time talking about the “var” keyword in C# because I’ve heard a number of misconceptions about it since it’s been introduced.

The var keyword is really just syntactic sugar that allows C# to resolve the type of a variable at compile time.  For example, the code

int i = 0;

is equivalent to

var i = 0;

The type of variable “i” has simply been inferred from it’s assignment.  The right side of the assignment is an integer, so the compiler treats i as an int throughout the rest of the scope of the variable.

var really shines when using anonymous types.  For example, I could write code like this.

var person = new { FirstName = "William", LastName = "Riker" };
var numbers = Enumerable.Range(0, 100).Select((i) => new { Number = i, Square = i*i });

Using var with anonymous types allows us to assign them to a variable without explicitly defining a type for the variable.  There still is a type for the variable, but it is a class that is implemented by the compiler.

One misconception is that the var keyword itself is a “type”.  Another is that it causes the compiler to not need to know the type of the variable.  Both of these are untrue, and using var like this does not remove statically typed nature of the language.  This is why whenever you use a “var” statement, you must include an assignment.

For example, doing this wouldn’t work as the compiler would throw an error because it doesn’t know what type “j” is supposed to be.

var j;

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.

Running multiple windows services in a single process

Sometimes in a large business application, it’s convenient to have more than one windows service available to allow for certain pieces of the application to be managed separately.  This is possible to create in two ways.  The first is rather straight forward.  For every service to create, create a different windows service executable.

The second is still straight forward, but less common, and another useful tidbit I found while reading the MSDN documentation.  This is to make a single service executable which contains many services.  The advantage to this is that the application shares a same executable process.  This can reduce memory usage especially if the program does things such as cache data into memory.  Or, if certain services are dependent on others running, they can inspect whether the other is running using shared memory such as static variables.  I’m going to show you how to set this up.

When setting up the services, simply create a second service.  To wire it up, where your program runs, add both services to an array that gets passed to ServiceBase.Run().

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] 
    new MultiServiceI(), 
    new MultiServiceII()

It’s as simple as that!  Create an extra service installer for your new service and you’ll be able to run them both.  When you start both the services, notice the PID in the task manager, you’ll notice it’s the same.


To demonstrate that the services are actually sharing memory, in my “OnStart” method, I logged the service that is starting and the last service that started.  The strings have been change for the respective services.

Program.Log("Started MultiService I, Last Service Started = " + Program.LastService);
Program.LastService = "MultiService I";

The implementation of these two are quite simple in the Program class.

public static string LastService = "";
public static void Log(string logText)
    File.AppendAllLines("C:\\multiservice.log", new[] { logText });

So, after running the first service followed by the second service, I get this in my log file

Started MultiService I, Last Service Started = 
Started MultiService II, Last Service Started = MultiService I

As you can see, when I start the second service the name of the first service is output as the last service that was run.

I hope you find this useful.  You can find a full solution on my samples repository https://bitbucket.org/hondomon/samples/src/master/dotNET/WindowServices/MultiService

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!");

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 (Debugger.IsAttached)

    while (Debugger.IsAttached)
    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 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)) 
		// 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); 
			} 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");