Redistributing user controls

Ever needed a recipe to build a user control library to use across several web applications? Here's one!
First of all, we should realise that this isn't something you can get out-of-the-box and as such, there are several half-solutions out there, and as far as I know there isn't a perfect one. The one I'm presenting here suits best for what I'm trying to achieve, and it doesn't mean it is the best for other people's situation.

My main motivation, other than user control reusability was to create a project structure that allowed me to migrate a webapplication developed in VB.NET to C#. This has to be done over a long-period and I don't want to keep adding code in VB.NET any time a new feature is needed. Hence I decided to build user controls in C# that I could use in VB.NET pages, thus avoiding any code-behind code in VB.NET.

There is however a big problem with creating user controls outside web applications: We're not supposed to do it! When you build a page (aspx) or a user control (ascx) in a regular web application, the compiler creates an assembly where each of this files produces a class that inherits from our "code-behind" class. This class is where some of the magic happens. When we create a user control outside the web application where the user control is being used the afore-mentioned classes don't exist. So how do we cope with this? We'll create a base class for all our user controls and we inject some magic in it as well! This base class will be responsible for:
  - manually loading the ascx file and parse it to dynamically create the elements/controls present in the ascx.
  - "binding" these elements/controls to the members that represent them in the code-behind class (this members are usually present in the designer file)
Here's the code to such a base class:

And here's the rest of my recipe:

1- Create new asp.net web application project. This makes sure we can create new user controls directly through the "new item" dialog, which would not be possible if we were to create a regular class library project.
  1.1- Clear all the files that visual studio placed inside the new project (leave only the AssemblyInfo.cs)

