Enterprise Asp.Net MVC Part 3: Controller

In this third part, we will discuss about controller. We aren’t done yet with the model (still require to add more validation) but let’s talk about the controller. In Asp.Net MVC, the controller act has the gate for the Http Request and answer back to any request with a Http Response. That’s it. It’s role should be limited to this task to respect the Single Responsability Principle.

But, we need to do a lot of thing when a client send information to the server. We need to convert the data in input to object, we need to convert this information to the model domain, we need to get into the database to load information and maybe to save information, we need to manipulate the data and we need to send back an answer. How can the controller be clean and in the same time be able to do all those things? Well, we will need to use the principle of seperation of concern and to split every task into multiple classes.

We will start with the model binding, which is the first step of any request.

Auto-mapping

In Asp.Net Mvc, the transformation of HTTP Get parameter or HTTP Post parameters into C# code is called Model Binding. The Model binding by default try to convert any data to primitive type or try to instantiate your model object if the request contain a Json object that fit the schema of your classes. That mean that you can simply use Asp.Net MVC to send back all properties values of your model back to the server and Asp.Net MVC is bright enough to build a new object for you.

[HttpPost]
public ActionResult Create(WorkoutModel model)
{
	//1)Validate model
	//2)Do manipulation
	//3)Save into the database

	return View("Create);//4)Return a response to the client
}

The problem with this approach is, it works fine if you use Model object to send information to the view but we are using ViewModel (this was an architecture decision we took in the first part of this series). ViewModel give us the leverage to add additional information like a list of exercises that could be used in the workout, etc. So, before the task 1 of validating the model, we need to convert back the view model into model object. This is where automapper come to the rescue.

An automapper is a library that map property from an object to an other one. In our example, we will use AutoMapper. It’s a free, open source, and widely used automapper. It can be configurable or by default map property name automatically. I won’t show you how to use automapper in this article but you can find good example in this blog or anywhere on the web.

So, once we have receive the view model back to from the view to the controller, we need to automap the view model to the model. That mean that every time we use a controller action that we need to do this task. This can be repetitive and error prone. That’s why a better approach is to implement a “Model” object. A little bit like Microsoft did with Asp.Net MVC with the View. We will create a Model property that will hold the converted view model. To do so, we will need to modify the BaseController.

Automapper and BaseController

We will modify the BaseController and override the method OnActionExecuting. This will give us the opportunity to modify the code before entering the code of the action defined inside the controller.

This is an overview of what we are going to do. First, we will have a concrete controller for every entity. In our case, the WorkoutController. Each controller inherit of the BaseController which is generic with 2 types. The first one is the model type, and the second is the view model type. The BaseController contain a reference to a IMapperFactory, which is a layer of abstraction to the AutoMapper implementation. We will come back later with the IMapperFactory. Finally, the BaseController contain a property of TModel type. That mean that for the WorkoutController that we will be able to use “this.Model” to get the model from the view model. For another entity, the Model will be of the entity type because it will use the TModel type defined by the BaseController. Here is the code that reflect the illustration above.

public class WorkoutController : BaseController<Workout, WorkoutViewModel>
{

	public WorkoutController(IMapperFactory mapperFactory):base(mapperFactory)
	{
	}


	public ActionResult Index()
	{
	}

	[HttpGet]
	public ActionResult Details(int id)
	{
	}

	[HttpGet]
	public ActionResult Create()
	{

	}

	[HttpPost]
	public ActionResult Create(WorkoutViewModel viewModel)
	{
	}

	[HttpGet]
	public ActionResult Edit(int id)
	{
	}

	[HttpPost]
	public ActionResult Edit(WorkoutViewModel viewModel)
	{
	}
}

public abstract class BaseController<TModel, TViewModel>:Controller
{
	private readonly IMapperFactory _mapperFactory;
	
	protected TModel Model { get; private set; }

	protected BaseController(IMapperFactory mapperFactory)
	{
		_mapperFactory = mapperFactory;
	}

	protected override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		base.OnActionExecuting(filterContext);
		if(filterContext.ActionParameters.Any())
		{
			var possibleViewModel = filterContext.ActionParameters.FirstOrDefault(x => x.Value.GetType() == typeof(TViewModel));
			if (possibleViewModel.Value!=null)
			{
				var viewModel = (TViewModel) possibleViewModel.Value;
				var model = (TModel) Activator.CreateInstance(typeof (TModel));
				Model = _mapperFactory.Map(viewModel, model);
			}
		}
	}
}

Anytime, inside the Update or Create, instead of using the viewModel parameter which is of WorkoutViewModel type, you can use the base.Model. This way to code give us few advantages. First, the controller is clean. No mapping is done on any concrete controller. Second, we still have access to the view model if required. Third, we do not repeat work on all controllers.

Service layer

Now that we have the data from the view, we need to do some manipulation. We will skip the validation process because it will be in another part of this series. Let’s jump to the service layers. The service layer is a layer between the service layer is above the controller and could be used not only by the web controller but by the web api controller or any other application. It’s the layer between the user interaction and the repository. It’s the one that can contact the repository, the cache, or manipulate many entity to return a unique one. The service layer will be used by the controller to access the repository and to build the view model. For example, it will load a specific workout if the user call the Edit action of the Workout controller. Not only it will load the workout, but it will give us the view model filled correctly with the extra properties that could contain additional choices to be selected (like a list of exercise) and additional localized text for example.

So, we need to modify the WorkoutController to have a service reference.

public class WorkoutController : BaseController<Workout, WorkoutViewModel>
{
	public WorkoutController(IMapperFactory mapperFactory):base(mapperFactory)
	{
	}
//...

will become:

public class WorkoutController : BaseController<Workout, WorkoutViewModel>
{
	private readonly IWorkoutService _service;
	public WorkoutController(IWorkoutService service, IMapperFactory mapperFactory):base(mapperFactory)
	{
		_service = service;
	}
//...

As you can see, the IWorkoutService has been added. This will give us the possibility to inject the service into the controller. Every controller will have its own service.

Because most of the service will look the same we can create a base service class, that I’ll call IService. The IService will contain the primitive call that are concerning getting the model, saving the model and deleting the model.

public interface IService<TModel, TViewModel>
{
	IEnumerable<TViewModel> GetAll();
	TViewModel Get(TModel model);
	int Create(TModel model);
	int Update(TModel model);
	int Delete(TModel model);
}

public interface IWorkoutService : IService<Workout, WorkoutViewModel>
{
}

We could add in IWorkoutService more specific method. For example, one could require to have a specicial Get that will return a extended view model with more data. Or, someone might want to have to model from the Get instead of the view model. This type of architecture let a flexibility.

If we check the concrete implementation of IWorkoutService we will see all repository access and the automapper to convert the model to view model.

public class WorkoutService : BaseService, IWorkoutService
{
	public WorkoutService(IRepositoryFactory repositoryFactory, IMapperFactory mapperFactory) : base(repositoryFactory, mapperFactory)
	{
	}

	#region Implementation of IService<Workout>

	public IEnumerable<WorkoutViewModel> GetAll()
	{
		var listModel = Repository.Workout.GetAll().ToList();
		return Mapper.Map<List<Workout>,List<WorkoutViewModel>>(listModel);
	}

	public WorkoutViewModel Get(Workout model)
	{
		var modelToBound = Repository.Workout.Get(model.Id);
		return Mapper.Map<Workout, WorkoutViewModel>(modelToBound);
	}

	public int Create(Workout model)
	{
		return Repository.Workout.Insert(model);
	}

	public int Update(Workout model)
	{
		return Repository.Workout.Update(model);
	}

	public int Delete(Workout model)
	{
		return Repository.Workout.Delete(model);
	}

