Walkthrough: Create a Windows Service Application in the component designer

Source: Internet
Author: User

The steps in this topic guide you through creating a simple Windows service application that writes messages to Event LogsProgram. The basic steps for creating and using a service include:

    • Use the "Windows Service" application template to create a project. This template creates a class inherited from servicebase for you and compiles a large number of basic services.CodeFor example, start the service code.

    • Write the code for the onstart and onstop processes, and rewrite any other methods to be redefined.

    • Add the installer necessary for the service application. By default, When you click the "add installer" Link, a class containing two or more installers will be added to the application: one for the installation process, each of the other installers is used for each associated service included in the project.

    • Generate your project.

    • Create an installation project to install the service and then install it.

    • Access Windows 2000 Service Control Manager and start your service.

First, create a project and set the values required for normal service operation.

Create a service

Create and configure a service
  1. Click Create Project on the File menu ".

    The Create Project dialog box is displayed.

  2. In the list of Visual Basic, Visual C #, Visual C ++, or Visual J # project templates, select the "Windows Service" project and name itMynewservice. Click OK ".

    Note:

    The project template is automatically added fromSystem. serviceprocess. servicebaseThe inherited name isService1.

  3. Click designer to selectService1. Then, in the "properties" window, SetService1Set the servicename and "(name)" attributes"Mynewservice".

  4. Set the autolog attributeTrue.

  5. Click "code" in the "View" menu to open the "Code Editor ". EditMainMethod to create a "mynewservice" instance. When you rename the service in step 3MainMethod. In the Visual C # and Visual J # applications,MainThe method is located in the program. CS and program. js files respectively.

    Visual Basic

    Copy code

    'ToAccess the main methodInVisual Basic,SelectMain from the 'method name drop-down list. This expands the component designer 'generated code region.Shared SubMain ()DimServicestorun ()AsSystem. serviceprocess. servicebase 'change the following lineToMatch. servicestorun =NewSystem. serviceprocess. servicebase () _ {New mynewservice ()} system. serviceprocess. servicebase. Run (servicestorun)End Sub

    C #

    Copy code

     
    Static VoidMain () {system. serviceprocess. servicebase [] servicestorun;// Change the following line to match.Servicestorun =NewSystem. serviceprocess. servicebase [] {NewMynewservice ()}; system. serviceprocess. servicebase. Run (servicestorun );}

    J #

    Copy code

    Public Static VoidMain (string [] ARGs) {system. serviceprocess. servicebase [] servicestorun; servicestorun =NewSystem. serviceprocess. servicebase [] {NewMynewservice ()}; system. serviceprocess. servicebase. Run (servicestorun );}

Add features to a service

In the next section, you will add Custom Event Logs to Windows Services. Event Logs are not associated with Windows Services in any form. Here, the EventLog component is used as an example of the component type that can be added to the Windows service. For more information about Custom Event Logs, see How to: create and remove Custom Event Logs.

Add the Custom Event Log feature to the service
  1. In Solution Explorer, right-click service1.vb, service1.cs, or service1.jsl, and select View designer ".

  2. On the components tab of the toolboxEventLogDrag the component to the designer.

  3. In Solution Explorer, right-click service1.vb, service1.cs, or service1.jsl, and select view code ".

  4. Edit the constructor to define a user event log.

    Visual Basic

    Copy code

    ' To Access the constructor In Visual Basic, Select   New From the 'method name drop-down list. Public   Sub   New () Mybase . New () initializecomponent ()If   Not System. Diagnostics. EventLog. sourceexists ( "Mysource" ) Then System. Diagnostics. EventLog. createeventsource ( "Mysource" ,_ "Mynewlog" ) End   If Eventlog1.source = "Mysource" Eventlog1.log = "Mynewlog"  End   Sub 

    C #

    Copy code

     
    PublicMynewservice () {initializecomponent ();If(! System. Diagnostics. EventLog. sourceexists ("Mysource") {System. Diagnostics. EventLog. createeventsource ("Mysource","Mynewlog");} Eventlog1.source ="Mysource"; Eventlog1.log ="Mynewlog";}

    J #

    Copy code

    PublicMynewservice () {initializecomponent ();If(! System. Diagnostics. EventLog. sourceexists ("Mysource") {System. Diagnostics. EventLog. createeventsource ("Mysource","Mynewlog");} Eventlog1.set _ source ("Mysource"); Eventlog1.set _ log ("Mynewlog");}

Define what happens when the service is started
  • In the Code Editor, findOnstartMethod, and write code to determine the situation that occurs when the service starts running:

    Visual Basic

    Copy code

     
    'ToAccess the onstartInVisual Basic,SelectOnstart from the 'method name drop-down list.Protected Overrides SubOnstart (ByvalARGs ()As String) Eventlog1.writeentry ("In onstart")End Sub

    C #

    Copy code

    ProtectedOverrideVoidOnstart (String[] ARGs) {eventlog1.writeentry ("In onstart");}

    J #

    Copy code

     
    Protected VoidOnstart (string [] ARGs) {eventlog1.writeentry ("In onstart");}

    Note:

    The service application is designed to run for a long time. Therefore, it usually polls or monitors the situation in the system. Monitoring is inOnstartMethod. However,OnstartIn fact, no monitoring is performed. Once a service operation starts,OnstartMethod must be returned to the operating system. It cannot always loop or block. To set a simple polling mechanism, you can use the system. Timers. Timer component. InOnstartYou can set the parameters on the component and set the enabled attributeTrue. Then, the timer will periodically trigger events in the Code. At this time, the service can perform its monitoring work.

Define what happens when the service is stopped
  • In the Code Editor, select from the method name drop-down listOnstopThis process is automatically rewritten when a project is created. Write code to determine what happens when the service is stopped:

    Visual Basic

    Copy code

    Protected Overrides SubOnstop () eventlog1.writeentry ("In onstop .")End Sub

    C #

    Copy code

     
    ProtectedOverrideVoidOnstop () {eventlog1.writeentry ("In onstop .");}

    J #

    Copy code

    Protected VoidOnstop () {eventlog1.writeentry ("In onstop .");}

You can also override the onpause, oncontinue, and onshutdown methods to define further processing of components.

Define other services
  • For the method to be processed, rewrite the appropriate method and define the operation to take place.

    The following code is rewritten.OncontinueSituation of the method era code:

    Visual Basic

    Copy code

    Protected Overrides SubOncontinue () eventlog1.writeentry ("In oncontinue .")End Sub

    C #

    Copy code

     
    ProtectedOverrideVoidOncontinue () {eventlog1.writeentry ("In oncontinue .");}

    J #

    Copy code

    Protected VoidOncontinue () {eventlog1.writeentry ("In oncontinue .");}

When installing Windows Services, you must perform some custom operations, which can be completed by the installer class. Visual Studio can create these installation programs for Windows Services and add them to projects.

Create an installer for the service
    1. In Solution Explorer, right-click service1.vb, service1.cs, or service1.jsl, and select View designer ".

    2. Click the background of the designer to select the service itself, instead of anything about it.

    3. When the design appliance has focus, right-click and click "add installer ".

      By default, add component classes that contain two installers to your project. Name the component projectinstaller, which contains the service installer and the service-related process installer.

    4. In the design view of projectinstaller, click serviceinstaller1 or serviceinstaller1 ".

    5. In the "properties" window, set the servicename attribute"Mynewservice".

    6. Set the starttype attribute to automatic.

    7. In the designer, click serviceprocessinstaller1 (for Visual Basic projects) or serviceprocessinstaller1 (for Visual C # Or Visual J # projects ). Set the account attribute to LocalService. This allows you to install and run the service on a local service account.

      Security considerations

      LocalServiceThe account is used as a non-privileged user on the local computer to display anonymous creden。 to any remote server. Be especially careful when using other accounts, so they have high privileges and increase your risk of malicious code attacks.

Generate a Service Project
    1. In Solution Explorer, right-click your project and select Properties From the shortcut menu ". The "Property designer" of the project appears ".

    2. Select "mynewservice" from the "launch object" list on the "application" page ".

    3. Press Ctrl + Shift + B to generate the project.

After a project is generated, you can deploy it. The installation project will install the compiled project file and run the installation program required to run the Windows service. To create a complete installation project, you need to add the project output mynewservice.exe to the installation project, and then add custom operations to install mynewservice.exe. For more information about the installation project, see the installation project. For more information about custom operations, see Walkthrough: create custom operations.

Create an installation project for the service
    1. In Solution Explorer, right-click solution, point to add, and click New project ".

    2. In the project type pane, select the installation and deployment projects folder.

    3. Select "Installation Project" in the "template" pane ". Name the project myservicesetup. Click OK ".

      The installation project is immediately added to the solution.

Then, output the Windows Service ProjectMynewservice.exeAdd to the installation project.

Add mynewservice.exe to the installation project
    1. In Solution Explorer, right-click "myservicesetup", point to "add", and select "project output ".

      The "add project output group" dialog box appears.

    2. Select "mynewservice" in the "project" box ".

    3. In the list box, select "primary output" and click "OK ".

      The main output project of mynewservice is added to the installation project.

Now add a custom operation to install the mynewservice.exe file.

Add custom operations to the installation project
    1. In Solution Explorer, right-click the installation project, point to view, and select Custom operations ".

      The custom operations editor is displayed.

    2. In the "Custom operations" editor, right-click the "Custom operations" node and select "add custom operations ".

      The "select items in project" dialog box appears.

    3. Double-click "application folder" in the list box to open it, select "main output (activity) of mynewservice", and click "OK ".

      The master output is added to all four nodes in the Custom operation: "Install", "Submit", "rollback", and "Uninstall ".

    4. In Solution Explorer, right-click the "myservicesetup" project and select "generate ".

Install Windows Services
    1. To install idea mynewservice.exe, right-click the installation project in Solution Explorer and select install ".

    2. Complete the steps in the installation wizard. Generate and save your solution.

Start and Stop services
    1. Open the Service Control Manager by performing one of the following operations:

      • In Windows XP and 2000 Professional Edition, right-click my computer on the desktop, and then click manage ". On the "Computer Management" console, expand the "services and applications" node.

        -Or-

      • On Windows Server 2003 and Windows 2000 Server, click Start, point to programs, click Administrative Tools, and then click Services ".

        Note:

        In Windows NT 4.0, you can open this dialog box from the control panel.

      "Mynewservice" is listed in the "service" Area of the window.

    2. Select your service from the list, right-click the service, and click Start ".

    3. Right-click the service and click "stop ".

Verify service event log output
    1. Open "server resource manager" and access the "event log" node. For more information, see How to: use Event Logs in server resource manager.

      Note:

      Visual Studio Standard Edition does not provide "Windows Service" templates and related functions. For more information, see Visual Studio.

    2. Find the list of mynewlog and expand it. You should see the items that the Service performs operations.

Uninstall Service
    1. Open "Control Panel" on the "Start" menu, click "Add/delete programs", find your service, and click "Uninstall ".

    2. You can also right-click the program icon of the. MSI file and select "Uninstall" to uninstall the program.

      Note:

      If the service is installed on Windows 2000, you must restart the system to reinstall the service. In Windows 2000, the service is not completely deleted before the system restarts.

Subsequent steps

You can use the servicecontroller component to send commands to installed services. UsageServicecontrollerFor more information about the control, see Monitoring Windows Services.

You can use the installer to create event logs when installing the application, instead of creating event logs when running the application. In addition, when the application is uninstalled, the event log is deleted by the installer. For more information, see Walkthrough: Install the event log component.

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.