How to create window service in Asp.Net

Window service is kind of application which run on window machine on server or local machine. Once we install window service, it work automatically or manually, it completely depend on us how we want to run it. If we want to automate any task, window service helps us to do that. Whenever we need to start, stop or restart, we can do that easily from services control manager.

So here, its an application which run in system as background process and perform task which you have implemented. Keep in mind one important thing about window service, if your machine get restarted, you may need to check it whether its running or stopped because some time it may happen that your window service got stopped working, you need to restart it from service control manager.

Steps to create, implement and configure window service:

1. Create and implement window service in visual studio environment
2. Install window service
3. Start, Stop and Restart window service
4. Tracking Log

1. Create and implement window service

Open .Net Visual Studio and choose to create new project. Once you choose new project, navigate to below path

New Project -> Templates -> Visual C# -> Window Desktop -> Window Service

How to create window service in Asp.Net

You must have to define Path and Project name here in above screen.

Name: Your window service project name.
Location: Its path or destination where you want to store your window service project.
Solution Name: .SLN file name you need to define. It help to reopen your project later in .NET environment.

Note: Here, you can choose any other language also to create your window service.

Once you create window service project, it will look like following screenshot.

How to create window service in Asp.Net

I have chosen “SampleWindowService” as project name and keep service name as it appeared in above screen. You may change service name if you would like to change by using right side property box.

Now, you need to install “Add Installer” by using right click and select “Add Installer” from design view of services1.cs page as appeared in below screen.

How to create window service in Asp.Net

Once you add installer, you can see below screen with “ServiceProcedureInstaller1” and “ServiceInstaller1” in design view of ProjectInstaller.cs page. Now, you need to edit following few property for “ServiceInstaller1” on right side property box.

Display Name: Sample Service
Service Name: Sample Service
Start Type: Automatic

How to create window service in Asp.Net

Now, select “ServiceProcedureInstaller1” and update Account on right side property as appeared in below screen.

Account = LocalSytsem

How to create window service in Asp.Net

Now, its time to implement service by wiring some code in C#. Look into below screen and open code window for “Services1.cs” file. You can do it by using below screen.

How to create window service in Asp.Net

Once code editor window open, it will look like below screen.

How to create window service in Asp.Net

Lets understand few method from this window.

private Timer timer1 = null;

You must need to take one timer as this will call service with defined time interval.

public Service1()
{
InitializeComponent();
}

Above method is constructor which initialize when we call this service.

protected override void OnStart(string[] args)
{
timer1 = new Timer();
this.timer1.Interval = 5000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
Library.WriteLog(“Window service started”);
}

OnStart method will execute when timer give signal to perform task with specified interval. You must have to define interval to execute this method. Interval you must need to define in numeric value. Here, I have defined that with 5000 numeric value that means it will execute in every 5 seconds. In this method I have created one delegator/event handler for timer so that will be called in each 5 seconds.

void timer1_Tick(object sender, ElapsedEventArgs e)
{
try
{
PerformTask();
Library.WriteLog(“Successfully called Window service”);
}
catch (Exception Ex)
{
Library.WriteLog(Ex.Message.ToString());
}
}

PerformTask method is actual method to perform your task. Whatever task you want to automate, you need to write your logic here. I have written one line text “Window Service API Called” in one text file every 5 seconds. I will show final output in “Tasks.txt” file later. See below method to understand logic.

public void PerformTask()
{
StreamWriter sw = null;
try
{
string FileName = “Tasks.txt”;
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + “\\” + FileName, true);
sw.WriteLine(DateTime.Now.ToString() + “: Window Service API Called”);
sw.Flush();
sw.Close();
}
catch (Exception Ex)
{
Library.WriteLog(Ex.Message.ToString());
}
}

protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteLog(“Timer ended.”);
}
This method will execute when you will stop window service from service control manager permanently. If you want to restart again, you need to start it from the same window.

How to create window service in Asp.Net

Finally you need to build your window service project in Release mode and system will generate required file with exe file.

You need to find you “BIN” folder where all required files are generated. Here, “SampleWindowService.exe” in main application file which we will need to use to install our window service in command prompt.
Now we have implemented window service sample, its ready to install in next step.

2. Install Window Service

You need to install window service in command prompt by using following steps.

Start Window -> Search for “CMD” -> Right Click and choose “Run as administrator” mode as appeared in below screen.

How to create window service in Asp.Net

Once command prompt open, you need to navigate following path as per below creen.

C:\Windows\Microsoft.NET\Framework\v4.0.30319

How to create window service in Asp.Net

Now, copy location of your exe file from bin folder and paste into command prompt window after installutil as per below screen.

How to create window service in Asp.Net

If your window service installed, you will see success message as per below screen.

How to create window service in Asp.Net

Now, window service is installed successfully and its time to start it from Service Control Manager.

3. Start, Stop and Restart window service

To start, stop and restart window service, you need to open Service Control Manager by using following steps.

Start Window Program -> Type “Services.msc” and hit enter button to open it. Once its open, you need to find your service from list as appeared in below screen.

How to create window service in Asp.Net

How to create window service in Asp.Net

Select your service, right click on it, click on “start” option and system will start your service. Once your service started, you can “restart or stop” it by using same steps, it will display restart or stop option by right click on it.

How to create window service in Asp.Net

Now, lets verify whether its adding “Window Service API Called” which we have written in PerformTask method in Service1.cs class.

Look into below screenshot which display “Task” text file generated and adding text value which we have defined in PerformTask method.

How to create window service in Asp.Net

You can see “Task.txt” file which is adding “Window Service API Called” in every 5 seconds.

4. Tracking Log

I have also created on class called “Librabry.cs” and method “WriteLog()” to add tracking log for the service. By this method, I am adding each execution details into one text file. Service will created text file with current date and time to log all tracking details as per below screen appeared.

How to create window service in Asp.Net

 

How to create window service in Asp.Net

I hope this article will help you to create your window service. You may comment if you need any help and I will try to respond you as earliest time.

Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *