Showing posts with label MVC 4. Show all posts
Showing posts with label MVC 4. Show all posts

Wednesday, 24 April 2013

Device Detection in ASP.NET MVC 4

In this example I am going to demonstrate the MVC 4 Device detection libraries. ASP.NET MVC 4 introduces Display Modes to which allows you to write device specific application. This is a newly introduced feature of ASP.NET MVC 4. This selects a view depending on the browser making the request, which means you can target specific devices and present the user device specific customized pages.

By default Display Mode Provider implements the mobile view;

clip_image002

You just need to provide the mobile specific pages to your application by just creating a pagename.mobile.cshtml and you are done.

clip_image004

I have done few customizations in my Web and Mobile pages just to display the requesting browser UserAgent and to identify if this is a page for web or mobile. Now let’s run the application and see output.

I have used Mozilla User Agent Switcher Add-on here to switch between the browsers. clip_image002[4]

Page displayed by default User Agent (Desktop)

clip_image004[4]

Page displayed when I select the iPhone as User Agent.

You can notice here that this all achieved without even writing a piece of code till now, with just the addition of .mobile.cshtml page I am able to achieve this.

But in real world things are not so straight forward, we have plenty of devices emerging every year and we have to provide device specific pages for each one of those devices with very little or negligible development effort and of course with minimal code changes.

With display mode provider we cannot just add a device specific pages instead we can also specify Browser specific page, OS Specific pages and even Vendor specific pages yes that is true. The only thing what we need to know is the identifiable user agent which provides us enough information about the Browser, Device, OS, etc information.

Now let me add some customization to my code for iPhone. In this case I am going to display a page which is specific to only iPhone. First of all let’s create a page for iPhone as Index.iphone.cshtml

clip_image006

You can and add some code which will tell us on runtime that this page is only meant for iPhone. Now add few lines of code in Global.ascx.cs file. Here in these codes I have added entry into the DisplayModeProvider for iPhone, this will tell the application that whenever you see the iPhone text in the browser UserAgent, just take the user to Index.iphone.cshtml page.

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iphone")



{



     ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf("iphone", StringComparison.OrdinalIgnoreCase) >= 0)



});






Now let’s see the output at runtime,



clip_image002[8]



Here in the screen above you can see that I have got an additional entry for iphone in DisplayModeProvider collection, and the output screen I got from the code is as below:



clip_image004[9]



Similarly you can add as many entries as you wish, and for e.g if you want to have same page for multiple devices like for iPad and Tablet I want to display Index.tablet.cshtml page, then you can write the codes as:





DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("tablet")



{



    ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf("tablet", StringComparison.OrdinalIgnoreCase) >= 0



    || context.GetOverriddenUserAgent().IndexOf("ipad", StringComparison.OrdinalIgnoreCase) >= 0)



});




So you can see DisplayModeProvider is fully customizable and extensible based on your requirement. But the catch is you need to have a complete list of Browser User Agents to handle virtually all the possible devices programmatically from your code. For I came across one very interesting link from Tech Brij Blog, including the code provided in this blog will complete this example and you can have a complete working example of the device detection using MVC 4





private static string GetDeviceType(string ua)



