Wednesday, June 30, 2010

A “useful” help page for ModelStateDictionary.AddModelError()?

Just tried to use Microsoft’s online documentation for ModelStateDictionary.AddModelError(). The following picture is a screen shot as of 30 June 2010:


Yes, that’s all. This page could be generated by a piece of software (maybe it was?). There is no useful information in this beyond what I can derived from the method signature in the first place.

I wonder: What is the value of this page?

There was a time a few years ago when Microsoft MSDN documentation was orders of magnitudes better and even had some meaningful examples. Today, it appears that we are increasingly relying on the “community” to make up for the lack of sufficient document by the vendor. This is disappointing.

Disable Disk Defragmenter on Windows Vista

Ok, this is not a .NET topic at all. Still. This problem got increasingly annoying on my Vista laptop. Upon each reboot, and at least once a day even without reboot, disk defragmenter kicked in and analyzed the disk (“Analyzing disk”). Each time it would say this would take “a few minutes”. However, I always had more than enough time to go fetch a coffee.

Of course I found all the recommendations regarding switching off the schedule and also go to the scheduled tasks and disable the one or two defrag related tasks. I also found the hint that changing certain registry values would help. And still, upon each reboot and even without reboot at least once a day disk defragmenter couldn’t help itself to at least analyze the disks even if it wouldn’t do the defragmentation itself. If would do so even if it came to the conclusion about 15 minutes ago that the hard drives would need to be defragmented.

So, here is what I did to disable disk defragmenter from running:

  • I opened explorer and navigated to \windows\system32
  • I took ownership of “dfrgntfs.exe”
  • Then I added myself with full permissions to the file
  • Finally I renamed the file to “dfrgntfs.exe_”

And now it has finally stopped re-analyzing the disks. I understand that it is useful to do that occasionally. But every 15 minutes? How much data can I possible write to the hard disk that this interval is justified?

And if I ever feel like defragmenting my hard disk(s) I just rename it back to its original name and run it manually.

Saturday, June 26, 2010

Formatting Source Code for (and other blog sites)

When you search the net for a solution to formatting source code for your blog there won’t be a shortage of hits. I’ve tried quite a large number of them only to be disappointed.

The best option I’ve found so far is this syntax highlighting tutorial. It uses a hosted version of Alex Gorbatchev’s SyntaxHighlighter, which has gained a lot of popularity (e.g. ASP.NET forums).

Here is an example for how your source code looks like once you’ve set everything up:

using System.Net.Mail;

