Error while installing the windows service using installutil command? - c#

I Will Explain what i am exactly doing.
STEP 1:
I Have taken the one class library file in which i have added the WCF service. In this service i am peforming operations.
STEP 2:
I have added the windows service in the same solution. In this service i have hosted the WCF service and debug it.
So it is working fine.
STEP 3:
Then I had created the set up of that files using installshied(basic msi project) and i install it. It is working fine.
But I am trying to install it using InstallUtil.exe it is giving error.
Error Message:-
Installing assembly 'C:\Users\Dattaprasad\Desktop\TestAllBrowswer\WindowsService1.exe'.
Affected parameters are:
i =
logtoconsole =
logfile = C:\Users\Dattaprasad\Desktop\TestAllBrowswer\WindowsService1.InstallLog
assemblypath = C:\Users\Dattaprasad\Desktop\TestAllBrowswer\WindowsService1.exe
name = HostCompression
Installing service HostCompression...
Service HostCompression has been successfully installed.
Creating EventLog source HostCompression in log Application...
An exception occurred in the OnAfterInstall event handler of System.ServiceProcess.ServiceInstaller.
System.InvalidOperationException: Cannot start service HostCompression on computer '.'.
The inner exception System.ComponentModel.Win32Exception was thrown with the following error message:
The service did not respond to the start or control request in a timely fashion.
Rolling back assembly 'C:\Users\Dattaprasad\Desktop\TestAllBrowswer\WindowsService1.exe'.
Affected parameters are:
i =
logtoconsole =
logfile = C:\Users\Dattaprasad\Desktop\TestAllBrowswer\WindowsService1.InstallLog
assemblypath = C:\Users\Dattaprasad\Desktop\TestAllBrowswer\WindowsService1.exe
name = HostCompression
Restoring event log to previous state for source HostCompression.
Service HostCompression is being removed from the system...
Service HostCompression was successfully removed from the system.
What I have tried:
Service1.cs file:-
ServiceHost m_serviceHost;
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
if (m_serviceHost != null) m_serviceHost.Close();
//string strAdrHTTP = "http://localhost:9100/CompressService/";
string strAdrTCP = "net.tcp://localhost:9200/CompressService";
string strAdrWebHttp = "http://localhost:9100/CompressService";
Uri[] adrbase = {
//new Uri(strAdrHTTP),
new Uri(strAdrTCP),
new Uri(strAdrWebHttp)
};
m_serviceHost = new ServiceHost(typeof(TestAllBrowser.Test), adrbase);
// ServiceDebugBehavior debug = m_serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior();
m_serviceHost.Description.Behaviors.Add(mBehave);
//m_serviceHost.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
#region BasicHttpBinding
#endregion
#region NetTcpBinding
NetTcpBinding tcpb = new NetTcpBinding();
tcpb.MaxReceivedMessageSize = 2147483647;
tcpb.MaxBufferPoolSize = 2147483647;
tcpb.MaxBufferSize = 2147483647;
tcpb.TransferMode = TransferMode.Streamed;
//tcpb.ReaderQuotas.MaxArrayLength = 2147483647;
//tcpb.ReaderQuotas.MaxStringContentLength = 2147483647;
tcpb.ReceiveTimeout = new TimeSpan(0, 10, 00);
tcpb.SendTimeout = new TimeSpan(0, 10, 00);
tcpb.CloseTimeout = new TimeSpan(0, 10, 00);
m_serviceHost.AddServiceEndpoint(typeof(TestAllBrowser.ITest), tcpb, strAdrTCP);
m_serviceHost.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
#endregion
#region WebHttpBinding
WebHttpBinding webb = new WebHttpBinding();
webb.MaxReceivedMessageSize = 2147483647;
webb.MaxBufferPoolSize = 2147483647;
webb.MaxBufferSize = 2147483647;
webb.TransferMode = TransferMode.Streamed;
//webb.ReaderQuotas.MaxArrayLength = 2147483647;
//webb.ReaderQuotas.MaxStringContentLength = 2147483647;
webb.ReceiveTimeout = new TimeSpan(0, 10, 00);
webb.SendTimeout = new TimeSpan(0, 10, 00);
webb.CloseTimeout = new TimeSpan(0, 10, 00);
webb.CrossDomainScriptAccessEnabled = true;
m_serviceHost.AddServiceEndpoint(typeof(TestAllBrowser.ITest), webb, strAdrWebHttp).Behaviors.Add((IEndpointBehavior)new WebHttpBehavior());
m_serviceHost.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
#endregion
m_serviceHost.Open();
}
protected override void OnStop()
{
if (m_serviceHost != null)
m_serviceHost.Close();
m_serviceHost = null;
}
ProjectInstaller.cs file:-
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
private IContainer components = (IContainer)null;
private ServiceProcessInstaller process;
private ServiceInstaller service;
private ServiceProcessInstaller serviceProcessInstaller1;
private ServiceInstaller serviceInstaller1;
public ProjectInstaller()
{
this.process = new ServiceProcessInstaller();
this.process.Account = ServiceAccount.LocalSystem;
this.service = new ServiceInstaller();
this.service.ServiceName = "HostCompression";
this.service.DisplayName = "HostCompression";
this.service.Description = "WCF Service Hosted";
this.service.StartType = ServiceStartMode.Automatic;
this.Installers.Add((Installer)this.process);
this.Installers.Add((Installer)this.service);
this.service.AfterInstall += new InstallEventHandler(this.serviceInstaller1_AfterInstall);
}
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
new ServiceController("HostCompression").Start();
}
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.ServiceName = "Service1";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}

