Monday, December 15, 2008

How to create windows service in .NET?

Windows service does not have User interface but can be accessed from the services list provided by windows operating system.
(Type “services.msc” in command prompt).
We also heard about web services,
This service provides information to the user but it does not have its own User interface and it is embedded or called in web applications like web pages.
So service will not have User interface to interact but runs at the back end to listen and respond for requests sent to it.
Windows service is very similar to web service, where as windows service serve specifically in desktop but web service can be accessed in internet using http protocol like a web site.
Example: - We see live cricket score board being updated in few web sites , it does not mean that each web developer stays at the stadium to update his data base data with live score :).
There runs a web service at one point which updates its database with the updated live score, all other different web sites running around the world access the same web service and share the same information.

Web service process

Windows service is very specific to desktop not as web service shown above.

Step 1:- Template in visual studio to create windows service

Step 2:- After creating windows service, we can observe the windows service class file opened and 2 methods (start and stop) in it.

For demo I am creating this service to log date and time when the service is started and stopped.

Step 3:-

After relevant logic is written in the class file for both start and stop events, we need to add installer that supports to insall the service.
(To add installer, double click on the “services.msc” in solution explorer, right click on the displayed window and click on “add installer”)

Step 4:
We can see “serviceInstaller1” object on the window after adding Installer.
Now go to properties of this “serviceInstaller1”, set attributes like service name, service description.

Step 5:
We can also see “serviceProcessInstaller1” object on the window after adding Installer.
Now go to properties of this “serviceProcessInstaller1”, set attributes going to account as “localsystem”.

Step 6:
Now build the entire solution in”release” mode.

Step 7:
After building solution go to release folder of the application and also open “.NET command prompt”.

Type “installutil “(space) drag and drop the .exe file created in release folder.

You can see windows is running steps to create service and finally a log file generated in release folder by installer.

Step 8:
Open services in your machine (go to command prompt and type “services.msc”).
You can find the service in the list created by you in all above steps.
Right click on the service and say “start”.

Step 9:
Now open the log file that will be created by your service in the release folder or the path where .exe file exists.

No comments:

Post a Comment