Create an Index for you Entity Framework Index

Either you are working with a field that require a fast access or if the field is used as reference in some case, you will need to create an Index. Unfortunately, Entity Framework does not offer a quick way to do it. To tell Entity Framework to generate the Sql Index on the column, you must use a Column Annotation. Entity Framework column annotation has an already created class named IndexAnnotation that can be added to your column.

this.Property(d => d.Date)
    .HasColumnAnnotation("Index"
                        , new IndexAnnotation(
                                              new IndexAttribute("IX_Date") {IsUnique = true}
                                             )
                        );

The code above set for a Date column an index. It creates a IndexAnnotation which create a unique index attribute.

This result into an Index inside the migration class with a unique property set to true.

CreateTable(
	"YourEntityName",
	c => new
		{
			Id = c.Int(nullable: false, identity: true),
			Date = c.DateTime(nullable: false),
		})
	.PrimaryKey(t => t.Id)
	.Index(t => t.Date, unique: true);

Never use Primitive Type for any Entities

I see in a lot of system an abuse of primitive types. Instead of using a class for an entity, the use of primitive is used. Often, when additional needs is required, additional primitives are used which duplicate. Here is some basic example:

public class Item
{
    public double Price{get;set;}
    public string Name{get;set;}
}

The problem is obvious, the Item class should not be in a primitive type for the Price. The first reason is if later we need to have additional information, like for example the currency, you will be stuck with a second property. The problem become even more obvious if you have several money element for the same class. The class become clutters of properties. It is also way easier in the future to add additional property or method without having to change a lot of place in your software — you change at one place, the class.

public class Item
{
    public double Price{get;set;}
    public int CurrencyTypeForPrice{get;set;}
    public double SuggestedPrice{get;set;}
    public int CurrencyTypeForSuggestedPrice{get;set;}
    public string Name{get;set;}
}

The second problem is when your application become big and you realize that you should have used decimal instead of double that you have to change at several places instead to a single class. The third problem is about operations. How can you compare two prices? You have to compare the double properties (the price) with the int property (the currency type) every time. Rather than having a class with the operator equal overriding that does it at one place, you have to do it everywhere.

The forth problem is about passing information by parameter. When you have a single class, for example a Money class instead of a decimal + type for currency, it is way cleaner to use. The fifth reason is when you are using Asp.Net MVC and Template. You can create a visual editor and display template for your entity type. For example, you could create a Money.cshtml which shows the right control for the user to allow him to select from a drop down the currency. Without a specific class for your entity you would have to create an Html helper that take two parameters: the amount and the currency.

Finally, you can add additional validation. If you entity is for money than you can say that your money must always be positive. This also imply the advantage to be able to unit test at a single place instead of everywhere when you use your money logic.

To conclude, you can see that their is several advantages like when refactoring your entity, when adding operations or when using framework like Asp.Net MVC. A cleaner code and less repetition is also very interesting. None but not the less, having a class instead of a primitive type allow you to unit tests logic on any logic about your entity.

Custom Validation Attribute for String with Underneath Property Validation

Validation can occur with an attribute during client side and server side. For example, one simple validation can be to ensure that a property string is all to lower case. This can be a simple attribute like the following one.

/// <summary>
/// Validate that the string is in lower case
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class LowerCaseString : BaseDataAnnotation
{
	protected override ValidationResult IsValid(object value, ValidationContext validationContext)
	{
		string model = value as string;
		
		if (model != null)
		{
			if(string.Equals(model, model.ToLowerInvariant(), StringComparison.InvariantCulture))
			{
				return ValidationResult.Success;
			}
		}
		return base.ReturnDefaultErrorMessage(string.Format(Resources.DataAnnotationErrorMessage.StringNotLowerCase, validationContext.DisplayName)
												, new[] { validationContext.MemberName });
	}
}

WebValidationAttribute
This class works well but sometime you may want to have the validation to appears but validating a property of the class. For example, here is a class named StockOrder that use a problem called StockSymbol which must be in lower case and we want to validate the property of this class during validation. Adding the LowerCaseString attribute without specifying the property to check on the StockSymbol class does not allow the case to string inside the attribute. It crashes.

public class StockOrder 
{
	[Required]
	[LowerCaseString]
	[Display(ResourceType = typeof(ModelPropertyDisplayName), Name = "StockSymbol")]
	public Symbol StockSymbol { get; set; }	
}

