Windows Service Programming in C# .Net For Coders & Students

Introduction to Windows Service programming and cranky details of debugging services in C# .Net.
4.5 (52 ratings) Instead of using a simple lifetime average, Udemy calculates a
course's star rating by considering a number of different factors
such as the number of ratings, the age of ratings, and the
likelihood of fraudulent ratings.
5,961 students enrolled
$19
$20
5% off
Take This Course
  • Lectures 27
  • Length 1.5 hours
  • Skill Level All Levels
  • Languages English
  • Includes Lifetime access
    30 day money back guarantee!
    Available on iOS and Android
    Certificate of Completion
Wishlisted Wishlist

How taking a course works

Discover

Find online courses made by experts from around the world.

Learn

Take your courses with you and learn anywhere, anytime.

Master

Learn and practice real-world skills and achieve your goals.

About This Course

Published 11/2015 English

Course Description

This course teaches you how to create Windows Service which are a key component of Windows operating system.

The course is divided in various sections.

In section one, you will learn the definition and anatomy of a Windows Service. You will also understand the difference between a Windows Service and other application types like Windows Forms.

In section two you will create a Windows Service project, and utilize installutil to install or uninstall a service.

After this you will open the Event Viewer to see the events... generated by your newly born service.

In section three you will learn how to debug a Windows Service.

You will also see how to integrate Log4Net logging library into your service project. Its a free & open source library and it lets you generate rolling log file.

In the next section you will look into a few real world scenarios like a file synchronization service and a periodic data update service. You will also learn how to create an installer project for easy setup and installation of a Windows Service.

In the final section we are going to create an admin application for a Windows Service. This application will have the ability to start/stop a service and get service status as well.

Please note that this course will not freeze in time, I will keep adding interesting and useful ideas with the passage of time.

I learned Windows Service programming the hard way, on my own. You sir! can take advantage of my experience and learn it quickly by joining this course. Sign up and I will see you inside!

What are the requirements?

  • Basics of C# .Net programming language

What am I going to get from this course?

  • Create new Windows Services
  • Debug Windows Services
  • Use Log4Net logging library

What is the target audience?

  • Fresh or experienced programmers with little to no experience in Windows Service programming
  • Programming students who want to learn how background services work

What you get with this course?

Not for you? No problem.
30 day money back guarantee.

Forever yours.
Lifetime access.

Learn on the go.
Desktop, iOS and Android.

Get rewarded.
Certificate of completion.

Curriculum

Section 1: Introduction to Windows Services
02:24

Hello and welcome to my course... creating Windows Services using C# .Net.

In this course... you will learn a very useful skill that is creating and debugging Windows Service applications.

I am Naeem Akram, I have done Windows Service programming as a full time job for several years.

My course is divided in various sections.

In section one, you will learn the definition and anatomy of a Windows Service. You will also understand the difference between a Windows Service and other application types like Windows Forms.

In section two you will create a Windows Service project, and utilize installutil.exe to install or uninstall a service.

After this you will open the Event Viewer to see the events... generated by your newly born service.

In section three you will learn how to debug a Windows Service.

You will also see how to integrate Log4Net logging library into your service project. Its a free & open source library and it lets you generate rolling log file.

In the next section you will look into a few real world scenarios like a file synchronization service and a periodic data update service. You will also learn how to create an installer project for easy setup and installation of a Windows Service.

In section 5 we are going to create an admin application for a Windows Service. This application will have the ability to start/stop a service and change the configuration file of the service.

Section 6 was added by popular demand. In this section I will show you how to create a setup installer for your Windows Service. I am going to use Inno Setup for this purpose.

Please note that this course will not freeze in time, I will keep adding interesting and useful ideas with the passage of time.

I learned Windows Service programming the hard way, on my own. You sir! can take advantage of my experience and learn it quickly by joining this course.

01:45

So now I am going to explain some very important concepts about Windows services.

First, open the services control manager SCM.(+pan into Run and show hint on screen but don’t go on with narration).

First of all, the columns name and description are self explanatory.

The column status shows the current status of the service, which might be any of the those shown on the screen.

Stopped

Started

Paused

Pending Start

Pending Stop

Pending Pause

The column Startup Type tells whether a service is started automatically by Windows or it is stopped, it is possible to disable a service as well and in that case this column will contain the word “Disabled”. In short the four possible values of a service start up type are shown on screen. That is

Manual

Automatic

Disabled

Automatic(Delayed Start)

The last column “Log On As” shows the username of the Windows account a particular service is going to use. Possible values of this field are:

Local System

Network Service

Local Service

Specific User

More information can be found on the link mentioned in the description of this lecture. https://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceaccount(v=vs.110).aspx

Having a specific set of credentials to logon makes it possible for Windows Services to start before a human user logs-in and stay operational even when a human user is gone.

Among these types of login credentials, LocalService is the one with the fewest powers. It’s a non-privileged user on the local machine.

LocalSystem on the other hand is the most powerful type of user and it can do almost anything you want the the machine.

Third type NetworkService is slightly more powerful than LocalService, and it can interact with various network services. Details are not relevant from the perspective of this course so I would prefer not to stress too much on the definition.

We can perform various service operations by clicking on a service entry in SCM and going to the Action menu.

There are some shortcuts on the top left as well.

It is also possible to right click a service and select ‘Properties’ from the dropdown.

The properties dialog not only allows you to start/stop/pause/resume a service, it also shows you the file path from where a specific service is running.

03:48

In this video, I will show you some major differences between Windows Service executables and simple exe files.

Let’s open a console application project

First of all I will press ‘Control+F5’

You see the console application starts working right away

Now let’s go to a Windows Service project and try the same.

Let me explain a couple ‘short things first

OnStart method of a windows service is being shown on the screen

The OnStart method of the service is called by Windows when a user clicks “Start” link on the Service Control Manager

In our demo code, we are writing some text to the debugging console in this method

Let me press ‘Control+F5’ keyboard shortcut once again

Boom! a message box says you can’t run a Windows Service from debugger baby.

This is the first difference

Now let’s head back to the console application project

Inside the main method, I will place a breakpoint on a console dot writeline which prints Hello World!

And I will click ‘Debug’ menu and select the menu item ‘Start Debugging’

You see, the breakpoint is hit instantly

I’ll press F5 so that the application continues execution

Let’s try to do the same with the Windows Service project

I will place a on Debugger dot writeline

Go to ‘Debug’ menu and click ‘Start Debugging’

The same error shows up again

This is difference number two

Finally, let us go to the output directory of our console application

Double click HelloWorld.exe file

You see, the application starts working right away

Let’s go to the output directory of the service project and try to run it by double clicking the .exe file in a similar fashion

Oops! It won’t start dancing to your tunes

This is the third difference

We need to install the service before we can run it

You will learn how to do it in the next section

The differences shown in this video can be downloaded in pdf form through the downloads section of this course. I’ve written these in the description of the lecture as well.

02:44

IMPORTANT: The source code for section 1 can be downloaded here.

In this video, I will show you some major differences between Windows Service executable and simple exe files.

Let’s open a console application project

First of all I will press ‘Control + F5’

You will see the console application starts working right away

Now let’s go to a Windows Service project and try the same.

Let me explain a couple ‘short things first

OnStart method of a windows service is being shown on the screen

The OnStart method of the service is called by Windows when a user clicks “Start” link on the Service Control Manager

In our demo code, we are writing some text to the debugging console in this method

Let me press ‘Control+F5’ keyboard shortcut once again

Boom! a message box says you can’t run a Windows Service from debugger baby.

This is the first difference

Now let’s head back to the console application project

Inside the main method, I will place a breakpoint on a console dot writeline which prints Hello World!

And I will click ‘Debug’ menu and select the menu item ‘Start Debugging’

You see, the breakpoint is hit instantly

I’ll press F5 so that the application continues execution

Let’s try to do the same with the Windows Service project

I will place a on Debugger dot writeline

Go to ‘Debug’ menu and click ‘Start Debugging’

The same error shows up again

This is difference number two

Finally, let us go to the output directory of our console application

Double click HelloWorld.exe file

You see, the application starts working right away

Let’s go to the output directory of the service project and try to run it by double clicking the .exe file in a similar fashion

Oops! It won’t start dancing to your tunes

This is the third difference

We need to install the service before we can run it

You will learn how to do it in the next section

The differences shown in this video can be downloaded in pdf form through the downloads section of this course. I’ve written these in the description of the lecture as well.

4 questions

This quiz is aimed at fortifying the basics of Windows Service programming which you have learned in general.

Section 2: Windows Service Programming Primer
02:00

It’s time! it’s time to create your first Windows Service project cadet and fire up Visual Studio

Hah ha ha ha… OK… <Launch Visual Studio, show splash for split second>

Visual Studio twenty fifteen Enterprise is up, I’ll click ‘File’ menu and select ‘New’, and then ‘Project’

Expand Visual C sharp

Expand Windows

Click ‘Classic Desktop’

Look for Windows Service and select it

Name of solution will be ‘Udemy Windows Service’

When we create a new Windows Service project, Service1.cs file is opened by default

We can see that this file is opened in design view

The code of our Windows Service is going to reside inside this file

First of all, I will like to change the name of this file

In solution explorer, right click the file ‘Service1.cs’

Select menu option ‘Rename’

