Archive
Getting Started with TopShelf
I am a huge fan and follower of open source project and there have been so many great open source projects which tend to solve our complex problem with such an ease. In fact I love the way open source is becoming main stream and even Microsoft has come to the party. However I have notice not every .net developer is across it at least in Canberra.
Today I am going to talk about an underrated open source project called TopShelf which in my opinion deserve a lot of more recognition in the community and decided to blog about it
So TopShelf is a windows service framework which allows to build windows services with out the pain of what .net/visual studio provides. The project is hosted at Github and can be found here.
In fact if you remember in April of this year I blogged “NServiceBus: The Magic of Generic Host” and showed you how NService Bus installs your handler as a windows service, but the real magic behing Generic host is TopShelf and Enterprise Service Bus like NServiceBus and Mass Transit both use TopShelf internally to install handlers as windows service.
Lets get stated and write some code to use TopShelf. Create a new console application and type the following NuGet Command.
NuGet will install ‘TopShelf 3.1.0′. Lets create an interface which will encapsulate the windows service start and stop method and TopShelf itself requires a start method and stop method
IService.cs
public interface IService { void Start(); void Stop(); }
For a real life example lets pretend we are writing an Email service which polls database every 10 seconds and based on some domain logic processes and sends the email. I am not going to go into the details of polling and threading etc and this is just a demo code for the Email Service.
EmailService.cs
public class EmailService : IService { public void Start() { Console.WriteLine("Starting Service ..."); } public void Stop() { Console.WriteLine("Stopping the service ..."); } }
Now in our main program we just have to wireup the TopShelf Host factory.
Program.cs
class Program { static void Main(string[] args) { HostFactory.Run(x => { x.Service<IService>(s => { s.ConstructUsing(name => new EmailService()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("Email Service to send emails and proudly hosted by TopShelf"); x.SetDisplayName("Email Service to send emails"); x.SetServiceName("EmailService"); }); } }
and that’s it there are no other moving parts or special type of projects or files to include. There are many other useful settings like under which account the windows service should run and on what other services it depends on etc can be easily configured using the fluent apis.The best thing about TopShelf is that as part of your development and debugging you can run it as a normal console application and when you are ready you can just install it as a windows service.
Lets look into installing it as windows service. Launch command prompt as Administrator

and type the following command :-

Topshelf will install the service and will output the following result and which means you have successfully installed your application as a windows service.

Now to verify it open up windows services snap in MMC and you will see your service installed properly with the service name and description. Remember that the display name and description can be anything you want however the windows service name cannot have any spaces as you can see in the above code.

Now you can go ahead and start the windows service. To uninstall it’s again the name of your executable with uninstall option.So for our demo app it will be
That’s it folks and have a happy coding new year !!!
Just Decompile
In this post I am going to talk about a free tool called JustDecompile by Telerik and I have been using it for sometime. I know a lot of people were upset when .NET Reflector tool was not free anymore and In my opinion it is a good and inexpensive replacement for .NET reflector.
The download link for JustDecompile is here.
Setup is a very easy 4 step process.

You can load different version of .Net framework as shown below.
It has a nice search functionality
One thing I use the most is language conversion between C# and VB.NET. I often have to work with legacy systems or other old projects where I have to either read VB.NET Code to understand the logic or write some code in VB.NET.And at times it is hard to switch gears between the two languages specially with each version of .NET adding complex language features like lambda expression etc.
I don’t know about you guys but this is how my brains works and I am not good at instantly switching between different languages and I find JustDecompile so productive as it allows you view the code in C#,VB.NET or IL Code.
That’s it folks and Happy De Compiling !!!
Debugger Canvas
I am really excited to post about this new tool called Debugger Canvas which adds an awesome visual experience to your debugging.
Here is a quick video demo and it is planned to be shipped around June.
For more information please visit the Microsoft Research website.
Automapper
Recently a friend of mine was talking to me about his interesting project and in the conversation I mentioned him to use Automapper. As he was not aware of it but when I started explaining him he really got intrigued by it. I provided him the link and thought about blogging about it.
As you have guess it, it’s mainly a very smart mapping tool and will do all your left right hand code mapping. Whether it’s a MVC project where you do a lot of mapping between View-Model to DTO’s or whether you are working in an integration, this is something you can’t miss. You can download the assembly from codeplex at
http://automapper.codeplex.com/releases/view/44802
Lets see some examples. Lets say i have two classes PersonDisplayVm & PersonDto and the dto instance is called item and the Vm instance is called model. So inorder to map the two objects so that we can copy value from dto to model we create a map between the classes and use the Map function to map it like this.
Mapper.Map(item, model);
and this is how my two classes look like
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public DateTime CreatedDateTime { get; set; }
}
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public DateTime CreatedDateTime { get; set; }
}
As you can see it already saved a lot of lines of code where we have to painstakingly assigning value of one attribute in the left hand side to the corresponding value in the right hand side.
Following TDD and our good habit of writing test lets write a quick test.
public class When_testing_person_mapping
{
public PersonDto GetPersonDto()
{
return new PersonDto
{
Id = 1,
FirstName = "Joe",
LastName = "Blogg",
Age = 45,
CreatedDateTime = DateTime.Now
};
}
[Test]
public void Should_be_able_to_map_dto_to_vm()
{
var dto = GetPersonDto();
var vm = new PersonDisplayVm();
Mapper.CreateMap<PersonDto, PersonDisplayVm>();
Mapper.Map(dto, vm);
Assert.IsTrue(dto.Id == vm.Id);
}
Now lets say if for some reason in my display view-model I have the created datetime as string if we try to do a automapping from view-model to dto then we get an exception like
Exception of type ‘AutoMapper.AutoMapperMappingException’ was thrown.
as the string datetime when intialize with DateTime.Now add AM PM string into the string field and automapper can’t map it directly.In order to fix this problem you have to create a custom type convertor like this
{
public DateTime Convert(ResolutionContext context)
{
return System.Convert.ToDateTime(context.SourceValue);
}
}
And add the custom type converter before our mapping happens like this
public void Should_be_able_to_map_dto_to_vm()
{
var dto = GetPersonDto();
var vm = new PersonDisplayVm();
Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
Mapper.CreateMap<PersonDto, PersonDisplayVm>();
Mapper.Map(dto, vm);
Assert.IsTrue(dto.Id == vm.Id);
}
And you will see our test this time passes with no exceptions.
Now lets say you have another system or some legacy code where the Person class returned has a PersonId field instead of Id and it would be real waste to write another class which looks like the legacy class and write the whole mapping yourself.
This is where some of extensibility point of this mapper comes into play so lets say your legacy class or any other class looks like this.
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public DateTime CreatedDateTime { get; set; }
}
to map the PersonId field to Id field in PersonDto class you can simple specify it like this.
public void Should_be_able_to_map_legacy_to_dto()
{
var dto = GetPersonDto();
var personLegacy = GetLegacyPerson();
Mapper.CreateMap<PersonLegacyDto, PersonDto>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.PersonId))
;
Mapper.Map(personLegacy, dto);
}
and you will see it does rest of the stuff, the .ForMember is an fluent interface so you can chain them for multiple property mapping.I use it quite often as it saves tones of writing left hand right hand code and saves a lot of time and energy. Hope you will find it handy to use and although I am using it in MVC project but can be used in any service/data layer project as well.
Code Contracts
I am always up for a new ideas and experimenting new stuff and one of the cool stuff I always read in “What’s new in .net 4.0” is the code contract. I mean it definitely sounds familiar as WCF have various forms of contracts, interfaces are contracts etc.
I started digging a bit into it and found out that it sits inside the “System.Diagnostics.Contract” assembly and that give me a clear direction where was this heading. For me I wanted to check out how much of code checking it can do before we execute the code.
But like most of the new and cool stuff they are not that easy for the first time and there are a lot of gotchas and hoops you have to go through before you can start using it.
So here is my set of steps to get started with it.
Step 1:
Download it from here. The first gotchas was here itself for “Static Checking” download the Premium Edition and for that you must have Visual Studio 2008 Team System, Visual Studio 2010 Premium Edition or Visual Studio 2010 Ultimate Edition.
Step 2
Start Visual Studio go to project properties and make sure you have the “Code Contracts” as the new tab in the properties.