Related

C# - "error 1001" - The specified service already exists. How to uninstall the service?

I have a project installer which installs a Windows service.
When I create a new version I need to uninstall it and install the new version.
Please check the code below:
private void InitializeComponent()
{
this.ServiceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
this.MyServiceInstaller = new System.ServiceProcess.ServiceInstaller();
//
// ServiceProcessInstaller
//
this.ServiceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.ServiceProcessInstaller.Password = null;
this.ServiceProcessInstaller.Username = null;
this.ServiceProcessInstaller.BeforeInstall += new System.Configuration.Install.InstallEventHandler(this.BeforeInstall);
//
// MyServiceInstaller
//
this.MyServiceInstaller.Description = "Description";
this.MyServiceInstaller.ServiceName = "My Service";
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.ServiceProcessInstaller,
this.MyServiceInstaller});
}
void BeforeInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());
foreach (ServiceController s in services)
{
if (s.ServiceName == "My Service")
{
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
ServiceInstallerObj.Context = new InstallContext();
ServiceInstallerObj.ServiceName = "My Service";
ServiceInstallerObj.Uninstall(null);
break;
}
}
}
I set the BeforeInstall event but I got Error 1001 again.

My Windows Service failing to get started after a reboot

I can successfully Start/Stop service Manually but it fails to start on a system restart although startup type is set to 'Automatic'. On some terminal, when rebooted, service fail to start with error failed to connect DB
29052019 17:25:27 ERROR Logs.TransactionLogManager - Exception Thrown in getNewSession()
29052019 17:25:27 ERROR Logs.TransactionLogManager - Unable To Open Database Session
29052019 17:25:27 ERROR Logs.TransactionLogManager - Unable to complete network request to host "localhost".
at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.CreateNewConnectionIfPossibleImpl(FbConnectionString connectionString)
at FirebirdSql.Data.FirebirdClient.FbConnectionPoolManager.Pool.GetConnection(FbConnection owner)
at FirebirdSql.Data.FirebirdClient.FbConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare()
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper)
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory)
at NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at StevensCommon.Database.FluentNHibernateManager.OpenNewSession()
at StevensCommon.DAOs.StevensDAO.GetNewSession()
On development environment whilst debugging I'm not even getting any error. Assuming that on my machine the firebird services does start up before my service, still it fails to start the service on a reboot. And nothing comes up in the log.
I've added some log points within the code and they all gets logged when I Stop/Start the service manually. But nothing shows up in the log when system is rebooted and server never gets started.
Tried adding Firebird Service as a dependencies in the Project/Service Installer, set the DelayedAutoStart = true. Whatever solution I read online I've tried it but service is not starting on a reboot.
Following I'm adding starting/entry point snippet of the service.
Program.cs
static class Program
{
static void Main(string[] args)
{
TransactionLogManager.WriteServiceLog("FLAG - Before DAO Call", null);
// Check to see if we have a licence
if (LicenceFileDAO.GetLicence() != null && LicenceManager.IsLicenceActive())
{
TransactionLogManager.WriteServiceLog("FLAG - Inside DAO Block", null);
//Run the IS Service
ServiceBase[] ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
TransactionLogManager.WriteServiceLog("FLAG - End of DAO Call", null);
}
else
{
TransactionLogManager.WriteServiceLog("No Valid Licence Found - Either A Licence Has Not Been Activated Or It Has Expired. Please Contact Support", null);
}
}
}
MyService.cs
public partial class MyService : ServiceBase
{
protected static Timer importTimer = null;
protected static Timer exportTimer = null;
protected static Timer licenceTimer = null;
protected static Timer requestTimer = null;
protected static Timer uploadTimer = null;
protected static Timer handshakeTimer = null;
protected static Timer scheduledReportTimer = null;
protected static Timer alertTimer = null;
public static Boolean ImportRunning = false;
public static Boolean ExportRunning = false;
public static Boolean RequestRunning = false;
public static Boolean UploadRunning = false;
public static Boolean HandshakeRunning = false;
public static Boolean ScheduledReportRunning = false;
public static Boolean AlertReportRunning = false;
public static int? zynkWorkflowProcessId = null;
public MyService()
{
TransactionLogManager.WriteServiceLog("FLAG - 1", null);
InitializeComponent();
InitializeServiceTimers();
try
{
MessengerService.Start();
TransactionLogManager.WriteServiceLog("Messaging Service Started", null);
}
catch (Exception e)
{
TransactionLogManager.WriteServiceLog(e.Message, e.StackTrace);
}
}
private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
//
// MyService
//
this.ServiceName = "MyService";
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
}
private void InitializeServiceTimers()
{
if (!System.Diagnostics.EventLog.SourceExists("Stevens Integration Service"))
{
System.Diagnostics.EventLog.CreateEventSource(
"Stevens Integration Service", "ServiceLog");
}
eventLog1.Source = "Stevens Integration Service";
eventLog1.Log = "ServiceLog";
TransactionLogManager.WriteServiceLog("FLAG - 2", null);
importTimer = new Timer(IntegrationServiceSettings.GetImportInterval() * 1000);
exportTimer = new Timer(IntegrationServiceSettings.GetExportInterval() * 1000);
licenceTimer = new Timer(86400 * 1000); // Daily
requestTimer = new Timer(IntegrationServiceSettings.GetRequestInterval() * 1000);
scheduledReportTimer = new Timer(30000);
alertTimer = new Timer(20000);
importTimer.Elapsed += new ElapsedEventHandler(ImportTimerElapsed);
exportTimer.Elapsed += new ElapsedEventHandler(ExportTimerElapsed);
licenceTimer.Elapsed += new ElapsedEventHandler(LicenceTimerElapsed);
requestTimer.Elapsed += new ElapsedEventHandler(RequestTimerElapsed);
scheduledReportTimer.Elapsed += new ElapsedEventHandler(ScheduledReportTimerElapsed);
alertTimer.Elapsed += new ElapsedEventHandler(AlertTimerElapsed);
TransactionLogManager.WriteServiceLog("FLAG - 3", null);
StartTimers();
TransactionLogManager.WriteServiceLog("FLAG - 4", null);
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("Stevens Integration Service Starting...");
TransactionLogManager.WriteServiceLog("FLAG - OnStart() Started", null);
if (StevensDAO.TestConnection())
{
eventLog1.WriteEntry("Configure Settings...");
IntegrationServiceSettings.InitialiseAll();
eventLog1.WriteEntry("Done.");
}
TransactionLogManager.WriteServiceLog("FLAG - OnStart() Finished", null);
TransactionLogManager.WriteServiceLogInfo("Started");
eventLog1.WriteEntry("Started.");
}
}
ProjectInstaller - That Includes System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
private MyService myService ;
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
this.myService = new IntegrationService.MyService();
// serviceProcessInstaller1
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
// serviceInstaller1
this.serviceInstaller1.Description = "My Integration Service";
this.serviceInstaller1.DisplayName = "MyService";
this.serviceInstaller1.ServiceName = "MyService";
//this.serviceInstaller1.ServicesDependedOn = new string[] { "Firebird Guardian - DefaultInstance", "Firebird Server - DefaultInstance" };
//this.serviceInstaller1.DelayedAutoStart = true;
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
// myService
this.myService.ExitCode = 0;
this.myService.ServiceName = "MyService";
// ProjectInstaller
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
LogPoints - On manual Start/Stop I do get following log points, but when I reboot the system nothing comes up
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - Before DAO Call
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - Inside DAO Block
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 1
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 2
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 3
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - 4
30052019 16:19:35 ERROR Logs.TransactionLogManager - Messaging Service Started
30052019 16:19:35 ERROR Logs.TransactionLogManager - FLAG - OnStart() Started
30052019 16:19:35 ERROR Logs.TransactionLogManager - Client 1 is now connected!
30052019 16:19:36 ERROR Logs.TransactionLogManager - FLAG - OnStart() Finished

