This article will show you how to use C # to develop a Windows service to record system usage.
Everyone wants to know what time they start and shut down their systems every day, and how much time the system runs every day. It would be a good idea to use a DataGrid control to display the system startup, shutdown, and time spent.
In this article, I have provided a way to achieve this goal-to develop a Windows service using C #. In fact, everyone knows a little about Windows services. However, for the purposes of this presentation, I only need to explain the Windows service as little as possible. Then we'll discuss how to design an application like this.
One, what is the Windows service.
In fact, Windows Services is just a process that runs in the background and does not require us to understand. Moreover, most of them do not require user interaction. If we type "services.msc" and enter on the "Run" command line of the Start menu, we can see the services running on our current system. Among them, some services are started automatically when the system is started. However, there are some services that must be started by hand to run.
Advantages of Windows Services
1. Able to run automatically.
2. Do not require user interaction.
3. Run in the background.
In general, Windows services are used in processes that are time-consuming, such as backing up databases, and so on.
Now, we're going to design a Windows service to realize the time it takes for your system to start and shut down. I designed this application using Visual Studio 2003.
Third, the design of Windows services
First step:
First open Visual Studio and select Visual C # Engineering. Select the template type as the Windows service and name it monitoring, as shown in the following illustration:
Step Two:
Press the F7 key to open the Code window. Then, add a reference to the System.IO namespace in order to write the system timing function into a file. Next, replace all occurrences of Service1 with the word monitoring. After that, transfer to design mode (key Shift+f7). Select Solution Explorer (Key ctrl+alt+l). Click on the Service1.cs and name it Monitoring.cs.
After that, move to the Code window. Add the following code to the OnStart event, as shown in the following illustration:
Features implemented in the OnStart event
First, create an XML file on the C disk and name it file1. Then, create the following code in this file:
Then, close it.
I created a service that was able to start automatically when the system started and recorded the startup time. When the system shuts down, it also closes. Also, it records the shutdown time and the time spent in the system.
First, I'm going to create a StreamWriter to write the system boot time into the File1.xml file.
After copying the code to your OnStart event, create a public variable, temp, just above the monitoring constructor, as shown in the following figure:
After that, copy this part of the code into your code window:
Then copy the following code into the OnStart event, as shown in the following illustration:
StreamWriter Writer=file.appendtext ("D://file1.xml"); Writer. Write (""); Writer. WriteLine (" " + (DateTime.Now.ToString ("Dd-mm-yy")) + ""); Writer. WriteLine (" " + (DateTime.Now.ToString ("T")) + " "); Temp=datetime.now; Writer. Close (); |
Features implemented in the OnShutdown event
When the system is shutting down, I use a StreamWriter to open the file1.xml-again it will note the system shutdown time and will also note the time span spent between system startup and shutdown. I used a temp variable in the OnStart and OnShutdown events. In OnStart, it is used to store startup time. It is then used again in the OnShutdown event to note the time interval between the system startup and shutdown.
Then we have to configure our Windows service to install and run.
So, first go to Design view and select the Properties window (you can press F4).
Set the CanStop and CanShutdown to True. Before installing, we must install a setup program.
Right-click the Design view window and choose Add Installer. Then, it will show ProjectInstaller.cs. In this file, both ServiceInstaller1 and serviceProcessInstaller1 exist. Go to the ServiceProcessInstaller1 property:
· Set account to LocalSystem.
· Then, go to the ServiceInstaller1 property.
· Set the DisplayName and servicename to monitoring.
· Set the Startup type (StartType) to Automatic.
Please refer to the following figure:
Then, go to the command prompt at vs.net.
Under the console, go to the service's Debug folder:
Enter "InstallUtil Monitoring.exe"
If it displays "Commit Phase Completed successfully", the service is successfully installed.
Then, reboot the system to start the service. After the reboot, open the File1.xml file, which records the system's start time. If the system is turned off, it records the shutdown time of the system and the length of time it uses the system. Through this section, we have completed recording the time spent on the system. Next, we will create a Web application to display the XML data in a Grid control.
In the next section, I'll explain how to extract this XML file data and display it in a DataGrid control.
Create a Web application with C #
In this section, we create a Web application with C # and name it systemmonitor.
Add the following namespaces:
Using System.IO; Using System.Xml; Using System.Text; |
After that, drag the DataGrid and label controls onto the page, as shown in the following illustration:
Copy the following code into 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 are:"); 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:
Let me explain what the program did in the Page_Load event.
First, I copy the contents of the file File1.xml (which contains system timing information) to the temporary file. Then, I add some tags to the temporary file. After that, I read the contents of temp to a dataset and finally bind it to a DataGrid. Later, I created the logic to find all the time that was spent.
I really want everyone to understand the code above.
The output of the above page is roughly as follows: