Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Posts Tagged ‘Window Service’

Handling Window services thru C#

Posted by Viral Sarvaiya on November 23, 2012


Hello.

Open Run window form start menu or Press Window key + R, Run window will open, in textbox type “services.msc” and Hit Enter, Service window will open.

Service window has list of the services installed in the computer.

To these all service we can call Window service in technical word.

Window service enable you to create long-running executable applications.

To know how to create window service please click here

C# provide you functionality to handle installed services, that will include in namespace System.ServiceProcess

Here i am explain, how to handle window service.

1. To get list of the Window service.

You can get list of the window service installed in computer from below code,

In System.ServiceProcess namespace we have a from that we can get list of the window service.


ServiceController[] ListServices = ServiceController.GetServices();

2. Search particular service from list.


ServiceController[] ListServices = ServiceController.GetServices();

string TextService = "My Sample Service"

if (LstServices.Where(a => a.ServiceName == TextService).Count() > 0)
{
ServiceController Myservice = new ServiceController(TextService);
}
else
{
MessageBox.Show(TextService + " is not Installed");
}

ServiceController.GetServices() gives list of the service so i take that in array of the ServiceController class.

And from linq query we can check that particular service is in the list or not and if that list count is greater than zero then we get that service is installed in the computer else not.

And to get that particular service, here i have creating object of the ServiceController class.

3. Check the status of the Service.

If the window service is installed in computer then we can also check the status of that window service.

Now we assume that we find the service “My Sample Service”.

So from below code we can get the status of the service whether it is Running, Paused, Stopped.


ServiceControllerStatus ServiceStatus = Myservice.Status;

ServiceControllerStatus is Enum for all service statuses.

If we want to compare status then we can use as like below.


if (ServiceStatus == ServiceControllerStatus.Running)
{
//Do something
}

4. Start/Stop the Service

From ServiceController class we can start or stop the particular Service with object of the ServiceController.

To start the service you can use


Myservice.Start();

And to stop the service you can use


Myservice.Stop();

5. To Restart the Service

To restart the service first we have to check that service is running or not and if it is running then we can stop the service and start the service.


ServiceController[] ListServices = ServiceController.GetServices();

string TextService = "My Sample Service"

if (LstServices.Where(a => a.ServiceName == TextService).Count() > 0)
{
ServiceController Myservice = new ServiceController(TextService);

ServiceControllerStatus ServiceStatus = Myservice.Status;

if (ServiceStatus == ServiceControllerStatus.Running)
{
Myservice.Stop();

TimeSpan timeout = TimeSpan.FromMilliseconds(2000);

Myservice.WaitForStatus(ServiceControllerStatus.Stopped, timeout);  //To wait 2 second for Stop Service

Myservice.Start();

Myservice.WaitForStatus(ServiceControllerStatus.Running, timeout);   // To wait 2 second for Start Service
}
}
else
{
MessageBox.Show(TextService + " is not Installed");
}

hope this will helpful

Thanks.

Posted in .Net, Window Service | Tagged: , , , , , , , , , , | Leave a Comment »

Creating Window Service with .NET VS2008

Posted by Viral Sarvaiya on December 31, 2010


Hi,

Last post of year 2010, and wish u happy new year…

today i post the basic thing of the window service.

What is a Windows Service?

Windows Service applications are long-running applications that are ideal for use in server environments. The applications do not have a user interface or produce any visual output. Any user messages are typically written to the Windows Event Log.

Windows Services are controlled through the Service Control Manager where they can be stopped, paused, and started as needed.

Create a Windows Service

The service we will create does nothing really useful other than serve as a demonstration. When the service is started we will log an entry in a database indicating that it has started. The service will create a database entry on a specified interval during the time in which it is running. The service will create a final database entry when stopping. The service will also automatically log an entry in the Windows Application Log when it is successfully started or stopped.

1. Start a new project

2. Select Windows Service from the list of available project templates

3. The designer will open in design mode

4. Take the time control to the designer(make sure it is not windows control, it has to


public System.Timers.Timer timer1;

5. set the Enabled property to False and the Interval property to 30000 milliseconds

now come to service.cs page..

there are class that extend ServiceBase class with there are constractor and 2 mehtod already created is start and stop.

6. Create table “ServiceLog” as per blow


CREATE TABLE MyServiceLog (
Id int IDENTITY (1, 1) NOT NULL,
Status varchar (100),
Created datetime NOT NULL
)

7. Create event timer’s ElapsedEventHandler timer1_Elapsed event

in the service.cs file


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Data.SqlClient;

namespace WindowsServiceTest
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
this.timer1.Enabled = true;
this.LogMessage("Service Started");
}

protected override void OnStop()
{
this.timer1.Enabled = false;
this.LogMessage("Service Stopped");
}

/*
* Respond to the Elapsed event of the timer control
*/

private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
this.LogMessage("Service Running");
}

/*
* Log specified message to database
*/

private void LogMessage(string Message)
{
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection("packet size=4096;server=ServerName;persist security info=False;database=DataBaseName;uid=Username;pwd=Password;");
command = new SqlCommand("INSERT INTO MyServiceLog (Status, Created) VALUES ('" + Message + "',getdate())", connection);
connection.Open();
int numrows = command.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
command.Dispose();
connection.Dispose();
}
}
}
}

8. Now Install the Windows Service

The Windows Service should be installed by using the InstallUtil.exe provided with the .NET Framework or through a deployment project such as a Microsoft Installer (MSI) file.

You must also add an Installer to your Windows Service so that the InstallUtil, or any other installation program, knows what configuration settings to apply to your service.

1. Switch to the design view for the service

2. Right click and select Add Installer

3. Switch to the design view of the ProjectInstaller that is added

4. Set the properties of the serviceInstaller1 component

1. ServiceName = My Sample Service

2. StartType = Automatic

5. Set the properties of the serviceProcessInstaller1 component

1. Account = LocalSystem

6. Build the Solution

The file ProjectInstaller.cs automatically made.

Install service with InstallUtil.exe

1. Open Visual Studio .NET command prompt

2. Go to the debug or release folder

3. Run command InstallUtil.exe MyWindowsService.exe

4. Open services from control panel -> administrative tools

5. Find the Service and right click on it and start the service.

6. Check the database. log will inserted to database in every 3 second

Enjoy Window service.

http://msdn.microsoft.com/en-us/library/d56de412

Posted in .Net, Visual Studio, Window Service | Tagged: , , | 1 Comment »

 
%d bloggers like this: