8/23/12

Protect Your Form Postback with Anti-Forgery


To secure a web page postback from malicious exploits, we can add a security token as a hidden field to the form or a cookie. When a postback is received, this token is validated to make sure that the request is not a cross-site request forgery.

When working with Razor Web Pages and WebMatrix, we can find a handy helper which provides this implementation right out of the box. The AntiForgery helper gives us the capability to create and validate the secured encrypted token by just using a couple of lines of code. This helper is found in the System.Web.Helpers.dll assembly, and it should be added automatically as a reference to your project in the bin folder. Note that for Visual Studio you need to install a Nuget Package using this command:

 Install-Package RazorGenerator.Templating

To show you how to use this helper, open a web page on WebMatrix and add the following mark-up:

@{
    // Validation token test during postback;
    if(IsPost){
        try
        {
            AntiForgery.Validate();
        }
        catch(Exception ex)
        {
            ModelState.AddFormError(ex.Message);
        }
     
        if(ModelState.IsValid)
        {
            Page.SuccessMessage = "Token validated!";           
        }        
    }    
}
<!DOCTYPE html>
<html lang="en">
    <head>  
    </head>
<body>
<div class="message-error">@Html.ValidationSummary()</div>
<div class="message-success">@Page.SuccessMessage</div>
<form method="post" action="">
    Full Name:<input type="text" name="username" id="username"/><br/>
    EMail:<input type="password" name="username" id="username"/><br/>
   @AntiForgery.GetHtml()
    <input type="submit" name="submit" value="Send"/>   
</form>
</body>
</html>
 
This is a simple contact page with two fields. This page is available to the public on the internet, and we would like to prevent any type of exploits. In order to do that, we have added this line of code in between the form tags:

@AntiForgery.GetHtml()

If you look at the page source after it has rendered on the browser, you can see that a hidden field has been added:



The _RequestVerificationToken field contains an encoded encrypted token. In addition, a cookie with the same information has been created. This allows the helper to cross check the token in both the form and cookie.

To validate the token during the post back, we use this code:

        try
        {
            AntiForgery.Validate();
        }
        catch(Exception ex)
        {
            ModelState.AddFormError(ex.Message);
        }

The call to Validate() raises an exception if the token is not valid. At this point, the code can stop doing any additional logic and just present an error using the ValidationSummary method from the Html helper.  If the token is successfully validated, we check the ModelState.IsValid method and continue the intended logic which for this example is just adding the contact information to the system.

I hope you can find this helper very useful for your own implementation.

8/21/12

Deploy Website from WebMatrix to Azure

og-bit.com
If you have created a web application on WebMatrix and want to host this application on a Windows Azure website, you will need to take a few additional steps to make sure your web application gets deployed to the correct location of your website.

After creating the website on Windows Azure, you will get a page indicating that the site has been created.




You can now click on the Download Publishing Profile link. This downloads a XML file which you should save. This file contains the publishing settings that are needed to be able to deploy the files to the correct location. The file looks a follows:



On the XML file, you can see the server settings as well as credentials to let you deploy the files to the correct Azure website. Some of the text you see on the file will match your application settings.

You now need to open your WebMatrix project and import this file.  On WebMatrix, click on the Remote tab. Now click on the Settings toolbar button.



This opens the project publish settings. The next step is to click on the Import publish settings link and select the file you just downloaded.

The previous step should populate all the settings. You can now click the Validate Connection button and you should get a message indicating that the connection was successful as shown below:



We are now ready to deploy the website.  On WebMatrix, click the Publish toolbar button.  You should see a Publish Preview screen showing all the files that are about to be deployed. On the first deployment, all the files will be deployed, so you should be patient and let the publishing process complete. If you do not have too many files, this will probably be a few seconds.  For additional deployment, only changes will be published.   WebMatrix should display a progress status bar at the bottom which looks similar to this:





When it is done, the status should read Complete, and the website URL should be displayed. Click on the URL to view your new website running on Azure.

I hope this instructions help your deployment be an easy experience.

