Call (Consume) ASP.Net Web API in Windows Service using C#

PriyaKann
 
on Apr 30, 2020 07:04 AM
5396 Views

Hi,

How to Consume Web API Data using Windows Service and Save in SQL Database Table

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 01, 2020 04:59 AM

Hi PriyaKann,

For windows service refer below article.

Simple Windows Service that runs periodically and once a day at specific time using C# and VB.Net

Automatically send Birthday email using C# and VB.Net

In place of Send email code call the Web API and insert the record to database.

For Web API refer below article.

Call (Consume) Web API in Windows Forms Application using C#

Use below code to call Web API and insert into database.

Namespaces

using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

Code

private void SchedularCallback(object e)
{
    try
    {
        string apiUrl = "APIURL";
        object input = new
        {
            Name = txtName.Text.Trim()
        };
        string inputJson = (new JavaScriptSerializer()).Serialize(input);
        WebClient client = new WebClient();
        client.Headers["Content-type"] = "application/json";
        client.Encoding = Encoding.UTF8;
        string json = client.UploadString(apiUrl + "/GetCustomers", inputJson);
        List<Customer> customers = (new JavaScriptSerializer()).Deserialize<List<Customer>>(json);
        foreach (Customer customer in customers)
        {
            string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO Custromers (CustomerID,ContactName,City) VALUES (@Id,@Name,@City)"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Id", customer.CustomerID);
                    cmd.Parameters.AddWithValue("@Name", customer.ContactName);
                    cmd.Parameters.AddWithValue("@City", customer.City);
                    cmd.Connection = con;
                }
            }
        }
        this.ScheduleService();
    }
    catch (Exception ex)
    {
        WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);

        //Stop the Windows Service.
        using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
        {
            serviceController.Stop();
        }
    }
}

public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
}