System Error when getting a value from a database using WCF (IIS 7.5)

I have an Android Application which connects to a database through WCF service hosted in IIS 7.5. I based it from here: Walkthrough - Working with WCF. I'm only using my localhost and I haven't configured the remote access. The problem is every time I click the button (which upon clicking will pass the value of the inputted number then process the sql statement then it will return the result which will appear in the textview beside the button), a dialog box appears saying System Error. I am running this app in Android emulator which should be fine since I only connect through a localhost.
Here are my codes:
MainActivity.cs
btnCheck = FindViewById<ImageButton>(Resource.Id.imageButton1);
btnCheck.Click += GetEmployeeDataOnClick;
private void InitializeEmployeeServiceClient()
{
BasicHttpBinding binding = CreateBasicHttp();
_client = new EmployeeServiceClient(binding, EndPoint);
_client.DisplayEmployeeCompleted += ClientOnDisplayEmployeeCompleted;
}
private static BasicHttpBinding CreateBasicHttp()
{
BasicHttpBinding binding = new BasicHttpBinding
{
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
return binding;
}
private void GetEmployeeDataOnClick(object sender, EventArgs eventArgs)
{
empNumber = FindViewById<EditText>(Resource.Id.editText1);
EmployeeNo employee = new EmployeeNo();
employee.EmpNo = empNumber.Text;
_client.DisplayEmployeeAsync(employee);
}
private void ClientOnDisplayEmployeeCompleted(object sender, DisplayEmployeeCompletedEventArgs displayEmployeeCompletedEventArgs)
{
empName = FindViewById<TextView>(Resource.Id.textView9);
string msg = null;
if (displayEmployeeCompletedEventArgs.Error != null)
{
msg = displayEmployeeCompletedEventArgs.Error.Message;
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetMessage(msg);
alert.SetPositiveButton("OK", (senderAlert, args) => {});
RunOnUiThread(() => {
alert.Show();});
}
else if (displayEmployeeCompletedEventArgs.Cancelled)
{
msg = "Request was cancelled.";
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetMessage(msg);
alert.SetPositiveButton("OK", (senderAlert, args) => {});
RunOnUiThread(() => {
alert.Show();
});
}
else
{
msg = displayEmployeeCompletedEventArgs.Result;
RunOnUiThread(() => empName.Text = msg);
}
}
IService.cs (WCF)
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
string DisplayEmployee(EmployeeNo empNo);
}
[DataContract]
public class EmployeeNo
{
string empNumber = string.Empty;
[DataMember]
public string EmpNo
{
get { return empNumber; }
set { empNumber = value; }
}
}
Service.svc.cs (WCF)
public string DisplayEmployee(EmployeeNo empNo)
{
// sql connection, statement (inputted empNo which corresponds to an EmpName)
return EmpName;
}
Am I doing this correctly? What is the problem here?
I am a total newbie here btw.
Change the IP addess to connect to your IIS to the actual IP address of your server (the host of your emulator in this case).
You can also use the hostname like "http://user-pc:8080/DataService".

Quartz Scheduling Application

I am writing a Scheduling Client Server Application. The Server Application uses Window Service using Quartz and the Client application (For testing using both WEB and Console Applications) . Both client /Server Project build successfully but when i start service and my console application communicate with this service .An exception Comes when Client Object Calls : sched.ScheduleJob(Job,Trigger)
it through Exception on this line.
Below is my code snippet
namespace QuartzService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private IScheduler sched;
public void Show()
{
try {
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteServer";
// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
// set remoting exporter
properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
properties["quartz.scheduler.exporter.port"] = "555";
properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
properties["quartz.scheduler.exporter.channelType"] = "tcp";
properties["quartz.scheduler.exporter.channelName"] = "httpQuartz";
/// properties = (NameValueCollection)ConfigurationManager.GetSection("quartz");
ISchedulerFactory sf = new StdSchedulerFactory(properties);
sched = sf.GetScheduler();
sched.Start();
string lines = "==================Start===========================\n"+DateTime.Now.TimeOfDay.ToString()+"\n====================END=========================\n";
// Write the string to a file.
string filepath = #"D:\Murtaza\Service\test.txt";
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt",true);
file.WriteLine(lines);
file.Close();
// Console.WriteLine("Hello");
// Thread.Sleep(TimeSpan.FromMinutes(1));
// sched.Shutdown(true);
}
catch { }
}
}
}
===============================
Here is Client Console Application Code:
namespace Client
{
class Program
{
static void Main(string[] args)
{
try
{
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteClient";
properties["quartz.scheduler.instanceId"] = "AUTO";
// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
// set remoting expoter
properties["quartz.scheduler.proxy"] = "true";
properties["quartz.scheduler.proxy.address"] = "tcp://10.0.0.46:555/QuartzScheduler";// "tcp://10.0.0.85:555/QuartzScheduler"; //"tcp://10.0.0.46:555/QuartzScheduler";
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();
IJobDetail job = JobBuilder.Create<TestJob>()
.WithIdentity("remotelyAddedJob", "default")
.Build();
JobDataMap map = job.JobDataMap;
map.Put("msg", "Your remotely added job has executed!");
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("remotelyAddedTrigger", "default")
.ForJob(job.Key)
.WithCronSchedule("/5 * * ? * *")
.Build();
// schedule the job
sched.ScheduleJob(job, trigger);
}
catch (Exception ex)
{ }
}
}
}

