Modifying BootStrap Tab Control for Extra Small Device

If you are using BootStrap and the Tab control you may have a weird rendering for Extra Small Device (under 768 pixel).
BootStrapTab
To fix this, it is possible for you to add this code. It removes the borders and remove the background.

/*For smaller device, tab control should not appear*/
@media (max-width: 767px) {
    .nav-tabs > li {
        float:none;
        border:1px solid #dddddd;
    }
    .nav-tabs > li.active > a{
        border:none;
    }
    .nav > li > a:hover, .nav > li > a:focus,
    .nav > li > a:hover, .nav > li > a:focus,
    .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus
     {
        background:none;
        border:none;
    }
}

BootStrapTabFixed

The end result is much better than the default behavior and the solution is simple and clean. I hope that it helps someone.

How to use Entity Framework with a list of Value Objects

A value object can be anything that would be in an enum in C#. However, we have this one in the database since it is an entity. The difference is that inside the code you have the id and description. This way, we have a fast access in the code without requiring to go in the database and we have a strong database that has all foreign key to the value object class. Even if Entity Framework supports Enum, it is not strongly typed inside the database. The database does not have a foreign key so it could be possible to set a value that would not be in C#.

Because of how Entity Framework works, we cannot simply have an entity to have a list of value objects. This would produce Entity Framework to set the entity id into the value object table. The desired effect is to have only one entry per value object. For example, I have a Contest entity that has a list of possible Stock Market. I want the value object, Stock Market to have in its table all possible stock exchange market and not have duplicate for different contest.

To fix this problem, we need to create an association table that will act has a association table in the database.

ContestMarket

Concerning Entity Framework, we need to specify the new entity in the configuration. We need to specify that its primary key is the combination of both primary key (Contest and Market). It would also be able to add additional property for the association like having a date. This association can be set by setting a key with an anonymous object.

    public class ContestMarketConfiguration : AssociationConfiguration
    {
        public ContestMarketConfiguration(): base(Constants.SchemaNames.Contest)
        {
            this.HasKey(c => new {MarketId = c.MarketId, ContestId= c.ContestId});
        }
    }

It is not required to specify the name of the property (MarketId, ContestId) but it is required to have these property directly inside the Entity. The following code does not work:

    public class ContestMarketConfiguration : AssociationConfiguration
    {
        public ContestMarketConfiguration(): base(Constants.SchemaNames.Contest)
        {
            this.HasKey(c => new {MarketId = c.Market.Id, ContestId= c.Contest.Id});
        }
    }

This is unfortunate because you have to play with the Model to had additional property just for the association. The entity looks like this:

public class ContestMarket
{
    public Contest Contest { get; set; }
    public int ContestId { get; set; }
    public MarketType Market { get; set; }
    public int MarketId { get; set; }
}

The Contest entity has a Collection of ContestMarket and the MarketType does not have anything. This way, this one can be used anywhere even without the Contest context.

Using AutoMapper to Map Abstract Classes

AutoMapper lets you map from one class to another class your object. It works fine until you want to map from a class to an abstract class. The reason is that AutoMapper instantiates the desired class type and since an abstract class cannot be instantiate will crash.

//Mapping
Mapper.CreateMap<SelectorItem, OrderType>()
//Use the mapping
var model = AutoMapper.Mapper.Map<SelectorItem, OrderType>(viewModel);

The code create the map from SelectorItem that is a normal class and OrderType that is an abstract class. The use of this map will not work. To fix this problem the mapping configuration must be changed to specify to AutoMapper how to instantiate the OrderType class, the abstract class.

Mapper.CreateMap<SelectorItem, OrderType>()
      .ConstructUsing(OrderTypeCreator);

The mapping requires the use of ConstructUsing method that has two signatures.

IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor);
IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor);

The first one is easy to use. It takes a method that has the source which is the class we start with and return a destination class that is the abstract class.

private OrderType OrderTypeCreator(SelectorItem arg)
{
     return OrderType.GetFromId(arg.Id);
}

This example takes from the concrete class the ID and use a factory to return the correct concrete class that inherit form the abstract OrderType class.

This way, we have AutoMapper that can map to abstract Class without problem.

