Installing windows service Using C# gives error - c#

Im working in windows service syncmysqldb.exe i need the service to run a process ie syncing of two mysql databases in n intervals of time given in setting.xml file
When i install this service service manager i see the service not in started state and when i try to run in manually by right clicking it gives following error
When i install service it gives following error
The description for Event ID ( 11001 ) in Source ( MsiInstaller ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event: Product: SetupSynMysqldb -- Error 1001. Error 1001. An exception occurred during the Commit phase of the installation. This exception will be ignored and installation will continue. However, the application might not function correctly after installation is complete. --> The savedState dictionary contains inconsistent data and might have been corrupted., (NULL), (NULL), (NULL), (NULL), , .
When i run service in service manager it gives following error
The SyncMysqlDb service failed to start due to the following error:
The system cannot find the file specified.
C# code
protected override void OnStart(string[] args)
{
try
{
//add this line to text file during start of service
EventLog.WriteEntry("SyncMysqlDb in OnStart. at " + DateTime.Now);
//handle Elapsed event
tmrSync.Elapsed += new ElapsedEventHandler(OnElapsedTime);
tmrSync.Interval = GetIntervals();
//enabling the timer
tmrSync.Enabled = true;
//TraceService(" tmrSync.Interval =" + tmrSync.Interval + " at " + DateTime.Now);
ThreadPool.QueueUserWorkItem(new WaitCallback(ServiceWorkerThread));
}
catch (Exception ex)
{
EventLog.WriteEntry("Service failed to start.", EventLogEntryType.Error, (int)Service1EventIds.Start_InitializationFailure, ex);
}
}
private void ServiceWorkerThread(object state)
{
// Periodically check if the service is stopping.
while (!this.stopping)
{
// Perform main service function here...
Thread.Sleep(2000); // Simulate some lengthy operations.
}
// Signal the stopped event.
this.stoppedEvent.Set();
}
protected override void OnStop()
{
tmrSync.Enabled = false;
//TraceService("stopping service" + DateTime.Now);
EventLog.WriteEntry("SyncMysqlDb in OnStop. at " + DateTime.Now);
this.stopping = true;
this.stoppedEvent.WaitOne();
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
try
{
EventLog.WriteEntry(#"Executing C:\SyncMysqlDbRepository\task.bat at " + DateTime.Now);
Process.Start(#"C:\SyncMysqlDbRepository\task.bat");
}
catch (Exception ex)
{
EventLog.WriteEntry("Service failed to start.at " + DateTime.Now, EventLogEntryType.Error, (int)Service1EventIds.Start_InitializationFailure, ex);
}
// TraceService("syncing db at " + DateTime.Now);
}
protected int GetIntervals()
{
var dt = new DataTable();
try
{
dt.ReadXmlSchema(#"C:\SyncMysqlDbRepository\SettingsDs.xml");
dt.ReadXml(#"C:\SyncMysqlDbRepository\Settings.xml");
}
catch (Exception ex)
{
EventLog.WriteEntry("GetIntervals failed at " + DateTime.Now, EventLogEntryType.Error, (int)Service1EventIds.Start_InitializationFailure, ex);
return 0;
}
return Convert.ToInt16(dt.Rows[0].ItemArray[2]); //Intervals from settings.xml
}

Related

UI of Process is not visible after Process.Start()

I have made a WCF Service and it contains a method string SaveVideoInformation()
The purpose of this method is to run a process if it is not running.
Following is the code of that method.
public string SaveVideoInformation(string ID, string videoName)
{
string Result = null;
try
{
Result = Insert(ID, videoName);
Process[] pname = Process.GetProcessesByName("AutoRunVideoWaterMarkingTook");
if (pname.Length == 0)
{
Result += " | Trying to run Process";
try
{
Process process = Process.Start(#"~\Debug\AutoRunVideoWaterMarkingTook.exe");
Result += " | Process Ran Successfully";
}
catch (Exception ex)
{
Result += " | Exception While Running the process";
throw new Exception("Unable to start Process);
}
}
else
{
Result += "|Process Already Running";
}
}
catch (Exception ex)
{
Result = "Not Done," + ex.Message;
}
return Result;
}
The problem I am facing is when i call this method from Windows Form Tool Application, it run successfully and i can see the UI.
but when i call this method from Windows Service, Process Starts but its UI is not visible.
That is most likely because your Windows Service is not in user interactive mode.
You have to enable this from the Services panel, as described in this blog: Check the Allow service to interact with desktop in the service properties Log On page.
Also read Microsofts recommendations on user interactive services.

Is this business logic in my view model, and is it allowed?

I have a WCF service that must be always up, and is therefore hosted by a Windows Service. My Windows Service model has simple startup code:
HostService:
public void StartService()
{
if (_hostController.Status != ServiceControllerStatus.Stopped && _hostController.Status != ServiceControllerStatus.StopPending)
{
var msg = string.Format("Service '{0}' must be in status '{1}' or '{2}' to accept a 'Start' command.",
HostResources.ServiceName, ServiceControllerStatus.Stopped, ServiceControllerStatus.StopPending);
throw new HostServiceException(msg, HostServiceException.HostServiceExceptionCategory.ServiceStatusControl);
}
try
{
_hostController.Start();
}
catch (Exception ex)
{
if (ex is Win32Exception || ex is InvalidOperationException)
{
throw new HostServiceException(string.Format("'{0}' failed to respond properly to a 'StartService` command: '{1}'", _hostController.ServiceName, ex.Message), ex);
}
throw;
}
try
{
_hostController.WaitForStatus(ServiceControllerStatus.Running, _waitForStatusTimeout);
}
catch (TimeoutException tx)
{
throw new HostServiceException(string.Format("{0} did not start respond after {1} seconds and the 'Start' command timed out.", _hostController.ServiceName, _waitForStatusTimeout.TotalSeconds), tx);
}
if (ServiceControllerStatus.Running != _hostController.Status)
{
throw new HostServiceException(string.Format("The 'StartService' command for '{0}' failed. The Service has a status of '{1}'.", _hostController.ServiceName, _hostController.Status));
}
}
My WCF service has even simpler startup code:
SchedulerService:
public void Start()
{
_isBusy = false;
var interval = _config.Settings.ServicePollingInterval * 1000;
_pollTimer = new Timer(interval);
_pollTimer.Enabled = true;
_pollTimer.Elapsed += PollTimerElapsed;
_pollTimer.Start();
Status = SchedulerServiceStatus.Running;
var msg = string.Format("'{0}' started with the timer set for {1} second{2} intervals.", SchedulerResources.ServiceName, _pollTimer.Interval / 1000, _pollTimer.Interval / 1000 > 1 ? "s" : "");
_logger.Info(msg);
StatusChanged(this, new SchedulerStatusChangeEventArgs(Status, msg));
}
It is the code in my view model in question here, because only if it can start the Windows Service, will it start the WCF service:
SchedulerViewModel:
private void ExecuteStart()
{
if (_hostModel.ServiceStatus != ServiceControllerStatus.Running)
{
_logger.Warn("The '" + _hostModel.ServiceName + "' host service is not running. The '" + GetType().Name + "' will attempt to start it.");
try
{
_hostModel.StartService();
}
catch (Exception ex)
{
var msg = string.Format("The '{0}' could not start the '{1}' host service: {2}", GetType().Name, _hostModel.ServiceName, ex.Message);
_logger.Error(msg, ex);
throw new HostServiceException(msg, HostServiceException.HostServiceExceptionCategory.ServiceController, ex);
}
}
try
{
_scheduler.Start();
}
catch (Exception ex)
{
throw new SchedulerServiceException(ex.Message, SchedulerServiceException.SchedulerServiceExceptionCategory.SchedulerControl, ex);
}
SchedulerStatus = _scheduler.Status;
CommandsCanExecuteChanged();
}
Now this is indeed not view logic, but it is hardly business logic either; more like housekeeping: I can only use the washing machine if the water supply is switched on. Now I don't really see the need for a whole new model with just an instance of HostModel and SchedulerService, just for this decision. What say the jury on my current setup?
I would push all the code behind another service and inject this via an interface into the VM, I'd do this becuase I presume the WCF expose state via events and you want to display this in the UI. If you push this behind another service allows to 'shape' the exposed state into a more UI centric model suited for use in the VM.
If you did this, from the view point of the VM all it would then know about is 'start\stop' methods and an event handler - the implementation is then abstracted away and makes testing the VM very easy via mocking.
To take this further I would consider using Reactive extensions instead of CLR events for communicating state changes in the service.

c# Windows Service starts and then stops

The code below builds without any errors and ran fine as console application. However now that I've made it into a WindowsService and used the C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil to successfully install it. It stops as soon as I start it up. I feel like I'm missing something simple that I'm going to forever hit myself over the head once another set of eyes looks at it.
Please forgive the mess you are about see. I will clean it up after its working properly. Thanks in advance for any help that can be provided.
Service1.cs
namespace LGCDialHome
{
public partial class Service1 : ServiceBase
{
private System.Timers.Timer _timer = null;
public Service1()
{
InitializeComponent();
System.Timers.Timer stateTimer = new System.Timers.Timer(60000);
}
protected override void OnStart(string[] args)
{
try
{
EventLog.WriteEntry("Dial Home service started : " + DateTime.Now);
_timer = new System.Timers.Timer();
_timer.Interval = 10000; //in milliseconds
EventLog.WriteEntry("Timer Interval is : " + _timer.Interval);
_timer.Elapsed += timer_Elapsed;
_timer.Start();
}
catch (Exception ex)
{
EventLog.WriteEntry("Dial Home service error : " + ex);
}
}
protected override void OnStop()
{
EventLog.WriteEntry("Dial Home service Stopped : " + DateTime.Now);
}
protected void timer_Elapsed(object sender, ElapsedEventArgs e)
{
int invokeCount = 0;
int maxCount = 10;
string host = Environment.MachineName;
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string uname = Environment.UserName;
try
{
_timer.Stop();
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),(++invokeCount).ToString());
Console.WriteLine("Host -> {0} \r\nNTID -> {1}", host, user);
if (invokeCount == maxCount)
{
invokeCount = 0;
}
}
catch (Exception ex)
{
EventLog.WriteEntry("Dial Home service error : " + ex);
}
finally
{
_timer.Start();
}
}
}
}
Well, you will need to debug your code, but attaching to Windows Services is a little different than debugging other types of projects.
Try the following:
1- At the very beginning of your OnStart() method, add the following line:
System.Threading.Thread.Sleep(10000);
2- Set a breakpoint on the next line immediately after the line above. Build and reinstall your service using InstallUtil.
3- Start your service.
4- In Visual Studio, click Debug -> Attach to Process.
5- Find your service in the Available Processes list and attach to it. This will cause the breakpoint to be hit, and will let you debug your code to see if there's any exception thrown (by looking at your code, I feel like the problem might be security related. The user that the service is running as might not have access to the EventLog or something).
Note: After starting your service, you have 10 seconds to perform steps 4 and 5. If you think you need more time, change the sleep value to something like 20000(20 seconds).

C# service: setup returns error 1001. Source MyService already exists on the local computer. EventID 11001

Currently I try to create a C# (2010) service.
I have created a visual studio setup project. Whenever I try to install the service I get the message
Error 1001. Source MyService already exists on the local computer.
In the eventlog I find the following info:
- System
- Provider
[ Name] MsiInstaller
- EventID 11001
[ Qualifiers] 0
Level 2
Task 0
Keywords 0x80000000000000
- TimeCreated
[ SystemTime] 2013-10-28T14:28:23.000000000Z
EventRecordID 206256
Channel Application
Computer <MyComputer>
- Security
[ UserID] S-1-5-21-703477020-2137377117-2121179097-8027
- EventData
Product: MyServiceSetup -- Error 1001. Error 1001. Source MyService already exists on the local computer.
(NULL)
(NULL)
(NULL)
(NULL)
(NULL)
7B30353636304544462D374645372D344243312D414442422D4534424244343645393646457D
I have tried the following commands (in a command window with admin-rights):
InstallUtil /u MyService.exe
and
sc delete MyService
But I keep getting this error. I install with sufficient rights. And I have absolutely no idea where I have to look for the solution.
Can somebody please help me? I have almost no hair left to pull out...
Thanx!!!
I ran into this issue myself and couldn't find a solution so after several days of research and testing and trying different things I FINALLY figured out a solution that solves this problem!
When you use Windows InstallUtil.exe to install the service it creates an event log source same as the name of your service and adds it to the "Application" event log. However when it uninstalls the service it doesn't remove this source. So when you try to re-install it, it tries to add the source again, but since it is already there it makes an error and since there is an error it rolls back the installation.
What I did is I added code to my service for self installing/uninstalling and a method to clean up the event logging that it uses and that Windows creates when it installs it the first time. That extra method is what fixed it for me. With the following code, pretty much just run the -delevent a couple times until it says nothing exists. Then try installing again and it should work.
In a command prompt with admin rights call these:
Service1.exe -install
Service1.exe -uninstall
Service1.exe -delevent
Here is my code:
Program.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;
namespace WindowsService1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
if (args.Length > 0)
{
foreach (string item in args)
{
switch (item.ToLower())
{
case "-install":
Install(false, args); break;
case "-uninstall":
Install(true, args); break;
case "-delevent":
DeleteEventStuff(); break;
default:
Console.Error.WriteLine("Argument not expected: " + item); break;
}
}
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
// This is the method that does the actual installing/uninstalling of the service for Windows
static void Install(bool uninstall, string[] args)
{
try
{
Console.WriteLine(uninstall ? "Uninstalling Service" : "Installing Service");
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(MyProjectInstaller).Assembly, args))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (uninstall)
{
inst.Uninstall(state);
Console.WriteLine();
Console.WriteLine("Uninstall Successful");
}
else
{
inst.Install(state);
Console.WriteLine();
Console.WriteLine("Installed Successfuly. Now Commiting...");
inst.Commit(state);
Console.WriteLine();
Console.WriteLine("Commit Successful");
}
}
catch (Exception ex)
{
try
{
Console.WriteLine();
Console.WriteLine("ERROR: " + ex.Message);
Console.WriteLine();
Console.WriteLine("Rolling back service installation...");
inst.Rollback(state);
Console.WriteLine();
Console.WriteLine("Rollback Successful");
}
catch { }
throw;
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
// This is the method that cleans up the event logging that Windows creates on install
static void DeleteEventStuff()
{
// Delete the event log stuff that the service actually uses.
if (System.Diagnostics.EventLog.SourceExists(Service1.eventSource))
{
try
{
System.Diagnostics.EventLog.DeleteEventSource(Service1.eventSource);
Console.WriteLine();
Console.WriteLine("Event source deleted successfully!");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("Error deleting event source: " + ex.Message);
}
}
else
Console.WriteLine(); Console.WriteLine("The event source '" + Service1.eventSource + "' does not exist.");
if (System.Diagnostics.EventLog.Exists(Service1.eventLog))
{
try
{
System.Diagnostics.EventLog.Delete(Service1.eventLog);
Console.WriteLine();
Console.WriteLine("Event log deleted successfully!");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("Error deleting event log: " + ex.Message);
}
}
else
Console.WriteLine(); Console.WriteLine("The event log '" + Service1.eventLog + "' does not exist.");
// Delete the event log stuff that windows installer utilities thinks the service will use.
if (System.Diagnostics.EventLog.SourceExists(Service1._serviceName))
{
try
{
System.Diagnostics.EventLog.DeleteEventSource(Service1._serviceName);
Console.WriteLine();
Console.WriteLine("Event source deleted successfully!");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("Error deleting event source: " + ex.Message);
}
}
else
Console.WriteLine(); Console.WriteLine("The event source '" + Service1._serviceName + "' does not exist.");
if (System.Diagnostics.EventLog.Exists(Service1._serviceName))
{
try
{
System.Diagnostics.EventLog.Delete(Service1._serviceName);
Console.WriteLine();
Console.WriteLine("Event log deleted successfully!");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("Error deleting event log: " + ex.Message);
}
}
else
Console.WriteLine(); Console.WriteLine("The event log '" + Service1._serviceName + "' does not exist.");
// Delete the actual custom event log file stored on the hard drive if it exists so it can be recreated on re-install
if (System.IO.File.Exists(#"%SystemRoot%\System32\winevt\Logs\" + Service1.eventLog + ".evtx"))
{
try
{
System.IO.File.Delete(#"%SystemRoot%\System32\winevt\Logs\" + Service1.eventLog + ".evtx");
Console.WriteLine();
Console.WriteLine("Event log found deleted from hard drive successfully!");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("Error deleting event log from hard drive: " + ex.Message);
}
}
else
Console.WriteLine(); Console.WriteLine("The event log '" + Service1._serviceName + "' file was not found on the hard drive.");
}
}
}

C# Windows Service - Started and then Stopped Automatically

I am creating this windows service by following the instructions at MSDN Walkthrough: Creating a Windows Service and after successful installation, I go to Services.msc to Start the Windows service and before it finishes starting up I get the following message:
The EIWindowsService service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
I know the Windows Service starts ok because there is an entry to the log file stating that the service started. I did some research before posting on here and the answer from Some Services Stop Automatically states that the problem could either be that the OnStart method is throwing an error, or that the OnStart is not kicking off a thread. So I modified my code so that the only thing within the OnStart is the starting of two timers and the log entry therefore needing no exception handling. I also added a thread to "jump" to another method.
I tried the windows service again and I know that it "moved" to the new method that the thread pointed to because I had a log entry in there that threw aFormatException error due to some conversion I was doing. I commented out the conversion and the windows service still just began to start up and then stopped automatically.
Further research indicated to me that I might need a loop to keep the processing within the method, so I took information from C - Windows Service the service on and set up an infinite while loop. I also found that there might be Garbage Collection going on and established a KeepAlive statement for the timers as suggested in Examples section of MSDN Timer Class. Still the same issues.
At this point I feel I've exhaused all the research I can do so it would be appropriate to post my question here. All my code is below and I will note that before I performed any change I uninstalled the Windows Service, removed the Setup Project, and deleted the installers from the C# code. I then made changes and started back over with the instructions in the Walkthrough starting at the point where it instructs how to setup the installers. I did this each time because I found that if I made changes and did not uninstall the Windows Service, remove the Setup Project, and delete the installers, then my changes would not take effect on the currently installed windows service.
Any assistance you can give would be most appreciated. I will be here for another 15min and then I will check this first thing tomorrow.
SERVICE1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace EIWindowsService
{
public partial class Service1 : ServiceBase
{
Logs.ErrorLog logFile = new Logs.ErrorLog();
private System.Threading.Thread onStartThread;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
iTimer.Start();
iTimer.Elapsed += new ElapsedEventHandler(iTimer_Elapsed);
pTimer.Start();
pTimer.Elapsed += new ElapsedEventHandler(pTimer_Elapsed);
onStartThread = new System.Threading.Thread(TimerValue);
onStartThread.Start();
logFile.SendToLog("EIWindows Service started on " + GetDate());
}
catch (ArgumentOutOfRangeException ex)
{
logFile.SendToLog("ArgumentOutOfRangeException", "EIWindowsService\\Service1.cs", "OnStart()", ex);
} //end of ArgumentOutOfRangeException CATCH statement
}
protected override void OnStop()
{
iTimer.Stop();
pTimer.Stop();
logFile.SendToLog("EIWindowsService\\Service1.cs", "OnStop()", "EIWindows Service stopped on " + GetDate());
}
private void TimerValue()
{
try
{
/*commented out because it was throwing an exception error*/
//double iTimerValue = Convert.ToDouble(iTimer.ToString());
//double pTimerValue = Convert.ToDouble(pTimer.ToString());
while (1 > 0)
{
//if (iTimerValue % 1800000 == 0) //if the timer hits the 30min mark
//{
// logFile.SendToLog("Current iTimer Value = " + iTimerValue.ToString());
//}
//if (pTimerValue % 1800000 == 0) //if the timer hits the 30min mark
//{
// logFile.SendToLog("Current pTimer Value = " + pTimerValue.ToString());
//}
GC.KeepAlive(iTimer);
GC.KeepAlive(pTimer);
}
//TimerValue();
}
catch (OverflowException ex)
{
logFile.SendToLog("OverflowException", "EIWindowsService\\Service1.cs", "TimerValue()", ex);
} //end of OverflowException CATCH statement
catch (ArgumentException ex)
{
logFile.SendToLog("ArgumentException", "EIWindowsService\\Service1.cs", "TimerValue()", ex);
} //end of ArgumentException CATCH statement
catch (FormatException ex)
{
logFile.SendToLog("FormatException", "EIWindowsService\\Service1.cs", "TimerValue()", ex);
} //end of FormatException CATCH statement
}
private string GetDate()
{
string current = "No Date Recorded";
try
{
current = DateTime.Now.ToString("F");
}
catch (FormatException ex)
{
logFile.SendToLog("FormatException", "EIWindowsService\\Service1.cs", "GetDate()", ex);
} //end of FormatException CATCH statement
return current;
} //end of method GetDate
private void iTimer_Elapsed(object source, ElapsedEventArgs e)
{
try
{
iTimer.Stop();
ImportI();
iTimer.Start();
}
catch (ArgumentOutOfRangeException ex)
{
logFile.SendToLog("ArgumentOutOfRangeException", "EIWindowsService\\Service1.cs", "iTimer_Elapsed()", ex);
} //end of ArgumentOutOfRangeException CATCH statement
} //end of method iTimer_Elapsed
private void pTimer_Elapsed(object source, ElapsedEventArgs e)
{
try
{
pTimer.Stop();
ImportP();
pTimer.Start();
}
catch (ArgumentOutOfRangeException ex)
{
logFile.SendToLog("ArgumentOutOfRangeException", "EIWindowsService\\Service1.cs", "pTimer_Elapsed()", ex);
} //end of ArgumentOutOfRangeException CATCH statement
} //end of method pTimer_Elapsed
private void ImportI()
{
//does some action but commented out because it never gets here and is not relavant to this question.
} //end of method ImportI
private void ImportP()
{
//does some action but commented out because it never gets here and is not relavant to this question.
} //end of method ImportP
}
}
SERVICE1.DESIGNER.CS (the relavant stuff)
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.pTimer = new System.Timers.Timer(10800000); //3hrs
this.iTimer = new System.Timers.Timer(3600000); //1hr
//
// pTimer
//
this.pTimer.Enabled = true;
//
// iTimer
//
this.iTimer.Enabled = true;
//
// Service1
//
this.ServiceName = "EIWindowsService";
}
#endregion
private System.Timers.Timer pTimer;
private System.Timers.Timer iTimer;
You don't need to create a separate thread or worry about the garbage collector. The framework handles all that for you. Just create the timers and they will be called. Here's an example.
public partial class Service1 : ServiceBase
{
private Timer timer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer = new Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
using (StreamWriter writer = File.AppendText(#"C:\Users\alfonso\Desktop\log.txt"))
{
writer.WriteLine(string.Format("{0} : {1}", DateTime.Now, "Logging from the service"));
}
}
protected override void OnStop()
{
}
}
Something else that may help someone coming across this post and the above solutions do not work. When I had this problem, I had added this to the config of my Windows Service:
<system.web>
<compilation debug ="true" />
</system.web>
I added this so that I could attach the debugger to the service when running it locally, however when I tried to move the service to another server it gave the specified error. By removing this from the config the service worked again.

Categories

Resources