Creating Custom Formatter in ASP.NET Web API TO HANDLE SPECIFIC formatted REQUEST

In this article I will show you how to create a custom formatter in ASP.Net Web API to send object in Request body with specific format.

This is a series of the article I wrote earlier in which I showed the way of handling formatted response.

Formatters in ASP .NET Web API plays an important role, when the request comes to the server, depending on the media-type, determines which formatter has to be used to parse the request and assemble the data into appropriate format as response. In ASP.Net Web API when the request is made by the user, Web API framework checks if it is Simple Type or a Complex Type. All types like string, integers, etc. are simple types and by default ASP.Net Web API read those values from URI and uses Model binding. On the other hand for complex types, ASP.Net WEB API framework read it from request body by default (the behavior can be overridden) an depending on the content-type load specific formatter from the list of formatters available in HttpConfiguration list.

Let suppose we want to send object in pipe format. In this post I will send a user object in request body in below format.

User object have two properties namely Name and Position and we need to send data in below format

Request Body: Name=Ovais | Position=Technical Architect

This can be done by implementing a custom formatter. When you are creating a custom formatter in ASP.Net Web API, you have two options one is when the request is arrived on server and you want to return the data in specific format or when the request arrives and you want to read/parse the data in specific format.

Steps to follow.

  1. Create a new Web API project in Visual Studio
  2. Add a new User class having two string properties namely Name and Position
  3. Add a new folder named “Infrastructure”. It’s always a good practice to place all the core level classes in particular folder. In my case I have named it Infrastructure.
  4. Add a new class and named it PipeFormatter
  5. Derive this class from BufferedMediaTypeFormatter
  6. Override CanReadType and ReadToStream methods and add the logic to handle incoming request
  7. Below is the complete code of PipeFormatter class

public class PipeFormatter : BufferedMediaTypeFormatter
public PipeFormatter() {
SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue(“text/pipe”)); }

