I have a console application which is an FTP server. This console application works fine. Now, I want to run this FTP Server using Windows Service.
I have an unhandled exception trapper which traps an unhandled exception. After this exception occurs, I want to stop the service, destruct the class for FTP Server, delay it for 10 seconds and restart the service.
Following is my code (The ftp server and service works fine if there is no unhandled exception but I want to successfully stop and restart the service. This code stops the service fine but doesn't restart it). Any ideas?
public partial class FTPService : ServiceBase
{
private static FtpServer _ftpServer;
public FTPService(string[] args)
{
InitializeComponent();
string eventSourceName = "Ftp Server Events";
eventLog1 = new System.Diagnostics.EventLog();
string logName = "Ftp Server Log";
if (args.Count() > 0)
{
eventSourceName = args[0];
}
if (args.Count() > 1)
{
logName = args[1];
}
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists(eventSourceName))
{
System.Diagnostics.EventLog.CreateEventSource(eventSourceName, logName);
}
eventLog1.Source = eventSourceName;
eventLog1.Log = logName;
if (!System.Diagnostics.EventLog.SourceExists("Ftp Server Events"))
{
System.Diagnostics.EventLog.CreateEventSource(
"Ftp Server Events", "Ftp Server Log");
}
this.ServiceName = "FTP Service";
this.AutoLog = true;
}
public static void Main(string[] args)
{
ServiceBase.Run(new FTPService(new string[0]));
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
var database = new Database(); // Gets database details as FTP server tals to database.
var configurationManager = new ConfigurationManagerWrapper(); // Same as above
_ftpServer = new FtpServer(new Assemblies.Ftp.FileSystem.StandardFileSystemClassFactory(database, configurationManager));
_ftpServer.Start(); //Starts the service (FTP Server works fine if there is no handled exception)
eventLog1.WriteEntry("Started");
FtpServerMessageHandler.Message += MessageHandler_Message;
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
}
protected override void OnStop()
{
_ftpServer.Stop(); // This calls the destructor for FTP Server, to close any TCP Listening connections, etc
base.OnStop(); // Here I stop the service itself.
eventLog1.WriteEntry("Stopped");
Thread.Sleep(10000);
}
protected void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) // unhandled exception handler
{
eventLog1.WriteEntry(e.ExceptionObject.ToString());
Thread.Sleep(5000);
OnStop(); // Calls onstop which stops FTP Server and destroys previous objects of FTP server
var serviceMgr = new ServiceController();
serviceMgr.Start(); // Here I want to restart the service (it doesn't work)
}
}
Try following:
services.msc -> your Service-> Properties -> Recovery
set properties for you
-> Save -> your Service -> restart