public class EmailHelper {
   private static void SendEmail(string from, string to, string subject, string body) {
      var message = new MailMessage(from, to, subject, body);
      using (var smtpClient = new SmtpClient()) {

And your XML code would look as follows (note the error in the multi-line comment, at time of publishing this post):

      <!-- Setting for release (need to update account settings): -->
      <!--<smtp deliveryMethod="Network">
         <network host="" port="25" />
      <!-- Setting for development (uses -->
      <smtp deliveryMethod="SpecifiedPickupDirectory">
         <specifiedPickupDirectory pickupDirectoryLocation="C:\data\Temp" />

image After some more searching I then found PreCode, yet another plug-in for Windows Live Writer (WLW). PreCode also supports SyntaxHighlighter.

When you use PreCode, it will also take care of the angle brackets as they need to be substituted so they are not interpreted as HTML.

Finally I seem to have found a solution that allows me to work seamlessly.

Here are the bits for this solution:

  • SyntaxHighlighter: See Alex Gorbetchev’s web site for more details, and check the syntax highlighting tutorial for how to set up your blog / web site.
  • PreCode: Download Precode from codeplex and install. Restart WLW.

The only thing missing – but I can live with that for the moment: The code is displayed in Edit and Preview mode in WLW but not highlighted. PreCode’s web site explains why.

How To Test Sending an Email in .NET?

Sending an email can be tested in many different ways. One option could be setting up an account with an online email provider (Yahoo, Hotmail, Google etc.) and then use that account for sending email.

To save time, however, it might be valuable to look at "SMTP Server for Developers” (SSFD on Codeplex). This simple tool – developed by Antix – gives you a local SMTP server which looks like a standard server from your application’s perspective but on the back side simply writes all emails to a folder. The emails are stored in a text file with the extension EML and with a predefined format (headers + empty line + body).

By using SSFD the round trip will be faster and for retrieving the email you simply read a file.

To configure email in .NET (I am using version 4.0) add the following to your web.config/app.config file (the highlighted line is needed so SmtpClient.Dispose() doesn’t throw an exception, see comments at the end of this post):

      <!-- Setting for release (need to update account settings): -->
      <!--<smtp deliveryMethod="Network">
            <network host="..." port="25" userName="..." password="..." />
      <!--Setting for development (uses>
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <network host="localhost" />
        <specifiedPickupDirectory pickupDirectoryLocation="C:\data\Temp" />

Then in your code write the following:

using System;
using System.Net.Mail;
using System.Reflection;

namespace WebPortal.Controllers {
   internal class EmailHelper {
      public static void SendEmail(string from, string to, string subject, string body) {
         try {
            using(var smtpClient = new SmtpClient()) {
               smtpClient.Send(new MailMessage(from, to, subject, body));
            // SmtpClient.Dispose() may throw exception despite Microsoft's own guide.
            // See blog post for further details.
         catch (Exception ex) {

      private static readonly log4net.ILog Log =

Of course this is only the simplest version. If you need to send to multiple recipients or want to use a specific encoding or HTML instead of text format then this code would needs a bit more meat. Furthermore in a production system you may want to add error handling that allows some feedback to the user or the system administrator.

One observation I made while working on this: Microsoft recommends that “a Dispose method should be callable multiple times without throwing an exception”. Unfortunately SmptClient.Dispose() throws an exception when no host has been specified, thus contradicting their own recommendation.

SSFD doesn’t require the hostname for operation but when you implement your client side code you may want to use “using(var smtpClient = new SmtpClient()) {…}” to ensure that all resources used by your code (e.g. server connections) are properly cleaned up. Without a hostname in the web.config file (or specified through some other means, e.g. programmatically) SmtpClient.Dispose() will throw an exception. Therefore even though SSFD doesn’t need it, add “<network host="localhost" />“ as shown in the above web.config example.

One More: R# Memory Consumption in VS 2010

In my last two posts I wrote about memory consumption of the VS 2010/Resharper 5 combo. In one of the posts I demonstrated how an average of about 10 MBytes of memory are lost each time you close and re-open a solution.

For this post I ran a different experiment. This time I just used R# in VS 2010 for a lengthy period of time without closing/re-opening the solution. The result is plotted in the following graph:


The horizontal axis is the commit to the source code repository that I did. I measured the memory usage after each commit. The vertical axis shows the usage of managed memory in MBytes.

As by and large R# is the only addin/extension that uses managed memory it still looks as if R# is “absorbing” this memory. It doesn’t seem look like memory fragmentation but rather like a memory leak. I didn’t run the experiment without R#. It wouldn’t be comparable as I wouldn’t have refactoring available to this degree.

Overall it seems as if version 5 of Resharper still hasn’t resolved the memory problems. Having said that for most project/solution types it should be fine, though.

Saturday, June 19, 2010

Update: ReSharper 5.0 Memory Consumption in Visual Studio 2010

After some discussions with a friend (thank you, Steve!) I have conducted further tests. This time I ran my little experiment with just Visual Studio 2010 and no add-in, extension or whatever installed. Just as it comes out of the box. To measure the memory consumption I used VMMap from SysInternals (owned by Microsoft).

VMMap also displays metrics for the Managed Heap. That’s the place where the objects are stored that are created when you instantiate objects using “new” within your C# code (other languages may use other keywords). Again I used the same solution as in my previous post on the subject, and I followed the same actions: Close Solution, Open Solution, Record current memory consumption.

This time I did 30 runs. First I did this for just VS 2010 without any add-in, extension, etc. Then I repeated the test but this time I had ReSharper installed. The memory I recorded was the “Committed Memory” as per VMMap. The results of my measurements is shown in the following graph:


For this test I used ReSharper 5.0.1659.36. Visual Studio 2010 was the latest and greatest according to Windows Update. VMMap was version 2.62. Be aware that for this test no other add-in, extension, etc. was loaded at any time. The only difference between the runs was that for the second run R# was installed while it wasn’t for the first run.

On a side note: You may wonder why closing and opening matters. Well, my preferred source control plug-in is AnkhSVN. And most of the time is does a great job. Except when it comes to service references. We version these as well but AnkhSVN doesn’t seem to pick up changes in these files reliably. Therefore when we need to update service references – which can happen a lot when we are implementing a new service library – then we use a different tool to commit the change set. Typically we use TortoiseSVN for that. And to make sure that all changes, including solution and project files, are properly saved and picked up, we close the solution file. After the commit we then re-open the solution and continue coding.

Your style of working is most certainly different so this scenario may not apply. For example, on days that I can fully spend on coding I typically commit 10 or more times a day.

At the end of the second test run I then looked at the details for where the managed memory is consumed. It looks as if the memory that doesn’t get freed is listed under Garbage Collector (GC). It appears as if the GC cannot free up some big chunks of memory. This could be application domains that cannot be free because there is still a reference, or large caches or something like that. Here is the screenshot I took from VMMap at the end of the second test run:

2010-06-19_0037-ReSharper5-MemoryConsumption-VMMap What to make of all of this? If you have small solutions, plenty of memory (and there are tricks to tell Visual Studio to use more than 2 GB), don’t need/want to close the solution as often as I do, I’m sure that you will be unaffected by this. I haven’t checked yet how the memory consumption evolves over time under normal workload. I’ll monitor this as well and see whether there is more to discover.

Thursday, June 17, 2010

Visual Studio 2010, ReSharper 5 and Memory Consumption

The final word on memory consumption for R# is still not said. It looks as if the jury is till out. But judge for yourself.

I ran the following experiment: I created a solution in VS 2010 with 5 projects in total. Three of the projects are libraries and two of the projects are ASP.NET web applications, one to host services and the other to host the web user interface. All projects are C# and targeting .NET 4.

Then I open a new instance of Visual Studio 2010 and switched on ReSharper’s feature to display the consumption of managed memory in the status bar. The starting value was 19 MBytes after opening VS and no solution loaded. Solution-wide analysis is turned off. The entire system is a laptop with 4 GByte RAM and 32-bit Vista Ultimate. All software is maintained automatically to receive the latest updates and hotfixes.

Next I repeated the following steps 20 times:

  1. Open Solution
  2. Note managed memory usage
  3. Close Solution

Then I plotted the result in a graph. The x-axis is the number of the iteration while the y-axis is the memory consumption in MBytes as reported by the number in the status line, which is an option of ReSharper. I also put a linear trend line on top of the graph. You will note that except for the very first value we seem to have linear trend:


I’m not an expert but based on my experience this graph does not indicate that this is caused by memory fragmentation. If it was memory fragmentation I would expect the growth to decrease and eventually to flatten out. In this case we see a perfectly linear trend which makes me believe that someone is holding on to memory. And I know for sure it’s not me!

Each opening of a solution eats about 11 MBytes of memory. Closing the solution – I thought – should give free all memory that was used up because of the solution being open.

But maybe I’m completely off here and out of my depth. In that case I beg you: Please help me understand!

Tuesday, June 15, 2010

Visual Studio 2010 Professional Crashes

Feature-wise Microsoft’s new Visual Studio 2010 is definitely a big step forward. I spare you the details. In addition a large number of extensions are available for adding features (and featurettes) that you think you can’t live without.

There is a danger, however: I have downloaded a few of them and I’m now in the mode of disabling all them except the ones I really need, e.g. the Subversion source control addin.

Why? In the last few days I have experienced on average probably two crashes per day. In one case the only thing that helped was rebooting the computer (ok, maybe I shouldn’t use Vista …) So far – admittedly including a large number of extensions – Visual Studio 2010 is by far more shaky and crash-prone than Visual Studio 2008. I don’t know why but this is a slight disappointment.

I’ll update this post once I have disabled or even removed all the bells and whistles that I don’t need to survive as coder. Let’s hope disabling/removing those extensions will make a a difference.

Sunday, June 13, 2010

A Simple CAPTCHA Mechanism for ASP.NET MVC 2

Sometimes you may want to protect certain functionality from being used by automated tools. One way of preventing this from happening is using a CAPTCHA, which is basically an image that is intended to be impossible to read by software (e.g. OCR) but possible to read by humans. The Wikipedia article is a good starting point with regards to the limitations of a CAPTCHA and suggestions for how to address those limitations.

In this post I’d like to show to you how you could integrate a simple CAPTCHA mechanism for ASP.NET MVC 2 using C#. My objectives for this implementation were:

  1. Ideally all CAPTCHA related code is located in a single class.
  2. Using the CAPTCHA in a view should be a single tag.
  3. Avoid having to register HTTP handlers or any other modification of the web.config file

Having all of that in mind I experimented a while, tried out a number of suggestions that I found on the web and settled for now with the one I’ll describe in this post.

I’ll start with how the CAPTCHA can be used in a view (for MVC newbies: roughly speaking this is MVC-lingo for page or form). In essence the solution uses a controller class named CaptchaController implementing a method Show(). In your view you use it like this:

Next to it, you probably would want to display a text box for the user to enter their reading of the CAPTCHA value, so in the view the markup for that would look as follows:

This will create an image and next to it you would display a text box as follows:


Of course the value in the image would change.

Now that we can display the CAPTCHA and also have a text box for the user to enter the CAPTCHA value, the next challenge is to store the CAPTCHA value somewhere so that once the user has entered the value and it is coming back to the server, some server side code can validate the CAPTCHA value. The server side code for this looks like this:

This method returns a boolean that you can then use for further processing.

All the rest happens behind the scenes and is completely handled by the class CaptchaController. So what follows is a description of the implementation.

When the CaptchaController renders an image it also creates a cryptographic hash as a session variable. This hash is an MD5 value in my implementation and the calculation uses an additional value to add some ‘salt’ before calculating the MD5 hash. Since the client has no access to the server side code it won’t be able to calculate a matching pair of MD5 and CAPTCHA value. As ‘salt’ I use the assembly’s full name which changes with each compile as it includes the version number.

And here is the source code for CaptchaController:

As always: If you find any bugs in this source code please let me know. And if you can think of other improvements I’d be interested, too.

In closing I’d like to mention reCAPTCHA, for which an ASP.NET component is available as well. Google is the owner of reCAPTCHA and uses it to correct mistakes due to the limitations of OCR (Optical Character Recognition) in their book scanning activities. Depending on your requirements reCAPTCHA might be a good solution as well in particular if you are seeking better protection and/or want to support visually impaired users.

Maybe one day I’ll have the time to look for a single tag / single class integration of reCAPTCHA for ASP.NET MVC …