	#endregion
}

As you can see, we are using the IMapperFactory to map data and not directly the automaper. This abstraction give us the possibility to mock the mapping easily later. Also, you can see that we are doing the same with the repository. We are using IRepositoryFactory which is not tightly bound to any repository, neither bound to the workout. That mean that workout could load exercises without problem. The detail about the repository will be defined in another article.

Conclusion

We have seen that we can have clean controller and the use of service help us to separate the request from the repository. We also have seen that it’s better to use interface instead of concrete classes because it gives us the possibility to mock later on, give us a layer of abstraction between concrete implementation of the controller and from the repository, mapper and so on. In the next article of this series we will discuss about the repository and Entity Framework in an enterprise Asp.Net MVC web application. We will come back with controller in the article concerning validation of the model. Indeed, the controller will have its role with validation and we will see how to implement a solution that will still respect the single responsibility principle.

Series Articles

Article #1: Asp.Net MVC Enterprise Quality Web Application
Article #2: Asp.Net MVC Enterprise Quality Web Application Model
Article #3: Asp.Net MVC Enterprise Quality Web Application Controller
Article #4: Asp.Net MVC Enterprise Quality Web Repository Layer
Article #5: Asp.Net MVC Enterprise Quality Web with Entity Framework
Article #6: Asp.Net MVC Enterprise Quality Layers
Article #7: Asp.Net MVC Enterprise Quality Web Security

Circular reference with Entity Framework and Json when developing with Asp.Net MVC

A circular reference was detected while serializing an object of type …

Here come the problem of serializing. First of all, this occur because a parent object reference a child object and this one reference back to its parents. Sound familiar? Well, if you are working with Entity Framework and Code First, it should. Why? Because most of the Entity are cross referencing each others. This way, it’s convenient for many operations. For example, if you are a Team entity that has a list of Player, won’t it be convenient to have the User having a Team property to access his team name. It’s also interesting to do myPlayer.Team.Id = 1 and save the myPlayer. This way you do not have to instantiate the Team 1 object and add the player and save the team. Anyways, that’s how Entity Framework work and when it’s time to serialize to Json, it can cause this behavior.

The second problem is concerning the object itself. When trying to serialize, you are in fact serializing the Proxy also which is not what you want. In fact, you will get this error.

The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships.

This is why you should disable the proxy creation and handle the state of your poco with the DbContext instead of relying on proxy. Disabling the proxy is a matter of setting to false your DbContext’s property ProxyCreationEnabled.

_dbContext.Configuration.ProxyCreationEnabled = false;

Let’s come back to the main purpose of this article. The problem with circular reference can be fixed by two solutions.

The first one, is to broke those references when we send the information to Json. That mean that in your controller, before sending back the ActionResult, you loop problematic property to remove the reference. If we take back the example with Player and Team, we could simply loop the Team array of Player and set to Null all Player[i].Team.

The second solution can be to use the attribute ScriptIgnore over the property of Team for example. So, it will serialize only from one side. I haven’t try this solution that I have found at StackOverflow.com because I do not think that I should alter the Model for the View this way. The serialization process shouldn’t impact the model and for sure not to make something work only in half. At the end, we loss the reference on one side which will require to us to rebind it later on.

A better solution is to use a different library of Json which can handle reference, by that I mean the Newton King Library. This library support circular reference by add ID to object serialized.

First, you need to remove the serialization from the default Json serializer and use the Json Newton King Library. This can be done in the Global.asax.cs file. with the following code.

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(new JsonSerializerSettings()));

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

As you can see, we are setting up the PreserceReferencesHandling.Ojects. This will add the reference to object when circular dependencies are found.

This setting add values into the Json structure that in the format “$id”: “1” and instead of copying the object over and over (and creating a stack over flow), will use the syntax “$ref”: “1” to refer to the object. For example, if we have an object Player that contain the Team and the Team contains the players, than we could have circular reference. The serialization with the library and the PreserceReferencesHandling will produce something similar to the code below if we serialize a single player.

The C# code:

class Program
{
	static void Main(string[] args)
	{
		var p = new Program();
		
	}

