Using Antiforgery with Ajax Jquery Call

Using Antiforgery is pretty straightforward with normal form. You need to add an attribute on the top of the action and use a simple Html helper inside your form. The attribute will check for a specific value in session that has been calculated to be unique for the form. The Html helper create an hidden field with the value. Once the request is sent to the server, a comparison between the hidden field and the value in session is done. If they are not equal, an exception is thrown. This is a security mechanism that increase the security against malicious use of your cookie. For example, no one can just force a user to post a form that use the cookie for credential because this one will miss the antiforgery token. That said, with Ajax you have to do a little bit more.

First, you still need to add the antiforgery token at the top of your controller’s action.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SymbolChangeList(SymbolToRenameAddViewModel symbolToSave)
{
   //...
}

The helper is also required. You have different option. First, you can re-use an existing antiforgery html helper if your page already have a form that is currently use this mechanism. For example, the login/logout form at the top of your site is using this by default. However, I prefer to create one for the Ajax call. It allows me to create an unique html’s container to have an easy access to it in JavaScript.

<div id="anti-forgery-token">
     @Html.AntiForgeryToken()
</div>

From there, you just need to add the value of the hidden field inside your post arguments.

 $.ajax({
        url: "/yourpage/here",
        type: 'POST',
        data: { idSymbolRename: id, 
		/*Others variables to send */, 
		__RequestVerificationToken: $('#anti-forgery-token [name=__RequestVerificationToken]').val() },
        cache: true,
        dataType: 'json',
        success: function (json) {
			// Success code here
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
           // Error code here
        }
});

As you see, we need to specify a value for the __RequestVerificationToken value and we get this one from the generated hidden field from the Html Helper.

This code does not require a lot of modification from any Ajax call done with JQuery. The only detail that change is that you need to add the request verification token into the data sent to the server and you are up to go with a protected Post method.

Asp.Net MVC Global Localization for DataAnnotation

If you are using for example the popular [Required] attribute you may stumble into the situation that you do not want to setup the name of the resource and the name of the file every time. A quick way to fix that is to use your own Required attribute that inherit from the default Mvc one.

RequireFileSetup

I create this attribute inside the namespace that has cross layer relationship. This way, I can use it inside my Model assembly, my ViewModel assembly. This is also where I setup the resource file. The attribute is very simple. It takes the display name to replace use this one inside the require message. Then, it loads the resource, do the string format to put the display name into the message.

public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    private string displayNameOfThePropertyRequired;

    public RequiredAttribute()
    {
        ErrorMessageResourceName = this.GetType().Name;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        displayNameOfThePropertyRequired = validationContext.DisplayName;
        return base.IsValid(value, validationContext);
    }

    public override string FormatErrorMessage(string name)
    {
        var msg = DataAnnotations.RequiredAttribute;
        return string.Format(msg, displayNameOfThePropertyRequired);
    }
}

I have not hardcoded the name of the resource, just the resource file. This way, we are able to setup every DataAnnotation attributes inside the same resource file. The name of the resource if the name of the attribute. It means that inside the resource file, we will see an entry “RequiredAttribute”. The use of this attribute is straight-forward, just use the Required attribute with the namespace by having the namespace before the attribute name or by having this one in the using statement.

[CrossLayer.Attributes.Required]
[Display(ResourceType = typeof(ModelPropertyDisplayName), Name = "StockSymbol")]
public Symbol StockSymbol { get; set; }

Why I do not recommend any more Entity Framework as your ORM

