Login Using WebAPI In Desktop Application

Hello Friends,
 
In this article, we are going to see,
  1. How to create web API
  2. How to host web API on IIS server
  3. How to use web API in a desktop application using the .NET client 
Prerequisites when you use this demo:
1) Download datatable structure and data
2) Execute in your SQL server
3) Set your database connection string from the web.config file
 
CREATE WEB API
 
STEP 1

Open Visual Studio, go to New Project -> Visual C# -> Web -> Asp.net Web Application, name your project, and click OK. You will see a screen as below.
 

Image1 

STEP 2

Select "Web API" from the template as shown in image1 and click OK. It will create a project for you as shown in image 2.
 

Image2
 
STEP 2

In this article, I am going show you how to login through web API from a desktop application. We need fields like email and password. Here, create a model for login class as shown in image 3 and add a code snippet in the newly-created model class.
 
You can create a model by right clicking on Models folder -> Add Class.
 

Image3
  1. public class Login  
  2.     {  
  3.         public int id { getset; }  
  4.         public string UserName { getset; }  
  5.         public string Email { getset; }  
  6.         public string Password { getset; }  
  7.     }  
STEP 3

Create Controller by right-clicking on the Controllers folder as shown in image4

Add-> Controller -> Web API 2 Controller - Empty .
 

Image4 
 
Put this below code snippet into Controller.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. using System.Configuration;  
  9. using System.Data;  
  10. using System.Data.SqlClient;  
  11. using LoginWebAPIDesktopAppDemo.Models;  
  12.   
  13. namespace LoginWebAPIDesktopAppDemo.Controllers  
  14. {  
  15.     public class LoginController : ApiController  
  16.     {  
  17.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["customerDB"].ToString());  
  18.         SqlCommand cmd = new SqlCommand();  
  19.         SqlDataAdapter adp = null;  
  20.   
  21.         [HttpGet]  
  22.         [ActionName("getCustomerInfo")]          
  23.         public DataTable Get()  
  24.         {  
  25.             DataTable dt = new DataTable();  
  26.             try  
  27.             {  
  28.                 cmd.CommandType = CommandType.Text;  
  29.                 cmd.CommandText = "select * from tbl_Cust";  
  30.                 cmd.Connection = con;  
  31.                 if (con.State == ConnectionState.Open)  
  32.                 {  
  33.                     con.Close();  
  34.                 }  
  35.                 adp = new SqlDataAdapter(cmd);  
  36.                 dt.TableName = "tbl_Cust";  
  37.                 adp.Fill(dt);  
  38.                 con.Close();  
  39.             }  
  40.             catch  
  41.             {  
  42.                   
  43.             }  
  44.             return dt;  
  45.         }  
  46.   
  47.         [HttpPost]  
  48.         public int Login([System.Web.Http.FromBody] Login lgn)  
  49.         {  
  50.             int ret = 0;  
  51.             try  
  52.             {  
  53.                 cmd.CommandType = CommandType.Text;                  
  54.                 cmd.CommandText = "SELECT count(*) FROM tbl_Cust WHERE Email ='" + lgn.Email.Trim() + "' and Password=" + lgn.Password.Trim();  
  55.                 cmd.Connection = con;  
  56.                 if (con.State == ConnectionState.Open)  
  57.                 {  
  58.                     con.Close();  
  59.                 }  
  60.                 con.Open();  
  61.                 ret = Convert.ToInt32(cmd.ExecuteScalar());  
  62.                 con.Close();  
  63.             }  
  64.             catch  
  65.             {  
  66.             }  
  67.             return ret;  
  68.         }  
  69.     }  
  70. }  
As, you can see, I have created two methods -
1) Get() is for getting all the customers' data
2) Login() is a parameterized method where we can pass email and password for validation.
 
NOTE
Web API will give two types of output -
1) XML(Default)
2) JSON.
 
Getting the response in XML

When you are set up, as per step 1, build the project and run the application. For getting the results in XML, you need to follow the route and execute the URL as shown in image 5.


Image 5
 
Getting a response in JSON:

For a JSON response, you need to set mediatypeheadervalues in WebApiConfig.cs file which is located in App_Start folder. Just set the code as shown in the below code snippet.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http.Headers;  
  5. using System.Web.Http;  
  6.   
  7. namespace LoginWebAPIDesktopAppDemo  
  8. {  
  9.     public static class WebApiConfig  
  10.     {  
  11.         public static void Register(HttpConfiguration config)  
  12.         {  
  13.             // Web API configuration and services  
  14.   
  15.             // Web API routes  
  16.             config.MapHttpAttributeRoutes();  
  17.   
  18.             config.Routes.MapHttpRoute(  
  19.                 name: "DefaultApi",  
  20.                 routeTemplate: "api/{controller}/{id}",  
  21.                 defaults: new { id = RouteParameter.Optional }  
  22.             );  
  23.             config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
  24.         }  
  25.     }  
  26. }  
Now, execute the URL in the browser and you get a response as shown in image6.


Image6
 
HOST WEB API ON IIS SERVER

STEP 1

Open IIS manager by executing inetmgr command in RUN as shown in Image 7.
 

Image 7 
 
STEP 2

Follow the steps shown in Image 8.

 
Image 8 
 
Just, right click on the left panel, the "Connections" section, which I have blurred with black. Go to Connections -> Sites - > Add Website.
You will see Add Website popup shown as in Image 8. Now, set your site name. You need to set application pool framework the same as you developed in the web API. You can see your web API's framework by just right clicking on web API project -> Properties -> Application - > Target Framework as shown in Image9.


Image 9
 
You are ready with your Web API and can execute it from IIS manager like this: http://localhost:80/api/login/getCustomerInfo
 
CREATE DESKTOP APPLICATION AND USE WEB API
 
STEP 1
 
For creating the desktop app, open Visual Studio, go to New Project -> Visual C# -> Windows -> Windows Form Application
 
Now, add a new form in the project with some login controls as shown in Image10.
 

Image10

Below is the code for Login.cs file. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. using System.Windows.Forms;  
  10. using System.Data.SqlClient;  
  11. using System.Web;  
  12. using Newtonsoft.Json.Linq;  
  13. using System.Text.RegularExpressions;  
  14. using System.Net.Http;  
  15. using System.Net.Http.Headers;  
  16.   
  17. namespace Login  
  18. {  
  19.     public partial class Login : Form  
  20.     {  
  21.         public Login()  
  22.         {  
  23.             InitializeComponent();  
  24.         }  
  25.   
  26.         private void btnLogin_Click(object sender, EventArgs e)  
  27.         {  
  28.             errorProvider1.SetError(txtUsername, "");  
  29.             errorProvider1.SetError(txtPassword, "");  
  30.             if (txtUsername.Text.ToString().Trim() != "" && txtPassword.Text.ToString().Trim() != "")  
  31.             {  
  32.                 using (var client = new HttpClient())  
  33.                 {  
  34.                     client.BaseAddress = new Uri("http://localhost:59/");  
  35.                     LoginClass lgn = new LoginClass { Email = txtUsername.Text.ToString(), Password = txtPassword.Text.ToString() };  
  36.                     var response = client.PostAsJsonAsync("api/Login/Login", lgn).Result;  
  37.                     var a = response.Content.ReadAsStringAsync();  
  38.                     if (a.Result.ToString().Trim() == "0")  
  39.                     {  
  40.                         lblErrorMessage.Text = "Invalid login credentials.";  
  41.                         lblErrorMessage.ForeColor = Color.Red;  
  42.                     }  
  43.                     else  
  44.                     {  
  45.                         lblErrorMessage.Text = "Loggedin successfully.";  
  46.                         lblErrorMessage.ForeColor = Color.Green;  
  47.                     }  
  48.                 }  
  49.             }  
  50.             else if (txtUsername.Text.ToString().Trim() == "" && txtPassword.Text.ToString().Trim() == "")  
  51.             {  
  52.                 errorProvider1.SetError(txtUsername, "Please enter the email");  
  53.                 errorProvider1.SetError(txtPassword, "Please enter the password");  
  54.             }  
  55.             else if (txtUsername.Text.ToString().Trim() == "")  
  56.             {  
  57.                 errorProvider1.SetError(txtUsername, "Please enter the email");  
  58.             }  
  59.             else if (txtPassword.Text.ToString().Trim() == "")  
  60.             {  
  61.                 errorProvider1.SetError(txtPassword, "Please enter the password");  
  62.             }  
  63.         }         
  64.   
  65.         private void ValidateEmail()  
  66.         {  
  67.             Regex regEmail = new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+"  
  68.                                     + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"  
  69.                                     + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"  
  70.                                     + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"  
  71.                                     + @"[a-zA-Z]{2,}))$",  
  72.                                     RegexOptions.Compiled);  
  73.   
  74.             if (!regEmail.IsMatch(txtUsername.Text))  
  75.             {  
  76.                 errorProvider1.SetError(txtUsername, "Please enter a Valid Email Address.");  
  77.             }  
  78.             else  
  79.             {  
  80.                 errorProvider1.SetError(txtUsername, "");  
  81.             }  
  82.         }  
  83.   
  84.         private void Login_FormClosed(object sender, FormClosedEventArgs e)  
  85.         {  
  86.             Application.Exit();  
  87.         }  
  88.   
  89.         private void txtUsername_Validating(object sender, CancelEventArgs e)  
  90.         {  
  91.             ValidateEmail();  
  92.         }  
  93.   
  94.   
  95.         public class LoginClass  
  96.         {  
  97.             public int id { getset; }  
  98.             public string UserName { getset; }  
  99.             public string Email { getset; }  
  100.             public string Password { getset; }  
  101.         }  
  102.     }  
  103.   
  104.      
  105. }  
STEP 2
 
We will receive the response from WEB API in json format. So for getting a response in a desktop application we need to add JSON.NET in out desktop app project as shown in Image 11. 
 
Go to references -> Right Click - > Manage Nuget Packages - > Online -> Search -> Json.net 

 
Image11
 
STEP 3
 
Now, build the desktop app project and run it. You will get a login screen as in Image 12 and you are done. 
 
 
I hope you will like this article and it might be useful to you. Please let me know if you have any suggestions/changes/corrections.