	public Program()
	{
		var t1 = new Team()
					 {
						 TeamName = "MyTeam"
					 };
		var p1 = new Player
					 {
						 PlayerName = "Patrick"
						 ,PlayerTeam = t1
					 };
		var p2 = new Player()
					 {
						 PlayerName = "Melodie"
						 ,
						 PlayerTeam = t1
					 };
		t1.Players.Add(p1);
		t1.Players.Add(p2);

		var settings = new JsonSerializerSettings()
						   {
							   PreserveReferencesHandling = PreserveReferencesHandling.Objects
						   };
		string json = JsonConvert.SerializeObject(p1, settings);
		Console.WriteLine(json);
		Console.ReadLine();
		//Product deserializedProduct = JsonConvert.DeserializeObject<Player>(json);

	}
}

public class Player
{
	public string PlayerName { get; set; }
	public Team PlayerTeam { get; set; }
}

public class Team
{
	public string TeamName { get; set; }
	public List<Player> Players { get; set; } 
	public Team()
	{
		this.Players = new List<Player>();
	}
}

The result:

{
	"$id":"1",
	"PlayerName":"Patrick",
	"PlayerTeam":
	{
		"$id":"2",
		"TeamName":"MyTeam",
		"Players":
			[
				{
					"$ref":"1"
				},
				{
					"$id":"3",
					"PlayerName":"Melodie",
					"PlayerTeam":
					{
						"$ref":"2"
					}
				}
			]
	}
}

If instead your serialize the team you will get:

{
	"$id":"1",
	"TeamName":"MyTeam",
	"Players":
		[
			{"$id":"2","PlayerName":"Patrick","PlayerTeam":{"$ref":"1"}},
			{"$id":"3","PlayerName":"Melodie","PlayerTeam":{"$ref":"1"}}
		]
}

To conclude, you have to remember two things with Asp.Net MVC and Entity Framework. First, if you have not disabled proxy, than you will have this object serialized and it will cause problem when serializing. Second, you need to break those circular reference to stop the possibility of stack overflow. Using Json Newton library is simple and powerful when it came to handling references.

Enterprise Asp.Net MVC Part 2: Building The Model

This is part 2 of the enterprise Asp.Net MVC web application creation. We have before discussed about the project that we will develop and now we will work on the model. We will create all classes first.

If we remember the UML class diagram, we will have to create 5 classes. One for the Workout, one the for WorkoutSession, one for the Exercise, one for the Muscle and one for the MuscleGroup.

All these classes will be used to contain the business logic but also to contains the Entity from Entity Framework 5. Since we are building in Code First mode with Entity Framework, we have to develop all business logic (model) classes first then the database will be generated by Entity Framework ORM.

So far, if I translate the Model diagram into classes I have :

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

public class Workout:BaseModel
{
	public DateTime StartTime { get; set; }
	public DateTime EndTime { get; set; }
	public string Name { get; set; }
	public string Goal{ get; set; }
	public ICollection<WorkoutSession> Sessions { get; set; }
}

public class WorkoutSession:BaseModel
{
	public string Name { get; set; }
	public ICollection<Exercise> Exercises { get; set; }
}

public class Exercise:BaseModel
{
	public string Name { get; set; }
	public string Repetitions { get; set; }
	public string Weights { get; set; }
	public string Tempo { get; set; }
	public TimeSpan RestBetweenSet{ get; set; }
	public virtual Muscle Muscle { get; set; }
	public ICollection<WorkoutSession> WorkoutSessions { get; set; }
}

public class Muscle : BaseModel
{
	public string Name { get; set; }
	public virtual MuscleGroup Group { get; set; }
	public ICollection<Exercise> Exercises { get; set; }
}

public class MuscleGroup:BaseModel
{
	public string Name { get; set; }
	public ICollection<Muscle> Muscles { get; set; }
}

Indeed, I separate all these classes into individual file. Few modeling problem raised on my mind while I was writing those classes. First, every exercise need to be sorted for the user because every exercise are always done in a specific order. We need to add an Order property but we cannot add it to the Exercise class because the order will change depending of the workout session. For example, I may have the “Bicep Curl” exercise done in first on Monday and last on Friday. Also, we will create a directory of Exercise later so we need to have the “meta data” of exercise somewhere else from the exercise of the workout session. In fact, if we put out database glasses, this information would be in a junction table. If we put back our developer glasses, we will simply have a WorkouttSessionExecise that will have 1-1 relationship to an Exercise. So, let’s modify the model diagram and the class.


Modified Class Diagram for the Workout Planner Web Application

The modification need to be reflected into the classes.

public class WorkoutSession:BaseModel
{
	public string Name { get; set; }
        public ICollection<WorkoutSessionExercise> WorkoutSessionExercises { get; set; }
        public virtual Workout Workout { get; set; }
}

public class WorkoutSessionExercise:BaseModel
{
        public int Order { get; set; }
        public string Repetitions { get; set; }
        public string Weights { get; set; }
        public string Tempo { get; set; }
        public TimeSpan RestBetweenSet { get; set; }
        public virtual Exercise Exercise { get; set; }
        public virtual WorkoutSession WorkoutSession { get; set; }
}

public class Exercise:BaseModel
{
        public string Name { get; set; }
        public virtual Muscle Muscle { get; set; }
        public ICollection<WorkoutSessionExercise> WorkoutSessionExercices { get; set; }
}

As you can see, if have also moved the repetition, weight, tempo and all specific user/workout session information into something that will let the user add his information while having the Exercise class having the static information like the name of the exercise and the muscle concerned.

The BaseModel class is used to have similar information like the primary key which is an Integer. Later, other information will be added.

Validating the model

The next step is to add validation to the model. We could set it up to the setter of every property where we want to have some validation but we can also use the IValidateObject interface to let the ModelBinding system of Asp.Net MVC handle validation of every model object. If you want more information concerning the IValidationObject, I suggest you to go read this blog post about IValidationObject interface. In short, the ModelBinding will verify every Validate method of the model when bound back to the controller and it will also Validate the object before saving it into Entity Framework. So, we have double validation automatically execute by .Net Framework. This is a big advantage because we cannot forget to validate the model since the framework do it for us. To make it mandatory we will inherit the interface from the BaseModel class and create an abstract method that will be defined on every model. This way, we are sure that we will have model with validation defined.

public abstract class BaseModel : IValidatableObject
{
	public int Id { get; set; }