{



    string ret = "";



    // Check if user agent is a smart TV - http://goo.gl/FocDk



    if (Regex.IsMatch(ua, @"GoogleTV|SmartTV|Internet.TV|NetCast|NETTV|AppleTV|boxee|Kylo|Roku|DLNADOC|CE\-HTML", RegexOptions.IgnoreCase))



    {



        ret = "tv";



    }



    // Check if user agent is a TV Based Gaming Console



    else if (Regex.IsMatch(ua, "Xbox|PLAYSTATION.3|Wii", RegexOptions.IgnoreCase))



    {



        ret = "tv";



    }



    // Check if user agent is a Tablet



    else if ((Regex.IsMatch(ua, "iP(a|ro)d", RegexOptions.IgnoreCase) || (Regex.IsMatch(ua, "tablet", RegexOptions.IgnoreCase)) && (!Regex.IsMatch(ua, "RX-34", RegexOptions.IgnoreCase)) || (Regex.IsMatch(ua, "FOLIO", RegexOptions.IgnoreCase))))



    {



        ret = "tablet";



    }



    // Check if user agent is an Android Tablet



    else if ((Regex.IsMatch(ua, "Linux", RegexOptions.IgnoreCase)) && (Regex.IsMatch(ua, "Android", RegexOptions.IgnoreCase)) && (!Regex.IsMatch(ua, "Fennec|mobi|HTC.Magic|HTCX06HT|Nexus.One|SC-02B|fone.945", RegexOptions.IgnoreCase)))



    {



        ret = "tablet";



    }



    // Check if user agent is a Kindle or Kindle Fire



    else if ((Regex.IsMatch(ua, "Kindle", RegexOptions.IgnoreCase)) || (Regex.IsMatch(ua, "Mac.OS", RegexOptions.IgnoreCase)) && (Regex.IsMatch(ua, "Silk", RegexOptions.IgnoreCase)))



    {



        ret = "tablet";



    }



    // Check if user agent is a pre Android 3.0 Tablet



    else if ((Regex.IsMatch(ua, @"GT-P10|SC-01C|SHW-M180S|SGH-T849|SCH-I800|SHW-M180L|SPH-P100|SGH-I987|zt180|HTC(.Flyer|\\_Flyer)|Sprint.ATP51|ViewPad7|pandigital(sprnova|nova)|Ideos.S7|Dell.Streak.7|Advent.Vega|A101IT|A70BHT|MID7015|Next2|nook", RegexOptions.IgnoreCase)) || (Regex.IsMatch(ua, "MB511", RegexOptions.IgnoreCase)) && (Regex.IsMatch(ua, "RUTEM", RegexOptions.IgnoreCase)))



    {



        ret = "tablet";



    }



    // Check if user agent is unique Mobile User Agent



    else if ((Regex.IsMatch(ua, "BOLT|Fennec|Iris|Maemo|Minimo|Mobi|mowser|NetFront|Novarra|Prism|RX-34|Skyfire|Tear|XV6875|XV6975|Google.Wireless.Transcoder", RegexOptions.IgnoreCase)))



    {



        ret = "mobile";



    }



    // Check if user agent is an odd Opera User Agent - http://goo.gl/nK90K



    else if ((Regex.IsMatch(ua, "Opera", RegexOptions.IgnoreCase)) && (Regex.IsMatch(ua, "Windows.NT.5", RegexOptions.IgnoreCase)) && (Regex.IsMatch(ua, @"HTC|Xda|Mini|Vario|SAMSUNG\-GT\-i8000|SAMSUNG\-SGH\-i9", RegexOptions.IgnoreCase)))



    {



        ret = "mobile";



    }



    // Check if user agent is Windows Desktop



    else if ((Regex.IsMatch(ua, "Windows.(NT|XP|ME|9)")) && (!Regex.IsMatch(ua, "Phone", RegexOptions.IgnoreCase)) || (Regex.IsMatch(ua, "Win(9|.9|NT)", RegexOptions.IgnoreCase)))



    {



        ret = "desktop";



    }



    // Check if agent is Mac Desktop



    else if ((Regex.IsMatch(ua, "Macintosh|PowerPC", RegexOptions.IgnoreCase)) && (!Regex.IsMatch(ua, "Silk", RegexOptions.IgnoreCase)))



    {



        ret = "desktop";



    }



    // Check if user agent is a Linux Desktop



    else if ((Regex.IsMatch(ua, "Linux", RegexOptions.IgnoreCase)) && (Regex.IsMatch(ua, "X11", RegexOptions.IgnoreCase)))



    {



        ret = "desktop";



    }



    // Check if user agent is a Solaris, SunOS, BSD Desktop



    else if ((Regex.IsMatch(ua, "Solaris|SunOS|BSD", RegexOptions.IgnoreCase)))



    {



        ret = "desktop";



    }



    // Check if user agent is a Desktop BOT/Crawler/Spider



    else if ((Regex.IsMatch(ua, "Bot|Crawler|Spider|Yahoo|ia_archiver|Covario-IDS|findlinks|DataparkSearch|larbin|Mediapartners-Google|NG-Search|Snappy|Teoma|Jeeves|TinEye", RegexOptions.IgnoreCase)) && (!Regex.IsMatch(ua, "Mobile", RegexOptions.IgnoreCase)))



    {



        ret = "desktop";



    }



    // Otherwise assume it is a Mobile Device



    else



    {



        ret = "mobile";



    }



        return ret;



}