If you follow that blog or know me than the title may shock you a little. Even if you do not know me, you might think I am crazy. Entity Framework (ef) is THE framework used in enterprise and it THE Microsoft’s ORM. It is not that I haven’t try to like it. I posted dozen and dozen of articles. Being a user before usable version (before version 4.3) and still a user today. For those who do not know me, well I am the one that fix EF every place where it does not work. It seems that this is a trend wherever I go. People at some point do not figure out what to do with EF and I can make it works. So, in the final, I guess I am not too bad. However, since few months, I have been using EF with a larger scale application and for a long time and I cannot handle it anymore. To give you some context, I have not a simple CRUD application. It has above 100 entities that has a lot of relationship between them. Sometime even circular dependencies. I am using in that project Unit of Work as shown by Julie Lerman and it is wonderful in theory and I still recommend that approach, but not with EF. I am also using, in this particular project, ID field in addition of the object property for foreign key, this way I can null the property and only use the ID has a key, well when possible. This is considered the “easy” approach with foreign key with Entity Framework.

Before starting to enumerate Entity Framework nightmare, I want to say that I am not allergic to EF, just that if I need to start a new project, I will never suggest that ORM. I’ll use something way lighter. I like the Migration tool, well until you reach a database that you cannot drop. I like the fact that I have not to handle SQL script to generate my database or to seed the database. Refactoring is also interesting because it does not require to play with text file. I like code first configuration until it starts to become a huge mess because you people can configure either way entities. On the final, EF is nice on the first look but more you go deep and more the pain is present.

