Sunday, 25 March 2012

CRUD operation using ASP.NET Web Api and MVC 4 – Part 1

ASP.NET Web API is a framework for building HTTP services using the .NET Framework. Since HTTP services are supported virtually by any platform so its is a powerful tool that can reach to broader range of client like Native mobile applications, browsers, desktop applications, etc.

Being novice on this topic I just tried to flex my skills to create a basic application to demonstrate ASP.NET Web Api using ASP.NET MVC 4, jQuery, EF Code First approach and SQL Server Database. But I hope this example will give you enough confidence to get these technologies rolling in real time environment using MVC Web Api and MVC 4 as Client.

Since here I have not covered very basics of MVC and Web Api so if you are beginner to ASP.NET MVC, jQuery, etc., I recommend you to go through some good MSDN Articles first.

Before you start you may need to install ASP.NET MVC 4 Beta release in you system from the following location: http://www.asp.net/mvc/mvc4

This post was getting very large to fit into one single post so I have divided into three post which is as follows,

  1. CRUD operation using ASP.NET Web Api and MVC 4 – Part 1 (Creating a Web Api Service)
  2. CRUD operation using ASP.NET Web Api and MVC 4 – Part 2 (Creating a Client application which will consume Web Api Services)

1. Creating a Web Api Service.

Now lets start, as usual first you will have to create a new project from VS2010, by selecting the New Project –> Web –> ASP.NET MVC 4 Web Application template.

image

Give a name or select the default name for you project and then Click on Ok button, you will get the following screen where you can select your desired template for ASP.NET MVC 4 application type, for this example we have to Select Web API template using Razor view engine.

image

Once you click okay, you will get the default project solution structure for ASP.NET MVC Application, you may not see any difference between you normal MVC application or Web Api application. Now lets get into the code to see what additional features and class libraries are provided by Web Api project which makes it different and better from you normal MVBC Application. To show this lets first open the ValuesController provided by the template. In this screen you can see the ValuesController is derived from ApiController of System.Web.Http library instead of Controller of System.Web.Mvc library with the default method provided for GET, POST, PUT and DELETE methods. And the other difference you can notice here is the action methods used here is not returning ActionResult, JsonResult or FileResult, etc., instead it just returns data.

image

Now the only thing left for us to customize or extend this classes to serve our purpose, Web Api is basically meant to expose our interfaces as a RESTful. To start this first I have created a simple Contact table as given below. This table is used to Create, Read, Update and Delete a record.

image

Now I have added a ADO.NET Entity Data Model to connect to database, and on top of that I have created a simple repository where I have defined my contracts for Add, Update, Delete, GetAll and GetById method on my ContactDetail tables.

image

Now I will derive my IContactRepository in ContactModel class where I am going to have my implementation of all the methods using EntityFramework DBContext classes. Given below is the code for ContactModel class.

   1: public class ContactModel : IContactRepository



   2: {



   3:     ContactEntities context = new ContactEntities();



   4:  



   5:     /// <summary>



   6:     /// Gets All Contact



   7:     /// </summary>



   8:     /// <returns>All Contact Details</returns>



   9:     public IEnumerable<ContactDetail> GetAll()



  10:     {



  11:         return context.ContactDetails;



  12:     }



  13:  



  14:     /// <summary>



  15:     /// Get Contact by Contact ID



  16:     /// </summary>



  17:     /// <param name="contactId">Contact Id</param>



  18:     /// <returns>Contact Detail</returns>



  19:     public ContactDetail GetById(int contactId)



  20:     {



  21:         IQueryable<ContactDetail> customers = context.ContactDetails.Where(a => a.ContactId == contactId);



  22:         return customers.FirstOrDefault();



  23:     }



  24:  



  25:     /// <summary>



  26:     /// Updates Existing Contact



  27:     /// </summary>



  28:     /// <param name="contact">Contact</param>



  29:     /// <returns>result</returns>



  30:     public int Update(ContactDetail contact)



  31:     {



  32:         ContactDetail updateContact = context.ContactDetails.FirstOrDefault(c => c.ContactId == contact.ContactId);



  33:         updateContact.FirstName = contact.FirstName.Trim();



  34:         updateContact.MiddleName = contact.MiddleName.Trim();



  35:         updateContact.LastName = contact.LastName.Trim();



  36:         updateContact.EmailAddress = contact.EmailAddress.Trim();



  37:  



  38:         return context.SaveChanges();



  39:     }



  40:  



  41:     /// <summary>



  42:     /// Adds New Contact



  43:     /// </summary>



  44:     /// <param name="contact">Contact</param>



  45:     public ContactDetail Add(ContactDetail contact)



  46:     {



  47:         var addedContact = context.ContactDetails.Add(contact);



  48:         context.SaveChanges();



  49:  



  50:         return addedContact;



  51:     }



  52:  



  53:     /// <summary>



  54:     /// Deletes Contact



  55:     /// </summary>



  56:     /// <param name="contactId">Contact ID</param>



  57:     public void Delete(int contactId)



  58:     { 



  59:         ContactDetail contact = context.ContactDetails.FirstOrDefault(a=>a.ContactId == contactId);



  60:         context.ContactDetails.Remove(contact);



  61:         context.SaveChanges();



  62:     }



  63: }




Now before I go for my controller, I need to register my controller and default routes, in Global.asax.cs file, but in our example we don’t need to worry about this, as this is already provided by the default ASP.NET MVC 4 Web Api template. But in case if you have any specific path you want to register then you will have to define it from here.



image



Now my next Step will be to define my actual API’s in the controller classes, completed code of my API class is given below.





   1: using System.Collections.Generic;



   2: using System.Web.Http;



   3: using MvcAppWebApi.Models;



   4: using System.Net;



   5:  



   6: namespace MvcAppWebApi.Controllers



   7: {



   8:     public class ValuesController : ApiController



   9:     {



  10:         IContactRepository repository = new ContactModel();



  11:  



  12:         // GET /api/values



  13:         [HttpGet]



  14:         public IEnumerable<ContactDetail> Get()



  15:         {



  16:             return repository.GetAll();



  17:         }



  18:  



  19:         // GET /api/values/5



  20:         [HttpGet]



  21:         public ContactDetail Get(int id)



  22:         {



  23:             ContactDetail contact = repository.GetById(id);



  24:             return contact;



  25:         }



  26:  



  27:         // POST /api/values



  28:         [HttpPost]



  29:         public void PostContact(ContactDetail contact)



  30:         {



  31:             repository.Add(contact);



  32:         }



  33:  



  34:         // PUT /api/values



  35:         [HttpPut]



  36:         public void PutContact(ContactDetail contact)



  37:         {



  38:             if (repository.Update(contact)==0)



  39:             {



  40:                 throw new HttpResponseException(HttpStatusCode.NotFound);



  41:             }



  42:         }



  43:  



  44:         // DELETE /api/values/5



  45:         [HttpDelete]



  46:         public void Delete(int id)



  47:         {



  48:             repository.Delete(id);



  49:         }



  50:     }



  51: }




From the above code my ValuesController API will expose the following methods



image



In the Action list above, I have exposed the following methods as Web Api,





  1. Get – This method calls the GetAll method from Repository and returns all the Contacts from the Database as IEnumerable<ContactDetail>




  2. Get – This method accepts ContactId as parameter and calls the GetById method of Repository which finally returns corresponding ContactDetail.




  3. Add – This action method calls the Add method of Repository to add a new ContactDetail.




  4. Update – This method accepts ContactDetail as a parameter which in turns calls Update method of Repository to update the selected ContactDetail.




  5. Delete – This method accepts ContactId as input parameter and in turn calls the Delete method of Repository, Using the ContactId repository retrieves the Contact from the context and finally delete the ContactDetail from the Database.




To customize the relative URI, with different names like “mycompany/customers” you have to change the Register route from Global.asax.cs and the controller name. In the below figure I have left the default route name as “api” this can be changed to “mycompany” and rename the “ValuesController” to “CustomersController”  this will give you the Relative URI as “mycompany/customers”



image



Now my Web Api is ready to take request, to test the API run the application first and press F12 to run the developer toolbar. Now in the developer toolbar you need to select the Network Tab and Press the Start Capture button, Once you developer toolbar is ready to monitor the browser request and response, type the URL along with the existing URL of the browser as “/api/values/” this should give you the Result as 200 which means GET request is successfully executed,



image



Now go to the Detailed View of the selected request. and select the response body tab, this is displaying my response returned from the API, containing all the Contact Details which is present in my Database.



image



Similarly you can test the “api/values/{id}” URI also.



In my next Post I am going to create a Client Application which will consume the above created Services, for Get, GetById, Update, Add and Deleting a Contact using jQuery. And after this I am going to deploy my Services on Windows Azure platform



2. CRUD operation using ASP.NET Web Api and MVC 4 – Part 2 (Creating a client application which will consume Web Api Services)



3. Hosting ASP.NET Web Api on Windows Azure Platform



Source codes of Part 1 and Part 2 of this post can be found here : https://docs.google.com/open?id=0BzIjFd_Ps-MSUm4zMklvYkxUMXlFZzdOWVBsaHJvQQ

Share:

Tuesday, 24 January 2012

ASP.NET MVC 3 Custom Validation using Data Annotations