The code above covers a very exhaustive list of devices/browsers/OS which are available. This is a reengineered version of Categorizr(A device detection script) provided with premium version of 51degrees.mobi



The function provided above uses RegEx library to find the matching content in the Browser User Agent string and based on the match it returns the device type as string. The Code below calls the GetDevice function to get the device type string to the ContextCondition as either tablet, mobile or tv.





DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("tablet")



{



   ContextCondition = (context => GetDeviceType(context.GetOverriddenUserAgent()) == "tablet")



});



DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("tv")



{



   ContextCondition = (context => GetDeviceType(context.GetOverriddenUserAgent()) == "tv")



});



DisplayModeProvider.Instance.Modes.Insert(2, new DefaultDisplayMode("mobile")



{



   ContextCondition = (context => GetDeviceType(context.GetOverriddenUserAgent()) == "mobile")



}); 




This is just a small sample of the Display Mode Provided packaged with ASP.NET MVC 4, other links which might help you in understanding the overall concepts are:



References:



http://www.campusmvp.net/displaymodes-in-mvc-4/



http://msdn.microsoft.com/en-us/library/system.web.webpages.displaymodeprovider(v=vs.111).aspx



Sample project with the implementation can be downloaded from here:



https://docs.google.com/file/d/0BzIjFd_Ps-MSQThrTklrbXZOQlU/edit?usp=sharing

Share:

Wednesday, 14 November 2012

My Top 8 picks for Microsoft.NET Architects (ASP.NET MVC)

Past few month was very hectic for me, now since I have some time for myself I am sharing the list of articles which I am going through, these articles are basically related to architecting .NET application using ASP.NET MVC. I hope you will find these links useful for you too.

  1. Of course not to mention GoF Design Pattern Tutorial: http://www.dofactory.com/Patterns/Patterns.aspx
  2. On the same line as above, this link elaborates the patterns by GoF as Illustrated GOF Design Patterns in C# Part I: Creational: (Series Article)http://www.codeproject.com/Articles/3130/Illustrated-GOF-Design-Patterns-in-C-Part-I-Creati
  3. A N-Tier Architecture Sample with ASP.NET MVC3, WCF, and Entity Framework : http://www.codeproject.com/Articles/434282/A-N-Tier-Architecture-Sample-with-ASP-NET-MVC3-WCF
  4. Design pattern – Inversion of control and Dependency injection by By Shivprasad Koirala: http://www.codeproject.com/Articles/29271/Design-pattern-Inversion-of-control-and-Dependency
  5. LINQ and WF Based Custom Profile Provider for ASP.NET 3.5, this article demonstrates Microsoft Provider Pattern using Workflow Foundation: http://www.codeproject.com/Articles/31308/LINQ-and-WF-Based-Custom-Profile-Provider-for-ASP
  6. patterns & practices Application Architecture Guide 2.0, Microsoft Link from where you can download free eBook, Microsoft Application Architecture Guide – by J.D. Meier, Alex Homer, David Hill, Jason Taylor, Prashant Bansode, Lonnie Wall, Rob Boucher Jr, Akshay Bogawat : http://apparchguide.codeplex.com/ or direct Link to download the eBook: Download the final release in PDF on MSDN, either you can download the pdf from this link or you can read the same book online at the link: http://msdn.microsoft.com/en-us/library/dd673617.aspx
  7. Architecture Guide: ASP.NET MVC Framework + N-tier + Entity Framework and Many More : http://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En
  8. Security is the most important aspect of any application specially when you are dealing with financial intuitions, even the best of the architecture is good-for-nothing if is is not secure. This is the link of top 10 Security vulnerabilities provided by Open Web Application Security Project, a non-profit charitable organization and elaborated with solution by Troy Hunt: OWASP Top 10 for .NET developers part 1: Injection : (Series Article) http://www.troyhunt.com/2010/05/owasp-top-10-for-net-developers-part-1.html , same is available for download as pdf eBook from  : http://asafaweb.com/OWASP%20Top%2010%20for%20.NET%20developers.pdf

