Creating a Web API that Supports CRUD Operations

This tutorial shows how to support CRUD operations in an HTTP service using ASP.NET Web API.

CRUD stands for “Create, Read, Update, and Delete,” which are the four basic database operations. Many HTTP services also model CRUD operations through REST or REST-like APIs.

In this tutorial, you will build a very simple web API to manage a list of products. Each product will contain a name, price, and category (such as “toys” or “hardware”), plus a product ID.

Download the completed project.

The products API will expose following methods.

Action HTTP method Relative URI
Get a list of all products GET /api/products
Get a product by ID GET /api/products/id
Get a product by category GET /api/products?category=category
Create a new product POST /api/products
Update a product PUT /api/products/id
Delete a product DELETE /api/products/id

Notice that some of the URIs include the product ID in path. For example, to get the product whose ID is 28, the client sends a GET request for http://hostname/api/products/28.

Resources

The products API defines URIs for two resource types:

Resource URI
The list of all the products. /api/products
An individual product. /api/products/id

Methods

The four main HTTP methods (GET, PUT, POST, and DELETE) can be mapped to CRUD operations as follows:

  • GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server.
  • PUT updates a resource at a specified URI. PUT can also be used to create a new resource at a specified URI, if the server allows clients to specify new URIs. For this tutorial, the API will not support creation through PUT.
  • POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message.
  • DELETE deletes a resource at a specified URI.

Note: The PUT method replaces the entire product entity. That is, the client is expected to send a complete representation of the updated product. If you want to support partial updates, the PATCH method is preferred. This tutorial does not implement PATCH.

Create a New Web API Project

Start by running Visual Studio and select New Project from the Start page. Or, from the File menu, select Newand then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project “ProductStore” and click OK.

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.

Adding a Model

model is an object that represents the data in your application. In ASP.NET Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client. Continue reading “Creating a Web API that Supports CRUD Operations”

ActionLink htmlAttributes “data-“

The problem is that your anonymous object property data-icon has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:

Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):

@Html.ActionLink("Edit","edit","markets",new{ id =1},new{@class="ui-btn-right", data_icon="gear"})
 

Use the overload that takes in a dictionary:

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });

source: http://stackoverflow.com/questions/4108943/actionlink-htmlattributes

