sumitmehta
New Member
- Messages
- 215
- Reaction score
- 1
- Points
- 0
Hye Guys.
I found a wonderful article on creating Windows Services in C#.NET. I thought to share it with you all. If you like, pls do rep me.
First let's take a closer look at Windows Service classes.
You can create Windows Services with the help of the ServiceBase class in the System.ServiceProcess namespace. It contains the following subset of events that interact with the Windows Service Control Manager(SCM):
Creating a Windows Service
Visual Studio .NET makes it simple to create a service using the code of choice:
[FONT="]1.[/FONT][FONT="]To create a new Windows Service, pick the Windows Service option from your Visual Studio Projects (choose appropriate language), give your service a name, and click OK. [/FONT]
[FONT="]2.[/FONT][FONT="]A Windows Service project is created with the default project name of WindowsService1 and a class name of Service1. [/FONT]
The next C# code listing includes the code skeleton Visual Studio creates, along with custom code to write information to the Windows Event Log when the associated events are fired. In addition, a constructor, dispose, and the point of execution (i.e., the main method) are included as well:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
namespace WindowsService1 {
public class Service1 : System.ServiceProcess.ServiceBase {
private EventLog log = null;
private System.ComponentModel.Container components = null;
public Service1() {
InitializeComponent();
}
static void Main() {
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
private void InitializeComponent() {
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Dispose();
} }
base.Dispose( disposing );
log.WriteEntry("Service dispose", EventLogEntryType.Information);
log.Close();
}
protected override void OnStart(string[] args) {
log = new EventLog("Builder.com");
log.WriteEntry("Service starting", EventLogEntryType.Information);
}
protected override void OnStop() {
log.WriteEntry("Service stopping.", EventLogEntryType.Information);
} } }
Notice that the code execution entry point (Main method) creates a new instance of the ServiceBase class (an object array) and adds an instance of your class to it. The use of the array demonstrates the ability to run more than one process within the service.
Windows service installation
While console, Windows Form, and ASP.NET applications are easy to install by copying files, you must explicitly install Windows Service applications. Visual Studio .NET simplifies the installation process for Windows server applications. It displays a link in the Properties window of the Windows Service called Add Installer. When you select the link, the IDE adds the necessary installer classes to your project as part of a separate module.
This includes two classes: System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller. Several properties may be set using the Properties window of each class. The most important property is Account within the ServiceProcessInstaller class. It specifies the Windows account under which the service runs (security context). The following options are available:
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
namespace WindowsService1 {
[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer {
public System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller testInstaller;
private System.ComponentModel.Container components = null;
public ProjectInstaller() {
InitializeComponent();
}
protected override void Dispose( bool disposing ) {
if(disposing) {
if(components != null) {
components.Dispose();
} }
base.Dispose( disposing );
}
#region Component Designer generated code
private void InitializeComponent() {
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.testInstaller = new System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller1.Account =
System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.testInstaller.DisplayName = "Test Installer";
this.testInstaller.ServiceName = "BuilderService";
this.testInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.Installers.AddRange(
new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.testInstaller});
}
#endregion
} }
With the installers added to the project, you may now install the Windows Service and run it on the target computer. Another approach within our project is how the service is started. There are three options:
InstallUtil WindowsService.exe
The line is run in the directory containing the assembly; otherwise, it would require the complete path to the assembly. After you install the new Service, it's located in the Services window of the Computer Management applet.
I found a wonderful article on creating Windows Services in C#.NET. I thought to share it with you all. If you like, pls do rep me.
First let's take a closer look at Windows Service classes.
You can create Windows Services with the help of the ServiceBase class in the System.ServiceProcess namespace. It contains the following subset of events that interact with the Windows Service Control Manager(SCM):
- [FONT="]OnContinue:[/FONT][FONT="] Fires when a continue command is sent to the service by the SCM. It specifies actions to take when a service resumes normal functioning after being paused. [/FONT]
- [FONT="]OnPause:[/FONT][FONT="] Fires when a pause command is sent to the service by the SCM. It specifies actions to take when a service pauses. [/FONT]
- [FONT="]OnPowerEvent:[/FONT][FONT="] Fires when the computer's power status has changed. This applies to laptop computers when they go into suspended mode, which isn't the same as a system shutdown. [/FONT]
- [FONT="]OnShutdown:[/FONT][FONT="] Fires when the system is shutting down. It specifies what should happen immediately prior to the system shutting down. [/FONT]
- [FONT="]OnStart:[/FONT][FONT="] Fires when a start command is sent to the service by the SCM or when the operating system starts (for a service that starts automatically). It specifies actions to take when the service starts. An array of String objects is the event's lone parameter. [/FONT]
- [FONT="]OnStop:[/FONT][FONT="] Fires when a stop command is sent to the service by the SCM. It specifies actions to take when a service stops running. [/FONT]
Creating a Windows Service
Visual Studio .NET makes it simple to create a service using the code of choice:
[FONT="]1.[/FONT][FONT="]To create a new Windows Service, pick the Windows Service option from your Visual Studio Projects (choose appropriate language), give your service a name, and click OK. [/FONT]
[FONT="]2.[/FONT][FONT="]A Windows Service project is created with the default project name of WindowsService1 and a class name of Service1. [/FONT]
The next C# code listing includes the code skeleton Visual Studio creates, along with custom code to write information to the Windows Event Log when the associated events are fired. In addition, a constructor, dispose, and the point of execution (i.e., the main method) are included as well:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
namespace WindowsService1 {
public class Service1 : System.ServiceProcess.ServiceBase {
private EventLog log = null;
private System.ComponentModel.Container components = null;
public Service1() {
InitializeComponent();
}
static void Main() {
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
private void InitializeComponent() {
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Dispose();
} }
base.Dispose( disposing );
log.WriteEntry("Service dispose", EventLogEntryType.Information);
log.Close();
}
protected override void OnStart(string[] args) {
log = new EventLog("Builder.com");
log.WriteEntry("Service starting", EventLogEntryType.Information);
}
protected override void OnStop() {
log.WriteEntry("Service stopping.", EventLogEntryType.Information);
} } }
Notice that the code execution entry point (Main method) creates a new instance of the ServiceBase class (an object array) and adds an instance of your class to it. The use of the array demonstrates the ability to run more than one process within the service.
Windows service installation
While console, Windows Form, and ASP.NET applications are easy to install by copying files, you must explicitly install Windows Service applications. Visual Studio .NET simplifies the installation process for Windows server applications. It displays a link in the Properties window of the Windows Service called Add Installer. When you select the link, the IDE adds the necessary installer classes to your project as part of a separate module.
This includes two classes: System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller. Several properties may be set using the Properties window of each class. The most important property is Account within the ServiceProcessInstaller class. It specifies the Windows account under which the service runs (security context). The following options are available:
- [FONT="]LocalService:[/FONT][FONT="] Service has extensive local privileges and presents the computer's credentials to remote servers. [/FONT]
- [FONT="]LocalSystem:[/FONT][FONT="] Service has limited local privileges and presents anonymous credentials to remote servers. [/FONT]
- [FONT="]NetworkService:[/FONT][FONT="] Service has limited local privileges and presents the computer's credentials to remote servers. [/FONT]
- [FONT="]User:[/FONT][FONT="] A local or network account is specified. You may specify the necessary username and password via properties, or you may type them during installation. The Service uses the security context of the specified user account. [/FONT]
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
namespace WindowsService1 {
[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer {
public System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller testInstaller;
private System.ComponentModel.Container components = null;
public ProjectInstaller() {
InitializeComponent();
}
protected override void Dispose( bool disposing ) {
if(disposing) {
if(components != null) {
components.Dispose();
} }
base.Dispose( disposing );
}
#region Component Designer generated code
private void InitializeComponent() {
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.testInstaller = new System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller1.Account =
System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.testInstaller.DisplayName = "Test Installer";
this.testInstaller.ServiceName = "BuilderService";
this.testInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.Installers.AddRange(
new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.testInstaller});
}
#endregion
} }
With the installers added to the project, you may now install the Windows Service and run it on the target computer. Another approach within our project is how the service is started. There are three options:
- [FONT="]Manual:[/FONT][FONT="] The user starts the Service. [/FONT]
- [FONT="]Disabled:[/FONT][FONT="] The Service isn't available for use. [/FONT]
- [FONT="]Automatic:[/FONT][FONT="] The Service starts automatically when the host computer starts. [/FONT]
- [FONT="]/LogFile=[filename] - Contains the log indicating installation success/failure. The default is the AssemblyName.InstallLog. [/FONT]
- [FONT="]/LogToConsole=(true|false) - Signals whether console output is enabled. [/FONT]
- [FONT="]/ShowCallStack - Signals whether call stack is displayed if an exception is encountered. [/FONT]
- [FONT="]/u - Uninstalls the Service. [/FONT]
InstallUtil WindowsService.exe
The line is run in the directory containing the assembly; otherwise, it would require the complete path to the assembly. After you install the new Service, it's located in the Services window of the Computer Management applet.