This list is open for comments, so go ahead and suggest me if you have good links which I can add to my top 8 and in the same line. Thanks.

Share:

Sunday, 1 April 2012

Hosting ASP.NET Web Api on Windows Azure Platform

In this post I am going to show you how to Host your ASP.NET Web Api Services on Windows Azure, to demonstrate this I am going to use my application which I have created in my previous couple of Post :

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

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

Before hosting my application I have to perform the following steps.

1. Add an Cloud Application from Add New project

image

2. Select ASP.NET MVC 4 Web Role, since I have used ASP.NET MVC 4 to create my Web Api project.

image

3. From the following Screen I have to select cancel, since I am adding this to my existing Web Api Project, and don’t want to create a new Applications.

image

4. Once the project creation is successful, right click on the Roles folder from the WebRole.Azure project and Select Add, from the add menu select Web Role Project in solution  and Select the WebApi Project listed in the Popup windows. This will add my Web Api project in the Roles folder of Azure project as given in the screen below.

image

image

5. Now our Azure project is configured to publish my WebApi service on Web, but before we publish we need to configure the Database connection which is currently pointing to my local system, we need to change this to the SQL Azure database. Since SQL Azure setup and configuration is out of scope of this Post, so I am not going to cover that here, but don’t worry I have given that instruction in my another post, which will help you to configure the Entity Framework EDMX with SQL Azure.

6. Now once your application is ready with the SQL Azure connection, we will publish our Application on Windows Azure. But before we continue, we may have to configure publish settings in my system, sometime back I have written couple of articles where you can find how to publish your website on Windows Azure. But simplest way to do the same I have given below. Right click on your Windows Azure project and Select Publish, You will be prompted with the screen below. Now Select the option “Sign in to download credential”

image

7. This link will take you to the windows azure site, where you will have to provide your credentials and then you can download the publishsettings files, using the Save as option. Save this file to your system.

image

8. Now select the import button and locate the downloaded publishsettings file, this will auto populate the Subscription dropdown as given below, I have used my 3 months free subscription to demonstrate this. You too can subscribe to 3 months free trial from here.

image

9. Provide your Name and Location details.

image

10. Select Ok then Next, you will land up in the below screen, where you can Say next.

image

11. Finally you will provided with the Publish Summary settings, where you can review your settings and it everything looks good then you can click on publish.

image

12. You can see the progress here, or if you want you can see the same in your Windows Azure console also.

image

Windows Azure console.

image

13. Once ready you will be come to the following screen, where you can see the status as Ready.

image

And that’s it we are ready to test our application. You can get the DNS name (URI) of your Web Api Service from the console once your applications are ready. Lets try out Api Services, in the browser using Developer ToolBar. Following are the list of Methods and URI are exposed to web.

image

Lets try with the Get (/api/values) and check in Dev Toolbar, So I am getting the Responsed code 200 and in the detailed view –> Response Body I can see my result returned from my Api Service.

image

image

Now lets try from from the Client screen where I have written few lines of jQuery to demonstrate the CRUD operation, details of which you can refer in my previous post.

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

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

GetById (/api/values/1) and GetAll (/api/values)

image

image

The codes for these sample can be downloaded from here https://docs.google.com/open?id=0BzIjFd_Ps-MSUm4zMklvYkxUMXlFZzdOWVBsaHJvQQ

This is the same code which I have already provided in my previous post : CRUD operation using ASP.NET Web Api and MVC 4 – Part 2, You will just have to do the configurations which I have mentioned in this post. Hope this helps.

Share:

Wednesday, 28 March 2012

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

This Post is continuation to my Previous Post where I have created a ASP.NET Web Api Service, In this Post I am going to create a simple client using jQuery, MVC 4 and Razor View Engine to call the Services and perform POST, DETELE, PUT and of course GET operations using the Web Api Service.

To get the Service details which I am going to consume in this article, you can refer to the Part 1 of this post : CRUD operation using ASP.NET Web Api and MVC 4 – Part 1

Lets just directly get into my client code, as discussed in Part 1 of this post, on how to create a Web Api Project you can follow the same steps here,

OR alternatively you can use any existing application not necessarily on MVC 4, it can be any web application which supports jQuery version 1.6.2 or later. Now lets start one by one

1. Get (Get All Records, GET)

In this function I have given a sample which gets all the records present in my Database using code first approach of entity framework, jQuery and ASP.NET Web Api Services. I have used two approach here, one using getJson function of jQuery and the other using ajax function.

   1: function GetCustomersAJAX() {



   2:        $.ajax({



   3:            url: "/api/values/",



   4:            type: "GET",



   5:            contentType: "application/json;charset=utf-8",



   6:            success: function(data)



   7:            {



   8:            //declare a varialbe which holds html string to be appnended to create a table structure from returned data                



   9:            var strHTML = "<table width='50%' style='border-width:thin;font-family:Verdana;font-size:small;border-collapse:collapse' border='1'>";



  10:            strHTML += "<tr><th>Contact ID</th><th>First Name</th><th>Middle Name</th><th>Last Name</th><th>Email Address</th></tr>";



  11:            //iterate over every object returened using each function                 



  12:            $.each(data, function (key, val) {



  13:                //Form a html row string based on the returned Json object                    



  14:                strHTML += "<tr>";



  15:                strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.ContactId + "</td>";



  16:                strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.FirstName + "</td>";



  17:                strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.MiddleName + "</td>";



  18:                strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.LastName + "</td>";



  19:                strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.EmailAddress + "</td>";



  20:                strHTML += "</tr>";



  21:            });



  22:            $('#contacts').append(strHTML);



  23:            },



  24:            statusCode: {



  25:                200: function () {



  26:                    alert("All Contact Displayed successfully using AJAX");



  27:                }



  28:            }



  29:            });



  30:        };




The function above calls the api url “api/values” without any input parameters using AJAX, and the same call using JSON is as below





   1: function GetCustomersJSON() {



   2:     $.getJSON("/api/values", function (data) {



   3:         //declare a varialbe which holds html string to be appnended to create a table structure from returned data                



   4:         var strHTML = "<table width='50%' style='border-width:thin;font-family:Verdana;font-size:small;border-collapse:collapse' border='1'>";



   5:         strHTML += "<tr><th>Contact ID</th><th>First Name</th><th>Middle Name</th><th>Last Name</th><th>Email Address</th></tr>";



   6:         //iterate over every object returened using each function                 



   7:         $.each(data, function (key, val) {



   8:             //Form a html row string based on the returned Json object                    



   9:             strHTML += "<tr>";



  10:             strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.ContactId + "</td>";



  11:             strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.FirstName + "</td>";



  12:             strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.MiddleName + "</td>";



  13:             strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.LastName + "</td>";



  14:             strHTML += "<td width='20%' style='border:1 solid gray;'>" + val.EmailAddress + "</td>";



  15:             strHTML += "</tr>";



  16:         });



  17:         //append html table to div                



  18:         $('#contacts').append(strHTML);



  19:     });



  20: }




