Create a Windows service with .NET

xiaoxiao2021-03-06  106

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.

Creating a Windows service Our upcoming this service 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. Creating a new project 2. From a list of available project templates. Select Windows service 3. Designer will open in design mode 4. Drag a Timer object from the component table of the toolbox to this design surface (Note: To pay Make sure to use Timer from the component list instead of the Windows Form list, 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

The composition of the Windows service is 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 resource? OnStart - Control Service Start? 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_GENER_CP1_CI_AS NOT NULL, [DT_CREATED] [DATETIME] NOT NULL) ON [ PRIMARY]

The Windows Service Sample is all source code for the Windows service I named myService. Most source code is automatically generated by Visual Studio. 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 design; initializeComponent ();

// The main entry point for the process static void main () {system.serviceProcess.serviceBase [] ServicesTorun; serviceUn = new system.serviceProcess.serviceBase [] {new myservice ()};

System.ServiceProcess.serviceBase.Run (ServiceStorun);

///

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

}

///

/// clean up any resources being used. /// protected Override Void Dispose (Bool Disposing) {if (disponents! = 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 start");} /// /// stop this service. /// protected override void onstop () {this.timer1. Enabled = false; this.logMessage ("service stopped");

/ * * Respond to the elapsed event of the time control * / private void time1_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 ( "Server = localhost SqlConnection; Database = SampleDatabase; Integrated Security = false; User ID = SA; password =; "); Command = New SqlCommand (" Insert Into MyServiceLog (" " " Message ", Getdate ()) ", GetDate ())", Connection.Open (); int Numrows = Command.executeNonQuery ();} catch (exception ex) {system.diagnostics.debug.writeline (ex.ssage);} finally {command.dispose (); connection.dispose ();}}}}

Installing the Windows service Windows service is different from the normal 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). Adding a Service Setup 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: Set the properties of the ServiceInstaller1 component: 1) ServiceName = My Sample Service 2 ), StartType = automatic5. Setting the properties of the serviceProcessInstaller1 component 1) Account = localsystem6. 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.collections; 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 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 = "My Sample Service"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.installers.addrange (new system.configuration.install.installer [] {this.serviceProcessInstaller1, this.serviceInstaller1} );} #ENDREGON}} Installing the Windows service with installutil now This service has been generated, you need to install it to 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. Execute command "installutil.exe myWindowsService.exe "Register this service to create a suitable registration item. 4. Right-click on "My Computer" on the desktop, select "Management" to make a computer management console 5. In the Service and Applications, you can find that your Windows service is already included. The service list is 6. Right-click your service to select Start, 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.

Debugging Windows services When you look at another angle, debugging Windows services is unlike a 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 running Windows services For the debugger, some additional Windows services are operated. These operations assume that you have installed this Windows service and it is running.

1. Load this item with Visual Studio 2. Click the "Debug" menu 3. Click "Process" menu 4. Make sure the display system process is selected 5. In the available process list, position the process on your executable name. Click. Select it 6. Click on the additional button 7. Click OK 8. Click to close 9. Set a breakpoint in the Timer1_elapsed method, then wait for it to execute

Summary Now you should have a rough understanding of Windows services and how to create, install, and debug them. 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 AuthorMark Strawmyer, MCSD, MCSE (NT4 / W2K), MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design And development of microsoft-based solutions. You can reach mark at mstrawmyer@crowechizek.com.

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

New Post(0)