My custom Windows Service not working with Windows Message Queue - c#

The windows service i coded is not working:
Intended funcionality: The service is supposed to receive messages from Windows Message Queue (MSMQ) and write the messages on .txt files.
It works when I run it not-as-a-service (directly from visual studio)
When I installed it as a service i can start it, but it doesn't do anything, not creating/writing .txt files anywhere
(I know it isn't writing the files elsewhere because when I run the program from VS the messages are still in the queue, so they weren't taken out by the service)
The difference between running it as a service and running it from visual studio is the next:
namespace ComponentAtrapador
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Service1 myService = new Service1();
myService.startMethod();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
}
(so if i run it as DEBUG it will run without me having to install it as a service)
Here's the service's code:
namespace ComponentAtrapador
{
public partial class Service1 : ServiceBase
{
private System.Timers.Timer _timer;
private System.ComponentModel.IContainer components1;
private System.Diagnostics.EventLog eventLog1;
public void startMethod()
{
OnStart(null);
}
public Service1()
{
InitializeComponent();
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
_timer = new System.Timers.Timer();
_timer.Interval = 5000; // 5 seconds
_timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
_timer.Start();
}
protected override void OnStop()
{
_timer.Stop();
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
string nombreArchivo = "archivoMensaje";
MessageQueue messageQueue = new MessageQueue(#".\Private$\SomeTestName");
System.Messaging.Message[] messages = messageQueue.GetAllMessages();
System.Messaging.Message m = new System.Messaging.Message();
foreach (System.Messaging.Message message in messages)
{
message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
string text = message.Body.ToString();
System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + nombreArchivo + Properties.Settings.Default.SettingNumero + ".txt", text);
Properties.Settings.Default.SettingNumero++;
Properties.Settings.Default.Save();
//Do something with the message.
}
// after all processing, delete all the messages
messageQueue.Purge();
//}
}
}
}

That is where Logs are so helpful, put couple of eventLog1.WriteEntry() inside your OnTimer method and you will see where is it failing.
I would check
how many messages I am getting.
I will put one eventLog1.WriteEntry() inside loop to see what is happening with each message etc...

Turns out the service didn't have enough permissions, fixed it by setting the serviceProcessInstaller of the service on visual studio to User, so that when i installed it it'd ask for credentials. Just had to type "./[username]" when it asked for my username for it to work.
Another way of fixing it would be going into the task manager > services > right click service > properties > security. And change the permissions there.

Related

Building Windows Service in C# with periodic task [duplicate]

This question already has answers here:
Better way to constantly run function periodically in C#
(3 answers)
Closed 2 years ago.
Id like to build a windows Service in C#.
This service needs to be run periodically like every 10s.
Questions:
What is the difference between Timers.timer and Threading.timer?
How can I call CheckingThings with parameters?
If i run this code, it does invoke CheckingThings more than once every second like declared in here:
_timer = new Timer(new TimerCallback(CheckingThings), autoEvent, 5000, 1000);
Here is what i've got so far:
public partial class WindowsService1 : ServiceBase
{
// Logging
private static Serilog.Core.Logger _logEvent;
public WindowsService1()
{
InitializeComponent();
}
public void OnDebug() {
OnStart(null);
}
protected override void OnStart(string[] args)
{
//Logging
try {
_logEvent = new LoggerConfiguration()
.WriteTo.File(AppDomain.CurrentDomain.BaseDirectory + #"Logs\Logfile.txt", rollingInterval: RollingInterval.Month)
.CreateLogger();
}
catch (Exception e)
{
_logEvent.Error("The logging service is not working as expected: {errorMsg}", e);
}
try
{
// initializing some data here
var autoEvent = new AutoResetEvent(true);
while (true)
{
_timer = new Timer(new TimerCallback(CheckingThings), autoEvent, 5000, 1000);
}
}
catch (Exception e) {
_logEvent.Error("An error occured while initializing service: {0}", e);
}
}
private static void CheckingThings(object stateInfo)
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
//These things needs to run periodically every 10s
}
protected override void OnStop()
{
_logEvent.Information("Stopping Service ...");
}
}
Here's a skeleton for a service class that does something every minute, using a System.Timers.Timer:
public partial class XService : ServiceBase
{
private Timer _minute = new Timer(60000);
public XService()
{
InitializeComponent();
_minute.Elapsed += Minute_Elapsed;
}
//this is async because my 'stuff' is async
private async void Minute_Elapsed(object sender, ElapsedEventArgs e)
{
_minute.Stop();
try
{
//stuff
}
catch (Exception ex)
{
//log ?
}
finally
{
_minute.Start();
}
}
protected override void OnStart(string[] args)
{
_minute.Start(); //this or..
Minute_Elapsed(null, null); //..this, if you want to do the things as soon as the service starts (otherwise the first tick will be a minute after start is called
}
...
I typically stop my timers while I do my thing - no point starting a job that takes 10 minutes and then another one a minute later, hence the stop/try/finally/start pattern
Edit:
Here's the tail part of the class and how it's started/launched both in debug (inside visual studio) and in release (as an installed windows service):
//just an adapter method so we can call OnStart like the service manager does, in a debugging context
public void PubOnStop()
{
OnStop();
}
}// end of XService class
static void Main(string[] args)
{
#if DEBUG
new XService().PubStart(args);
Thread.Sleep(Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new XService()
};
ServiceBase.Run(ServicesToRun);
#endif
}