Both my function above gives the list of all the contacts I have in my DB and wraps the results in a HTML Tables using $each method of jQuery. Just for a quick reference here I am giving below the Get method which maps to the url “api/values”





   1: // GET /api/values



   2: [HttpGet]



   3: public IEnumerable<ContactDetail> Get()



   4: {



   5:     return repository.GetAll();



   6: }




And the corresponding repository method is as below:





   1: ContactEntities context = new ContactEntities();



   2:  



   3: /// <summary>



   4: /// Gets All Contact



   5: /// </summary>



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



   7: public IEnumerable<ContactDetail> GetAll()



   8: {



   9:     return context.ContactDetails;



  10: }




When I run my application and press the Get All Button either Ajax or Json, I will get the following result.



image



Now let me run my Developer toolbar using F12 key of IE 9 to show you the result in raw data format using Ajax and Json.



image



This is giving me the the Http result as 200, which means Get request is Successful, which exactly I am checking in the jQuery ajax code using the statusCode: 200, and displaying the Success message. Similarly for other results we can either return from my controller as 404 not found and handle it here to display appropriate message.



image



Now lets dig more into this request, by clicking into go to detailed view of developer toolbar and see the response body, this gave me the following Text output, this will be same for both JSON and AJAX.



[{"ContactId":1,"EmailAddress":"bmdayal@hotmail.com ","FirstName":"Brij      ","LastName":"Dayal     ","MiddleName":"Mohan     "},{"ContactId":2,"EmailAddress":"arunudai@abccorp.com","FirstName":"Arun      ","LastName":"Udai      ","MiddleName":"Dayal     "},{"ContactId":13,"EmailAddress":"somwhere@abccorp.com","FirstName":"Someone   ","LastName":"Sometime  ","MiddleName":"Somewhere "}]


2. Get (Get By Id, GET)



Now let me take you to my next Get request which is get by Id, this will take id as a parameter and returns me the specific contact:





   1: function GetCustomersByIdAJAX() {



   2:     //declare a varialbe which holds html string to be appnended to create a table structure from returned data



   3:     $.ajax({



   4:     url: "/api/values/" + $("#ContactId").val(),



   5:         type: "GET",



   6:         contentType: "application/json;charset=utf-8",



   7:         success: function(data)



   8:         {



   9:              if (data != null) {



  10:                  $("#ContactFName").val(data.FirstName);



  11:                  $("#ContactMName").val(data.MiddleName);



  12:                  $("#ContactLName").val(data.LastName);



  13:                  $("#ContactEmail").val(data.EmailAddress);



  14:              }



  15:              else {



  16:                  alert("Customer does not exists");



  17:                 ResetForm();



  18:              }



  19:          },



  20:          statusCode: {



  21:             //Web API Post method returns status code as 201                    



  22:             200: function () {



  23:                 $('#errMsg').html('');



  24:                 //alert("Contact Displayed successfully using AJAX");



  25:                 //GetCustomersById();



  26:             },



  27:              400:  function (jqXHR, textStatus, err) 



  28:              {                    



  29:                 $('#errMsg').html('Error: ' + err);                



  30:              },



  31:              404: function (jqXHR, textStatus, err) 



  32:              {                    



  33:                 $('#errMsg').html('Error: ' + err);                



  34:              }



  35:          }



  36:        });



  37: }




And the same code using Json is as follows





   1: function GetCustomersByIdJSON() {



   2:     //declare a varialbe which holds html string to be appnended to create a table structure from returned data



   3:     $.getJSON("api/values/" + $("#ContactId").val(),



   4:          function (data) {



   5:              if (data != null) {



   6:                  $("#ContactFName").val(data.FirstName);



   7:                  $("#ContactMName").val(data.MiddleName);



   8:                  $("#ContactLName").val(data.LastName);



   9:                  $("#ContactEmail").val(data.EmailAddress);



  10:                  $('#errMsg').html('');



  11:              }



  12:              else {



  13:                  alert("Customer does not exists");



  14:                 ResetForm();



  15:              }



  16:          })



  17:          .fail(                



  18:              function (jqXHR, textStatus, err) 



  19:              {                    



  20:                 $('#errMsg').html('Error: ' + err);                



  21:              });



  22:  



  23:     return false;



  24: }




In the code above for AJAX I have handled the different error codes aka Not Found, Bad Request or Success using their error codes, to elaborate more on this let me first give here the code for controller





   1: // GET /api/values/5



   2: [HttpGet]



   3: public ContactDetail Get(int id)



   4: {



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



   6:     if (contact == null)



   7:         throw new HttpResponseException(HttpStatusCode.NotFound);



   8:     return contact;



   9: }




So now you can see above few things, first of all my Contact Id should be integer, if this this not integer then I will get HttpResponseException as BadRequest (400), and if the Contact Id does not exists then I am explicitly throwing the Not Found Exception (404) and if everything is success the system is giving me Success response (200), which I am handling in my jQuery as below



image



Now when I run my application I will get the following result:



For Success Result (200)



image



For Bad Request (400):



image



And finally for Not Found (404)



image



These are just few examples, you can have as many as possible depending upon your requirements. The code of the repository is given below I hope this code is self explanatory,





   1: /// <summary>



   2: /// Get Contact by Contact ID



   3: /// </summary>



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



   5: /// <returns>Contact Detail</returns>



   6: public ContactDetail GetById(int contactId)



   7: {



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



   9:     return customers.FirstOrDefault();



  10: }




So with these codes above I have covered the GET, now lets move on to PUT, POST and DELETE of Web Api. defined as Update, Add and Delete in my example.



3. Update (PUT)



In this method I have created a simple form where I can search for a contact as I have given in my example above, displaying the values in the HTML text boxes, updating those values and finally I am saving those updated values back to my Database.



Her let me start in reverse direction, I am first giving my repository code and then controller and then I will show how I am updating those values using jQuery.





   1: /// <summary>



   2: /// Updates Existing Contact



   3: /// </summary>



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



   5: /// <returns>result</returns>



   6: public int Update(ContactDetail contact)



   7: {



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



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



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



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



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



  13:  



  14:     return context.SaveChanges();



  15: }




My repository codes are very simple I am just taking the updated contact from the controller, searching the same in the context of Entity model, and finally calling SaveChanges.





   1: // PUT /api/values



   2: [HttpPut]



   3: public void PutContact(ContactDetail contact)



   4: {



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



   6:     {



   7:         throw new HttpResponseException(HttpStatusCode.NotFound);



   8:     }



   9: }




Controller codes is also just taking the value from the HttpRequestContext and just passing the values to the repository, now lets get into my view code where I am taking the values from the Html Controls, creating the Json object and using Ajax I am passing the contact object to the controller.





   1: function UpdateContact() {



   2:     //create a Json object based on data entered by user            



   3:     var newContact = {



   4:         ContactID: $("#ContactId").val(),



   5:         FirstName: $("#ContactFName").val(),



   6:         MiddleName: $("#ContactMName").val(),



   7:         LastName: $("#ContactLName").val(),



   8:         EmailAddress: $("#ContactEmail").val(),



   9:     };



  10:     //call jQuery Ajax method which calls Json.stringify method to convert             



  11:     //the Json object into string and send it with post method            



  12:     $.ajax({



  13:         url: "/api/values/",



  14:         data: JSON.stringify(newContact),



  15:         type: "PUT",



  16:         contentType: "application/json;charset=utf-8",



  17:         statusCode: {



  18:             //Web API Post method returns status code as 201                    



  19:             200: function () {



  20:                 alert("Employee Updated successfully");



  21:                 //GetCustomersById();



  22:             }



  23:         }



  24:     });



  25:     return false;



  26: }




