473,387 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Window Service

BW
Hi all! I'm not sure where to post this so I'm giving these a try. If there
is a better (more appropriate) place to post please let me know.

I want to create a service (in C#). The service's purpose is to monitor a
given service, and when the service becomes disabled and/or stopped I want
to restart the service.

I have figured out how to restart a stopped service by using the
ServiceController.Start() method.

Obviously,this only works if the service is enabled. So, I must enabled the
service before I can restart it.

Does anyone know how to re-enable the a service that had been disabled?
TIA
BW

I do have a very good reason for doing this and it is not malicious in
nature.
Nov 17 '05 #1
7 7241
You need set the StartType property using ServiceInstaller. I've never done
this, so you may need to uninstall and reinstall the service for this to
take.
--
Don Burn (MVP, Windows DDK)
Windows 2k/XP/2k3 Filesystem and Driver Consulting
Remove StopSpam from the email to reply

"BW" <so*****@somewhere.net> wrote in message
news:O5****************@TK2MSFTNGP14.phx.gbl...
Hi all! I'm not sure where to post this so I'm giving these a try. If
there
is a better (more appropriate) place to post please let me know.

I want to create a service (in C#). The service's purpose is to monitor a
given service, and when the service becomes disabled and/or stopped I want
to restart the service.

I have figured out how to restart a stopped service by using the
ServiceController.Start() method.

Obviously,this only works if the service is enabled. So, I must enabled
the
service before I can restart it.

Does anyone know how to re-enable the a service that had been disabled?
TIA
BW

I do have a very good reason for doing this and it is not malicious in
nature.

Nov 17 '05 #2

"BW" <so*****@somewhere.net> wrote in message
news:O5****************@TK2MSFTNGP14.phx.gbl...
Hi all! I'm not sure where to post this so I'm giving these a try. If
there
is a better (more appropriate) place to post please let me know.

I want to create a service (in C#). The service's purpose is to monitor a
given service, and when the service becomes disabled and/or stopped I want
to restart the service.

I have figured out how to restart a stopped service by using the
ServiceController.Start() method.

Obviously,this only works if the service is enabled. So, I must enabled
the
service before I can restart it.

Does anyone know how to re-enable the a service that had been disabled?
TIA
BW

I do have a very good reason for doing this and it is not malicious in
nature.

And what if your watchdog service gets stopped/disabled?

Willy.


Nov 17 '05 #3
BW
Good question, Willy!

The truth is, I really don't care.

Here's the situation: the powers that be have determined that there are
exploits in the debug service (MDM). So, periodically (twice per day
minimum) the active directory (don't know it that's the correct term here,
it's what they call it) goes out on the LAN and kills MDM and disables it.

This, of course, makes it next to impossible to debug. And the network
people refuse to single out the developer group.

So, when we are trying to debug and the and the service goes down, I have
written a batch file so devs can enable the service and restart it. and I'm
looking for a way to do this in code, so I can write a monitor service.

The thing that kills the debug service won't kill mine since they don't know
about it. they only kill "known" services.

I'm also not married to the idea of my app being a service. It could just as
easily be a windows app that sits in the background to do the monitoring.

-- BW

"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:Ox**************@TK2MSFTNGP10.phx.gbl...

"BW" <so*****@somewhere.net> wrote in message
news:O5****************@TK2MSFTNGP14.phx.gbl...
Hi all! I'm not sure where to post this so I'm giving these a try. If
there
is a better (more appropriate) place to post please let me know.

I want to create a service (in C#). The service's purpose is to monitor a given service, and when the service becomes disabled and/or stopped I want to restart the service.

I have figured out how to restart a stopped service by using the
ServiceController.Start() method.

Obviously,this only works if the service is enabled. So, I must enabled
the
service before I can restart it.

Does anyone know how to re-enable the a service that had been disabled?
TIA
BW

I do have a very good reason for doing this and it is not malicious in
nature.

And what if your watchdog service gets stopped/disabled?

Willy.

Nov 17 '05 #4
Hi,

I think that the easiest way to do it is updating the registry, in
System\\CurrentControlSet\\Services\\ServiceName there is a flag for this, I
do not remember the correct value but it's easy to see it.
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"BW" <so*****@somewhere.net> wrote in message
news:O5****************@TK2MSFTNGP14.phx.gbl...
Hi all! I'm not sure where to post this so I'm giving these a try. If
there
is a better (more appropriate) place to post please let me know.

I want to create a service (in C#). The service's purpose is to monitor a
given service, and when the service becomes disabled and/or stopped I want
to restart the service.

I have figured out how to restart a stopped service by using the
ServiceController.Start() method.

Obviously,this only works if the service is enabled. So, I must enabled
the
service before I can restart it.

Does anyone know how to re-enable the a service that had been disabled?
TIA
BW

I do have a very good reason for doing this and it is not malicious in
nature.

Nov 17 '05 #5

"BW" <so*****@somewhere.net> wrote in message
news:ek****************@tk2msftngp13.phx.gbl...
Good question, Willy!

The truth is, I really don't care.

Here's the situation: the powers that be have determined that there are
exploits in the debug service (MDM). So, periodically (twice per day
minimum) the active directory (don't know it that's the correct term here,
it's what they call it) goes out on the LAN and kills MDM and disables it.

This, of course, makes it next to impossible to debug. And the network
people refuse to single out the developer group.

So, when we are trying to debug and the and the service goes down, I have
written a batch file so devs can enable the service and restart it. and
I'm
looking for a way to do this in code, so I can write a monitor service.

The thing that kills the debug service won't kill mine since they don't
know
about it. they only kill "known" services.

I'm also not married to the idea of my app being a service. It could just
as
easily be a windows app that sits in the background to do the monitoring.

-- BW

I see, well, I suggest you don't put to much effort in this yourself and
simply use Process.Start to run sc.exe, this utility can do anything that
can possibly be done with a service.
Another option is to use System.Management and WMI.
Herewith is a small console program to give you a head start. Start this
program from the console window , disable mdm followed by a stop mdm, you'll
see that the service restarts and the is enabled again.

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Management;
class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEventWatcher w= null;
WqlEventQuery q;
ManagementOperationObserver observer = new ManagementOperationObserver();

// Bind to local machine
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true; //sets required privilege
try {
q = new WqlEventQuery();
q.EventClassName = "__InstanceOperationEvent";
q.Condition = @"TargetInstance ISA 'Win32_Service' and
TargetInstance.Name='mdm'";
q.WithinInterval = new TimeSpan(0,0,10); // poll interval 10 secs.
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(we.ServiceEventArrived);
w.Start();
System.Threading.Thread.Sleep(-1); // suspend thread

}
catch(Exception e) {
Console.WriteLine(e);
}
finally
{
w.Stop();
}

}

public void ServiceEventArrived(object sender, EventArrivedEventArgs e) {
ManagementBaseObject mbo =
(ManagementBaseObject)e.NewEvent["TargetInstance"];
if((bool)mbo["Started"] == false)
{
Console.WriteLine("Service:{0} stopped", mbo["DisplayName"]);
RestartService(mbo["Name"].ToString());
}
}

public void RestartService(string ServiceName)
{
ManagementPath myPath = new ManagementPath();
ManagementBaseObject outParams = null;
myPath.Server = System.Environment.MachineName;
myPath.NamespacePath = @"root\CIMV2";
myPath.RelativePath = "Win32_Service.Name='" + ServiceName + "'";
using (ManagementObject service = new ManagementObject(myPath))
{
// Set startmode to Automatic (auto start at boot )
ManagementBaseObject inputArgs =
service.GetMethodParameters("ChangeStartMode");
inputArgs["startmode"] = "Automatic";
outParams = service.InvokeMethod("ChangeStartMode", inputArgs, null);
// return check ignored for brevity
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
if(ret == 0)
Console.WriteLine("Service startmode changed");
else Console.WriteLine("Startmode Failed with error code: {0}", ret);
// Start service
outParams = service.InvokeMethod("StartService", null, null);
ret = (uint)(outParams.Properties["ReturnValue"].Value);
if(ret == 0)
Console.WriteLine("Service Restart Succeeded");
else Console.WriteLine("Failed with error code: {0}", ret);
}
}
}
Willy.
Nov 17 '05 #6
BW
Yep, sc is what I'm currently using in the batch file I wrote.

I was just looking to find a more elegant way rather than shelling out to do
it.

I'll take a look at the WMI stuff this weekend.

Thanks a lot, Willy!
Regards,
BW

"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:ey*************@TK2MSFTNGP15.phx.gbl...

"BW" <so*****@somewhere.net> wrote in message
news:ek****************@tk2msftngp13.phx.gbl...
Good question, Willy!

The truth is, I really don't care.

Here's the situation: the powers that be have determined that there are
exploits in the debug service (MDM). So, periodically (twice per day
minimum) the active directory (don't know it that's the correct term here, it's what they call it) goes out on the LAN and kills MDM and disables it.
This, of course, makes it next to impossible to debug. And the network
people refuse to single out the developer group.

So, when we are trying to debug and the and the service goes down, I have written a batch file so devs can enable the service and restart it. and
I'm
looking for a way to do this in code, so I can write a monitor service.

The thing that kills the debug service won't kill mine since they don't
know
about it. they only kill "known" services.

I'm also not married to the idea of my app being a service. It could just as
easily be a windows app that sits in the background to do the monitoring.
-- BW
I see, well, I suggest you don't put to much effort in this yourself and
simply use Process.Start to run sc.exe, this utility can do anything that
can possibly be done with a service.
Another option is to use System.Management and WMI.
Herewith is a small console program to give you a head start. Start this
program from the console window , disable mdm followed by a stop mdm,

you'll see that the service restarts and the is enabled again.

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Management;
class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEventWatcher w= null;
WqlEventQuery q;
ManagementOperationObserver observer = new ManagementOperationObserver();
// Bind to local machine
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true; //sets required privilege
try {
q = new WqlEventQuery();
q.EventClassName = "__InstanceOperationEvent";
q.Condition = @"TargetInstance ISA 'Win32_Service' and
TargetInstance.Name='mdm'";
q.WithinInterval = new TimeSpan(0,0,10); // poll interval 10 secs.
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(we.ServiceEventArrived);
w.Start();
System.Threading.Thread.Sleep(-1); // suspend thread

}
catch(Exception e) {
Console.WriteLine(e);
}
finally
{
w.Stop();
}

}

public void ServiceEventArrived(object sender, EventArrivedEventArgs e) {
ManagementBaseObject mbo =
(ManagementBaseObject)e.NewEvent["TargetInstance"];
if((bool)mbo["Started"] == false)
{
Console.WriteLine("Service:{0} stopped", mbo["DisplayName"]);
RestartService(mbo["Name"].ToString());
}
}

public void RestartService(string ServiceName)
{
ManagementPath myPath = new ManagementPath();
ManagementBaseObject outParams = null;
myPath.Server = System.Environment.MachineName;
myPath.NamespacePath = @"root\CIMV2";
myPath.RelativePath = "Win32_Service.Name='" + ServiceName + "'";
using (ManagementObject service = new ManagementObject(myPath))
{
// Set startmode to Automatic (auto start at boot )
ManagementBaseObject inputArgs =
service.GetMethodParameters("ChangeStartMode");
inputArgs["startmode"] = "Automatic";
outParams = service.InvokeMethod("ChangeStartMode", inputArgs, null); // return check ignored for brevity
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
if(ret == 0)
Console.WriteLine("Service startmode changed");
else Console.WriteLine("Startmode Failed with error code: {0}", ret);
// Start service
outParams = service.InvokeMethod("StartService", null, null);
ret = (uint)(outParams.Properties["ReturnValue"].Value);
if(ret == 0)
Console.WriteLine("Service Restart Succeeded");
else Console.WriteLine("Failed with error code: {0}", ret);
}
}
}
Willy.

Nov 17 '05 #7
changing this value directly will only confuse the SCM. The SCM uses the
registry to store state across reboots, but does not necessarily update its
state based on runtime registry changes. Use the SCM APIs, like
ChangeServiceConfig() (don't know the C# equivalent).

--
Please do not send e-mail directly to this alias. this alias is for
newsgroup purposes only.
This posting is provided "AS IS" with no warranties, and confers no rights.
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us> wrote
in message news:un*************@TK2MSFTNGP15.phx.gbl...
Hi,

I think that the easiest way to do it is updating the registry, in
System\\CurrentControlSet\\Services\\ServiceName there is a flag for this,
I do not remember the correct value but it's easy to see it.
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"BW" <so*****@somewhere.net> wrote in message
news:O5****************@TK2MSFTNGP14.phx.gbl...
Hi all! I'm not sure where to post this so I'm giving these a try. If
there
is a better (more appropriate) place to post please let me know.

I want to create a service (in C#). The service's purpose is to monitor a
given service, and when the service becomes disabled and/or stopped I
want
to restart the service.

I have figured out how to restart a stopped service by using the
ServiceController.Start() method.

Obviously,this only works if the service is enabled. So, I must enabled
the
service before I can restart it.

Does anyone know how to re-enable the a service that had been disabled?
TIA
BW

I do have a very good reason for doing this and it is not malicious in
nature.


Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Usman | last post by:
Hi I have a window service written in C#. I have another application that requires a lengthy process to be performed like taking backup. How can I make this lengthy process be performed by...
4
by: utkarsh | last post by:
Hi, I want to develop a Window Service in C# that should be capable of sisplaying the a icon in the window tray. Based on some logic in service, icon should be changed to some other...
4
by: drodrig | last post by:
Hi. I am trying to close/kill all processes that show visible windows on Windows XP. So far I've created a script that uses win32gui.EnumWindows to iterate through all windows, check for which...
4
by: ianyian | last post by:
hi experts, im doing some staff bween th the aspx + MS Word.chellcheck, and and which running on my ypc is no problem ( windows xp , activation by ASPNET ), buts someshow when i try to deploy to...
1
by: =?Utf-8?B?Vmlua2k=?= | last post by:
Hello Everyone, I have created a very simple window service. This window service in turn is calling a function that exist in a windows form. When I am trying to run this windows service. window...
7
by: =?Utf-8?B?Vmlua2k=?= | last post by:
public void sendKeysTest() { Process myProcess = Process.Start(@"C:\winnt\system32\cmd.exe"); SetForegroundWindow(myProcess.Handle); if (myProcess.Responding) SendKeys.SendWait("{ENTER}");...
2
by: =?Utf-8?B?YW5hbmQga3VtYXI=?= | last post by:
Hi, We have a requirement where windows service application XX will be deployed on two servers that is load balanced. The windows service polls the file directory and performs some logic when the...
0
by: henkya | last post by:
Language Used: C# Project Typed: Setup Project (for .NET Window Service) Hi Bump into this issue and seriously have a hunch that this is a bug in the .NET setup project. These are the scenario:...
0
by: olanger | last post by:
Let me explain the scenerio, I have a window service that has timer and OnElapsed timer event I'm calling a method. This method process business logic and It's multi threaded. The problem...when the...
2
by: gray d newbie | last post by:
Greetings All, This is my first time creating a Window Service and I am having this error message when I try to start my window service (currently known as Service1). Below is my code for Window...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.