IT Community - Software Programming, Web Development and Technical Support

How to create a windows service program?

This is a discussion on How to create a windows service program? within the C# Programming forums, part of the Software Development category; How to create a program that can be installed as a windows service, not as a normal desktop program. using ....


Go Back   IT Community - Software Programming, Web Development and Technical Support > Software Development > C# Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 09-05-2007, 01:21 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Thumbs up How to create a windows service program?

How to create a program that can be installed as a windows service, not as a normal desktop program.
using .net and C#.
How do we do that?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 09-05-2007, 01:23 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Default Re: How to create a windows service program?

Creating the Windows Service

1. Create a timer object at class scope:


Code:
private System.Timers.Timer timer=null;
2. Set up the timer within the class constructor:


Code:
public scheduler() {

string servicepollinterval = System.Configuration.ConfigurationSettings.AppSettings
["servicepollinterval"];

	double interval=10000;
	try {
		interval = Convert.ToDouble(servicepollinterval);
	}catch(Exception) {}
	
timer = new System.Timers.Timer(interval);
	timer.Elapsed += new ElapsedEventHandler( this.ServiceTimer_Tick );

}
Notice that we are getting the timer's interval value by using


Code:
System.Configuration.ConfigurationSettings.AppSettings
["servicepollinterval"];
I will cover the configuration file in more detail in step three.


Code:
timer.Elapsed += new ElapsedEventHandler( this.ServiceTimer_Tick );
This sets up the event handler for when the timer elapses. It will be fired when the timer runs for the duration of the set interval. I'll get into more detail on this further down.

3. Next we need to start and stop the timer based on our Service's events.


Code:
protected override void OnStart(string[] args) {
	timer.AutoReset = true;
	timer.Enabled=true;
	timer.Start();
}

protected override void OnStop() {
	timer.AutoReset = false;
	timer.Enabled = false;
}	

Optionally you can define the OnPause and OnContinue members:

protected override void OnPause() {
	this.timer.Stop();
}

protected override void OnContinue() {
	this.timer.Start();
}
4. The timer's Elapsed Event handler.


Code:
timer.Elapsed += new ElapsedEventHandler( this.ServiceTimer_Tick );
This line instructs the Framework to call the "ServiceTimer_Tick" method within our current class when the timer elapses -- that is, when its interval runs its course. So we must implement this method in our class as such:


Code:
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e) {
	this.timer.Stop();
	//IMPLEMENT YOUR TIMER TICK HERE
	this.timer.Start();
}

Last edited by Mramesh : 09-05-2007 at 07:11 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 09-05-2007, 01:24 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Default Re: How to create a windows service program?

Creating the Windows Service

Code:
FileMonitor.cs
namespace FileMonitor
{
using System;
using System.Collections;
using System.Core;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Web.Services;
using System.Diagnostics;
using System.ServiceProcess;
using System.WinForms;
using System.IO;
using Microsoft.Win32.Interop;


public class WinService1 : System.ServiceProcess.ServiceBase
{

private System.ComponentModel.Container components;
private System.IO.FileSystemWatcher fileSystemWatcher1;
private ObjectList fileWatchers;

private System.Diagnostics.PerformanceCounter fDelCtr;
private System.Diagnostics.PerformanceCounter fCrCtr;

public WinService1()
{
// This call is required by the WinForms Component Designer.
InitializeComponent();

// TODO: Add any initialization after the InitComponent call

servicePaused = false;

this.CanPauseAndContinue = true;
this.CanStop = true;

}

// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;

// More than one user Service may run within the same process. To add

ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
WinService1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container ();
this.fileSystemWatcher1 = new System.IO.FileSystemWatcher ();
fileSystemWatcher1.BeginInit ();

this.fDelCtr = new System.Diagnostics.PerformanceCounter ();
this.fCrCtr = new System.Diagnostics.PerformanceCounter ();

fileSystemWatcher1.Enabled = true;

fDelCtr.CategoryName = "FileMonitorService";
fCrCtr.CategoryName = "FileMonitorService";


fDelCtr.CounterName = "Files Deleted";
fCrCtr.CounterName = "Files Created";


this.ServiceName = "FileMonitor";
fileWatchers = new ObjectList();
fileSystemWatcher1.EndInit ();
}

/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
string[] drives = Environment.GetLogicalDrives();

// create filesystem watchers for local fixed drives
foreach (string curDrive in drives )
{
if ( PlatformInvokeKernel32.GetDriveType(curDrive) == win.DRIVE_FIXED)
{
int item = fileWatchers.Add( new FileSystemWatcher() );
FileSystemWatcher curWatcher = (FileSystemWatcher)
fileWatchers[item];

curWatcher.BeginInit ();
curWatcher.Target = System.IO.WatcherTarget.File;
curWatcher.IncludeSubdirectories = true;
curWatcher.Path = curDrive;
curWatcher.Created += new FileSystemEventHandler(OnFileCreated);
curWatcher.Deleted += new FileSystemEventHandler(OnFileDeleted);
curWatcher.Enabled = true;
curWatcher.EndInit();
}
}
}

