Creating WEB API And Consuming In Console Application Using Web Client In An Asynchronous Way

Basically, create Web API to share data with others or to get the data from others.

You might think, why should we consume Web API in console Application? 

Nowadays, we have tasks such as to consume data from a third party Server on a timely basis [run after every 1 hour or 3 hours]. For doing this, we need a console app consuming Web API hosted on the third party Server and then we can configure it in Task Scheduler to run on a timely basis.

You can download the source code from here.
web api

Why  use the Web API when Web service is there?

Currently, most mobile devices, browsers and tablets are the media for accessing most of the internet and in this, people are using the mobile apps the most and to provide the data to the apps, we are now going to use Microsoft's new technology.

Web API is easy to consume.

Web API returns the data in various formats. Some are JSON (JavaScript Object Notation), XML (Extensible Markup Language), CSV (comma separated values).

Web Service is also easy to consume.

Web Service returns the data in only one format, SOAP [Simple Object Access Protocol], which is XML-based.

We need to create different Web Service for a different format and also to do this, one needs lots of R&D work.

Topics

  1. Creating Web API
  2. Consuming Web API, using Web Client in console.

Creating Web API

Creating Web API is a simple step Lets start……

Open Visual Studio IDE from Visual Studio IDE. Select File. Inside it, select project. After selecting, a new dialog will pop up with the name “New Project”. In this dialog, in the left pane, you will find Templates. Just expand it and you can see Visual C# just expands it. Select Web Template from it. After selecting the template, finally we are going to choose Project “ASP.NET MVC4 Web Application” and Name our Project as “MvcEventManager”.

Creating Web API
Fig 1. Add and Name the Project

After adding, new dialogs will pop-up for choosing the template.

Add and Naming Project

Inside this, we are going choose Web API and finally click OK button. Don’t miss choosing View engine as Razor.

After clicking OK button, a New Web API project is created, as shown below:

Project View after adding
Fig 2. Project View after adding

After creating the project, we are going have a look at the database part first, before moving forward.

Database part

I have a database with the name MVCAPP. In it, I have tables with the name EventTB, which we are going to use for creating API.

EventTB Table

Event Table in Design Mode
Fig 3.Event Table in Design Mode

EventTB Table Contains Data

Showing data in EventTB table
Fig 4 .Showing data in EventTB table

After looking at the tables and data, we are going to add ADO.NET Entity framework to the project.

Adding ADO.NET Entity Framework to project

For adding ADO.NET Entity framework to the project, just right click on Model folder. Inside it, select Add and finally select ADO.NET Entity Data Model .

For reference, look at the snapshot, given below:

Adding ADO.NET entity Data Model
Fig 5.Adding ADO.NET Entity Data Model

After selecting ADO.NET Entity Data Model, it will pop up a new dialog with the name “Specify Name for Item”.

Naming ADO.NET entity Data Model
Fig 6.Naming ADO.NET Entity Data Model

Enter the name of the item as EventModel. Click OK button.

After clicking OK button, a New Wizard of Entity Data Model will pop up.

Choosing Model Content
Fig 7.Choosing Model Content

In this, we are going to choose Generate from database option and click Next button. After clicking Next button, a new wizard will pop up for choosing the database connection.

Choosing your data connection
Fig 8.Choosing your data connection

For choosing new database connection for the Application, just click New Connection button and a dialog will pop up with the name “Connection Properties”.

In this Connection Properties dialog, you need to enter your Server name of SQL, after which you need to choose the mode, which you are going to use for connecting is the Windows Authentication Mode or SQL Server Mode Authentication. To show the demo, I have chosen SQL server mode.

Finally select the database, which you want to use “Select or enter database Name”, as I have chosen MVCAPP as my database for a demo.

The last step is to click OK button.

Setting Connection Properties
Fig 9.Setting Connection Properties

After choosing the database connection, final view of connection Wizard will be:

Choosing your data connection for adding in Web.config file
Fig 10. Choosing your data connection for adding in Web.config file

Just select Connection string option as Yes, which will be added to The Web.Config file with the sensitive data and finally click Next button.

After clicking Next button, a new dialog will pop up for choosing the database objects.

Choosing database objects

Choosing your database objects
Fig 11. Choosing your database objects

In this wizard, we are just going to choose an object, which we want to use.

I am going to choose only EventTB table from Tables objects and click Finish button. After clicking Finish button and Event Model, diagram is created along with the table, which we have chosen.

EventModel Diagram
Fig 12. EventModel Diagram

Next step is to add API Controller.

Adding API Controller

For adding API Controller just right click on Controller folder. Select Add. Inside it, select Controller. After selecting Controller, a new dialog will pop up with the name Add Controller now. To create a Controller, we need to name the controller and I am going to name it as “EventController”. In scaffold option, we are going to choose. We have the templates to choose. In it, we are going choose “API controller with read/write actions, using Entity framework”.