Let’s start with migration tool. This is great. I can launch with few key strokes my development database, seed some values. Same thing for my integration environment where I have some transactions that rollback between test the changes. This is great. The problem is that the script generated by migration tool sometime just does not make any sense. The quickest way is to kill all migration scripts (c# generated file) and start again. This is really fast but cause problem if you have a database with already some data. You also do not have any more the Up and Down methods so it is impossible to come back to a previous version in the case that you need to rollback to fix a bug. Of course, you have the workaround to reuse the file used in your source control, but well… also, the seed is awesome if you have a blank database, otherwise, welcome trouble and maintenance cost goes very high. Again, I am not talking about some simple CRUD application that has 20 entities… I am talking about enterprise grade software with a minimum of 100 entities with 10 to 20 properties each. That said, this Migration tool is not what make me not recommend Entity Framework.

The killer argument against Entity Framework is that the DbContext is a mess to work with. If you are using an unit of work, then you have that unit that collect entities state during the DbContext life — mostly all the Http Request. So you have a Save method, you test this one and it works. You call that method from a different part of your system and suddenly it breaks. You have error about concurrency, about the entity has changed, about entity that try to be added, etc. You try to debug, your figure out that some entity has the property set and the id set, so you want to null the property but the problem is that code after the commit may need this information so you cannot just null properties. You have than several choices. You can divide your model from your entity, which come with a huge cost of mapping. You can get back the entity from the database, which has the cost of having to do additional calls to the database. You can also clone the entity, null the properties and save the clone. This approach is the one taken in my last project. The disadvantage is that you do not have once saved a new entity the ID automatically set into your model class, just on the clone and you also finish to have code like that:

public void Save(StockOrder order)
{
    var orderToSave = order.DeepClone();
    portefolio.Owners = null;
    portefolio.Contest = null;
    portefolio.PortefolioStatistics = null;
    foreach (var order1 in portefolio.Orders)
    {
         order1.Portefolio = null;
         order1.UserWhoPlacedTheOrder = null;
    }
//...

Well, this is really just a small snippet and this is not really pretty. The problem become even uglier if you just want to change 1 value — for example, changing an entity’s state. To do something like that I would expect just to have to set which property I want to save and commit. Indeed, this is not what always works. So after having to null all properties of the main entity that we do not care to save, we need to specify which scalar property we want. Here is another piece of code that illustrate the problem.

if (portefolio.IsNew())
{
	base.UnitOfWork.Entry(portefolio).State = EntityState.Added;
}
else
{
	var portefolioWaitingBeingSaved = base.UnitOfWork.Set<Portefolio>().Local.SingleOrDefault(d => d.Id == portefolio.Id);
	if (portefolioWaitingBeingSaved == null || base.UnitOfWork.Entry(portefolioWaitingBeingSaved).State == EntityState.Detached) //Only do it once
	{
		base.UnitOfWork.Entry(portefolio).State = EntityState.Added;         // Add to generate new ID for entities underneat
		base.UnitOfWork.Entry(portefolio).State = EntityState.Unchanged;     // We change none of the scalar property, except the one that we specify after this call
		base.UnitOfWork.Entry(portefolio).Property(g => g.Capital).IsModified = true;
	}
}

If the entity “Portefolio” is new, than we just add. This is fine. However, if this is not the case, than we save which mean that I just want to save the “Capital”. Well, I have to to a dace with Entity Framework by Adding and setting back to Unchanged the state, then setting the property that I want to save to true. Do not forget that I had also to put all other properties to null. I should just had to specify the entity, ensure that this one has its primary key set and tell EF to update the property desired. That’s it… but no.

This does not end there, sometime in a detached software like in the case of web development, the use of unit of work become more a pain than something else. The main goal is to have several operation under the same transactions. It also helps a lot during test to mock the unit of work but sometime I couldn’t get rid of problem about the DbContext having a reference to Entities that I just do not care any more. I created a Reset method the UnitOfWork class which can detach all entities. This way I can call this method before some operations. However, it works not always. So, I have a hack in the unit of work that simply kill the DbContext and create a new one. Sometime, if more than one commit is required in an Http Request, this method is needed. To few time I need to use it I feel bad, bad that I need to hack around with a version 6…

The bad experience is more than just hacking around, is that the ORM is supposed to make the life easier of developers and EF seems that this is not the case. This is not the case of what I see when I go into enterprise, neither my own. I am organizing my last project with Visual Studio Online and I have all my tasks and bug well planned. A quick glance to my impediment show that more than 70% of them are about Entity Framework. 85% of the time that I went above my estimation if because of Entity Framework bugs. Ouch.

The last thing I want to share is that Entity Framework lacks of basic feature like doing an update with a where clause. EF team expect that you get the entity from the database first on an Http Request this way you can ensure that the entity retrieved is really for the user and than you update this one — this cause 2 database calls. Instead, a better approach would have been to get the data from the Http Request, build your entity with the binding fields of the Html form and save this one with a where clause with the user authenticated. If the entity does not belong to the user than no update is done — EF could return 0 entity saved. 1 database call. This is one scenario on many that EF does not make sense if every database call is important for you. Which make me think that most of the time people are working on Intranet application when using Entity Framework. This is fine. And well, there is not a way out-of-the-box the set index… how come after 6 version? Oh yeah, EF 7 will work on NoSql database… this is not what we need, we need a solid ORM.

To conclude this rant on Entity Framework, I continue to work with Entity Framework every day on my side project (not at Microsoft), I am sure I will continue to work in the future with Entity Framework in multiple companies that use it on their website. However, I will not start a new project with this ORM on my own. If after 4 years of EF under my belt I still struggle to update a single field in one of my class than it means that something is wrong.

How to get more output from a Http404 error with Asp.Net MVC?

Asp.Net MVC has some tricky scenario where you can get a 404 error and you have no idea why. You have unit tested all your route but you still have a 404! This is crazy and you start burning time and turning around to figure out what is wrong. This is even more true with complex routing where a single variable can change the whole game.

Http404ErrorDetail

If you get a 404 page, a quick trick is to check the source code of that 404 page. This way you will get some information:

  1. The controller that the route try to reach
  2. The action that is invoked

To do that, just right click the 404 page, select View Page Source.
http404ViewSource

If you are sure that the controller and action exist than you should verify that the Http Method is the one you want. For example, the code above has the controller and action but for Http Post only, not Http Get.

Create Step-by-Step Help in a Wizard Form Directly in your Page

The main idea in this article is to write a custom help for every page without having the user leaving the page. The help must take the hand of the user through all steps required for a specific task. I decided to use a library built by LinkedIn called HopScotch. This open source library is still maintain by Linked and allow to assign html box with an arrow to specific Html. The library is great but is in JavaScript. If you are working with Asp.Net MVC, you may want to have something that will generate all the JSON for you and also put the help trigger only if the current page contains help. This article will show you a way to do it pretty easily. Also, we will do a quick patch to the current version of LinkedIn HopScotch to allow to use the library on dynamic Dom element.

LinkedInHopScotchExample

The first step is to download the code from GitHub. Their is no Nuget package, so you will have to go in the page, download the Zip file and go into the distribution folder (dist). This one contains a CSS file, a JavaScript file and some images. Once you add all those files into your solution you have to alter few of these files. I usually do not like to alter third-party code because it is hard to keep with the next versions, but this time you have no choice if you want to keep your code with the MVC framework (content and script folder). The first modification was with the CSS file that was expecting the image to be on a sibling folder. This is not a big deal if you do not care to have image next to CSS folder. However, the bigger change that must be done is in the JavaScript file. This one need a new public function to add the next element. This is required because the library setup all the wizard’s steps when the page load. If you want during your help’s steps generate Html and link your help to that dynamically generated Html, than you must also specify dynamically that the next step will be this instance.

This modification is the following:
1) Search for getCurrTarget
2) Add the following code under the code found in step 1:

