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.
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
- Creating Web API
- 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”.
Fig 1. Add and Name the 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. Don’t miss choosing View engine as Razor.
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 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 .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:
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 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 database option and click Next button. After clicking Next button, a new wizard will pop up for choosing the database 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.
Fig 9.Setting Connection Properties
After choosing the database connection, final view of connection Wizard will be:
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
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. 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”.
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.
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.
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”.
Fig 16. Creating Console application and naming it
After entering the project name, finally click OK button and your console project will be created.
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”.
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
- using System;
- using System.Net;
- namespace ConsoleEventManager {
- public class ConsumeEventSync {
- public void GetAllEventData()
- {
- using(var client = new WebClient())
- {
- Uri URI = new Uri("http://localhost:50024/api/Event");
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
-
- client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadString_AllEvent_Callback);
- client.DownloadStringAsync(URI);
- }
- }
-
- void DownloadString_AllEvent_Callback(object sender, DownloadStringCompletedEventArgs e) {
- Console.WriteLine(e.Result);
- }
- }
- }
Calling Method in Main - namespace ConsoleEventManager {
- class Program {
- static void Main(string[] args) {
- ConsumeEventSync objAsync = new ConsumeEventSync();
- objAsync.GetAllEventData();
- }
- }
- }
Output: Showing the data for all the Events.
Fig 19. Get All Events Records
Get All Events Records By ID
- public void GetAllEventData_ByEventID(string EventID)
- {
- using(var client = new WebClient())
- {
- Uri URI = new Uri("http://localhost:50024/api/Event/" + EventID);
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
-
-
- client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadString_EventByID_Callback);
- client.DownloadStringAsync(URI);
- Console.ReadLine();
- }
- }
-
- void DownloadString_EventByID_Callback(object sender, DownloadStringCompletedEventArgs e) {
- Console.WriteLine(e.Result);
- }
Calling Method in Main - namespace ConsoleEventManager {
- class Program {
- static void Main(string[] args) {
- ConsumeEventSync objAsync = new ConsumeEventSync();
- objAsync.GetAllEventData_ByEventID("3");
-
- }
- }
- }
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 this, 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 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.
Fig 22. Adding Newtonsoft.JSON
- public void PostEvent_data()
- {
- using(var client = new WebClient()) {
- Uri URI = new Uri("http://localhost:50024/api/Event");
- EventTB objtb = new EventTB();
- objtb.EventID = 0;
- objtb.EventName = "Party";
- objtb.EventStartsDate = DateTime.Now;
- objtb.EventEndsDate = DateTime.Now;
- objtb.EventLocation = "Mumbai";
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
- client.UploadStringCompleted += new UploadStringCompletedEventHandler(UploadString_POST_Callback);
- client.UploadStringAsync(URI, JsonConvert.SerializeObject(objtb));
- }
- }
- void UploadString_POST_Callback(object sender, UploadStringCompletedEventArgs e) {
- Console.WriteLine(e.Result);
- }
Calling Method in Main - class Program {
- static void Main(string[] args) {
- ConsumeEventSync objAsync = new ConsumeEventSync();
- objAsync.PostEvent_data();
-
- }
- }
- Output: In response, we are getting 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 it in URL, we need to set the parameter (EventID).
Along with it, we need to set the method ["PUT"] in UploadStringAsync.
- public void PutEvent_data(int EventID)
- {
- Uri URI = new Uri("http://localhost:50024/api/Event/" + EventID);
- using(var client = new WebClient()) {
- EventTB objtb = new EventTB();
- objtb.EventID = 7;
- objtb.EventName = "Mumbai 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");
- client.UploadStringCompleted += new UploadStringCompletedEventHandler(UploadString_PUT_Callback);
- client.UploadStringAsync(URI, "PUT", JsonConvert.SerializeObject(objtb));
- }
- }
- void UploadString_PUT_Callback(object sender, UploadStringCompletedEventArgs e) {
- Console.WriteLine(e.Result);
- }
Calling Method in Main
- class Program {
- static void Main(string[] args) {
- ConsumeEventSync objAsync = new ConsumeEventSync();
- objAsync.PutEvent_data(9);
-
- }
- }
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 the method ["Delete"] and data as [""] in UploadStringAsync.
- public void DeleteEvent_data(int EventID)
- {
- Uri URI = new Uri("http://localhost:50024/api/Event/" + EventID);
- using(var client = new WebClient()) {
- client.Headers.Add("Content-Type:application/json");
- client.Headers.Add("Accept:application/json");
- client.UploadStringCompleted += new UploadStringCompletedEventHandler(DeleteString_EventByID_Callback);
- client.UploadStringAsync(URI, "Delete", "");
- }
- }
- void DeleteString_EventByID_Callback(object sender, UploadStringCompletedEventArgs e) {
- Console.WriteLine(e.Result);
- }
- Calling Me
thod in Main
- class Program
- {
- static void Main(string[] args)
- {
- ConsumeEventSync objAsync = new ConsumeEventSync();
- objAsync.DeleteEvent_data(9);
-
- }
- }
Output: Delete record is shown as output.
Fig 26. Deleted event data