How to add an Area with Visual Studio for Asp.Net MVC project

Adding an area can be done manually by adding a folder inside your Web Site project under the Areas folder. From there you can add a folder for your controller. However, a better way exist that create for your the area with all folders required. It also add the _ViewStart.cshtml for you. If you right click the Areas folder you will not find anything related to Add Area.

NoArea

Everything is hidden in the contextual menu of the website project.
Area

This will add for you your area. If not Areas folder exist, it will add it for your. It will also take care to register the area with the map route.

Failed to initialize the PowerShell host

During the migration of Entity Framework to 6.1.0 I received an error about PowerShell host that failed to initialized.

Adding ‘EntityFramework 6.1.0’ to BusinessLogicUnitTest.
Successfully added ‘EntityFramework 6.1.0’ to BusinessLogicUnitTest.
Executing script file ‘C:\Users\Patrick\Documents\TFS\BourseVirtuelle\Code\BourseVirtuelle\packages\EntityFramework.6.1.0\tools\install.ps1’.
Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.

The problem was the system has it executions policy to restrictive. One way to fix the problem is to open a PowerShell console as administrator and to set the execution policy to unrestricted.

Set-ExecutionPolicy Unrestricted

PowerShellSetExecutionPolicy

From there, open again Visual Studio 2013 and open the Package Manager Console. This was also required before using Nuget to update Entity Framework. Opening the Package Manager Console seem to execute a Power Shell script named Profile.ps1 located in your Program Files folder.

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\b331wcwx.fbh\Modules\NuGet\Profile.ps1

How to use Asp.Net DisplayFor or EditorFor within a loop

You can use the Html Helper to use the template system of Asp.Net MVC. You can have @Html.DisplayFor and @Html.EditorFor. The first one is to display the information into a read only control and the latter is the control that allow to modify the value. Both takes as parameter a Lambda expression of the view Model. Without going into too much detail about where DisplayFor or the EditorFor take their file, just remember that it searches for a folder EditorTemplates or DisplayTemplates in the directory where the view use one of these helpers first and then it goes check for Views>Shared>DisplayTemplates or EditorTemplates.

DisplayForLoop

But, what if you want to use one of these two method within a loop to show value of a collection inside your model? This collection is from another type of the model and you cannot select from the Lambda expression items within a collection but only property of the model? The trick is to use Lambda for the current page model but not using any of the property. Instead, simple choose the variable your want to use the template item.

<tbody>
	@{
		foreach (var contestListItemViewModel in Model.Contests)
		{
			<tr>
				<td>@Html.ActionLink(contestListItemViewModel.Name.Current, "Edit", "Contest", new { Area = Constants.Areas.ADMINISTRATOR, id = contestListItemViewModel.Id }, null)</td>
				<td>@Html.DisplayFor(d => contestListItemViewModel.StartingTime.ToShortDateString())</td>
				<td>@Html.DisplayFor(d => contestListItemViewModel.EndingTime.ToShortDateString())</td>
				<td>@Html.DisplayFor(d => contestListItemViewModel.InitialCapital)</td>
				<td>@Html.DisplayFor(d => contestListItemViewModel.IsUsingStockRules)</td>
				<td>@Html.DisplayFor(d => contestListItemViewModel.IsUsingShortRules)</td>
				<td>@Html.DisplayFor(d => contestListItemViewModel.IsUsingOptionRules)</td>
			</tr>
		}
	}
</tbody>

As you can see, the code in this example is inside a foreach and I can use the DisplayFor Html Helper. The variable for the expression is “d” but I do not use the “d” variable. Instead, I am using the variable that is populated by the foreach “contestListItemviewModel”.

This is the simplest way to use the powerful reusable template system within a loop in Asp.Net MVC.

How to make a Asp.Net MVC HtmlHelper that use generic work with Razor

If you create a Html Helper with Asp.Net MVC that take a generic type, you may stumble into a problem when using it. An error concerning compilation of the page when executing raise with a yellow screen of death.

An exception of type ‘System.Web.HttpCompileException’ occurred in System.Web.dll but was not handled in user code Compiler Error Message: CS1502: The best overloaded method match for ‘System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)’ has some invalid arguments

This code is the result of simply calling this line:

@Html.Test<ContestListItemViewModel>() //Does not work

The Html Helper is very simple.

public static MvcHtmlString Test<TEntityType>(this HtmlHelper htmlHelper)
{
        return new MvcHtmlString("<p>Test</P>");
}

To make it works, you have to have it inside a Razor statement like this:

@{
    var x = Html.Test<ContestListItemViewModel>();
    @Html.Raw(x);
}

The problem is it is not very clean. However, it is possible to fix this with a single line statement if you wrap the Html Helper within parentheses.

@(Html.Test<ContestListItemViewModel>())

How come? Well, Razor become confused if it has to render the result with Html or with C# variable because of the ContestListItemViewModel that is interpreted as Html. Adding parentheses help Razor to generate the Html output and remove the confusion, which remove the error.

How to quickly initialize a C# Dictionary in one line

I stumble into a situation where I had to fill up a dictionary but desire not to use the .Add method. The case appears to be frequent if you are using Help Helper of Asp.Net MVC. The reason is that if you want to add html attribute by Html Helper than you have to provide a dictionary of key-value that represent the attribute name and attribute value.

Here is a class that represent a simple scenario.

public class ColumnHeader
{
    public IDictionary<string, string> Attributes { get; set; }
}

If you want to initialize the property, than you can use new but also to double the curly braces.

var col = new ColumnHeader{Attributes = new Dictionary<string, string>{{ "attribute1","value1"}}};

This is an example about how to add a single value into the dictionary. As you can see, we have a first curly brace to initialize the property itself and then we have the double curly brace that initialize the dictionary and the key value. If we wanted to initialize two items, we could by adding a comma after the curly brace for the key value.

var col = new ColumnHeader{Attributes = new Dictionary<string, string>{{ "attribute1","value1"},{ "attribute2","value2"}}};

Nothing more to said. Initializing a dictionary with C# without having to initialize it with the empty constructor and then adding individually every key-value is very straightforward.

Asp.Net Editor Template with BootStrap for Currency Field

If you are developing an application that require to have money, they are big change that this money must be in a currency. So, every time you have to select a money, you have to select the currency too. A design pattern is to have a class that represent the money instead of using a decimal directly.

For example.

public class Contest
{
    public Money InitialCapital { get; set; }
}

public class Money
{
	public Money()
	{
		Currency = CurrencyType.Canada;
	}

	public decimal Value { get; set; }
	public int CurrencyTypeId {
		get { return this.Currency.Id; }
		set { this.Currency = CurrencyType.GetFromId(value); }
	}
	/// <summary>
	/// This is ignored by EntityFramework
	/// </summary>
	public CurrencyType Currency { get; set; }
}

This code use the pattern Value Object for all currencies. This is why it has additional code that you may not need. In fact, what is important is the the Money class has the money itself inside the Value property and then the currency inside CurrencyType property.

From there, you have the View Model that is different. This is a good example of why having a view model is important. The view model will have the whole list of existing and possible currency that the user can choose from. This is not the type of information that you should have in your model since the model should represent the reality. The view model should look this way:

public class ContestViewModel
{
    [UIHint("SelectorForMoneyViewModel")]
    public SelectorForMoneyViewModel InitialCapital { get; set; }
}

The SelectorForMoneyViewModel is a simple class that has the Money and the list of available currencies.

public class SelectorForMoneyViewModel
{
	public MoneyViewModel Current { get; set; }

	public List<SelectorItem> AvailableCurrencies { get; set; }

	public SelectorForMoneyViewModel()
	{
		this.Current = new MoneyViewModel();
		this.AvailableCurrencies = new List<SelectorItem>();
	}
}

From there, the Editor Template can use this list and put the whole list into the currency drop down. The result should look like the following picture. The first image is the control when not open and the second picture when the user click the currency field.

BootStrapperCurrency1

BootStrapperCurrency2Open

This is possible with the use of BootStrap but can be reproduced without it. I am using BootStrap because because it is available by default with Asp.Net MVC since version 5.

@model ViewModel.Selectors.Implementations.Money.SelectorForMoneyViewModel

