A nice article on Windows Services

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):
  • [FONT=&quot]OnContinue:[/FONT][FONT=&quot] 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=&quot]OnPause:[/FONT][FONT=&quot] Fires when a pause command is sent to the service by the SCM. It specifies actions to take when a service pauses. [/FONT]
  • [FONT=&quot]OnPowerEvent:[/FONT][FONT=&quot] 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=&quot]OnShutdown:[/FONT][FONT=&quot] Fires when the system is shutting down. It specifies what should happen immediately prior to the system shutting down. [/FONT]
  • [FONT=&quot]OnStart:[/FONT][FONT=&quot] 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=&quot]OnStop:[/FONT][FONT=&quot] Fires when a stop command is sent to the service by the SCM. It specifies actions to take when a service stops running. [/FONT]
Only the OnStart event accepts any type of parameter. The main starting point of a Windows Service execution is the Main method, which accepts no parameters.

Creating a Windows Service
Visual Studio .NET makes it simple to create a service using the code of choice:
[FONT=&quot]1.[/FONT][FONT=&quot]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=&quot]2.[/FONT][FONT=&quot]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=&quot]LocalService:[/FONT][FONT=&quot] Service has extensive local privileges and presents the computer's credentials to remote servers. [/FONT]
  • [FONT=&quot]LocalSystem:[/FONT][FONT=&quot] Service has limited local privileges and presents anonymous credentials to remote servers. [/FONT]
  • [FONT=&quot]NetworkService:[/FONT][FONT=&quot] Service has limited local privileges and presents the computer's credentials to remote servers. [/FONT]
  • [FONT=&quot]User:[/FONT][FONT=&quot] 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]
When an installer is added to the Service, the ProjectInstaller class is added. Defining properties via each class's Properties window results in an associated line of code in the corresponding ProjectInstaller class. The following code shows a sample installer for our C#-based Windows service with various properties defined, including the Account set to LocalService and ServiceName set to BuilderService.
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=&quot]Manual:[/FONT][FONT=&quot] The user starts the Service. [/FONT]
  • [FONT=&quot]Disabled:[/FONT][FONT=&quot] The Service isn't available for use. [/FONT]
  • [FONT=&quot]Automatic:[/FONT][FONT=&quot] The Service starts automatically when the host computer starts. [/FONT]
In our example, I have the Service start automatically. With the Service properly compiled, we install it on the target computer via the Microsoft .NET Framework Installation utility (InstallUtil.exe) command-line tool. It allows you to easily install and uninstall our service. The compiled file (executable) or assembly is passed to it. Also, it provides the following command-line switches:
  • [FONT=&quot]/LogFile=[filename] - Contains the log indicating installation success/failure. The default is the AssemblyName.InstallLog. [/FONT]
  • [FONT=&quot]/LogToConsole=(true|false) - Signals whether console output is enabled. [/FONT]
  • [FONT=&quot]/ShowCallStack - Signals whether call stack is displayed if an exception is encountered. [/FONT]
  • [FONT=&quot]/u - Uninstalls the Service. [/FONT]
With our sample Service, the following line takes care of the installation:
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.
 

sunils

New Member
Messages
2,266
Reaction score
0
Points
0
thanks for the tutorial. But do you know how to program COM using Dot.NET.

I was banging my head and searching the net for this.
 

sumitmehta

New Member
Messages
215
Reaction score
1
Points
0
For this, you have to use Com Interopability. If you are making a dll in C# for other apps to use, there is an option in the properties 'Make assembly COM-visible'. Right-click your project name in Project Explorer and goto Properties. Under Application, click Assembly Information. You will get this option there. For external objects to be used in C#, there are a few restrictions. But I can give you an example of using an object developed in VC++ in C#.

For C++ file, below is the code:

// testDLL.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"

BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}

extern "C" _declspec(dllexport) int _cdecl myAge();

extern "C" _declspec(dllexport) int _cdecl myAge() {

return 21;
}


This function returns value 21. (Of course this is a very simple function for demonstration)

Now compile it as a DLL.

Now use it in C# as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
[System.Runtime.InteropServices.DllImport("D:\\testDLL\\Debug\\testDLL.dll")]
static extern int myAge();
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int a;
a = myAge();
MessageBox.Show(a.ToString());
}
}
}

I hope the above helps. Similarly, For win32 calls, use the following syntax:

[DllImport("winmm.dll", EntryPoint="PlaySoundA")]
private static extern int PlaySound (string lpszName, int hModule, int dwFlags);

I also mentioned win32 calls because they are also very important part of windows programming.
 

sunils

New Member
Messages
2,266
Reaction score
0
Points
0
ok thanks for the info. but i read a book, which says develop the com and use the component services in the control panel and create an application there and so and so. couldn't understand that. If you can post about it, it may be much helpful.
 

Senjai

New Member
Messages
26
Reaction score
0
Points
0
THIS IS A GREAT TUTORIAL, ive been looking everywere for this kind of thing in C# xD thanks alot
 
Top