Use C # To develop a Windows Service Monitoring System

Source: Internet
Author: User

Abstract: This article will show you how to use C # To develop a Windows service to record system usage.

Everyone wants to know at what time they start and shut down their systems every day, and how long the systems run every day. It would be a good idea to use a DataGrid Control to display the system startup, shutdown, and time consumed.

In this article, I provide a method to achieve this goal-use C # To develop a Windows service. In fact, everyone knows a little about Windows Services. However, for the purpose of introduction, I have to explain as few Windows Services as possible. Then we will discuss how to design such an application.

1. What is a Windows service?

In fact, Windows Services only run in the background and do not require us to understand the process. Moreover, most of them do not require user interaction. If we enter "services. msc" under the "run" command line in the "Start" menu and press enter, then we can see the Service Running in our current system. Some services are automatically started when the system starts. However, some services must be manually started before they can run.

Ii. Advantages of Windows Services

1. It can run automatically.

2. User interaction is not required.

3. Run in the background.

Generally, Windows Services are used in many time-consuming processes, such as backing up databases.

Now, we need to design a Windows service to record the time required for starting and disabling your system. I designed this application using Visual Studio 2003.

3. Design Windows Services

Step 1:

Open Visual Studio and select the Visual C # project. Set the template type to Windows Service and name it Monitoring, as shown in:

Step 2:

Press F7 to open the code window. Then, add a reference to the System. IO namespace to compile the System timing function into a file. Next, replace all Service1 statements with Monitoring. Then, switch to the design mode (Press shift + F7 ). Select Solution Explorer (Press Ctrl + Alt + L ). Click Service1.cs and name it Monitoring. cs.

Then, go to the code window. Add the following code to the OnStart event, as shown in:

Functions implemented in the OnStart event

First, create an XML file on drive C and name it file1. Then, create the following code in this file:

 

<? Xml version = "1.0" encoding = "UTF-8" standalone = "no"?>
<Times>

Then, close it.

I created a service that can be automatically started at system startup and record the startup time. When the system is disabled, it is also disabled. In addition, it records the shutdown time and the time spent in the system.

First, I want to create a streamwriter to write the system startup time to the file1.xml file.

After you copy the code to your onstart event, create a public variable temp on the monitoring constructor, as shown in:


After that, copy the code to your code window:
Copy the following code to the onstart event, as shown in:

StreamWriter writer = File. AppendText ("d :\\ file1.xml ");
Writer. Write ("<time> ");
Writer. WriteLine ("<Date>" + (DateTime. Now. ToString ("dd-MM-yy") + "</Date> ");
Writer. WriteLine ("<started>" + (DateTime. Now. ToString ("t") + "</started> ");
Temp = DateTime. Now;
Writer. Close ();

 

Functions implemented in the onshutdown event

When the system is shutting down, I use a streamwriter to open file1.xml again-it will write down the system shutdown time and the time span between system startup and shutdown. I used a temp variable in the onstart and onshutdown events. In onstart, it is used to store the startup time. It is then used again in the onshutdown event to note the time interval between system startup and shutdown.

Then, we must configure our windows service for installation and running.

Therefore, first go to the design view and select the attribute window (you can press F4 ).

Set canstop and canshutdown to true. Before installation, We must install an installer.

Right-click the design view and select "add installer ". It then displays projectinstaller. CS. In this file, both serviceinstaller1 and serviceprocessinstaller1 exist. Go to the serviceprocessinstaller1 attribute:

· Set the Account to LocalSystem.

· Go To The serviceInstaller1 attribute.

· Set DisplayName and ServiceName to Monitoring.

· Set StartType to automatic.

See:
 

  
Then, go to the command prompt of VS. NET.

Go to the Debug folder of the service on the console:

Enter "InstallUtil Monitoring.exe"

If "Commit Phase Completed Successfully" is displayed, the service is Successfully installed.

Then, restart the system to start the service. After the restart, open the file1.xml file, which records the start time of the system. If the system is shut down, it records the system's shutdown time and the length of time it takes to use the system. Through this part, we have completed recording the time consumed by the system. Next, we will create a web application to display xml data in a Grid control.

In the next section, I will explain how to extract the xml file data and display it in a DataGrid Control.
4. Use C # to create a Web application

In this section, we use C # to create a web application and name it SystemMonitor.

Add the following namespace:

Using System. IO;
Using System. Xml;
Using System. Text;

Then, drag the DataGrid and Label controls to the page, as shown in:


Copy the following code to the Page_Load event:

File. Copy ("c: \ file1.xml", "c: \ temp1.xml", true );
StreamWriter writer1 = File. AppendText ("c: \ temp1.xml ");
Writer1.Write ("<shutdown> undefined </shutdown> ");
Writer1.Write ("<timespent> undefined </timespent> ");
Writer1.Write ("</time> ");
Writer1.WriteLine ("</times> ");
Writer1.Close ();
DataSet ds = new DataSet ();
Ds. ReadXml ("c: \ temp1.xml ");
TimeSpan t = new TimeSpan ();
DataGrid1.DataSource = ds;
DataGrid1.DataBind ();
XmlTextReader reader = new XmlTextReader ("c: \ temp1.xml ");
While (reader. Read ())
{
If (reader. NodeType = XmlNodeType. Element)
{
If (reader. Name = "timespent ")
{
String temp11 = reader. ReadInnerXml (). ToString ();
If (temp11! = "Undefined ")
{
Temp11 = temp11.Replace (":",".");
Temp11 = temp11.Replace ("","");
Duration + = Convert. ToDouble (temp11 );
}
}
}
}
Response. Write ("Total Duration is :");
Double temp122 = Convert. ToDouble (duration );
String hr = temp122.ToString ();
String hrstr = hr. Substring (0, hr. IndexOf ("."));
Response. Write (hrstr. ToString () + "Hours ");
String mins = hr. Substring (hr. IndexOf (".") + 1, (hr. Length-hr. IndexOf (".")-1 ));
Response. Write ("" + mins. ToString () + "Minutes ");
Reader. Close ();
File. Delete ("c: \ temp1.xml ");

Finally, paste the following declaration to the top of the Page_Load event:

Private double duration;

I will explain what the program has done in the Page_Load event.

First, I copied the file file1.xml (which contains the system timing information) to the temporary file. Then, I add some tags to the temporary file. Then, I read the temp content to a dataset, and finally bound it to a DataGrid. Later, I will create a logic to find all the time spent.

I hope everyone can understand the above Code.

The output results on the above page are roughly as follows:

 

From: http://blog.csdn.net/teng_s2000/archive/2006/07/26/979422.aspx

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.