Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Wednesday, March 12, 2014

HTML 5 tutorial - How to access web service (Web API) from HTML file



In this tutorial, we will go over, how to retrieve data using ajax and display it within our HTML page.

To start with, will create a new ASP.NET empty web application and keep adding files as and when we need to do.

Select New project option from the menu and select the following option :



Once you do that, the solution explorer should be loaded with your empty file structure.



Now lets add a HTML file and call it HTML_API.  The most important task for me to achieve in this HTML will be to invoke a web service using ajax call and display the results within a table structure.


Once the files is created, lets edit the HTML and make necessary changes to make ajax calls. To achieve this, we need to include jQuery within our script tag. This can be achieved in more than one way.


  1. You could either download the file here and include it in your project
  2. You could use any of the CDN's below and refer them online.

 CDN's are nothing but Content Delivery Network. The purpose of CDN is, they host the required files and by referring them, you can still achieve the same output.

Below is a sample of various CDN options (excludes including through physical path).

In our tutorial, I will be using google api's to refer for jQuery. More over, I will be using the same Web API tutorial (which I used for MVC Grid) to display data. 

Below is the ajax code to invoke Web Service from HTML 5 page.

What is being done here is, invoking the web service and on its successful return with data, we are creating a table row and inserting the values within <td> tags. The whole content is finally appended to the table with id "category" and that would complete the getting results displayed within the table tag.

Below is the image for having the table tag as defined above.

Earlier while testing, I had this error occurring and unable to get the data from database. That's when I realized that I needed the following line.

jQuery.support.cors = true;

CORS are nothing but, Cross Origin Resource Sharing and mainly used for Cross-domain requests.

The final result is below:


Happy coding...

Thursday, March 6, 2014

How to invoke a Web API method within a controller.....


ASP.Net Web API is a powerful tool to retrieve data and to serve a broad range of clients. Once created, it can used to access data in mobile applications too.

   Web API's are helpful to create RESTful services and are similar to MVC controllers, but here the class will be derived from APIController when compared to MVC applications where it will be just Controller. This framework is really helpful to build HTTP based services and can very well control the returned data type  to be json or xml.

   If you are developing an application in MVC, it well suites to have Web API, as it is also based on routing concepts.

 Now lets get into the tutorial to see how to invoke a method in Web API....

 In your MVC controller method, make sure you invoke HttpClient to get started. (for HttpClient, if you have any issues, make sure you refer the namesapce : System.Net.Http;)

 We will use HttpClient and define the URI property within client object as below.....  This defines our base url that the web service is located at...

string url = "http://localhost:1001";
 using (HttpClient client = new HttpClient())
{
     client.BaseAddress = new Uri(url);
     client.DefaultRequestHeaders.Accept.Add(new                  
                                             MediaTypeWithQualityHeaderValue("application/json"));
      
}

In the above, we are using Headers property to define, what kind of data will be handled from server. In the above scenario, we are letting it know that we are dealing json format data. (you can even prefer to use xml format, based on what fits your need well).

Before invoking the method, we should make sure the controller name and method name that we are about to call for data. This defines our path, that we will be using with our client object.

Example : below is our Web API definition...


Given the class name is WebApiTestController, this is how we will use it with our client object.

HttpResponseMessage msg = client.GetAsync("api/WebApiTest/<MethodName>").Result;

Using the above, we can identify if our call was successful by trying the method :
 if(msg.IsSuccessStatusCode), then we had successfully accessed our method  and we can retrieve our data as below...

var mylist = msg.Content.ReadAsAsync<object>().Result;

To have the list converted to a compatible IList<T> object, you can use Result.ToList(); The resultset would be a List object.

  Below is the compiled list for complete code to invoke a web API method....




Happy coding...



Tuesday, February 18, 2014

How to invoke a stored procedure in Web API using Entity Framework

In this tutorial, we will go over sample code to retrieve data with Web API and Entity Framework (invoking a stored procedure to return data).

 Before getting started, I installed Entity Framework 4.3.0. To learn more about installation, click here....

 For this example, I had installed Northwind database and created a sample stored procedure that would return few records, which we will fetch through Web API methods in this illustration...

Create a sample procedure as below...



   To start with, create a folder called Data Model. Right click on Data Model and select add new item...


In the above, I created a new ADO.NET Entity Data Model named DBEntity. I will be using this one for the tutorial.

 I prefer to create an empty data model and add stored procedures as I go. (this works well with just stored procedures approach)...



Once you click finish, this should open up DBEntity.edmx file. Right click on Stored Procedures and click "update model from database"



Once you do that, make sure it has the connection to the DB server it needs to, if not click on New Connection and enter the server details and make sure the connection is working fine by clicking on Test Connection.

Finally we should see a window where it shows up with three tabs, Add, Refresh and Delete... In the Add tab, expand stored procedures and you should see the one created in first step. Check on the TestProc stored procedure and click finish... (refer below..)


Now, our DBEntity.edmx should be like the one below, with new stored procedure added to it...  To include a stored procedure, right click on Function Import  and select Add function import to add stored procedure.




In the window that appears,  select TestProc from stored procedure name and give "TestProc" for Function import name..

Once you click on get column information, this should give the set of columns that will be returned. Now click on the button "Create New Complex type" and this should create a new result-set as "TestProc_Result". Finally the screen should look like the below image.....  If so, then click ok...



Now, its time to get started on invoking the stored procedure and testing the results....  You can find the entity name in web.config and use it for data retrieval... (here the name is DBEntityContainer)

In my WebApiTestController, will add the following code (class and implementation to retrieve data).

 public class CategoryList
        {
            public int CategoryID { get; set; }
            public string CategoryName { get; set; }
            public string CategoryDescription { get; set; }
        }

        public IList<CategoryList> GetSampleData()
        {

            List<CategoryList> catList = new  List<CategoryList>();

            using(WebAPI.DataModel.DBEntityContainer test = new DataModel.DBEntityContainer())
            {
                var result = test.TestProc().ToList();

                foreach (var item in result.ToList())
                {
                    catList.Add(new CategoryList { CategoryID = item.CategoryID, CategoryName = item.CategoryName, CategoryDescription = item.Description});
                }
                return catList;
            }

        }


Now press F5 and you should be able to see the output as below...



Happy coding...



Wednesday, January 22, 2014

A look into Web API - Creating a simple Web API application... - Part 2



Click here to view part 1



Lets create a model class for our sample and use it to test...





I had created a class called TestData.cs and defined it as below.




As said, I am extending the class from ApiController and added the following code...




Above code will make use of my model TestData to generate some sample data and to display them when invoked.

Now we are all set to run this web service and display the data to end users. When you press F5, you should be able to see the result below.. (I am using chrome to run it)



That's just getting started with Web API's... Happy coding...

A look into Web API - Creating a simple Web API application... - Part 1


ASP.Net Web API is a powerful framework to retrieve data and to serve a broad range of clients. Once created, it can be used to access data within mobile applications too.

   Web API's support developers to create RESTful services and the request is controlled by Controllers, which is similar to MVC controllers, but here the class will be derived from APIController when compared to MVC applications where it will be just Controller. This framework is really helpful to build HTTP based services and can very well control the returned data type  to be json or XML.

   If you are developing an application in MVC, it well suites to have Web API, as it is also based on routing concepts. More over, a given set of data can be accessed/modified through GET,PUT,DELETE etc.....

Now lets see how to create a simple Web API and invoke it through its URL....

I will create a new web API, by making the following choice : ASP.NET MVC 4 Web Application



    After making the selection, make sure you select Web API option (with View Engine type being Razor).



  Sample generated file structure below :


 
   Main controller method inherits from APIController with default value being ValuesController. For tutorial purpose, I will create a new controller WebAPITestController  that would generate and return data on invoking the method.





  Now we have the controller ready. Since this is a regular Controller, we should extend the class with  Sytem.Web.Http.ApiController to make it a Web API or we can select the following option when creating a controller, which will load with few empty basic method structures....






Click here to continue Creating a simple Web API....