Step 3
Lets gets started with writing some code
using System.Diagnostics.Contracts;
namespace CodeContract
{
public class ProductRepository
{
public void AddProduct(Int32 productId,string description)
{
if (productId <= 0)
{
throw new ArgumentException();
}
//… Rest of the implementation …
}
}
}
and write a simple test for the add method.
[TestMethod]
public void Test()
{
var dc = new ProductRepository();
dc.AddProduct(10, "Chai");
}
Now when we build the test and run it there are no surprises and the test passes with flying(green) colours.

Lets say instead of passing a positive values we pass a negative one and as expected the test failed and got our exception.

I am glad that we wrote the test and it was caught before the code went into the production but wish if there was some tool which could tell me about this exception even before I could execute the code. Sounds crazy isn’t it ? ( reminds me of Minority Report
where the perpetrators are caught before they have committed the crime ).
No the idea is not that crazy and lets see how we can use Code contract to anticipate these type of code pitfalls.
Go to the Static Checking section and check the following checkboxes
- Perform Static Contraqct Checking
- Check in Background
- Show squigglies
and in Runtime Checking check the “Perform Runtime Contract Checking”. now we will add a bit of magic into our “Add Product” method ..
using System.Diagnostics.Contracts;
namespace CodeContract
{
public class ProductRepository
{
public void AddProduct(Int32 productId,string description)
{
if (productId <= 0)
{
throw new ArgumentException();
//return;
}
Contract.EndContractBlock();
//… Rest of the implementation …
}
}
}
All we have done is just added one method “EndContractBlock()” of the Contract class right after out exception and lets built the test project.

