Answers
Jul 13, 2007 - 02:08 PM
That should be fairly simple! When you create a new project in Visual Studio, you just select Windows Service Project as the project type. This gives you a class whch inherits from System.ServiceProcess.ServiceBase and overrides OnStart(), OnStop(), OnPause(), OnContinue(), and OnShutdown(). The method names should be self explanatory. You add your code into the methods. The on start method is the one where you start your processing. Usually people use a timer there to kick off actions i.e. every 10 minutes or so.
The main difference is, you can't just run it i.e. for debugging from inside Visual Studio. You have to add an Installer class. There you can set if the service runs under a user account, starts automatically etc.
In order to install the during development, teh easiest method is to use installutil from a Visual Studio Command Prompt. i.e. "installutil /i C:\MyServiceProject\bin\Debug\Servicename.exe"
If you need to debug, you have to attach the debugger to the service process. Open the Processes menu from the Debug menu and attach to your service.
Let me know if it helped!
Cheers
Peter
The main difference is, you can't just run it i.e. for debugging from inside Visual Studio. You have to add an Installer class. There you can set if the service runs under a user account, starts automatically etc.
In order to install the during development, teh easiest method is to use installutil from a Visual Studio Command Prompt. i.e. "installutil /i C:\MyServiceProject\bin\Debug\Servicename.exe"
If you need to debug, you have to attach the debugger to the service process. Open the Processes menu from the Debug menu and attach to your service.
Let me know if it helped!
Cheers
Peter
Jul 13, 2007 - 02:09 PM
Here is a sample I found in a book:
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);
}
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
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 ();
}
///
/// Set things in motion so your service can do its work.
///
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();
}
}
}
///
/// Stop this service.
///
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
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);
}
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
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 ();
}
///
/// Set things in motion so your service can do its work.
///
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();
}
}
}
///
/// Stop this service.
///
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
Oct 18, 2007 - 03:11 AM
using System;
using System.Diagnostics;
using System.ServiceProcess;
namespace WindowsService
{
class WindowsService : ServiceBase
{
///
/// Public Constructor for WindowsService.
/// - Put all of your Initialization code here.
///
public WindowsService()
{
this.ServiceName = "My Windows Service";
this.EventLog.Log = "Application";
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
///
/// The Main Thread: This is where your Service is Run.
///
static void Main()
{
ServiceBase.Run(new WindowsService());
}
///
/// Dispose of objects that need it here.
///
/// Whether
/// or not disposing is going on.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
///
/// OnStart(): Put startup code here
/// - Start threads, get inital data, etc.
///
///
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
///
/// OnStop(): Put your stop code here
/// - Stop threads, set final data, etc.
///
protected override void OnStop()
{
base.OnStop();
}
///
/// OnPause: Put your pause code here
/// - Pause working threads, etc.
///
protected override void OnPause()
{
base.OnPause();
}
///
/// OnContinue(): Put your continue code here
/// - Un-pause working threads, etc.
///
protected override void OnContinue()
{
base.OnContinue();
}
///
/// OnShutdown(): Called when the System is shutting down
/// - Put code here when you need special handling
/// of code that deals with a system shutdown, such
/// as saving special data before shutdown.
///
protected override void OnShutdown()
{
base.OnShutdown();
}
///
/// OnCustomCommand(): If you need to send a command to your
/// service without the need for Remoting or Sockets, use
/// this method to do custom methods.
///
/// Arbitrary Integer between 128 & 256
protected override void OnCustomCommand(int command)
{
// A custom command can be sent to a service by using this method:
//# int command = 128; //Some Arbitrary number between 128 & 256
//# ServiceController sc = new ServiceController("NameOfService");
//# sc.ExecuteCommand(command);
base.OnCustomCommand(command);
}
///
/// OnPowerEvent(): Useful for detecting power status changes,
/// such as going into Suspend mode or Low Battery for laptops.
///
/// The Power Broadcast Status
/// (BatteryLow, Suspend, etc.)
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return base.OnPowerEvent(powerStatus);
}
Apr 24, 2008 - 12:58 AM
sir,i am a new person to this field.i want to create a small program like popupmesage getting displayed at few seconds.which i can keep as a window services .it must be in Csharp.
hope u will help me
hope u will help me
Sep 11, 2013 - 11:41 PM
If you want to create a windows service program, then you can go to msdn.microsoft site that they gives the whole information about how to create a windows service program.
Add New Comment