Why won't this service start - c#

I have a Windows Service that I'm having some problems getting working.
The pertinent functions are as follows:
( Edited to reflect current )
static void Main()
{
if (Debugger.IsAttached)
{
ContinuumService Service = new ContinuumService();
Service.Start(new Object[] { });
while (true)
Thread.Sleep(1);
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ContinuumService()
};
ServiceBase.Run(ServicesToRun);
}
}
public ContinuumService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
My installer is set to 'Allow service to interact with desktop' ( as I cannot seem to get the service to install without this ), and I know that the service is being installed - but is incapable of starting for some reason.
It's my understanding that a service Start command will execute OnStart and wait for that method to complete. Upon completion if the process is still running, the service reports running... If this is skewed please let me know.
The exact error I am getting back from the installer is 'Service '[display name]' ([name]) failed to start. Verify that you have sufficient privileges to start system services.'; and from the log that is generated behind the installer, I get an error 1920 with the same message.
In either case - I can't come up with a valid reason why this would be the case. Any advice would be great.

I believe your problem is both the loops and lack of base.OnStart() and base.OnStop() calls. You can start and stop a basic service with no loops, and it will run perpetually. Example basic service that literally does nothing:
public class ExampleService : ServiceBase
{
private static void Main()
{
ServiceBase.Run(new[] { new ExampleService() });
}
public ExampleService()
{
// Name the Service
ServiceName = "Example Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
// Does nothing
}
protected override void OnStop()
{
base.OnStop();
}
}
Try implementing this, see that it works, and incrementally add your logic and test.

Apparently there was an issue in my installer. After flipping options off, on, back off, inside out, and every other direction I could, I somehow corrupted the MSI, and had to rebuild it. A full wipe of the original installer project and a fresh build installed the service successfully. This was an issue in Advanced Installer 9.3
Thanks.

Related

Correct way to kill service in C#, to be always recovered by SCM

We have a service that needs to kill itself (reason: we use a third party lib, that has unpredictable behavior in shutdown scenarios ...). Sometimes the service is not restarted by the Windows Service Control manager. The service recovery actions, in the SCM, are set to "Restart the Service" (for the first, the second and subsequent failures).
That's the way we kill our service:
public static void TerminateProcess(string message)
{
Log.ErrorFormat("Terminating Process becauses of: {0}", message);
Process.GetCurrentProcess().Kill();
}
Does anybody knows if this Process.GetCurrentProcess().Kill(); is a good way to kill the service?
I also read some threads, where the following combination was suggested:
class MyService : ServiceBase
{
void KillMe()
{
this.ExitCode = 1; // ServiceBase.ExitCode
System.Environment.Exit(1);
}
}
I also found this stackoverflow thread, but it doesn't state anything about service recovery.
What's the preferred/safe way to kill a service, so that the SCM will restart it?
Thx
Make a singleton instance of your service. And then you you can stop your service using stop() method.
public partial class ABCService : ServiceBase
{
public static ABCService ServiceInstance;
private void InitService()
{
ServiceInstance = this;
}
}
public static void StopService()
{
if(ABCService.ServiceInstance != null)
{
ABCService.ServiceInstance.Stop();
}
}
And you don't want the to restart automatically
public static void ChangeServiceMode(bool serviceAutoEnable)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\NixService", true);
if (key != null)
{
//Set service to manual / Automatic (Automatic = 2, manual = 3)
int serviceMode = serviceAutoEnable ? 2 : 3;
key.SetValue("Start", serviceMode, RegistryValueKind.DWord);
key.Close();
}
}
}
I think that it is necessary to understand: in what cases it is necessary to disable the service.
The first method you describe allows you to kill a service from a third-party code base. And the second option is in the service itself, but I think that the last option is not realizable, because the question arises: what circumstances should there be for the service to kill itself ???
IMHO the first option is more practical.

OnStart in serviceAppliction don't work

I building a service that will edit db data form me.I want to run Encrypt for connectionString when service starts/or recive reuqest and i can't catch the OnStart
What i am diing wrong?
My class
public class Service1 : IService1
{
protected void OnStart(string[] args)
{
string stop="";
//can't get here
//here Encrypt the section.
// section.SectionInformation.ProtectSection("DataProtectiond");
}
public string GetData(int value)
{
//my functions
}
}
While debugging a service it's very hard to catch the OnStart method. You can't run a service from Visual Studio, and in production, the OnStart method is already called before you can attach your debugger. What you can do is put the following code in the OnStart method:
System.Diagnostics.Debugger.Launch()
This will pop up a window where you can select a debugger. If you have Visual Studio solution already open, you can select this and the debugger will be attached to your service.
To "run your service" from Visual Studio, you can put something like this in your Main():
static void Main()
{
if (!Environment.UserInteractive)
{
// Startup as service.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyServices()
};
ServiceBase.Run(ServicesToRun);
}
else
{
//Start things locally here,
//for example the same things you do in the OnStart() method of your service
}
}
Now you can simply run the program from Visual Studio, but it will also work as a service when you install it on your production server...

Window Service not accessing external method

