Creating Web API And Consuming In Console Application Using Web Client In A Synchronous Way

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

Nowadays, we have a task such as consuming 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 the Task Scheduler to run on a timely basis.
webapi

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 people are using mobile apps the most, and to provide data to apps we are now going to use the Microsoft new technology.

Web API is easy to consume.

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

Web Service is also easy to consume.

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

If we try this, many content types return in Web Service. We need to create the different Web Services for a different format and also to do this, it 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. Let's start……

Open Visual Studio IDE from Visual studio IDE. Select file. Inside it, select the 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#, which needs to be expanded, select Web Template from it. After selecting the final template, we are going to choose the Project “ASP.NET MVC4 Web Application” and name our project as “MvcEventManager”.

Add and Naming Project
Fig 1. Add and Naming 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. 

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 the tables with the name EventTB, which we are going to use for creating API.

EventTB Table

EventTB Table
Fig 3.Event Table in Design Mode

EventTB Table Contains Data

EventTB Table Contains Data
Fig 4 .Shows data in EventTB table

After having a look at the tables and data, now, we are going 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 the 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 the database option and click Next button.

After clicking the 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 a 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. Afterwards, you need to choose the mode, which you are going to use for the connecting --   either Windows Authentication Mode or SQL Server Mode Authentication for showing demo and I have chosen SQL server mode.

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

The last step is to click the OK button.

Setting Connection Properties
Fig 9.Setting Connection Properties

After choosing the database connection, final view of connection Wizard is shown below: 

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

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 and after selecting Controller a new dialog will pop up with name Add Controller -- now to create a Controller we need to name controller. I am going to name it as “EventController” and then in scaffold option, we are going to choose. We have Templates to choose in it and 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 a model, just build your Application once and retry this step. After clicking Add button, a complete ready-made API is created and you do not need to manually do things 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 the JSON response we have got.

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

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

Now, we have created API and API begins with creating Console Application and consuming API in it.

Creating Console application

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

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

After entering the project name, finally click the OK button and your console project creates.

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 created. For doing this, we are going to create 2 new classes with Name “ConsumeEventSync” and “ConsumeEventAsync”.

ConsumeEventSync in this class is going to consume API in a synchronous way.

ConsumeEventAsync in this class is going to consume API in an asynchronous way.

Project View after adding
Fig 18. Project View after adding

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

Get All Events Records

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Text;  
  6. namespace ConsoleEventManager  
  7. {  
  8.     public class ConsumeEventSync  
  9.     {  
  10.         public void GetAllEventData() //Get All Events Records  
  11.             {  
  12.                 using(var client = new WebClient()) //WebClient  
  13.                     {  
  14.                         client.Headers.Add("Content-Type:application/json"); //Content-Type  
  15.                         client.Headers.Add("Accept:application/json");  
  16.                         var result = client.DownloadString("http://localhost:50024/api/Event"); //URI  
  17.                         Console.WriteLine(Environment.NewLine + result);  
  18.                     }  
  19.             }  
  20.     }  
  21. }  
Calling Method in Main
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ConsoleEventManager   
  6. {  
  7.     class Program {  
  8.         static void Main(string[] args) {  
  9.             ConsumeEventSync objsync = new ConsumeEventSync();  
  10.             objsync.GetAllEventData();  
  11.         }  
  12.     }  
  13. }  
Output: Showing the data for all 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.                 client.Headers.Add("Content-Type:application/json"); //Content-Type  
  6.                 client.Headers.Add("Accept:application/json");  
  7.                 var result = client.DownloadString("http://localhost:50024/api/Event/" + EventID); //URI  
  8.                 Console.WriteLine(Environment.NewLine + result);  
  9.             }  
  10.     }  
Calling Method in Main
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ConsoleEventManager  
  6. {  
  7.     class Program {  
  8.         static void Main(string[] args) {  
  9.             ConsumeEventSync objsync = new ConsumeEventSync();  
  10.             objsync.GetAllEventData_ByEventID("2"); //Get All Events Records By ID  
  11.         }  
  12.     }  
  13. }  
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 it. 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 the Newtonsoft.Json, just select Tools Menu from Visual studio IDE and add NuGet Package Manager inside the Manage NuGet Packages for solution.

After selecting Manage NuGet Packages dialog popup, 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.             EventTB objtb = new EventTB(); //Setting parameter to post  
  5.             objtb.EventID = 0;  
  6.             objtb.EventName = "Late-Night Music";  
  7.             objtb.EventStartsDate = DateTime.Now;  
  8.             objtb.EventEndsDate = DateTime.Now;  
  9.             objtb.EventLocation = "Mumbai";  
  10.             client.Headers.Add("Content-Type:application/json");  
  11.             client.Headers.Add("Accept:application/json");  
  12.             var result = client.UploadString("http://localhost:50024/api/Event", JsonConvert.SerializeObject(objtb));  
  13.             Console.WriteLine(result);  
  14.         }  
  15.     }  
Calling Method in Main
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ConsoleEventManager   
  6. {  
  7.     class Program {  
  8.         static void Main(string[] args) {  
  9.             ConsumeEventSync objsync = new ConsumeEventSync();  
  10.             objsync.PostEvent_data(); //Adding Event  
  11.         }  
  12.     }  
  13. }  
Output: In response, we are getting the 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 that in the URL, we also need to set the parameter (EventID).

Along with it, we need to set Method ["PUT"] in UploadString.
  1. public void PutEvent_data(int EventID) //Update Event  
  2.     {  
  3.         using(var client = new WebClient()) {  
  4.             EventTB objtb = new EventTB();  
  5.             objtb.EventID = 7;  
  6.             objtb.EventName = "Late-Night Music Rocks"//Value to Update  
  7.             objtb.EventStartsDate = DateTime.Now;  
  8.             objtb.EventEndsDate = DateTime.Now;  
  9.             objtb.EventLocation = "Mumbai";  
  10.             client.Headers.Add("Content-Type:application/json");  
  11.             client.Headers.Add("Accept:application/json");  
  12.             var result = client.UploadString("http://localhost:50024/api/Event/" + EventID, "PUT", JsonConvert.SerializeObject(objtb));  
  13.             Console.WriteLine(result);  
  14.         }  
  15.     }  
Calling Method in Main
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ConsoleEventManager  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args) {  
  10.             ConsumeEventSync objsync = new ConsumeEventSync();  
  11.             objsync.PutEvent_data(7); //Update Event  
  12.         }  
  13.     }  
  14. }  
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 Method ["Delete"] and data as [""] in UploadString.
  1. public void DeleteEvent_data(int EventID) //Update Event  
  2.     {  
  3.         using(var client = new WebClient()) {  
  4.             client.Headers.Add("Content-Type:application/json");  
  5.             client.Headers.Add("Accept:application/json");  
  6.             var result = client.UploadString("http://localhost:50024/api/Event/" + EventID, "Delete""");  
  7.             Console.WriteLine(result);  
  8.         }  
  9.     }  
Calling Method in Main
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ConsoleEventManager   
  6. {  
  7.     class Program {  
  8.         static void Main(string[] args) {  
  9.             ConsumeEventSync objsync = new ConsumeEventSync();  
  10.             objsync.DeleteEvent_data(7); //Delete Event  
  11.         }  
  12.     }  
  13. }  
Output: Delete the record is shown as output.

Deleted Event Data
Fig 26. Deleted Event Data