Adding Event Controller and setting Scaffolding option
Fig 13. Adding Event Controller and setting Scaffolding option

Note:
 If you are not finding Model, just build your Application once and retry this step.

After clicking Add button, a complete ready-made API is created and you are not required to manually stuff here.

Event Controller API
Fig 14. Event Controller API

Now, we have created API. Let’s test on Fiddler.

We are going to call Get all Records of Event API [http://localhost:50024/api/Event].

After calling, here is JSON response we have got.

Note:
 If you do not have Fiddler, you can check it on the Browser to just enter URL and execute.

 Testing Event Controller API in Fiddler
Fig 15. Testing Event Controller API in Fiddler

Now, we have completed creating it. Now, let’s begin with creating console Application and consuming API in it.

Creating Console application

Open Visual Studio IDE from Visual Studio IDE. Select file. Inside it, select project and after selecting a new dialog will pop up with the name “New Project”. In this dialog, in the left panel, you will find the templates. Just expand it and you can see Visual C#. Just expand it and select Windows Template from it. After selecting the template, finally we are going to choose Project “Console Application” and name our Project as “ConsoleEventManager”.

Creating Console application and naming it
Fig 16. Creating Console application and naming it

After entering the project name, finally click OK button and your console project will be created.

View after adding Console application
Fig 17. View after adding Console application

Now, after creating a console Application, we are going to consume Event Web API which we have created. For doing this, we are going to create new classes with the name “ConsumeEventSync”.

 Project View after adding
Fig 18. Project View after adding

Now, after adding the classes, we are going to first consume API in an Asynchronous way.

The Call method gets called, when the download string is completed and in call back method, we will get the data in response.

Get All Events Records

  1. using System;  
  2. using System.Net;  
  3. namespace ConsoleEventManager {  
  4.     public class ConsumeEventSync {  
  5.         public void GetAllEventData() //Get All Events Records  
  6.             {  
  7.                 using(var client = new WebClient()) //WebClient  
  8.                     {  
  9.                         Uri URI = new Uri("http://localhost:50024/api/Event");  
  10.                         client.Headers.Add("Content-Type:application/json"); //Content-Type  
  11.                         client.Headers.Add("Accept:application/json");  
  12.                         //Event  
  13.                         client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadString_AllEvent_Callback);  
  14.                         client.DownloadStringAsync(URI); //URI  
  15.                     }  
  16.             }  
  17.             // Callback Method  
  18.         void DownloadString_AllEvent_Callback(object sender, DownloadStringCompletedEventArgs e) {  
  19.             Console.WriteLine(e.Result); // e.Result will Return Data   
  20.         }  
  21.     }  
  22. }  
Calling Method in Main
  1. namespace ConsoleEventManager {  
  2.     class Program {  
  3.         static void Main(string[] args) {  
  4.             ConsumeEventSync objAsync = new ConsumeEventSync();  
  5.             objAsync.GetAllEventData(); //Get All Records in Asynchronous way [DownloadStringAsync]  
  6.         }  
  7.     }  
  8. }  
Output: Showing the data for all the Events.

Get All Events Records
Fig 19. Get All Events Records

Get All Events Records By ID
  1. public void GetAllEventData_ByEventID(string EventID) //Get All Events Records By ID  
  2.     {  
  3.         using(var client = new WebClient()) //WebClient  
  4.             {  
  5.                 Uri URI = new Uri("http://localhost:50024/api/Event/" + EventID);  
  6.                 client.Headers.Add("Content-Type:application/json"); //Content-Type  
  7.                 client.Headers.Add("Accept:application/json");  
  8.                 // DownloadStringCompleted Method gets Called   
  9.                 // when an asynchronous resource-download operation completes.  
  10.                 client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadString_EventByID_Callback);  
  11.                 client.DownloadStringAsync(URI); //URI  
  12.                 Console.ReadLine();  
  13.             }  
  14.     }  
  15.     // Callback Method  
  16. void DownloadString_EventByID_Callback(object sender, DownloadStringCompletedEventArgs e) {  
  17.     Console.WriteLine(e.Result); // e.Result will Return Data   
  18. }  
Calling Method in Main
  1. namespace ConsoleEventManager {  
  2.     class Program {  
  3.         static void Main(string[] args) {  
  4.             ConsumeEventSync objAsync = new ConsumeEventSync();  
  5.             objAsync.GetAllEventData_ByEventID("3");  
  6.             //Get All Events Records By ID in Asynchronous way [DownloadStringAsync]  
  7.         }  
  8.     }  
  9. }  
Output: Showing the data against EventID, which we have passed to the method.

Get All Events Records by ID
Fig 20. Get all events records by ID

Adding Data

For posting the data, we require parameters to send the data. For doing this, I have added a similar class of EventTB in a console project.

Adding EventTB Class in Console Project
Fig 21. Adding EventTB class in console project

Adding Newtonsoft.Json to console application

