Create a Windows service with .NET

xiaoxiao2021-03-20  244

We will study how to create an application as a Windows service. The content contains what is Windows service, how to create, install, and debug them. Will use the class of System.ServiceProcess.serviceBase namespace.

What is Windows service?

The Windows service application is an application that requires long-term running, which is particularly suitable for the server environment. It does not have a user interface, and no visual output is generated. Any user message will be written into the Windows event log. When the computer is started, the service will automatically start running. They don't want users to log in to run, they can run in any user environment including this system. By service control manager, Windows service is controllable, terminating, pause, and when needed.

Windows services, previous NT services are brought to by part of the Windows NT operating system. They are not available under Windows 9X and Windows Me. You need to use the NT level operating system to run Windows services, such as Windows NT, Windows 2000 Professional, or Windows 2000 Server. For example, the products in Windows services include: Microsoft Exchange, SQL Server, and other Windows Time services for computer clocks.

Create a Windows service

This service we will create is not done in addition to the demonstration. When the service is started, an entry message is registered into a database to indicate that this service has been launched. During the service run, it will create a database item record periodically within the specified time interval. The last database record is created when the service is stopped. This service will automatically register with the Windows application log, which is successfully started or stopped.

Visual Studio .NET enables the creation of a Windows service to become a fairly simple matter. The instructions for launching our demo service procedures are summarized below.

1. New project

2. Select Windows service from a list of available project templates

3. Designer will open in design mode

4. Drag a Timer object from the component table of the toolbox to this design surface (Note: Be sure to use Timer from the list of components instead of the Windows Forms)

5. Set the Timer property, the enabled property is false, the interval property is 30000 milliseconds

6. Switch to the code view page (press F7 or select the code in the View menu), then fill in this service

Composition of Windows services

In the code included in your class, you will notice that the Windows service you created will expand the System.ServiceProcess.Service class. All Windows services established in .NET methods must expand this class. It requires your service to overload the following methods, and Visual Studio includes these methods by default.

• Dispose - Clear any controlled and unmnaged resources (Managed and Unmanaged Resources)

• OnStart - Control Service Launched

• OnStop - Control Service Stop

Database table script sample

The database table used in this example is created using the following T-SQL script. I chose the SQL Server database. You can easily modify this example allows it to run under Access or any other database you choose.

Create Table [DBO]. [MyServiceLog] (

[IN_LOGID] [INT] Identity (1, 1) Not NULL,

[vc_status] [nvarchar] (40)

Collate SQL_LATIN1_GENERAL_CP1_CI_AS NOT NULL,

[dt_created] [datetime] not null

) On [primary]

Windows service sample

Here is all source code for the Windows service I named myService. Most source code is automatically generated by Visual Studio. Using system;

Using system.collections;

Using system.componentmodel;

Using system.data;

Using system.data.sqlclient;

Using system.diagnostics;

Using system.serviceProcess;

Namespace CodeGuru.mywindowsService

{

Public class myService: system.serviceProcess.serviceBase

{

Private system.timers.timer Timer1;

///

/// Required Designer Variable.

///

Private system.componentmodel.Container Components = NULL;

Public myService ()

{

// this call is required by the windows.forms

// Component Designer.

InitializationComponent ();

}

// the main entry point for the process

Static void main ()

{

System.ServiceProcess.serviceBase [] ServicesTorun;

ServiceStorun = new system.serviceProcess.serviceBase []

{New myservice ()};

System.ServiceProcess.serviceBase.Run (ServiceStorun);

}

///

/// Required Method for Designer Support - Do Not Modify

/// The contents of this method with the code editor.

///

Private vidinitiRizeComponent ()

{

This.Timer1 = new system.timers.timer ();

(System.comPonentModel.isupportInitialize)

(this.timer1))).

//

// Timer1

//

this.timer1.interval = 30000;

this.timer1.elapsed =

New system.timers.eLapseDeventhandler (this.timer1_elapsed);

//

// myService

//

This.ServiceName = "My Sample Service";

(System.comPonentModel.isupportInitialize)

(this.timer1)). Endinit ();

}

///

/// Clean Up Any Resources Being Used.

///

Protected Override Void Dispose (Bool Disposing)

{

IF (Disposing)

{

IF (Components! = NULL)

{

Components.dispose ();

}

}

Base.dispose (Disposing);

///

/// set Things in Motion So your service can do its work.

///

protected override void onstart (String [] ARGS)

{

THIS.TIMER1.ENABLED = TRUE;

THIS.LOGMESSAGE ("Service Started");

}

///

/// stop this service.

///

protected override void onstop ()

{

this.timer1.enabled = false;

This.LogMessage ("Service Stopped");

}

/ *

* Respond to the Elapsed Event of the Timer Control

* /

PRIVATE VOID TIMER1_ELAPSED (Object Sender,

System.timers.elapseDeventargs e)

{

THIS.LOGMESSAGE ("Service Running");

}

/ *

* Log Specified Message to Database

* /

Private void logmessage (string message)

{

SqlConnection Connection = NULL;

Sqlcommand command = NULL;

Try

{

Connection = New SqlConnection

"Server = localhost; database = sampledatabase; integrated

Security = false; user ID = sa; password =; ");

Command = New SQLCOMMAND (

INSERT INTO MyServiceLog (VC_STATUS, DT_CREATED)

VALUES ('" message ", getdate ()) ", connection);

Connection.open ();

INT Numrows = Command.executenonQuery ();

}

Catch (Exception EX)

{

System.Diagnostics.debug.writeLine (ex.Message);

}

Finally

{

Command.dispose ();

Connection.dispose ();

}

}

}

}

Install Windows service

The Windows service is different from the ordinary Windows application. It is impossible to simply start Windows service by running an EXE. Installing a Windows service should be done by install forward provustic.exe provided using .NET Framework, or through file deployment items such as a Microsoft Installer (MSI).

Add service installer

Create a Windows service, which is not enough to install this service only with installutil programs. You must also add a service installer to your Windows service, so that INSTALLUTIL or any other installer know how to configure what you are serving.

1. Switch this service program to the design view

2. Right-click the design view to select "Add Setup"

3. Switch to the design view of the Just added ProjectInstaller

4. Set the properties of the ServiceInstaller1 component: 1) ServiceName = My Sample Service

2) StartType = Automatic

5. Set the properties of the ServiceProcessInstaller1 component

1) Account = localsystem

6. Generate solutions

After completing the few steps above, the following source code is automatically generated by Visual Studio, which is included in the source file of ProjectInstaller.cs.

Using system;

Using system.collections;

Using system.componentmodel;

Using system.configuration.install;

Namespace CodeGuru.mywindowsService

{

///

/// Summary Description for ProjectInstaller.

///

[Runinstaller (TRUE)]

Public Class ProjectInstaller:

System.configuration.install.installer

{

Private system.serviceProcess.ServiceProcessInstaller

ServiceProcessInstaller1;

Private System.ServiceProcess.serviceInstaller ServiceInstaller1;

///

/// Required Designer Variable.

///

Private system.componentmodel.Container Components = NULL;

Public ProjectInstaller ()

{

// this call is required by the designer.

InitializationComponent ();

// Todo: add anyinitization after the initcomponent call

}

#Region Component Designer Generated Code

///

/// Required Method for Designer Support - Do Not Modify

/// The contents of this method with the code editor.

///

Private vidinitiRizeComponent ()

{

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 = "My Sample Service"; this.serviceInstaller1.startType =

System.ServiceProcess.ServiceStartMode.Automatic;

//

// ProjectInstaller

//

this.installers.Addrange (New

System.configuration.install.installer []

{this.ServiceProcessInstaller1, this.serviceInstaller1});

}

#ndregion

}

}

Install Windows service with InstallUTIL

Now this service has been generated, you need to install it before you can use it. The following will guide you to install your new service.

1. Open the Visual Studio .NET command prompt

2. Change the path to the BIN / Debug folder location where your project is located (if you compile by Release mode in Bin / Release folder)

3. Run "installutil.exe myWindowsservice.exe" to register this service so that it creates a suitable registration item.

4. Right click on "My Computer" on the desktop, select "Manage" to make a computer management console

5. In the Services section inside the Service and Applications, you can find that your Windows service is already included in the service list.

6. Right-click your service to select startup you can start your service.

This will ask you to uninstall and reinstall this service every time you need to modify the Windows service. However, be careful before uninstalling this service, it is best to ensure that the service management console has been closed, which will be a good habit. If you don't have this, you may have trouble when you uninstall and reopen Windows services. If you only uninstall the service, you can perform the phase of the installutil command to log out of the service, but you have to add a / u command switch back.

Debug Windows service

From another angular view, debugging Windows services is different from one normal application. Debugging the steps of Windows service requirements. The service cannot be as good as you do for ordinary applications, as long as you do it simply in the development environment, you can debug it. The service must be installed and started first, this is in front of us has done it. In order to facilitate tracking of debug code, once the service is started, you have to use Visual Studio to attach the running process (Attach). Remember, any modifications made to your Windows service are uninstalled and re-installed.

Additional WINDOWS services

In order to debug the program, some additional Windows service will be attached. These operations assume that you have installed this Windows service and it is running.

1. Load this project with Visual Studio

2. Click the "Debug" menu

3. Click on the "Process" menu

4. Make sure the display system process is selected

5. In the list of available processes, locate the process on your executable name Click to select it.

6. Click the attached button

7. Click OK

8. Click to close

9. Set a breakpoint in the Timer1_elapsed method, then wait for it to execute

to sum up

Now you should have anything about Windows services, and how to create, install, and debug them have a rough understanding. Features of the amount of Windows services you can study. These features include the ability to pause (onPause) and restoring. The ability to pause and recovery is not enabled by default, to be set via the Windows service properties.

About the Author

转载请注明原文地址:https://www.9cbs.com/read-130368.html

New Post(0)