Complex Type cannot have reference to entities

If you have a complex type, you cannot have within this one any reference to other entities. Let’s imagine that I have a money class.

    public class Money
    {
        public decimal Value { get; set; }
        public CurrencyType Currency { get; set; }
    }

Has you can see, it has a reference to another class, named CurrencyType. This type is abstract and must be set to a Currency class like USD or CND. However, this bring Entity Framework with a ModelValidationException.

System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

DataAccess.Contexts.Implementations.CurrencyType: Name: Each type name in a schema must be unique. Type name ‘CurrencyType’ is already defined.

It is not possible to have this configuration. It would be very practical because you can have the Money in any of you class and the table would have the Money_Value and Money_CurrencyId.

One option is to remove the currency from the Money or to have both property of the Currency class inside the Money class. However, the strong positive that we had with CurrencyType was that this one was using Value Object pattern. This mean that it was strongly typed in the code and had a reference to a Currency table which had USD and CDN currency.

The question is how to use Entity Framework and still have an association between the amount of the money (value) and the currency without losing the strongly association with the table that has all currencies? This lead us to a second option that is to remove the money from the entity that has the money. Instead of having the money directly into the class, you can have all money into a separated table. This remove the use if complex type on the money table. Of course, this cause some overhead by having more tables and more joins to do to get all the information. It also has the problem of having the ID of the Money inside your Entity.

A possible solution that I have used is to loss the strong Foreign Key but still have the data directly into the entity that use the money. This way, less tables, more speed, and in the code we use the value object pattern. Here is the money class and the value object class for currency.

public class Money
{
	public decimal Value { get; set; }
	public int CurrencyTypeId {
		get { return this.Currency.Id; }
		set { this.Currency = CurrencyType.GetCurrencyFromId(value); }
	}
	///
/// This is ignored by EntityFramework
	///
	public CurrencyType Currency { get; set; }
}

public abstract class CurrencyType : ValueObject
{

	public static readonly CurrencyType Canada = new CanadianCurrency();
	public static readonly CurrencyType UnitedStatesOfAmerica = new USACurrency();

	public static CurrencyType GetCurrencyFromId(int value)
	{
		Type type = typeof(CurrencyType);

		var fields =  type.GetFields(BindingFlags.Public | BindingFlags.Static);
		foreach (var field in fields)
		{
			var fieldValue = field.GetValue(null) as CurrencyType;
			if (fieldValue != null)
			{
				if (fieldValue.Id == value)
				{
					return fieldValue;
				}
			}
		}
		throw new KeyNotFoundException(string.Concat(value, " cannot be found in any static fields."));
	}
}

As you can see, the money class does have the value and the CurrencyType property. This property is ignored by Entity Framework so Money can be as Complex Type. However, we have an integer field that can be used but should not since we have a strongly typed currency property. Here is how to make it works with Entity configuration.

public class MoneyConfiguration : ComplexTypeConfiguration
{
	public MoneyConfiguration()
	{
		this.Ignore(d => d.Currency);
	}
}

How to use this money class? The best way is to check the unit tests.

[TestMethod]
public void GivenAnInteger_WhenIntegerIsAKeyOfACurrency_ThenReturnConcreteCurrency()
{
    // Arrange
    var idOfCanada = CurrencyType.Canada.Id;
    var expected = CurrencyType.Canada;

    // Act
    var found = CurrencyType.GetCurrencyFromId(idOfCanada);

    //Assert
    Assert.IsInstanceOfType(found,typeof(CanadianCurrency));
    Assert.AreEqual(expected.Id,found.Id);
}

This is required because when we will load from Entity Framework, we will only get the integer. But, in the business logic the code will use the property. This is why the property of CurrencyTypeId is tightly bound with Currency with the reflection code. In the case that the Id is not legit (does not exist), an exception is thrown. This should never occur but we should still test the case.

[TestMethod]
public void GivenAnInteger_WhenIntegerIsNotAnExistingKeyOfACurrency_ThenThrowException()
{
    // Arrange
    const int idNonExisting = -1;

    // Act & Assert
    TestExtensions.Thrown(() => CurrencyType.GetCurrencyFromId(idNonExisting));
}

UnitTestPassed
To conclude, this might not be the best solution since it would be cleaner not to have this integer in the class. It would also be better not to have this integer without a foreign key to the CurrencyType table. However, since the value will be filled up and handled by Entity Framework only, we still control the integrity with the code. It would be possible for us to add manually the foreign key too.

Registering with Microsoft Unity an interface to a concrete class with multiple constructors

If you are using inversion of control, you may come into the scenario that you want to register your interface to a concrete class that has multiple constructors. Registering with Microsoft Unity an interface to a concrete class with multiple constructors is something that require to specify to Unity which of the constructor to use.

container
    .RegisterType<IMainDbContext, MainDbContext>();

The code above can work if MainDbContext has only one constructor. Even if this one require several parameters, it does not matter. Unity will try to solve every parameters. However, in the case that MainDbContext has several constructor, Unity does not know which one to evaluate. Well, that is not totally true. In fact, Microsoft Unity try the one with the most parameters. This can be problematic if you have more than one parameter with the same amount of parameters.

To select which constructors you have to use the InjectionConstructor class. This class allows to specify parameters type. You can use the ResolvedParameter that is generic. You can specify for every parameters the type you want.

container
     .RegisterType<IMainDbContext, MainDbContext>(
        new InjectionConstructor(
            new ResolvedParameter<IRunningContext>()
        )
     );

As you can see, this indicate to Microsoft Unity to resolve the IRunningContext from its container to inject the object into the single parameter constructor of MainDbContext. In that case, we take the single constructor of MainDbContext that has its parameter of IRunningContext.

Asp.Net Bind Attribute for your Controller

Asp.Net MVC gives you the possibility to control the flow of information between Html Form and .Net Controller. It is possible to have model classes that are bound to Html Forms but without desire them to be sent back from forms.

A simple use case can be that we have a user model class that has a “IsAdmin” property. The user class can be bound to an html form, and instead of having a EditorFor for this property, a simple DisplayFor is set. An hacker could create an hidden field inside the form with the name “IsAdmin” and send “True”. Once the form is submitted, the “IsAdmin” will be bound because the Model Binding maps every form name fields to properties of the class.

Asp.Net MVC lets you specify which properties that is allowed to be bound from a form OR which properties that should never be read from the HTML form. This is also called white listing properties or black listing properties.

To demonstrate you this feature, I have create a simple model class that has 5 properties which can be nullable. These properties are all bound to an Html Form. For the purpose of this exercise, they are all bound to text boxes. In fact, as mentioned, some could not have been bound to a editable control and some one could forge the post later on. The first example send all properties back to the controller, and the controller set all information info a view bag and show again the view. The view should be filled up with the view bag information.

Here is all steps.
AspNetMVCControllerBind

If property1 and property2 should not be bound from the form, we need to blacklist them. To tell the Asp.Net MVC Model Binding to not use properties, the attribute Bind must be used with the property Exclude.

In this screenshot, you can see that the property 1 and property 2 is not inside the view bag. The reason is that the model binder does not set the value to the model which kept the value to the default one. Since the model are nullable int for all properties, the default value remain NULL.

AspNetMVCControllerBindExclude

Finally, another scenario is available to white list properties. This option is interesting if you do have a lot of properties to exclude. Instead of having to specify a lot of properties in the exclude field, you just need to specify few in the Include field.

AspNetMVCControllerBindInclude

You can everything discussed in this blog post by download my Asp.Net MVC Bind project on GitHub

Asp.Net MVC Model Validation

I have played around with Data Annotation and IValidatableObject interface. As you may know, these are the two officials way to validate your model. The Data Annotation and the Validate method of the interface IValidatableObject are used when the model binding is executing during the post from the web page to the controller and also when saving with Entity Framework. It is also possible to manually execute the validation manually.

The problem I have encounter was during unit test. If you do the test by yourself you will see that if something is wrong with Data Annotation that the Validate method is not even called. The reason behind this behavior is that Data Annotation are for light validation like if a field is required. If this one is not required, than it does not make sense to go to the Validate method because it will fail further validations. This is quite true but not interesting if you want to have all possibles errors of the object.

