How Windows service services is installed in Visual Studio 2012

Source: Internet
Author: User



A Windows Service application is a program that runs in the background of the operating system for a long time, and it is particularly suitable for a server environment that does not have a user interface and produces no visual output, and any user output is written back into the Windows event log. When the computer starts, the service begins to run automatically, and they don't want the user to be logged on.



You can view the services in an existing system by selecting the menu "Start"-〉 "Control Panel"-〉 "System and Security"-〉 "Administrative Tools"-〉 "services", such as:






Create a Window service



Create a new Window service item MyService, such as






Drag a Timer object from the Component table in the Toolbox to the View Designer.



Set the Timer property to enable the True,interval property to be 3000 milliseconds



Double-click the Timer event to add an event


Background code
   public partial class Service1: ServiceBase
    {
        public Service1 ()
        {
            InitializeComponent ();
        }

        protected override void OnStart (string [] args)
        {
            // TODO: Add code here to start the service.
         }

        protected override void OnStop ()
        {
            // TODO: Add code here to perform the shutdown required to stop the service.
         }

        private void timer1_Elapsed (object sender, System.Timers.ElapsedEventArgs e)
        {

        }
    }
public partial class Service1: ServiceBase
    {
        public Service1 ()
        {
            InitializeComponent ();
        }
        protected override void OnStart (string [] args)
        {
            // TODO: Add code here to start the service.
            string state = DateTime.Now.ToString ("yyyy-MM-dd hh: mm: ss") + "Start";
            WriteLog (state);
        }
        protected override void OnStop ()
        {
            // TODO: Add code here to perform the shutdown required to stop the service.
            string state = DateTime.Now.ToString ("yyyy-MM-dd hh: mm: ss") + "Stop";
            WriteLog (state);
        }
        private void timer1_Elapsed (object sender, System.Timers.ElapsedEventArgs e)
        {
            WriteLog (DateTime.Now.ToString ("yyyy-MM-dd hh: mm: ss"));
        }
        public void WriteLog (string str)
        {
            using (StreamWriter sw = File.AppendText (@ "c: \ service.txt"))
            {
                sw.WriteLine (str);
                sw.Flush ();
            }
        }
    } 


where OnStart and OnStop are the server start and stop, after the event operation method, Writelog is the operation method;



Switch the service program Service1.cs to view mode, right-click Design view to select the "Add Installer" option, and then automatically add a ProjectInstaller.cs in the project



Set the ServiceInstaller1 component properties,



Servicename=myservicelog Install server name;



Starttype=automatic Boot automatically



Design the attribute account=localsystem of ServiceProcessInstaller1;



Run compilation, a simple Windows service has been developed to complete



Note: If the file path in the code is written as "Service.txt", then the file is saved in the C:\WINDOWS\system32 folder.



Installing the Window Service



Install command: InstallUtil.exe MyServiceLog.exe



InstallUtil exists path is: C:\WINDOWS\Microsoft.NET\Framework\. NET version number



Copy the InstallUtil.exe in the C:\WINDOWS\Microsoft.NET\Framework\ version number path to the Bin/debug or Bin/release folder and run the command directly in the Command line window



InstallUtil.exe MyServiceLog.exe, register this service in the system and make it a suitable registration key, such as:



Then, in the Window service list, start the Myservicelog service



Uninstalling the Window service



Command: InstallUtil.exe myservicelog.exe/u



If you modify this service, but the path does not need to re-register the service, directly stop the service, and then overwrite the original file with the new file, if the path changes, you should uninstall the service, and then reinstall the service.



Window Service Application Architecture



The. NET Framework provides more support for Windows services under namespace System.ServiceProcess.



The include classes are as follows:



ServiceBase base class for all window services



ServiceController an instance of this class represents a specific Windows service



Servicecontrollerpermission used to control the use rights of ServiceController



ServiceInstaller used to perform the installation of Windows services



ServiceProcessInstaller is used to perform the installation of a Windows service, unlike the above class, which can represent a process that can execute a Windows service.



ServiceBase class



Derived from ServiceBase when a service class is defined in a service application. Any useful service will override the OnStart and OnStop methods. For other features, you can override OnPause and OnContinue with specific behaviors to respond to changes in service status.



A service is a long-running executable file that does not support the user interface and may not run under the logged-on user account. The service can run without any user logging on to the computer.



By default, the service runs under the system account, which differs from the administrator account. You cannot change the permissions of the system account. Alternatively, you can use ServiceProcessInstaller to specify the user account that will be used when the service is run.



An executable file can contain multiple services, but each service must contain a separate serviceinstaller. The ServiceInstaller instance registers the service in the system. The Setup program also associates each service with an event log that you can use to log service commands. Themain ()function in the executable defines which services should run. The current working directory of the service is the system directory, not the directory where the executable file resides.



When a service is started, the system locates the appropriate executable file and runs the service's OnStart method, which is contained within the executable file. However, running the service is not the same as running the executable file. The executable file loads the service only. Services are accessed through the Service Control Manager (for example, start and stop).



When you first call start on a service, the executable calls the constructor of the ServiceBase derived class. The OnStart command processing method is called immediately after the constructor executes. After the first load of the service, the constructor does not execute again, so it is necessary to separate the processing performed by the constructor from the processing performed by the OnStart . Any resources that can be freed by OnStop should be created in OnStart . If the service starts again after OnStop frees the resource, creating the resource in the constructor will prevent these resources from being created correctly.



The Service Control Manager (SCM) provides a way to interact with the service. You can use SCM to pass start, stop, pause (pause), continue (Continue), or custom commands to the service. The SCM uses the values of CanStop and canpauseandcontinue to determine whether the service accepts a stop, pause, or Continue command. Stop, pause, or Continue is enabled in the SCM context menu only if the corresponding property CanStop or canpauseandcontinue in the service class is true . If enabled, the corresponding command is passed to the service and calls OnStop,OnPause , or OnContinue. If CanStop, CanShutdown, or canpauseandcontinue are false, even if the appropriate command-handling method (such as OnStop) has been implemented, Will not be dealt with.



You can use the ServiceController class to programmatically implement the functionality that SCM uses to implement the user interface. Tasks available in the console can be handled automatically. If CanStop,canshutdown , or canpauseandcontinue are true, the corresponding command-handling method has not been implemented (such as OnStop), the system throws an exception and ignores the command.



You do not have to implement OnStart,OnStop , or any other method in ServiceBase . However, the behavior of the service is described in OnStart , so at least the member should be rewritten. The service name of the service must be set in themain ()function of the executable file. The service name set inmain ()must exactly match the ServiceName property of the service installer.



You can use InstallUtil.exe to install services in the system.



You can refer to the literature: Http://msdn.microsoft.com/zh-cn/library/system.serviceprocess.servicebase (vs.80). aspx



How Windows service services is installed in Visual Studio 2012


Related Article

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.