How to auto start window service - c#

I have a window service which i developed in c# (vs2008).
please tell me what should i do to make it auto start after installation and also auto start on every time when system gets restarted.
EDIT:
I am using setup & deployment project to install it.
Thanks

Follow the instructions given here to add an installer to your Service application. Pay particular attention to step 5, where you set the StartType property.
To start the service after installation, see Automatically start a Windows Service on install

Try following way,
private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
var service = new ServiceController(serviceInstaller.ServiceName);
if (service.Status != ServiceControllerStatus.Running)
{
service.Start();
}
}

Related

c# ManagedInstallerClass.InstallHelper blocks service executable

I am trying to do some kind of Installer where i need to install a WinService.
What I currently do is adding the Service.exe as Resource to my Installer Project, then write all bytes of it to a specific folder.
After successfully writing the file to a specified folder, i install the service using ManagedInstallerClass.InstallHelper
The problem i've with it now is that the ManagedInstallerClass.InstallHelper is somehow locking the Service executable, so i cannot delete/overwrite the file (from outside or inside the program), because it's blocked while the Installer Application is running, beginning from first ManagedInstallerClass.InstallHelper call on the Service file.
Here is my code which causes this problem.
private void button1_Click(object sender, EventArgs e)
{
try
{
UninstallAndStopServiceIfExist("RDPBFP_Service");
}
catch (Exception)
{
MessageBox.Show("Service not running, so cannot stop it!");
}
Thread.Sleep(1000);
//File.Delete(#"C:\RDPBFP\RDP-Bruteforce-Protector_Service.exe");
Directory.CreateDirectory(#"C:\RDPBFP");
File.WriteAllBytes(#"C:\RDPBFP\RDPBFP_Service.exe", Properties.Resources.RDPBFP_Service);
try
{
ManagedInstallerClass.InstallHelper(new string[] { #"C:\RDPBFP\RDPBFP_Service.exe" });
}
catch (Exception i_ex)
{
MessageBox.Show(i_ex.Message);
}
//StartService("RDPBFP_Service");
}
So it works fine at first time running it, but second time running it crashes at File.WriteAllBytes.
The service is not running, Windows clearly tells me it's used by my Installer Application when trying to delete it from Windows Explorer.
I'd really appreciate an beginner(which i am) friendly explanation why this happens the way i do it and in best case a solution. I found this post but this did not worked for me.
Thanks in advice.
PS: I know there are Setup Projects and more convenient/professional things, but thats not what i need/want
Well i am now installing it via cmd Process and sc create, still wonder why the InstallHelper wont release the file after installed successfully

C# Service installer - Upgrade install not stopping service before uninstall

Please review the code below for my project installer BeforeInstall event. The event is being called, as the install completes successfully and will uninstall my service, before installing the new one, but ONLY if I stop the running service before running the installer for the new version.
For some reason, the code in the event is either not stopping the service, or it is not waiting for the service to stop, both of which I am telling it to do before going on to uninstall the service - which again, will complete successfully if the service is not running. It does not appear to even stop the service because after I get the error that resources are in use, I look in services and see that the service is indeed still running. For reference I have also included the AfterInstall event which successfully starts my service.
[EDIT]
It seems like the check to see if the resources are in use is occurring before my event fires. Actually, I've since tried multiple events from the installer and service installer to no avail. Such as OnBeforeUninstall... etc... I've tried multiple methods of shutting down the process including opening cmd.exe and running sc stop on my service. It does not even attempt to run cmd.exe before it checks if resources are in use. Is there a better place to run the service stop code before the resource check happens? I've even thrown it in before Initialize component on the project installer class. Does anyone know when the resource check happens?
void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e)
{
List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());
foreach (ServiceController s in services)
{
if (s.ServiceName == this.serviceInstaller1.ServiceName)
{
if(s.Status == ServiceControllerStatus.Running)
{
s.Stop();
s.WaitForStatus(ServiceControllerStatus.Stopped);
}
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
ServiceInstallerObj.Context = new InstallContext();
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.ServiceName = s.ServiceName;
ServiceInstallerObj.Uninstall(null);
break;
}
}
}
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
using (ServiceController s = new ServiceController(serviceInstaller1.ServiceName))
{
s.Start();
}
}

How can a windows service programmatically restart itself when another windows service is restarted?

I work on windows service project , i want to restart my windows service when Lync Front-End service was restarted
i know how i restart my windows service i use this answer , but i don't know how i restart it when the Front-End Service was restarted
and i know i can check the windows service status by use ServiceController Class
Run this code in your service :
EventLog log = EventLog.GetEventLogs().First(o => o.Log == "Security");
log.EnableRaisingEvents = true;
log.EntryWritten += (s, e) => {p.print(e); };
Write a method for event log
void test(EntryWrittenEventArgs entry)
{
//you can check event log in the log viewer and set
//EventLogEntryType and InstanceId accordingly.
EventLogEntry evntLog=entry.Entry;
if (evntLog.EntryType == EventLogEntryType.SuccessAudit &&
evntLog.InstanceId==123)
{
//Code to restart the service
}
}
I) Topshelf is an open source project for developing Windows Services easily. It will save you time and even if you decide not to use it, you can learn from it's source code.
II) The short answer is you have to poll the status of the other service. There is no (plain) event based mechanism for this.
If you can not make any modifications to the other service then you can poll over it's status by (in a separate Task):
var sc = new ServiceController(serviceName);
status = sc.Status;
And use the answer you've mentioned to restart yours (and again poll in OnStart until the other service get started completely).
But if you can modify the other service then you can use other means like pipes or named mutexes to do that (again needs polling in a separate Task or at OnStart and probably at OnStop).

C# about Windows service

What would be a short example with a Windows service and how to install and run it?
I've searched on the Internet, but what I've tried didn't have anything written on the On Start method. Plus, when I've tried to install it the error OpenSCManager keeps popping up.
Find install util at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
Then run InstallUtil.exe "c:\myservice.exe"
Go to services.msc and then locate and start your service
Here are some examples about how to write and install a Windows service in C#:
A Windows Service Application
Simple Windows Service Sample
ASP.NET Tutorials : Creating Windows Service in C#
Creating a Windows Service in C#
How to Create and Work With Windows Services in C#
Creating a Simple Windows Service in C#
My answer to this question gives you step-by-step instructions for creating a Windows service in C#.
Easiest language for creating a Windows service
My answer to this question shows you have to modify the service so that it can install and uninstall itself from the command line.
How to make a .NET Windows Service start right after the installation?
InstallUtil.exe has been part of .NET since 1.1, so it should be on your system. However, you likely can't use it from a 'normal' command prompt. If you have Visual Studio installed, open the Visual Studio command prompt. That'll define the appropriate environment variables that make InstallUtil accessible without path information.
The OnStart() callback gives you an opportunity to start the business logic of your service. If you don't do anything in the OnStart() callback, your service will immediately shut down. Typically, you'll start a thread that performs the work you're interested in. Here is a small example to show you what it looks like.
private static System.Timers.Timer _timer;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Write a message to the event log.
string msg = String.Format("The Elapsed event was raised at {0}", e.SignalTime);
EventLog.WriteEntry(msg, EventLogEntryType.Information);
}
protected override void OnStart(string[] args)
{
// Create a timer with a 10-econd interval.
_timer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Signal the timer to raise Elapsed events every 10 seconds.
_timer.Start();
}
protected override void OnStop()
{
// Stop and dispose of the timer.
_timer.Stop();
_timer.Dispose();
}
Doing something like this will effectively keep your service running until it shuts down. Hope this helps.

c# Windows Service Console.Writeln

I wrote, installed, and successfully started a Windows Service in c# that does nothing :) Initially I just want echo stuff to the console, db queries the service makes etc. I used the OnStart in my service, but from a cmd prompt when I do a net start "My Service" where do these messages show up?
I'm open to better ways. I'm new to this and feeling my way through it step by step by echoing back to the console my progress. Should I echo to the event log instead? How do I do that?(I know, I know, google it)
protected override void OnStart(string[] args)
{
base.OnStart(args);
Console.WriteLine("Sham-Wow!");
}
You cannot write the console from a Windows Service.
I recommend you using any logging utility, such as log4net.
The second alternative is writing to the Event Log (System.Diagnostics.EventLog)
Try System.Diagnostics.Trace.WriteLine and you will see your messages in Output window of Visual Studio or with dbgview utility.
If you want to run your application as a console application (so you can see your console output) or as a service you can achieve this with the following:
Ensure that your application is compiled as a Console application.
Alter the application's Main method so that you can branch for service or console execution.
Run your application as follows to get a console "myservice.exe /console".
It's been years since I have done this so might need a little tweaking, but something like follows:
static void Main(string[]] args)
{
if (args.Length == 0)
{
//Service entry
System.ServiceProcess.ServiceBase[] services;
services = new System.ServiceProcess.ServiceBase[] { new WinService1() };
System.ServiceProcess.ServiceBase.Run(services);
}
else
{
//Console entry
OnStart(args);
}
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
Console.WriteLine("Sham-Wow!");
}
This is fine for some early experimentation, but I would recommend Log4Net once you have got your head around things.
The most common/accepted way of communicating the status of your service is to write to the Windows Event Log.
For easier debugging, I would recommend that you put all of your business code into a separate class from the service component. You can then use that class from either your service, or from a console application. While you are creating the service, you will use the console application to host your component, so that you can easily step-into the code.
Very old question, but very relevant. This is how I implemented a logging mechanism that I could inspect while the Windows service is running.
Create a log file. My favorite is Log4net as mentioned before.
Open PowerShell and run this command Get-Content "path/to/file.log" -Wait
You will be able to monitor the file as it changes. This is like the tail command in linux.

Categories

Resources