You may think that you should set the LowerCaseString to the string property in the beneath property’s class. However, we cannot only set the attribute on the property class because the graphical user interface need to add the validation to the property and not the property of a property. To fix this problem, it is possible to add a property to the attribute with the goal of specifying the property to validate underneath.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class LowerCaseString : BaseDataAnnotation
{
	public string InnerProperty { get; set; }
	protected override ValidationResult IsValid(object value, ValidationContext validationContext)
	{
		string model;
		if (value is string || String.IsNullOrEmpty(InnerProperty))
		{
			model = value as string;
		}
		else
		{
			Type thisType = value.GetType();
			PropertyInfo theMethod = thisType.GetProperty(InnerProperty);
			model = (string)theMethod.GetValue(value);
		}
		if (model != null)
		{
			if(string.Equals(model, model.ToLowerInvariant(), StringComparison.InvariantCulture))
			{
				return ValidationResult.Success;
			}
		}
		return base.ReturnDefaultErrorMessage(string.Format(Resources.DataAnnotationErrorMessage.StringNotLowerCase, validationContext.DisplayName)
												, new[] { validationContext.MemberName });
	}
}

The InnerProperty property is checked to see if set and if it is set on an attribute that is not a string than by reflection we get the property value and validate. The goal of verifying if the property is a string is for advanced scenario where the validation is done on a class on the Model and on a string on the ViewModel. This situation can occur if you are working with a Model-ViewModel architecture and that you transfer automatically with AutoMapper Data Annotation validation.

public class StockOrder 
{
	[Required]
	[LowerCaseString(InnerProperty = "Value")]
	[Display(ResourceType = typeof(ModelPropertyDisplayName), Name = "StockSymbol")]
	public Symbol StockSymbol { get; set; }	
}

At the end, what is important is that you can specify inside an attribute which property to validate and having the option to be more specific in some scenario.

How to AutoMap Asp.Net Attribute from Model to ViewModel

If you are using DisplayAttribute and DataAnnotation Attribute with an architecture that use Model and ViewModel, by default, you have to duplicate those attributes. The problem is that you cannot keep all display attribute on the view model only because you want to have you exception to have the display name into it. You also want to have the data annotation on your model because they add validation into the model, not into a class designed for rendering, the view model. That say, Display Attribute and Data Annotation are quite useful in Asp.net because they are using for Label and for client-side validation. So, we need them in both place. The best place is to have the attribute on the Model classes. Mostly because the model classes are the heart of the system where logic of your system live.

With that in mind, we need when transferring the values from the model classes into the view model classes transfer the attributes too. This require some works to change some Asp.Net behaviors and also do some work with AutoMapper to maps more than just the specified properties but also attributes for those specified properties. All code discussed in this article is open sourced in this Git Repository : https://github.com/MrDesjardins/AutoMapperAttributesMapping.

The first change is on Asp.Net MVC. We need to define a new DataAnnotationsModelMetadataProvider. The goal of this class is to create a new provider to handle attributes. So every times MVC will access the attributes on the view model, it will call this method. We will access AutoMapper and get from the attributes from the model. As you can notice, we pass inside the constructor a IConfigurationProvider that allow you to pass AutoMapper configuration.

internal class MappedDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
	private readonly IConfigurationProvider mapper;

	public MappedDataAnnotationsModelMetadataProvider(IConfigurationProvider mapper)
	{
		this.mapper = mapper;
	}

	protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
	{
		var mappedAttributes = containerType == null ? attributes : mapper.GetMappedAttributes(containerType, propertyName, attributes).ToArray();
		var modelMetadata = base.CreateMetadata(mappedAttributes, containerType, modelAccessor, modelType, propertyName);
		return modelMetadata;
	}
}

This class must be instantiated during the startup of you web project. Ideally in the Global.asax. I created a class to have a public access which can be called from the global.asax.

public class ModelMetadataProviderConfig
{
    public static void RegisterModelMetadataProvider()
    {
        ModelMetadataProviders.Current = new MappedDataAnnotationsModelMetadataProvider(Mapper.Engine.ConfigurationProvider);
    }
}

