Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Create and Deploy Window Service in ASP.Net



Introduction:

Window Service enables you to create long running executable application that runs in their window session. It can be automatically started when computer boots, can be paused and restarted without any user Interaction.

Requirement:

One of the most common requirement of some business is long running schedule jobs based on some interval and Window service is a reliable solution to do the goal that can do required job behind the scenes without interfering other users on computer.

Process Architecture:

                Window Service applications are based on a Class that inherits  from the System.ServiceProcess.ServiceBaseclass. One can override various methods  from this class and define functionality for them. In addition a class named ServiceController can be used to manipulate the service itself. ServiceBase  class  exposes following methods which you can override to add custom behaviour.

Method
Description
OnStart
Indicate what actions should be taken when your service starts running. You must write Code in this procedure for your service to perform useful work.
OnPause
Indicate what should happen when your service is paused.
OnStop
Indicate what should happen when your service stops running.
OnContinue
Indicate what should happen when your service resumes normal functioning after being paused.
OnShutdown
Indicate what should happen just prior to your system shutting down, if your service is running at that time.
OnCustomCommand
Indicate what should happen when your service receives a custom command. For more information on custom commands, see MSDN online.
OnPowerEvent
Indicate how the service should respond when a power management event is received, such as a low battery or suspended operation.







*             The Runmethod on the ServiceBaseclass. This is the main entry point for the service. When you create a service using the Windows Service template, code is inserted in your application's Main method to run the service.

System.ServiceProcess.ServiceBase[] ServicesToRun;

ServicesToRun = new System.ServiceProcess.ServiceBase[]

  { new Service1() };

System.ServiceProcess.ServiceBase.Run(ServicesToRun);



These examples use an array of type ServiceBase, into which each service your application contains can be added, and then all of the services can be run together. If you are only creating a single service, however, you might choose not to use the array and simply declare a new object inheriting from ServiceBase and then run it.

*Your service must override at least OnStart and OnStop to be useful. You can also use a component called the ServiceController to communicate with and control the behavior of an existing service.
Create a Window Service
Open Visual Studio and from the menus select "File" -> "New" -> "Project...".



Please ensure to include ‘Add to Source Control’

After you click "OK", the project will be created and you will see the design view of the service as shown in the following screen. Right-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or any other name that you want to give it. Then click “click here to switch to code view”.
Now add below code in Scheduler.cs file
using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.ServiceProcess;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Timers;
namespaceFeedbackMailer
{
    public partial class MailScheduler : ServiceBase
    {
        private System.Threading.TimerCallback timerDelegate;
        private System.Threading.Timer stateTimer;
 //       private Timer timer1 = null; 
        public MailScheduler()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timerDelegate = newSystem.Threading.TimerCallback(Timer);
            stateTimer = newSystem.Threading.Timer(timerDelegate, null, 30000, System.Threading.Timeout.Infinite);
            Library.filecreation_Data("Window Service Started");
        }
        public void Timer(ObjectstateInfo)
        {
                SHOW();
        }

        public void SHOW()
        {
            try
            {
                Library myLib = new Library();
                myLib.SendMail();
          
            }
            catch(Exception ex)
            {
                Library.filecreation_Data(ex.ToString());
            }
        }
        protected override void OnStop()
        {
Library.filecreation_Data("Window Service stopped");
        }
    }
}

In the code view, you can see two methods called OnStart() and OnStop(). The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.
Right-click the on project, add a new class and name it "Library.cs". This class will be useful to create the methods that we require in the project.
Make the class public and declare it as a Static class.
In this class we’ll write all business logic required for the project with database connection.
Set connection string in App.config file.
Create a log method (filecreation_Data) to log the exceptions
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.IO;
usingSystem.Data;
usingSystem.Data.SqlClient;
using System.Configuration;
usingSystem.Web.Mail;
namespaceFeedbackMailer
{
 public   class Library
    {
        protected SqlConnection con;
        protected SqlDataReader reader;
        protected String ErrorMsg;
        protected String ErrorException;
      
        SqlTransaction trans;
        public Library()
        {
            string strCon = ConfigurationManager.AppSettings["DBConn"].ToString();
            con = new SqlConnection(strCon);
        }
       
        public static void filecreation_Data(string str1)
        {
string str = @"C:\sample.txt";
            string sdate = DateTime.Now.ToString();
            System.IO.StreamWriter sw = new System.IO.StreamWriter(str, true);
            sw.WriteLine("\n Data " + sdate);
            sw.WriteLine(str1);
            sw.Close();
        }
     public DataTable getEmployeeDetails()
         {
             SqlCommand cmd = new SqlCommand();
             DataTable dtTableABC = new DataTable();
            if (con.State==ConnectionState.Closed)
            {
                con.Open();
            }
                cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "XYZ";
            cmd.Parameters.AddWithValue("@Type", 13);
           
            SqlDataAdapter sd = new SqlDataAdapter(cmd);
            sd.Fill(dtTableABC);
            con.Close();
            return dtTableABC;
           
          }
     public DataTable getEmployeeDetailsfor1monthFeedback()
     {
         SqlCommand cmd = new SqlCommand();
         DataTable dtTableABC = new DataTable();
         if (con.State == ConnectionState.Closed)
         {
             con.Open();
         }
         cmd.Connection = con;
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.CommandText = "XYZ";
         cmd.Parameters.AddWithValue("@Type", 19);

         SqlDataAdapter sd = new SqlDataAdapter(cmd);
         sd.Fill(dtTableABC);
         con.Close();
         return dtTableABC;

     }

     public void  UpdateStatus(int empCode,string criteria)
     {
         SqlCommand cmd = new SqlCommand();
         try {
         DataTable dtTableStatus = new DataTable();
         if (con.State == ConnectionState.Closed)
         {
             con.Open();
         }
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "XYZ";
                cmd.Parameters.AddWithValue("@Type", 14);
                cmd.Parameters.AddWithValue("@empCode", empCode);
                cmd.Parameters.AddWithValue("@mailerstatus", criteria);
                SqlDataAdapter sd = new SqlDataAdapter(cmd);
                sd.Fill(dtTableStatus);
         con.Close();
         }
         catch(Exception ex)
         {con.Close();
         Library.filecreation_Data("ex" + ex + DateTime.Now.ToString());
         }
        

     }

     public void SendMail( )
     {
         int r=0;
         DataTable dttbl = getEmployeeDetails();
         if (dttbl.Rows.Count > 0)
         {
             for (r = 0; r
             {
                 if (dttbl.Rows[r]["status"].ToString() != "1")
                 {
                     int empId = Convert.ToInt32(dttbl.Rows[r]["empcode"].ToString());
                     string empName = dttbl.Rows[r]["empName"].ToString();
                     string empEmailId = dttbl.Rows[r]["empEmailId"].ToString();
                     string ABCname = dttbl.Rows[r]["empName1"].ToString();
                     string link = "http://abc-solutions.com/ABC/ABCFeedbackForm.aspx?eid=" + empId + "";

                     string sBody = @"          
               
               
               
                
                   
               
               
                   
                
                    
                   
                   
Hi " + empName + @",
Please share feedback for your ABC " + ABCname + @".
+ link + @"'>" + link + @"
                   
                   
                       
                       
                        
                               
                       
                       
                               
                       
                       
With Regards,

                            ABC
                       
                        ABCSolutions Limited
                       
                            Web: www.ABC-solutions.com’
 
 

                        
                    ";
                     DateTime dtString = DateTime.Now;
                     string strDate = "";
                     strDate = dtString.ToString("dd-MMMM-yyyy hh:mm tt"); // formated date - 21 July 2015 03:00 PM 
                     try { SmtpMail.SmtpServer = "LOCALHOST"; }
                     catch (Exception ex)
                     {
                         Library.filecreation_Data("ex" + ex + DateTime.Now.ToString());
                     }


                     try
                     {

                         MailMessage mail = new MailMessage();
                         //  mail.To = empEmailId;
                         mail.To = empEmailId;

                         mail.Bcc = "[email protected]";
                         mail.From = "[email protected]";
                         mail.Subject = "ABC-Feedback";
                         mail.Body = sBody;
                         mail.BodyFormat = MailFormat.Html;
                         SmtpMail.Send(mail);


                     }
                     catch (Exception ex)
                     {
                         Library.filecreation_Data("ex" + ex + DateTime.Now.ToString());
                     }
                     finally
                     {

                     }
                     UpdateStatus(empId, "ABC");
                     Library.filecreation_Data("ABC Mail Send" + DateTime.Now.ToString());

                 }
             }
             }
         }
  
     }


    }
Now return to Scheduler.cs file in design view and right click on editor window and click AddInstaller.
There will be a new file called ProjectInstaller.cs. Right click on serviceInstaller1 and click properties. Change servicename as desired and change startype from Manual to Automatic .
Right click on serviceProcessInstaller1, go to properties window and change Account to ‘LocalSystem’
Mention Description and Displayname as well.
Build the project to see .exe file at location where you created solution.

Installing Service Setup

Download  Project Installer  for Visualstudio 2013:
https://visualstudiogallery.msdn.microsoft.com/9abe329c-9bba-44a1-be59-0fbf6151054d(VSI-bundle)
Install It.
Now click FileàAddàNew ProjectàOther Project TypesàVisual Studio InstalleràSetup Project

Now Right click on Setup FolderàSelect AddàProject OutputàPrimary Output

Select Setup folder then select Custom Action Report from Solution explorer.
Select Custom Actions from Console-Right Click-Add Custom Action-OK
Finally Build Setup clicking on Setup Folder.
*Delete all files(primary output) under Custom Action whenever any changes in window service code.






This post first appeared on Pivot In SQL Server, please read the originial post: here

Share the post

How to Create and Deploy Window Service in ASP.Net

×

Subscribe to Pivot In Sql Server

Get updates delivered right to your inbox!

Thank you for your subscription

×