Tuesday, September 1, 2015

How To Create a Downloadable Web API - Calling the ASP.Net Web API With jQuery and JavaScript

How To Create a Downloadable Web API

Introduction
In this article we will describe how to create a downloadable Web API. Since we know that an API is a framework that can help to create HTTP services to provide the responses of the client request. HTTP services reaches a broad range of clients and also includes the browsers and mobile services. Here we describe the calling of the API application  from the browser.
Step 1
Create the Blank Solution
  • Open Visual Studio 2012
  • Select "File" -> "New" -> "Project...".
  • On the template window select "Installed" > "Template" > "Other Project Type" > "Visual Studio Solution".
  • Now choose "Blank Solution" and change the name of this solution to "HelloSolution".
  • Now click on the "OK" button.
sol1.jpg

Step 2
Create ASP. Net MVC Web API application
After creating the blank solution we can now add an ASP.Net Web API project.
  • Right-click on the solution "HelloSolution" in the Solution Explorer.
  • Select "Add" > "New Project..."
  • In the Installed Templates expand the "Visual C#" node and select "ASP. Net MVC 4 Application".
  • Click on "OK" button.
  • Select the Web API from the New ASP.Net Web API.
sol3.jpg

sol4.jpg

Solution Explorer image

sol5.jpg
Step 3
Add the Controller
Now use the following procedure to create the Controller:
  • Right-click on the Controller Folder in the Solution Explorer. Select "Add" > "Controller".
  • In the controller window change the name to "helloController".
  • And in the template select Empty API controller.
  • Click on the "Add" button.
sol6.jpg
sol7.jpg
Step 4
Write the following code in the helloController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace helloAPI.Controllers
{
    public class helloController : ApiController
    {
       
        public string Get()
        {
            return "Mudita Rathore";
        }
           public string Get(string Id)
        {
            return "Mudita " + Id;
        }
       
    }
}

Step 5
Now to call the Web API from the browser.
For calling the Web API, first we debug the code, then the result will look like this:
 exe1.jpg
Now we access the URL "http://localhost:48909/api/hello".
 exe2.jpg
Now we click on "Open" and select the browser to access the Web API.

Output
The result will look like this in the Mozilla Firebox browser:
res1.jpg


Calling the ASP.Net Web API With jQuery and JavaScript
Introduction
In this article we will use jQuery and JavaScript for calling the Web API. We know that the ASP. Net Web API is a framework for creating Web APIs of the .NET Framework. In this article we will use the ASP. Net Web API to create a Web API that returns a list of items. 
Now we will provide the procedure for creating the Web API.
Step 1
First we create the Web API project as in the following:
  • Open Visual Studio 2012 and select "File" -> "New" -> "Project...".
  • In the Template Window select Visual C# >Web and then select "ASP. Net MVC 4 Web Application". Change the name of this to "ExampleAPI" and click on the "OK" button.
example.jpg

In the New ASP. Net MVC 4 project window select "Web API" and click the "OK" button.
exampl1.jpg

Step 2
Now we Add a Model
In the ASP. Net Web API the Model can be serialized automatically in Java Script Object Notation (JSON) and Extensible Markup Language (XML) format. We can use the model to represent the data  in our application.
Now we will describe how to create the model in the application.
  • In the Solution Explorer right-click on the "Model" folder
  • From the context menu select "Add" and select the class
ex1.jpg

Step 3
We change the class name to "Item" and add this code to the class:using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace ExampleAPI.Models
{
    
public class Item    {
        
public int Id { getset; }
        
public string name { getset; }
        
public string Type { getset; }
        
public decimal cost { getset; }
    }
}

Step 4
Add the Controller
The Controller handles the HTTP requests. There are two types of controllers; they are:

HomeController: used for serving the HTML pages to the WebSite. It cannot have direct interaction with the Web API.
ValuesController: works as an example of the Web API.
Use the following to add the controller:
  • In the Solution Explorer right-click on the "Controller" folder.
  • Select "Add and Select Controller".
  • Change the name of the controller to "Items".
  • In the Template select "Empty API Controller".
example 3.jpg


cont.jpg


Now add the following code to the Controller.
namespace ExampleAPI.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
    using ExampleAPI.Models;

    public class ItemsController : ApiController
    {
        Item[] items = new Item[]
        {
            new Item{Id = 1,name="Apple", Type="Fruit",cost=100},
            new Item{Id = 2,name="Tomato",Type="vasitable",cost=50},
        new Item {Id = 3,name="T-Shirt",Type="cloths",cost=500}
        };
        public IEnumerable<Item> GetAllItems()
        {
            return items;
        }
        public Item GetItemById(int id)
        {
            var item = items.FirstOrDefault((I) => I.Id == id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return item;
        }
        public IEnumerable<Item>GetItemsByType(string type)
        {

            return items.Where(
                (I) => string.Equals(I.Type, type,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
}

Step5
For calling the Web API with jQuery an JavaScript
In the Solution Explorer, expand the Home Folder and double-click on the Index.cshtml.
cshtml.jpg
 And write this code.
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <link href="../../Content/Site.css" rel="stylesheet" />
    <script src="../../Scripts/jquery-1.7.1.min.js"
        type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () 
{
                 $.getJSON("api/items/",
                function (Data) {

                    $.each(Data, function (key, val)
{
                    var str = val.name + ': $' + val.cost;
                        $('
  • '
  • , { text: str })
                            .appendTo($('#items'));
                        });
                    });
                });

                function show() {
                    var Id = $('#itId').val();
                    $.getJSON("api/items/" + Id,
                        function (Data) {
                            var str = Data.name + ': $' + Data.cost;
                            $('#items').text(str);
                        })
                    .fail(
                        function (jqXHR, textStatus, err) {
                            $('#items').text('Error: ' + err);
                        });
                }
            </script>

    </head>
    <body id="body" >
        <div class="main-content">
            <div>
                <h1>Showing All Items </h1>
                <ul id="items"/>
            </div>
            <div>
                <label for="itId">ID:</label>
                <input type="text" id="itId" size="5"/>
                <input type="button" value="Search" onclick="show();" />
                <p id="item" />
            </div>
        </div>
    </body>
    </html>
    Result
     resultex.jpg
     Search the Item Through Id
    resultex2.jpg

    No comments:

    View Tenant (ULS) Logs in SharePoint Online using CSOM

    Even though the classes exist in the CSOM, the Microsoft Office 365 Engineering team has confirmed that this is something which is not poss...