Windows service creates a .sys file frequently

I have created a windows service using .Net framework 4.7 with C# as the language. This service basically fetches computer hardware information (CPU usage) and writes it to a log file (using log4net). After compiling the service in release mode, when i installed it using installutil, the service is created and upon starting the service, a file with same name as 'exe' file with extension of 'sys' gets created frequently and deleted as well. Now when i stop the service, it is no longer created. I have created few windows services in the past using .Net but never encountered such behavior.
Program.cs
static void Main()
{
#if DEBUG
Service serv = new Service();
serv.StartIt();
Thread.Sleep(20000);
serv.StopIt();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service()
};
ServiceBase.Run(ServicesToRun);
#endif
}
Service.cs
Timer timer = null;
public Service()
{
InitializeComponent();
timer = new Timer(1000);
timer.Elapsed += Timer_Elapsed;
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
SystemInfo si = new SystemInfo();
si.GetSystemInfo();
}
#if DEBUG
public void StartIt()
{
timer.Start();
}
public void StopIt()
{
timer.Stop();
}
protected override void OnStart(string[] args)
{ }
protected override void OnStop() { }
#else
protected override void OnStart(string[] args)
{
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
}
#endif
Note: I am using OpenHardwareMonitor library to collect hardware information.
Link to the problem description

C# Windows Service - Timer is not working in debugging

I have started building up the windows service in the c# language. And i want to implement the timer feature inside it. But for some reason, the DoIt timer event handler is not getting fired during the debugging and i am not getting any exception also. I am trying to debug the windows service using Debug->Start new instance.
The line TraceLog.WriteTrace("Router Service Started"); does get hit and executed.
public partial class EntryPoint : ServiceBase
{
private const int TIMER_INTERVAL = 10000;
private System.Timers.Timer mvTimer = new System.Timers.Timer();
[MTAThread()]
[System.Diagnostics.DebuggerNonUserCode()]
public static void Main()
{
#if DEBUG
EntryPoint service = new EntryPoint();
service.Start();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new EntryPoint()
};
ServiceBase.Run(ServicesToRun);
#endif
}
public EntryPoint()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
InitializeComponent();
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception)e.ExceptionObject;
if (ex != null)
{
Console.WriteLine(ex);
}
}
public void Start()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
TraceLog.SetTrace(ConfigurationManager.AppSettings["RouterTraceLog"]);
TraceLog.WriteTrace("Router Service Started");
mvTimer = new Timer();
mvTimer.Elapsed += new ElapsedEventHandler(DoIt);
try
{
mvTimer.Interval = TIMER_INTERVAL;
mvTimer.Enabled = true;
}
catch (Exception ex)
{
mvTimer.Interval = TIMER_INTERVAL;
TraceLog.WriteTrace(ex.Message);
}
}
private void DoIt(object sender, ElapsedEventArgs e)
{
TraceLog.WriteTrace("Inside DoIt :: " + DateTime.UtcNow.ToString());
}
protected override void OnStop()
{
mvTimer.Enabled = false;
TraceLog.WriteTrace("Router Service stopping");
}
Please suggest. I am missing something very small and not able to nail it down.
In debug mode, the application exits after the function OnStart finishes. There's nothing to stop the application from quitting.
What you need is add a Console.ReadLine(); to prevent the application from exiting.
#if DEBUG
EntryPoint service = new EntryPoint();
service.Start();
Console.ReadLine();
#else
You can read more at MSDN on How to: Debug Windows Service Applications

Windows service does nothing on production PC

