Monday, 3 July 2006

Windows Services

I have had to use windows services quite a few times, and always forget how to install them - so here is a guide!!!


Step 1: Create the service.


File -> New -> project -> Visual c# -> Windows -> Windows Service


If you have created a service before then you can skip this part!


So there will be two methods OnStart(string[] args) and OnStop(). You obviously will only be using a service if you want something to be running constantly (or periodically). So I would suggest that you create a timer object in here, add an elapsed event :



protected override void OnStart(string[] args)
{


m_oTimer = new System.Timers.Timer(double.Parse(args[0]));
m_oTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_oTimer_Elapsed);
m_oTimer.Start();

}

void m_oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
EventLog.WriteEntry("Service Name", "Timer Event", EventLogEntryType
.Information);
m_oTimer.Stop();
//Code goes here
m_oTimer.Start();
}



That will cause your code to run periodically depending on the argument you pass into the service.


Step 2: Add an installer


This bit is the easy bit. Go to the design viewer of your service (double click on the service cs file on the solution explorer). Right click on the form and select "Add Installer". This will create a project installer for you with a service process installer and a service installer.


Right click on the service installer and select properties. Enter a service name, and change the start type to Automatic.


Right click on the service process installer and select properties. Now you can change the account type:


" User is the default account setting and it allows the service to impersonate a specific user whether or not that user is logged in. Local System is a system account with high privileges similar to the Administrator account. However, Local System account doesn't have necessary access to UI elements. So, if you pop up a dialog as Local System, it will show on a system desktop!" nicked from http://csharpcomputing.com/Tutorials/Lesson22.htm


Step 3: Add an instillation project.


  • File->New->Project->Other Project Types->Setup and Deployment-> Setup Project
  • Right click on the project and select View->File system
  • Now right click on the application folder and select Project Output
  • Now select Primary output, and make sure your services project is selected, then click ok.
  • Now right click on the setup project again and select View->Custom Actions
  • Right click on the root node Custom Actions and select "Add custom Actions"
  • Double click on the "Application Folder", select "Primary output from..." and click ok.

Step 4: Build your installer and you should be ready to go!

3 comments:

Gyorgy said...

Thank you very much.
This was a very clear tutorial, exactly that I needed.

Ross Dargan said...

Glad I could help:)

Ross

Tim said...

Thanks Ross! This made it nice and easy!

Tim