I have a windows service application. When I press the button, I want to start the service. But I'm receiving the following the error.
Window Service Start Failure:
Cannot start service from the command line or debugger. A Windows
Service must first be installed (using installutil.exe) and then started
with the ServerExplorer, Windows Service Administrative tool or the NET
START command.
C# Code:
namespace WindowsFormsApplication1
{
partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
RegistryKey KEY = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\baslat", true);
KEY.DeleteValue("timer",true);
}
protected override void OnShutdown()
{
RegistryKey KEY = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\baslat", true);
KEY.SetValue("timer","");
}
}
}
It's telling you what to do. You need to install the service inside windows. Then you can stop and start it using the windows service control manager.
You can't start it like an exe as services have different entry points. However there is nothing stopping you from having an exe that runs under the SCM and as a normal program.
You need to install the service, as the error message suggest :
installutil.exe yourservice.exe
Then you can start it with :
net start yourservice
Related
I'm trying to write a Windows service that opens a program when it starts/restarts. I doubt it makes a difference but it's a spreadsheet program like Excel just in case it's important to this task. It's located at the root of my D: drive. Process.Start works just fine in this console program (so I know I'm using it right):
namespace Example
{
public class Program
{
public static void Main()
{
System.Diagnostics.Process.Start(#"D:\program.exe");
}
}
}
I followed this guide: https://learn.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer to write my own service. I have that exact same line in the OnStart method of my service project as seen here:
protected override void OnStart()
{
System.Diagnostics.Process.Start(#"D:\program.exe");
}
I opened the install utility as administrator and successfully built and installed as described in the guide. Nothing was happening when I started the service, so I looked up how to debug a service. I changed my OnStart method to:
protected override void OnStart()
{
System.Diagnostics.Debugger.Launch();
System.Diagnostics.Process.Start(#"D:\program.exe");
}
While stepping through my code, I could see Process.Start threw an InvalidOperationException error. I read up on it (https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception?view=netframework-4.7.2) but I'm stuck as to how to resolve it. I tried the local user, local service, and system service accounts when building and installing, but none helped. Has anyone launched executables in a service?
I am not able to detect this Logon event in Windows.
Here is my code:
namespace ConsoleApplication2
{
public class MyService: ServiceBase
{
public MyService()
{
CanPauseAndContinue = true;
CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
base.OnSessionChange(changeDescription);
}
}
class Program
{
static void Main(string[] args)
{
MyService tpl = new MyService();
Thread t = new Thread(delegate()
{
while (true) { }
});
t.Start();
}
}
}
How do I test run this app and then remote desktop into my laptop? I can see the event generated in Windows EventViewer, but my OnSessionChange is never called (I added a breakpoint inside).
Is my code wrong or is the way I am testing wrong?
Normally multiple concurrent remote desktop sessions are not allowed on any of Windows desktop systems. So to use RDP to login as a different user then I assume that you have hacked this, or are using windows server (which rules out XP!).
Regardless, each user logged into the system will therefore have their own applications running and each set of applications are unique to that user. So App1 could be run independently by each user.
That means that your console application cannot detect the other user that is logged on.
To do this you must use a Windows Service. This runs in the background and can detect and work for multiple users and also detect login and logout. See this SO link
This is the purpose of inheriting MyService from ServiceBase. If you are not running the application as a service, then you are not running it correctly!
You need to first install your application as a service and then run it like a service.
You say that you don't think your application can run as a service. I'm not sure why, but if this is the case then you would have to instead look at creating some kind of script to run your application upon start-up/login.
This way, every time somebody logs in then your application would run. This might anyway be simpler for you.
I have created a c# windows service
when I put my visual studio in debug mode and I run it , it works correctly
but when I create a setup and install it , it doesn't work(means the service installed correctly and start but my code doesn't running).
(I built setup like this https://support.microsoft.com/en-us/kb/816169)
this is my Code:
This is my Code : dropbox.com/s/eq13fng88gk714u/myTelephone.zip?dl=0
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
myTelephone myService1 = new myTelephone();
myService1.onDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new myTelephone()
};
ServiceBase.Run(ServicesToRun);
#endif
}
And
public partial class myTelephone : ServiceBase
{
public myTelephone()
{
InitializeComponent();
} public void onDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
//////save some data in sql server
}}
Did you even try to google this before asking?
Anyways, just use Topshelf via nuget. This way you always execute the same code when debugging and when it's installed.
As you didn't provide anything except of 'it does not work', I'll try to assume:
either your Windows service is not being installed - then see the 'your service executable'.exe.InstallLog file in the same folder where 'your service executable' is located;
or the Windows service was installed successfully but it doesn't start - then go to the Event Viewer and look for the error message there related to your service. If that's the case then most probably that's because your OnStart method goes to timeout. In this case:
Either request additional time inside the method:
// request additional 4 seconds for the start-up process
this.RequestAdditionalTime(4000);
or move the code that access the SQL database out of the method, for example, creating a new thread and doing all your staff there.
I think you are trying to install this by clickicg exe file. It is not correct.
Try next:
Open cmd
cd to directory with myTelephone.exe
run next
sc create myTelephone binpath= "myTelephone.exe" start= auto
net start myTelephone
Or you also could do add to pre-build event:
net stop $(ProjectName)
sc delete $(ProjectName)
exit /b 0
As post-build event:
sc create $(ProjectName) binpath= "$(TargetPath)" start= auto
net start $(ProjectName)
And on each build you will have installed service.
I am working on an asp.net MVC-5 web project where i have to send daily email to all users. And i know there are 2 ways to achieve this:
Windows service
Sql server agent job.
I have decided to use Windows service. I am working on Express Version of Visual Studio 2013 for Web, so Windows service template is not present in it. After digging a lot i have created a windows service as console application in Visual Studio. Here's the code:
Service
public class FirstService : ServiceBase
{
public FirstService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.EventLog.WriteEntry("FirstService Service Has Started");
}
protected override void OnStop()
{
this.EventLog.WriteEntry("FirstService Service Has Stopped");
}
private void InitializeComponent()
{
this.ServiceName = "FirstService";
this.CanStop = true;
this.AutoLog = false;
this.EventLog.Log = "Application";
this.EventLog.Source = "FirstService";
}
}
Installer
[RunInstaller(true)]
public class MyServiceInstaller : Installer
{
private ServiceProcessInstaller FirstServiceProcessInstaller;
private ServiceInstaller FirstServiceInstaller;
public MyServiceInstaller()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.FirstServiceProcessInstaller = new ServiceProcessInstaller();
this.FirstServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.FirstServiceProcessInstaller.Username = null;
this.FirstServiceProcessInstaller.Password = null;
this.FirstServiceInstaller = new ServiceInstaller();
this.FirstServiceInstaller.Description = "FirstService Service Template";
this.FirstServiceInstaller.DisplayName = "First Service";
this.FirstServiceInstaller.ServiceName = "FirstService";
this.FirstServiceInstaller.StartType = ServiceStartMode.Manual;
this.Installers.AddRange(new Installer[] { this.FirstServiceProcessInstaller, this.FirstServiceInstaller });
}
}
Main
static class Program
{
[STAThread]
static void Main()
{
ServiceBase.Run(new FirstService());
}
}
After this i have successfully installed this service using installutil.exe and can successfully start and stop service from Control Panel -> Administrative Tools -> Serivces.
Upto this everything is good.
Now as i mention earlier i want to use windows service in my mvc-5 application for sending automatic email to my application users, i have some questions:
How i will integrate Windows Service in my asp.net mvc-5 application?
How i will deploy the application to the server?
How i will install the windows service on my application hosting server?
Please suggest me any good tutorial which contains the example, if possible.
Thanks!
Let me suggest two more options:
Create a console application and use Task Scheduler to invoke it at a given time. This option is really simple.
Use Quartz.net. This option may be valid in case you are using a shared host environment.
I donĀ“t understand what you mean by integrating windows service in your mvc application.
They are two different processes, so you need to implement any sort of communication between processes (e.g. through database, file, messaging, etc).
You can invoke a controller action using HTTPWebRequest / WebClient class, the controller action will send the mails to users.
2 & 3 : You need to follow the same steps as you did in the local development system.
Hope it helps
I've created a run of the mill C# Windows Service using the windows service project template. I've been able to install it correctly, and start and stop it without any issues.
However, when I go to my event viewer to see the log of it starting and stopping, I get nothing.
Here's the sample code I'm testing:
public MyService()
{
InitializeComponent();
ServiceName = "My Data Service";
EventLog.Log = "Application";
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("Starting My Data Service");
}
protected override void OnStop()
{
EventLog.WriteEntry("Ending MyData Service");
}
Also, my OS is Windows Vista.
If you want it to log to the default log use
EventLog.WriteEntry("Starting My Data Service", EventLogEntryType.Information);
Of course, you have to ensure that the service is running under an account with sufficient privileges to write to the log and to "run as a service".
Found this example on SO, Best Way to write to the event log
Here's an example where you specify the source too, rather than displaying as .NET Runtime... MSDN Example
EventLog requires an EventSource created to be able to write.