Did you wish the BackgroundWorker had a generic method?

We all love Generics. I love a little too much. It just makes me feel clean and tidy whenever I use it in my code. Awesome. Ok, enough of my incest for Generics.

It is quite common thing in a Windows desktop client application to have a user interface, which in response to some user actions performs certain tasks in the background. You certain would not want to make things like database/webservice calls on the UI thread. This could end up in showing the nice “Not Responding” message in your application title bar. If it is Vista you are running, it might be the Blue Screen of death who knows. In a normal Windows Forms application you would spawn a background thread and perform the tasks there. In a WPF application, well you could do the same but there is a BackgroundWorker available that does it for you. A straightforward usage of this class can be as below,

var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += BackgroundWorkerDoWork;
backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;
backgroundWorker.RunWorkerAsync();


The problem is, say you have 10 buttons on your UI and you want to make 10 different webservice calls one for each button click event. You would end up with 10 different BackgroundWorker objects each with their handlers scattered in some class. I think it can be made a little tidier, you would require 10 different BackgroundWorker objects for sure, but a Generic wrapper around this could make life a little easier. We can do this by using a generic class and a generic delegate in it. Enough words, lets see some code,



internal class ServiceHelper<T>
where T: class
{
private readonly BackgroundWorker backgroundWorker;
internal delegate void Completed(T result);
internal event Completed CompletedHandler;

internal ServiceHelper()
{
backgroundWorker = new BackgroundWorker();
}

internal void InvokeMethod(Func<T> method)
{
backgroundWorker.DoWork += BackgroundWorkerDoWork;
backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;
backgroundWorker.RunWorkerAsync();
}

private void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e == null)
return;
var result = e.Result as T;
if (result == null)
throw new InvalidCastException("The result obtained is not of the requested type.");
if (CompletedHandler != null)
CompletedHandler(result);
}

private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
if (e == null)
return;
var method = e.Argument as Func<T>;
if (method == null)
return;
e.Result = method();
}
}


All we have done is wrapped the BackgroundWorker inside a generic class and provided a generic event handler for clients to subscribe to.



Happy Programming!


Custom email with Hudson continuous integration

If you are using continuous integration for your project, you are cool. If you are using Hudson, you are uber cool. Anyways, regardless of the continuous integration (CI) tool you are using, sending emails via it is very useful. Hudson, certainly has a default Email Notification system. I was excited to see this feature, but once I saw the default email content, I was like, mmhhe!, this needs some revamp. There is a plugin available for custom email notification, http://wiki.hudson-ci.org/display/HUDSON/Email-ext+plugin. This plugin allows us to send HTML content in the email. Now we are talking. You would find tons of links in the cloud on how to setup this plugin to get things started. But, in my experience, the requirements for the contents of the email, its format etc. varies from team to team. Just to put be a little helpful here, below is the HTML content of the email I am using for a test project of mine,

<div class="panelMacro">
<table>
<tbody>
<tr>
<td class="noteMacro">
Hudson project, <a
href="${PROJECT_URL}">${PROJECT_NAME}</a>, is <b>${BUILD_STATUS}</b> for
build number <a href="${BUILD_URL}">${BUILD_NUMBER}</a>
</td>
</tr>
<tr>
<td class="infoMacro">
Build cause: ${CAUSE}
</td>
</tr>
<tr></tr>
<tr>
<td>
<div><b>Changes</b></div>
<br />
<div class="changesList">${CHANGES, showPaths=true, format="<div><b>[%a]</b> - %p</div><br />"}</div>
</td>
</tr>
<tr>
<td>
<div><b>Build Log</b></div>
<br />
<div style="font-size:13px;">${BUILD_LOG_REGEX, regex="Build FAILED*", linesAfter=100}</div>
</td>
</tr>
</tbody>
</table>
</div>


I have not included the stylesheet content used by this html. I have included the following things in the email,




  • Project url, project name, build status and build url. These links obviously are not accessible if you are seeing this email outside your company network.

  • Build cause says whether the build was triggered due to an SCM change, started manually by a user etc.

  • Change list, displays a list of commits done since the last change. Each entry shows the user committing the change, and the name of the file checked in.

  • Build log, shows the end of the log in case of a failure. This helps in knowing what were the build errors which caused the build failure. It is kind of important if you are not able to see the Console output as you are outside the company network and not able to access Hudson url. The way this works is, by doing a regex match on the “Build Failed” text in the Console output.


This is just a sample of how you could make your email notification really useful even when you or your team is not able to access Hudson dashboard.


Hmm..what pattern will you use here?