And this is pure magic. The Code contract reports a warning since we are violating the value of the passed parameter with a blue squiggly as we turned that option on.
As you can this is just a tip of the iceberg and imagine what you can achieve when you started define these contracts using annotation and decorating your classes with it, this will definitely make your API/library and your testing more robust.
The other area where I see a lot of use could be of a legacy .NET app which doesn’t have good unit test or any test at all, you can assert these contract block to identify various defects in the legacy .NET app.
LinqPad
I know you guys have already heard a lot about LinqPad and how great it is. If not here is a blog about LinqPad and it’s a great tool for learning LINQ.
But one of the cool things about LinqPad is that it is a great code snippet IDE too , with LinqPad you will never ever have a need to write a Console Application for a quick prototype.
Today I am going to show how to use external assembly or custom assemblies to use in this code snippet IDE. For illustration sake I’m going to use the JavascriptSerializer class to see whether my dotnet class will get serialize or not as a JSON Object and if it serializes then how would my JSON object will look like
So let’s assume you have downloaded and install LinqPad successfully. In order to add an external assembly click Query > Query Properties > Additional References.

Click on “Add” to add a new assembly.

You can type in the assembly you want to add and Autocompletion will take care of it.

Import any additional namespace you might have with in the selected assembly. Like in my case I am importing the System.Web.Script.Serialization namespace.

Lets write some code…

This is one gotchas I want to highlight when you first start using LinqPad. When you hit the run button you see it says “Error compling query” and it took me a while to figure it out. It’s complaining becasue in LinqPad by default it assumes you are trying to execute some expression so lets change it to “C# program”.

Now when we run the program it shows the desired result.

JQuery Snippets
If you are web developer or thinking into moving to the lighter side (with a pun
) then you simply can’t ignore JQuery and in my personal opinion invest some time and energy into it and it will pay you off in the long run.
A couple of weeks ago I blogged about the free JQuery ebook and I also blogged about how to roll out your own code snippet using the code snippet designer.
This post is about the jQuery snippets which I think is a great way of learning jQuery syntax. You can download it from here. Once it’s downloaded unzip the file, run the msi and complete the installation.
Before we start using the snippets lets browse to the “Documents\Visual Studio 2010\Code Snippets\Visual Web Developer” folder and as you can see there are two folders “My HTML Snippet” and “My JScript Snippets”.
Under “HTML Snippets” folder

Under JScript Snippets” folder

If you open one of these snippet files you can see it is quite similar to what we did using the snippet designer and shows the full potential of using snippets in your own development environment.
Lets start using the snippets and get some jquery code in our page. Below is a simple html page and when we type the keyword “jq”

and when we hit tab twice the snippet generates the base jquery code, it’s that simple.

Now it’s not too scary to get use to of jQuery syntax .
The Art of Mocking – Part 3
Before completing the trilogy let’s have a quick recap on what we have done so far.
The Art of Mocking – Part 1
The Art of Mocking – Part 2
One of the biggest gotchas for mocking framework is that you can’t mock a sealed class and can only mock either an interface or an abstract class. If you every try doing it to a sealed class you get this exception.
Type to mock must be an interface or an abstract or non-sealed class.
We learned in the previous posts how we can design our classes using SOLID and TDD principle so that you can use mocking framework to test it in isolation, but how about a piece of code which has a dependency on an existing .NET framework class which is sealed or doesn’t provide an interface or an abstract. How would you approach mocking with that.
For example we had a lot of problems when we were using LinqToSql as it’s DataContext class does not provides and interface and the System.Data.Linq.Table class is a sealed class and the work arounds were not that great.

It’s an interesting problem and this is where an interesting framework comes into picture and it’s called Moles Framework. Moles is part of the Microsoft pex and moles research project, it can be downloaded from visual studio gallery but for PEX you need a MSDN subscription.
I haven’t played with it yet but through the documentation I could see what its potential is, and if I come across something which I can’t mockup I will use it rather extracting interfaces and working on workarounds.
Group Items Plugin
A friend of mine showed me this plug-in for Visual Studio 2010 which is great for grouping items.

and you can read all about it at Mokosh Blog post.I really like to group various interfaces and its implementing classes together as shown above.