linq: LET clause (C# Reference)

In a query expression, it is sometimes useful to store the result of a sub-expression in order to use it in subsequent clauses. You can do this with the let keyword, which creates a new range variable and initializes it with the result of the expression you supply. Once initialized with a value, the range variable cannot be used to store another value. However, if the range variable holds a queryable type, it can be queried.

In the following example let is used in two ways:

  1. To create an enumerable type that can itself be queried.
  2. To enable the query to call ToLower only one time on the range variable word. Without using let, you would have to call ToLower in each predicate in the where clause.
class LetSample1
{
    static void Main()
    {
        string[] strings = 
        {
            "A penny saved is a penny earned.",
            "The early bird catches the worm.",
            "The pen is mightier than the sword." 
        };

        // Split the sentence into an array of words 
        // and select those whose first letter is a vowel. 
        var earlyBirdQuery =
            from sentence in strings
            let words = sentence.Split(' ')
            from word in words
            let w = word.ToLower()
            where w[0] == 'a' || w[0] == 'e'
                || w[0] == 'i' || w[0] == 'o'
                || w[0] == 'u'
            select word;

        // Execute the query. 
        foreach (var v in earlyBirdQuery)
        {
            Console.WriteLine("\"{0}\" starts with a vowel", v);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    "A" starts with a vowel
    "is" starts with a vowel
    "a" starts with a vowel
    "earned." starts with a vowel
    "early" starts with a vowel
    "is" starts with a vowel
*/

Source: http://msdn.microsoft.com/en-us/library/bb383976.aspx

Internet Explorer (IE) – Defining, Investigating and Specifying document compatibility

Defining document compatibility (source)

Document compatibility defines how Windows Internet Explorer renders your webpages. Like other popular browsers, Windows Internet Explorer supports document compatibility modes that affect the way webpages are interpreted and displayed. These modes, also called document modes, allow you to choose between support for the latest standard or support for certain behaviors popularized by older browsers. Here you’ll learn about the document compatibility modes supported by Internet Explorer and other popular browsers, and how to specify the document mode for a webpage.

The document mode of a webpage is determined by its document type, which is specified using a <!DOCTYPE> directive.

See more in source: http://msdn.microsoft.com/en-us/library/cc288325%28VS.85%29.aspx

Specifying legacy document modes (source)

Understanding legacy document modes

When using the X-UA-Compatible header to restrict a webpage to a legacy document mode, use one of the following values:

  • A value corresponding to a specific document mode, such as IE9 mode, IE8 Standards mode, or IE7 Standards mode. To do so, use one of the following declarations:
    <meta http-equiv="x-ua-compatible" content="IE=9" >
    <meta http-equiv="x-ua-compatible" content="IE=8" >
    <meta http-equiv="x-ua-compatible" content="IE=7" >
    

    By using one of these values, you’re restricting the webpage to the standards mode of the corresponding version of Internet Explorer.

  • In certain cases, you might want Internet Explorer to use the document type declaration to either restrict a webpage to a specific standards mode or to use a document mode representing a much older version of the browser, such as Internet Explorer 5.5.To do so, specify one of the following values, depending on your desired standards mode:
    <meta http-equiv="x-ua-compatible" content="IE=EmulateIE9" >
    <meta http-equiv="x-ua-compatible" content="IE=EmulateIE8" >
    <meta http-equiv="x-ua-compatible" content="IE=EmulateIE7" >
    

    (This setting is useful in cases where you might have a collection of webpages that use different values for the doctype directive.)With these settings, the page is displayed either in the standards mode corresponding to the version you specified or it’s displayed in IE5 (Quirks) mode.

  • For testing purposes, you can also use the following value to display the webpage in the highest standards mode supported by Internet Explorer.
    <meta http-equiv="x-ua-compatible" content="IE=edge" >
    

    Note  Edge mode is intended for testing purposes only; do not use it in a production environment.

    Because it forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use this for all pages viewed with Internet Explorer. Don’t do this, as the X-UA-Compatible header is only supported starting with Windows Internet Explorer 8.

    Tip  If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration, as shown in the earlier example.

The need to restrict a webpage to a legacy document mode usually occurs because the webpage is designed to support a given version of a browser or relies on older features that are no longer supported by the browser. Use legacy document modes only temporarily to allow your pages to be viewed while you update those pages to support current standards and practices.

See more in source: http://msdn.microsoft.com/en-us/library/jj676915%28v=vs.85%29.aspx

Investigating Document Mode Issues (source)

Displaying Webpages in Different Document Modes

To use the F12 tools to display webpages in different document modes, complete the following steps.

  1. If the F12 tools are not already open, press F12 to open the tools. Notice that the current document mode is displayed in the right side of the menu bar of the F12 tools window.The document mode of a webpage is displayed near the upper corner of the F12 developer tools window
  2. When you click the document mode menu button, a menu displays additional document modes that can be used to display your webpage.Click the document mode control to display a menu of additional document modes available for your webpage.
  3. Click the Internet Explorer 9 standards option from the menu to display your webpage in IE9 mode. If you trace the style attributes for the previously selected object, the border-radius child attributes now appear with the other CSS attributes.The Internet Explorer 9 standards command displays a webpage in IE9 Standards mode.
  4. When the webpage is displayed in the appropriate document mode, the webpage appears as intended and the div elements are displayed with rounded corners.The corners are rounded when the webpage is displayed in IE9 Standards mode.

See more in source: http://msdn.microsoft.com/en-us/library/gg699340%28v=vs.85%29.aspx

jQuery – Browser Support and Microsoft Ajax Content Delivery Network

Browser Support


Current Active Support
Internet Explorer Chrome Firefox Safari Opera
jQuery 1.x 6+ Current − 1 version Current − 1 version Current − 1 version Current − 1 version
jQuery 2.x 9+

Any problem with jQuery in the above browsers should be considered and reported as a bug in jQuery.

Current – 1 version denotes that we support the current stable version of the browser and the version that preceded it. For example, if the current version of a browser is 24.x, we support the 24.x and 23.x versions.

Source: http://jquery.com/browser-support/

——————–

Microsoft Ajax Content Delivery Network

The Microsoft Ajax Content Delivery Network (CDN) hosts popular third party JavaScript libraries such as jQuery and enables you to easily add them to your Web applications. For example, you can start using jQuery which is hosted on this CDN simply by adding a <script> tag to your page that points to ajax.aspnetcdn.com.

By taking advantage of the CDN, you can significantly improve the performance of your Ajax applications. The contents of the CDN are cached on servers located around the world. In addition, the CDN enables browsers to reuse cached third party JavaScript files for web sites that are located in different domains.

The CDN supports SSL (HTTPS) in case you need to serve a web page using the Secure Sockets Layer.

The CDN hosts the following third party script libraries which have been uploaded, and are licensed to you, by the owners of those libraries:

  • jQuery (www.jquery.com)
  • jQuery UI (www.jqueryui.com)
  • jQuery Mobile (www.jquerymobile.com)
  • jQuery Validation (www.jquery.com)
  • jQuery Cycle (www.malsup.com/jquery/cycle/)
  • jQuery DataTables (http://datatables.net/)
  • Ajax Control Toolkit (owned by the Outercurve Foundation – http://www.outercurve.org)

The Microsoft Ajax CDN also includes the following libraries which have been uploaded by Microsoft:

  • ASP.NET Ajax
  • ASP.NET MVC JavaScript Files
  • ASP.NET SignalR JavaScript Files

Microsoft does not claim ownership of any third-party libraries hosted on this CDN. The copyright owners of the libraries are licensing these libraries to you. Any rights that you may have to download and use such libraries are granted solely by the respective copyright owners. Because these are not Microsoft libraries, Microsoft provides no warranties or intellectual property rights licenses (including no implied patent rights) for the third party libraries hosted on this CDN.

If you wish to submit your JavaScript library and your library is one of the top JavaScript libraries (as listed on http://trends.builtwith.com) or extensions/plugins to these libraries that are (a) popular; or (b) helpful for use on ASP.NET then please contact AjaxCDNSubmission@Microsoft.com.

Source: http://www.asp.net/ajaxlibrary/cdn.ashx

Resizing an iframe based on content

If you do not need to handle iframe content from a different domain, try this code, it will solve the problem completely and it’s simple:

<script language="JavaScript">
<!--
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>

<i frame src="usagelogs/default.aspx" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>

Important:

onLoad="autoResize('iframe1');" //this is executed after load frame

Source: http://goo.gl/a4hao

Custom Filters in MVC – Authorization , Action, Result, Exception Filters

Filters in MVC are attributes which you can apply to a controller action or an entire controller. This will allow us to add pre and post behavior to controller action methods.

There are 4 types of Filters. Which were described in above image.

Objective: Learn about filters and create custom filters for better understanding.

Step 1: Create a simple MVC Web application. Lets see the Output Cache filter first.
I created a View and pertaining Action method. See them below.

View:

//OutPutTest.cshtml
@{
    ViewBag.Title = "OutPutTest";
}
lt;h2>OutPutTest</h2>
<h3>@ViewBag.Date</h3>

Action Method:

//OutPutTest Action Method
[OutputCache(Duration=10)]
 public ActionResult OutPutTest()
 {
   ViewBag.Date = DateTime.Now.ToString("T");
   return View();
 }

Output : so as per the current implementation, the view should be displaying current time with seconds. so for every refresh, the seconds part will be changed…
But observe the [OutputCache(Duration=10)] attribute applied to action method. This will make the response cached for 10 seconds. Thus the seconds part will not be changed for next 10 seconds.

Step 2: Authorization Filter : This filter will be executed once after user is authenticated
In this step lets create a custom Authorization filter. For this create a class which inherits AuthorizeAttribute or implements IAuthorizationFilter interface. All we are doing here is just passing a message to View.

public class CustAuthFilter : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {            
            filterContext.Controller.ViewBag.AutherizationMessage = "Custom Authorization: Message from OnAuthorization method.";
        }        
    }

Now we have our CustomAuthFilter which will be executed immedealty after user is authenticated. But inorder to make it happen we need to apply this [CustAuthFilter] attribute on top either a custom action or to an entire controller itself.
We have another method OnUnauthorizedRequest event to redirect the unauthorized users to some default pages.

Step 3: Action Filter : There are 4 events available in an action filter.
#1.OnActionExecuting – Runs before execution of Action method.
#2.OnActionExecuted – Runs after execution of Action method.
#3.OnResultExecuting – Runs before content is rendered to View.
#4.OnResultExecuted – Runs after content is rendered to view.
So lets create a CustomActionFilter. Create a class inherting ActionFilterAttribute class of implementing IActionFilter and IResultFilter interfaces.

public class CustomActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage1 = "Custom Action Filter: Message from OnActionExecuting method.";
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage2 = "Custom Action Filter: Message from OnActionExecuted method.";
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage3 = "Custom Action Filter: Message from OnResultExecuting method.";
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage4 = "Custom Action Filter: Message from OnResultExecuted method.";
        }        
    }

Now all we need to do is to apply [CustomActionFilter] attribute on an Action Method.

Step 4: Exception Filter: This filter is used to capture any execptions if raised by controller or an action method. Create a class which will inherit FilterAttribute class and implement IExceptionFilter interface.

public class CustExceptionFilter : FilterAttribute, IExceptionFilter
    {
        public  void OnException(ExceptionContext filterContext)
        {
            filterContext.Controller.ViewBag.ExceptionMessage = "Custom Exception: Message from OnException method.";
        }        
    }

Now all we need to do to handle any exceptions or erros is to apply [CustExceptionFilter]attribute on an Action Method.

Step 5: Now we have all custom filters created. Lets decorate our index action method with them.
Contoller code:

namespace CustomActionFilterMVC.Controllers
{
    [CustAuthFilter]
    public class HomeController : Controller
    {
       [CustExceptionFilter]
       [CustomActionFilter]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();            
        }

        public ActionResult About()
        {
            return View();
        }

        [OutputCache(Duration=10)]
        public ActionResult OutPutTest()
        {
            ViewBag.Date = DateTime.Now.ToString("T");
            return View();
        }
    }
}

Step 6: Now update Index view to reflect all the messages from cutom filters.

@{
    ViewBag.Title = "Home Page";
}

<h2>Output Messages :</h2>
<br />
<h3>@ViewBag.AutherizationMessage</h3>
<br />
<h3>@ViewBag.CustomActionMessage1</h3>
<br />
<h3>@ViewBag.CustomActionMessage2</h3>
<br />
<h3>@ViewBag.CustomActionMessage3</h3>
<br />
<h3>@ViewBag.CustomActionMessage4</h3>
<br />
<h3>@ViewBag.ExceptionMessage</h3>

Step 7: Now execute the application and see the out put.

Now compare the output with the view definition and see the differences.

First thing is , we dint have any message from OnResultExecuted event.
Reason: That event will be executed after content is rendered to view, so by that time the view is rendered,  OnResultExecuted event is not and message is not yet assigned to ViewBag.

Second thing, we dint have any message from exception filter. If there is any exception raised by the code, then the Exception Filter codee will come into picture.

with this , we have covered different kinds of filters in MVC and how to create custom filters and how to apply them.

Source: http://goo.gl/sQbbEJ