Sharing the things I learn day by day

Wednesday, December 25, 2013

INTRODUCTION TO WEB API (PART 1)

Hi All,

This blog post will demonstrate on how to create a RESTful web service using Web API, which is introduced by Microsoft with the MVC 4 release. 


I’m using Visual Studio 2012 for this demonstration.


First I will create a New Project and I will select a MVC 4 Web Application. I name it as WebAPIDemo.



Next you will be prompted to select the template, and you can see that there is a template for Web API as well. This template will give you a class in which the HTTP methods are implemented which can run and test immediately. It will also provide a MVC web application which can be used to test your Web API.

But for this demonstration I will not be using the Web API template. I will use the Basic template. I will not be testing the Web API using a MVC application. I will show you some tools available in which RESTful services can be tested.




Web API works on the MVC principle. The way how to invoke a method in the Web API is the same as in MVC.

So next I will create a controller and will name at as StudentController. From the template I will select “Empty API Controller”.




All Web API controller classes extend from the ApiController class. In StudentController, I will write four methods to Insert, Update, Search and Delete to represent the CRUD oprations.


CRUD Operation
Method Name
Insert
InsertStudentDetails
Delete
DeleteStudentDetails
Update
UpdateStudentDetails
Select
SelectStudentDetails
GetAllStudents

I will create a class called Student which has four attributes. Place the Student class inside the Models folder.


The content of the class is shown below.


Now let’s implement the four methods. Since I’m not going to use a database to store and retrieve values, I will hardcode student details in a list and use it. The list is as below.


The tool I’m going to use to test the API is “RESTClient” Download. This is a tool for Firefox. If you are using chrome then you can use “Postman” Download. You can just run the application and test it in these tools.



First I will implement the GetAllStudents method which returns all the students in the list.




[HttpGet] attribute indicates to the Web API that this is a HTTP GET method. So below is the result after invoking the method.

Request URL: http://localhost:3625/api/Student/GetAllStudents

Note: You need to change the port number accordingly when you try this out in your machine.


Request:






Response:

The response contains the three student details I hardcoded in the list.

Next I will implement the SelectStudentDetails method which accepts the studentID as the parameter.




Request URL: http://localhost:3625/api/Student/SelectStudentDetails?studentID=1

Here when invoking the method the studentID is passed.

Response:














For rest of the demo please read INTRODUCTION TO WEB API (PART 2)

INTRODUCTION TO WEB API (PART 2)


<<INTRODUCTION TO WEB API (PART 1)

Hi,

In this post I will implement rest of the methods.

Now I have the select methods implemented. Now I will implement the InsertStudentDetails method. 


















As you can see I have invoked another method to get the student data that is been passed through the request. The method implementation of GetRequestData is shown below.









In this method I’m getting the data in the request as a string. Since I’m passing the data in Json format I need a Json deserializer. For that I’m using the Json framework for .NET which can be downloaded from here: http://james.newtonking.com/json . Then I can convert the data into a Student object. The Json which is passed in the request is shown below.

{
        "StudentID" : 4,
        "StudentName" : "Nipuni",
        "Age" : 35,
        "Address" : "Colombo 5"

}

Request URL: http://localhost:3625/api/Student/InsertStudentDetails

Set the content type of the header as application/json.
























Add the Json to the body section.

Request:














Response:













Now if the GetAllStudents methods is called you can see the newly inserted record to the List.

Next I will implement the UpdateStudentDetails Method.

























This method also uses the GetRequestData Method to get the details of the student that needs to be updated. Then I search for a matching record with the student ID. If a record is found then I update it or else I sent back a response message Not Found.

The why how the message is invoke is the same as the insertStudentDetails Method.

Request URL: http://localhost:3625/api/Student/UpdateStudentDetails

Next I will implement the DeleteStudentDetails method.











I have searched for the student using the student ID, and if it’s found I delete that student and return true or else return false.

Request URL: http://localhost:3625/api/Student/DeleteStudentDetails?studentID=1

Once a delete operation is done if you run the GetAllStudents method you can see whether the student is deleted.

That's all for this blog,
Happy Coding.

Friday, May 17, 2013

INSERTING DATA IN XML FORMAT TO THE TABLES IN THE DATABASE

Hi All,

In my previous blog post I explained how to convert the data in a DataTable to SqlXml format to send in to the database. So in this post I will explain how to insert that data into the tables of the database. Here I'm using SQL Server 2008 R2 as my database.

I will be using the same XML which was generated in my previous blog post.

XML to be inserted











So first up I will create a table in sql server to store this information.







OK so now since we have the table created now lets insert the data to this table. I will write a stored procedure which accepts an XML as a parameter and then insert the data to the Student table through the stored procedure.

Stroed Procedure to insert the XML Data To the Student Table






















The stored procedure accepts the student details as an XML parameter. The this XML is parsed using the MSXML parser, which makes the XML ready for consumption. You can read more on sp_xml_preparedocument from here.

So once the XML ready then I can select the data from the XML using OPENXML and then insert the data to the Student table.

Next we can call the Stored Procedure by passing the XML.

Calling the strored procedure by passing the XML













So if we query the student table now, we can see the data inserted.

Data Inserted to the Student Table









That's all for this post.
Happy Coding.

Monday, May 6, 2013

CONVERTING DATA IN A DATATABLE TO SQLXML TO SEND TO THE DATABASE

Hi All,

Today I'm going to explain on how to convert the data in a DataTable to SqlXml. This would be helpful when you have lots of records in a DataTable, and you need to insert them at one go rather than inserting each row one at a time.

So I will create a small console based application to demonstrate this. I will show 2 ways on how this can be done. But I'm not sure about the performance in both the approaches.

First up I will create a DataTable and add some columns to it. Remember when you create the DataTable you have to give a name to it. Otherwise the XML cannot be created.


Creating the DataTable







I have named my DataTable as "SampleTable". Then I add some records to this.

Adding Records to the DataTable














So I inserted 2 records to the DataTable. To create the XML I will be using a stream. The stream that I'm going to use is a MemoryStream. DataTable has a method called WriteXml() which has 16 overloaded versions. I will use the overloaded version of the method which accepts a stream object.

Writing the data in the DataTable to the stream





Now we have the stream. I will explain 2 ways on how to convert this stream to SqlXml.

Method 1:

This is the most simplest way of doing it. I can create a object of type SqlXml by passing the stream object to the constructor. Remember to Flush and Close the stream once you have finished working with it.

Creating the SqlXml from the stream







Output :













Method 2 :

The next method is to use a XmlTextReader. Then from the XmlTextReader object I construct the SqlXml object.

Creating the SqlXml from the XmlTextReader







Output :













Both the outputs are the same. This XML can be sent into a stored procdeure in the database to insert the data to the tables.

Thats all for this post.
Happy Coding.

Monday, April 22, 2013

EXTRACTING THE HTML OF A PAGE AND READING IT OUT INTO A BYTE STREAM

Hey All,

It has been along time since I have last posted a blog post. Sorry about that. Today I'm going to post a small part of my final year research project.

My final year research project which was a group project, was to build a web browser for windows mobile 7 which is capable of doing some predefined commands according to the human voice, reading out a web page upon a users request and resume capable downloading. Also it had the other features like bookmarks, history etc like the other normal browsers had.

So my part in the project was to build the "reading out a web page upon users request". To start off I had no clue on how to do it. As in my previous blog posts i knew how to do it in the windows mode, so I thought it might work for windows mobile 7 as well. Surprisingly the windows phone 7.1 SDK didn't have the System.Speech. So I had to think about another way solve this problem. Therefore by trying out different things and reading lots of articles on the net I came up with my own version of doing it.

Solution Summary

I used a WCF service to extract the HTML from the web page that the user is requesting to read out and then I wrote a recursive function which will clean up the unwanted stuff (images,banners,flash) in the extracted HTML and then read out the cleaned HTML into a byte stream and return it back to the phone and convert the byte stream to WMA format and play it out.

I will explain code I have written for it below.

Step 1 : (Click to enlarge the image)

HTML Extraction Method
















To briefly explain the above code,
  1. The method expects the the URL of the web page that needs to be read out.
  2. I created a object from the "WebClient" class which is in the System.Net Namespace and use the "DownloadString" method to download the HTML of the requested web page as a string.
  3. Then I created a object out of the "SpeechSynthesizer" class which is in the System.Speech.Synthesis Namespace to help me with the voice part.
  4. Then I use the memory stream to hold on to the voice which will be read out by the "SpeechSynthesizer".
  5. Then the output of the "SpeechSynthesizer" is set to the wave stream by calling the method "SetOutputToWaveStream" and by passing it the memory stream object.
  6. In this case I'm only reading out to the user the content what are available in the paragraph tags of the extracted HTML. Therefor I take a sub string of the extracted HTML and then send it in to the recursive function for further to be cleaned up.
  7. Then for every paragraph the sub string method gives me, I call the "filterString" method which is the recursive method to clean up the unnecessary HTML tags within the extracted paragraph line. The "filterString" method will return the cleaned up string and it will be appended to the "toSpeak" object which is of type "PromptBuilder".
  8. Once the loop is done the "Speak" method is called and the voice is read out to the memory stream.
  9. Then I call the "ToArray" method of the memory stream object which converts the voice to a byte array.
  10. Remember to Flush and Close the memory stream.
  11. Finally I return the byte stream back to the phone.
** Note : Not all the web sites allows to extract the HTML content. Also not all the websites are according to the W3C standard. Therefor this code doesn't work for them. In that case the catch block is fired and the "Sorry, This page cannot be read" phrase is read out to the user.

Step 2 : (Click to Enlarge)
 
The Recursive Method


















  1. The filterString method which is the recursive method, expects the string that needs to be cleaned up. The point to keep in mind is that the string which is passed into the method is the content within the paragraph tags of the extracted HTML.
  2. It will simply remove the content within the "<" and ">" signs and the signs itself.
  3. If no "<" sign is contained in the string then it is considerd that the string dosent have any HTML tags in it.
  4. Finally after the recursive method ends it returns the string without any HTML tags.
This is the way how I did it. There may be other more accurate solutions than mine. Just put the thinking cap on and think.

Thats all for this post.
Happy Coding.