<div class="input-group">
    @Html.EditorFor(viewModel => viewModel.Current.Value)
    @Html.HiddenFor(viewModel => viewModel.Current.Currency.Id)
    <div class="input-group-btn">
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">@Model.Current.Currency.DisplayText<span class="caret"></span></button>
        <ul class="dropdown-menu pull-right">
            @foreach (var currency in Model.AvailableCurrencies)
            {
                <li><a href="#" data-id="@currency.Id">@currency.DisplayText</a></li>
            }
        </ul>
    </div><!-- /btn-group -->
</div><!-- /input-group -->

First of all, we need to setup an hidden field to set the value of the selected currency. This would require some JavaScript to set from the the dropdown value into the hidden field that will be sent to the server. The first EditorFirst is important because it shows the value. The rest of the code is the drop down that is set at the right of the textbox of the decimal value.

Here is the Javascript that must be used for every pages that has the component.


//For each link that is inside a FORM when used as DropDown-Menu Item we want to be able
//to click an element and set this one as the visual one. We also set the value of the selected
//item into the hidden field of the selected dropdown to have this value pushed to the server.
$('form').on('click', '.dropdown-menu>li>a',
    function () {
        return dropdownMenuLinkAction($(this));
    }
);

//@description: Dropdown menu for a choice
//@param link: a link that must be under the dropdown-menu
function dropdownMenuLinkAction(link)
{
    //Current link information
    var htmlLink = $(link);
    var clickedId = htmlLink.attr('data-id');
    var clickedDisplayName = htmlLink.html();
    var controlContainer = htmlLink.closest('.input-group');
    //Change the hidden field (should only have one)
    controlContainer.find(':hidden').each(
        function () {
            $(this).val(clickedId);
        }
    );
    //Change the visual of the dropdown (should only have one)
    controlContainer.find('.dropdown-toggle').each(
        function () {
            var htmlDropDown = $(this);
            var currentFullHtml = htmlDropDown.html();
            var toRemove = htmlDropDown.text();
            var toWriteBack = currentFullHtml.replace(toRemove, "");
            htmlDropDown.html(clickedDisplayName + " " + toWriteBack);
        }
    );
    $(this).dropdown("toggle"); //Close the menu once clicked
    return false;
}

It attaches to every form that has a dropdown an action that is linked into each link of the drop down. This action takes the information set into the html attribute data-id to be able to move it into the html hidden field. The second part is to update the dropdown label to display the selected currency to the control when this one is closed.

Inline Razor Helper instead of Html Helper for you Asp.Net MVC WebSite

In Asp.Net MVC you have two ways to create code that can be reusable within your page, or editor template or display template. Asp.Net MVC call these reusable mechanim Helpers. You can create Html Helper or Razor Helper. They are both generating Html but in a different way. The first one is independant of any rendering engine, while the second one use only Razor. One comes with several helpers already created for you, like Html.ActionLink, Html.LabelFor, Html.EditorFor when the second one does not have any developed for you. However, the last one can use the first one. This is not true the other way around.

Let see the first one, Html Helper. It is more popular than the other one. It is coded in C# (of VB.Net) and is in fact an extension to HtmlHelper. You just have to create a static class with a static method that extend System.Web.Mvc.HtmlHelper. Here is a small example.

using System.Web.Mvc;

namespace TestHtmlHelper.HtmlHelper
{
    public static class MyCustomHtmlHelper
    {
        public static MvcHtmlString MyFirstHelper(this System.Web.Mvc.HtmlHelper htmlHelper)
        {
            return new MvcHtmlString("
Test

");
        }
    }
}

If you want to use this extension, you just have to use the @Html keyword in any of your view or template.

@using TestHtmlHelper.HtmlHelper
<div>@Html.MyFirstHelper()</div>

This will render :

<div>
Test
</div>

This is not impressive, but in fact, these helper can be very useful when you specify a property, like for @Html.TextBoxFor(model=>model.MyDate). This can use reflection to get the display name which can be added in the helper to create a label to add it or to check the type to render something depending of the property type. It goes beyond just outputing static Html.

Let’s create a simple Html Helper that take a object in parameter where we can sepecify which property to display. We will do something simple that set the name of the property into an header tag and its value inside a paragraph.

namespace TestHtmlHelper.HtmlHelper
{
    public static class MyCustomHtmlHelper
    {
        public static MvcHtmlString MyFirstHelper(this System.Web.Mvc.HtmlHelper htmlHelper)
        {
            return new MvcHtmlString("

Test

");
        }

        public static MvcHtmlString YourGenericHelperFor<TModel, TProperty>(this HtmlHelper htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var propertyName = metadata.PropertyName;
            var value = metadata.Model;
            return new MvcHtmlString(string.Format("<h1>{0}</h1><p>{1}</p>", propertyName, value));
        }
    }
}

As you can see, the Html Helper does not know about how the model class is made from. It just knowns that it takes by parameter an expression where we will get by reflection the property and its value. The use of this method is like the TextBoxFor Html helper.

@model TestHtmlHelper.Models.MyModel
@using TestHtmlHelper.HtmlHelper
<div>@Html.MyFirstHelper()</div>
<div>@Html.TextBoxFor(d => d.Name)</div>
<div>@Html.YourGenericHelperFor(d => d.Name)</div>

The result is previsable as you can see:

<div>
Test</div>
<div><input id="Name" type="text" name="Name" value="This is a test name" /></div>
<div>
<h1>Name</h1>
This is a test name</div>

Before going into the Razor Html Helper, you can see that inside the Html Helper I am concatenating string to have my end result. This is only possible in simple scenario. Otherwise, it becomes a mess. This is why you can use Html classes to help you rendering your output. In fact, the Html Helper we just created should be coded this way:

public static MvcHtmlString YourGenericHelperPropertyConstructedFor<TModel, TProperty>(this HtmlHelper htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
    //Get values
    var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var propertyName = metadata.PropertyName;
    var value = metadata.Model;
    //Html Construction
    var header = new TagBuilder("h1") {InnerHtml = propertyName};
    var paragraph = new TagBuilder("p") {InnerHtml = value.ToString()};
    return new MvcHtmlString(header.ToString() + paragraph);
}

Of course, at the first look we can see no problem. But, this is just two tag. Imagine nested Html elements with Html attributes. Imagine having a lot of classes, inputs, and styles. This can become a huge method of several dozen of lines. Of course, the Html rendering is also not simple but it is always more readable than having a huge amount of classes that call each of them. This is why the next approach is very interesting.

Creating inline razor helper can be done directly into any .cshtml file but it does not have the ability to be reusable which is not something interesting. This is why, it is possible to store them into that App_Code. To create an app code, you have to right click the project and add an existing asp.net folder.

AddAppCodeFolder

From there, you can add your .cshtml that can have several Razor helper. The use it simple. You have to use the @ following by the file name inside the App_Code following by the name of the helper.

<div>
    @RazorInlineHelper.MyFirstRazorHelper()
</div>

The file looks like this:

@helper MyFirstRazorHelper()
{
    <p>Test Razor</p>
}

We can have parameter link Html Helper. If we try to reproduce previous method from the Html helper into Razor Helper the file would look like this.

@helper MyFirstRazorHelper()
{
    <p>Test Razor</p>
}

@helper YourGenericHelperFor(string propertyName, string value)
{

    <h1>@propertyName</h1><p>@value</p>
}

@helper YourGenericHelperPropertyConstructedFor(string propertyName, string value)
{

    <h1>@propertyName</h1><p>@value</p>
}

We can see that it is not possible to use Lambda expression to get attribute value or to get value. You have to pass them as parameter. For example, the YourGenericHelperFor was changed to get two strings. One for the property name and one for the value. The use looks like this:

<div>
    @RazorInlineHelper.MyFirstRazorHelper()
</div>
<div>
    @Html.TextBoxFor(d => d.Name)
</div>
<div>
    @RazorInlineHelper.YourGenericHelperFor(@Html.DisplayNameFor(d=>d.Name).ToString(), @Model.Name)
</div>
<div>
    @RazorInlineHelper.YourGenericHelperPropertyConstructedFor(@Html.DisplayNameFor(d => d.Name).ToString(), @Model.Name)
</div>

One other limitation is the use of existing Html helper. StackOverFlow has a solution to create an Html Helper that do some trick to access the Html helper of the page. Here is one solution.

public static HtmlHelper<object> GetPageHelper(this System.Web.WebPages.Html.HtmlHelper html)
{
    return ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;
}

It is possible from there to use inside your Helper @Html.

I added the whole post code into GitHub for you to play around with the code. Have fun using Html helper and Razor Helper. Keep in mind that Helper does not do as much as Html Helper but can in the hand be a lot more easier to maintain.

Why it is wrong to use the Asp.Net MVC MetaDataType Attribute

First of all, let’s talk about MetaDataType attribute and why it exists. This one is from the System.ComponentModel.DataAnnotations.MetadataTypeAttribute namespace. It roles is to add attribute to a class without having to modify this one. You can add this attribute that takes a single parameter to a class that will have all the attribute.

Some rules restraint the use of MetaDataType. It cannot be applied to a property and can be only be applied to a single class for each class type. This attribute cannot be inherited, so you cannot customize it. On the other side, this attribute can be applied to partial class which is the main purpose of this attribute. This attribute will be respected by ASP.NET MVC but will not be read by Entity Framework. This is something interesting if you want to add additional validation or display attribute that does not affect the database. However, it is a good wake up call for any body who use this strategy for validation attributes to know why it should be validated only during the input of the value and not during the save.

Second, from the description we can come to the conclusion that it was implemented for the scenario of Entity Framework with the Database First Approach. The model classes are automatically generated from the EDMX file and even if they are in C# and that you can edit them, you should not. The reason is that if you change your database that you will have to generate the model again which will override your changes. This is why, Entity Framework creates those generated classes as partial class. This allow you to create your own class with the same name and define additional properties, fields and methods. But, what about existing properties that you would want to add attributes? This is where MetaDataType come into play.

//Class from Entity Framework Database First
public partial class YourModelClass
{
    public string YourProperty{get;set;}
}

//Your Partial Class
[MetadataType(typeof(YourModelClassMetaData))]
public partial class YourModelClass
{
}

//The class that add your attributes
public class YourModelClassMetaData
{
    [Required]
    public object YourProperty{get;set;};
}

To illustrate the use of MetaDataType, let’s see an example with Entity Framework. As you can see, the first class of the code snippet is the generated class. This one as all your properties that represent every columns of your table. This class should not be edited by your since the file can be overridden by an automatic tool. This is why the second class come into play. It uses the partial keyword to give your a leverage. You can add new stuffs without touching the generated file. The only constraint is to have the partial keyword and the same class name. This way, .Net can match the classes and merge them into a single class. In this example, we add the MetaDataType attribute that give the capability to a class to delegate the attribute association. This is what we want: to add attribute to existing properties. Having only partial class is not enough because you can add but not attribute because these one must be set over an existing property.

The last class in the code snippet is the one referenced by the MetadataType attribute of the second. It tells .Net Framework to go into this third class, to do reflection to get a property-property association and to move the attribute from the referenced class into the class that the MetadataType attribute has been set. This is why the property type does not matter. Only the name.

In another scenario, where you do not want to add attributes to class that come from Entity Framework, you could have directly into your model class the MetadataType attribute and uncluttered your model from any attribute by having them all in another class.

At the end, what is wrong with MetadataType? It does not seem to hurt anything? Well, this is where I have something that bother me. How come the model class are directly used in the view? This mean that you are using ViewBag, ViewData or something else to pass additional information to the view. This mean that your design is less testable since it relies on a static object mechanism. It is also not required and someone could omit it without breaking anything. It also means that you are splitting your model class into 3 files. One generated, one of yours and one with attributes. This generate a lot of noises just to by-pass a view model approach or to not use Entity Framework Code First (that can be used even if you are working with the database first).

I believe this approach is viable for small application that you know that will not be over 15 entities with not a lot of business logic. It is a tool in the middle of a lot of others. Nevertheless, this is far from being an approach that should be opted to be “the one” that must be used absolutely. This approach end often by having UIHint, mixed with Required, mixed with Display attribute. Some are back-end, some are front-ends, everything is mixed up in a huge class that seem not that huge because it is divided in three.

Power Shell refuses to execute script inside Visual Studio

If you are running Visual Studio 2013 and execute inside the Package Manager Console a Power Shell script, you may stumble into a failure. A message concerning PSSecurityException that cannot load the script because of something disabled. Even if few minutes ago you were able to run the command, this can appear.

Script.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.

The trick is to execute the following line.

Set-ExecutionPolicy RemoteSigned

This will raise a question that you have to write “y” to accept.

Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic. Do you want to change the execution policy?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"):y