Enhanced Telerik’s WebForms (ASPX, ASCX) to Razor (CSHTML) Converter

I recently came across a command line tool, developed by Telerik, which allows you to convert Web Forms types MVC Views (ASPX, ASCX) to Razor CSHTML Views. You can find more information here. You may also download full source code from Git.

I did some small enhancements to this command line tool, and contributed to the project.

  1. Added GUI support.
  2. Select and convert multiple Views.
  3. Views filtering – You would only be able to select ASPX/ASCX Views.
  4. VS2010 integration – VS Extensions.

If you are interested trying it out, you can download the VS Extension from the VS Gallery.

For most developers converting web forms Views to Razor is a once off task. So if you don’t like to have it part of VS Extensions, click here to download as a standalone tool.

Unfortunately this tool doesn’t support VBHTML.  If you are interested to know more on VBHTML syntax, Jemison White has a nice blog post.

Here  is another post by Scott Hanselman on Mixing Razor Views and Web Forms.

Automating QUnit and JSTestDriver within VS2010

I briefly touched based on this during my presentation at Code Camp. There were number of developers who were interested in browser based Unit Testing. This blog post is to provide you with some information on how you would automate browser based Unit Testing with VS2010.

QUnit is a great JavaScript Unit Testing tool which allows you write powerful browser based Unit Tests. You can find more information on QUnit here.

As described in the JSTestDriver Getting Started, you can use the below command to run both Java server and the client using a single command.

java jar <path>/JsTestDriver.jar port 9876browser firefoxpath,chromepath –tests all

Next step is to automate the above command within VS2010. You can easily achieve this by using VS External Tools.

·         VS -> Tools -> External Tools ‘Add new’

·         Specify the Title E.g “Js Unit Tests Run”

·         Specify the Command – C:\Program Files\Java\jre6\bin\java.exe

(This is the path where your java runtime is located)

·         Specify the Arguments

-jar <path>/JsTestDriver.jar –port 9876 –browser  “C:\Program Files\Internet Explorer\iexplore.exe, C:\Program Files\Mozilla Firefox\firefox.exe” –tests all

·         Initial Directory is the path to the directory where the JSTestDriver is located.

·         Ensure you select the “Use Output Window” check box, so you can see the Unit Tests result in the output windows.

Once you run the VS external command, you should be able to see your output similar to below.


You can further automate this by running a VS macro, so every time when you save a JS file the above command will run all browser Unit Tests.


Code Camp OZ2010 – Real World Unit Testing & Future

I hope you all had a great time at Code Camp and a safe journey back home.

This blog post is to provide you with some additional references on the presentation Real World Unit Testing & Future. I have also included some answers to the questions which some of you have had after the presentation. At the end of this post, there is a link and you can download my presentation slides. 

Download TestLint http://site.typemock.com/test-lint/

Links to Roy Osherove’s Test Reviews.

Unity : http://weblogs.asp.net/rosherove/archive/2009/03/23/test-review-3-unity.aspx

ASP.NET MVC : http://weblogs.asp.net/rosherove/archive/2009/03/21/test-review-2-asp-net-mvc-unit-tests.aspx

Question on multiple Asserts in a Unit Test?

Post presentation questions interested me that some of you have different opinions on having multiple asserts within a Unit Test. The point I wanted to make was, as a general rule, it is best to have one assert per Unit Test.  Having said that, there may be instances where you would like to test logically related things within the same Unit Test.  Which means “Multiple aspects of the same object”. If one aspect fails then we would consider as the Unit Test is fail. 

        public void TraceOutput_SimpleStringWithCommaDelimitted_AnalyseTraceData()
            TraceAnaliser traceAnaliser = new TraceAnaliser();

            AppTraceOutput traceOutput = traceAnaliser.AnalyseTraceData("Europe, Africa, 10:00, Australia, Simon");

            //Different aspects of the same object being tested.
            Assert.AreEqual(traceOutput.ReadLine(1)[0], "Europe");
            Assert.AreEqual(traceOutput.ReadLine(1)[1], "Africa");
            Assert.AreEqual(traceOutput.ReadLine(1)[2], "10.00");
            Assert.IsTrue(traceOutput.LineCount == 1);

If you want to make the above test more maintainable you would also consider comparing the objects. For example…

Assert.AreEqual(traceOutput, expected);

Having multiple asserts in Unit Tests raise maintainability issues. If the first assert fails, then the subsequent asserts will never get executed.  We would never know those subsequent asserts were succeeded or not.  Since it is a partial picture, sometimes it is very hard to isolate the problem why the Unit Test is failing. If the tests are separated and solid they are easier to read and easier to maintain.

Also I came across with another tool (NUnit Addin for Running one assert per test ) which I did not include in my talk, but please feel free to have a look at this.


The difference between the Code Contracts and Unit Tests.

There was a question on Code Contracts and Pex. Code Contracts allows you to perform powerful assertions within your production code. It encapsulates the intention of your design using contracts, so the compiler tools using Static Analysis, Runtime Analysiscan be used to discover those intentions (E.g Pre Conditions and Post Conditions). Unit Test, verifies a piece of logic/behaviour within a method while allowing you to improve the design of the production code. One cannot replace each other as they both have different purposes.

Download Code Contracts and Pex

Code Contracts – http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx

Pex – http://research.microsoft.com/en-us/projects/pex/

Where can I get more information on Code Contracts and Pex?

Here is a video from PDC 2010 which explains some useful information using Pex and Code Contracts. http://channel9.msdn.com/Blogs/martinesmann/Code-Contracts-and-Pex-Power-Charge-Your-Assertions-and-Unit-Tests

Download Sinon, JSTestDriver and QUnit

a.      Sinon – http://cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks

b.      JSTestDriver – http://code.google.com/p/js-test-driver/

C.      QUnit – http://docs.jquery.com/Qunit 

d.   QUnit to JSTestDriver adaptor – http://code.google.com/p/js-test-driver/wiki/QUnitAdapter

(Note : I will soon write a separate blog post on how to automate this within VS 2010)

Powerpoint slides. Real world Unit Testing & Future.pptx (971.90 kb)

Code Camp 2010 – Real world unit testing from David Burela on Vimeo.

Attribute based Performance Counters with Enterprise Library 4.1

This post is based on my previous post on Getting started with Enterprise Library Performance Counters

Let’s assume you don’t want to use the config files to configure performance counters. You need to use the PerformanceCounterCallHandlers.

In order to achieve this, you need to follow the same steps – until step number 7, which I have stated in my previous post.

Step number 8 is different. Your config file will only contain the below.

    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <section name="instrumentationConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation.Configuration.InstrumentationConfigurationSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  <instrumentationConfiguration performanceCountersEnabled="true"
    eventLoggingEnabled="false" wmiEnabled="false" applicationInstanceName="" />

As you can see above, you can easily turn off the performance counters as a whole entity.

Now to add performance counters to a target method, you can simply use the PerformanceCounterCallHandler attribute as specified below.

[PerformanceCounterCallHandler("DemoCounters", "Operations Started/sec", IncrementCallsPerSecond = true)]
public void SampleMethod(int i)

ASP.NET MVC 3 Preview 1 Source code

Microsoft has uploaded the source code for MVC 3 Preview 1. You can download the source code from below

You can download the preview 1 from below link

There are some useful features (considered to be included in MVC 3) is now available in MVC Preview 1.
Some of the features in preview 3 features are below

  • New ActionResults
  • New Razor View Engine
  • HttpNotFoundResult, HttpRedirectResult with support for Permanent Redirects, and HttpStatusCodeResult.
  • Global Filters
  • Model Binding to JSON
  • Validation – .NET 4 introduced IValidatableObject and improvements on ValidationAttribute to provide even better validation and ASP.NET MVC 3 will offer better support for them.
  • Dependency Injection and Common Service Locator Enhancements

You can find more information

It is very early stage so there are no guarantees that all these features will be included in the final release.

MVC2 Validation step by step

Out of the box, MVC 2 framework supports both server side and client side validation. Server Side validation is based on System.ComponentModel.DataAnnotations, and Client Side validation is based on ASP.NET Ajax 4.0. Both Server and Client Side validation are loosely coupled, and they are joined using JSON.

You can also have multiple validator providers plugged in and run at the same time. You can remove the built-in validation providers and you can create your own once.

Prior to MVC 2, MVC 1 used third party frameworks and plug-ins such as xVal to enable both client side and server validation. MVC 2 allows you to enable both server side and client side validation without having to use any third party frameworks or plug-ins.

This article explains how to enable both server side and client side validation step by step.

Enabling server side validation.

Lets start with the View Model. Please refer to the DemoModel code sample below.

There is a DisplayName attribute for each property. This attribute produces the name, which you should display within the View. Form validation point of view, it doesn’t add any value at all. What is important here is the “Required” attribute and “StringLength” attribute. These attributes belong to theSystem.ComponentModel.DataAnnotations namespace.

There four built-in attributes that you can for validation. :Required,  StringLength,  Range and RegularExpression.  If any of above attributes doesn’t fit for your requirements, then you can easily create your own validation attribute if needed. For more info please refer to the article here.

  1. This is how the View looks like.

(Please not that greyed code samples are not relevant to MVC validation.)


You can see that I’m deriving from ValidationDemo.Models.DemoModel. So my View will be strongly typed and I can bind to the Model properties using m => m.ProductCode etc. The value that enter to the ProductCode text box is bound to the value of the Model using <%= Html.TextBoxFor(m => m.ProductCode) %>

The validation message is displayed using the html helper extension.

<%= Html.ValidationMessageFor(m => m.ProductCode) %>

f you remove this line, your validation will still work, however no messages will be displayed.

Importantly you must ensure that your form which require validation is placed in between <% using(Html.BeginForm()) {  } tags. (Please see above)

2. One last thing to remember is that you need an action method within your Controller to be able to execute your form POST. You must also pass the model to your action method, as a parameter.

public class ValidationController : Controller
public ActionResult Demo()
return View();

public ActionResult Demo(DemoModel model)
return View();

3. Now when you click on Submit button, server side validation will trigger and the error messages are displayed.



Using ValidationSummaryControl

If you need the validation summary control (most of you do), you have to add the following helper extension method to the View. You can add this helper method anywhere you like (within the View).

<%= Html.ValidationSummary(false, “Product creation was unsuccessful. Please correct the errors and try again.”) %>

The first argument (excludePropertyErrors: true/false) specifies whether you want display list of error underneath the ValidationSummaryControl.

Enabling client side validation.

MVC 2, uses Microsoft AJAX 4.0 as the default client side library. You can also use the JQuery version of the validation library. It is in MVC 2 Futures project. You can download it from MVC2 Future library.

1.       Ensure you reference three JS files within your application.

If you are using MS Ajax

<script src=”/Scripts/MicrosoftAjax.js” type=”text/javascript”></script>

<script src=”/Scripts/MicrosoftMvcAjax.js” type=”text/javascript”></script>

<script src=”/Scripts/MicrosoftMvcValidation.js” type=”text/javascript”></script>

 If you are using Jquery

<script src=”/Scripts/jquery-1.3.2.min.js” type=”text/javascript”></script>

<script src=”/Scripts/jquery.validate.min.js” type=”text/javascript”></script>

<script src=”/Scripts/MicrosoftMvcJQueryValidation.js” type=”text/javascript”></script>

2. Within your View, before the <% using (Html.BeginForm()) { %> statement, you need to add the code: <%Html.EnableClientValidation(); %>

3. That’s it. Now run the app. You can see the client side validation in action.


If it is still not working, ensure the browser does not disable your JavaScript by default. For example in FireFox you need to ensure both Java and Javascript is not disabled. To be honest I don’t know why Java needed to be disabled. Please let me know if anyone finds out.

Enabling Validation Summary Control for client side.

Out of the box Validation Summary Control does not work for client side validation. For example you cannot display validation summary error massagers, within the Validation Summary Control during client side user interactions. To enable this you can implement a solution, which is described in the post here.

Practical approach to Unit Testing

This article explains some key approaches that you would consider when writing Unit Tests. 

As developers most of us write Unit Tests and we all know what is a Unit Test. Some may have slightly different opinions, but it is actually a programmatic verification of a single method/unit to ensure it behaves as expected. The reason I explain this because some developers still refers to a Unit is a component, assembly, or a module. When to comes to the term Unit Testing, you really testing a sensible testable unit of your software, and anything bigger than that would considered to be more of a integration testing. 


Lets get real and discuss some of the benefits. I want to be more practical, and leave the MSDN Unit Testing benefits behind.

As a developer when you decide to write Unit Tests, do you ask the question from yourself, why I’m really writing these Unit Tests? Some of you answer Yes, and some of you say No.

Answer No, is simply because not knowing what you do, or because everyone else write Unit Tests. If your answer is Yes, that’s great, and you really consider the pros and cons of having Unit Tests.

All these benefits can be categorized into 3 main areas.

1.       Quality.

2.       Design.

3.       Cost benefits.


Lets talk about these areas briefly. 

The quality that provides by the Unit Tests can be many ways. It assists developing testable code. With TDD, the method/function that you write against a Unit Test, is well defined, and has a single responsibility. Unit Tests it self provide a valuable documentation to the project.  Less bugs will be introduced, also fixing bugs will be lot easier. As a developer you will have a great confidence on your system. 

If you practice TDD, you know Unit Test allows you to design a specific behaviour within your method. For example with TDD, you write your test first, make it fails, and then based on your test you write the method to ensure that your test passes. The result of this is basically designing a specific behaviour within your method. The other aspect of the Design is, when you design your system, you will also consider your functional requirements. Because one of the things that you need to ensure when you design your system is that your functional requirements have been met. Your Unit Tests are based on these functional requirements. I will discuss this in more detail in “Selective Unit Testing” section. 

We would love to develop a perfect system. But in reality, that is not always the case. Worse and the painful thing is some time projects are over the budget. This could be due to number of factors. One of the most common issues associated with the project cost is unexpected work at the end of the development cycle. This could be due to the number of bugs that have been raised during system testing. The number of iterations between the development and system testing cycles seems never ending due to the amount of bugs been raised. This can be due to poor system design, and or un-testable code. 

As you can see here, the number of defects you find is high during the development and the cost to fix those defects is relatively low when comparing to further stage of project life cycle. This is why the Unit Tests are important to ensure that we introduce fewer bugs during the development so the cost to fix those bugs are negligible at the later stage of the project cycle.

Selective Unit Testing

Writing “Unit Tests” is a good thing. Writing bad Unit Tests and/or unnecessary Unit Tests can lead to considerably high maintenance cost to your overall project. Do you believe on statements such as

We should aim for 100% code coverage”, “Any Unit Test is better than none”, or “Our main priority is the Unit Testing”?. All these statements do not add much value at all. These are some examples of expressing the way of the excitement, which causes by the Unit Testing

Few years ago we hired a developer to one of our projects. He is very keen on Unit Testing and he spent lot of time writing and managing Unit Tests. At the end our project was over the budget, and not what we really expected. If he decided what is really important, and write only the necessary Unit Tests, it would have reduced our cost. 

This is where it is really important that we need to ensure we write the absolutely necessary Unit Tests. This is also applicable if you practice TDD. You just don’t need to write Unit Tests for every method you write with in your application. Lets see some of these characteristics, and then how you decide what Unit Tests to write. 

If you are aiming to write Unit Tests for every method to make your manager happy with higher code coverage, then it is fantastic to write these types of tests. But did you know that most of your tests did not add much value to the quality of your system at all. You see your entire tests pass with green ticks. There are so many green ticks make you feel good. Someone could argue that “All the tests are there to ensure that every method behave as expected when it runs”.  Well not necessarily correct. Did you consider if you have to make a change to a component how much re-factoring need to be carried out? 

Let’s explain this with an example. When you have an obvious method, which takes a String parameter and returns a Boolean, and there are 100 methods calling this simple method, change to this method to return a String would require changing all those 100 methods. How about the repetition? Your Unit Test probably written to ensure that calling method takes a String value and returns a Boolean. Isn’t this repeating the same thing? How about the DRY? The time you have spent to write this Unit Test, you should have spent for some important task such as analysing some business requirements. 

Consider the future maintenance cost for both production code and all these Unit Tests? The amount of time you need to write Unit Tests for every single method, the amount of time you have to spend to write tests for complicated methods, which add no obvious benefits to the design of the system. They do not add any value at all. 

You may also reluctant to make changes to your code because of the amount to Unit Tests and the fear of breaking them.


So how you decide what Unit Tests to write. In order to decide this, you need to understand the types of methods you would normally write within your application. 

1.       Simple methods – These methods are very obvious and simple. Just by having a look at code you can clearly see what it does.  The code it self explains the design of it.

        /// <summary>

        /// Gets the first name from fulllname.

        /// </summary>

        /// <param>The full name.</param>

        /// <returns>First Name</returns>

        public string GetFirstNameFromFulllname(string fullName)


            if (string.IsNullOrEmpty(fullName))


                return string.Empty;


            return fullName.Substring(0, fullName.IndexOf(” “));


If you perform additional design and verification through Unit Testing, this method will give you a minimal benefit.

So if the method is simple and the design is obvious, you don’t need a Unit Test. If you are a TDD partitioner, the concept is the same. You do not need to write tests for every method you write within your application. 

2.       Components that are already tested – I see some developers trying test components that have already been tested by the framework.            

        /// <summary>

        /// Adds the companies to cache.

        /// </summary>

        /// <param>The company list.</param>

        public void AddCompaniesToCache(IList<Company> companyList)


            if (companyList != null && companyList.Count() > 0)


HttpContext.Cache.Add(“companyCahchkey”, companyList, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 15, 0), CacheItemPriority.Normal, null);



The real purpose of this method is to add a list of companies to cache. A test would be to ensure the list is added to the cache. Why would do you need to write Unit Tests against this method when the ASP.NET caching – Cache  is already tested for its capabilities. You can also see this method is very simple and hence Unit Tests are not required. 

3.       Complex methods and have no value to the design at all

For example you may have a method that writes to a registry using a complex pattern, and then using a complex algorithm to generate some custom strings, then serializes the data before calling a web service.

It will be very exhaustive exercise to write dependencies for some of these complex methods. There are so many things and variations to consider. These methods are not related to your main design or requirements but to assist or help other methods to get the job done.  Most of these methods are self-contained algorithms. 

4.        High Level methods – There are methods within your application that integrated or calls other Units of methods. 

public void ManageResourceData(string resources)


            if (string.IsNullOrEmpty(resources))

                throw new ArgumentNullException(“resources”);

            string retResourceValues = MergeResources(resources);






As you see here there are few units of methods being called. Writing Unit Tests for these types of methods, often waist of time. 

5.       Complex methods with so many dependencies.

Some refer to this as GOD methods. Most TDD practitioners not experience these type of methods as they would to like to perform one assert per single method. Also methods are smaller and always written for a single responsibility. You might come across with a situation where complex method with so many dependencies. The method itself performs so many other things and need to be re-factored in order to make it more testable. You can see these methods really hard to Unit Tests. You have two options

 a.       Re-factor your method and consider using interfaces, so you can mock all your dependencies during Unit Test.

b.       Simply do not waist your time to write the Unit Test. You may not have enough time to re-factor, and you can spend this time for something more useful.

Unit Tests

So the next important question is “What types of methods that you write Unit Tests against?”. The answer is not simple, which why you need to think carefully, before you write Unit Tests.

 If you an application author, you would consider writing Unit Tests against the method that actually define your requirements. The focus should be to write methods with less number of dependencies by providing a single responsibility, while focusing on a specific requirement. Your dependencies should be easily mockable. The same consideration is applied if you are practicing TDD. When you implement your method with, then to pass your Unit Test, you should consider it as defining a specific requirement. If not, the test it self does not add value to your app.


The above graph displays the number of Unit Tests increases with the requirements. The more requirements you have the more Unit Tests you should have. 

For example you may have a high level requirement to write a Banking application where customer performs banking operations. When you design your application, you will consider more detail requirements, such as customers should be able to withdraw, deposit, transfer, print statements within your application. Regardless of wether you are TDD practitioner or not, you should consider writing Unit Tests for withdraw, deposit, transfer and print statements. By doing this you add the real quality to your application. You will have the confidence that your application performs as expected from the Unit Level.

You should not consider writing Unit Tests for any algorithms that may have to calculate your balances, encryptions, serializations, locked/isolated, or wether the database get initialised. These are some of the examples that you should avoid as they do not add much values your Unit Tests.

If you framework author you would consider writing Unit Tests ensure that the methods you have written confirms to the key design principles of your framework. Framework author should target the requirements, which provided by the design of the framework. For example, you are developing a resource management framework, and you need to ensure the developer who uses the framework could successfully retrieve images from your resource management system. So you would write a Unit Test to ensure that developers can retrieve images as expected.

I do not say that we should avoid Unit Tests and should not practice TDD. They both provide some real benefits to the application. However having unnecessary code / Uni Tests leads to more maintenance, and extra cost to projects.