I m a bit new here . I am trying to learn window service from microsoft tutorial :
http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx
I installed and run it perfectly ..event logs are working Fine ...Now I am trying access One function in another c# project (named ASMSFetch) which has reference to the service project ...
This is Service .cs file code
public partial class MyNewService : ServiceBase
{
public MyNewService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ASMSFetch.Program.UpdateSMS();
}
}
and ASMSFetch Project Program.cs
public class Program
{
static void Main(string[] args)
{
UpdateSMS();
}
public static void UpdateSMS()
{
Console.WriteLine("UpdateSMS started");
Console.ReadLine();
}
But that "UpdateSMS started" messege doesnot appear when I install and run the service from computer management -> service section ..
I tried to search it .but couldnt able to find reasonable .
Any suggestion would be helpful ...
See here...
http://msdn.microsoft.com/en-us/library/76477d2t(v=vs.110).aspx
Under item #4 - you need to call your service. If the above is all your code, then you're missing that and nothing is actually starting the service. When the OS starts your service, all it does is call the Main() method, just like any other EXE.
You need to add a line like this:
System.ServiceProcess.ServiceBase.Run(new MyNewService());

Stop service without error "Service cannot be started. The handle is invalid"

I have WIndows Service app and want to stop service when main code is executed. I am trying to execute ServiceBase.Stop() in OnStart event, everything works fine, the service is stopped but I get annoying error message in event viewer
"Service cannot be started. The handle is invalid"
Any ideas how to stop windows service without errors?
public partial class VirtualServerInitService : ServiceBase
{
public ILogger EventLogger = new EventLogger();
public VirtualServerInitService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
EventLogger.Write("Starting service!");
new VirtualServerInit(EventLogger).Run();
EventLogger.Write("VirtualServerInit code was executed");
Stop();//This code works and also gives error in event viewer
}
protected override void OnStop()
{
EventLogger.Write("Stopping service!");
}
}
Use a thread to make sure the OnStart method finishes. The threadpool will put your workitem on the queue and once a thread it is available it will execute your Run method and then calls Stop on the service. By then the windows service manager already handled the succesful start of your service and hence no error will be sent to the Eventlog when Stop is called.
protected override void OnStart(string[] args)
{
EventLogger.Write("Starting service!");
ThreadPool.QueueUserWorkItem( _ => {
new VirtualServerInit(EventLogger).Run();
EventLogger.Write("VirtualServerInit code was executed");
this.Stop();
});
}
You might consider leaving the service running and use a CustomCommand to control if actual work needs to be done. For that you can override OnCustomCommand and send a pre determined integer to ask the service to perform a particular task for example by calling sc virtualsvc control 128 from the commandline.
protected virtual void OnCustomCommand(int command)
{
switch(command)
{
case 128:
new VirtualServerInit(EventLogger).Run();
EventLogger.Write("VirtualServerInit code was executed");
// maybe keep state if this only can be run once
break;
default:
EventLogger.Write(String.Format("Unknown control code:{0}", command));
break;
}
}

How to Create a C# Listener Service for MSMQ as a Windows Service

I'll start by saying I'm not a .NET developer, but have been thrown into a project where I need to use MSMQ so a classic ASP web application can send messages to a C# Windows Service that handles the processing. I have experience integrating other message queues with other languages, but like I mentioned, I don't have much experience with .NET and Windows development so some guidance would be much appreciated.
Here are my questions...
Could someone provide some basic C# code that listens to an existing MSMQ queue and responds to the new message by doing something simple like writing the current timestamp to a log file or sending an email?
How do I package this code up in Visual Studio .NET to create and install a Windows Service? (What type of project should it be, etc. I'm using Visual C# 2010 Express.)
Finally, I'm not sure which version and/or implementation of MSMQ I need to be using for my requirements with classic ASP. I think the COM version is what I need, but I've also read about a new WCF version, as well as differences between 3.0 and 4.0. Could someone please give me direction on which version I should be using?
Many thanks!
You can wait for a message on a given queue using the following code (You want to use the private queue named SomeQueue on your computer, named ComputerName => QueueName = #"ComputerName\private$\SomeQueue")
public void AsyncWatchQueue(object encapsulatedQueueName)
{
Message newMessage;
MessageQueue queue;
string queueName = encapsulatedQueueName as string;
if (queueName == null)
return;
try
{
if (!MessageQueue.Exists(queueName))
MessageQueue.Create(queueName);
else
{
queue = new MessageQueue(queueName);
if (queue.CanRead)
newMessage = queue.Receive();
}
HandleNewMessage(newMessage); // Do something with the message
}
// This exception is raised when the Abort method
// (in the thread's instance) is called
catch (ThreadAbortException e)
{
//Do thread shutdown
}
finally
{
queue.Dispose();
}
}
Note: the Receove method will block untill a message is received at which point it'll remove the message from the queue and return it.
edit: added code for the implementation of the multithreaded portion (and renamed the above method signature)
Thread Creation Code:
public Thread AddWatchingThread(string QueueName)
{
Thread Watcher =
new Thread(new ParameterizedThreadStart(AsyncWatchQueue));
Watcher.Start(QueueName);
// The thread instance is used to manipulate (or shutdown the thread)
return Watcher;
}
I'll just note, that this is untested cod, it's just an quick example
As far as I know, Visual Studio Express does not have a project template for a service. That does not mean you cannot write a windows service with VSE, just that you will not have a template to get you started.
To create a service you can just create a normal Console application. Create the service class which will be responsible for the actual service implementation. It will look something like this
using System.ServiceProcess;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
Then the Service startup code can go into the Main function of your service.
using System.ServiceProcess;
namespace WindowsService1
{
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
That should give you the basic framework for your service. The other thing you will need is to add an installer for the service so that it can be installed as a service. The following should get you started, note I have note tested this.
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace WindowsService1
{
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller serviceProcessInstaller1;
private ServiceInstaller serviceInstaller1;
public ProjectInstaller()
{
this.serviceProcessInstaller1 = new ServiceProcessInstaller();
this.serviceInstaller1 = new ServiceInstaller();
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceInstaller1.ServiceName = "Service1";
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
}
}
Given the above, you should have enough to search around or ask for more details around the service creation. As for the MSMQ listener, you can use the following MSDN article as a starting point
http://msdn.microsoft.com/en-us/library/ms978425.aspx

Categories

Resources