Windows services are programs that generally run in the background and follow the interface of the Windows Service Control Manager (SCM). In this chapter, I discussed the architecture of Windows services and how the SCM manages the Windows services and the Windows service database (which is stored in the Windows registry).
Traditionally, it was considered difficult to create Windows services, but with the .NET Framework, creating a Windows service is just like creating any other application. Credit for this simplicity goes to the improved programming model and the functionality of the ServiceBase class. This class acts as the base class for all the Windows services.
I also discussed how to add installation classes (the ServiceProcessInstaller and the ServiceInstaller classes) to a Windows service project so that the Windows service can be installed using the installation tools such as installutil.exe .
You also learned about various tools for controlling and managing Windows services, such as the Services MMC snap-in, Visual Studio .NET Server Explorer, the NET utility (net.exe), and the Service Control utility (sc.exe).
Finally, I discussed how you could programmatically control a Windows service. I explained and used various members of the ServiceController class to accomplish this.
When you start a Windows service, you can also pass startup parameters to the service.
In this exercise, I'll create a new Windows service named OrderServiceEx . This Windows service is almost the same as OrderService that was created in Step By Step 6.1. The only difference is that OrderServiceEx accepts the value of the NotifyFilter property and the Path property of the FileSystemWatcher component at startup time.
The startup parameters to a Windows service are given just as the command-line arguments are provided to a Console application. The major difference is that rather than accepting the arguments in the Main() method, the Windows services accept arguments in the OnStart() method. This is because the Main() method here can be common to several Windows services in an application. However, each of these services has its own individual OnStart() method.
Estimated Time : 30 minutes.
Launch Visual Studio .NET. Select File, New, Blank Solution, and name the new solution 310C06Exercises . Click OK.
Add a new Visual Basic Windows Service project named Exercise6-1 to the solution.
The Windows service project contains a file named Service1.vb . Rename this file to OrderServiceEx.vb . Click on the designer surface. Then, in the Properties windows, set the Name and ServiceName properties to OrderServiceEx and set the CanPauseAndContinue property to True .
Switch to the code view and change all occurrences of Service1 to OrderServiceEx . Add the following statements to the code:
Imports System.Data.SqlClient Imports System.IO
Add a FileSystemWatcher component onto the surface of the OrderServiceEx component. Access the Properties window for the FileSystemWatcher component; change its Name property to fswOrders and EnableRaisingEvents property to False .
Add the following event handler:
Private Sub fswOrders_Created(_ ByVal sender As Object, _ ByVal e As _ System.IO.FileSystemEventArgs) _ Handles fswOrders.Created Dim dsOrders As DataSet = _ New DataSet("Orders") ' Read the contents of the XML file ' into the Orders DataSet dsOrders.ReadXml(e.FullPath) ' Set up the database connection string Dim strConn As String = _ "data source=(local);" & _ "initial catalog=Northwind;" & _ "integrated security=SSPI" Dim strOrderQuery As String = _ "SELECT * FROM Orders" ' Create a DataAdapter for the Orders ' table of the Northwind database Dim daOrders As SqlDataAdapter = _ New SqlDataAdapter(strOrderQuery, _ strConn) ' Automatically generate the update ' command to reconcile the changes ' made to the DataSet Dim cbOrders As SqlCommandBuilder = _ New SqlCommandBuilder(daOrders) ' Update the DataSet daOrders.Update(dsOrders, "Orders") daOrders.Dispose() Dim fi As FileInfo = _ New FileInfo(e.FullPath) ' Create a subdirectory named "Updated" ' if it does not already exists fi.Directory.CreateSubdirectory(_ "Updated") ' Copy the processed file to updated ' directory, overwriting if needed File.Copy(e.FullPath, _ fi.DirectoryName & _ "\Updated\" & fi.Name, True) ' Delete the XML file from its 'original location fi.Delete() End Sub
In the code, search for the skeletons of the OnStart() and OnStop() methods and modify them as shown here:
Protected Overrides Sub OnStart(_ ByVal args() As String) fswOrders.Filter = args(0) fswOrders.Path = args(1) fswOrders.EnableRaisingEvents = True End Sub Protected Overrides Sub OnStop() fswOrders.EnableRaisingEvents = False End Sub
Add the following code to the OrderService class to override the OnPause() and the OnContinue() methods of the base class:
Protected Overrides Sub OnPause() fswOrders.EnableRaisingEvents = False End Sub Protected Overrides Sub OnContinue() fswOrders.EnableRaisingEvents = True End Sub
Access the Properties window for the OrderServiceEx component and click on the Add Installer hyperlink.
Access the properties for the ServiceProcessInstaller1 component and change its Account property from User to LocalSystem .
Access the properties for the ServiceInstaller1 component and change the DisplayName property to OrderServiceEx and the StartType property to Automatic .
Set OrderServiceEx as the startup object for the project.
Build the project Exercise6-1 . Open the Visual Studio .NET Command Prompt, switch to the bin directory of the project and type the following command:
Open the Services MMC snap-in. Open the property window for OrderServiceEx. In the Start parameters text box, type the following (as shown in Figure 6.14) and click on the Start button:
Create an XML file in the c:\OrderEx folder. You may use the same XML file that you used in Step By Step 6.4. You'll note that the record has been updated to the Orders table in the Northwind database.
What is a Windows service?
A Windows service is a long-running process that usually runs in the background without any user interaction. A Windows service must conform to the interface provided by the Windows Service Control Manager.
What is the Service Control Manager (SCM), and what does it do?
The Service Control Manager (SCM) is a part of the operating system that manages Windows services. SCM also manages the Windows service database (which is stored in the Windows Registry) and provides a mechanism through which other programs can interact with the Windows service database and the Windows service in execution.
How can you control and monitor a Windows service?
You can control and monitor a Windows service in several ways. The easiest way is to use the tools that come installed with Windows such as the NET utility ( net.exe ), Service Control utility ( sc.exe ), and the Services MMC snap-in. You can also control Windows services through the Server Explorer windows of Visual Studio .NET. Sometimes you might need to control the Windows service programmatically; in that case, you can use the methods and properties of the ServiceController class.
What is the significance of the Run() method of the ServiceBase class?
The Run() method is usually called from the Main() method of a Windows service executable file. The Run() method loads the Windows service in memory and passes it a reference to the SCM. This enables SCM to pass control messages to a Windows service.
How can you programmatically enumerate the Windows services installed on a computer?
You can get a list of Windows services installed on a computer by calling the static ServiceController.GetServices() method. This method returns an array of ServiceController objects, each associated with a Windows service.
How do you write to an event log from a Windows service application?
To write entries in the Application event log from a Windows service application, you just need to use the EventLog.WriteEntry() method. However, if you need to write entries to any other event log, you should create a new EventLog object in your application.
How can you receive startup parameters in a Windows service?
Any startup parameters provided to a Windows service are passed to the OnStart() method call as array strings. You can process this array to retrieve the startup parameters in the OnStart() method.
What is the difference between the ServiceProcessInstaller and the ServiceInstaller classes?
The ServiceProcessInstaller class performs the installation tasks that are common to all Windows services in an application. These include setting the logon account for the Windows service. The ServiceInstaller class, on the other hand, performs the installation tasks that are specific to a Windows service such as setting the ServiceName and StartType .
You are required to design an application that monitors incoming emails and analyzes them to filter out junk emails. The emails arrive at a well-known port, and you use conditions stored in an XML file to determine whether an email is possibly a junk email. Your application will bounce back all junk email while it will forward the other emails to a groupware application. You want this application to run continuously with minimal interaction with the desktop user. How should you design this application?
B. The application in question runs continuously and requires minimal user interaction. The application also just listens to email and is not required to listen to Web-based requests . Given these characteristics, you should design this application as a Windows service instead of the application type specified in other options. For more information, see the section "Understanding Windows Services" in this chapter.
You are designing a Windows service application that will be used by other applications over the Internet. You want the users of the application to have access to only certain directories on your system. Which of the following techniques should you use?
A. You can only specify the security settings for a Windows service at the time of installation. When you want to run the Windows service with a specific username and password, the Account property must be set to User.
You are working on a team that is designing a Windows service that monitors the Web server performance on an ongoing basis. You are given a task to make sure that an entry is written to the Application event log when the Windows service is started, paused , resumed, or stopped . You want to write a minimum amount of code to achieve this. Which of the following options would you choose?
B. When you set the AutoLog property to true, the Windows service class automatically writes events to the Application event log. All other options require more code to be written in order to achieve the same results.
You are developing a Windows service application that accepts startup parameters. Which of the following methods would you program to retrieve and process these parameters?
C. When a Windows service is started, any startup parameters are passed to the OnStart() method.
You are part of a team that is developing a Windows service application to monitor a legacy application for new data. Occasionally your application might encounter errors. You want to develop an error reporting mechanism that is easy to use for administrators who will monitor and maintain the application on day-to-day basis. You also want a scheme that is robust and requires a minimal amount of code. Which of the following techniques should you choose?
A. You should use an event log for error reporting from a Windows service. Event logs are easy to use for administrators because they already use event logs for monitoring notifications from other applications. The service base class provides an EventLog property that allows you to write messages to the Application event log using a single line of code.
You have designed a Windows service application that contains two Windows services. You now want to add installer classes to this application so that the application can be installed with tools such as installutil.exe. You have added a new class inherited from the Installers class in your application. To the Installers collection of this class, you would like to add the custom installation components for properly installing the Windows services in your application. Which of the following custom components combinations would you like to add to the Installers collection of the Installer class?
B. For installing a Windows service application, you need to have one instance of the ServiceProcessInstaller class and as many instances of the ServiceInstaller class as the number of services you want to install.
You are required to design a Windows service that cannot be paused. Which of the following options will help you to accomplish this requirement?
B. If you do not want a Windows service to be paused, you need to set the CanPauseAndContinue property of the Web service to false . If this property is true , SCM might send pause and continue messages to your service. The CanStop property and the OnStop() method won't help because stopping a Windows service is different from pausing a Windows service. In case of stopping, the Windows service is unloaded from memory and all its resources are reclaimed.
Your application is required to monitor changes to files in the c:\Documents directory. You are especially interested in taking actions when there are any changes to the PDF files in this directory. You are using a FileSystemWatcher component to accomplish this task. How should you set the Filter and NotifyFilter properties of this component? (Select two.)
A and B. For a FileSystemWatcher component, the Filter property specifies what files are to be monitored , whereas NotifyFilter specifies the type of changes to watch for.
You have recently designed a Windows service application. You now want to install the application in order to test its functionality. Which of the following options should you choose to install this application?
D. Although the Server Explorer Window, Services MMC snap-in, and the .NET utility allow you to control and monitor a Windows service, they do not allow you to install one. To install a Windows service, either you should use installutil.exe or you should create a Windows installer-based setup project.
You are designing an application that needs to know the Windows services that are installed on a computer. Which of the following classes would allow you retrieve this information?
C. The ServiceController class interacts with SCM to enumerate the list of services installed on a computer. You get this information using the static GetServices() method of this class.
Your group is designing a Windows service application that constantly monitors the computer to keep it tuned . This service performs tasks such as disk defragmentation, Registry cleanup, and virus detection. The service needs to have high privilege in order to perform its task. In what security context should you set up this service to run?
B. The LocalSystem value defines a highly privileged account. As compared to this, the LocalService and NetworkService values provide a lower privilege level for the security context. Privileges for User depend on the specified username and password.
Which of the following options correctly identifies the security context in which a Windows service is executed?
D. Most Windows services are started before a user logs on, and they keep on running across multiple user sessions. Therefore, the functionality of a Windows service cannot depend on the permissions available to the currently logged on user. A Windows service always executes using an assigned user identity that is specified at the time of Windows service installation.
You are designing a Windows service application, and you want to set the service to start automatically when the computer is restarted. Which of the following classes would allow you retrieve this information?
B. The StartType property of the ServiceInstaller class is used to specify whether a service will be started manually, will be started automatically when computer starts, or will not start at all.
Your colleague has designed a Windows service application by inheriting a class from the ServiceBase class. She is complaining that she is able to compile the program successfully, but when she tries to run the program, she is getting an error. What should you suggest to resolve this problem? (Select two answers.)
A and C. The Windows service must be installed in the Windows Registry before it can be started. Although the service is installed in Windows Registry, it is not a good idea to directly manipulate the registry. You should instead use installation tools, such as installutil.exe , that interact with SCM to install a Windows service in the Windows Registry. After the service is installed successfully, you should instruct your colleague to start the Windows service using the Service MMC snap-in because if the start type of the service is not set up as automatic, the service will not start automatically when the computer restarts.
Your colleagues are testing a Windows service application. They are arguing over in what order the following constructs are called when a Windows service is started.
Which of the following orders should you suggest to them?
A. The Main() method of the application is always the first to execute. The Main() method executes the Run() method of the ServiceBase class, which passes the reference of the Windows service to the SCM. The SCM then invokes the OnStart() method of the Windows service.
1. Visual Studio .NET Combined Help Collection
Windows Service Applications
Service Application Programming Architecture
Monitoring Windows Services
Walkthrough: Creating a Windows Service Application in the Component Designer