Windows service details are not described in this article. If you want to know, search for it on the Internet. The keyword is "Windows service". The search results will not disappoint you! The intended readers of this article are those who have some knowledge about Windows service but have not compiled any Windows service programs.
First, we are not in a rush to introduce how to code, step 1 and step 2. Before you start, you need to know why I want to do so and whether there are other convenient, simple, and fast solutions. If I have to do this, what are the advantages. Because I have encountered many similar situations and made things happily, I found that either it is too complicated or the customer is uncomfortable, or there is still a simpler way, in short, it is useless from the perspective of the Project Manager. The time for doing this is in vain, delaying the progress of the project. Of course, from the perspective of personal experience, it is completely another comment and result.
Now, I suppose you have thought very clearly, and decided to use Windows service to solve your problems in the project. You want to know how to create a Windows service. Next I will introduce it. For ease of understanding, the following sections are described separately.
I. Business Environment used in the Windows service example
The reason for introducing the business environment used by the Windows service example is that it is easier to understand it later. The Windows service example I mentioned in this article comes from the need of a web project in our actual work. This project is an online examination system, which has such a trade-off, because there are a large number of candidates, in order to avoid an error in inserting the answer information into the database during the exam submission, this method is adopted: let all the candidates hand in the exam first, instead of inserting data into the database, you can generate an XML file for the examinee's answer, upload the file to a fixed directory on the server, and then parse the XML file by the program, extract data and insert it to the database. To reduce the pressure on the server, the XML file parsing work uploaded to the server cannot be performed during the examination. This is to minimize the chance of errors during the examination. Therefore, you must consider how to parse the XML files uploaded to the server and when to parse them. If you do not consider this, you can directly execute a piece of code on the web system after the examinee submits an XML file containing the answer information to the server to scan the XML file submitted in a fixed directory, read data and insert it into the database. This is also a good method. However, if you want to parse these XML files when the server is under less pressure, and refer to the comments on the Internet, it is said that there are three good methods: first, using database jobs; 2. Use Windows scheduled tasks; 3. Use Windows service. In any case, I finally decided to use Windows service.
Ii. functions implemented by the Windows service example
The Windows service example in this article is simple and clear to implement modern functions: 1. regularly scan XML files in the fixed directory of the server; 2. Periodically scan XML files in the fixed directory, if the time is between and, extract the data in the XML file and insert the data to the t_datiqk table in the local database kaoshi; 3. If the data is extracted and inserted successfully, delete an XML file in a fixed directory.
3. Use C # To create a Windows Service in vs2005
I have introduced a lot of Windows Service examples in this article. It is estimated that you are very impatient. Well, now we are entering the coding and operation steps of the real knife and real gun. Thanks to Microsoft and vs2005, it is so easy and quick to create a Windows service. Next, we will introduce how to use C # In vs2005 to create windows servcie.
1. Create a Windows Service Project
Open vs2005, click File-New-Project (usually teamsuit visiostudio), and select Windows service. For example.
In the project name input box, enter gradeservice (this is the name of Windows service. You can't care about it if you like it), and then select the Save path of the project below, click OK. In the solution browser, we can see that vs2005 has automatically generated some necessary files for you, as shown in figure
. Switch vs2005 to the attribute browsing page. service1.cs has the following attributes:
Whether autolog is automatically written to the System Log File
Receive Power Events During canhandlepowerevent Service
Whether the canpauseandcontinue Service accepts the pause or continue running request
Whether the canshutdown Service receives a notification when the computer that runs it shuts down, so that it can call the onshutdown Process
Whether the canstop Service accepts the stop operation request
Servicename service name
The default file name generated by the system makes me uncomfortable. I decided to change it. Right-click "service1.cs" and change it to "gradeservice", as shown in.
In vs2005, a window is displayed. Click "yes ".
2. Improve the Windows service function and add business code
To record the log, drag "components" in the toolbar to an EventLog. In addition, a timer is required because scheduled execution is required. You can see from the Internet that there are three timers. One is system. Timers. timer; the other is system. Threading. timer; the other is system. Windows. Forms. Timer. It is recommended that you use system. Timers. Timer. However, this is not visible on the design page. It can be seen only in gradeservice. Designer. CS. Double-click the gradeservice. CS [design] Page to go to the code page. There are two empty functions, onstart and onstop. As the name implies, the onstart function is executed when the service is started, and the onstop function is executed when the service is stopped.
The following is the code for gradeservice. CS.
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. diagnostics;
Using system. serviceprocess;
Using system. text;
Using system. IO;
Using system. Web;
Using system. Data. sqlclient;
Using system. configuration;
Namespace gradeservice
{
Public partial class gradeservice: servicebase
{
Public gradeservice ()
{
Initializecomponent ();
// If the system time viewer does not contain a category such as "XML file parsing", add
If (! System. Diagnostics. EventLog. exists ("XML file parsing "))
{
System. Diagnostics. EventLog. createeventsource ("XML file parsing service", "XML file parsing ");
}
// Set the log name
This. EventLog. log = "XML file parsing ";
// Set the log Source
This. EventLog. Source = "XML file parsing service ";
}
/// <Summary>
/// Start the service
/// </Summary>
/// <Param name = "ARGs"> </param>
Protected override void onstart (string [] ARGs)
{
// Todo: Add code here to start your service.
If (this. Timer = NULL)
{
EventLog. writeentry ("XML file parsing service started ");
Timer = new system. Timers. Timer ();
// Execute every 5 minutes
This. Timer. interval = 5x60x1000;
// Set timer to trigger elapsed events
This. Timer. Enabled = true;
// Start
This. Timer. Start ();
This. Timer. elapsed + = new system. Timers. elapsedeventhandler (timer_elapsed );
}
}
/// <Summary>
/// Code executed after the time interval reaches
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Void timer_elapsed (Object sender, system. Timers. elapsedeventargs E)
{
// Stop timing
This. Timer. Stop ();
// Obtain the current system time
Datetime now = datetime. now;
// Determine whether the current time is between 20 and 23. If yes, run the Business Code; otherwise, no execution is performed.
If (now. Hour <= 23 & now. Hour> = 20)
{
// Obtain the path for saving the XML file in the app. config file
String _ basepath = system. configuration. configurationsettings. deleetpath ["filepath"];
// Start scanning files
This. scanfile (_ basepath );
}
// Start timing
This. Timer. Start ();
}
/// <Summary>
/// Stop the service
/// </Summary>
Protected override void onstop ()
{
// Todo: Add code here to perform any tear-down necessary to stop your service.
If (this. timer! = NULL)
{
This. Timer. Enabled = false;
This. Timer. Stop ();
This. Timer. Dispose ();
EventLog. writeentry ("XML file parsing Service stopped ");
}
} // <Summary>
/// Parse the file and insert the data into the database
/// </Summary>
/// <Param name = "FILENAME"> full file path </param>
/// <Param name = "name"> file name </param>
Private void insertdata (string filename, string name)
{
// Read XML file content
Dataset DS = new dataset ();
DS. readxml (filename );
// Loop the dataset and insert the content, using transactions
String MSG = "parsing file" + name + "successful! ";
// Obtain the database connection string
String sqlconnstring = system. configuration. configurationsettings. deleettings
["Sqlconnstring"];
If (sqlconnstring = NULL)
{
EventLog. writeentry ("no database connection string found in the app. config file. The parsing file is aborted! ");
Return;
}
// Establish a database connection
Sqlconnection conn = new sqlconnection (sqlconnstring );
Try
{
Conn. open ();
}
Catch (exception E)
{
// Record the cause if the connection fails
EventLog. writeentry (E. Message );
Return;
}
// Start the transaction
Sqltransaction TRAN = conn. begintransaction ();
Sqlcommand comm = new sqlcommand ();
Comm. Transaction = Tran;
Comm. Connection = conn;
Try
{
// Obtain the admission ticket and exam number from the XML file name
String temp = Name. substring (0, name. Length-4 );
String [] tempxmlname = temp. Split ('-');
// Admission ticket number
String c_zhunkaozhm = tempxmlname [0]. tostring ();
// Exam ID
String c_shijuanbh = tempxmlname [3]. tostring ();
// SQL statement
String strsqlinsert = "insert into t_datiqk
(C_zhunkaozhm, c_shijuanbh, c_timubh, c_timulx, c_fenzhi, c_geshilx, c_wentims, c_daan, c_huidada, c_datisj, c_zhe
Ngque) Values
(@ C_zhunkaozhm, @ c_shijuanbh, @ c_timubh, @ c_timulx, @ c_fenzhi, @ c_geshilx, @ c_wentims, @ c_daan, @ c_huidada, @ c_da
Tisj, @ c_zhengque )";
// SQL Parameters
Sqlparameter Param;
// The data extracted from the circular XML file
For (INT I = 0; I <Ds. Tables [0]. Rows. Count; I ++)
{
Comm. Parameters. Clear ();
Comm. commandtext = strsqlinsert; // SQL statement
Param = new sqlparameter ("@ c_zhunkaozhm", sqldbtype. varchar); // Admission Ticket No.
Param. value = c_zhunkaozhm;
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_shijuanbh", sqldbtype. varchar); // Exam ID
Param. value = c_shijuanbh;
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_timubh", sqldbtype. varchar); // question No.
Param. value = Ds. Tables [0]. Rows [I] ["c_bianhao"]. tostring ();
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_timulx", sqldbtype. INT); // question type
Param. value = convert. toint32 (Ds. Tables [0]. Rows [I] ["c_timulx"]);
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_fenzhi", sqldbtype. Float); // score
Param. value = convert. tosingle (Ds. Tables [0]. Rows [I] ["c_fenzhi"]);
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_geshilx", sqldbtype. INT); // format type
Param. value = convert. toint32 (Ds. Tables [0]. Rows [I] ["c_geshilx"]);
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_wentims", sqldbtype. varchar); // Problem Description
Param. value = Ds. Tables [0]. Rows [I] ["c_wentims"]. tostring ();
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_daan", sqldbtype. INT); // correct answer
Param. value = convert. toint32 (Ds. Tables [0]. Rows [I] ["c_zhengqueda"]);
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_huidada", sqldbtype. INT); // The examinee answers
Param. value = convert. toint32 (Ds. Tables [0]. Rows [I] ["c_daan"]);
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_datisj", sqldbtype. datetime); // Answer time
Param. value = convert. todatetime (Ds. Tables [0]. Rows [I] ["c_datisj"]);
Comm. Parameters. Add (PARAM );
Param = new sqlparameter ("@ c_zhengque", sqldbtype. INT); // check whether the parameter is correct.
Param. value = convert. toint32 (Ds. Tables [0]. Rows [I] ["c_zhengque"]);
Comm. Parameters. Add (PARAM );
Comm. executenonquery (); // execute the update
}
Tran. Commit ();
// Delete the XML file after the scan is successful
If (file. exists (filename ))
{
File. Delete (filename );
}
}
Catch (exception ex)
{
// Roll SQL operations
Tran. rollback ();
// Obtain the exception information
MSG = ex. message;
}
Finally
{
Conn. Close ();
}
// Write operation information or exception information to the log (the log can be seen in the System Event Viewer)
EventLog. writeentry (MSG );
}
/// <Summary>
/// Scan objects in a specific path cyclically
/// </Summary>
/// <Param name = "filepath"> </param>
Private void scanfile (string filepath)
{
// Create a directoryinfo instance
Directoryinfo dirinfo = new directoryinfo (filepath );
// Obtain the file list of the source directory
Fileinfo [] files = dirinfo. getfiles ();
// Cyclically parse the file
For (INT I = 0; I <files. length; I ++)
{
// Determine whether the file suffix is XML
String Postfix = files [I]. extension;
// Obtain the full path
String filenme = files [I]. fullname;
// Get the file name
String name = files [I]. Name;
If (Postfix = ". xml ")
{
This. insertdata (filenme, name );
}
}
}
}
}
3. Add the installer to the Service Application
If you want to install Windows service.exe, you can install gradeservice.exe in different ways.
First, we need to add an installer to Windows service. Right-click the design view and select add installer. Vs will add projectinstaller for us. CS, and add components serviceinstaller1 and serviceprocessinstaller1 to projectinstaller. Now let's modify their attributes to control service installation and startup options. In the project installer design view, select serviceprocessinstaller1 and select the account attribute as LocalSystem to start the account service. If you want the service to be automatically started when the system starts, select the starttype attribute of serviceinstaller1 as automatic. If it is manually started, select manaul.
Next, we need to install service. we need to use intallutil.exe, which is located in C:/Windows/Microsoft. net/framework/v2.0.50727. click the Start menu, select "run", Enter cmd in the run dialog box, enter the command line window, and enter CD:/Windows/Microsoft. net/framework/v2.0.50727, enter this directory, and then enter installutil F:/project/Examination System/project code/service/gradeservice/bin/debug/gradeservice.exe, the content behind installutil is the path of the executable program generated by our project, which can be modified according to your actual situation.
If you set starttype of serviceinstaller1 to automatic, the service is running after the service is installed. If starttype is manual, you need to start it manually. Now, go to "service". To open "service", click "start", point to "Settings", and click "Control Panel ". Click "performance and maintenance" and "Management Tools", and then double-click "service ". You should be able to see our service gradeservice. Here, we can start, shut down the service, and set the Service Startup type. Then, let's see if the service has correctly written logs. We need to go to the Event Viewer. To open the Event Viewer, click Start and point to settings ", click control panel ". Click performance and maintenance, click management tools, and double-click event viewer ". As shown in, our message has been successfully written to the system log ,.
4. Minor problems found during the use of Windows Service
In the use of Windows service, because of some variables, do not want to die, want to save in the configuration file, so added a configuration file for the sample service, called app. config. Some keys are defined, such as <add key = "sqlconnstring" value = "Data Source = (local); database = kaoshi; user id = sa; Password = 780910; "/>. However, it is found that if the service has been installed and the key value in APP. config is modified without affecting the service, Windows servcie still runs according to the key value before the app. config file is modified. I wonder if other siblings have encountered this situation.
5. How to control the self-created Windows Service in Asp.net)
Windows service can be controlled in Asp.net. You can control the Windows Service of the server in a web project built in Asp.net. However, there are two prerequisites.
1. Add reference system. serviceprocess. dll in the web project solution Resource Manager;
Then in. CS
Using system. serviceprocess;
Then write the code in the event:
Servicecontroller SC = new servicecontroller ("gradeservicecontrller"); // create a service control object
If (SC. Status = servicecontrollerstatus. Stopped)
{
SC. Start (); // start the service
}
2. Simulate an administrator user in Web. config.
For example, admin (belongs to the Administrator group .)
As follows:
<Configuration>
<System. Web>
<Identity impersonate = "true" username = "admin" Password = "admin"/>
</System. Web>
</Configuration>