this.setNextTarget = function(el) {
  currTour.steps[currStepNum+1].target = el;
 };

This allow later to call the setNextTarget function and specifying the Dom Element dynamically generated.

So now we are all set. We can create the steps for a single page. I decided to create an interface called IHelp. When my View Model class is passed into the View, if this one implements IHelp, than I will display the button to start the wizard help and also generate the JavaScript. This way, I setup once the system and any further page just need to use that interface without having to care about HopScotch at all.

Here is the interface code:

public interface IHelp
{
     HelpViewModel GetHelp();
}

This interface is just method to get the help ViewModel. The HelpViewModel class is the one that contain codes about the HopScotch JavaScript. This is the class that the Html Helper later will use to generate the JSON object and the JavaScript call. It contains the tour id which is something unique. This is used in the case we use multiple page HopScotch wizard which I do not plan to use. This is why I just generate a random id. The list of steps are every help box. Each one contains the title, the description, which element to link to and also JavaScript action if required. Other than that, this view model can set some JavaScript action when we start the help wizard, stop this one or end it. The difference between close and end is that close is whenever the user stop using the help and end is only after every steps are done.

    public class HelpViewModel
    {
        private readonly string tourId;

        public HelpViewModel()
        {
            tourId = Guid.NewGuid().ToString();
            this.Steps = new List<HelpStep>();
        }
        public string TourId
        {
            get { return tourId; }
        }

        public List<HelpStep> Steps { get; set; }
        public JRaw OnStart { get; set; }
        public JRaw OnClose { get; set; }
        public JRaw OnEnd { get; set; }
        public string StepsJson
        {
            get {
                return JsonConvert.SerializeObject(this.Steps
                                                ,Formatting.Indented
                                                , new JsonSerializerSettings{ContractResolver = new CamelCasePropertyNamesContractResolver()});
            }
        }

    }

In this code, few things worth to stop by. First, we are using the type JRaw. JRaw come from Json.Net library and allow to serialize data that won’t be proceeded during serialization. This is required for JavaScript function to be generated as a function and not a string. The second interesting part is the StepsJson method. This one is there for steps. The help take care to build the HelpViewModel which is the data for the wizard itself while the steps are done automatically with the serialization.

Steps are pretty straightforward. The class contains a one to one relationship with the JavaScript equivalence.

    public class HelpStep
    {
        public HelpStep()
        {
            
        }

        public HelpStep(string title, string content, JRaw target, string placement)
        {
            this.Title = title;
            this.Content = content;
            this.Target = target;
            this.Placement = placement;
        }
        public string Title { get; set; }
        public string Content { get; set; }
        public JRaw Target { get; set; }
        public JRaw OnPrev { get; set; }
        public JRaw OnNext { get; set; }
        public JRaw OnShow { get; set; }
        public string Placement { get; set; }
    }

