ArticleDirectory
- Append a running Windows Service
Compile a Windows ServiceProgram, Regularly extract records from the database to send emails.
Test environment: Visual Studio 2005 SP1, Windows Server 2003 sp2
1. Create a project
Open vs2005 and create a "Windows Service" project.
2. Add Timer
Expand the "toolbox" and double-click "timer" under the "component" tab. Then, a timer component is added, change "name" to "timemail", "enabled" to "false", and "interval" to "60000 ".
Next, we will do some repair work. I don't know if I have not found a place for the vs2005 bug. This problem does not exist in vs2003: the "timer" just added under "component" should come from "system. timers namespace ", also only" system. timers. timer "can work normally in the Windows service program, but now this timer belongs to" system. windows. forms. timer. So you have to make some modifications. Open the ". Designer. cs" file and modify it as follows:
# Region Generated by the component designerCode //...
/// <Summary>
/// Required methods supported by the designer-do not
/// Use the code editor to modify the content of this method.
/// </Summary>
Private Void Initializecomponent ()
{
This . Components = New System. componentmodel. Container ();
// This. timemail = new system. Windows. Forms. Timer (this. components); original
This . Timemail = New System. Timers. Timer (); // Change
This . Timemail. Interval = 60000 ;
This . Servicename = " Service1 " ; }
# Endregion
// Private system. Windows. Forms. Timer timemail; original
Private System. Timers. Timer timemail; // Change
3. Add a configuration file
Each time the service calls the configuration file, it obtains some basic parameters, so that some changes can directly modify the configuration file without having to modify the code. The new serviceconfig. xml file is stored in the project "bin \ debug:
<? XML version = "1.0" encoding = "UTF-8" ?>
< Serviceconfig >
< Serviceitem
Name = "Sendemail"
Enable = "True"
Elapsed = "60000"
Connectionstring = "Your database connection ..."
SMTP = "SMTP address"
Account = "Your email account ..."
Password = "Your password ..." >
</ Serviceitem >
</ Serviceconfig >
4. The following is the implementation code
Using System;
Using System. Collections. Generic;
Using System. componentmodel;
Using System. Data;
Using System. diagnostics;
Using System. serviceprocess;
Using System. text;
Using System. xml; // Operation configuration file
Using System. IO; // Write logs
Using System. Threading; // Thread used
Namespace Clientwindowsservice
{
Public Partial Class Clientservice: servicebase
{
Public Clientservice ()
{
Initializecomponent ();
}
Protected Override Void Onstart ( String [] ARGs)
{
// Service Startup
This . Timemail. Enabled = True ;
This . Tsendemail ();
}
protected override void onstop ()
{< br> /// service stop
This . timemail. enabled = false ;
}
private void timemail_elapsed ( Object sender, system. timers. elapsedeventargs e)
{< br> /// timer
This . tsendemail ();
}
// enable the new process to send emails
private void tsendemail ()
{< br> thread t = New thread ( New threadstart (sendemail);
T. start ();
}
// Email sending Function
Private Void Sendemail ()
{
Xmldocument Doc = New Xmldocument ();
// Add system. Windows. Forms reference to get the execution directory
String Configfile = System. Windows. Forms. application. startuppath. tostring () + " \ Serviceconfig. xml " ;
Doc. Load (@ configfile );
Xmlelement Root = Doc. documentelement;
Foreach (Xmlnode Node In Root)
{
// If the service is enabled in the configuration file
If (Node. attributes [ " Name " ]. Value = " Sendemail " && Node. attributes [ " Enable " ]. Value = " True " )
{
Try
{
// Read the database and send emails.
}
Catch (Exception error)
{
// Write Error Log
Using (Streamwriter SW = New Streamwriter (system. Windows. Forms. application. startuppath. tostring () + @" " + Datetime. Now. tostring ( " Yyyy-mm-dd " ) + " . Txt " , True , System. Text. encoding. utf8 ))
{
Sw. writeline (datetime. Now. tostring () + " : " );
Sw. writeline (error. tostring ());
Sw. writeline ( " --------------------------------------------- " );
Sw. Close ();
}
}
}
} // End foreach
}
}//End Class
}//End namespace
V. Deployment services
In design mode, right-click --> add installer --> set the account of serviceprocessinstaller1 to LocalSystem
Set starttype of serviceinstaller1 to automatic
Compile
Run: % SystemRoot % \ microsoft.net \ framework \ v2.0.50727 \ installutil.exe D: \ project directory \ bin \ debug \ executable file name .exe in command mode
Every time you need to modify the Windows Service, this requires you to uninstall and reinstall the service. However, it is a good habit to ensure that the service management console is closed before you uninstall the service. If this is not the case, you may encounter problems when uninstalling and re-installing Windows Services. If you only uninstall the service, you can run the installutil command to log out of the service. However, you need to add a/u command to the end.
Debug Windows Services
From another perspective, debugging Windows Services is totally different from a common application. More steps are required to debug Windows Services. Services cannot be debugged as long as they are simply executed in the development environment as you do for common applications. The service must be installed and started first. We have done this in the previous section. To facilitate code tracing and debugging, once the service is started, you must use Visual Studio to append the running process (attach ). Remember, any modifications made to your Windows service must be uninstalled and reinstalled.
Append a running Windows Service
To debug the program, some operating instructions for the Windows Service are attached. These operations assume that you have installed the Windows service and it is running.
1. Use Visual Studio to load this project
2. Click the "debug" menu
3. Click the process menu.
4. Ensure that the system process is selected
5. In the list of available processes, locate the process on your Executable File Name and click to select it
6. Click the Add button.
7. Click OK.
8. Click Close.
9. Set a breakpoint in the timerreceivelapsed method and wait for it to execute
6. Download Code
Http://files.cnblogs.com/linckle/log.rar