Windows Service creation and installation

Source: Internet
Author: User
Tags configuration settings net command

We'll 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. A class that uses 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 suitable for a server environment. It does not have a user interface and does not produce any visual output. Any user messages will be written into the Windows event log. When the computer starts, the service automatically starts running. They don't have to be logged in to run, they can run in any user environment that includes the system. Through the Service Control Manager, Windows services are controllable and can be terminated, paused, and started when needed.

Windows Services, formerly NT services, were introduced as part of the Windows NT operating system. They are not in Windows 9x and under 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, such as setting the computer clock.


Create a Windows service

We are about to create this service in addition to demonstrating nothing to do. When the 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 interval of time. The last database record is created when the service is stopped. This service automatically registers the logs in the Windows application log when it successfully starts or stops.

Visual Studio. NET makes it a fairly simple thing to create a Windows service. The instructions for starting our Demo service program are outlined below.

1. Create a new project
2. Select Windows Services from a list of available project templates
3. The designer opens in design mode
4. Drag a Timer object onto the design surface from the Component table in the Toolbox (note: To ensure that you are using a timer from the list of components instead of from the Windows Forms list)
5. Set the Timer property, the Enabled property is the False,interval property for 30000 milliseconds
6. Switch to the Code view page (press F7 or select Code from the View menu) and then add the function to the service


The composition of Windows services

In the code contained behind your class, you will notice that the Windows service you created expands the System.ServiceProcess.Service class. All with. NET-based Windows services must extend this class. It will require your service to reload the following methods, which are included by Visual Studio by default.

dispose– Remove any controlled and uncontrolled resources (managed and unmanaged resource)
onstart– Control Service startup
onstop– Control Service stopped

Examples of Windows services

Here is a test case, the service named Service1 Black is automatically generated, the red part of the code I added, green for me to add the comment, this case has no other meaning, just insert the record into the database.

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Diagnostics;
Using System.ServiceProcess;
Using System.Configuration.Install;
Using Sysdata.db;

Namespace Servertest
{
public class Service1:System.ServiceProcess.ServiceBase
{
Private System.Timers.Timer timer1;
<summary>
The required designer variables.
</summary>
Private System.ComponentModel.Container components = null;

Public Service1 ()
{
This call is required by the Windows.Forms Component Designer.
InitializeComponent ();

TODO: Add any initialization after the initcomponent call
}

Main entry point of the process
static void Main ()
{
System.serviceprocess.servicebase[] ServicesToRun;

Multiple User services can be run in the same process. To add
Another service is added to this process, please change the downstream
To create another service object. For example
//
ServicesToRun = new system.serviceprocess.servicebase[] {new Service1 (), New MySecondUserService ()};
//
ServicesToRun = new system.serviceprocess.servicebase[] {new Service1 ()};

System.ServiceProcess.ServiceBase.Run (ServicesToRun);
}

<summary>
Designer supports required methods-do not use the Code Editor
Modify the contents of this method.
</summary>
private void InitializeComponent ()
{
This.timer1 = new System.Timers.Timer ();
((System.ComponentModel.ISupportInitialize) (This.timer1)). BeginInit ();
//
Timer1
//
This.timer1.Enabled = true;
This.timer1.Interval = 30000;
this.timer1.Elapsed + = new System.Timers.ElapsedEventHandler (this.timer1_elapsed);
//
Service1
//
This. ServiceName = "Service1";
((System.ComponentModel.ISupportInitialize) (This.timer1)). EndInit ();

}

  ///<summary>
  ///Clean up all the resources that are in use.
  ///</summary>
  protected override void Dispose (bool disposing)
   {
   if (disposing)
   {
    if (Components! = NULL)
    {
     components. Dispose ();
    }
   }
   base. Dispose (disposing);
  }

  ///<summary>
  ///set up a specific action so that the service can perform its work.
  ///</summary>
  protected override void OnStart (string[] args)
  {
   //TODO: Add code here to start the service.
   this.timer1.enabled = true;
   this. LogMessage ("Service Started");
  }
 
  ///<summary>
  ///Stop this service.
  ///</summary>
  protected override void OnStop ()
  {
    //TODO: Add code here to perform the close operation required to stop the service.
   this.timer1.enabled = false;
   this. LogMessage ("Service Stopped");
  }

private void LogMessage (string xmsg)
{
Try
{
//Here is a record that inserts a message into the database, and below is the method by which I call the pre-written DB class to add records, or you can use other methods to write to the database. xmsg
Db.querysql ("Insert into sysmsg (sysmsg) VALUES ('" +xmsg+ "')");
}
Catch
{
//Do not take any action
}
}

private void Timer1_elapsed (object sender, System.Timers.ElapsedEventArgs e)
{
logmessage ("Check service run! ");
}
}
}

&NBSP;
Install Windows Services

Windows services differs from normal Windows applications. It is not possible to start the Windows service simply 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

Creating a Windows service is not sufficient to install the service with the InstallUtil program alone. You must also add a service installer to your Windows service, which makes it easy for installutil or any other installer to know what configuration settings are applied to your service.

1. Switch the service program to Design view
2. Right-click Design view, select Add Installer
3. Switch to The Design view of the 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 Solution

installing Windows services with InstallUtil

Now that the service has been generated, you need to install it before you can use it. The following actions 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 are compiling 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.
Note: Run directly InstallUtil.exe may fail, prompt:
' InstallUtil.exe ' is not an internal or external command, nor is it a program or batch file that can be run.
You can find this executable program in C:\WINNT\Microsoft.NET\Framework\v1.1.4322
4. Right-click on "My Computer" on the desktop and select "Manage" to hit the Computer Management console
5. In the "Services" section of "Services and Applications", you can find that your Windows service is already included in the list of services
6. Right-click on your service selection to start your service.

This will require you to uninstall and reinstall the service every time you need to modify the Windows service. Note, 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 be having trouble uninstalling and reinstalling Windows Services. If you uninstall the service only, you can execute the installutil command to unregister the service, but add a/u command switch later.


Debugging Windows Services

From another point of view, debugging a Windows service is definitely different from a normal application. More steps are required to debug Windows service requirements. The service cannot be done as you would for a normal application, as long as you simply execute it in a development environment and you can debug it. The service must be installed and started first, which we have already done in the previous section. To make it easier to track debug code, once the service is started, you will need to attach the running process (attach) in Visual Studio. Remember that any changes you make to your Windows service will have to be uninstalled and re-installed.


Attaching a running Windows service

In order to debug the program, there are additional instructions for the Windows service. These actions assume that you have installed the Windows service and that it is running.

1. Load this project with Visual Studio
2. Click on 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, click to select it by locating the process on your executable file name
6. Click the Attach button
7. Click OK
8. Click Close
9. Set a breakpoint in the Timer1_elapsed method and wait for it to execute


Summary

Now you should have a rough idea of what Windows services are and how to create, install, and debug them. The features of the Windows service are available on your own. These features include the ability to pause (OnPause) and Restore (OnContinue). The ability to pause and resume is not enabled by default and is set through the Windows Service properties.

Windows Service creation and installation

Related Article

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.