ASP.NET MVC 3 System.ComponentModel.DataAnnotations package provides a vast range of Data Annotations attribute, but there are certain scenarios where we need something which is very specific to our business requirements and we need to implement our own Validation Attributes. ASP.NET being an extensible framework which makes it possible for the developer to add user defined custom business validations using custom data annotations.

In this article I am going to demonstrate Custom Validation using ASP.NET Data Annotations.

First let us take a scenario where I need to create a form where I have to Draw a graph based on Date Range. In this form I have a graph control and From and To Date. Using the ‘Required’ DataAnnotation I can check if the Date is entered or not, Date Format can be validated using the RegularExpression Validator, but to validate some of the specific case like Comparing the From Date and To Date, Minimum date should not less than 2005, etc we need to create our Custom Validation Classes.

To start with this example lets first…

  1. Create a Telerik MVC 3 Web Application(Razor) from New Project. This is optional you can also use normal ASP.NET MVC 3 Web Project too.
  2. In the model folder create a Class ‘DateValidationAttribute.cs’ here we have to suffix the class with Attribute as this is a standard which is recognized by our ASP.NET MVC Application for any class to be used for DataAnnotation. Here the ‘Attribute’ suffix is suppressed and only the first part ‘DateValidation’ is used in the View Model Class as Data Annotation.
  3. Add a reference to System.ComponentModel.DataAnnotations.dll to our Project.
  4. Add a namespace reference of System.ComponentModel.DataAnnotation class in our DateValidationAttribute.cs class.
  5. In our DateValidationAttribute class implement ValidationAttribute base class, ValidationAttribute Class is the base class for all the System defined and user defined Custom Validation attribute classes.

With the steps given above our initial class will look something similar to the one below.

   1: public class DateValidationAttribute: ValidationAttribute



   2: {



   3:     public DateValidationAttribute()



   4:     { }



   5:     



   6: }




In this example I am creating a class named DateValidationAttribute.cs which extends base class ‘ValidationAttribute’  of System.ComponentModel.DataAnnotation package.



Now to provide the custom Validation Logic in this class we have to override the IsValid method of ValidationAttribute class and to make this class more generic, I have created a enum, which tells us what is the type of the validation I am going to use my DateValidation class.





   1: public enum ValidationType



   2: {



   3:     RangeValidation,



   4:     Compare



   5: }






And before we override the IsValid method we have to pass the initialization parameters to our DateValidationAttribute class constructor with the fromDate, toDate ValidationType, defaultErrorMessage and basePropertyName, here propertyNameToCompare is the property name of the ‘FromDate’.  We are going to need ‘FromDate’ to compare with ToDate and Validate the Dates.





   1: private ValidationType _validationType;



   2: private DateTime? _fromDate;



   3: private DateTime _toDate;



   4: private string _defaultErrorMessage;



   5: private string _propertyNameToCompare;



   6:  



   7: public DateValidationAttribute(ValidationType validationType, string message, string compareWith = "", string fromDate= "")



   8: {



   9:     _validationType = validationType;



  10:     switch (validationType)



  11:     {



  12:         case ValidationType.Compare:



  13:             {



  14:                 _propertyNameToCompare = compareWith;



  15:                 _defaultErrorMessage = message;



  16:                 break;



  17:             }



  18:         case ValidationType.RangeValidation:



  19:             {



  20:                 _fromDate = new DateTime(2000,1,1);



  21:                 _toDate = DateTime.Today;



  22:                 _defaultErrorMessage = message;



  23:                 break;



  24:             }



  25:  



  26:     }



  27: }




Now we are ready to override the IsValid method where we are going to implement the actual business rule validation. I have used Switch statement here to check which Validation Type the user is requested for.





   1: protected override ValidationResult IsValid(object value, ValidationContext validationContext)



   2: {



   3:     switch (_validationType)



   4:     {



   5:         case ValidationType.Compare:



   6:             {



   7:                 var baseProperyInfo = validationContext.ObjectType.GetProperty(_propertyNameToCompare);



   8:                 var startDate = (DateTime)baseProperyInfo.GetValue(validationContext.ObjectInstance, null);



   9:  



  10:                 if(value!=null)



  11:                 {



  12:                     DateTime thisDate = (DateTime)value;



  13:                     Type classType = typeof(TelerikMvcCustomValidationApp.Models.AccountModel);



  14:                     PropertyInfo methodInfo = classType.GetProperty(_propertyNameToCompare);



  15:                     DisplayAttribute displayAttr = (DisplayAttribute)Attribute.GetCustomAttribute(methodInfo, typeof(DisplayAttribute));



  16:                     if (thisDate <= startDate)



  17:                     {



  18:                         string message = string.Format(_defaultErrorMessage, validationContext.DisplayName, displayAttr.Name);



  19:                         return new ValidationResult(message);



  20:                     }



  21:                 }



  22:                 break;



  23:             }



  24:         case ValidationType.RangeValidation:



  25:             {



  26:                //Range Validation Logic Here



  27:                 break;



  28:             }



  29:        



  30:     }



  31:     return null;



  32: }



  33:     }






