Create a windows service.
We are going to create a service that writes the current time to a text file every minute.
1) We are going to write the logic in a class library.
2) Create the service
3) Install and Uninstall service
4) Create a setup and deploy project to setup the service
5) Create a Schedule Task
6) Difference between Windows service and Scheduled tasks.
1) Class Library
First let us create the class library.
Open Visual Studio 2005
File->New Project-> Class Library
Name: ServiceTextWrite
Solution Name: MyNewService
In the solution explorer we see the following files. I have renamed the default Class.cs file to WriteToFile.cs
In the WriteToFile.cs I have added the following method
public void writeToFile()
{
TextWriter tw = new StreamWriter(@"C:\ServiceLog.txt",true);
tw.WriteLine(DateTime.Now);
tw.Close();
}
Just make sure you have created a file ServiceLog.txt in c:
TextWriter tw = new StreamWriter(@"C:\ServiceLog.txt",true);
The above line appends to the data in the text file.
Build the project.
2) Create the service
The next step is to create the service
File ->Add-> New Project

Select Windows service and Name TextWriterService and click OK
Now your solution explorer looks as below
First step is to add a Timer to the Service1.cs. But we cannot drag and drop the timer from the tool box, because the toolbox has System.Windows.Forms.Timer and those events will not be raised in Windows Service. Please refer the link below for further details
http://support.microsoft.com/kb/820639
So we have to use System.Timers.Timer.
Open Service1.Designer.cs. We find a method InitializeComponent.
private void InitializeComponent()
{
this .components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
Here we have to add the Timer.
So the function is
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Timers.Timer(this.components);
//
// Service1
//
this.ServiceName = "Service1";
}
Open the Service1.cs[Design]
And set properties for the Timer

Make sure Enabled is True; Interval is 60000 milliseconds i.e. 60 sec i.e. 1 minute.

Add event for the timer
Clicking on the event takes us to the code behind page Service1.cs
When the service starts we want to start the timer. So code is as follows
protected override void OnStart(string[] args)
{
timer1.Start();
}
When the service stops we want to stop the timer.
protected override void OnStop()
{
timer1.Stop();
}
When the timer is elapsed we want to write the time to the file
For this we have to add the class library as reference. Right Click on Your Service project(TextWriterService) and select Add Reference
Click on Browse Tab and select ServiceTextWriter.dll that we created earlier in step 1.
Write the following code and make sure you add using ServiceTextWriter;
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
WriteToFile obj = new WriteToFile();
obj.writeToFile();
}
So now the Service1.cs looks as below
Right click on Service1.cs[Design] and select Properties
Here we can change the service name as TextWriterService. We can customize other properties as needed. For Example CanPauseAndContinue if set to true, the service can be paused and continued.
Right click on Service1.cs[Design] and select Add Installer
It adds ProjectInstaller.cs
ProjectInstaller.cs[design] is as below
Right Click on seviceInstaller1 and select properties. Make sure the ServiceName matches the Service name we have given in Service1.cs properties. Here we can also setup the startup type of the service i.e. Manual, Automatic, Disabled.
• Manual: - User has to start the service
• Automatic: - Service starts automatically after system restarts etc. In real time we mostly use this option.
• Disabled: - Service is disabled.
After you install the service we can see the services (Right Click on My Computers and select Manage, under Services and Applications Select Services)
Here the column StartUp Type matches with what we have given above in the property Start Type (Manual, Automatic, Disabled).
We can change them if we Right Click on the Service and select Properties
In the Startup type Drop down select the one needed and click apply.
In ProjectInstaller.cs[Design] right click on serviceProcessInstaller1 and select properties.
We have a property named Account. It takes up following values
• LocalService
• NetworkService
• LocalSystem
• User
If we select the option User, It asks us for User Name and Password when we install the service. In real time we mostly use User option. Otherwise we can use LocalSystem.
The service is created, build the service project.
3) Install and Uninstall Service
There are two ways to Install/Uninstall service. One is using Visual Studio Command Prompt and installutil command and the other is using setup and deploy project.
Let us see using Visual Studio Command prompt installutil
To install a service
>installutil “path to the service.exe”
To uninstall a service
>installutil /U “path to the service.exe”
Install service
After you click enter, it shows the processing and we get message install has completed.
After this open the service i.e. Right Click on My Computers and select Manage, under Services and Applications Select Services
We have given the name TextWriterService
To start the service, Right Click on the service and select Start.
When the service is started go to C:\ServiceLog.txt. It should be updated every minute with the time.
To stop the service
Right Click on the service and select Stop
To uninstall the service
In Visual Studio Command Prompt type the command and click enter.
C:\Program Files\Microsoft Visual Studio 8\VC> installutil /U "C:\Documents and S
ettings\MXB5195\My Documents\Visual Studio 2005\Projects\MyNewService\TextWriter
Service\bin\Debug\TextWriterService.exe"
This removes the service from our operating System.
4) Create a setup and deploy project to setup the service
File -> Add New Project ->Other Project Types-> Setup and Deploy
Name is TextWriterSetup
Right Click on TextWriterSetup in Solution Explorer and select Add-> Project Output
In the Project be sure to select the Windows Service (TextWriterService) as Primary Output and click OK.
Now the solution Explorer is as follows
Again Right Click on TextWriterSetup in Solution Explorer and select View ->Custom Actions
This brings up the page as below
Right Click on CustomActions and select Add Custom Actions. It brings up the following window
Select Application Folder and Primary output from TextWriterService (Active) and click OK
It display as below
Build the setup project
In the debug folder we see two setup files created
C:\Documents and Settings\MXB5195\My Documents\Visual Studio 2005\Projects\MyNewService\TextWriterSetup\Debug
We can copy the .msi file on any server and run it, to install the service on that machine
To Install the service, double click on the .msi file
Follow the instructions by click on Next and the service will be installed
To start and stop the service, Right Click on the service in Console Management window and select Start or stop.
To uninstall the service
Go to Control Panel, Add or Remove Programs and select TextWriterSetup and click on Remove
5) Create a Schedule Task
Just create a class library with the logic that has to be performed.
Go To Control Panel -> Scheduled Tasks
Click on Add Scheduled Task
A wizard open up. Follow the instruction in the wizard
Click On Browse and select your dll and select the schedule
6) Difference between Windows service and Scheduled tasks.
Windows Service is a dedicated process. It uses system resources from the time it is started until it stops.
Scheduled Task uses system resources only when the scheduled time occurs.
One Real time example of Windows service is monitoring a directory where client puts a document. This service copies that document to our server.
Scheduled Tasks example is we collect Users Statistics i.e. which Page the user visited, Time Visited, IP address etc. Every month on 1st at 2:00 am CST the database is archived and the tables are cleared.
Let me know if needed with screenshots
0 Comments Received
Post a Comment