I will change the name to UdemyWindowsService.cs

VS will ask if you want to rename all references of this service, click Yes

There is another file ‘Program.cs’ in the solution explorer files hierarchy,

don’t worry about it.

Double click on UdemyWindowsService.cs

Now click inside the designer area

On the properties panel, change property ‘ServiceName’ to ‘Udemy Windows Service’

Build the project Ctrl+Shift+B

I hope you remember that we can’t run a Windows Service without installing it

In the next video, I will tell you how to solve this problem.

03:18

I’ve opened the Windows Service project which we created in the last lecture

The file UdemyWindowsService.cs is opened in design view

If you have moved to code view somehow, just goto ‘View’ menu and select ‘Designer’

Now right click in the designer area

Select the menu item ‘Add Installer’

The file ‘ProjectInstaller.cs’ will open in designer view

Your Windows Service is almost ready for the action

We need to change a few properties

First of all, right click click ‘serviceProcessInstaller1’ and select menu item ‘Properties’.

Change the property ‘User’ to LocalSystemAccount

Now right click ‘serviceInstaller1’ and select menu item ‘Properties’.

Set the property ‘Display Name’ to ‘Udemy Demo Service’

Set the property ‘Description’ to something like ‘My hello world Windows Service’

Now go back to ‘UdemyWindowsService.cs’ file in design view

Right click designer area and select ‘Properties’

I am about to tell you a very small but important thing.

The property ‘Service Name’ of your service must have the same value as the serviceInstaller.ServiceName

If this value is different, your service will not work.

Now let’s go to the next lecture and prepare to run our service

01:46

IMPORTANT: Download source code here.

I’ve opened the Windows Service project

I am repeating this step on the start of every video intentionally, to help people who are not watching the course in one go

The file ‘UdemyWindowsService.cs’ is opened in designer view

Right click and select ‘View Code’ from the options

We can see a partial class which is derived from ServiceBase

After the constructor, this class contains overrided methods ‘OnStart’ and ‘OnStop’

The method OnStart is called by the system when the service is started, either by Windows automatically or by a user clicking Start in Service Control Manager

The other method OnStop is called by the system before stopping the service.

Click inside the method OnStart and write following code

EventLog dot WriteEntry. “Udemy Windows Service by naeem is starting.”

Comma, EventLogEntryType dot Information.

Copy the same line of code over to OnStop method.

By default, every Windows Service is capable of writing events to the event log given that it is being run with appropriate permissions.

Now build the service

In the next lecture, we will build your service and run it.

03:07

I have opened the Windows Service solution which we have created and configured in this section so far

Build the project

Open Solution Explorer

Select project ‘UdemyWindowsService’

Click ‘Show All Files’ icon

Expand the ‘bin’ folder

Right click the ‘Debug’ folder

Select option ‘Open Folder in File Explorer’

Look at the contents of the folder

You see an application exe file ‘UdemyWindowsService’

Now click ‘Start Menu’ and type ‘Developer Command Prompt’

For older versions of Visual Studio you can use ‘Visual Studio Command Prompt’

Open the developer command prompt

Now type installutil dot exe space minus i space

Go back to file explorer

Press shift key and right click the UdemyWindowsService.exe file

Click menu option ‘Copy as path’

Now go back to the developer command prompt

Right click the top of the window and from drop down menu select option ‘Paste’

Press enter key.

The command prompt says ‘The transacted install has completed’ this means our service is installed!

(keep command line on screen)Now let’s open service control manager

Look for ‘Udemy Demo Service’ in the list of services

Click the service

And now click ‘Start’ button

The status of the service will change to ‘Started’

The operations buttons on top left will also change from ‘Start’ to ‘Stop this service’ and ‘Restart the service’

Click ‘Stop’ link. The service will stop. The status and operation buttons will change accordingly.

02:32

(close everything else but SCM)Let us take a quick look into Windows Event Log

I will click start button and type Event Viewer and open it

The event viewer can take a few minutes to load the data

Let’s Expand the node ‘Windows Logs’

I’ll Click the sub-item ‘Application’

I will Look for ‘Udemy Windows Service’ in the ‘Source’ column

When I click on an item in the list, the lower half of the window shows some stuff in ‘General’ and ‘Details’ tab

The General tab will have the message your application would’ve written to the Windows event logs.

Now click on the ‘System’ node under ‘Windows Logs’

If you didn’t install this service a long long while ago, you will be able to find an event related to service install near the top of list view.

In our case, I’ve found the event related to service installation. It says ‘A service was installed in the system.‘

1 page

Removing or Uninstalling a Windows Service is a simple operation which can be performed using the same .Net framework utility which we used to install a service. This short document shows you how do just that using InstallUtil -u command.

6 questions

How well do you know your Windows Service code?

Section 3: Windows Service Debugging Techniques
05:31

I will open the Windows Service project which we created in last section

The source files can be downloaded from the downloads section of all videos of section two, three, four, or five

The sources are available on GitHub too, a link is present in the course & video description.

Before we start debugging

Let us add a few lines of code in the ‘OnStart’ method.

I’ve added an integer variable i with initial value zero and a do while loop after it. The loop is simply printing the integer to debug console and incrementing it.

In order to start debugging, we need to add some code which will launch the debugger on run time.

Let’s do it right on top of the OnStart method.

System dot Diagnostics dot Debugger dot Launch

Before starting the build, make sure that debug configuration is selected on top

Now let’s build the service

If you have already installed the service during previous videos, go to service control manager and make sure it is stopped. Otherwise, the build process will fail.

Also, you don’t need to do run InstallUtil again if it’s already there.

The reason is that we installed the service straight from the debug folder and building the project again will simply replace the old files.

If you haven’t installed the service already, take a look at video four of section two and install the service.

Open service control manager, click ‘Udemy Windows Service’ and click the ‘Start’ link

Service start progress dialog shows up

Another dialog with a list of visual studio versions and your open Windows service project has shown up

Click your already opened Windows Service project from the list and click Yes

You see that the control is transferred to the point in your code where you had launched the debugger.

Now you can continue debugging normally, let’s press F ten.

Let’s switch back to Service Control Manager for a second

You see the start service dialog is still up on screen

Let’s switch back to your service code

Make sure that the output console is visible on the bottom of screen, if it is not there already go to ‘Debug’ menu, ‘Window’, and then select ‘Output’.

Let’s pin it permanently and clear it as well.

By pressing F ten key a few times you will hit Write Line statement inside the loop.

in the Output window below, you can see that the string “Value of i is colon zero”

Similarly, we can add a watch to see the value of variable i

Right click i and select ‘Add a watch’ from the drop down

The value of variable i can be seen in the Watch window below

The value can be seen by hovering over the variable i

I will press F five a few more times to see what’s going on

Now press F five

Stop debugger by clicking the stop button on top, you may press Shift + F5

Switch back to ‘Service Control Manager’, most probably a dialog will be on screen already screaming that the service startup failed.

Don’t bother it and press OK

Click your Windows Service and press F five to refresh SCM

The service is now showing as started.

Once you’ve gone through the video, you may remove the Debugger dot launch call

In the next video, I will introduce you to Log 4 Net library.

Log 4 Net is used to generate rolling log files that help immensely in diagnosing problems in production environments.

01:51

In order to use this technique, we need to run as administrator both Visual Studio and Service Control Manager.

Let me do it

[Action – Click Start, right click VS, select “Run as Admin”]

[Action – Minimize “VS”]

[Action – Click Start, type “Services”, right click, select “Run as Admin”]

[Action – Go back to “VS”]

I am going to place a break point in service “Stop” method.

Now I will go to the service control manager and start our Udemy Windows Service

The service has started, now go back to Visual Studio

Click “Debug” menu and select “Attach to Process”

On the dialog box, click a list item in the column “Available Process” and press U

“UdemyWindowsService.exe” will be highlighted

I have expanded the “Process” column so that full process name will be visible

You can see there’s a process “UdemyWindowsService.vshost.exe” right underneath our service process

Don’t let that one confuse you

So, I’ve selected “UdemyWindowsService.exe”

I will click the button “Attach”

[PAUSE] Once the debugger is attached, you’ll see that Visual Studio UI will change to debug mode

Now I will go back to the service control manager and stop the service, the break-point in “Stop” method should be hit.

There you go

It is possible to use this technique in a variety of scenarios.

I suggest you keep this technique in mind when watching the videos in “practical usages” section which comes next

07:21

This slightly lengthy lecture shows you how to add Log4Net library in your Windows service project, how to configure it, and how to use it in code. In just seven minutes, we are going to cover a lot of very useful stuff commonly used in enterprise application software. Contents of the Log4Net config file are given below FYI.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<configSections>

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" allowExeDefinition="MachineToRoamingUser"/>

<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

<section name="UdemyWindowsService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />

</sectionGroup>

</configSections>

<log4net debug="true">

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">

<file type="log4net.Util.PatternString" value=".\ServiceLog.txt"/>

<appendToFile value="true"/>

<rollingStyle value="Size"/>

<maxSizeRollBackups value="10"/>

<maximumFileSize value="10MB"/>

<staticLogFileName value="true"/>

<layout type="log4net.Layout.PatternLayout">

<conversionPattern value="%p %d %r %m %newline"/>

</layout>

<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>

</appender>

<logger name="servicelog">

<level value="DEBUG"/>

<appender-ref ref="RollingLogFileAppender"/>

</logger>

</log4net>

<startup>

<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />

</startup>

</configuration>


05:30

Yet another exciting demo! In this you are going to see your rolling text log file functionality in action. I am also going to show you BareTail which is a cool utility used to watch log files in real time, its very popular among professional programmers.

Section 4: Practical usages of Windows Service
03:21

Welcome to section 4

In this section I am going to show you some real world usages of Windows Services.

In this lecture, we will create a skeleton of a Windows Service which will be capable of reading data in a periodic fashion

A few common examples are, reading data from a website and storing it to a database, reading data from a database and sending an alert if need be etc.

First of all, We are going to use the service project which we’ve created until section three. The source code is already available in download section of this video

We are going to use a system dot threading dot timer for periodic data updates

This timer will be started upon service start and keep firing at set intervals.

First of all, open UdemyWindowsService.cs file and double click in the designer area

Inside the code, I’m going to define a System dot Threading dot Timer member variable on class level

System.Threading.Timer mRepeatingTimer;

Let’s define a class level variable which will be updated by our thread. double mCounter; now set the value of this counter to zero on startup

We also need to define a callback method which will be invoked by this timer

public void myTimerCallback(object objParam)

Let’s write some text to the log file

mLogger. Debug “Value of counter is mCounter plus plus

Now let us go back to OnStart method

Inside this method we will start our thread.

mTimer equals new System dot Threading dot Timer(myTimerCallback comma mTimer comma 1000 comma 1000);

These numbers are in millisecond.

First number tells after how many milliseconds the timer will be fired first time

Second number tells after how many milliseconds the timer will be fired subsequently

We can increase or decrease the duration of the timer by changing these numbers

Now let’s build and see if all is well

We will run this service in next lecture

01:07

Let’s open the service debug folder

I have got the serviceLog.txt file open in BareTail

Its a free software that hot updates the text file as soon as it is changed by your windows service

Let’s start the service

Now I’m going to open the service log file using baretail.

How to generate rolling text log files is explained in section three of this course.

You can see that the log file is updated by the timer again and again

Now you know how to create a periodic data update service, you may use the skeleton shown here in production as well.

06:05

Important: Source code is available in download section

Dear student, now I am going to show you how to make your Windows Service watch for changes on the file system.

We will create a new folder and provide its path to your Windows Service.

Once we write appropriate code, Windows operating system will notify your service every time a file changes in this directory.

The service will get events when a file is created, deleted, changed, or renamed.

First of all, open the Udemy Windows Service project.

Expand solution explorer, expand bin and right click debug folder, select “Open in file explorer”.

Right click in the file explorer and select “New” “Folder”. I will call this folder “Watch Me”.

Now switch back to our service project and open UdemyWindowsService.cs

Go to code view

add namespace System.IO.

using system.io.

We need this namespace for file system watcher.

Next, let’s define a class level member of type FileSystemWatcher.

FileSystemWatcher mFSW;

Go to the end of OnStart method of the service.

If you have the line of code which starts the timer, the one we created in a previous video of this section. Change the thread parameters to 100000.

You can comment the line of code as well. Otherwise, the timer will keep ticking and log file will keep growing which won’t let you see the events related to file system watcher.

Now, back to real work.

Instantiate the file system watcher.

mFSW = new FileSystemWatcher();

We’ll supply the path of the folder which we want to monitor as parameter.

We will also enable raising events by setting a flag like mFSW.EnableRaisingEvents = true;

Lets set another flag to enable monitoring of sub-directories.

mFSW.IncludeSubdirectories = true;

Now let’s add a callback delegate to handle file system events.

mFSW.Created += Visual Studio 2015 says “Press TAB to insert”. I’m cool with that. I’ll press tab.

The VS has automatically created appropriate callback method.

It shows a rename dialog as well, we haven’t used this method anywhere else so I’ll just click ‘Apply’.

Let’s rename the delegate to “MFSW_somethingHappenedToTheFolder”

Click the like bulb and allow VS to rename all references.

At this stage, we can use the same delegate to handle multiple types of events.

For example

mFSW.Changed += MFSW_somethingHappenedToTheFolder;

mFSW.Deleted += MFSW_somethingHappenedToTheFolder;

and

mFSW.Renamed += MFSW_somethingHappenedToTheFolder;

There’s a “NotImplementedException” inside the newly generated method.

Let’s delete it and add some code.

mLogger.Debug(string.Format("{0} - \r\nnFile event for: {1}", e.ChangeType, e.FullPath));

We’re writing the same line to the output console as well.

Let’s build the service to see if everything is okay or not.

Build succeeded, we’re in good shape.

In the next video, we will run this service and see a demo.

03:53

To start with, we need to open the installation folder of our service.

We’ve been doing this through visual studio. Let’s do it another way this time.

Run the service control manager by press windows R and typing services.msc and pressing enter

Find udemy windows service in list of services

Right click and select “Properties”

Look for “Path to executeable”, copy this value.

Launch Run dialog by pressing Windows + R

Paste the file path value

Remove the double quotes from start and end of the path

From the end of path, remove UdemyWindowsService.exe

Now press “Enter”

The debug folder has opened

You can see that the folder “Watch Me” is there

Our service is going to monitor any changes made to this folder.

Next, launch BareTail

If the serviceLog.txt file is already there, drag it over to bare tail

Now I’ll delete the log file from disk

Let's go back to service control manager and close the service properties dialog which we opened earlier

Start Udemy Windows Service

Tuck file explorer on one side and bare tail on the other

You can see a new ServiceLog.txt file has been created by the service

Right click and copy this file

Double click to open the folder “Watch Me”

Right click and paste the file which you copied earlier

You can see that a “Changed” event has shown up in the log file.

The event also contains path of the file

Similarly, launch “Notepad” and type some text.

Now save the file in the folder which is being watched by our service.

I will copy the folder path from explorer window and paste it in file save dialog

FIle name is first.txt

Now you see that three events were fired against new file creation, one “Created” event and two “Changed”.

Let’s go back to the explorer and delete one of the files.

An event “Deleted” is shown in the log file by the service.

Your service can take any action on the files when these events happen.

For example, I once created a password synchronization application. It had a Windows Password Filter which was invoked on system password change, wrote the new password in encrypted form to the disk, and then a separate file system watcher service would pick it up and send the user name/password over to a cloud based system.

Section 5: Advanced Windows Service Programming
03:00

In this video I will show you how to add a config file to your project and how to use it to pass parameters over to your service.

03:17

You are going to dig deep into the config file and see what are its various components and how you can take advantage in deployments by changing various values.

06:10

It is possible to control a service using a desktop application or an ASP.Net website using System.ServiceProcess.ServiceController class.

I will show you how to use this class.

Let’s open the UdemyWindowsService solution.

Right click the solution and select “Add” and “New Project”

Go to Visual C# and click “Windows” and then click “Windows Forms Application”.

Let’s name it “USAdmin”

I’m going to rename the file “Form1.cs” to “USAdmin.cs”

Now double click to open the form in design view.

I’ll click the form and then go to properties and change the “Text” to “Udemy Service Admin”.

Next I’ll add a label to the service, rename it to “lblServiceStatus” and change its text property to “Service Status”.

We need to add the assembly reference of System.ServiceProcess here.

Go to the “References” node under the “USAdmin” project.

Right click the “References” node and click “Add Reference”

Expand “Assemblies” and then “Framework”

Click the search text box and type “System.ServiceProcess”.

The relevant assembly will show up.

Click the checkbox behind it and click button “OK”.

Now right click the USAdmin form and select “View Code”

Go to the top of the file and add a using statement.

using System.ServiceProcess.

Now go back to the design view and double click the form body.

VS will automatically add an OnLoad method delegate for you.

Let’s get outside this delegate’s body and define a new method, it will be used to retrieve the status of our running service.

We’ll use a local variable of type ServiceController here, let’s define it.

ServiceController sc = new ServiceController("Udemy Windows Service");

We’ve used the constructor which takes only the service name and assumes it is running on the local machine.

I’m sure you have memorized the name of our Windows service that is “Udemy Windows Service”, I’m passing that to the constructor.

Next let’s get the status of the service by calling sc.Status.ToString().

I’m keeping the value in a local variable which will be returned in the end of the method.

I’ve also created a Try/Catch safety net around the property read operation, it will help if you mistakenly supply the wrong service name.

Now let’s go the USAdminMain_Load method, call getServiceStatus, and assign the return value to the status label.

Build the project to see if everything is okay.

After successful build I will go back to the designer view and add a new button “Get Status” as well.

Double click the “btnGetStatus”, a new OnClick method will be generated for you.

I will copy over the status line of code which from the OnLoad method.

lblServiceStatus.Text = string.Format("Service Status: {0}", getServiceStatus());

Now let’s build again.

Right click “USAdmin” and select “Start New Instance”.

The form will show up, you can see that the service status is “Stopped” at present.

Let’s go to service control manager and start the service.

Back on the form, I will click the button “Get Status”, the value will be updated to “Running”.

In the next video I will show you how to start/stop a service from your forms application.

I am a professional programmer, I will be happy to answer your questions and help you in case of a problem. Feel free to reach out.

Happy learning and stay tuned for more. :)

06:37

Starting or stopping a service is a very simple step. In this video I’m going to show you how to do it in asynchronous fashion.

First of all, let’s create new methods in our form to start and stop service.

public bool startService()

public bool stopService()

For the purpose of this demo I’m going to define service name as a constant.

Otherwise, you might put the service name in config file and read the value on runtime.

Let’s go to the top of the form and define the constant like this

const string CONST_SERVICE_NAME = "Udemy Windows Service";

Back in the startService method, I will define a service controller like we did earlier and call its method “StartService”.

try

{

sc.Start();

sc.WaitForStatus(ServiceControllerStatus.Running);

}catch(Exception excp)

{

MessageBox.Show

(excp.Message, "Error",

MessageBoxButtons.OK,

MessageBoxIcon.Error);

bRetVal = false;

}

The boilerplate like try/catch safety net is in place.

Let me do the same in stopService as well.

The difference is the method call Stop in the later method and the parameter of waitForServiceStatus method which is changed to stopped..

Please note that if an exception occurs while starting or stopping the service, both of these methods are going to return false.

If the operation goes successful, the methods will return true. We will use this value in a while.

Next, I’m going to add a couple of buttons to start/stops the service.

I’ve added two buttons, start and stop.

Both buttons are disabled by default, the OnLoad method of the form will decide which one should be enabled on the startup.

I’ve done it through the value of lblServiceStatus instead of calling the getServiceStatus method again. Here’s the code

if (lblServiceStatus.Text.EndsWith("Stopped"))

{

btnStart.Enabled = true;

}

else

{

btnStop.Enabled = true;

}

I’ll also add the logic to enable/disable start/stop buttons to the method getServiceStatus.

if (lblServiceStatus.Text.EndsWith("Stopped"))

{

btnStart.Enabled = true;

}

else

{

btnStop.Enabled = true;

}

Now I am going to go to the form design view and double click the button “Start”.

In the onClick callback, let’s call the method which we wrote earlier to start the service.

if (startService())

{

btnStop.Enabled = true;

btnStart.Enabled = false;

}

lblServiceStatus.Text = "Service Status: " + getServiceStatus();

This piece of code will attempt to start the service and if it succeeds, it will update the button state. The last line will update the status label.

Let’s do the logical equivalent in serviceStop as well.

if (stopService())

{

btnStart.Enabled = true;

btnStop.Enabled = false;

}

lblServiceStatus.Text = "Service Status: " + getServiceStatus();

Now let’s build everything.

And run the form application.

It says that the service is stopped. The start button you can see is enabled and the stop button is disabled.

I’ll click “Start” button.

The system shows an error message :(

It says “Cannot open service Udemy Windows Service on the system”

Well, that’s because we’re not running VS with admin privileges.

You can do two things.

Either close the VS, and start it as administrator again.

Or go to the debug directory of the solution, right click and run the application as administrator.

Let’s do the former.

Now I’ll run the application

And I’m going to click “Start” button.

You see it will take a short while, and then the button statuses will change.

Let’ check the service status in SCM.

It looks correct

Now click the stop button and refresh the SCM.

This is the end of this video.

I hope you found it useful.

Section 6: Installing a Windows Service with Inno Setup
02:08

SC.exe is a command line utility built into Windows operating system.

You don’t need to install it separately.

That’s why we can use it to install/uninstall a Windows service.

Most probably you would’ve installed the UdemyWindowsService on your machine

In that case, un-install the service using technique shown in lecture 10 “Uninstall a Windows Service”.

We’re going to run command prompt as administrator

Open the debug folder of the service and copy the path of the service exe file

Now go to the command prompt and key-in command

sc.exe create Name="Udemy Windows Service" binPath="C:\Users\Naeem Akram\Documents\Visual Studio 2015\Projects\UdemyWindowsService\UdemyWindowsService\UdemyWindowsService\bin\Debug\UdemyWindowsService.exe"

In order to see the detailed help about sc.exe, just type the command sc on command prompt.

Now go to service control manager, our service will show as installed.

Let’s run our service

Everything looks fine

In order to uninstall a service, we are going to use the command given below

Sc.exe delete “Udemy Windows Service”

The parameter in double quotes is the name of the service

Let’s try it

Now refresh the SCM

The service is gone!

We are going to use these commands in next videos of this section, to install and uninstall a Windows Service.

01:02

I’ve chosen to use Inno setup to create an installer for our Windows Service.

There are various reasons for this.

First of all Microsoft has pulled the plug on the installer projects which came with Visual Studio by default.

They are supporting WiX toolkit, I’ve used it a for a project and I … found it complicated.

So, I’ll show you how to use Inno Setup which is a free installation system.

The download link is given in course description and shown on the screen as well

http://www.jrsoftware.org/isinfo.php

Download and install the latest stable release of Inno Setup.

In the next video we will create an installer setup which will use Inno Setup and SC.exe to install our service on a non-developer PC.

07:29

Before we start creating installer for our service, let us build our project in release mode.

We must build our projects in “Release” mode before sending them to deployment

So now let’s go to our service project and select “Release” from the build toolbar

Go to “Build” menu and select “Build”

Next… I am going to launch the “Inno Setup Compiler”.

[Click start, click “Inno Setup Compiler”]

Click check box “Create a new script file using the Script Wizard”, click “OK” button

Click Next

Supply Application parameters like Application name would be “Udemy Windows Service”

Version 1.0, Publisher can be your name or my name etc.

Cilck “Next”

Application folder name will be again “Udemy Windows Service”, click “Next”

For “Application main executable file” we will click “Browse” button

I will browse to the “Release” folder of our project and pick “Udemy Windows Service.exe”

Uncheck the check-box “Allow user to start the application after setup has completed”

Click button “Other Application files and select “Log4Net.dll” and service config file as well

Click the button again and pick the files of US Admin as well

Click “Open” button

Click “Next” button

Start Menu folder name will be “I Love You”, or maybe “Udemy Windows Service” is okay.

Click Next three times

I will call “Compiler Output base file name” … “SetupUWS”

Click “Next” button twice

And click “Finish” button

Don’t compile the script, we need to make some important changes

Firstly, “My App Name” will become “Udemy Windows Service”

We will add a [Run] section

This section will run when setup has finished copying files to destination program files directory

It will contain the “sc” command in a slightly twisted fashion

I am about to bring in the command, hold your breath and don’t freak out. I will explain.

This syntax means that we are going to launch the command prompt and pass it the sc command

The /c will make the command run and close the command prompt afterwards

You can see the words sc and create which were explained in first video of this section

The next parameter {#MyAppname} is defined on top of this script file

[Scroll Up]

It will be resolved to “Udemy Windows Service” on run time.

On the command prompt we need to put the name in double quotes, the extra double quote is used as an escape sequence.

Same is true for binPath Which will be ultimately resolved to the path of our main service file on target machine.

I must mention a very small error which can give you a head-ache.

See this space between binPath= and the double quotes, miss it and you will regret.

Don’t miss this space, the sc command will fail.

Similarly, we can add a section UninstallRun which will run when we will run the uninstall utility

Let me put the script here

In this case we are running the “sc” with “delete” command

I would love to make things even sweeter by making a small change to the [icons] section

In the first line, I will change {#MyAppExeName} to “USAdmin.exe”

I will make the same change in the line below, which lets us create an icon on the desktop

Now let compile the script

I will click “Build” menu and select “Compile”

The system didn’t show any error

You can either click the play button on the toolbar

Right here[emphasis on button]

Or, you can go to the output folder of your installer project and run the SetupUWS.exe

In the next video, you are going to see this very installer in action!

01:48

I will browse to the “Output” directory of our setup project

SetupUWS.exe is present there.

I will double click the file and launch the installer

Just keep clicking the next button, I will like to create a desktop icon though.

Click Install button

Now click “Finish” button

You can see an icon is created on the desktop, I will right click it and select “Run as Administrator”

Now click the button “Start Service”

The service has started.

We can check in the service control manager.

[Click windows button and click Service Control manager]

You see, Udemy Windows Service is present and installed

Let me show you the application installation folder as well

[Open using explorer]

Here you can see all files related to your service

The service log file is also in place

That’s all for this video

I believe the course is pretty much complete now after the addition of the installer section.

Thanks very much for watching, feel free to ask questions and get in touch.

03:20

A brief introduction about my first online course titled "TCP/IP socket programming in C# .Net for coders & students".

The course URL is: https://www.udemy.com/tcpip-socket-programming-for-coders-using-csharp-net/

Students Who Viewed This Course Also Viewed

  • Loading
  • Loading
  • Loading

Instructor Biography

Naeem Akram, Sr. Software Engineer

I am A person with many talents and interests, ranging from gardening to programming and poetry to cooking.

I've been writing computer software code(C++, C# .Net) since 2006, creating awesome Android apps since 2012. I've been working as a freelance software developer since Nov. 2012.

I've extensively worked on network communications, computer telephony integration(CTI) using Microsoft TAPI 2.x and 3.x, and LDAP server programming(Active Directory). Android app development has been my focus as a freelancer, I've created and published several apps for clients and a couple for myself on Google Play store.

I've been sharing my knowledge through my blogs, and I am confident its time share more things that I've experienced with the world in a comprehensive video format.

Ready to start learning?
Take This Course