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.
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,
- Creating Web API.
- 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”.
Fig 1. Add and Naming Project
After adding, new dialogs will pop-up for choosing the template.
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:
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
Fig 3.Event Table in Design Mode
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:
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”.
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.
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.
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.
Fig 9.Setting Connection Properties
After choosing the database connection, final view of connection Wizard is shown below:
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
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.
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”.
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.
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.
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”.
Fig 16. Creating Console application and naming it
After entering the project name, finally click the OK button and your console project creates.
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.
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text;
- namespace ConsoleEventManager
- {
- public class ConsumeEventSync
- {
- public void GetAllEventData()
- {
- using(var client = new WebClient())
- {
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
- var result = client.DownloadString("http://localhost:50024/api/Event"); //URI
- Console.WriteLine(Environment.NewLine + result);
- }
- }
- }
- }
Calling Method in Main
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleEventManager
- {
- class Program {
- static void Main(string[] args) {
- ConsumeEventSync objsync = new ConsumeEventSync();
- objsync.GetAllEventData();
- }
- }
- }
Output: Showing the data for all Events.
Fig 19. Get All Events Records
Get All Events Records By ID - public void GetAllEventData_ByEventID(string EventID)
- {
- using(var client = new WebClient())
- {
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
- var result = client.DownloadString("http://localhost:50024/api/Event/" + EventID); //URI
- Console.WriteLine(Environment.NewLine + result);
- }
- }
Calling Method in Main
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleEventManager
- {
- class Program {
- static void Main(string[] args) {
- ConsumeEventSync objsync = new ConsumeEventSync();
- objsync.GetAllEventData_ByEventID("2");
- }
- }
- }
Output: Showing the data against EventID, which we have passed to the Method.
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.
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.
Fig 22. Adding Newtonsoft.Json
- public void PostEvent_data()
- {
- using(var client = new WebClient()) {
- EventTB objtb = new EventTB();
- objtb.EventID = 0;
- objtb.EventName = "Late-Night Music";
- objtb.EventStartsDate = DateTime.Now;
- objtb.EventEndsDate = DateTime.Now;
- objtb.EventLocation = "Mumbai";
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
- var result = client.UploadString("http://localhost:50024/api/Event", JsonConvert.SerializeObject(objtb));
- Console.WriteLine(result);
- }
- }
Calling Method in Main
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleEventManager
- {
- class Program {
- static void Main(string[] args) {
- ConsumeEventSync objsync = new ConsumeEventSync();
- objsync.PostEvent_data();
- }
- }
- }
Output: In response, we are getting the data, which we have inserted.
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.
- public void PutEvent_data(int EventID)
- {
- using(var client = new WebClient()) {
- EventTB objtb = new EventTB();
- objtb.EventID = 7;
- objtb.EventName = "Late-Night Music Rocks";
- objtb.EventStartsDate = DateTime.Now;
- objtb.EventEndsDate = DateTime.Now;
- objtb.EventLocation = "Mumbai";
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
- var result = client.UploadString("http://localhost:50024/api/Event/" + EventID, "PUT", JsonConvert.SerializeObject(objtb));
- Console.WriteLine(result);
- }
- }
Calling Method in Main
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleEventManager
- {
- class Program
- {
- static void Main(string[] args) {
- ConsumeEventSync objsync = new ConsumeEventSync();
- objsync.PutEvent_data(7);
- }
- }
- }
Output: Output for the update is empty.
Fig 24. Updating Event Data.
Updated 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.
- public void DeleteEvent_data(int EventID)
- {
- using(var client = new WebClient()) {
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
- var result = client.UploadString("http://localhost:50024/api/Event/" + EventID, "Delete", "");
- Console.WriteLine(result);
- }
- }
Calling Method in Main
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleEventManager
- {
- class Program {
- static void Main(string[] args) {
- ConsumeEventSync objsync = new ConsumeEventSync();
- objsync.DeleteEvent_data(7);
- }
- }
- }
Output: Delete the record is shown as output.
Fig 26. Deleted Event Data