I have an application that schedules jobs using Quartz.Net. It works on my development laptop perfectly both as a winforms application (with start and stop buttons) and as a Windows Services whose OnStart() and OnStop() event code matches the start and stop button code of the winforms application. They're both in the same solution using the same "model" code (in its own project).
If I run the winforms application on the production computer it works perfectly, the jobs are executed according to their schedule as expected. However if I install and run it as a Windows Service on the production PC nothing happens! The jobs do not run.
I have no idea how to debug this. Please let me know if you have any suggestions as to what might be wrong.
Also please let me know what other information I should be providing.
Oh - dev PC is running Windows 7, production PC is running Windows 8.1! Could that be the problem? I built the service by following this tutorial: http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx which does not indicate that anything special needs to be done for deploying to Windows 8?
Could this have something to do with environment variables (which I know nothing about)?
Here is some code which may be relevant:
The service:
namespace DataPump
{
public partial class DataPumpService : ServiceBase
{
private TaskManager _taskManager;
public DataPumpService()
{
InitializeComponent();
_taskManager = new TaskManager();
}
protected override void OnStart(string[] args)
{
_taskManager.Go();
}
protected override void OnStop()
{
_taskManager.Stop();
}
}
}
The form code (different project):
namespace DataPump
{
public partial class Form1 : Form
{
private TaskManager _taskManager = new TaskManager();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
_taskManager.Go(); //Loops infinitely, does not block
label1.Text = "Running...";
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = "Stopping...";
_taskManager.Stop();
label1.Text = "Idle";
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_taskManager.Stop();
}
}
}
Selected code from TaskManager code (third project which the first two each reference):
public class TaskManager
{
//...
private IScheduler _scheduler = StdSchedulerFactory.GetDefaultScheduler();
//...
public void Go()
{
if (_scheduler.GetCurrentlyExecutingJobs().Count() == 0)
{
_scheduler.Start();
_scheduler.AddCalendar(CalendarName, MakeSAPublicHolidayCalendar(), false, true);
foreach (DatapumpJob job in JobList)
{
_scheduler.ScheduleJob(MakeJob(job), MakeTriggerCron(job));
}
}
}
//...
public void Stop()
{
foreach (string name in _scheduler.GetCurrentlyExecutingJobs().Select(j => j.JobDetail.Key.Name))
{
_scheduler.Interrupt(new JobKey(name));
}
_scheduler.Shutdown(true);
}
//...
}
Where JobList is a get only property that generates a List<DatapumpJob>where DatapumpJob implements IInterrutableJob but adds common features including a job name which gets use by the three methods beginning Make... which are all private methods within the TaskManager class.
This code is to answer a question from the comments regarding ServiceBase.Run():
Program.cs (auto-generated):
namespace DataPump
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new DataPumpService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
This turned out to be a network permissions issue. The service was running, it was just unable to access the network drive. So really my question was mi-specified.
After trying this: https://serverfault.com/questions/177139/windows-service-cant-access-network-share we eventually got it to work by setting the service to run as a specific user account on the PC.

Windows Service Tick ElapsedEventArgs is never called

I tried to deploy one service which works great in local to the production server. But on this server, the ElapsedEventHandler seems to never call my method Tick()
I have read other similar threads as
First Windows Service - timer seems not to tick
or
Timer tick event is not called in windows service
but i couldn't have any answer to my problem :/
I also tried to use _timer.Enabled=1 instead of _timer.Start (no incidence normally but still tried) and also tried to reinstall service a couple of times.
I use the Timer from Class System.Timers.
here is my code :
static void Main()
{
var servicesToRun = new ServiceBase[]
{
new SynchronizeEvents()
};
#if DEBUG
servicesToRun.LoadServices();
#else
ServiceBase.Run(servicesToRun);
#endif
}
and
public partial class SynchronizeEvents : ServiceBase
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();//Nlog
private Timer _timer;//From Class System.Timers
private readonly DbSetName _db = new DbSetName ();
private static readonly Dictionary<Employee, otherStuff> Subscriptions = new Dictionary<Employee, otherStuff>();
public SynchronizeEvents()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_logger.Trace("Service Start");
_timer = new Timer(5000) { AutoReset = false };//Same problem without AutoReset = false
_timer.Elapsed += Tick;
_timer.Start();
_logger.Trace("End OnStart");
}
protected override void OnShutdown()
{
_logger.Trace("OnShutdown");
_timer.Stop();
base.OnShutdown();
}
protected void Tick(object sender, ElapsedEventArgs elapsedEventArgs)
{
_logger.Trace("Tick");
_timer.Stop();
Compute();
_timer.Start();
}
protected override void OnStop()
{
_logger.Trace("OnStop");
}
Everything works great while on DebugMode and also on local computer in Release mode, but when i install it on production server the only logs i got are :
2014-09-08 16:35:57.1929 TRACE Service Start
2014-09-08 16:35:57.2085 TRACE End OnStart
i also got this when i stop the service...
2014-09-08 16:40:52.4072 TRACE End OnStop
Actually i got to apologize to Steve Wellens, he was right to ask about what Compute do.
The problem was related to Compute().
It had some code which required a DLL which was missing.
I don't know why _logger.Trace("Tick"); wasn't called and no Exception was triggered :/
I had to comment my program line per line to find out where the problem came from...

Categories

Resources