For adding Newtonsoft.JSON, just select Tools Menu from Visual studio IDE, NuGet Package Manager. Inside it, Manage NuGet Packages for the solution.

After selecting Manage NuGet Packages a dialog will popup. Inside the search box, type Newtonsoft.JSON and click install button.

Adding Newtonsoft.Json
Fig 22. Adding Newtonsoft.JSON
  1. public void PostEvent_data() //Adding Event  
  2.     {  
  3.         using(var client = new WebClient()) {  
  4.             Uri URI = new Uri("http://localhost:50024/api/Event");  
  5.             EventTB objtb = new EventTB();  
  6.             objtb.EventID = 0;  
  7.             objtb.EventName = "Party";  
  8.             objtb.EventStartsDate = DateTime.Now;  
  9.             objtb.EventEndsDate = DateTime.Now;  
  10.             objtb.EventLocation = "Mumbai";  
  11.             client.Headers.Add("Content-Type:application/json");  
  12.             client.Headers.Add("Accept:application/json");  
  13.             client.UploadStringCompleted += new UploadStringCompletedEventHandler(UploadString_POST_Callback);  
  14.             client.UploadStringAsync(URI, JsonConvert.SerializeObject(objtb));  
  15.         }  
  16.     }  
  17. void UploadString_POST_Callback(object sender, UploadStringCompletedEventArgs e) {  
  18.     Console.WriteLine(e.Result);  
  19. }  
Calling Method in Main
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         ConsumeEventSync objAsync = new ConsumeEventSync();  
  4.         objAsync.PostEvent_data();  
  5.         //Adding Event in Asynchronous way [UploadStringAsync ]  
  6.     }  
  7. }  
  8. Output: In response, we are getting data which we have inserted.  
Adding Event Data
Fig 23. Adding Event Data

Updating Data

In this PUT method, we need to set EventID, which we want to update and along with it in URL, we need to set the parameter (EventID).

Along with it, we need to set the method ["PUT"] in UploadStringAsync.
  1. public void PutEvent_data(int EventID) //Update Event  
  2.     {  
  3.         Uri URI = new Uri("http://localhost:50024/api/Event/" + EventID);  
  4.         using(var client = new WebClient()) {  
  5.             EventTB objtb = new EventTB();  
  6.             objtb.EventID = 7;  
  7.             objtb.EventName = "Mumbai Rocks"//Value to Update  
  8.             objtb.EventStartsDate = DateTime.Now;  
  9.             objtb.EventEndsDate = DateTime.Now;  
  10.             objtb.EventLocation = "Mumbai";  
  11.             client.Headers.Add("Content-Type:application/json");  
  12.             client.Headers.Add("Accept:application/json");  
  13.             client.UploadStringCompleted += new UploadStringCompletedEventHandler(UploadString_PUT_Callback);  
  14.             client.UploadStringAsync(URI, "PUT", JsonConvert.SerializeObject(objtb));  
  15.         }  
  16.     }  
  17. void UploadString_PUT_Callback(object sender, UploadStringCompletedEventArgs e) {  
  18.     Console.WriteLine(e.Result);  
  19. }  
Calling Method in Main
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         ConsumeEventSync objAsync = new ConsumeEventSync();  
  4.         objAsync.PutEvent_data(9);  
  5.         //Update Event in Asynchronous way [UploadStringAsync]  
  6.     }  
  7. }  
Output: Output for the update is empty.

Updating Event Data
Fig 24. Updating event data

Updated Data

 Updated Event Data
Fig 25. Updated Event Data

Delete Data

In this Delete method, we need to set EventID, which we want to delete.

Along with it, we need to set the method ["Delete"] and data as [""] in UploadStringAsync.
  1. public void DeleteEvent_data(int EventID) //Delete Event  
  2.     {  
  3.         Uri URI = new Uri("http://localhost:50024/api/Event/" + EventID);  
  4.         using(var client = new WebClient()) {  
  5.             client.Headers.Add("Content-Type:application/json");  
  6.             client.Headers.Add("Accept:application/json");  
  7.             client.UploadStringCompleted += new UploadStringCompletedEventHandler(DeleteString_EventByID_Callback);  
  8.             client.UploadStringAsync(URI, "Delete"""); //UR  
  9.         }  
  10.     }  
  11. void DeleteString_EventByID_Callback(object sender, UploadStringCompletedEventArgs e) {  
  12.     Console.WriteLine(e.Result);  
  13. }  
  14. Calling Me  
thod in Main
  1. class Program  
  2. {  
  3.     static void Main(string[] args)   
  4.   {  
  5.         ConsumeEventSync objAsync = new ConsumeEventSync();  
  6.         objAsync.DeleteEvent_data(9);  
  7.         //Delete Event in Asynchronous way [UploadStringAsync]  
  8.     }  
  9. }  
Output: Delete record is shown as output.

Deleted Event Data
Fig 26. Deleted event data