Create a Windows service with. Net

Source: Internet
Author: User
Tags configuration settings log net command require time interval visual studio
window| creation We will look at how to create an application that serves as a Windows service. Content contains what Windows services are, how to create, install, and debug them. The class that will use the System.ServiceProcess.ServiceBase namespace.

What is a Windows service?

A Windows Service application is an application that needs to run for a long time and is particularly suited for server environments. It has no user interface and does not produce any visual output. Any user messages will be written to the Windows event log. When the computer starts, the service automatically starts running. They do not have to be logged on by the user, and they can run in any user environment that includes the system. With the Service Control Manager, Windows services are controllable and can be terminated, paused, and started when needed.
Windows services, previous NT services, were introduced as part of the Windows NT operating system. They are not in Windows 9x and Windows Me. You need to use an NT-level operating system to run Windows services, such as Windows NT, Windows Professional, or Windows Server. For example, products in the form of Windows services are Microsoft Exchange, SQL Server, and other Windows Time services that set the computer clock.

Create a Windows service
The service we are about to create will do nothing but demo. When a service is started, an entry information is registered in a database to indicate that the service has been started. During a service run, it periodically creates a database project record within a specified time interval. The last database record is created when the service is stopped. This service automatically registers records of the Windows application log when it starts or stops successfully.
Visual Studio. NET makes it a fairly simple thing to create a Windows service. The instructions for starting our Demo service program are summarized below.
1. Create a new project
2. Choose Windows Services from a list of available project templates
3. Designer opens in design mode
4. Drag a Timer object from the Component table of the toolbox to the design surface (note: Make sure to use the timer from the list of components rather than from the list of Windows Forms)
5. Set Timer property, Enabled property is False,interval property 30000 ms
6. Switch to the Code view page (press F7 or select the code in the View menu) and add functionality to the service

Composition of Windows Services
In the code that follows your class, you will notice that the Windows service you created expands the System.ServiceProcess.Service class. All in. net method to build Windows services must extend this class. It will require your service to overload the following methods, which are included by Visual Studio by default.
dispose– clears any managed and uncontrolled resources (managed and unmanaged)
onstart– Control Service Launch
onstop– Control Service stopped
database table Script Sample
The database tables used in this example are created using the following T-SQL script. I chose the SQL Server database. You can easily modify this example to make it 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]

Examples of Windows services
Here is all the source code for the Windows service I named MyService. Most of the source code is generated automatically 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 are 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 to Designer support-do not modify
The contents is 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 being used.
</summary>
protected override void Dispose (bool disposing)
{
if (disposing)
{
if (Components!= null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing);
}
<summary>
The Set things in motion so your service can does 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)
{
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 ();
}
}
}
}

Installing Windows Services
Windows services are different from normal Windows applications. It is not possible to simply start the Windows service by running an EXE. Installing a Windows service should be done by using the InstallUtil.exe provided by the. NET framework, or through a file deployment project such as a Microsoft Installer (MSI).

Add Service Installer
To create a Windows service, it is not enough to use the InstallUtil program to install the service. You must also add a service installer to your Windows service so that installutil or any other installer knows what configuration settings to apply to your service.
1. Switch this service program to Design view
2. Right-click Design view to select "Add Installer"
3. Switch to the Design view of the newly 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. Build the solution
After completing the previous steps, the following source code is automatically generated by Visual Studio, which is included in the ProjectInstaller.cs source file.
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 are required by the Designer.
InitializeComponent ();
Todo:add any initialization on the initcomponent call
}
#region Component Designer generated code
<summary>
Required to Designer support-do not modify
The contents is 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
}
}

Installing Windows Services with InstallUtil
Now that the service has been generated, you need to install it well before you can use it. The following instructions will guide you through the installation of your new service.
1. Open Visual Studio. NET command prompt
2. Change the path to the Bin\Debug folder location where your project is located (if you compile in release mode in the Bin\release folder)
3. Execute the command "InstallUtil.exe MyWindowsService.exe" to register the service so that it establishes an appropriate registration entry.
4. Right-click on the desktop "My Computer", select "Management" Can play Computer Management console
5. In the "Services" section of "Services and Applications", you can find that your Windows services are already included in the list of services.
6. Right-click your service option to start your service.
This will require you to uninstall and reinstall the service each time you need to modify the Windows service. Be aware, however, that it is a good practice to ensure that the service management console is turned off before uninstalling the service. If this is not the case, you may have trouble uninstalling and reinstalling Windows Services. To uninstall the service only, you can perform a phase of the InstallUtil command to unregister the service, but add a/u command switch at the back.

Debugging Windows Services
From another perspective, debugging a Windows service is a different thing from a normal application. More steps are required to debug Windows services. Services cannot be debugged as you do for ordinary applications, as long as they are simply executed in the development environment. The service must be installed and started first, which we have already done in the previous section. To facilitate tracking of debugging code, once the service is started, you will need to use Visual Studio to attach the running process (attach). Remember that any changes you make to your Windows service will be uninstalled and reinstalled for this service.

Attaching a running Windows service
For debugging programs, some instructions for operating the Windows service are attached. These operations assume that you have installed the Windows service and that it is running.
1. Load this project with Visual Studio
2. Click the "Debug" menu
3. Click on the "Process" menu
4. Ensure that the display system process is selected
5. In the list of available processes, position the process on your executable file name and click to select it
6. Click on the Additional button
7. Click OK
8. Click Close
9. Set a breakpoint in the Timer1_elapsed method and wait for it to execute

Summarize
Now you should have a rough idea of what Windows services are and how to create, install, and debug them. The functionality of the Windows service's forehead you can study it yourself. These features include the ability to pause (OnPause) and Restore (oncontinue). The ability to pause and restore is not enabled by default and is set 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.