public override bool CanReadType(Type type)
if (type == typeof(User)) {
 return true;

return false


public override object ReadFromStream(Type type, System.IO.Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger, System.Threading.CancellationToken cancellationToken) {

 User userObject = new User();

 StreamReader reader = new StreamReader(readStream);

 string str=reader.ReadToEnd();

 String[] propArr = str.Split(new char[] { ‘|’ });

 foreach (var val in propArr) {
string[] propIntArr = val.Split(new char[] { ‘=’ });
if (propIntArr[0].ToLower().Trim().Equals(“name”)){
userObject.Name = propIntArr[1].ToString();
else if (propIntArr[0].ToLower().Trim().Equals(“position”)) {
userObject.Position = propIntArr[1].ToString();
return userObject;

 8. In the above code you can see that I have added the “text/pipe” media type in the supported media type list. This you have to add it so you can specify the Content-Type attribute when sending HTTP request.

 9. Now open the WebApiConfig class placed under App_Start folder

 10. Add an entry in the config.Formatters collection as below.

config.Formatters.Add(new WebApplication1.Infrastructure.PipeFormatter));

 11. Build the project and run.

 12. In order to test I used Fiddler
13. Requesting from fiddler

14. ReadFromStream method is called and populate the User object

15. And finally on my controller Post method I am receiving this object.

Hope this helps!

Providing Interactive Grid handling in ASP.Net MVC Application using Kendo UI

Nowadays, in every application, grid plays an important role in providing rich and easy interface for data management. In my last project I used Telerik Kendo UI Grid control for ASP.Net which I found quite easy and robust to use with ASP.NET MVC applications. Developers only need to provide some configuration and the rest of features like paging, sorting, filtering editing, updating, etc. runs accordingly. Moreover, there are lot of different skins available which you can apply depending on your UI design.

Following are the steps shows the usage of Telerik Kendo UI Grid control in ASP .NET MVC applications with a minimal amount of code.

  1. Create a new ASP.Net MVC Web Application in Visual Studio
  2. Make sure you have installed the Telerik ASP.NET MVC Controls suite from telerik website.
  3. In your MVC project add a reference to Kendo.MVC.dll from C:\Program Files (x86)\Telerik\UI for ASP.NET MVC Q1 2014\wrappers\aspnetmvc\Binaries\Mvc5
  4. Under the Scripts folder add kendo.all.min.js and kendo.aspnetmvc.min.js files from C:\Program Files (x86)\Telerik\UI for ASP.NET MVC Q1 2014\JS
  5. Then, create another folder Styles under root MVC project and add three files and a Default folder containing images for telerik controls.

    – kendo.common.min.css

    – kendo.dataviz.min.css

    – kendo.default.min.css

  6. Open BundleConfig.cs file and add entries to newly added Kendo CSS files and Javascript files.










7. Now open the _Layout.cshtml as this is the default master page in ASP.Net MVC application and add the newly configure kendo bundle in the head section as below


8. Now let’s create a new controller named “DemoController”


9.  Create a sample model class that contains few properties


Int32 Id { set; get; }

String Name { set; get; }

String Company { set; get; }

String Designation { set; get; }

String EmailAddress { set; get; }

10. Then in the newly added DemoController add a GetPersons method that returns the list of persons to display in a view.

DemoController : Controller


// GET: Demo

ActionResult GetPersons([DataSourceRequest] DataSourceRequest request)


List<Person> personLst = new

Person { Id = 1, Name = “Ovais Mehboob”, Company = “USTS”, Designation = “Technical Architect”, EmailAddress = “” });

Person { Id = 1, Name = “Khusro Habib”, Company = “EO”, Designation = “SAP Lead”, EmailAddress = “n/a” });

Person { Id = 1, Name = “David”, Company = “USTS”, Designation = “Network Administrator”, EmailAddress = “n/a” });

return Json(personLst);



11. Create a Index method that returns ActionResult. As per the default routing engine this will be invoked whenever the controller will be called without action name

12. Add a new empty view by right clicking the Index method

13. Add the html.kendo grid code as shown below in the Index.cshtml page

@using System.Collections;

@using Kendo.Mvc.UI;




.Columns(columns =>


columns.Bound(p => p.Name).Width(200).Title(“Name”);

columns.Bound(p => p.Company).Width(300).Title(“Company”);

columns.Bound(p => p.Designation).Width(200).Title(“Designation”);

columns.Bound(p => p.EmailAddress).Width(200).Title(“Email Address”);


.HtmlAttributes(new { style = “height: 500px” })

.Editable(editable => editable.Mode(GridEditMode.InCell))







.Resizable(resizable => resizable.Columns(true))

.DataSource(dataSource => dataSource





.Model(model =>


model.Id(p => p.Id);



.Read(action => action.Action(“GetPersons”, “Demo”))

.Update(“SavePerson”, “Demo”)



14. If you see the above code the .Read is the method where you can specify the action name followed with a Controller name

15. Likewise read, you can add update and delete methods as well

16. There are many attributes provided which you can configure on the fly like Pageable() for paging, Filterable() for filtering. For detailed documentation for each method please visit

17. Once you build and run the project you will see something like below

Hope this helps!

Awarded Microsoft MVP (Most Valuable Professional) Award

I am glad to announce that on 1st July 2014, I received an email from Microsoft on being awarded as the Microsoft MVP (Most Valuable Professional) in ASP.Net/IIS. I got really excited to see the award and that Microsoft has recognized my contributions I did in the community.

I am more impassioned and certainly increases my motivation to contribute more in the community.

I would like to thanks Microsoft for acknowledging my efforts and especially Microsoft Innovation Center, Pakistan for sponsoring my technical sessions/events and giving me opportunity to contribute and participate in Boot camps and Tech Ed events.

Looking forward to continue my efforts and share the knowledge as much as I can to help the community.

Grab eBooks and Videos in a very low price – by Packt Publishing

Being an active participant in reviewing Packt Publishing books related to Software discipline, I would like to celebrate the 10 years completion of Packt and wanted to express the new and exciting promotion in which they are offering all the eBooks and Videos for just $10.

Folks, hurry up and grab some good titles!

Here is a link Packt $10 Offer


Common errors in processing EDI documents using BizTalk Server 2013

Following are some errors I encountered while setting up an EDI in BizTalk Server 2013. These are quite common errors but I thought to write a post showing the exact reason of the problem which may help someone configuring EDI.

I will try to keep update this article the more errors I come across so it will be used as a reference.

ERROR 1: Agreement Resolution based on the context properties for x12 Protocol has failed


In order to resolve this error check the Identifiers values in parties agreement and when sending an EDI document specify the exact values that have been set for ISA6 and ISA8 in the identifiers tab of the Source Party agreement. These values should match the value of an EDI document for the same ISA6 and ISA6 properties.

In the above screen shot ISA6 and ISA8 values are PartyA and PartyB and the Sender and Receiver qualifiers are ZZ-Mutually Defined (X12)

So the EDI document header should be something like below

ISA^00^ ^00^ ^ZZ^PartyA ^ZZ^PartyB




ERROR 2: Delimiters are not unique, field and segment separator are the same. The sequence number of the suspended message is 1.


EDI document is fixed length format. This error comes up when the values length exceeded or does not meet the fixed length format. When structuring EDI document its better to define the values properly otherwise sometimes it becomes hard to rectify this type of error.

Step by Step guide of setting up an EDI in BizTalk Server 2013

What is an EDI

EDI – Electronic Data Interchange is an electronic communication medium that is use to exchange documents between different trading partners. EDI have specific text file format followed with specific version and document Id. For example, the Warehouse shipping order document is termed as 940 EDI document.

Why do company prefer EDI to exchange documents?

There are many benefits. Computer to computer exchange is much less expensive, cost is a primary reason, as it’s a standard every business understands and parse the documents easily.

Role of BizTalk Server

BizTalk server is a powerful server side product developed by Microsoft that is used for integrating distributed systems or applications. It acts as a middle hub where the businesses can submit documents and the destination client can get it in his specific format. It works on the publisher/subscriber model in which the client can subscribe to the incoming messages and the publisher publishes it to that port. On the other hand if you need to tweak some attributes of the document or to transform the inputted document into the client’s specific format can be done using mapping or pipeline.


In this article I will give the complete step by step in sending 940 EDI document and converting it to the client’s specific XML format, and placing it to the destination folder.

  1. Open Visual Studio 2012. (With BizTalk 2013 you can create BizTalk projects using VS 2012)
  2. Create a new empty BizTalk project



  3. Specify name and click OK.
  4. As we have to process EDI 940 document we need to add its schema
  5. Right click the project and add existing schema from C:\Program Files (x86)\Microsoft BizTalk Server 2013\XSD_Schema\EDI



  6. Now create another schema which you wanted to send to the destination client.



  7. Now add some child elements into the schema as shown below



  8. Now add a map to provide mapping between the 940 schema file to our custom created schema file.


  9. Once this is added, we can see screen like this



  10. Now click on the Open Source schema and select 940 schema document



  11. Now click on the Open destination schema and select client specific one we recently created


  12. For demo only, I am mapping ST01 with OrderNo and ST02 with CompanyCode



  1. Save the project and build it.
  2. Before deploying sign the assembly from project properties signing tab


  3. Go to the deployment tab and select Restart host Instances to True and specify the Application Name


  4. Rebuild and deploy the solution, you will see the application added under the Applications
  5. Go to the BizTalk administrative console and you can see the application added in the Applications tab
  6. Now create a receive port where you will submit the EDI 940 text file.

    Right click the Receive Ports and click add New -> One way receive port



  7. In order to process EDI document we have add a reference to BizTalk EDI Application
  8. Right click the application and click properties
  9. Go to the references tab
  10. Add application reference as BizTalk EDI Application



  11. Click on the Receive Locations and add new receive location by hitting the New button
  12. Specify Receive location name as RecieveLocation
  13. Select Type as File as we will be putting the EDI txt file on particular folder
  14. Click configure to select the path and other attributes
  15. Specify the receive folder and select file mask as *.txt
  16. I have specified C:\demo\in as folder path where I will put EDI txt files


  17. Now add a send port where the file after processing by BizTalk will be send.



  18. In the SendPort window select TYPE as file and configure the path where the document will be placed after processing from BizTalk. I have selected file extension as .xml as I will be sending the custom formatter xml on the folder.
  19. Select send pipeline as XMLTransmit
  20. Add Outbound Maps and select the map you have created above.


  21. Specify Filter to process only those messages that have specific attributes.
  22. Here I will select BTS.RecievePortName = “RecievePort”


  23. Click Ok



Running Solution

Now when you place the EDI text file at C:\Demo\In folder it will be picked, transformed into client specific xml format and placed it into the C:\Demo\out folder by BizTalk Server.

Output file format looks like below

<?xml version=”1.0″ encoding=”utf-8″?><ns0:DemoData xmlns:ns0=”http://DemoPrj.clientspecific”><OrderNo>94A</OrderNo><CompanyCode>0001</CompanyCode></ns0:DemoData&gt;


Hope this helps to those who are new to BizTalk and EDI implementations.

Key practice of MVVM in XAMP apps

In XAML based apps i.e. Silverlight, WPF, Windows store and windows phone apps there are many ways to bind objects or collections with control properties.

In order to bind it with textbox (suppose), one way is to set the DataContext property of the container i.e. Grid, StackPanel etc. and bind it using {Binding Path=PropertyName} where property name could be any property of the object binded with the DataContext property of the container. There are many ways of binding shown in my other article

Although there are many other ways of binding, but for example if you want to update the control property when the object value modifies real problem comes in. In order to achieve this we can implement MVVM pattern. MVVM works with Model, View and ViewModel. Where a Model represents a domain model, View contains controls whereas the ViewModel is the model of a view and contains the properties, events, etc. particularly to the View. In order to handle this scenario, we can create a ViewModel in this below example and then bind it to the view in the later stage. To notifying UI thread we have to implement INotifyPropertyChanged interface.

TestViewModel: INotifyPropertyChanged



public RegistrationViewModel()


attributes = new



PropertyChangedEventHandler PropertyChanged;


string _name;


string Name



set { this._name = value;



get { return _name; }



ObservableCollection<String> _attributes;


ObservableCollection<String> Attributes




This._attributes = value;



get { return _attributes; }






void NotifyChangeEvent(string propName)


if (PropertyChanged != null)

PropertyChanged(this, new





In the above code you can see I have two properties Name and Attributes. While setting Name value I am calling NotifyChangeEvent that checks the event and call invoke if it’s not null.

You may notice that the Attributes collection is ObservableCollection and not List, etc. if we set it to List, etc. it does not notifies any modification happens to the collection.


Now let suppose you have a form containing two textboxes and a list.

XAML as follows

<Grid Name=”grdreg” Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”>

Name=”txtBox” HorizontalAlignment=”Left” Height=”124″ Margin=”161,128,0,0″ TextWrapping=”Wrap”
VerticalAlignment=”Top” Width=”297″/>

<TextBox Name=”txtBox2″ HorizontalAlignment=”Left” Height=”142″ Margin=”161,276,0,0″ TextWrapping=”Wrap” Text=”{Binding Path=Name}” VerticalAlignment=”Top” Width=”423″/>

<Button Content=”Update” HorizontalAlignment=”Left” Height=”130″ Margin=”475,125,0,0″ VerticalAlignment=”Top” Width=”112″ Click=”Button_Click”/>

<ListBox ItemsSource=”{Binding Path=Attributes}”
HorizontalAlignment=”Left” Height=”290″ Margin=”616,128,0,0″ VerticalAlignment=”Top” Width=”159″/>



The first textbox in white is a TextBox control (txtBox) and the second in gray is also a TextBox control (txtBox2), whereas the right one in vertical is ListBox. In the XAML, you can bind any object property like {Binding Path=PropertyName} and in this snippet the txtBox is binded with Name property like {Binding Path=Name}.

For list control you can set ItemsSource property and use the same {Binding Path=PropertyName} to bind with specific collection property. Now how does the runtime know which object property has to be mapped. This can be done by specifying the DataContext property of the container where all controls reside and this I have set it in the code-behind (You can also set in XAML)

Code behind

BlankPage1 : Page



RegistrationViewModel viewModel;

public BlankPage1()




viewModel= new

grdreg.DataContext = viewModel;



void Button_Click(object sender, RoutedEventArgs e)


viewModel.Name = txtBox.Text;





On page constructor I am initializing the viewModel and setting it to the DataContext property of grid container “grdreg”.

That’s all…

you can start modifying values of the view model, UI will be updated accordingly.

Tip: In case you have apps for different platforms namely Silverlight, windows phone and windows store apps etc. you can use Portable Class Library and place all your view models there.

Extending and Customizing authentication mechanism in Web Applications using ASP .NET Identity


ASP.NET security module evolved time to time. First in 2005, Microsoft introduced ASP.Net Membership which is used to authenticate users using Forms authentication and the user names, password etc. stored in the SQL Server database. There were few limitations with this framework as the database schema was designed for SQL Server only and you cannot change it. Secondly, if you wanted to extend some more properties related to profile information etc. you have to create separate tables. Another limitation is OWIN. Since the authentication is based on Forms Authentication, the membership cannot use OWIN.

What is OWIN: OWIN includes middleware components for authentication that supports to log in users from external authentication namely Microsoft Accounts, Facebook, and Twitter etc. OWIN also includes support for OAuth 2.0, JWT and CORS.

Today, everyone maintains social network accounts like Twitter, Facebook, etc. and people most likely prefer to login or linking applications with these accounts rather creating new ones.

Keeping all these limitations Microsoft developed another framework “ASP.Net Identity” that does not only supports OWIN but more or less the extension and customizing of the authentication module is far easy and practical as compared to the ASP.Net Membership framework.

What is ASP.Net Identity?

ASP.Net Identity is a new membership framework to provide user logins and security in web applications. It allows adding login features in web application and also easily customizable to extend the user information.

Following are some of the feature of the ASP.NET Identity system taken from

One ASP.NET Identity system

  • ASP.NET Identity can be used with all of the ASP.NET frameworks such as ASP.NET MVC, Web Forms, Web Pages, Web API and SignalR

Ease of plugging in profile data about the user

  • When you create new users in your application, it is now easy to add extra information about the user. For eg.. if you wanted to add a Birthdate option for users when they Register an account in your application.
  • ASP.NET Identity uses Entity Framework Code First and it is possible to extend the POCO classes.

Persistence control

  • By default the ASP.NET Identity system will store all the user information in a database. ASP.NET Identity uses Entity Framework Code First to implement all of its persistence mechanism.
  • If your application requirements are that this information might be stored in a different storage mechanism such as SharePoint, Azure Table Service, No Sql databases etc. it is now possible to plug in different storage providers.

Unit testability

  • ASP.NET Identity makes the web application more unit testable. You can write Unit Tests for the parts of your application that use ASP.NET Identity

Simple Role provider

  • There is a Simple Role provider which lets you restrict access to parts of your application by Roles. You can easily create Roles such as “Admin” and add Users to Roles.

Claims Based

  • ASP.NET Identity supports claims-based authentication, where the user’s identity is represented as a set of claims. There is a Claims

External Logins

  • You can easily add external logins such as Microsoft Account, Facebook, Twitter and Google to your application store the user specific data in your application using this system.
  • You can also add login functionality using Windows Azure Active Directory and store the user specific data in your application using this system.

ASP.Net Identity comes with ASP.Net MVC 5 or you can also add it using NuGet Package manager console. Identity framework is based upon three libraries namely

  • Microsoft.AspNet.Identity.EntityFramework

    This package has the Entity Framework implementation of ASP.NET Identity which will persist the ASP.NET Identity data and schema to SQL Server.

  • Microsoft.AspNet.Identity.Core

    This package has the core interfaces for ASP.NET Identity. This package can be used to write an implementation for ASP.NET Identity that targets different persistence stores such as Azure Table Storage, NoSQL databases etc.

  • Microsoft.AspNet.Identity.OWIN

    This package contains functionality that is used to plug in OWIN authentication with ASP.NET Identity in ASP.NET applications. This is used when you add log in functionality to your application and call into OWIN Cookie Authentication middleware to generate a cookie.


Steps to extend and configure ASP.NET Identity

Usually mid – large sized web applications are divided into different layers i.e. Presentation, Service, Business, Data Access etc. and usually models resides on the common layer which can be used by data access, service and presentation layers. When designing the architecture of web application and implementing security we have to follow the basic style of placing code in specific layers otherwise the code become shambolic.

In ASP.Net Identity, as the models are related to ASP.Net identity framework resides in Microsoft.AspNet.Identity.EntityFramework and with the help of Code First entity framework we can easily provide the association with other entities where needed.

Let’s proceed with some hands-on now

1. Open Visual Studio 2013 and create a new Web application project and select MVC template. If you create a web application project using Visual Studio 2013 you will automatically get these three assemblies referenced by default.

 2. In case if you have Visual Studio 2010 you can manually add it using NuGet Package manager console and search term ‘asp net identity’



3. Open AccountController, you will notice that its calling parameterized constructor from default AccountController constructor and initializing UserManager, UserStore and ApplicationDbContext

public class AccountController : Controller
public AccountController(): this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser> (new ApplicationDbContext()))){

public AccountController(UserManager<ApplicationUser> userManager)

UserManager = userManager;



4. UserManager is basically the entry point for performing signing operations, it takes UserStore as a parameter which is implemented by IUserLoginStore, IUserRoleStore, IUserClaimStore, IUserStore etc to provide repositories for user-related data such as user data, passwords, claims, roles etc. UserStore takes a DbContext as parameter and have the implementation details of how the particular User is stored. If you notice the ApplicationDbContext it is derived from IdentityDbContext and not the standard DbContext class this is because the IdentityDbContext is specific to the ASP .NET Identity framework and it allows entities to have String as a primary key.

5. Let’s generate a database from Identity framework entities using entity framework code first approach.

 a. In the visual studio, open Package Manager Console and select your web project as the startup project. In case if you have different layer for data access components you can select that specific layer and add the references to the ASP .NET Identity framework libraries via Nuget.

 b. Execute command enable-migration, that creates a Migration folder and create a Configuration class. Note: you can also enable the automatic migration by settings its AutomaticMigrationsEnabled property to true in the configuration class constructor.


c. Now open the ApplicationDBContext class and see which database connection name it’s pointing to. By default its pointing to DefaultConnection



d. To migrate the Identity tables into existing or separate database, we can change the connectionString as


<add name=DefaultConnection connectionString=Data Source=.\mssqlexpress;Initial Catalog=TestDB;Integrated Security=False;

User Id=sa; Password=sa123; Timeout=500000providerName=System.Data.SqlClient />

e. Now execute add-migration command in the package manager and name it Initial


f. It creates a class with two methods Up() and Down(), Up will be called to sync the changes from code first model to the database, and Down can be used to revert changes back to last state.



g. Now execute update-database command so the new database and identity tables will be created.




6. We can also create custom tables by adding DbSet properties for new tables in the ApplicationDbContext class and customize it according to our need.

7.  Let suppose, we want to extend the security module and provide page level security in which whenever the user navigates to any page system checks the feature set of user that belongs to particular role and redirect it to the login page if it does not exist. To handle this scenario we can follows below steps

a. Create a model named as View

public class View{

public String ViewName { set; get; }
public String ViewQualifiedName { set; get; }
public Int64 ViewParentId { set; get; }


b. Create another model named RolePermission

public class RolePermission{
public IdentityRole RoleId { set; get; }

 public View ViewId { set; get; }


c. Add the DbSet property for RolePermission and View in the ApplicationDbContext class

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{
public ApplicationDbContext() : base(“SecurityTestDB”, throwIfV1Schema: false){
public DbSet<View> View { set; get; }

  public DbSet<RolePermission> RolePermissions { set; get; }

   public static ApplicationDbContext Create(){
    return new ApplicationDbContext();


d. Follow the same steps as above to migrate model changes into database.

e. When we run the migration using add-migration and update-database commands it will create another table named as View in the SecurityTestDB and defines one to many relationship between ASPNetRoles and RolePermission table and View and RolePermission table.

8. Now let suppose we need to add more fields in the AspNetUsers or any other identities table we can customize it by adding a new class inheriting from Identity* class and specify new properties.

a. For example in the ASPNetRoles I need to add IsActive bit which can be used to enable/disable role rather deleting it completely I can create new class named SecurityRoles

b. Derive SecurityRoles with IdentityRole

c. Add IsActive Boolean property as follows

d. Enable migration

 public override void Up(){
AddColumn(“dbo.AspNetRoles”, “IsActive”, c => c.Boolean());


 public override void Down()
DropColumn(“dbo.AspNetRoles”, “IsActive”);






With the power of Entity Framework and new Identity framework its quite easy now to customize security framework according to our need. The beauty is that the core classes remain intact and it doesn’t harm the underlying logic of the authentication mechanism provided by Microsoft.


Implementing Validation mechanism in ASP.Net MVC project using Unobtrusive JavaScript for validation

In this article I will walk you through the steps of implementing validation in the ASP.Net MVC project using jquery.validate.unobtrusive.js

What is Unobtrusive JavaScript?

Unobtrusive JavaScript is the best practices to separate the JavaScript code from presentation or html.

For example

onclick=”alert(‘hello world’)

The above code is obtrusive as we have called the JavaScript alert method within the html control’s input tag. In order to make this unobtrusive we can create a separate JavaScript file and with the help of jQuery we can register a click event for this button like this.

$(document).ready(function () {

$(‘#btn’).click(function (e) {

    alert(‘hello world’);



For validation there is a JavaScript named jquery.validate.unobtrusive.js which can automatically attach validation with all the input controls that you have in your html file. But those controls should have data-val attribute to true. Otherwise the validation for that particular control does not applied. In ASP.Net MVC, you know that there are many HTML helper functions like @Html.TextBoxFor, @Html.EditorFor, etc. that takes an expression and attributes. By default, when we use these methods in our code, depending on the data annotation attributes we have used in our Model it automatically applies the validation at the time of rendering the html control.

For example

If our model is

Person : Message


[GridColumn(“Id”, true)]

int Id { set; get; }



[GridColumn(“Name”, false)]

[StringLength(10, ErrorMessage=“Length cannot exceed to 10 character”)]

string Name { set; get; }


In ASP.Net MVC we can associate a model while adding a view and in that view we can call HTML helper functions like this

@Html.EditorFor(model => model.Name)

This will generates an html as follows

<input data-val=”true” data-val-length=”Length cannot exceed to 10 character” data-val-length-max=”10″ data-val-required=”The Name field is required.” id=”Name” name=”Name” type=”text” value=”Ovais” />

You can see that depending on the model it has automatically added the data-val-* properties in the html.

There is no magic, actually in order to make this work

  1. You have to add a jquery.validation.unobtrusive.js in your project.
  2. Then add the file path in the bundle like this





  3. Then add the script reference in the page as within the script section like this

@section scripts{



       4. Make sure you have controls place inside a form.

Handling validation in AJAX calls

When using server side post back in ASP.Net MVC validation works smooth. But for example if you want to invoke some AJAXified request on any button click and wanted to know if the form is validated or not you can add a code like this

$(‘#Save’).click(function (e) {

var $val = $(this).parents(‘form’);

if (!($val.valid()))


else alert(‘form have no errors’);


Hope this helps!    

Sync Calendar Events using CALDAV in C#

In this post I will walk you through the steps of reading calendar events from CALDAV supported servers. Yahoo, Google, etc. supports CALDAV

What is CALDAV?

CALDAV is an internet standard allowing client to access scheduling information on remote server. It’s an extension of WebDAV which is a HTTP-based protocol for data manipulation. The protocol is defined by RFC 4791. As it’s an extension to WEBDAV protocol it uses HTTP verbs to manipulate calendar events some of them mostly used are PROPFIND, SEARCH, etc.

Background Information

  1. Every server has a separate URI to access calendar events.



  1. Each Calendar folder is a collection and contains many calendar events. Each calendar event is a file and ended with .ics extension. .ics is well understood by many clients and you can easily export data from .ics to local client application.

How to Program

Now let’s see how to write a code to call Yahoo calendar events

  1. First of all create a new project in Microsoft Visual C# .NET
  2. Add reference to DDay.iCal library from Nuget Package manager console. This library will be used to read .ics files and read information about each event.
  3. Write below code to retrieve calendar event on any click event.


    In the above code snippet you have to configure your user name, password and modify the calendar URI depending on your calendarname and username.

If you see the code, I specified a content string which contains the request that I am sending it to the server. CALDAV have specific request formats which you can study here

ExecuteMethod is a helper method that sends request to the server and returns the response stream. Once I get the response stream I load the XML document and read the InnerXml of the file to get the complete XML. Then I parse the xml document and search for DAV:href element that contains the calendar event file (.ics) information. Once I get the list of .ics file paths, I call DownloadICS helper method to get the complete event information.

Helper Methods
Following are the helper method that performs specific operations. Please write these in your code to compile the project.

DownloadICS – Downloads .ics files


ExecuteMethod: Request calendar and returns response stream