8/19/12

Functions in ASP.Net Razor Web Pages


When using Razor Web Pages, it is very common to embed dynamic content on the HTML markup by using a server variable with the following format:

@{
   var message = "Hello";
}

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h1>@message</h1>
    </body>
</html>

This renders a page with a simple hello message. In some instances, we may want the message to be more dynamic and to display a message based on some condition. For those cases, we can leverage the @functions block feature of the Razor syntax. The purpose of this block is to let us add functions that can be called from within the page.  Since each page is defined as a class, we can add functions and properties to support more complex functionality on Web Pages.  Let’s look at this example:

@functions {
    string GetMessage(){
      var req = Request["typ"];
      var message = "Hello";
      if (req=="sales"){
          message ="Welcome to sales";
      }
      else if (req=="support"){         
          message = "Welcome to Support";
      }
      return message;
 }
 
}
 
<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h1>@GetMessage()</h1>
    </body>
</html>

In this example, we call the @GetMessage function which just reads a URL parameter and based on the parameter, it determines what message to display. Notice how the function call is embedded in the markup. To use it, we must proceed it with the @ character which is use to start inline expressions.  To define the function, we use the @functions block directive. In this block we can add functions and properties that can be reused in the page.

The following table shows what query string can be used to load this page and the expected output:

QueryString
Output
Mydomain.com/Page
Hello
Mydomain/Page?typ=sales
Welcome to Sales
Mydomain/Page?typ=support
Welcome to Support

I would suggest using functions on Web Pages for specific functionality on each page. If you want to build functions for common functionality that can be used in several pages, you should add a separate CSHTML page and make the methods static. If you need to reuse blocks of HTML, Razor helpers should be used instead.

8/12/12

SharePoint XsltListViewWebPart Remove CheckBoxes for Custom Views


When displaying a list view with items, the XsltListViewWebPart adds by default a check box on the header (to select all the items) and to each row. The purpose of the checkbox is to select one or more items to enable some custom actions on the ribbon. An example of a list view with checkboxes is displayed below:



This out of the box feature is a great to have, but there are some cases in which we want to create custom views which may have many list views for different lists, and we do not want the custom action ribbon to be available. When the ribbon is not available and the user clicks on any checkbox, a JavaScript error is displayed as follows:



To avoid this problem, we need to remove the checkbox for the custom view only and not affect the other list views. If you edit your custom view on SharePoint Designer, you will not find any setting that allows you to do this. There is however an attribute that can be added to the markup which allow us to remove the checkbox. Edit your custom view/page and find the View tag for your list view. Add the attribute TabularView=FALSE to the view as you see below:



  Save the file and reload it on your browser.  When this attribute is set to false, the check boxes do not get created on the view as you can see below:




Since this change is only done to the custom view, it should not affect your other views/pages. I hope you find this helpful.

8/9/12

SharePoint How to Prevent Edit Item Form Submit

In SharePoint, the Edit Item Form is used to update a list item. In some instances, we may want to prevent the user from updating the record because of some rule validation and block the form submit on the client side. On a simple HTML form, we could use the preventDefault() function or just return false from the raised event handler, but this does not work on SharePoint because the Save button calls a specific JavaScript function to do the submit.

If you inspect the Save button on the form, you can see that there is a call to a PreSaveItem function. This function can be used to add code to perform one or more tasks that may be required in order to allow the item to be updated. I often use this function when I have an item that is associated to some business rule constraint defined in another list or a web service, and I need to make sure that a certain condition is met. To implement this function, you can open the edit item form and embed the following JavaScript (or add a reference to a JavaScript file with the same content):


function PreSaveItem(){
       var allowPostback = RuleValidation();
       if (!allowPostback)
          alert(“Sorry, we are unable to update this record …”);
       return allowPostback;
}

function RuleValidation(){
  //todo  ajax or client object model call to check the constraints
}



If the custom rule validation function returns true the update is submitted. If the function returns false, we let the user know that there was a problem, and he/she can then make the necessary corrections.