Working with Windows Service Using VS 2005

本文介绍如何使用Visual Studio 2005创建、安装及设置Windows服务。文章详细讲解了从创建服务项目到构建安装程序的全过程,并演示了如何通过服务控制管理器启动已安装的服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Abstract

In this article, I will describe how to implement, setup, install Windows Services with the help of snapshots.

Introduction

A Windows Service is a program which runs continuously in the background of an Operating System. It was formerly known as NT services. Window service internally uses the Service Control Manager (SCM) of the operating system. A service must be installed in an SCM database before it can be launched. SCM controls the entire lifetime of each installed service.

Implementing Windows services has become the choice of the current era of business as it requires minimum human intervention after deployment and gives long running functionality. We also say Window service application works as an Engine; once started it will keep running until the machine shuts down or gets some abnormal error.

Building a Windows Service

Create a Windows Service project in Visual Studio 2005 as given below:

File >> New >> Project

It will open the New Project window. Choose the following settings:

  • Project types: C# >> Windows
  • Visual Studio installed templates: Windows Service
  • Name: MyService

Specify the location for the solution and let the solution name be MyService. Select the check box for "create directory for solution."

Figure 1 – Creating new Windows service project using Visual Studio 2005 IDE

Click OK to create the solution and project. The IDE will automatically add a Service1.cs class file in the project MyService; rename Service1.cs into MyService.cs. Switch to the code view of MyService.cs and open the OnStart function of the MyService class. Add the following codes in the OnStart function:

protected override void OnStart(string[] args) { // TODO: Add code here to start your service. const Int32 iTimer_Interval = 60000; Timer oTimer; System.IO.File.AppendAllText("C:\\MyLog.txt", "MyService has been started at " + DateTime.Now.ToShortTimeString()); System.Threading.TimerCallback tDelegate = EventAction; oTimer = new System.Threading.Timer(tDelegate, this, 0, iTimer_Interval);}

Next, implement EventAction procedure in the MyService class. Note that the EventAction is the procedure which is to be fired/called at each timer interval of 60 seconds raised by Timer implemented in OnStart function above. For a simple example, we will implement to write the current time in a text file MyLog.txt in C drive. Add the following code in the MyService class for EventAction procedure:

public void EventAction(object sender) { System.IO.File.AppendAllText("C:\\MyLog.txt", "MyService fires EventAction at " + DateTime.Now.ToShortTimeString());}

Now we need to add installer components in the service project to set service setup properties. Installer components provided in Visual Studio automatically create Operating System environment objects like registry keys, Windows services control manager event handlers, executables for installation utilities when installing a service application, SCM initialization, etc.

To Add Installer in the Windows Service

Open the MyService.cs file in design view. Right click on the form and choose Add Installer in the pop up menu:

This will add a new file ProjectInstaller.cs with two controls, ServiceProcessInstaller1 and ServiceInstaller1, in the project. Select ServiceProcessInstaller1 and press F4 to open its properties window. Set the Account type to LocalSystem.

Now select the ServiceInstaller1 control and press F4 to go to its properties window. Set the ServiceName as "MyService" and StartType as "Automatic." Setting StartType to automatic will automatically start the service (after installation) whenever the computer restarts.

Build the MyService project. If the build is successful, then we are ready with the service. Now to install this service in the system, we need an installer/setup file. So we will create and add a setup project for the service in the current solution through which we can install/uninstall the service.

Building a Setup for the Windows Service

In the solution "MyService," follow the steps given below to create a setup project.

File >> Add >> New Project

It will open the Add New Project window. Choose the following settings:

  • Project types: Other Project Types >> Setup and Deployment
  • Visual Studio Installed Templates: Setup Project
  • Project Name: MyServiceSetup
  • Click OK to create the project. The setup project MyServiceSetup will be added in the solution and IDE will show you the file system window for the setup.

Right click on the project MyServiceSetup and choose View >> Custom Actions from the pop up menu. It will open the Custom Actions settings window for the setup deployment. Right click on the Custom Actions Node and choose "Add Custom Actions."

After clicking on "Add Custom Actions" a window will appear to select the item for the deployment.

Double click on the "Application Folder." The "Add Output" button will be enabled now. Click on it to open the "Add Project Output Group" window.

In this window, choose the "Primary Output" under MyService and Click the "OK" button. You will see that a new entry Primary output from MyService (Active) in the parent "Select Item in Project" window. Click OK to complete the custom settings.

Now Build the MyServiceSetup project. If the build is successful, then you can find MyServiceSetup.msi file in …\MyServiceSetup\Debug folder.

Installing Windows Service using IDE

You can use setup file MyServiceSetup.msi to install/uninstall the service MyService on any computer. Also you can use Visual Studio 2005 IDE to install the service using setup project. I prefer to use IDE to install/uninstall services as it is convenient during implementation and debugging.

To install MyService using Visual Studio 2005 IDE, right click on the MyServiceSetup project in the solution explorer and choose Install in the pop-up menu.

It will open the window installer wizard. Click Next button and specify the installation folder location in the folder location text box. Click Next button. It will show you the confirmation window. Click Next to start the installation. It will show you the installing status and then completion message window. Now the service should be installed in the machine. Let us find and start the service as given in the next section.

Starting the Installed Windows Service

Reach the installed Services following any of the methods given below.

Open Service Control Manager: Control Panel >> Administrative Tools >> Services.

OR

Right click on My Computer, choose Manage. It will open the Computer Management window. In the tree view, open Services and Applications and click Services.

OR

In the Visual Studio 2005 IDE, open Server Explorer by pressing CTRL+ALT+S and choose node Services under the machine name of Servers tag.

Find the MyService in the list. Right click on it and choose Start to start the service.

Now the service MyWinService has been started and its status should be changed to "Started" in the list. Remember that this sample service is implemented to write log time in a text file "C:\MyLog.txt". For the confirmation of the accuracy of service, you can verify the existence of file. The service should write the current time in the file MyLog.txt at each interval of 60 seconds. If it is so, then we are sure that service is performing as per the implementation.

Worker Services are a type of .NET Core application that can be hosted as a background service on Windows or Linux machines. To deploy a Worker Service from Windows to Linux, you can follow these steps: 1. Build the Worker Service Build the Worker Service using the .NET Core SDK on Windows using the following command: ``` dotnet publish -c Release -r linux-x64 ``` This command will create a release build of the application for the Linux x64 architecture. 2. Copy the published files to Linux Once the build is complete, navigate to the publish folder, which is located in the `bin\Release\net5.0\linux-x64\publish` directory of your application. Copy the entire contents of the publish folder to your Linux machine using a secure file transfer protocol such as SFTP or SCP. 3. Run the Worker Service on Linux Once the files are copied to the Linux machine, navigate to the directory where you copied the files and run the following command to start the Worker Service: ``` dotnet [WorkerServiceName].dll ``` Replace `[WorkerServiceName]` with the name of your Worker Service's main DLL file. This command will start the Worker Service as a background process on your Linux machine. 4. Manage the Worker Service on Linux To manage the Worker Service on Linux, you can use system tools such as `systemd` or `supervisord` to manage the service's lifecycle, including starting, stopping, and restarting the service. For example, to start the service using `systemd`, create a new service file in the `/etc/systemd/system` directory with the following contents: ``` [Unit] Description=[ServiceDescription] After=network.target [Service] WorkingDirectory=[ServiceWorkingDirectory] ExecStart=[ServiceExecutable] Restart=always [Install] WantedBy=multi-user.target ``` Replace `[ServiceDescription]` with a brief description of your service, `[ServiceWorkingDirectory]` with the path to your service's working directory, and `[ServiceExecutable]` with the path to the `dotnet` executable and your Worker Service's main DLL file. Once the service file is created, run the following commands to start and enable the service: ``` systemctl start [ServiceName] systemctl enable [ServiceName] ``` Replace `[ServiceName]` with the name of your service file (without the `.service` extension). This will start the service and configure it to start automatically on system boot.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值