Create and Install a Windows Service in C#

Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account.
This article explains a step-by-step process of developing and installing a Windows Service to do a scheduled job based on a time interval.
In Visual Studio, create a new project . Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the right side.





After you click "OK", the project will be created and you will see the design view of the service.

Then click “click here to switch to 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 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.
Add this directive to the class:

using System.IO;


Create a log method (WriteErrorLog) to log the exceptions.

public static void WriteErrorLog(Exception ex)
{
    StreamWriter sw = null;
    try
    {
        sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
        sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
        sw.Flush();
        sw.Close();
    }
    catch
    {

    }
}

Create one more log method (WriteErrorLog) to log the custom messages.

public static void WriteErrorLog(string message)
{
    StreamWriter sw = null;
    try
    {
        sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
        sw.WriteLine(DateTime.Now.ToString() + ": "+ message);
        sw.Flush();
        sw.Close();
    }
    catch
    {

    }
}

Now return to our Service1.cs file and declare a Timer.

using System.Timers;
.
.
.
private Timer timer1 = null;

Write the following code in the OnStart() method and timer1_Tick() and OnStop():

protected override void OnStart(string[] args)
{
    timer1 = new Timer();
    this.timer1.Interval = 30000;
    this.timer1.Elapsed += new ElapsedEventHandler(this.timer1_Tick);
    timer1.Enabled = true;
    Library.WriteErrorLog("Test window service started");
}

private void timer1_Tick(object sender,ElapsedEventArgs e)
{
    Library.WriteErrorLog("Timer ticked and some job has been done successfully");
}
protected override void OnStop()
{
    timer1.Enabled = false;
    Library.WriteErrorLog("Test window service stopped");
}

Now return to the Service1.cs [Design] and right-click on the editor window then click "Add Installer".


Then you can see that there will be a new file called "ProjectInstaller.cs".
Right-click on the "serviceInstaller1" and click "Properties". Change the ServiceName to "TestService" and StartType to "Manual.
Right-click the serviceProcessInstaller1, go to the properties window and change "Account" to "LocalSystem".
Build the project to see the .exe file at the location where you created the solution.
That's all. Your Windows Service is all ready to install in your machine.

Installing the Windows Service:

Go to "Start" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" then click "Developer Command Prompt for VS2012".

cd <physical location of your TestWindowService.exe file>




Next type the following command:

InstallUtil.exe “TestWindowService.exe”

and press Enter.

TestWindowService

Here you go, the TestWindowService is installed successfully.

installed successfully

How to start the Windows Service
Since we chose StartType = Manual, we must start the Windows Service manually by visiting the "Services and Applications" window in the computer.

StartType

Select the Test Windows Service and click "Start" to start the service. Go to the "TestWindowService.exe" location to see the logs.

LogFile.txt
Since we are tracking our Windows Service by writing some logs to a .txt file called LogFile.txt, we can test the working condition of our Windows Service by looking at this log file.

LogFile

As you can see in the preceding screen, you can find the LogFile.txt file at the physical location that your TestWindowService solution exists.

Click the LogFile.txt to see the logs, whether our service is doing the job that we set it to do for every 30 seconds.
 
logs

If you look at the preceding log file, we can prove that our Windows Service is running and doing the job that we wanted on a 30 seconds interval.

Stop the Windows Service
To stop the Windows Service, just click "Stop" link in the Services window by selecting our TestWindowService.

Logfile after stopping our service:
 
Stop the window service

Type the following two commands in the "Developer Command Prompt for VS2012" to uninstall the TestWindowService.exe.

cd <physical location of your TestWindowService.exe file>
  1. and press Enter. In my case it is:
    cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug
  2. InstallUtil.exe /u “TestWindowService.exe”
    And press enter.
    After executing the preceding commands, the TestWindowService will be uninstalled from your computer.



Reference:
Develop and Install a Windows Service in C#
Create and Install a Windows Service in C# Create and Install a Windows Service in C# Reviewed by Bloggeur DZ on 03:05 Rating: 5

Aucun commentaire:

Fourni par Blogger.