Use. Net to create a Windows Service

Source: Internet
Author: User
Tags net command

Use. Net to create a Windows Service

Author: Mark strawmyer

The operations related to Visual Studio. NET are handled based on the Visual Studio. NET display information in the Chinese version.

We will study how to create an application as a Windows ServiceProgram. The content includes what is a Windows service and how to create, install, and debug them. The system. serviceprocess. servicebase namespace class is used.

What is a Windows service?

Windows service applications are applications that require long-term running. They are especially suitable for server environments. It does not have a user interface and does not produce any visual output. Any user message is written into the Windows event log. When the computer starts, the service automatically starts running. They do not run only when users log on. They can run in any user environment including the system. Through the Service Control Manager, Windows Services are controllable and can be terminated, paused, and started as needed.

Windows Services, formerly NT services, are introduced as part of the Windows NT operating system. They are not in Windows 9x or Windows ME. You need to use an NT-level operating system to run Windows Services, such as Windows NT, Windows 2000 Professional, or Windows 2000 Server. For example, products in the form of Windows Services include Microsoft Exchange and SQL Server, and Windows Time services such as computer clock settings.

Create a Windows Service

The service we are about to create does nothing except demonstration. When the service is started, an entry is registered to a database to indicate that the service has been started. During service running, it regularly creates a database project record at a specified interval. When the service is stopped, the last database record is created. This service automatically registers with the Windows Application log the records when it is successfully started or stopped.

Visual Studio. NET makes creating a Windows Service quite simple. The following describes how to start the demo service program.

1. Create a project

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

3. The designer opens in design mode.

4. Drag a timer object from the component table in the toolbox to the design surface (Note: Make sure that timer is used from the component list rather than from the Windows form List)

5. Set the timer attribute. The enabled attribute is false, and the interval attribute is 30000 milliseconds.

6. SwitchCodeView page (Press F7 or select code in the View menu), and then fill in the function for this service

Composition of Windows Services

In the code behind your class, you will notice that the Windows service you created expands the system. serviceprocess. Service class. All Windows Services created in. Net mode must expand this class. It requires your service to reload the following methods. Visual Studio includes these methods by default.

& #8226; dispose-clear any managed and unmanaged Resources)

& #8226; onstart-Control Service Startup

& #8226; onstop-Control Service stop

Database Table script sample

The database tables used in this example are created using the following T-SQL script. Select the SQL Server database. You can easily modify this example so that it can run in access or any 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 example

The following are all Windows Services named myservice.Source code. 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;

/// <Remarks>

/// Required designer variable.

/// </Remarks>

Private system. componentmodel. Container components = NULL;

Public myservice ()

{

// This call is required by the windows. Forms

// Component designer.

Initializecomponent ();

}

// 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 );

}

/// <Summary>

/// Required method for designer support-do not modify

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

/// </Summary>

Private void initializecomponent ()

{

This. timer1 = new system. Timers. Timer ();

(System. componentmodel. isupportinitialize)

(This. timer1). begininit ();

//

// 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 ();

}

/// <Summary>

/// Clean up any resources being used.

/// </Summary>

Protected override void dispose (bool disposing)

{

If (disposing)

{

If (components! = NULL)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

/// <Summary>

/// Set things in motion so your service can do its work.

/// </Summary>

Protected override void onstart (string [] ARGs)

{

This. timer1.enabled = true;

This. logmessage ("service started ");

}

/// <Summary>

/// Stop this service.

/// </Summary>

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)

{< br>
This. logmessage ("Service Running");

}

/*
* log specified message to database
*/
private void logmessage (string message)

{< br>
sqlconnection connection = NULL;
sqlcommand = 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 ();

}< br>
catch (exception ex)

{< br>
system. diagnostics. debug. writeline (ex. message);

}< br>
finally

{< br>
command. dispose ();
connection. dispose ();

}

Install Windows Services

Windows Services are different from common Windows applications. It is impossible to simply start the Windows service by running an EXE. To install a Windows service, you must use installutil.exe of. Net framework.exe, or use a file deployment project such as Microsoft Installer (MSI.

Add service Installer

It is not enough to create a Windows Service and only use the installutil program to install the service. You must add a service installer to your Windows Service so that installutil or any other installer can know how your service is configured.

1. Switch the service program to the design view.

2. Right-click the design view and select "add installer"

3. Switch to the design view of the newly added projectinstaller.

4. Set the attributes of the serviceinstaller1 component:

1) servicename = My Sample Service

2) starttype = automatic

5. Set the attributes of the serviceprocessinstaller1 component

1) account = LocalSystem

6. Generate a solution

After completing the preceding steps, Visual Studio automatically generates the following source code, which is included in the source file projectinstaller. CS.

Using system;

Using system. collections;

Using system. componentmodel;

Using system. configuration. Install;

Namespace codeguru. mywindowsservice

{

/// <Summary>

/// Summary description for projectinstaller.

/// </Summary>

[Runinstaller (true)]

Public class projectinstaller:

System. configuration. Install. Installer

{

Private system. serviceprocess. serviceprocessinstaller

Serviceprocessinstaller1;

Private system. serviceprocess. serviceinstaller serviceinstaller1;

/// <Summary>

/// Required designer variable.

/// </Summary>

Private system. componentmodel. Container components = NULL;

Public projectinstaller ()

{

// This call is required by the designer.

Initializecomponent ();

// Todo: add any initialization after the initcomponent call

}

# Region component designer generated code

/// <Summary>

/// Required method for designer support-do not modify

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

/// </Summary>

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 });

}

# Endregion

}

}

Install Windows Services with installutil

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

1. Prompt for opening the Visual Studio. NET command

2. Change the path to the bin \ debug folder of your project (if you compile in release mode, in the bin \ release folder)

3. Execute the command "installutil.exe mywindowsservice.exe" to register this service and create an appropriate registration item.

4. Right-click "my computer" on the desktop and select "manage" to access the computer management console.

5. In the "services" section of "services and applications", you can find that your Windows services are included in the Service list.

6. Right-click your service and choose start to start your service.

Every time you need to modify the Windows Service, this requires you to uninstall and reinstall the service. However, it is a good habit to ensure that the service management console is closed before you uninstall the service. If this is not the case, you may encounter problems when uninstalling and re-installing Windows Services. If you only uninstall the service, you can run the installutil command to log out of the service. However, you need to add a/u command to the end.

Debug Windows Services

From another perspective, debugging Windows Services is totally different from a common application. More steps are required to debug Windows Services. Services cannot be debugged as long as they are simply executed in the development environment as you do for common applications. The service must be installed and started first. We have done this in the previous section. To facilitate code tracing and debugging, once the service is started, you must use Visual Studio to append the running process (attach ). Remember, any modifications made to your Windows service must be uninstalled and reinstalled.

Append a running Windows Service

To debug the program, some operating instructions for the Windows Service are attached. These operations assume that you have installed the Windows service and it is running.

1. Use Visual Studio to load this project

2. Click the "debug" menu

3. Click the process menu.

4. Ensure that the system process is selected

5. In the list of available processes, locate the process on your Executable File Name and click to select it

6. Click the Add button.

7. Click OK.

8. Click Close.

9. Set a breakpoint in the timerreceivelapsed method and wait for it to execute

Summary

Now you should have a rough understanding of what Windows Services are and how to create, install, and debug them. You can study the functions of Windows Services on your own. These functions include onpause and oncontinue. The pause and resume capabilities are not enabled by default. You must set them through Windows Service properties.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.