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?
Related
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();
}
}
}
}
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().
What I am trying to do is to run the activity while having a background process when a button is pressed. (Because my real problem is when I am having a very long process, my front-end is being stopped for a while)
What I tried to do is to make a service and bind to it (which I don't know if I made it right since I thought it will work independently). But still, when I am trying to access the method from the service, my foreground is still being stopped for a while.
HOW CAN I ACHIEVE TO MAKE MY FOREGROUND STILL RUNNING WHILE WAITING FOR THE RESPONSE OF WEB SERVICE IN THE BACKGROUND
(I ALREADY MADE IT WITH PROGRESS BAR TO MAKE THE USER AWARE IT IS STILL LOADING)
Here is my service, serviceConnection and binder code: // it is still useless, i'm just trying to test this
[Service]
public class MyService : Service
{
static readonly string TAG = "X:" + typeof(MyService).Name;
int i;
#region Override OnCreate()
public override void OnCreate()
{
base.OnCreate();
Toast.MakeText(this, "MyService started", ToastLength.Short).Show();
}
#endregion
#region Override OnDestroy
public override void OnDestroy()
{
base.OnDestroy();
StopSelf();
Log.Debug(TAG, "MyService destroyed at {0}.", DateTime.Now);
}
#endregion
#region Override OnBind
public override IBinder OnBind(Intent intent)
{
return new MyBinder(this);
}
#endregion
public string GetTimestamp(string value)
{
// this is just a testing
if (value == string.Empty)
{
for (i = 0; i < 9999999; i++)
{
if (i == 100000)
Log.Debug(TAG, "100000 zxc");
if (i == 500000)
Log.Debug(TAG, "500000 zxc");
}
return "empty";
}
else
return i.ToString() + " from service";
}
}
public class MyBinder : Binder
{
MyService service;
public MyBinder(MyService service)
{
Toast.MakeText(service.ApplicationContext, "my binder", ToastLength.Short).Show();
this.service = service;
}
public string GetFormattedTimestamp(string value)
{
return service?.GetTimestamp(value);
}
}
public class MyServiceConnection : Java.Lang.Object, IServiceConnection
{
static readonly string TAG = typeof(MyServiceConnection).FullName;
public bool IsConnected { get; private set; }
public MyBinder Binder { get; private set; }
public MyServiceConnection()
{
IsConnected = false;
Binder = null;
}
public void OnServiceConnected(ComponentName name, IBinder binder)
{
Binder = binder as MyBinder;
IsConnected = Binder != null;
Log.Debug(TAG, "OnServiceConnected zxc");
}
public void OnServiceDisconnected(ComponentName name)
{
Log.Debug(TAG, "OnServiceDisconnected zxc");
IsConnected = false;
Binder = null;
}
}
I have a windows service which is designed to continuously retrieve messages from Azure service bus queue and pass it to other queues.I have deployed this service to one of the server computer but unfortunately the service keeps failing at a random time interval.
My application handles the exceptions and writes them to a file.The main purpose of this application is to hook up to the queue and listen all the messages continuously and never move to the Application stop stage.I'm using a timer in this application and I don't think that is causing any problem.I'd like to know what would be the best approach to handle errors and make my application stable, below is the code. Thanks in advance.
public partial class Scheduler : ServiceBase
{
private Timer Scheduletimer = null;
private string servicenamespace;
private string issuesecretkey;
private string sourcequeue;
private string destinationqueue;
public Scheduler()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Scheduletimer = new Timer();
this.Scheduletimer.Interval = 1000;//1 sec
this.Scheduletimer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
Scheduletimer.Enabled = true;
WriteToFile("Application started : "+DateTime.Now.ToString());
}
protected void timer1_Tick(object sender, ElapsedEventArgs e)
{
Scheduletimer.Enabled = false;
WriteToFile("Business logic started : " + DateTime.Now.ToString());
//Business Logic code goes here
}
protected override void OnStop()
{
Scheduletimer.Enabled = false;
WriteToFile("Application stoped : "+DateTime.Now.ToString());
}
public void WriteToFile(string text)
{
string directory = AppDomain.CurrentDomain.BaseDirectory;
string logfilepath = directory + "LogFile.txt";
using (StreamWriter writer = new StreamWriter(logfilepath, true))
{
writer.WriteLine(text);
writer.Close();
}
}
public void WriteErrorsToFile(Exception ex)
{
string directory = AppDomain.CurrentDomain.BaseDirectory;
string Errorlogfilepath = directory + "ErrorLogFile.txt";
using (StreamWriter writer = new StreamWriter(Errorlogfilepath, true))
{
writer.WriteLine("Time Occured: " + DateTime.Now.ToString());
writer.WriteLine(ex.Message +" "+ DateTime.Now.ToString());
writer.Close();
}
}
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.