Kbase

Base de Conhecimento

Creating a Windows Service through Visual Studio.NET

Publicado por agostinhojr em 21 Março, 2007

 

Creating a Windows Service through Visual Studio.NET

Synopsis:

Services run in the Windows operating system as a part of the operating system. These components activate when the operating system boots and keep functioning until the operating system is shut down. This article is a walk through that guides you how to create your own Windows services through Visual Studio.NET.

Note: These concepts do not apply to Windows 9x and Windows Me operating systems.

Defining the Problem:

There are often times when you would have felt the need to create some module or part of your application that would boot up with the operating system and stays functioning until the operating system is not shut down or some type of process that would repeat itself after a specific period of time and etc.

Defining the Solution:

Cases that have been mentioned above require to create serviced components. A serviced component runs as a service in the Windows operating system. If you have worked on Windows NT or Windows 2000 platforms, you would know about many Windows services like Print Spooler Service, Fax Service, Event Log and etc. All these services activate with the operating system and perform different operations related to operating system or the software application along with which they get installed. Although services can automatically start themselves, but you can also change their status by altering their Startup Type property to Manual or Disabled through the Service Control Manager (SCM).

Getting Started

Lets now start with the process of creating a Windows service of our own. In this article I will be creating a Windows service that deletes records from a table after an interval of two minutes. The service will also write entries in a log file of its own.

Open up Visual Studio and select File-New-Project. From the project type window that appears select the Windows Service template. Name the project and select the location where you want this project to be created. In the case of this example, I have named my project as AspaService.

(Figure shows Window Service template selected for creating the new project)

Click the OK button. Visual Studio.NET creates a default template and displays the design view of a page named as Service1.vb, as also shown in the figure below.

(Figure shows default template for the Window Service project created by VS.NET)

In the Properties pane, change the File Name property of the file to DeleteRecords.vb. Changing the file name also changes the name of the file on the designer tab.

Now place a Timer control and an EventLog control from the Toolbox-Components menu on the designer. See the following figure.

(Figure shows the Timer and EventLog components placed on the designer)

After placing the components, double click on the designer window to open up its source file. In the source file expand the Component Designer Generated Code section. Under the Sub New sub procedure write down the following lines of code after the InitializeComponent() method.

If Not EventLog.SourceExists(“MySource”) Then
EventLog.CreateEventSource(“MySource”, “MyNewLog”)
End If

EventLog1.Source = “MySource”
EventLog1.Log = “MyNewLog”

See the following figure for a more clear view.

(Figure shows the code written for creating an event log source)

The code here checks to see if an eventlog source file by name of MySource exists. If it does that file would be assigned to our EventLog object as the source file, otherwise the file would first be created and then be used.

Close the Component Designer Generated Code region by clicking on the (-) sign next to it. This would close the node and the code in it. Notice that there are two sub procedures that are also existing in the source file. These have been shown below in the figure.

(Figure shows the events of the Windows service generated in the default template by VS.NET)

The OnStart() and OnStop() are among two of the events of a Windows service. There are others also like OnContinue and OnPause() etc, but these are the two that are created for us in the default template. The OnStart() event occurs when the service starts and the OnStop() event occurs when the serviced component is stopped. Before writing code into these events first of all include the following namespace at the top of your source file.

                     

Imports System.Data.SqlClient

 
       

Since the service would be used to delete records from a table after a specific period of time therefore this namespace is required to declare the objects that would be used for connecting and executing the SQL statements on the database server.

After this declare a variable of date data type in the class and initialize it with the current date and time. See the following figure.

(Figure shows the declaring and the initializing of a Date data type variable)

As shown in the figure a variable named _PreviousTime of data type Date is declared and is initialized with the current date and time of the system, which is assigned to it through the Now() function.

Now from the designer view, double click on the timer control and write the code within its Elapsed event as shown in the figure below.

(Figure shows the code for the Elapsed event of the Timer Control)

