Source Link:
http://www.codeproject.com/KB/cs/SimpleService.aspx
http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
Simple Windows Service Sample
By Mahmoud Nasr
Introduction
As a matter of fact Microsoft Windows services, formerly known as NT services enable you to create long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.
This makes 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.
Windows services don�t have any interface to the user, so it can not be debugged like any regular application, but it�s debugged as a process. .NET has a very nice tool that enables processes debugging while it�s in the run status, by easily pressing Ctrl + Alt + P shortcut.
Background
I�ve searched well so many sites about a code that I can with the help of it, build a simple Windows service, but I found a lot of code on how to manage the current Windows services of the system and that�s through the ServiceController
class.
After searching the MSDN, I�ve found some nice code that helped me to create this simple Windows service. Hope it can help as a basic architecture for and usage of such a Windows service.
Using the code
At first you should simply open VS.NET and then at the File menu click on New, Project. From the New Project Dialog Box, choose the Windows service template project and name it MyNewService like shown below:
The project template automatically adds a component class that is called Service1
by default and inherits from System.ServiceProcess.ServiceBase
.
Click the designer. Then, in the Properties window, set the ServiceName
property for Service1
to MyNewService
.
Set the Name
property to MyNewService
. Set the AutoLog
property to true
.
In the code editor, edit the Main
method to create an instance of MyNewService
. When you renamed the service in step 3, the class name was not modified in the Main
method. To access the Main
method in VC#, expand the Component Designer generated code region.
![](https://i-blog.csdnimg.cn/blog_migrate/74fd2798202fde65c452efa4582b9818.gif)
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
//Change the following line to match.
ServicesToRun = new
System.ServiceProcess.ServiceBase[] { new MyNewService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
In the next section, you will add a custom event log to your Windows service. Event logs are not associated in any way with Windows services. Here the EventLog
component is used as an example of the type of components you could add to a Windows service.
To add custom event log functionality to your service:
- In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.
- From the Components tab of the Toolbox, drag an
EventLog
component to the designer. - In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Code.
- Edit the constructor to define a custom event log.
To access the constructor in Visual C#, expand the Component Designer generated code region.
![](https://i-blog.csdnimg.cn/blog_migrate/74fd2798202fde65c452efa4582b9818.gif)
public MyNewService()
{
InitializeComponent()
if(!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse"))
System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse",
"DoDyLog");
eventLog1.Source = "DoDyLogSourse";
// the event log source by which
//the application is registered on the computer
eventLog1.Log = "DoDyLog";
}
To define what happens when the service starts, in the code editor, locate the OnStart
method that was automatically overridden when you created the project, and write code to determine what occurs when the service begins running:
![](https://i-blog.csdnimg.cn/blog_migrate/74fd2798202fde65c452efa4582b9818.gif)
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("my service started");
}
The OnStart
method must return to the operating system once the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer
component. In the OnStart
method, you would set parameters on the component, and then you would set the Timer.Enabled
property to true
. The timer would then raise events in your code periodically, at which time your service could do its monitoring.
To define what happens when the service is stopped, in the code editor, locate the OnStop
procedure that was automatically overridden when you created the project, and write code to determine what occurs when the service is stopped:
![](https://i-blog.csdnimg.cn/blog_migrate/74fd2798202fde65c452efa4582b9818.gif)
protected override void OnStop()
{
eventLog1.WriteEntry("my service stoped");
}
You can also override the OnPause
, OnContinue
, and OnShutdown
methods to define further processing for your component. For the method you want to handle, override the appropriate method and define what you want to occur. The following code shows what it looks like if you override the OnContinue
method:
![](https://i-blog.csdnimg.cn/blog_migrate/74fd2798202fde65c452efa4582b9818.gif)
protected override void OnContinue()
{
eventLog1.WriteEntry("my service is continuing in working");
}
Some custom actions need to occur when installing a Windows service, which can be done by the Installer
class. Visual Studio can create these installers specifically for a Windows service and add them to your project. To create the installers for your service.
- Return to design view for
Service1
. - Click the background of the designer to select the service itself, rather than any of its contents.
- In the Properties window, click the Add Installer link in the gray area beneath the list of properties. By default, a component class containing two installers is added to your project. The component is named
ProjectInstaller
, and the installers it contains are the installer for your service and the installer for the service's associated process. - Access design view for
ProjectInstaller
, and clickServiceInstaller1
. - In the Properties window, set the
ServiceName
property toMyNewService
. - Set the
StartType
property toAutomatic
.
Tip
To avoid being asked about the system username and password you must change the Account
for the serviceProcessInstaller
to LocalSystem
. This is done by opening the ProjectInstaller
design and then selecting the serviceProcessInstaller
, press F4 and then change the Account
property to LocalSystem
. Or you can manually do that by creating a class that inherits from System.Configuration.Install.Installer
like this:
![](https://i-blog.csdnimg.cn/blog_migrate/74fd2798202fde65c452efa4582b9818.gif)
[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer
private System.ServiceProcess.ServiceProcessInstaller
serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
/// <summary>
/// Required designer variable.
/// </summary> private System.ComponentModel.Container components = null;
public ProjectInstaller()
// This call is required by the Designer.
InitializeComponent();
// TODO: Add any initialization after the InitComponent call
}
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 = "MyNewService";
this.serviceInstaller1.StartType =
System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange
(new System.Configuration.Install.Installer[]
{
this.serviceInstaller1,
this.serviceInstaller1});
}
}
To build your service project
- In Solution Explorer, right-click your project and select Properties from the shortcut menu. The project's Property Pages dialog box appears.
- In the left pane, select the General tab in the Common Properties folder.
- From the
Startup object
list, chooseMyNewService
. Click OK. - Press Ctrl+Shift+B to build the project.
Now that the project is built, it can be deployed. A setup project will install the compiled project files and run the installers needed to run the Windows service. To create a complete setup project, you will need to add the project output, MyNewService.exe, to the setup project and then add a custom action to have MyNewService.exe installed.
To create a setup project for your service
- On the File menu, point to Add Project, and then choose New Project.
- In the Project Types pane, select the Setup and Deployment Projects folder.
- In the Templates pane, select Setup Project. Name the project
MyServiceSetup
.
A setup project is added to the solution. Next you will add the output from the Windows service project, MyNewService.exe, to the setup.
To add MyNewService.exe to the setup project
- In Solution Explorer, right-click
MyServiceSetup
, point to Add, then choose Project Output. The Add Project Output Group dialog box appears. -
MyNewService
is selected in the Project box. - From the list box, select Primary Output, and click OK.
A project item for the primary output of
MyNewService
is added to the setup project. Now add a custom action to install the MyNewService.exe file.
To add a custom action to the setup project
- In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions. The Custom Actions editor appears.
- In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action. The Select Item in Project dialog box appears.
- Double-click the application folder in the list box to open it, select primary output from
MyNewService
(Active), and click OK. The primary output is added to all four nodes of the custom actions � Install, Commit, Rollback, and Uninstall. - Build the setup project.
To install the Windows Service
Browse to the directory where the setup project was saved, and run the .msi file to install MyNewService.exe.
To start and stop your service
- Open the Services Control Manager by doing one of the following:
- In Windows 2000 Professional, right-click My Computer on the desktop, then click Manage. In the Computer Management console, expand the Services and Applications node.
-Or-
- In Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.
Note:In Windows NT version 4.0, you can open this dialog box from Control Panel.
- In Windows 2000 Professional, right-click My Computer on the desktop, then click Manage. In the Computer Management console, expand the Services and Applications node.
- You should now see
MyNewService
listed in the Services section of the window. - Select your service in the list, right-click it, and then click Start.
Right-click the service, and then click Stop.
To verify the event log output of your service
- Open Server Explorer and access the Event Logs node. For more information, see Working with Event Logs in Server Explorer.
Note:The Servers node of Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET.
To uninstall your service
- On the Start menu, open Control Panel and click Add/Remove Programs, and then locate your service and click Uninstall.
- You can also uninstall the program by right-clicking the program icon for the .msi file and selecting Uninstall.
License
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
About the Author
Mahmoud Nasr![]() Member | i've been with .net for about 5 years since the beta 1.0 ver. along with ASP.net and windows services.. am experienced in Java, C, C++, Prolog, Assembly, ASP, VB, VB.net, C# and ASP.net am very fond of Web Development and Graphics Libraries Programming like Open GL,CSGL and SDGL worked in Microsoft Egypt Co., Delta Software and now am working in Al-Alamiah Sakhr Co., Riyadh, saudi arabia. +966-508969725
|
How to Write Windows Service and Control It By Application
By Laker
Introduction
This article presents the guide to write a Windows service program and control it from another program.
Background
Many projects which I was part of needed the program running as a Windows service. It can auto startup when Windows Restarts and access Domain resource when it runs under special user. But sometimes, Windows service program is not easy to control and config, for example: I need the Windows service running once a day, but maybe I change my idea, need it to run every three hours, so how I config it or make the Windows service more flexible is a puzzle.
Solution
- Make Windows service run as it is, making some small modifications to other programs can control it.
- Write a small application to control the Windows service.
- Use a Windows Scheduler to run the application, config run time as you wish.
Steps
-
Write a Windows service program (Here, we start to program step by step):
- Step 1. File -> Project -> Windows C# -> Windows -> Console Application
- Step 2. Add References to this project:
System.Configuration.Install
System.ServiceProcess
- Step 3. Add a new class: SimpleServiceMain.cs (you can rename Program.cs to it, or delete Program.cs, then add a new one).
Collapse
public class SimpleServiceMain : ServiceBase
{
....
protected override void OnCustomCommand(int command)
{
// You can add the process which controlled by external program
OutputDebugString("[SimpleService]" +
"SimpleService OnCustomerCommand
(" + command.ToString() + ")");
base.OnCustomCommand(command);
}
....
} - Step 4. Add a new class: SimpleServiceInstall.cs:
Collapse
[RunInstaller(true)]
public class SimpleServiceInstall : Installer
{
public SimpleServiceInstall()
{
ServiceProcessInstaller serviceProcessInstaller =
new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Password = null;
//# Service Information
serviceInstaller.DisplayName = "SimpleService";
serviceInstaller.Description = "SimpleService";
serviceInstaller.StartType = ServiceStartMode.Automatic;
// This must be identical to the
// WindowsService.ServiceBase name
// set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = "SimpleService";
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
}
} - Step 5. Install the Windows service. Here is a batch script to install/uninstall the service:
Collapse
Install.bat
==============================================================
ECHO OFF
REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%
echo Installing WindowsService...
echo ---------------------------------------------------
InstallUtil /i SimpleService.exe
sc start SimpleService
echo ---------------------------------------------------
echo Done
pause
==============================================================
Unstall.bat
==============================================================
@ECHO OFF
REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%
sc stop SimpleService
echo Installing WindowsService...
echo ---------------------------------------------------
InstallUtil /u SimpleService.exe
echo ---------------------------------------------------
echo Done
pause
==============================================================
-
Write a Windows application to control a Windows service.
Please make sure that when the application runs, the service has been installed to the system.
- Step 1. File -> Project -> Windows C# -> Console Application
- Step 2. Add Reference to this project.
System.Configuration.Install
System.ServiceProcess
- Step 3. Add these codes in Program.cs:
Collapse
...
static void Main(string[] args)
{
string aMachine = "." ;
string aServiceName = "";
if( args.Length == 1 ){
aServiceName = args[0];
}
else if (args.Length >= 2)
{
aMachine = args[0];
aServiceName = args[1];
}
else
{
Console.WriteLine("Error Parameters,
the command line should be: ");
Console.WriteLine("SimpleServiceController ServiceName or");
Console.WriteLine
("SimpleServiceController Machine Name ServiceName");
}
System.ServiceProcess.ServiceController sc =
new System.ServiceProcess.ServiceController();
sc.MachineName = aMachine;
sc.ServiceName = aServiceName;
sc.ExecuteCommand(130);
}
... -
How to use Windows Scheduler to control how your program runs. Please read Windows help for more information.
-
You can use Windows Batch (*.bat) to control multi services by
SimpleServiceController
. -
About
OutputDebugString
, you can get the tools to view the information: See DebugView for Windows.
History
- 17th March, 2008: Initial post
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
About the Author
Laker![]() Member | More than 10 years programme experience on C, C++, C#, Delphi.
|