Another issue that I had with Data Annotation is that if you do have annotation in a property of your first model class, than they are not validated. A small test that show this behavior is this unit test:

[TestClass]
public class UnitTest1
{
	[TestMethod]
	public void TestMethod2()
	{
		var s = new Annot1();
		var results = s.Validate();
		Assert.AreEqual(2, results.Count());
	}
}

public class Annot1:BaseClass2
{
    public Annot1()
    {
        Annot1Property3 = new Annot2();
    }

    public string Annot1Property1 { get; set; }
    public string Annot1Property2 { get; set; }
    public Annot2 Annot1Property3 { get; set; }
  
}

public class Annot2 : BaseClass2
{
    [Required]
    public string Annot2Property1 { get; set; }
    [Required]
    public string Annot2Property2 { get; set; }
 
}

public abstract class BaseClass2
{
    public IEnumerable<ValidationResult> Validate()
    {
        var results = new List<ValidationResult>();
        var validationContext = new ValidationContext(this, null, null);
        Validator.TryValidateObject(this, validationContext, results, true);
        return results;
    }
}

This test fails even we can should expect to have two with the class Annot2 and its two required field.

How can you have validation from Data Annotation from every inheritance levels and having at the same time every validate method to be executed, even if the field is not there? You need to create your own Validate method that will call the TryValidateObject on every inheritance level. Here is an example that show how to use the base model class that has a validate method. It has the advantage that we can call the validate at each level of inheritance but also just call the base class which will go deeper to validate everything.

public abstract class BaseClass
{
    public IEnumerable<ValidationResult> Validate()
    {
        var results = new List<ValidationResult>();
        var validationContext = new ValidationContext(this, null, null);
        Validator.TryValidateObject(this, validationContext, results, true);
        var r = new List<ValidationResult>(results);

        if (this is IValidatableObject)
        {
            IEnumerable<ValidationResult> errors = (this as IValidatableObject).Validate(new ValidationContext(this));
            r.AddRange(errors);
        }
        var childrenResults = ValidateChildren();
        r.AddRange(childrenResults);
        return r;
    }

    public abstract IEnumerable<ValidationResult> ValidateChildren();

}

public class Class1 : BaseClass, IValidatableObject
{
    public Class1()
    {
        Property1 = new Class2();
    }
    public Class2 Property1 { get; set; }
    [Required]
    public string AString1 { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        return new[] {new ValidationResult("Error from class1")};
    }

    public override IEnumerable<ValidationResult> ValidateChildren()
    {
        var r = new List<ValidationResult>();
        var childrenResult = Property1.Validate();
        r.AddRange(childrenResult);
        return r;
    }
}

public class Class2 :BaseClass, IValidatableObject
{
    public Class2()
    {
        Property2 = new Class3();
    }
    public Class3 Property2 { get; set; }
    [Required]
    public string AString2 { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        yield return new ValidationResult("Error from class2");
    }

    public override IEnumerable<ValidationResult> ValidateChildren()
    {
        var r = new List<ValidationResult>();
        var childrenResult = Property2.Validate();
        r.AddRange(childrenResult);
        return r;
    }
}

public class Class3:BaseClass
{
    [Required]
    public string AString3 { get; set; }

    public override IEnumerable<ValidationResult> ValidateChildren()
    {
        return new List<ValidationResult>();
    }
}
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var s = new Class1();
        var results = s.Validate();
        Assert.AreEqual(5, results.Count());
    }
}

This works. You can call the validate directly to Class3 and have 1 validation result. But the main objective is to call the validation on Class1. Class1 has a property that use Class2 and this one has Class3. Three level deeps! The code is not clean because it has some repetition but the problem is solved. Every ValidateChildren call all property that has a class that must be validated. It accumulates all validation results and return it. The validate method explicitly calls the Validate method so even if the Data Annotation has error, this one is executed.

You can find all unit test code in this GitHub Repository.

Asp.Net MVC Login with email instead of UserName with Identity

I found very strange that it is not a simple task to login with an email in Asp.Net MVC. You cannot simply decide what property is the identifier. Asp.Net MVC decides for you that it is the UserName property.

Here is a the IdentityUser class from Microsoft.AspNet.Identity.EntityFramework.

namespace Microsoft.AspNet.Identity.EntityFramework
{
  public class IdentityUser : IUser
  {
    public virtual string Id { get; set; }
    public virtual string UserName { get; set; }
    public virtual string PasswordHash { get; set; }
    public virtual string SecurityStamp { get; set; }
    public virtual ICollection<IdentityUserRole> Roles { get; private set; }
    public virtual ICollection<IdentityUserClaim> Claims { get; private set; }
    public virtual ICollection<IdentityUserLogin> Logins { get; private set; }
    public IdentityUser()
    {
      this.Id = Guid.NewGuid().ToString();
      this.Claims = (ICollection<IdentityUserClaim>) new List<IdentityUserClaim>();
      this.Roles = (ICollection<IdentityUserRole>) new List<IdentityUserRole>();
      this.Logins = (ICollection<IdentityUserLogin>) new List<IdentityUserLogin>();
    }
    public IdentityUser(string userName): this()
    {
      this.UserName = userName;
    }
  }
}

The first step to use email is to add an email property to this class. Microsoft Identity team has not sealed the class, so it is possible to inherit from it and add you own property. This will extend what we can do with Identity.

public class ApplicationUser : IdentityUser
{
    public string Email { get; set; }
}

That’s it for the model. Entity Framework will use this class instead of the default one if you define you DbContext with a special class.

public class MainDbContext : IdentityDbContext<ApplicationUser>{//...}

That is what is required. This create in the background a DbSet of your class that inherit from IdentityUser. I have called mine ApplicationUser, but you can use whatever you prefer. IdentityDbContext override the OnModelCreating. This is important that if you inherit from it that you call the base class to still have all the configuration provided by the IdentityDbContext. To be more detailed, the OnModelCreating associate the custom class to AspNetUsers table. It does plenty of others thing, but from what it concerns us right now, this is it. From here, if you instruct Entity Framework to build your database, you should see in the database your field in Identity table.
AspNetUserEmailProperty

The next step is to change the View Model and the View. The View Model for the registration use an UserName property. We can remove this and add one for Email.

public class RegisterViewModel
{
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [Display(Name="Email")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}

This is the place where you can add additional data annotation to have more validation. Then, we need to change the view that use the Register View Model. We need to remove the username form group to add a new one for email.

 <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>

The last step is to change the controller to do something with the email and username. Since Identity still use username and password combination than we have to trick the system.

First of all, we need to generate a user name from the email. It is not possible to use directly the email because it has some invalid characters like @. You can have a small method that transform the user name.

public string GenerateUserName(string email)
{
    return email.Replace("@", "").Replace(".", "").Replace("-", "");
}

From here, you can create a new ApplicationUser and assign your generated user name into the property. The next code remains the same by calling the UserManager.

Second, we need to modify the login because user will enter an email and you need to transform it to user name. The login ViewModel needs to be changed.

public class LoginViewModel
{

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name="Email")]
    public string Email { get; set; }
    
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

The view also change by not having input for an username but for an email. This is the same way we have done for the registration page. I will not put the code here to keep it simple.

Finally, the controller must be changed too. Not a lot of thing need to be changed but since we ask for an email and that the system use a username than we must convert it.

var user = await userService.FindAsync(GenerateUserName(model.Email), model.Password);

In conclusion, it requires some manipulation but it is not difficult. It would be cleaner not to manipulate the UserName property but it is still not a nightmare to proceed.

Concerning the user name

The algorithm that generate the user name is not strong. Collision can occur if you have the concatenation this way. This is not a huge deal since it will fail to save in the database but still a better way is to have something unique. To save character like @ as user name, the framework allows you to configure the UserManager to have not only alphanumeric characters.

public UserManager(IMainDbContext dbContext)
{
	var dbMainContext = dbContext.GetDbContext();
	this.userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbMainContext));

	//Allow to have email in the username
	this.userManager.UserValidator = new UserValidator<ApplicationUser>(this.userManager)
	{
		AllowOnlyAlphanumericUserNames = false
	};
}

As you can see, you can set a new UserValidator and set the AllowOnlyAlphanumericUserNames to false. This is way better!