IsValid method above returns the ValidationResult which is a member of System.ComponentModel.DataAnnotation. Here ValidationResult represents a container for the results of a validation request. Now with these pieces of code our DateValidationAttribute class is ready to consume. I understand that there are lots of tight coupling with the implementation class with this Validation component, this code is just for indicative usage of the Custom Data Annotation an extensibility feature provided by ASP.NET. In actual this class may require few changes.



Now lets come to my model class where I am going to use this as Data Annotation Attribute. In this example I have created a AccountModel.cs class and declared just two properties one is ToDate and another is FromDate for this example.





   1: public class AccountModel



   2: {



   3:     [Display(Name = "From Date")]



   4:     [Required]



   5:     public DateTime FromDate { get; set; }



   6:  



   7:     [Display(Name = "To Date")]



   8:     [Required]



   9:     [DateValidation(ValidationType.Compare, "Selected dates should be Less than From Date.", compareWith: "FromDate")]



  10:     public DateTime ToDate { get; set; }



  11: }






In this example I have used Telerik controls for DatePicker control. Telerik controls for MVC can be installed from Tools—>Extension Manager—> Online Templates. This Date controls I have created as a partial view in Views—>Shared folder, so that this can be used across my applications.





   1: @model TelerikMvcCustomValidationApp.Models.AccountModel



   2: @{



   3:     ViewBag.Title = "Home Page";



   4: }



   5: <form action="/Home/DateValidate" method="post">



   6: <h2>@ViewBag.Message</h2>



   7: <fieldset>



   8:     <span>



   9:         @Html.LabelFor(m => m.FromDate)



  10:         @Html.Telerik().DatePickerFor(m => m.FromDate)



  11:         @Html.ValidationMessageFor(m => m.FromDate)



  12:     </span>



  13:     <br />



  14:     <span>



  15:         @Html.LabelFor(m => m.ToDate)



  16:         @Html.Telerik().DatePickerFor(m => m.ToDate)



  17:         @Html.ValidationMessageFor(m => m.ToDate)



  18:     </span>



  19: </fieldset>



  20: <input type="submit" value="Validate Date" name="btnValidate" id="btnValidate" />



  21: </form>




In the code above I am keeping the form method as post and Action to my DateValidation Action of HomeController. When the user clicks the Submit button the form Post the result to Controller and triggers the Validation logic defined in our Custom Validation Logic.



Now to embed this partial view into my Index page I have to write just one line as below in ‘Index.cshtml’ page.





@Html.Partial("DateValidate")



And that’s it in the View Side, if you are already familiar with MVC and Razor this code will be very simple for you to understand.

Now coming to my Home Controller, where I have created an Action method which Provides custom action on Validation failure and Success.





public ActionResult DateValidate(AccountModel model)



{



    if (!ModelState.IsValid)



        return View(model);



    return RedirectToAction("About");



}






Just to keep this simple I am redirecting the user to About Page of my ASP.NET MVC Application, which is already provided. And for Validation failure I am keeping the user in the same page with the validation message displayed. Now lets assemble all the pieces of codes and test it. I am entering the invalid data where I am keeping the From Date more than To Date, with this I am getting the result as given in the screen below.



image



And for the built in Required Field Validation



image



If you can look into the code above for DateValidationAttribute class I have also provided an additional Validation for Date Range Validation, this can be used to restrict the user to enter dates in some Range based on the Business requirements.  I am leaving it for you to implement. In order to Implement the same attribute multiple times we have to just fine tune some lines of my code as below.



image



But you can see above by default you cannot use the same Data Annotation Attribute multiple times in the same Property. To Get this working you have to provide additional Attribute to our DateValidationAttribute Class as below.



image



With AllowMultiple=true we can use the same DataAnnotation attribute multiple times in the same Property.



This code is just an extract of the actual implementation which is more structured and bigger. But I hope this example will give you a quick start on how to use the Custom Validation Data Annotation attributes. For further reading you can follow the links below from MSDN.





You can also download the sample code from here.

Share:

Saturday, 14 January 2012

MphasiS – Spirit of Winning Award, Dec 2011

I am glad to announce that once again second time in a year I received MphasiS – Spirit of Winning award for the month of Dec 2011. This award is presented to the individual for living by the MphasiS Values and demonstrating the Winning Spirit.

image

This came as a great new year gift for me. Thanks to all my colleagues, managers and my readers for their continuous support.

Share: