Deploy a Windows Service
Bookmark
 

Rating: 5.00/5
1 2 3 4 5
1 people have rated this article

 
Posted On: Jun 18 2008
Views: 4062
BookMarked: 1
Downloads: 69
 
 
This article describes how to create a simple windows service.

“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.”

Source: http://msdn.microsoft.com/en-us/library/d56de412(VS.80).aspx

Above link gives brief explanation about the Windows Service. It is very easy to create a Windows Service using Visual Studio Tool. Please follow the given steps below to create a Windows Service Using Visual Studio 2005.

To create a New Windows Service Project
  • From the File menu, create a new project.
  • Select the C# Windows project type.
  • Select the Windows Service Template.
  • Name the project TestService.



Then double-click on the Service1.cs file. Then right click on the design mode, select View Code.

For Service file, there will be three methods by default.
  1. Constructor - public Service1()
  2. OnStart – This method is fired when you start the service.
  3. OnStop – This method is fired when you stop the service.

You need to add your functionality in the OnStart() method of Service1.cs
Take a simple scenario such as logging current local time in a text file. The current time logging logic will be:
FileStream fs = null;
StreamWriter sw = null;
try
{
String Dir="C:\\Test Services";
if (!Directory.Exists(Dir))
{
Directory.CreateDirectory(Dir);
}
Dir="C:\\Test Services\\Logs";
if (!Directory.Exists(Dir))
{
Directory.CreateDirectory(Dir);
}
fs = new FileStream(Dir+"\\Service.txt", FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
sw = new StreamWriter(fs);
sw.WriteLine("Service Started at "+DateTime.Now);
sw.WriteLine();
}
catch (Exception ex)
{
}
finally
{
if (sw != null)
{
sw.Flush(); sw.Close(); } if (fs != null) { fs.Close(); } }
Please copy and paste the above code in OnStart() event of Service1.cs.
Build the project using the Build dialog box. Now you are done creating windows service.
You can install your service by using a command-line utility called InstallUtil.exe. You can also install your service by creating step-up project using Visual Studio.

To install your service manually
  • Open Visual Studio Command Prompt, Go to the directory in which your project's compiled executable file is located. Usually it is located at Your Project/Debug/Bin.
  • Run InstallUtil.exe from the command line with your project's output as a parameter. installutil yourproject.exe

To uninstall your service manually
  • Run InstallUtil.exe from the command line with your project's output as a parameter.
  • installutil /u yourproject.exe

To install your service using Setup project

You can install the service using Project Installer file. You can set your own custom actions with it that will run your project installer with its associated project and install the service.

Double-Click the Service1.cs file. Then right click on the design mode, select Add Installer. This will add a ProjectInstaller.cs file to your windows service project. Expand the ProjectInstaller.cs node, then select ProjectInstaller.Designer.cs. In the ProjectInstaller.Designer.cs file, expand Component Designer generated code hidden content.



To install your service,you need an account information. Use the LocalSytem account has all privilages to run your service. You can also create your own account to run the service.
To make it more meaningful add Description, DisplayName in your ProjectInstaller.Designer.cs file. Also set windows service Start type as automatic.
Replace InitializeComponent() method with following code:
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
// // serviceProcessInstaller1 //
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
// // serviceInstaller1 //
this.serviceInstaller1.ServiceName = "Service1";
this.serviceInstaller1.Description = "Test Service ASP.NET";
this.serviceInstaller1.DisplayName = "Test Service ASP.NET";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
// // ProjectInstaller //
this.Installers.AddRange(new System.Configuration.Install.Installer[]
{
this.serviceProcessInstaller1, this.serviceInstaller1});
}
To create a setup project to for windows service
  1. From the File/Add/New Project menu, add a new project.
  2. Select the Other Project Types/Deployment and Setup project type.
  3. Select the Setup Project Template.
  4. Name the project TestServiceSetup.

Source: http://msdn.microsoft.com/en-us/library/sd8zc8ha(VS.80).aspx



This will add a setup project to your windows service project. To install your windows service, you need to define the custom actions on the setup project.

To install your windows service
  1. Right click on the Setup project, select File System from the dialog box. You will get a File System Tab.
  2. Right Click on the File System Tab/Application Folder, add project output as shown in picture. This will install your Windows Service EXE in the target machine. If you like to add external files such as images, .config file, text file, dll to target machine,  add your external file to the application folder.
  3.          

             

  4. Right click on the Setup project, select Custom Action from the dialog box. You will get a Custom Action Tab.
  5. Right Click on the Custom Action, Select Application Folder and the add project output from Test Service as shown in the picture.
  6.          


Now you are done with creating setup project. Final step is set your setup project for release. Right click on the Root Solution, then select property dialog box. In the Solution Property Pages Wizard, open Configuration properties and then select configuration. Then change your setup project configuration type to release as shown in the picture. Finally, build the root solution.



To install your service, go to the setup project directory in which your project's Release folder is located, and then run the .msi file.
Now you need to start your service manually. Right click on the My Computer icon, select Manage option. From service and application computer management wizard, right click on your services name, select start.



Once you started your service you can find a file named Test Service//Logs//Service.txt directory on the C drive.
To make your service run every X amount time, you need to have timer declared in your service. Then set your method as timer’s elapsed event. This will make your function run every X amount of millisecond.
private Timer t=null;
public Service1()
{
InitializeComponent();
t = new Timer(1*60*1000);
t.Elapsed += new ElapsedEventHandler(RunMyFunction);
}

protected override void OnStart(string[] args)
{
t.Start();
}

protected override void OnStop()
{
t.Stop();
}

public void RunMyFunction (Object sender, EventArgs e)
{
//Your logic goes here...
}

I hope this article helps to create a simple windows service. You can add your own logic in the RunMyFunction() method.This will run every one minute.
You can also use ProjectName.exe.config to supply your parameters to the window service as key/value pair.

Be sure to place ProjectName.exe.config to directory where your windows service is installed. So that your windows can read the key/value pair. I recommend not use the app.config file if your parameter changes often. ProjectName.exe.config is not part of the your windows service eexecutable, so you can make the changes any time without rebuilding it.


Rate This Article

Please Sign In In to post messages.