	#region IValidatableObject Members

	public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
	{
		return ValidateModel(validationContext);
	}

	#endregion

	protected abstract IEnumerable<ValidationResult> ValidateModel(ValidationContext validationContext);
}

All our model classes are modified to have the abstract method defined. Here is an example of a model class with validation and one that doesn’t have (yet) any validation logic.

public class Workout : BaseModel
{
	public DateTime StartTime { get; set; }
	public DateTime? EndTime { get; set; }
	public string Name { get; set; }
	public string Goal { get; set; }
	public ICollection<WorkoutSession> Sessions { get; set; }

	protected override IEnumerable<ValidationResult> ValidateModel(ValidationContext validationContext)
	{
		if (string.IsNullOrEmpty(Name))
		{
			yield return new ValidationResult("Name is mandatory", new[] {"Name"});
		}
		if (EndTime.HasValue)
		{
			if (StartTime > EndTime.Value)
			{
				yield return new ValidationResult("EndTime must be after the StartTime", new[] {"StartTime", "EndTime"});
			}
		}
	}
}

public class WorkoutSessionExercise : BaseModel
{
	public int Order { get; set; }
	public string Repetitions { get; set; }
	public string Weights { get; set; }
	public string Tempo { get; set; }
	public TimeSpan RestBetweenSet { get; set; }
        public virtual Exercise Exercise { get; set; }
        public virtual WorkoutSession WorkoutSession { get; set; }

	protected override IEnumerable<ValidationResult> ValidateModel(ValidationContext validationContext)
	{
		return new Collection<ValidationResult>();
	}
}

The first example show you some validation on the Name that need to be defined. It also validate the StartTime that must be before the EndTime. As you can see, the error will be displayed on both property if the error occur.

I also defined the EndTime as Nullable. This will let the user not enter a ending date to the workout, and for us, give us some scenario to test with nullable type.

The second example show you an example where we do not have any validation defined. It returns a simple empty collection (that must be inherit from IEnumerable).

Localized string

The last thing that bother me with this model is that for the moment, we take for grant that everything is in English all the time. In fact, the workout goal could be in the user language but the exercise name must be translated into the language of the user. In a previous blog post, we have discussed about a technique that can be used to have with Entity Framework multiple language handled automatically. It also doesn’t brake any object oriented theory. So, let’s apply now the modification to the model by changing some string into LocalizedString class.

To do, we will add this class :

[ComplexType]
public class LocalizedString
{
	public string French { get; set; }
	public string English { get; set; }

	[NotMapped]
	public string Current
	{
		get { return (string) LanguageProperty().GetValue(this); }
		set { LanguageProperty().SetValue(this, value); }
	}

	public override string ToString()
	{
		return Current;
	}

	private PropertyInfo LanguageProperty()
	{
		string currentLanguage = Thread.CurrentThread.CurrentUICulture.DisplayName;
		return GetType().GetProperty(currentLanguage);
	}
}

This class lets you have French and English for every LocalizedString defined. It will add a column in the database for French and one for English.

As you can see, the LocalizedString does have a ComplexType attribute which will tel Entity Framework to merge the property into the owner and not to create a relationship to a table called LocalizedString. For example, we will use LocalizedString with the name of Exercise. So the Exercise will have in its table Name_French and Name_English.

public class Exercise : BaseModel
{
	public LocalizedString Name { get; set; }
	public virtual Muscle Muscle { get; set; }
	public ICollection<WorkoutSessionExercise> WorkoutSessionExercices { get; set; }