Multiple windows services in a single project = mystery

I'm having a bizarre issue that I haven't seen before and I'm thinking it MUST be something simple that I'm not seeing in my code.
I have a project with 2 windows services defined. One I've called DataSyncService, the other SubscriptionService. Both are added to the same project installer. Both use a timer control from System.Timers.
If I start both services together, they seem to work fine. The timers elapse at the appropriate time and everything looks okay. However, if I start either service individually, leaving the other stopped, everything goes haywire. The timer elapses constantly and on the wrong service. In other words, if I start the DataSyncService, the SubscriptionService timer elapses over and over. ...which is obviously strange.
The setup is similar to what I've done in the past so I'm really stumped. I even tried deleting both service and starting over but it doesn't seem to make a difference. At this point, I'm thinking I've made a simple error in the way I'm defining the services and my brain just won't let me see it. It must be creating some sort of threading issue that causes one service to race when the other is stopped. Here the code....
From Program.cs:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new DataSyncService(),
new SubscriptionService()
};
ServiceBase.Run(ServicesToRun);
}
From ProjectInstaller.designer.cs:
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.dataSyncInstaller = new System.ServiceProcess.ServiceInstaller();
this.subscriptionInstaller = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// dataSyncInstaller
//
this.dataSyncInstaller.DisplayName = "Data Sync Service";
this.dataSyncInstaller.ServiceName = "DataSyncService";
this.dataSyncInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// subscriptionInstaller
//
this.subscriptionInstaller.DisplayName = "Subscription Service";
this.subscriptionInstaller.ServiceName = "SubscriptionService";
this.subscriptionInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.dataSyncInstaller,
this.subscriptionInstaller});
}
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller dataSyncInstaller;
private System.ServiceProcess.ServiceInstaller subscriptionInstaller;
From DataSyncService.cs:
public static readonly int _defaultInterval = 43200000;
//log4net.ILog log;
public DataSyncService()
{
InitializeComponent();
//log = LogFactory.Instance.GetLogger(this);
}
protected override void OnStart(string[] args)
{
timer1.Interval = _defaultInterval; //GetInterval();
timer1.Enabled = true;
EventLog.WriteEntry("MyProj", "Data Sync Service Started", EventLogEntryType.Information);
//log.Info("Data Sync Service Started");
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
EventLog.WriteEntry("MyProj", "Data Sync Timer Elapsed.", EventLogEntryType.Information);
}
private void InitializeComponent()
{
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// DataSyncService
//
this.ServiceName = "DataSyncService";
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}
From SubscriptionService:
public static readonly int _defaultInterval = 300000;
//log4net.ILog log;
public SubscriptionService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1.Interval = _defaultInterval; //GetInterval();
timer1.Enabled = true;
EventLog.WriteEntry("MyProj", "Subscription Service Started", EventLogEntryType.Information);
//log.Info("Subscription Service Started");
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
EventLog.WriteEntry("MyProj", "Subscription Service Time Elapsed", EventLogEntryType.Information);
}
private void InitializeComponent() //in designer
{
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// SubscriptionService
//
this.ServiceName = "SubscriptionService";
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}
Again, the problem is that the timer1_elapsed handler runs constantly when only one of the services is started. And it's the handler on the OPPOSITE service.
Anybody see anything?
In the Service.Designer.cs files InitializeComponent() methods, I'm missing
this.CanShutdown = true;
...and I shouldn't be enabling the timers there since I do it in the OnStart handlers.
So it should be something like:
private void InitializeComponent()
{
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
//
// timer1
//
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// DataSyncService
//
this.ServiceName = "DataSyncService";
this.CanShutdown = true;
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}

Categories