This event is fired by the timer after every millisecond (the default behavior which can be changed). On being fired, it compares the current minute of the system time by subtracting two from it with the minute of the time stored in the _PreviousTime variable. On having a match it would call the custom defined procedure DeleteRecords(), that would actually delete the records from the table in the database server. The code for DeleteRecords() is as shown below in the figure.

(Figure shows code for the custom sub procedure DeleteRecords( ))

The code in the procedure is simple. It creates a connection object that is being used to connect to the Pubs database on the local system server. A command object is also created that is provided the connection object and the query parameters in the constructor. The temp is a table that you will have to create yourself as it is not provided in the Pubs database by default.

Within the Try block the command object is executed and incase of a successful execution the entry is listed into the log file that was created earlier in this project. The Try and Catch section is to handle any types of errors that may arise and incase if an error is encountered it would be written into the same eventlog file that was created earlier.

Having done this, add some lines of code to the OnStart() and OnStop() events of the service also. See the following figure.

(Figure Shows the code to be written in the OnStart and OnStop events)

When the service starts it will make an entry into the log file stating “In OnStart” and after that it would start the timer. Similarly, when the service is stopped, an entry is made in the log file and the timer is stopped.

This completes the coding required to create the service. But the service cannot be just tested by clicking F5. For testing a service it is required to be installed first.

Creating an Installer for the service

Return to the designer view and click on the background of the designer to select it.

Once selected change the Name and ServiceName properties to AspaService.

Right click on the designer and select the Add Installer option. Visual Studio will create a new component class named as ProjectInstaller. The design view of the class will show two installers on the designer. The ServiceInstaller1 is to install your service and the other ServiceProcessInstaller1 is to install the process associated with the service. See the following figure.

(Figure shows the design view for the Project Installer having two installer placed by default)

Click on ServiceInstaller1, set the Name property to AspaService and StartType property to Automatic.

Now click on ServiceProcessInstaller1 to select it. Set the Account property to LocalSystem. Incase if you leave it as User, you would be required to provide a username and a password during installation. The other two options for the property i.e. LocalService and NetworkService are only applicable on WindowsXP.

Creating a Setup Project

For creating a setup project, select File-New-Project.

From the New Project window, select Setup and Deployment Projects from Project Types and select Setup Project from the Templates pane.

Name the project as Aspa Service Setup and select the Add to Solution radio button option. See the figure below for a demonstration.

(Figure shows settings for the new Setup Project)

Click OK. Visual studio will create a default template for you.

In the solution explorer right click on the Aspa Service Setup, point to Add, then choose Project Output. The Add Project Output Group dialog appears.

Make sure that AspaService is selected in the Project box. From the list box below the Project box, select Primary Output. This has been displayed in the figure below.

(Figure shows settings for Add Project Output Group)

Click OK. A project item for the primary output of AspaService is added to the setup project. Now add a custom action to install the AspaService.exe file.

Adding 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 AspaService(Active), and click OK. The primary output is added to all four nodes of the custom actions — Install, Commit, Rollback, and Uninstall.

Now Build the Setup Project.

Installing the Service

Browse to where the setup project has been saved and double click the .msi file. Install the service and then view it through the SCM. The SCM can be opened from Start-Programs-Administrative Tools-Services menu. In the SCM the service will appear by the name of AspaService or any other name that you have given to the service.

The Service in action

Click on the service to select it. Then right click and select the Start option. This would start your service and it would also write down an entry into the log file. To view the log file open the Event Viewer from the Administrative Tools menu. Within the Event Viewer click on MyNewLog in the left pane and then from the right pane double click on the first event entry. See the description section and it will show In OnStart, which is what you specified in the OnStart event of your service.

Create a table in the pubs database by name of temp and fill it with some records. After an interval of two minutes review the table and you would see that all of the records from the table have been deleted. Another entry for the successful deletion of the records will also be listed in the log and you can view that from the Event Viewer as well.

Uninstalling the Service

To uninstall the service simply rerun the .msi file. Select the Remove option from the wizard window and the service will be uninstalled automatically.

Categories:

Deixe uma resposta

XHTML: Você pode usar estas tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>