In the above example once I created the contact object in JSON, I am using the Json.stringyfy method to convert the object to string format, which can be passed to the controller. Now lets see this in action, in the developer toolbar you can see my both the results are showing 200, one is used for GET and other for PUT,



image



Now lets get deeper into the request and response. Here you can see my Request body has the updated values, which is passed as a string to the Action method Update, which in turn calls the repository and update my contact Database.



image



4. Add (POST)



As the name indicates this method is used to Add a new record to the Database, my Add method is very much similar to the Update method only difference is instead of calling the HttpPut this is using HttpPost, and in repository I have to add a new contact object to the entity context and save the changes.





   1: function AddContact() {



   2:     //create a Json object based on data entered by user            



   3:     var newContact = {



   4:         ContactID: $("#ContactId").val(),



   5:         FirstName: $("#ContactFName").val(),



   6:         MiddleName: $("#ContactMName").val(),



   7:         LastName: $("#ContactLName").val(),



   8:         EmailAddress: $("#ContactEmail").val(),



   9:     };



  10:     //call jQuery Ajax method which calls Json.stringify method to convert             



  11:     //the Json object into string and send it with post method            



  12:     $.ajax({



  13:         url: "/api/values/",



  14:         data: JSON.stringify(newContact),



  15:         type: "POST",



  16:         contentType: "application/json;charset=utf-8",



  17:         statusCode: {



  18:             //Web API Post method returns status code as 201                    



  19:             200: function () {



  20:                 alert("Employee Added successfully");



  21:                 //GetCustomersById();



  22:             }



  23:         }



  24:     });



  25:     return false;



  26: }




You can see my jQuery code, this is same as what I have used for update, only difference is instead of using the PUT I am using POST



image



and this will call the action method which is listening to HttpPost.





   1: // POST /api/values



   2: [HttpPost]



   3: public void PostContact(ContactDetail contact)



   4: {



   5:     repository.Add(contact);



   6: }




and my repository method is taking the contact object and saving this to the Database





   1: /// <summary>



   2: /// Adds New Contact



   3: /// </summary>



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



   5: public ContactDetail Add(ContactDetail contact)



   6: {



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



   8:     context.SaveChanges();



   9:  



  10:     return addedContact;



  11: }




Now lets see this in action.



image



the last result returned in the Dev Toolbar shows the result as 200, and the method as POST, which means addition successful, if you check the detailed view this will give you the request body which is very much similar to what we have in update method.



5. Delete (DELETE)



And last but not the least, lets clean up my unwanted records using the delete method. this method is simplest of all, where I just pass the contact id the action method, which uses the repository method to delete the contacts.



image



Table above is showing all my contacts present in the database, I will try to delete the contact id 16.



image



In the Dev Toolbar you can see my Method is showing DETELE and Result is 200, which means Delete Success.



With all the examples above I just tried to demonstrate a basic CRUD operations using jQuery and ASP.NET Web Api.



To explore more into this topic you can always refer to the http://www.asp.net link: http://www.asp.net/mvc/mvc4 



In the same link you can download the MVC4 beta, and explore the other features of MVC 4, tutorials, samples, Videos, etc



You can download the complete code I have used for this example from here:  https://docs.google.com/open?id=0BzIjFd_Ps-MSUm4zMklvYkxUMXlFZzdOWVBsaHJvQQ



Sample code includes both Part 1 and Part 2 of this post.



In my next post I have shown how you can publish and host your application on Windows Azure Platform: Hosting ASP.NET Web Api on Windows Azure Platform

Share: