Wednesday, June 8, 2011

Holiday for 4 weeks

As I’m going on a holiday for 4 weeks tomorrow, no new posts or at least not many will be published during that time. Wish you all a nice day and stay happy. I’m looking forward to start posting again after July the 5th.

Sunday, June 5, 2011

.NET Compiler Directives

Not sure how to use .NET compiler directives (#pragma) or not sure when to use it?

Take a look at this blog post, Compiler directive #Pragma reference, by Daily .NET Tips. It contains a short description of the two different types of Pragma, and when they are used.

Saturday, June 4, 2011

Glimpse ASP.NET debugger

Glimpse is a Firebug like debugger used to debug ASP.NET. Among others it can help you debug routes and enable tracing in ASP.NET MVC, it also has a plugin to help you debug Ajax. Glimpse also allows you to take a look at the execution stack, including all action filters and etc. called to display the view or page.

At the moment Glimpse supports ASP.NET Web Forms and ASP.NET MVC, but more technologies are going to be supported, including PHP, Ruby on Rails, and Node.js.

It is a very powerful tool and enables you to debug stuff, which can be difficult to debug using Visual Studio.

I strongly recommend you to watch the introduction video at, and try it out. Glimpse can be downloaded via NuGet.

Routes in ASP.NET MVC: The Rails Way

Some think that using routes in ASP.NET MVC, are a little to noisy and likes the Rails way better.

The Rails Way



@Html.RouteLink("Home", "Root")

A bright individual, Rob Conery, wanted to change this a wrote a blog post called, Referencing Routes in ASP.NET MVC The Rails Way. Basically it allows you to use routes in ASP.NET MVC this way

Routes in MVC the Rails way

// And set route variables like this
@Routes.home_url(new { id = "stuff" });

HtmlTags 1.0 released

A new release of the HtmlTags library has been released. If you don’t know what the library does I suggest you take a look at the HtmlTags readme, and the Announcing HtmlTags 1.0 blog post.
The library allows you to create HTML tags in a fluent way, instead of the StringBuilder.
A quick example would be
Default way

@Html.TextBox("FirstName", "Lucas", new Dictionary<string, object> {{"id", "first-name"}, {"class", "required"})
Using HtmlTags


Clearing ASP.NET Session Variables

How to clear the ASP.NET session correctly and what are the difference between Session.Clear(), Session.Remove() and Session.Abandon()?

The blog post ASP.NET Internals: “Clearing ASP.NET Session Variables” a in-depth look, written by Abhijit Jana, answers these questions.


Friday, June 3, 2011

Data Annotations Extensions

The System.ComponentModel.DataAnnotations contains the most basic validation rules like

  • String length
  • Required
  • Range
  • Regular expression

These validators can be used for many things, but sometimes they just aren’t enough. That’s where the open source project DataAnnotationsExtensions comes to the rescue. It contains many of the most sought after validators, and some less used ones too. Currently it contains the following validators:

I’ve added links for each validator to the demo page on their web site. The project comes in two versions, one which only contains server side validation, and one which also supports client-side validation with ASP.NET MVC3. Both versions are available for download from NuGet and from the DataAnnotationsExtensions download page.

The library just makes data validation in ASP.NET Dynamic Data and ASP.NET MVC much easier and more readable.

ASP.NET Dynamic Data - Part 8 - Customizing Field Validation

In ASP.NET Dynamic Data you can customize and extend data validation in several different ways.

  • Using DataAnnotations attributes on individual data fields.
  • Overriding the partial class method that processes changes for the individual data field.
  • Override the OnValidating or Validate event, to customize validation for any data field.
  • Create a custom validation attribute

Creating a partial class for validation

The first thing we need to do, is to create the partial class that extends the data model. This makes it possible to add metadata through attributes and implementing partial class methods to create your own validation logic. We have already done this in this serie in part 2, so take a look there if you don’t know how to do this, after that we need to create the metadata class which is done in part 3.

Customize validation using attributes

This is the easiest way. It allows you to use default validation rules provided by the DataAnnotations attributes.

  1. In the partial class create a property or field with the same name as the data field to validate.
  2. Apply one of the attributes from the DataAnnotations namespace to the field or property.
Example 1

public class TableMetaData {
	public object Name { get; set; }

	public object Description;

The example makes the Name attribute required and the length of the description at least 10 characters long. You can also apply several validation attributes to the same field.

Using partial class method for an individual field

Another way to do more complex validation, is to override a partial class method that processes changes made to an individual data field. The naming convention for this is On<FieldName>Changing.

  1. Override the partial class method.
  2. Add the validation logic.
Example 2

public partial class Table {
	partial void OnNameChanging(string value) {
		if (value.Length < 5) {
			throw new ValidationException("Name must be at least 5 characters long.");

	partial void OnPriceChanging(double price) {
		if (price < 0) {
			throw new ValidationException("Price cannot be negative!");

The example validates the name is at least 5 characters long, and the price is non-negative. This example could also be done using the built-in attrbutes. All exceptions thrown in the data model are caught by the DynamicValidator control, which also displays it in the page. The parameter is typed to match the data type in the model.

Using partial class method for all fields in the model

This method allows you to control the validation logic for all fields in the data model at the same time, which is very useful when the logic can be applied to more than one data field, and allows you to validate combinations of multiple data fields.
The way to do this is different whether you use a Linq to SQL or Entity Framework data model.

Linq to SQL

  1. Override the OnValidate method
  2. Add to validation logic
Example 3

partial void OnValidate(ChangeAction action) {
	if (this._IsStock && this._Amount <= 0) {
		throw new ValidationException("The product cannot be in stock when the amount is 0 or less");

The example validate that a product only can be in stock, when the amount is greater than zero.

Entity Framework

  1. Create a partial class for the entity class you want to implement custom validation on
  2. Language specific step
    • If C# create a partial method called OnContextCreated which registers an event handler for the SavingChanges event
    • If VB just create an event handler for the SavingChanges event
  3. Add the logic to the partial class method
Example 4

public partial class ProductsEntities {
	partial void OnContextCreated() {
		SavingChanges += OnSavingChanges;
	public void OnSavingChanges(object sender, EventArgs e) {
		var stateManager = ((ProductsEntities)sender).ObjectStateManager;
		var changedEntities = stateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added);
		foreach (var entry in changedEntities) {
			if (entry.Entity is Product) {
				Product prod = (Product)entry.Entity;
				if (prod.InStock && prod.Amount <= 0) {
					throw new ValidationException("Product cannot be in stock when the amount is zero or less");

Custom validation attribute

Let’s you create an attribute you can reuse across projects and/or models for a single data field. The attribute must derived from ValidationAttribute.

  1. Create a new class
  2. Add references to System, System.Globalization and System.ComponentModel.DataAnnotations
  3. Make the class sealed
  4. Derive the class from ValidationAttribute
  5. Apply the AttributeUsageAttribute and indicate that the attribute only can be applied to a property or field one time
  6. Override the IsValid and add the validation logic inside
  7. Optionally you can override the FormatErrorMessage to perform error-message formatting.
  8. Apply the attribute just as you would with one of the built-in validation attributes

An example of a attribute could look like this

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false]
public sealed class CapitalizeAttribute : ValidationAttribute {
	public override bool IsValid(object value) {
		return Char.Uppercase(value.ToString()[0]);

	public override string FormatErrorMessage(string name) {
		return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);

Type-Safe ASP.NET Session

I just hate loosing object types such as you do in when retreving objects from the ASP.NET session, like done here

// Fails if the key does exists in the session
// as an integer cannot be null
int id = (int)Session["id"];
// Doesn't throw an error as we handle null
int id = Session["id"] == null ? -1 : (int)Session["id"];
Wouldn’t it be nice if we handled this more gracfully? And actually  got the object back we expected? This could easily be accomplished using extension methods.

public static class SessionExtensions
    public static T Get<T>(this HttpSessionStateBase session, string key)
        return (T)session[key];

    public static bool TryGet<T>(this HttpSessionStateBase session, string key, out T item)
        object sessionItem = session[key];
        if (sessionItem == null)
            item = default(T);
            return false;

            item = (T)sessionItem;
        catch (InvalidCastException)
            item = default(T);
            return false;

        return true;

    public static Result<T> SafeGet<T>(this HttpSessionStateBase session, string key)
        object sessionObject = session[key];
        if (sessionObject == null)
            return new Result<T> { Success = false };

            T item = (T)sessionObject;
            return new Result<T> { Success = true, Value = item };
        catch (InvalidCastException)
            return new Result<T> { Success = false };

public class Result<T>
    public T Value { get; set; }
    public bool Success { get; set; }

I’ve created several methods to get the value from session. The Get method just gets the object and casts it to the specified object, the downside here is the possibility for an InvalidCastException. The TryGet method, uses the standard .NET way, and uses and out parameter. The last method, SafeGet, is my prefered way (I just hate out parameters), and returns an object which contains the success and the value. Each method can be used like this

Session["test"] = 10;
int integer = Session.Get<int>("test");
if (Session.TryGet("test", out integer)) {
    // Use value
var resultObject = Session.SafeGet<int>("test");
if (resultObject.Success) {
        // Use value (result.Value)

This method can of course easily be adapted to similar situations like TempData.

Thursday, June 2, 2011

Wrap another tag inside a Label tag (MVC extension method)

A web developer at work recently wanted to wrap a input tag inside a label tag for easier layout. The HTML wanted looked like this:

<label for="name">Name:<input type="text" id="name" name="name" /></label>

This was a in MVC project, and because of this I’ve decided to create an extension method to do this. The extension method should also support adding attributes to the label tag. The extension method I came up with looks like this:

  1: public static string LabelWrap(this HtmlHelper helper, string label, MvcHtmlString @object, object attribtues = null)
  2: {
  3:   StringBuilder sb = new StringBuilder();
  4:   Match match = Regex.Match(@object.ToHtmlString(), @"id=""(?<ID>\w+)""");
  5:   if (match.Success)
  6:   {
  7:     sb.AppendFormat(@"<label for=""{0}""", match.Groups["ID"].Value);
  8:     if (attribtues != null)
  9:       {
 10:         PropertyInfo[] propertyInfos = attribtues.GetType().GetProperties();
 11:         foreach (PropertyInfo propertyInfo in propertyInfos)
 12:         {
 13:           sb.AppendFormat(@" {0}=""{1}""", propertyInfo.Name, propertyInfo.GetValue(attribtues, null));
 14:         }
 15:       }
 16:       sb.AppendFormat(">{0}{1}", label, @object.ToHtmlString());
 17:       sb.Append("</label>");
 18:     }
 19:     return sb.ToString();
 20:   }
 21: }

The method doesn’t take into account, whether or id could be found.

Using the method is very simple

@Html.LabelWrap("Name:", Html.TextBoxFor(model => model.Name))

And adding attributes to the label tag, just as easy

@Html.LabelWrap("Name:", Html.TextBoxFor(model => model.Name), new { @class = "cssClass" })
Could it be easier?

Using CDNs and Browser Caching to Improve Web Site Performance

Web Site performance is of great importance to many developers, and a lot of techniques can be used to increase performance. An example could be using CDNs (Content Delivery Networks) and browser caching, both a very easy to implement in ASP.NET. Just take a look at the blog post Using CDNs and Expires to Improve Web Site Performance written by Rick Anderson. The post focuses on how to do this in MVC, but can easily be adapted to Web Forms, just by writing the full links instead of using the in-page Razor helper.

ASP.NET MVC Validation with the Entity Framework

Model validation in ASP.NET MVC are very easy and effective, especially if you create the model yourself. It gets a little more complicated when using the entity framework or Linq to SQL, but when know how to do it, it’s a breeze.

If you have read my series on ASP.NET Dynamic Data you’ve almost read the answer in part 3. You have to create a partial class, extending the entity class and define some meta data for the entity.

The tutorial on the ASP.NET MVC web site, Validation with the Data Annotation Validators, explains this in more detail with focus on MVC.

Disable RequestValidation in ASP.NET MVC3

In a recent ASP.NET MVC3 project I’ve got the dreaded yellow screen of death with the error

A potentially dangerous Request.Form value was detected from the client

What to do? I’ve got the error in ASP.NET forms, and know how to fix it by disabling request validation. Request validation can be disabled both globally and on a single page. Generally I would recommend not disabling request validation globally as it is very effective against simple cross-site scripting (XSS) attacks.

But how to fix this in MVC? After some searching on the web, I found a blog post by David Hayden describing how to do this in MVC, AllowHtml Attribute in ASP.NET MVC3. As the post describes you can use the AllowHtml attribute to disabled request validation on a single property on the model. If you don’t use a model and just want to receive some HTML in a action, you can still use the ValidateInput attribute, which disables request validation on the whole action.

Wednesday, June 1, 2011

ASP.NET Dynamic Data - Part 7 - Customize Edit Field Templates

So far we've only concentrated on customize the "simple" fields, the display fields, but what about the edit fields?
Exactly this are the topic of this post. We are going to create a custom field template, and adapt the edit template to our needs.
The field template are created as described in ASP.NET Dynamic Data - Part 3 - Customize Field Templates. This is the template we'll continue working on.

The default template

The default edit template looks like this.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PriceCustom_Edit.ascx.cs" Inherits="DynamicData_FieldTemplates_PriceCustom_EditField" %>

<asp:TextBox ID="TextBox1" runat="server" Text='<%# FieldValueEditString %>'></asp:TextBox>

<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />
<asp:DynamicValidator runat="server" ID="DynamicValidator1" ControlToValidate="TextBox1" Display="Dynamic" />
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;

public partial class DynamicData_FieldTemplates_PriceCustom_EditField : System.Web.DynamicData.FieldTemplateUserControl {
    protected void Page_Load(object sender, EventArgs e) {
        TextBox1.MaxLength = Column.MaxLength;
        if (Column.MaxLength < 20)
            TextBox1.Columns = Column.MaxLength;
        TextBox1.ToolTip = Column.Description;

    protected override void ExtractValues(IOrderedDictionary dictionary) {
        dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);

    public override Control DataControl {
        get {
            return TextBox1;
By default three validators are present, RequiredFieldValidator, RegularExpressionValidator and DynamicValidator. The RequiredFieldValidator of course makes the field required, the RegularExpressionValidator is empty and does nothing, the DynamicValidator takes care of all the validations defined in the data model.
In this case we'll add a custom validator, that ensures the entered value is an integer between 0 and 100.

Add and implement the custom validator

First we'll add a custom validator in the markup, which looks like this
<asp:CustomValidator runat="server" ID="CustomValidator1" ControlToValidate="TextBox1" Display="Dynamic" OnServerValidate="PriceValidation" />
Next we have to implement the validation method, called PriceValidation. This method checks if this the entered value is a interger between 0 and 100.
protected void PriceValidation(object source, ServerValidateEventArgs args)
    bool result = false;
    int value;
    result = Int32.TryParse(TextBox1.Text, out value);
    if (!result)
        CustomValidator1.ErrorMessage = "The entered value is not an integer";
        args.IsValid = false;

    if (value < 0 || value > 100)
        CustomValidator1.ErrorMessage = "The entered value not between 0 and 100";
        args.IsValid = false;

    args.IsValid = true;
That's it we have now customized the edit field template. This hopefully gives an idea of how to customize the edit template, anything you could normally do in a user control, are possible here.
Here at the end is a screenshot of the custom error message.