Method of Using. NET to create a Windows Service Page 1/2

Source: Internet
Author: User
Document directory
  • What is a Windows service?
  • Create a Windows Service
  • Composition of Windows Services
  • Database Table script sample
  • Windows service example

Note: I learned C # through translation. Visual Studio is involved in this article.. NET operations. NET display information for processing, so that everyone can not misunderstand.

Author: Mark Strawmyer

We will study how to create an application as a Windows service. 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. Switch to the Code view page (Press F7 or select code from the View menu) and 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.

• Dispose-clear any managed and unmanaged resources)
• OnStart-Control Service Startup
• 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 is all the source code of the Windows service 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;
/// <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)
{
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 ();
}
}
}
}

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.