2- Creating user controls in your new project
  2.1 - Add a new "Web User Control" item to your project
  2.2 - Design your control as you always do
  2.3 - Open the designer files and copy the declaration of controls you'll want to access later on to the code-behind class. (You can also keep the designer files as partial classes to your code-behind class, but there's not much point in it as visual studio won't be able to update it later on)
  2.4 - Delete the designer files (unless you've decided to keep it as a partial class)
  2.5 - The control header (in the ascx file) should be cleaned to keep only the Language attribute, thus leaving only the following header:

  2.6 - Change the ascx file build action from "Content" to "Embedded Resource"
  2.7 - Change the control base class from "UserControl" to our own "BaseUserControl"

3- Using the user controls in your web application
  3.1 - Reference the new project in our old web application
  3.2 - Change the web.config to avoid registering the control in every page you'll use it:

Alternatively you could register the control in in the pages you want to use it by adding the following line:

And we're done! Here's a list of the issues found with this solution (so far):
- Couldn't get the control skins to work with my user controls
- Local and Global Resources are currently in the web application (instead of being properly encapsulated in the user controls that uses them), as asp.net loads them from the page, not the user control. There are at least two workarounds for this. We could create a resource provider and resolve the resources manually or we could use resources like we do in a regular winforms application, instead of using the local/global resources asp.net approach.

That's all folks!


Testing emails with neptune

Most of us have already developed some feature that sends emails, and when we finish the development phase we need to test it, but how? Surely we can force the application to send a mail to ourselves, but sometimes we don’t even have an available smtp server to use, or it requires further development steps to enable it with some authentication mechanism.
An alternative is to use a lightweight local smtp server focused on this development needs. So today I’ll show you how to use Neptune (There is another product with similar features, which I’ve never used, so feel free to explore it as an alternative to Neptune. It’s called SMTP4Dev and you can find it at smtp4dev.codeplex.com).
The latest Neptune version (downloadable at http://donovanbrown.com/post/Neptune-with-POP3.aspx) even supplies a POP port so that you can easily check the emails you sent, instead of only acknowledging that an email was successfully sent.
Neptune runs in the windows tray. With a right click on it’s icon you access a context menu which allows you to stop the smtp server and access a window showing further details as the smtp/pop ports and the number of email messages processed.

As mentioned earlier, you can easily set up an email account on your outlook (or another email client) to use the pop server supplied by neptune to take a look at the emails sent from your application. Most of the account details (as the username, password and email address) are dummy and make no difference for the pop server. You just have to specify that the mail server is

If you’re interested in unit testing your emails, Neptune also supplies some extensibility mechanisms for that purpose.


Using Keyboard Hooks in .NET

Here's another code snippet. This one shows you how to use keyboard hooks in .NET.
I took hints from a few online articles about this subject and stumbled upon an issue that arises when you try to use hooks in .NET 4.0. Typically when you invoke the SetWindowsHookEx, you supply it with the instance of the current module. In most articles you'll find that this can be done with the following line:

However this does not work in .NET 4. For further information see this discussion and this one as well. As stated in the later, an alternative way of doing this so that it works in .NET 4 (as well as in the older framework versions) is:

Here's the code snippet for my HookManager class:

And an usage example:


Brand new Reflector alternatives

So, now that our loved free .NET Reflector is about to run out of juice, what alternatives do we have. I've said before that I'm willing to pay for it, but there are many of you out there who are just too much pissed off at Redgate to buy anything from them!
Whose about to step in and take away some of Redgate's future clients? Jetbrains! Yes, the same ones that develop another much loved tool: ReSharper. They're introducing decompiling capabilities in their tool and also promising to release the decompiler as a free standalone tool by the end of the year! Check it out here: http://blogs.jetbrains.com/dotnet/
That got me thinking if it's finally time to buy ReSharper! What about you?

Also, there's another free tool on the horizon: ILSpy

Edit (24/02/2011): It seems another alternative is about to rise on the horizon! If you look at the Telerik's JustCode pre-release blog post (where they provide a special preview of the release highlights for their Q1'2011 release) you can read the following paragraph:
The new decompiling functionality will enable you to recover lost source code and allow you to explore and analyze compiled .NET assemblies. We know a lot of you will welcome this addition as it comes in response to your feedback and recent developments in the industry.


Test INotifyPropertyChanged Pattern implementations

Today, I'll cover a well known topic: different implementations of the INotifyPropertyChanged interface (henceforth referred to as INPC). Its most common use is when you're implementing the MVVM pattern. This interface makes sure that your viewmodel properties update the binded interface components when you change the property value. So, with so many WPF and silverlight applications out there, it's a well known interface and you probably also know that it's regular implementation is somewhat boring and extensively verbose! That's why there are so many different alternatives out there. I decided to collect a few and test them for performance.
The main motivation was to validate the suspected performance penalty of implementations based on expression trees. So I'm pitting this kind of implementation against the most common and basic implementation, two AOP (see http://en.wikipedia.org/wiki/Aspect-oriented_programming) implementations (one using IL weaving and another using a dynamic proxy) and the usage of dependency properties. Dependency properties may seem a little out of place, but they are one of the common alternatives to using the INotifyPropertyChanged.

The main reasons to research for different INPC implementations (the aforementioned boringness and verbosity) should obviously be taken into account. Most developers don't like that they can't use the simpler syntax of automatic properties if the want to use INPC.
It's not my objective to discuss the advantages and disadvantages of each, as you can find easily find several articles that delve deep into that subject. However, there are a few points we should keep in mind when choosing the kind of implementation to use. 
A perfectly good example are the disadvantages of using dependency properties: the need of inheriting from DependencyObject and the fact that these properties can't be changed from non-UI dispatcher threads. These may be two show-stoppers depending on your situation. The first also applies to the usage of expression trees. If your viewmodels are depending on some kind of ViewModelBase class then, that's not much of a fuss, but if you wish to achieve some kind of Naked MVVM implementation (see http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx) than you can't rely on a base class. Anyway, if you can avoid it, there's no need to burn your base class (see http://www.artima.com/intv/dotnet.html). 

On the other hand, most AOP approaches only make sense if you're using an IOC container to resolve your viewmodels. This is due to the fact that you can't instantiate your viewmodel class directly, you'll need to call a method that creates a proxy (where the INPC is injected) for your viewmodel. One of the AOP approaches (the one using PostSharp) we're using here avoids this by injecting the INPC in your class in a post-build action through IL weaving (see http://www.sharpcrafters.com/aop.net/msil-injection).

The Test

The test is pretty simple. Each of the implementations resides in a separate class which has the integer property (conveniently named "Property") we'll be using in the test. This property will be assigned 200.000 times in a cycle and we'll be controlling the time it takes for this cycle to complete. We'll also make sure that the PropertyChanged event is handled by an event handler that does absolutely nothing (we just want to measure the event handler invocation time, not the time the event handler takes to execute, so we're making it as simple as possible).

Example source for a specific test:

I've shown the example of the PostSharp implementation because the AOP test implementations require you to add the event handler through reflection, as the event doesn't exist at compile time. That's the only difference from the non-AOP implementations. Notice that you won't need to do this in real-life applications because you won't be registering explicitly the PropertyChanged event, that's the job of the framework's binding mechanism.
Also note that in the Castle Dynamic Proxy implementation, the instantiation of the test class would be replaced by a call to create the proxy (which, as stated above, would not be visible if we were using an IOC container to resolve the class)

Test Results

Here's the code to the implementations used in the test, which by the way, I'm not claiming ownership for, I've just gathered and altered them slightly where needed.
Common INPC implementation (which I'm calling the "Plain old" way)

Expression Trees implementation

Dependency Properties implementation

PostSharp AOP implementation

Castle Dynamic Proxy AOP implementation

After this, I think it's safe to conclude that the Expression trees implementation implies a severe performance penalty and although it's far simpler than the "Plain old" way of doing it, it still loses in simplicity when compared to the AOP implementations. That said, I should say that I've always been a fan of PostSharp and I currently consider it to be the best way of implementing INPC, although it is a payed tool.


RIP .NET Reflector (as a free version)

If you still haven't heard about it, here's a bad news: Redgate is about to put an end on the .NET reflector's free version as soon as they release the new version (which will be .NET Reflector 7). This new version seems to be scheduled for late february/early march. Knowing that the free version will only work until May 30, you'll soon have to make a decision: either buy it or stop using it. Well, I guess you could maintain a virtual machine with a freezed date and no internet conectivity at all to avoid connections with redgate servers, but where's the praticality in that?

I've made my decision, it's an easy decision, 35$ is not that much for one of the most important tools I use on a daily basis! Otherwise, I would have to make ildasm my new best friend!
As a developer I understand the importance of getting payed for what you develop and that the comporate side demands return on investment upon the new features being developed. Don't get me wrong, I do like the idea of open source, I just don't think we can apply it everywhere. The fact that the .NET community isn't taking this decision very well isn't much of a surprise for me. We all had the expectation that we'ld never have to pay for it, you may even state that we Redgate led us to believe that, that's what's the fuss is all about!
At the end of the day, what really matters is that we're talking about a fanstastic product that deserves the investment. Also, Redgate states that "Version 7 will be sold as a perpetual license, with no time bomb or forced updates", so that's definitely worth the value. I may even consider buying the pro edition...

What worries me is knowing that there a few companies that will not buy it for their developers! Let's just hope my company buys the necessary licenses asap, so I'm not forced to use my personal license at work!


Stack Walking

Have you ever needed to determine who's calling your methods or merely needed to inspect the call stack?

There's a fairly simple way of doing it by using the StackTrace class. I'll show you an usage example.
First, let's start by creating a small class that creates a stack of 3 method calls just so that we have some to call stack to look into.
This should do it:

Now, let's call Method1 and hook up an event handler that will gather the stack trace and print some information about each stack frame.

You should pay special attention to the boolean parameter of the StackTrace constructor. It defines if file information should be gathered (the file, line and column of the method being called). As we'll see below, gathering this information incurs in a performance penalty! Also, these values will likely be absent from a release build, as it is built without debug symbols.

You may be wondering about the performance of such a feature. I've made some testing and got back the values below. Note that these tests are merely indicative. My laptop had dozens of applications running that could interfere with the processor availability. Anyway, each value from the results below is the best out of three attempts and the average values for a single execution are consistent. Also, for the testing purposes, the Console.WriteLine instructions were removed.
These tests were made using a Debug version of the application.
The graph above shows the time it takes to run several executions of the ShowStackTrace method. The same tests were made with and without gathering file information. As you can see, there is a substantial difference.
The graph below shows the average time of a single execution.
As you can see, a single run, without file information takes in average 0.05 milliseconds! On a debug build! That seems pretty darn fast. It might be interesting to point out that this is the same way that exceptions gather their stack trace.

I wonder how this times stack up against the times achieved in a stack walk using the dbghelp.dll library. Maybe on a future blog post...