	protected override IEnumerable<ValidationResult> ValidateModel(ValidationContext validationContext)
	{
		if (Name==null)
		{
			yield return new ValidationResult("Name is mandatory", new[] {"Name"});
		}
	}
}

As you can see, the Name property is now of type LocalizedString and we have modified the validation that now check if the name is defined.

Series Articles

Article #1: Asp.Net MVC Enterprise Quality Web Application
Article #2: Asp.Net MVC Enterprise Quality Web Application Model
Article #3: Asp.Net MVC Enterprise Quality Web Application Controller
Article #4: Asp.Net MVC Enterprise Quality Web Repository Layer
Article #5: Asp.Net MVC Enterprise Quality Web with Entity Framework
Article #6: Asp.Net MVC Enterprise Quality Layers
Article #7: Asp.Net MVC Enterprise Quality Web Security

Enterprise Asp.Net MVC Part 1: The Planification

As discussed before, a multi part posts will be published during the next weeks concerning how to develop enterprise web application with Microsoft Asp.Net MVC framework.

This first part will contains the project itself, the class diagram and the setup of the solution. The project will be iterative and incremental. We will establish the domain in this post, but we will enhance it during other parts. The reason we will do this is because in real life, the model change. We will start slowly and add stuff during the next week to finally have something done.

First of all, let define the project that we will create. Since I workout at the gym since a long time, I thought that we could build a gym workout planner. When people go to the gym, they have a plan of exercises for every group of exercise. Usually, trainer split every body part on multiple session during the week. So, in 1 week, you can go 4 times to the gym and train with 4 different workout. This is what we call a workout with 4 different session of exercise. Each session contains different exercises. Every exercise contains a name, a number of set and repetitions. It can also contain tempo which are at what time the exercise movement is done. While a set is the number of time you are doing the exercise, the repetition is the number of movement done every set of time. For example, you can have the exercise called “Leg Press” which are done 5 times (5 sets) of 10 repetitions (10 reps).

The Model in UML Class Diagram

If we try to translate this application into a static UML diagram, like the UML Class diagram we have something like below.

As we can see, we will have user that will be identified by the system which could have zero or many workout. Every workout will have at least one session (in the case a user want to do the same workout every training session) or could have multiple session (in case the user split his training in multiple session for example 4 different training per week). Workout session contain multiple exercise which are all associated to a muscle. Every muscle are grouped in group. For example, the bicep muscle and tricep muscle could be in the arm’s group. For the moment, let stay simple and not elaborate further more. Later, we will be able to give advice to user depending of objectives or muscles desired to train.

Creating a new Asp.Net MVC 4 project with Visual Studio 2012

New project screen in Visual Studio 2012

A new project is created with the MVC 4 project type. The next step is to select the MVC4 template to be applied with Razor View Engine.

Visual Studio 2012's project template screen.

I have selected the Unit Test project to be created cause as any serious enterprise project, we will unit test most of what we will develop. Not only it will secure us but it will ensure us to develop with interface and good habit.

From there, we are setup to start. We have multiple possibility. We could start by implementing Microsoft Membership straight from the beginning or we can start by doing the system for a single user. If we look at the model diagram, 5 classes on 6 are concerning everything but user account. I suggest that we start doing the application for a single user. By that I mean that will will remove the User class and develop everything for a single user for few times. The advantage will be that we won’t have to configure the Microsoft Membership with Entity Framework from the start and will remove some overhead. Also, if we do not have time to implement this part of the software, we will have something functional rapidly for at least one user.

Series Articles

Article #1: Asp.Net MVC Enterprise Quality Web Application
Article #2: Asp.Net MVC Enterprise Quality Web Application Model
Article #3: Asp.Net MVC Enterprise Quality Web Application Controller
Article #4: Asp.Net MVC Enterprise Quality Web Repository Layer
Article #5: Asp.Net MVC Enterprise Quality Web with Entity Framework
Article #6: Asp.Net MVC Enterprise Quality Layers
Article #7: Asp.Net MVC Enterprise Quality Web Security

How to handle multiple global constants in an application

The best way to have something organized and having constants in a single place is to have a class that will have inner class. This way, you can organize by theme your constants.

public static class GlobalConstants
{
	public static class Division1
	{
		public const string Const1 = "123";
		public const string Const2 = "qwe";
		public const string Const3 = "asdfgh";
	}