Design patterns are cool. Umm… what does that mean. At the vending machine in office, developers love to get into discussions about how they used State pattern and rescued the project. Young grasshoppers like me love to read some book or blog and think how could I make use of this newly learnt “thing” in my project. Recently our company hired a “super software guy”. He was something like 35-40 years experienced in the industry, carrying with him a whole bunch of presentation slides and a huge set of his own rules. Basically he was one of those Architecture Astronauts. I highly recommend reading Joel’s take on such people especially for young grasshoppers like me who are at a stage where Lead position is soon to come. I had asked a quite honest (I think) question to the lecturer about the way I think about design patterns in a project. I said, when I look at a problem in my project, a coding problem, I think, what pattern can help me here. Then I go home and open my “Head First Design Patterns” copy and see if something strikes me. Am I doing the right thing? He said Yes. He added that is really how one should code in a project.

I have utmost respect for the lecturer and for his immense experience in the field, but after spending some time reading blogs, books by some industry experts, I think the lecturer completely missed the point. Design patterns are recurring solution to a recurring problem, they are industry wide accepted norms. But they do make things complicated. In several simple scenarios, implementing patterns mostly leads to more code which causes unnecessary maintenance problems. The idea should be to solve the problem in the simplest possible manner, which keeps the code clean, taking care of common OOPS principles like cohesion and coupling. If proper thinking is done, you would end up with a solution probably close to some pattern that already exists. But there is absolutely no need to think of a pattern as soon as you see a problem.

If programming was as easy as finding a design pattern for a problem then I think I should quit my job and live in a van down by the river eating a steady diet of government cheese.

Happy Programming!


Microsoft is too fast for me?

Microsoft is quite famous (or infamous) in throwing lots of things at the customers to see what sticks on them. The speed at which they are releasing new versions of the programming languages, upgrades to Visual Studio, new features for the ASP.NET stack, is just amazing. On one side it is a good thing that they are keen in improving the product over and over again, by either upgrading it or completely replacing it with something new. But on the other side, it is almost impossible to keep track of all the new stuff Microsoft is doing.

I am a developer (for now), and I follow some awesome .NET guys on their blogs. Most of them keep on posting the steaming hot new stuff and are all excited about it. Some of these bloggers are full time bloggers and are really interested in doing this. Take C# language for example. I am not sure how many clients have moved to C# 4.0 in their production environment, at least the client I am working with, they are still using .NET 3.5 heavily. C# 4.0 comes along with loads of new features really worth learning. So I am all excited to get on it. I was not even half way and bloggers started talking about C# 5! Dude!

I understand technology evolves these days at real high speed and one really need not be at par with everything in the world. For someone like me following techy blogs every morning before starting to work, I think being very eclectic is is really important. If I do not read, or at least skim through all the posts I have in my Google reader I feel a little uneasy. But its time to use that “Mark all as Read” link sometimes.

Happy Reading!


Think of Production Support now, not later!

Developers just love to get into the code as soon as possible. Some might also like skip writing any specs, just start and finish the fuckin code and impress your manager, and get an appraisal. Wohoo. For what they might not realize that this is a proven recipe for disaster.
So you and your team are hired by a really big fat organization to build a software product. The client really wants this done in 5 months, or else he is screwed, and consequently you too. This is what generally happens,
- Numerous white board sessions understanding what is required and different approaches to implement it.
- All developers in your team including you are super excited to work on this from scratch. Your team creates a sleek POC which showcases how this would work. Everyone goes home happily and drink beer.
- Development work starts and the developers crazily slap the keyboard punching thousands of lines of code.
- The product is ready in 4 months, testers have no clue what the heck this is all about, but they are asked to test it.So they do!
- With a go ahead from testers, it finally reaches on the desk of Production Support. As a developer you are asked to explain in brief the overall architecture and usage of the product.
- And they say, What the fuck is this!!!!!!!!!%^%&^%&^.

You might say, Production Support guys are dumb, the developers could understand the system so well, why can't they? There lies the first mistake. You assumed all along that you or your kind, are the users of the product. As a matter of fact, when the shit hits the fan, the Production Support guys will be the real users of this product as they would have to solve issues in real time. So, how to avoid this fiasco? Well, the only time to resolve this would be the initial stages of design. Put yourselves into a Production Support role and try using the product.
- Try answering questions like, if someone calls about something not working in the product, how would you as a support guy, troubleshoot the
product.
- Can we remote into the users machine and overhaul the product.
- Can the product automatically send logs and crash dumps when something wrong happens.
- Can it make lunch. What?
- May be try involving a production support team lead or someone who accounts for their team and try to get their ideas too.

If you do not think of these things, your product will be usable only from a developer's perspective and not from someone who this product was really made for. So, please think about supporting the product while designing the architecture, or else down the line, it might be the developers who will be asked to support the product all along!

Happy Programming!