The big piece of code is with AutoMapper. The DataAnnotationsModelMetaDataProvider calls the GetMappedAttributes from AutoMapper. This is a custom method that do the mapping for attributes. This method is pretty big and do a lot of looping. The first one is looping all the registered mapping. We need to get from all mapper where we are going to map to the destination one. Since we are using the meta data from the type used inside the view, which is the View Model class, we need to search through the list of mapping for the destination type. This can lead to several mapping, this is why we have a second loop that search for the property name. We make sure that we search only for mapped type, not those ignored. The last loop can be customized for your need. I decided to map attribute that are of type ValidationAttribute and DisplayAttribute.

public static IEnumerable<Attribute> GetMappedAttributes(this IConfigurationProvider mapper,
	Type viewModelType,
	string viewModelPropertyName,
	IEnumerable<Attribute> viewModelPropertyAttributes)
{
	if (viewModelType == null)
		throw new ArgumentNullException("viewModelType");

	//For all automapper configurations about the view model we are working with
	foreach (var typeMap in mapper.GetAllTypeMaps()
		.Where(i => i.DestinationType == viewModelType))
	{
		//Get the properties from the model we found from automapper
		var propertyMaps = typeMap.GetPropertyMaps()
			.Where(propertyMap => !propertyMap.IsIgnored() && propertyMap.SourceMember != null)
			.Where(propertyMap => propertyMap.DestinationProperty.Name == viewModelPropertyName);

		foreach (var propertyMap in propertyMaps)
		{
			//Only get the attribute from the model if the view model does not define it
			foreach (Attribute attribute in propertyMap.SourceMember.GetCustomAttributes(typeof(ValidationAttribute), true))
			{
				if (!viewModelPropertyAttributes.Any(i => i.GetType().IsInstanceOfType(attribute)
														  || attribute.GetType().IsInstanceOfType(i)))
					yield return attribute;
			}
			//Only get the attribute from the model if the view model does not define it
			foreach (Attribute attribute in propertyMap.SourceMember.GetCustomAttributes(typeof(DisplayAttribute), true))
			{
				if (!viewModelPropertyAttributes.Any(i => i.GetType() == attribute.GetType()))
					yield return attribute;
			}

		}
	}

	//Add all view model attribute
	if (viewModelPropertyAttributes != null)
	{
		foreach (var attribute in viewModelPropertyAttributes)
		{
			yield return attribute;
		}
	}
}

This method returns a list of attributes that are then set to the ViewModel object with the call to the base.CreateMetaData method. To see the result, you can add a display attribute on the model and see what is happening when you use the Html helper for label.

public class UserModel
{
    public int Id { get; set; }

    [Display(Name = "First Name Here")]
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
public class UserViewModel
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The .csHtml:

<div class="row">
    <div class="col-md-6">
        @Html.LabelFor(d => d.FirstName)
        @Html.TextBoxFor(d => d.FirstName)
    </div>
    <div class="col-md-6">
        @Html.LabelFor(d => d.LastName)
        @Html.TextBoxFor(d => d.LastName)
    </div>
</div>

Display
This example shows one label that has the Display attribute, this is the FirstName, and one that does not have it, this is the LastName. For the complete code and example, go to GitHub.

Tracing with Event Tracing for Windows (ETW) an Asp.Net VNext

Tracing information can be done in multiple ways. You can use the Diagnostic framework, use Microsoft Enterprise Library or Log4Net. However, if you need to trace performance information, Event Tracing for Windows (ETW) is the way to go. The reason is the Event Tracing for Windows (ETW) is build to receive stream of information and to manage, with Windows, the most efficient way to not reduce the performance of your system. It always get information on the whole system which can be better to figure out why something is getting slower if it impacted by something outside your application.

Since .Net Framework 4.5, ETW is way easier to setup and to use. However, keep in mind that it is not as sweet as it could be. ETW’s tools are old and not easy to understand. This is why, I suggest that you go see those Channel9 Videos on PerfView. PerfView is the tool to read the log created by ETW. When you application is using ETW, this one is sending log to the system. However, if this one does not capture it, nothing is saved. Therefore, that has the advantage to quickly start gathering information just by opening a listener, like PerfView.

Before going into PerfView, you need to setup your code to add specific events. Otherwise, you will capture every systems and application events but none of yours. With .Net Framework 4.5 and above, you need to create a class that inherit from System.Diagnostics.Tracing.EventSource. That say, you need to have a reference to System.Diagnostic. This one is available for Asp.Net VNext. You need to add the Diagnostic reference into the project.json of your project.

{
    "frameworks": {
        "aspnet50": {
            "dependencies": {
                 "Microsoft.AspNet.Diagnostics":  "1.0.0-beta1"
            }
        },
        "aspnetcore50": {
            "dependencies": {
                "System.Runtime": "4.0.20-beta-22231"
            }
        }
    }
}

The class that you create and that inherit from EventSource must have an attribute of type EventSource that define the name of the Provider. Then, you need to create one method for every event you want to capture. Every method needs to have an atribute of type Event. This define the message to be recorded. Here is an example.

[EventSource(Name = "MyTracingProvider")]
public sealed class MyTracingProviderEventSource : EventSource
{
	[Event(1, Message = "Method '{1}' begin", Level = EventLevel.Informational)]
	public void MethodCallBegin(string methodName)
	{
		if (this.IsEnabled())
		{
			WriteEvent(1, methodName);
		}
	}
}

What is important here is that the method you define must has only primitive parameter. This is not only true for the WriteEvent method used to pass information to the event message but also to the method name. Passing a collection of one of your class and transforming this array into string within the method before passing the produced string to WriteEvent will not work. In fact, the result will be in PerfView under a Guid instead of your event name with the exception message that it cannot read. Here is an output

ThreadID="25,652" FormattedMessage="ERROR: Exception during construction of EventSource MyTracingProvider: 
Unsupported type IEnumerable`1 in event source. " DataLength="230" 

PerfViewErrorParameters

By the time you have created all events you want to capture, you should have downloaded PerfView. It is a free tool to capture and read all traces. If you are using Asp.Net VNext, you can start your application — PerfView works with IISExpress. Then, in the main menu, select Collect and Run. In the command area, enter the path of IISExpress. Mine was installed in the x86 folder (“C:\Program Files (x86)\IIS Express\iisexpress.exe”).
PerfViewCommand
It is important to specify in the Additional Provider your provider name specified in the attribute above the Event Source class. It must also start with the * character if you do not want to specify which process your events come from. If you click Run Command, it captures events. You can do some action on your website, close the website (or kill IISExpress). PerfView will automatically create the result in a Zip file and it opens the result into a Windows Application. You need to double click the Events node under the PerfViewData.etl.zip node. This will open a list of events from where you can search for the one you have defined in your code.

Events

To conclude, ETW is a great way to capture performance tracing. Windows Azure is compatible with this mechanism and you can use Windows Azure Storage Table to get information from your website. It is also a powerful tool to get insight of what is going on and to get some additional metric of your system without polluting the rest of your logs. You can find the additional information on the Msdn Blog about why ETW is considered to be the ideal solution for high speed logging. Their is also a tutorial from Msdn Blog about ETW. Some resources are also available on Azure Website about how to read ETW log with Asp.Net VNext and Visual Studio 2015.

How to Debug Entity Framework Migration Seeding

Debugging Entity Framework’s Migration Seeding can be confusing because you cannot just set a breakpoint and execute the Migration command to update your database. You must use a second Visual Studio to debug the first one. The easiest way is to use the System.Diagnostics.Debugger.Launch method. By calling that method, inside your code, a second Visual Studio will open and debug the first one that is executing the migration command. The second Visual Studio will be in debug mode. The trick is to keep this one attached to the first one until you are completely done. That mean that you can debug the first one with break point, stop it if you have error, edit the code, run the migration command again, etc. All that without stopping the second Visual Studio. If you stop the second Visual Studio that is attached to the first one, you will have to reattach which can take several times. However, by keeping the second Visual Studio always attached on the first one, you do not have any waiting time.

if (System.Diagnostics.Debugger.IsAttached == false)
   System.Diagnostics.Debugger.Launch();

The code shows what you should copy paste, right before where you expect the problem.

Regex to get Everything Until a Specific Character is Found

Stripping attribute from HTML can be time consuming if you do it manually. Since the value can change on each of the attribute, you cannot do a simple search and replace. What you need is a regular expression that will search for the attribute you want to remove and with anything between quotes. That mean you need to have a Regex that search a string until a specific character is reach. In the case of having an Html attribute with a value between double quote that change you need to search what does not change and have the Regex catching all until it found the second quote.

data-info="this is value 1"
data-info="thisIsValue2"

The Regex to parse all string and is the following one. It takes the part that does not change and search for everything not a double quote. The Regex part that does this is the square bracket following by the ^ symbol. It informs the Regex to search everything until it finds the double quote. The “everything” is specified by the star character that is following the ending square bracket.

data-info=\"[^"]*\"