Поддержка  •  Дневник  •  Без рекламы  •  О сайте  •  Реклама  •  Поставить баннер  •  Fleshlight  •  Прислать  •  Хроника  •  Translate Гости: 9    Участники: 1 Авторизация Авторизация   Регистрация 
Метод Научного Тыка
RULVEN
Поиск  
Blackball iMag | интернет-журнал
Каталог


Начало » Разработка ПО » Develop and Install a Windows Service in C#
Мне повезёт!

Develop and Install a Windows Service in C#


Добавлено: Пн 16.11.2020 • Sergeant
Источник: источник
Просмотров: 607
Комментарии: 0


What is a Windows Service

  • Enables you to create long-running executable applications that run in their own windows session.
  • Can be automatically started when the computer boots, can be paused and restarted without any user interaction.
  • Easily installable by running the command line utility InstallUtil.exe and passing the path to the service's executable file.

Why a Windows Service?

One of the most common requirements of some businesses is long-running scheduled jobs based on some time interval. For example: sending a newsletter everyday afternoon or send an email alert to the customer for every one hour.

So building a Windows Service could be one of the reliable solutions to do the goal that can do the required job in the behind the scenes without interfering others users on the same computer.

Introduction

This article explains a step-by-step process of developing and installing a Windows Service to do a scheduled job based on a time interval.

Open Visual Studio and from the menus select "File" -> "New" -> "Project...".

A New Project window will open. Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the right hand side and name the project "TestWindowsService" as shown in the following screenshot.

After you click "OK", the project will be created and you will see the design view of the service as shown in the following screen. Right-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or any other name that you want to give it. Then click “click here to switch to code view”.

In the code view, you can see two methods called OnStart() and OnStop(). The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.

Right-click the TestWindowService project, add a new class and name it "Library.cs". This class will be useful to create the methods that we require in the project. If your TestWindowService is a big project, you can create a ClassLibrary project and reference it to your TestWindowService.

Library.cs

Make the class public and declare it as a Static class.

Create a log method (WriteErrorLog) to log the exceptions.

Create one more log method (WriteErrorLog) to log the custom messages.

Scheduler.cs

Now return to our Scheduler.cs file and declare a Timer.

Write the following code in the OnStart() method and timer1_Tick():

Write the following code in the OnStop() method:

Scheduler.cs [Design]

Now return to the Scheduler.cs [Design] and right-click on the editor window then click "Add Installer".

Then you can see that there will be a new file called "ProjectInstaller.cs" as shown in the following.

Right-click on the "serviceInstaller1" and click "Properties".

Change the ServiceName to "Test Windows Service" (or your own name) and StartType to "Manual" (or you can choose "Automatic" if you need this service to be automatic).

Right-click the serviceProcessInstaller1, go to the properties window and change "Account" to "LocalSystem".

Build the project to see the .exe file at the location where you created the solution.

That's all. Your Windows Service is all ready to install in your machine.

Installing the Windows Service

Go to "Start" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" then click "Developer Command Prompt for VS2012".

Type the following command:

cd

in my case it is:

cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug

Next type the following command:

InstallUtil.exe “TestWindowService.exe”

and press Enter.

Here you go, the TestWindowService is installed successfully.

How to start the Windows Service

Since we chose StartType = Manual, we must start the Windows Service manually by visiting the "Services and Applications" window in the computer.

Select the Test Windows Service and click "Start" to start the service. Go to the "TestWindowService.exe" location to see the logs.

LogFile.txt

Since we are tracking our Windows Service by writing some logs to a .txt file called LogFile.txt, we can test the working condition of our Windows Service by looking at this log file.

As you can see in the preceding screen, you can find the LogFile.txt file at the physical location that your TestWindowService solution exists.

Click the LogFile.txt to see the logs, whether our service is doing the job that we set it to do for every 30 seconds.

If you look at the preceding log file, we can prove that our Windows Service is running and doing the job that we wanted on a 30 seconds interval.

Stop the Windows Service

To stop the Windows Service, just click "Stop" link in the Services window by selecting our TestWindowService.

Logfile after stopping our service:

Type the following two commands in the "Developer Command Prompt for VS2012" to uninstall the TestWindowService.exe.

  1. cd
    and press Enter. In my case it is:
    cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug
  2. InstallUtil.exe /u “TestWindowService.exe”
    And press enter.
    After executing the preceding commands, the TestWindowService will be uninstalled from your computer.

Summary

In this article, I explained how to develop a Windows Service and install it using InstallUtil.exe from a command prompt.

I believe that I have explained each step clearly that can be easily understandable for a beginner to develop and install a Windows Service.



Мне нравится 0   Мне не нравится 0



Комментарии

Чтобы добавить видео с YouTube, нужно написать [@youtube=xxxxx] , где xxxxx – ID видео.


Комментарии: 0
Нет ни одного комментария.
RSS-лента
Поделиться ссылкой:
Мясной рулет из фарша с яйцом Мясной рулет из фарша с яйцом
12 бесподобных рецептов свиных ребрышек в рукаве в духовке 12 бесподобных рецептов свиных ребрышек в рукаве в духовке
Виски Laphroaig — элитный напиток из Шотландии Виски Laphroaig — элитный напиток из Шотландии
Зачем нужен eSIM. Как это работает и почему об этом так много говорят Зачем нужен eSIM. Как это работает и почему об этом так много говорят
Какой оптимальный объём оперативной памяти? Какой оптимальный объём оперативной памяти?
Несоответствия исторических пластов Windows 11 — если копнуть, на дне сохранились даже элементы Windows 3.1 Несоответствия исторических пластов Windows 11 — если копнуть, на дне сохранились даже элементы Windows 3.1
Грог: рецепт в домашних условиях, правила приготовления Грог: рецепт в домашних условиях, правила приготовления
Кто такой архитектор ПО и как им стать Кто такой архитектор ПО и как им стать
Неподходящие сексуальные стимулы Неподходящие сексуальные стимулы
Если завтра призыв

Новое
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник 2 дня назад, 09:08
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
30 вопросов на собеседовании фронтенд разработчика Пн 15.04.2024
30 вопросов на собеседовании фронтенд разработчика
15 соусов для креветок, которые ты захочешь приготовить Сб 13.04.2024
15 соусов для креветок, которые ты захочешь приготовить
10 простых рецептов рыбы в кляре Пт 12.04.2024
10 простых рецептов рыбы в кляре
2 простых рецепта алкогольного пунша в домашних условиях Пт 12.04.2024
2 простых рецепта алкогольного пунша в домашних условиях
20 рецептов соуса барбекю, которые готовятся проще простого Пт 12.04.2024
20 рецептов соуса барбекю, которые готовятся проще простого
8 лучших рецептов мегрельского соуса Пт 12.04.2024
8 лучших рецептов мегрельского соуса
15 лёгких рецептов соуса Унаги в домашних условиях Пт 12.04.2024
15 лёгких рецептов соуса Унаги в домашних условиях
Ср 10.04.2024
Секреты здоровых ногтей: Уход и питание для красивого маникюра
High performance object-oriented data access with Dapper Ср 10.04.2024
High performance object-oriented data access with Dapper
Книги
Coding clean, reliable, and safe REST APIs with ASP.NET Core 8 3 дня назад, 10:09
Coding clean, reliable, and safe REST APIs with ASP.NET Core 8
Год: 2023
Building IoT Visualizations using Grafana Вт 09.04.2024
Building IoT Visualizations using Grafana
Год: 2022
Getting Started with Grafana Вт 02.04.2024
Getting Started with Grafana
Год: 2022
Prometheus: Up & Running Вт 26.03.2024
Prometheus: Up & Running
Год: 2018

Разработано на основе BlackNight CMS
Release v.2024-04-19
© 2000–2024 Blackball
Дизайн & программирование:
О сайтеРеклама
Visitors
Web-site performed by Sergey Drozdov
BlackballРекламаСтатистикаПоддержка | МузыкаПлейлистыКиноВидеоИгрыАудиоПрограммыСтатьиКартинкиЮморФорумДневник сайтаПрислать контент