The Target property is the JQuery selector to the item. This could be also a straight JavaScript selector to the Dom element.
The next part is to have something that use the View Model and to generate the HopScotch code. The partial view that hack has an helper is only used when the View Model implement the IHelp interface. Inside the layout.cshtml :

@if (Model is IHelp)
{
      @Html.Partial("_helpScript", Model as IHelp)
}

This code call the partial view:

@model ViewModel.Infrastructures.Definitions.IHelp
<script type="text/javascript">
    @{
        var infoTour = Model.GetHelp();
    }
    var tour = {
        id: "@infoTour.TourId",
        steps: @Html.Raw(infoTour.StepsJson),
        onClose : @infoTour.OnClose,
        onError : function (e){console.log(e);},
        showPrevButton: false
    };

    //See _Header.cshtml for the ID
    $('#page-help-button').click(function () {
        hopscotch.startTour(tour);
    });

</script> 

This create the help (called tour in Hopscotch). Then, it add to the help button the action to start the help wizard. The generated code look like the one that can be found in the official website. To create the first help wizard, you just need to have your view model having the implementation using the IHelp. Here is an example:

 public HelpViewModel GetHelp()
        {
            return new HelpViewModel() {
                Steps = {
                    new HelpStep("Join Contest", "You can join one or many contests.", new JRaw("$('#contest-unsubscribed-panel-header')[0]"), "bottom"),
                    new HelpStep("Your Contest", "All the contest you are subscribed are listed here.", new JRaw("$('#contest-subscribed-panel-header')[0]"), "top")
                        {OnShow = new JRaw("function(){createTemporaryContest();}")},
                    new HelpStep("All Existing Contests", "This is the title of the contest", new JRaw("$('tempo-title')[0]"), "top")
                        {OnShow = new JRaw("function(){hopscotch.setNextTarget($('#tempo-description')[0]); }")},
                    new HelpStep("Time", "This is the remaining time of the contest", new JRaw("$('#tempo-description')[0]"), "bottom")
                        {OnShow = new JRaw("function(){hopscotch.setNextTarget($('#tempo-number')[0]); }")},
                    new HelpStep("Participants", "This is the number of user already the contest", new JRaw("$('#tempo-number')[0]"), "top")
                        {OnShow = new JRaw("function(){hopscotch.setNextTarget($('#tempo-description')[0]); }")},
                    new HelpStep("More Details", "Clicking on the contest will show you the full description of the contest. If you see this box having a shining animation, it means that is it a brand new contest.", new JRaw("$('#tempo-click-description')[0]"), "top")
                        {OnShow = new JRaw("function(){deleteTemporaryContest(); }")},
                    new HelpStep("What Happen If...", "Once you join, the contest will leave this container and get into the joined contest above", new JRaw("$('#contest-subscribed')[0]"), "top")
                        {OnNext = new JRaw("function(){deleteTemporaryContestFromJoinedContest();}")},
                    new HelpStep("Done", "Now is it your turn!", new JRaw("$('h1')[0]"), "bottom"){OnShow = new JRaw("function(){removeEverything();}")},
                },
                OnClose = new JRaw("function(){removeEverything();}")
            };
        }

Their is few things that is not perfect there, but it is quite rapid to work this way. It can be easily re-factored later too. As you can see, I setup every steps in order. In that example, string are not yet localized, but we can leverage of .Net Resource file easily by having all steps in the ViewModel. The selector require to use JRaw as explained earlier. You can see some method call for OnShow. These method create temporary Dom element that are done if the user really do the action. For example, the createTemporaryContest method create some Dom element, and later, the method deleteTemporaryContest or removeEverything take care to remove those temporary html. The fix we did to LinkedIn HopScotch is used in the OnShow, just a step before this one is used. OnShow allows to do an action when the help’s step is shown. This is the perfect time to set the next step on the dynamic generated html element.

Here is an animation of the final result.