/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
// reset the counters back to 0

if( fDelCtr.RawValue != 0 )
{
fDelCtr.IncrementBy(-fDelCtr.RawValue);
}

if( fCrCtr.RawValue != 0 )
{
fCrCtr.IncrementBy(-fCrCtr.RawValue);
}
}

protected override void OnPause()
{
servicePaused = true;
}

protected override void OnContinue()
{
servicePaused = false;
}

private void OnFileCreated(Object source, FileSystemEvent

Last edited by Mramesh : 09-05-2007 at 07:11 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 09-05-2007, 01:39 AM
Sundaram Sundaram is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Location: chennai
Posts: 117
Sundaram is on a distinguished road
Send a message via MSN to Sundaram Send a message via Yahoo to Sundaram
Question Re: How to create a windows service program?

Hi Ramesh

Could you Explain me, What is a Windows Service

thanx

Sundar
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 09-05-2007, 01:43 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Default Re: How to create a windows service program?

What is a Windows Service?

Windows Service is nothing but process running in background without our knowledge.You often need programs that run continuously in the background. It mostly won't require User interaction. If we type "services.msc" in Run of Start Menu, we can see what are the services running in our system. Some will start automatically, when system starts. But some services has to be started by us manually.
For example, an email server is expected to listen continuously on a network port for incoming email messages, a print spooler is expected to listen continuously to print requests, and so on.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 09-05-2007, 05:45 AM
SaravananJ SaravananJ is offline
D-Web Programmer
 
Join Date: Aug 2007
Posts: 79
SaravananJ is on a distinguished road
Default Can we create Setup for windows service...?

Hi All,


Can we create setup for the windows service....? please explain how to create the setup.....


thanks....
__________________
J.Saravanan
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 09-05-2007, 05:52 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: How to create setup for windows service...?

Hi Saravanan,

We can create a setup project for the windows services also....

please follow the steps to create the setup for windows service...


Create a Setup Project for a Windows Service

Use a Compiled Setup Project to Install the Windows Service
After you complete the steps to configure the Windows Service project, follow these steps to add a deployment project that packages the service application so that the service application can be installed:

1. Add a new project to your LogWriterService project. To do this, follow these steps:
a. In Solution Explorer, right-click Solution 'LogWriterService' (1 project), point to Add, and then click New Project.
b. Click Setup and Deployment Projects under Project Types, and then click Setup Project under Templates.
c. In the Name text box, type ServiceSetup.
d. Type C:\ in the Location text box, and then click OK.
2. Tell the deployment project what to package. To do this, follow these steps:
a. In Solution Explorer, right-click ServiceSetup, point to Add, and then click Project Output
b. In the Add Project Output Group dialog box, in the Project box, click LogWriterService
c. Click Primary Output, and then click OK.
3. For correct installation, add only primary output. To add the custom actions, follow these steps:
a. In Solution Explorer, right-click ServiceSetup, point to View, and then click Custom Actions
b. Right-click Custom Actions, and then click Add Custom Action.
c. Click Application Folder, and then click OK.
d. Click Primary output from LogWriterService (Active), and then click OK.

Notice that Primary output appears under Install, Commit, Rollback and Uninstall.
4. By default, setup projects are not included in the build configuration. To build the solution, use one of the following methods:
• Method 1
a. Right-click LogWriterService, and then click Build.
b. Right-click ServiceSetup, and then click Build.
• Method 2
a. On the Build menu, click Configuration Manager to build the whole solution.
b. Click to select the Build check box for ServiceSetup.
c. Press F7 to build the whole solution. When the solution is built, you have a complete installation package that is available for the service.
5. To install the newly built service, right-click ServiceSetup, and then click Install.
6. In the ServiceSetup dialog box, click Next three times. Notice that a progress bar appears while the service installs.
7. When the service is installed, click Close.

I hope this will help you...

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 09-05-2007, 07:30 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Could you explain me how to creating Project Installer?

Hi All,

Could you explain me how to creating Project Installer?


thanks....
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 09-05-2007, 07:38 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Default Re: How to create a windows service program?

Creating the Project Installer

The Project Installer is responsible for taking our Windows Service class and installing it into our system. We first need to create a class in our current project. Just name it "ProjectInstaller.cs".

Now I want to review each relevant line marked "//**'X'**" in the entire Project Installer code.


Code:
public class ProjectInstaller {

[RunInstaller(true)]  //**1**
	public class ProjectInstaller : System.Configuration.Install.Installer {  //**2**
	private System.ComponentModel.Container components;
	private System.ServiceProcess.ServiceInstaller serviceInstaller1; //**3**
	private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; //**4**

		public ProjectInstaller() {
			InitializeComponent();
		}

	private void InitializeComponent() {
		this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
		this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();

		this.serviceInstaller1.DisplayName = "Scheduler_Net";  //**5**
		this.serviceInstaller1.ServiceName = "Scheduler_Net";  //**6**

		this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;  //**7**

		this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;  //**8**
		this.serviceProcessInstaller1.Password = null;  //**9**
		this.serviceProcessInstaller1.Username = null; 

		//**10**
		this.Installers.AddRange(new System.Configuration.Install.Installer[] {

	this.serviceProcessInstaller1,
	this.serviceInstaller1});
		}

	}
}
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 09-05-2007, 07:45 AM
Sundaram Sundaram is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Location: chennai
Posts: 117
Sundaram is on a distinguished road
Send a message via MSN to Sundaram Send a message via Yahoo to Sundaram
Default Re: How to create a windows service program?

hi,
How could you Create the Configuration File???
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 09-05-2007, 07:55 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Default Re: How to create a windows service program?

Creating the Configuration File


The easiest way to configure the service is though the standard "APPNAME.EXE.config" (config) file, which the Framework automatically allows you to use through the "System.Configuration.ConfigurationSettings" class. With this class, we can actually create separate sections within the same configuration file, one for the service itself and others for any plug-ins we create. This simplifies administration to one XML file.

We are using the "System.Configuration.ConfigurationSettings" class to read the Timer interval into our class. It is using the standard "appSettings" section in the config file. See the XML snippet in below.

We want to create and use different sections for our plug-ins. We first need to create a "configSections" node with a "sectionGroup" for our plug-ins. The easiest way to describe this is to look at a slimed down version of the config file.


Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!-- application specific settings -->
  <configSections>
    <sectionGroup name="PlugInSettings">
      <!--notice we have an entry for each plugin's settings node below-->
        <section name="TemplatePluginSettings" type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
  </configSections>
  
  <appSettings>
    <add key="servicepollinterval" value="10000" />       
  </appSettings>
  
  <PlugInSettings>
    <TemplatePluginSettings>
      <add key="whatever" value="whatever-value" />
    </TemplatePluginSettings>
  </PlugInSettings>
</configuration>
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 09-05-2007, 08:07 AM
SaravananJ SaravananJ is offline
D-Web Programmer
 
Join Date: Aug 2007
Posts: 79
SaravananJ is on a distinguished road
Default Re: How to create a windows service program?

Hi all,

How to use Timers, Can you Explain me Using Timers in a Windows Service? and give me sample code in c#?

Thanks
SaravananJ
__________________
J.Saravanan
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 09-05-2007, 08:11 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: How to create a windows service program?

What Is a Timer?

A timer is an object that can be used in your applications to cause an event to occur on a specified interval. There are three timer controls available within the Microsoft .NET Framework. Each one has it specific nuances. The three types of timers are as follows:

* System.Windows.Forms.Timer—is designed for use in a single threaded Windows Forms based application. This is the same timer design as what has been available since early versions of Visual Basic. A common mistake is attempting to use this timer in a Windows Service application.
* System.Timers.Timer—is an updated version of the Windows Forms timer that has been optimized to run in a server environment where a user interface does not exist. This timer is ideal for use in Windows Services.
* System.Threading.Timer—is designed for use with ThreadPools. It uses callback methods rather than events and therefore does not rely on the operating system to support timers. We won't cover this timer as a part of this article.

Controlling a Timer

Each of the timers exposes some basic properties and methods that allow you to control its behavior. The Windows.Forms.Timer and Timers.Timer classes expose the same items:

* Enabled—property indicating whether or not the timer is enabled and should be raising the event.
* Interval—property allowing you to set the number of milliseconds between events.
* Start—method allowing you to start the timer.
* Stop—method allowing you to stop the timer.

The System.Threading.Timer object has different properties and methods for controlling its behavior. We're not going to cover the use of this timer here, so we'll skip the particulars.

Using a System.Timers.Timer Sample Code

The following sample code briefly demonstrates the programmatic setup of a timer in the System.Timers namespace. This example uses a Windows console application for simplicity in being able to see the outcome without requiring a lot of setup.

Code:
using System;

namespace ConsoleTimer
{
   /// <summary>
   /// Sample class for testing a server based timer.
   /// </summary>
   class Class1
   {
      System.Timers.Timer testTimer = new System.Timers.Timer();

      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main(string[] args)
      {
         Class1 test = new Class1();
         test.testTimer.Enabled = true;
         test.testTimer.Interval = 5000;    // Execute timer every
                                            // five seconds
         test.testTimer.Elapsed += new
            System.Timers.ElapsedEventHandler(test.testTimer_Elapsed);

         // Sit and wait so we can see some output
         Console.ReadLine();
      }

      private void testTimer_Elapsed(object sender,
         System.Timers.ElapsedEventArgs e)
      {
         System.Console.WriteLine("myTimer event occurred");
      }
   }
}
Using a System.Timers.Timer in a Windows Service

Now that we have seen a simple example of using a timer, we'll get more complex and apply them to a Windows Service. The example in the prior column showed the creation and use of a single timer. This time around, we'll spin up a number of threads and execute multiple timers. This will give us the opportunity to show how to set configurations in threads as well. The first thing we'll need to do is create our item that will run as a thread. Then, we'll create the Windows Service to create the threads. Finally, we'll add an installer to handle the installation of the Windows Service.

TimedItem Sample Code

The following sample code contains an object with a single timer. It simply starts and stops the timer and responds to the timer's event when appropriate. Because parameters cannot be passed to threads, we create a class like this and set the properties equal to the values we would want to pass as parameters to the method running as a thread. Each time the event fires for the item, an entry will be written to the Application log.

Code:
using System;

namespace CodeGuru.TimerService
{
   /// <summary>
   /// Demonstrate the use of a timer.
   /// </summary>
   public class TimedItem
   {
      private System.Diagnostics.EventLog _AppEventLog;
      private System.Timers.Timer _Timer;

      private int _Interval = 30000;
      public int Interval
      {
         get { return this._Interval; }
         set { this._Interval = value; }
      }

      private string _Name = "";
      public string Name
      {
         get { return this._Name; }
         set { this._Name = value; }
      }

      /// <summary>
      /// Constructor
      /// </summary>
      public TimedItem(System.Diagnostics.EventLog AppEventLog)
      {
         this._Timer = new System.Timers.Timer();
         this._Timer.Elapsed += new
         System.Timers.ElapsedEventHandler(_Timer_Elapsed);
         this._Timer.Enabled = false;
         this._Timer.Interval = this.Interval;
         this._AppEventLog = AppEventLog;
      }

      /// <summary>
      /// Start the timer.
      /// </summary>
      public void StartTimer()
      {
         this._Timer.Enabled = true;
      }

      /// <summary>
      /// Stop the timer.
      /// </summary>
      public void StopTimer()
      {
         this._Timer.Enabled = false;
      }


      /*
       * Respond to the _Timer elapsed event.
       */
      private void _Timer_Elapsed(object sender,
         System.Timers.ElapsedEventArgs e)
      {
         this._AppEventLog.WriteEntry("Time elapsed for " + this.Name,
            System.Diagnostics.EventLogEntryType.Information);
      }
   }
}
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Windows Service error oxygen C# Programming 1 02-27-2008 09:48 PM
Windows Service Balasubramanian.S C# Programming 1 02-27-2008 09:47 PM
What is a Windows Service and how does its lifecycle differ from a “standard” EXE? vadivelanvaidyanathan ASP and ASP.NET Programming 1 07-16-2007 01:31 AM
How to write Bluetooth Connection program in c# for Windows mobile 5.0 ? theone Windows Mobile 0 07-16-2007 12:16 AM
simple windows service to generate automatic mails kingmaker C# Programming 0 07-16-2007 12:04 AM


All times are GMT -7. The time now is 11:33 PM.


Copyright ©2004 - 2007, DiscussWeb. All Rights Reserved.

SEO by vBSEO 3.0.0