	public static class Division2
	{
		public const string Const1 = "123";
	}
}

Of course, it’s always better to have your constant in the class that they are more related. For example, the default value for a specific property of a class should be directly inside this class. But, for global constants that are used across the application, than having a global constants class can do the job.

Entity Framework 5.0 and Timespan type

Entity Framework version 5, like its previous version doesn’t map timespan. The following error will raise when you try to.

There is no store type corresponding to the conceptual side type ‘Edm.Time(Nullable=True,DefaultValue=,Precision=)’ of primitive type ‘Time’.

I thought that Entity Framework 5 was able with SQL Server 2008 R2 to map Timespan to Time. I was wrong. However, theirs a work around.

public Int64 TimeBetweenExercicesTicks{ get; set; }

[NotMapped]
public TimeSpan TimeBetweenExercices
{
    get { return TimeSpan.FromTicks(TimeBetweenExercicesTicks); }
    set { TimeBetweenExercicesTicks= value.Ticks; }
}

First, you should want to still use in your code the TimeSpan type because it’s convenient to manipulate time. But, on the other side Entity Framework doesn’t map the type. Fortunately, we can map the ticks and simply ignore the property with the TimeSpan type.

The example above show you this scenario where an entity required to have the time between two exercices. In fact, the TimeBetweenExercices is not mapped to the database but the underlying property TimeBetweenExercicesTicks. Since an Int64 can be mapped and that we do not loss any precision by converting ticks to/from timespan, that we can use this time.

How to add ReCaptcha to your Asp.Net MVC4 register form.

To prevent bot (automatic program that act like a human without being a real one) to register account to your website, you can use what we can captcha. Captcha is image that only human can read. They have letters that need to be input in a text box when the form is filled up. Today, I’ll show you how to implement ReCaptcha, a popular Captcha service that is totally free and owned by Google.

The first step is to register a API key for your website. You can go to http://www.google.com/recaptcha and create a new one. I suggest you to not check the check box of “Enable this key on all domains” to be able to debug with localhost. So, after this step, you will have a private and public key that will be required to use the ReCaptcha service.

The second step is to have library to access ReCaptcha. Inside your project, add the two following NuGet Package. One is the Recaptcha API service and the other one will give you Html helper.

The third step is to configure your project with the public and private key. This can be done by adding 2 appsettings in the web.config.

  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="RecaptchaPrivateKey" value="123nI9cSAAAAALtUefffnLRn2pWb7IpNrtOGQjzz" />
    <add key="RecaptchaPublicKey" value="123nI9cSAAAAAOH3eee3t1ZaZ6rRUwHQK4KMimfu" />
  </appSettings>

The forth step is to let know every page about the new library by adding the name space into the system.web configuration of the web.config.

  <system.web>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="Recaptcha" />
      </namespaces>
    </pages>

The fifth step is to add the control to the register form.

<li>
     @Html.Raw(Html.GenerateCaptcha())
     @Html.ValidationMessage("recaptcha")
</li>

The last step is to check if everything is fine from the controller side. This will be validated when the user will submit the form to the server.

[RecaptchaControlMvc.CaptchaValidator]
public ActionResult Register(RegisterModel model, bool captchaValid, string captchaErrorMessage)
{
    if (ModelState.IsValid)
    {
        if (!captchaValid)
        {
            ModelState.AddModelError("recaptcha", captchaErrorMessage);
            return View(model);
        }
//...

You need first to add the attribute that will call the server and do the validation. Second, you need to add 2 variables to the action that will tell you if the captcha is valid and the message. You can then check the value and display the form again if it’s wrong.

Nothing has to be done when developing into localhost (or 127.0.0.1) because ReCaptcha service allow developer to use for any key the localhost domain.

Behind the library

The first section was enough to let you implement ReCaptcha with your Asp.Net MVC 4 website. Now, let check a little bit the code behind the library. First, the html helper. This helper, create an instance of RecaptchaControl with the id “recaptcha”.

public static string GenerateCaptcha(this HtmlHelper helper)
{
  return RecaptchaControlMvc.GenerateCaptcha(helper, "recaptcha", "default");
}

public static string GenerateCaptcha(this HtmlHelper helper, string id, string theme)
{
  if (string.IsNullOrEmpty(RecaptchaControlMvc.publicKey) || string.IsNullOrEmpty(RecaptchaControlMvc.privateKey))
	throw new ApplicationException("reCAPTCHA needs to be configured with a public & private key.");
  RecaptchaControl recaptchaControl1 = new RecaptchaControl();
  recaptchaControl1.ID = id;
  recaptchaControl1.Theme = theme;
  recaptchaControl1.PublicKey = RecaptchaControlMvc.publicKey;
  recaptchaControl1.PrivateKey = RecaptchaControlMvc.privateKey;
  RecaptchaControl recaptchaControl2 = recaptchaControl1;
  HtmlTextWriter writer = new HtmlTextWriter((TextWriter) new StringWriter());
  recaptchaControl2.RenderControl(writer);
  return writer.InnerWriter.ToString();
}

This is quite interesting because when you validate your recaptcha you may want to add the error message next to it.

From the same code, we can see that the public and private key come from RecaptchaControlMvc… Those are two static string that get their value from the application setting of the web config file.

  public static class RecaptchaControlMvc
  {
    private static string publicKey = ConfigurationManager.AppSettings["RecaptchaPublicKey"];
    private static string privateKey = ConfigurationManager.AppSettings["RecaptchaPrivateKey"];

So far, nothing very hard to understand and we have two answers concerning the name of the control generated and the name of the setting used for the web.config.

The last interesting part is concerning the filter that we had to add to the action to validate the input of the user. This one is straight forward. It uses the RecaptchaValidator class to access the service and get a response from the ReCaptcha service. It then add the validation answer to the parameter. We have now our third answer concerning what are the parameter to add to the action.

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
	RecaptchaValidator recaptchaValidator = new RecaptchaValidator();
	recaptchaValidator.PrivateKey = RecaptchaControlMvc.PrivateKey;
	recaptchaValidator.RemoteIP = filterContext.HttpContext.Request.UserHostAddress;
	recaptchaValidator.Challenge = filterContext.HttpContext.Request.Form["recaptcha_challenge_field"];
	recaptchaValidator.Response = filterContext.HttpContext.Request.Form["recaptcha_response_field"];
	this.recaptchaResponse = !string.IsNullOrEmpty(recaptchaValidator.Challenge) ? (!string.IsNullOrEmpty(recaptchaValidator.Response) ? recaptchaValidator.Validate() : RecaptchaResponse.InvalidResponse) : RecaptchaResponse.InvalidChallenge;
	filterContext.ActionParameters["captchaValid"] = (object) (bool) (this.recaptchaResponse.IsValid ? 1 : 0);
	filterContext.ActionParameters["captchaErrorMessage"] = (object) this.recaptchaResponse.ErrorMessage;
	base.OnActionExecuting(filterContext);
  }

So that’s it for using a captcha to the register form of an Asp.Net MVC 4 application.

Asp.Net MVC4 AllowAnonymous

In Asp.Net MVC3 and before, if we wanted to make my default all action of controller to be secured we had to create a AllowAnonymous filter and to add a global filter which was requiring a valid authentification before accessing the action.

With Asp.Net MVC 4, it’s built in. You need to go inside the App_Start folder which contain the FilterConfig.cs file. Inside the FilterConfig.cs you will found what was inside the Global.Asax.cs : the static method RegisterGlobalFilters.

You need to add to this method the new folder called “AuthorizeAttribute”.

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new AuthorizeAttribute());
        }
    }

By now, all action require a valid authentification. If you want to allow anonymous person to see the action, you need to add the AllowAuthorize attribute to the action. In fact, it’s already been setup for the login and register method of the AccountController.cs.

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
	ViewBag.ReturnUrl = returnUrl;
	return View();
}

[AllowAnonymous]
public ActionResult Register()
{
	return View();
}

That’s it. Pretty simple and more secure!

How to add Javascript and CSS dynamically to your view with Asp.Net MVC4

In a previous post concerning how to add CSS and Javascript file dynamically depending of the action used, we have found a way to add those by setting a filter to the controller or the action of any controller. The problem with this approach is that it’s the controller who choose client side element. In fact, the controller should just tell what view to use and the use itself should be able to handle what CSS or Javascript to load. Of course, adding CSS/Javascript directly into the View ain’t the best solution because we want to put the CSS at the top of the Html header and we want to setup the Javascript at the bottom of the html.

This is where Asp.Net MVC section can shine.

Named Section

Asp.Net MVC have something called Named Section. It lets the developer setup optional placeholder inside the master page and if required, let the view inject some html code.

    ...
    <script type="text/javascript" src="@Url.Content("/Scripts/javascriptAlwaysLoaded.js)">
    @RenderSection("scripts", required: false)
</html>

The code above show you the idea of some code that could have been written to be in the master page. As you can see, we have 1 Javascript file hard coded, that will be loaded what so ever the page. This is good for JQuery or other Javascript file that require to be always there. Then, we have the RenderSection. RenderSection works a little bit like RenderBody(). We have set the parameter required to false, which mean that this place holder ain’t required if no script need to be registered.

The next step is to go into a view that need to have a specific script and to add the html to load this one. For example:

@section scripts
{
     <script type="text/javascript" src="@Url.Content("/Scripts/ABC.js")"></script>
}

Conclusion

I think this approach is better than the Filter one because it let you handle client side directly inside the view without having to modify the controller. It’s also not exactly to the controller the specify what design style (CSS) or script (Javascript) to display. In fact, the controller role is really to handle request and give a correct response to this one, not to implement detail for the view.

Automatic migration was not applied because it would result in data loss

When you are using Entity Framework and try to use the migration tool you may have this message.

Automatic migration was not applied because it would result in data loss

I had this error while doing this exact command inside the Package Manager Console.

Update-Database -Verbose

This happen because you have some data inside the table and the migration tool want to drop the table. This create a conflict for the migration tool and instead of taking the decision of deleting the data it show this error. If you are using the migration tool because you want to create the whole database and seed data with the seed method than you can force the table drop.

You simply need to use force.

Update-Database -Verbose -Force