I have a windows service that is having trouble executing the Onstart() method after installing it and running it from the service menu.I'm logging everything that is happening at every step of the execution to see where the problem is. But there is no error, it logs and runs fine in the main method , up until the service is actually called to run and then it just does nothing.
It's interesting to note that it doesn't have ANY problem running in debug.
My program class(starting point) from which the service is called :
public class Program
{
private static Container _container;
private static ILogger<Program> _logger;
/// <summary>
/// The main entry point for the application.
/// </summary>
private static void Main()
{
_container = SimpleInjectorContainer.Build(registerConfig: true, useThreadScopedLifestyle: true);
SimpleInjectorContainer.LoggAndVerify(_container);
using (ThreadScopedLifestyle.BeginScope(_container))
{
try
{
_logger = _container.GetInstance<ILogger<Program>>();
_logger.LogInformation("Test - Works");
VerifyConfiguration();
}
catch (Exception ex)
{
var logger = _container.GetInstance<ILogger<Program>>();
logger.LogError(ex, "Configuration is not valid");
throw;
}
if (Environment.UserInteractive)
{
RunDebug();
}
else
{
System.Diagnostics.Debugger.Launch();
_logger.LogInformation("It's Here 49");
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
_container.GetInstance<SenderService>()
};
_logger.LogInformation("It's Here 56");
//up until here its fine, but it doesn't run the next line
ServiceBase.Run(ServicesToRun);
_logger.LogInformation("It's Here 58");
}
}
}
private static void RunDebug()
{
var senderService = _container.GetInstance<SenderService>();
senderService.TestStart();
Console.WriteLine("Sender Started Debug");
Console.ReadLine();
senderService.TestStop();
}
private static void VerifyConfiguration()
{
var configValidator = _container.GetInstance<IConfigurationValidator>();
configValidator.VerifyOperatorPrefixNumbers();
configValidator.VerifyConfiguration();
configValidator.VerifyOperators();
}
}
My actual service :
public partial class SenderService : ServiceBase
{
private readonly Container container;
private readonly ILogger<SenderService> logger;
private readonly ISmsHandlerConfig config;
private readonly IConfigurationValidator configValidator;
public SenderService(
Container container,
ILogger<SenderService> logger,
ISmsHandlerConfig config,
IConfigurationValidator configValidator)
{
this.InitializeComponent();
this.container = container;
this.logger = logger;
this.config = config;
this.configValidator = configValidator;
}
public void TestStart()
{
Console.WriteLine($"Starting {ServiceName} service");
this.OnStart();
}
public void TestStop()
{
Console.WriteLine($"Stopping {ServiceName} service");
this.OnStop();
}
protected void OnStart()
{
try
{
this.logger.LogInformation($"{this.ServiceName} starting");
SmsHandlerAction();
}
catch (Exception ex)
{
this.logger.LogError(ex, $"Error starting service {this.ServiceName}");
throw;
}
}
protected override void OnStop()
{
try
{
this.Dispose();
this.logger.LogInformation($"{this.ServiceName} stopped");
}
catch (Exception ex)
{
this.logger.LogError(ex, $"Error stopping service {this.ServiceName}");
}
}
private void SmsHandlerAction()
{
while (true)
{
this.logger.LogInformation($"{this.ServiceName} started");
using (ThreadScopedLifestyle.BeginScope(this.container))
{
var smsSenderService = this.container.GetInstance<ISmsSenderService>();
var sendResult = smsSenderService.SendSms(this.container);
// Wait if there are not messages for sending
if (!sendResult && this.config.IdleTimeMiliseconds != 0)
{
Thread.Sleep(this.config.IdleTimeMiliseconds);
}
}
}
}
}
this is what is logged:
2019-02-12 18:02:18.7972 INFO Test - Works
2019-02-12 18:02:20.6370 INFO It's Here 49
2019-02-12 18:02:20.6410 INFO It's Here 56
and after I stop the service :
2019-02-12 18:02:35.7375 INFO SenderService stopped
2019-02-12 18:02:35.7375 INFO It's Here 58
It missing the this.logger.LogInformation($"{this.ServiceName} starting"); part.
It doesn't log the line in the onstart method , because it never actually executes, I checked if the service was running, but just failed to log and that is not the case.
My IDE is VS 2017, OS is Win 7, DI library is SimpleInjector 4.0.12.
I know about a similar question asked on stackoverfllow(this) but I don't see how it solves my problem.
Also my event viewer doesn't log any problems also, only information about it starting successfully.
I'm pretty lost so any guidance will be of help.
I found the problem, it was because I removed the override on the OnStart().
Related
I have developed a C# Windows service to get some datas from DB and process them in an infinite loop. The service was working fine with nothing but loop in it yesterday but today I have finished the development and tried to test it as a Windows service but it keep says Starting and when the green bar is complete it gives me "1053" error. I have checked if there are any logs and my service is inserting logs and even processing Datas but somehow I still get this error.
I have installed the service from my release folder. There is no error on Event Viewer regarding the service. And my service looks like below.
*UPDATE: When I check event viewer I see below messages in a sequence; "Session 1 started", "Ending Session 1" "Machine restart required". I have tried restarting but it didn't make any difference
Program.cs
static class Program
{
static void Main()
{
try
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new spService()
};
ServiceBase.Run(ServicesToRun);
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
}
}
}
Service1.cs
public partial class spService: ServiceBase
{
public spService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
SpPushOperation spo = new SpPushOperation();
spo.StartSpPushOperation();
}
protected override void OnStop()
{
SpPushOperation spo = new SpPushOperation();
spo.StopSpPushOperation();
}
}
SpPushOperation.cs
class SpPushOperation
{
public readonly NLog.ILogger Logger = NLog.LogManager.GetCurrentClassLogger();
public void StartSpPushOperation()
{
try
{
Logger.Info("-------------");
Logger.Info("SpPushOperation Started..");
Logger.Info("-------------");
while(true)
{
//some process in here
}
}
catch(Exception e)
{
Logger.Info("!!!!!!!!!!!!!!");
Logger.Info("Error on getting StartSpPushOperation Error: " + e);
Logger.Info("!!!!!!!!!!!!!!");
}
}
}
Any help would be appreciated. Thanks.
Issue was caused due to using infinite loop in service. To fix this issue instead of using infinite loop start the service with a thread and run for every 60 seconds.
I'm doing a base project for windows services with the posibility to debug the Windows Service in console and I'm havig a problem with install.
I get the error 1053. InvalidOperationException. The service did not respond in a timely maner. I have done in the past Windows Services following this practices and I have never seen this error.
I have beetn trying with console or without it and always fails. I don't know what could be the cause of the error because the service is extremly simple with no blocking operations or something like that.
The exception is thrown in AfterInstall event in the installer.
MainClass
public class Program
{
enum RunMode { NONE, INSTALL, UNINSTALL, CONSOLE, RETHROW};
static int Main(string[] args)
{
RunMode runMode = GetRunMode(args);
try
{
switch (runMode)
{
case RunMode.INSTALL:
SelfInstaller.Install(args);
break;
case RunMode.UNINSTALL:
SelfInstaller.Uninstall(args);
break;
case RunMode.CONSOLE:
RunConsoleMode();
break;
case RunMode.RETHROW:
RunService();
break;
default:
break;
}
return 0;
}
catch (Exception ex)
{
if (runMode == RunMode.RETHROW) throw;
Console.WriteLine($"Error Running: {ex.Message}");
return -1;
}
}
private static RunMode GetRunMode(string[] args)
{
foreach (string arg in args)
{
switch (arg)
{
case "-i":
case "-install":
return RunMode.INSTALL;
case "-u":
case "-uninstall":
return RunMode.UNINSTALL;
case "-c":
case "-console":
return RunMode.CONSOLE;
case "-r":
return RunMode.RETHROW;
default:
Console.WriteLine($"Argument not expected {string.Join("|", args)}");
break;
}
}
return RunMode.NONE;
}
private static void RunService()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new WinService() };
ServiceBase.Run(ServicesToRun);
}
private static void RunConsoleMode()
{
var srv = new WinService();
Console.WriteLine("Starting ...");
srv.StartUp();
Console.WriteLine("System running; press any key to stop");
Console.ReadKey(true);
srv.ShutDown();
Console.WriteLine("System stopped");
Console.ReadLine();
}
}
Windows Service
internal class WinService : ServiceBase
{
#region Windows Service Lifecycle
protected override void OnStart(string[] args)
{
base.OnStart(args);
StartUp();
}
protected override void OnStop()
{
ShutDown();
}
#endregion
#region Start and StopMethods
public void StartUp()
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Service Started");
}
public void ShutDown()
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Service Stopped");
}
#endregion
}
Service Installer
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
public MyServiceInstallerProcess()
{
this.Account = ServiceAccount.LocalSystem;
}
}
[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
public MyServiceInstaller()
{
this.Description = ConfigurationManager.AppSettings["ServiceDescription"];
this.DisplayName = ConfigurationManager.AppSettings["ServiceDisplayName"];
this.ServiceName = ConfigurationManager.AppSettings["ServiceName"];
this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.AfterInstall += ServiceInstaller_AfterInstall;
this.BeforeUninstall += ServiceInstaller_BeforeUninstall;
}
void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
using (ServiceController sc = new ServiceController(this.ServiceName))
{
sc.Start();
}
}
void ServiceInstaller_BeforeUninstall(object sender, InstallEventArgs e)
{
using (ServiceController sc = new ServiceController(this.ServiceName))
{
if (sc.Status == ServiceControllerStatus.Running)
{
sc.Stop();
}
}
}
}
We've developed SignalR selfhost server in "c#.net as window services" and accessed by mobile application as client. We've developed with help of this link http://www.asp.net/signalr/overview/deployment/tutorial-signalr-self-host.
This window services is running fine and after couple of days, mobile server could not response to the mobile client. We didn't know the reason why server is not working after couple of days.But window service is running successfully only didn't response to mobile client.
Also we tried restart service for every 6 hours but still we have no solution. Our code on server side is
Startup class
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR(new HubConfiguration() { EnableJSONP = true });
}
}
Service class
public partial class MobileService : ServiceBase
{
//SignalR
private IDisposable signalR { get; set; }
public string App_ServerURL = null;
public MobileHub obj_HubCMobileServer = new MobileHub();
public MobileService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
App_ServerURL = "http://192.168.1.4:8888";
obj_HubCMobileServer.Init();
Task.Run(() => StartServer());
}
catch (Exception ex)
{
MobileService.Instance.server_Log(ex.Message + ex.StackTrace);
}
}
private void StartServer()
{
try
{
// server_Log("SignalR server init " + App_ServerURL);
signalR = WebApp.Start(App_ServerURL);
server_journal("SignalR server started at " + App_ServerURL);
GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(50);
}
catch (Exception ex)
{
server_Log(ex.Message + ex.StackTrace);
return;
}
}
HUB class
public class MobileHub : Hub
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MobileHub>();
static readonly object thisLock = new object();
System.Timers.Timer timer = new System.Timers.Timer();
public void Init()
{
try
{
timer.Enabled = true;
timer.Start();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
}
catch (Exception ex)
{
MobileService.Instance.server_Log(ex.Message + ex.StackTrace);
}
}
.....
.....
.....
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
return (base.OnReconnected());
}
}
Anyone could you give solution or is there anyway restart mobile SignalR selfhost server for every 12 hours?
I'm working on a function which need to run every hour and i adopted service way to write. but now i'm facing issues in running service while in debug mode help.
every thing looks fine to me, code start from debug section and calculation started but here is the problem when i try to get the distinct elements from db the service code stops.
//main
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Service1 myService = new Service1();
myService.onDebug();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
//*********************************************************
//Service.cs code is here
public Service1()
{
InitializeComponent();
}
public void onDebug()
{
OnStart(null); //untill now working fine
}
protected override void OnStart(string[] args)
{
try
{
//this is the function i want to run every hour, i have made successfully perfect in a console application but in window service its not working
var hourlyTimer = new System.Threading.Timer(e => hourlyCalculateSummaryForAllDevices(), null, TimeSpan.FromMinutes(0), TimeSpan.FromMinutes(0));
}
catch (Exception ex)
{
string msg = ex.Message;
}
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "ServiceStarted.txt");
}
protected override void OnStop()
{
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "HourlySummaryServiceStopped.txt");
}
//*********************************************************
//hourly Summary calculation functions
public static void hourlyCalculateSummaryForAllDevices()
{
findDistinctAssets(); //ok f11 pressed when cursor come here
}
static async void findDistinctAssets()
{
var collection = _database.GetCollection<BsonDocument>(telemetryCollectionName);
var filter = new BsonDocument();
var cursor = await collection.DistinctAsync<Int64>("AssetName", filter);
//while (await cursor.MoveNextAsync()) //here the service code stopped automatically, im stuck why?
//{
var assets = cursor.Current;
foreach (var asset in assets)
{
CalculateSummaryOfAssets(Convert.ToInt64(asset));
}
Console.Read();
//}
}
I try to create a windows service which automatically startsup.
I am able to install and deinstall the service. If I try to start it, I get following error message: "Der Dienst antwortete nicht rechtzeitig auf die Start- oder Steueranfrage". (I try to translate) "The service don't respont in time on start or control request".
Here is my poor code
public class LisaServerService: System.ServiceProcess.ServiceBase
{
private Program lisaServerServiceProgram;
public static string LisaServiceName = "LISA-ServerService";
[STAThread]
public static void Main(string[] args)
{
LisaServerService lisaServerService = new LisaServerService();
if (Environment.UserInteractive)
{
lisaServerService.OnStart(args);
Console.WriteLine("I am a service. Normally you can't see the console... just ignore me");
Console.ReadLine();
lisaServerService.OnStop();
}
else
{
ServiceBase.Run(lisaServerService);
}
}
public LisaServerService()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.CanShutdown = true;
this.ServiceName = "LISA - ServerService";
this.CanPauseAndContinue = true;
this.lisaServerServiceProgram = new Program();
}
protected override void OnStart(string[] args)
{
lisaServerServiceProgram.Start(null);
base.OnStart(args);
}
protected override void OnStop()
{
lisaServerServiceProgram.Stop();
base.OnStop();
}
protected override void OnShutdown()
{
OnStop();
base.OnShutdown();
}
}
Program.cs
public class Program
{
public Program()
{
Logger.LogLevel = LogLevel.Information;
Logger.LogRange = LogRange.Write;
Logger.Log("Logger initialized");
}
public void Start(string[] args)
{
DatabaseHandler.StartDatabase();
NetworkHandler.StartNetwork();
Logger.Log("Service started");
}
if I run the service as a console program, it works fine.
So the db connection + logger are working fine too. (Also within < 10ms)
If you're running the service in interactive mode it's waiting for the console here:
if (Environment.UserInteractive)
{
lisaServerService.OnStart(args);
Console.WriteLine("I am a service. Normally you can't see the console... just ignore me");
Console.ReadLine();
...
That is likely preventing the service from responding properly to indicate it is started.