I have searched and searched for Windows Service information and it is mostly non-existent or outdated. Further, there is no Windows Service template in VS 2013 (that I can find).
I am making a simple performance monitor that logs to a text file the CPU and RAM. I followed a couple outdated tutorials and came up with stuff on my own.
When I try running via F5 (a coworker's suggestion) the command prompt flashes open, closes and then the program ends. I don't think the OnStart method is ever invoked.
I can get the service installed fine from the VS command prompt but when trying to start the process I get an error that it does not start in a timely manner. I have even tried enabling interaction with the desktop in the Service Manager.
I have also tried both Debug and Release builds.
I have looked at other SO questions that suggested to do all initialization in the OnStart method, which I think I do (though I may be wrong -- I am obviously still learning).
The relevant code:
namespace SystemMonitorD
{
public class SystemMonitorD : ServiceBase
{
private Timer StateTimer { get; set; }
private TimerCallback TimerDelegate { get; set; }
private SystemMonitorL SysMon { get; set; }
public SystemMonitorD()
{
ServiceName = "SystemMonitorD";
CanStop = true;
CanPauseAndContinue = true;
AutoLog = true;
}
protected override void OnStart(string[] args)
{
SysMon = new SystemMonitorL();
TimerDelegate = SysMon.Log;
StateTimer = new Timer(TimerDelegate, null, SysMon.WaitTime, SysMon.WaitTime);
}
protected override void OnStop()
{
SysMon.StatusLog("Stop");
StateTimer.Dispose();
}
protected override void OnPause()
{
SysMon.StatusLog("Pause");
StateTimer.Change(Timeout.Infinite, Timeout.Infinite);
}
protected override void OnContinue()
{
SysMon.StatusLog("Continue");
StateTimer.Change(SysMon.WaitTime, SysMon.WaitTime);
}
public static void Main()
{
}
}
public class SystemMonitorL
{
private readonly String _fileLocation = #"C:\Users\ian.elletson\Desktop\logD.txt";
public int WaitTime { get; private set; }
private IOutput Logger { get; set; }
private List<SystemMonitor> SystemMonitors { get; set; }
public SystemMonitorL()
{
WaitTime = 1000;
Logger = new Logger(_fileLocation);
SystemMonitors = new List<SystemMonitor>
{
SystemMonitorFactory.MakeSystemMonitor("CPU"),
SystemMonitorFactory.MakeSystemMonitor("RAM")
};
Logger.WriteLine(string.Format("Polling every {0} second(s)", WaitTime / 1000));
}
public void Log(Object stateObject)
{
foreach (var monitor in SystemMonitors)
{
Logger.WriteLine(monitor.ToString());
}
}
public void StatusLog(String status)
{
String message;
switch (status)
{
case "Stop" :
message = "stopped";
break;
case "Pause" :
message = "paused";
break;
case "Continue":
message = "continued";
break;
default:
message = "ERROR";
break;
}
Logger.WriteLine(string.Format("Logging {0} at {1}", message, TimeZone.CurrentTimeZone.ToLocalTime(DateTime.Now)));
}
}
[RunInstaller(true)]
public class SystemMonitorDInstaller : Installer
{
ServiceProcessInstaller ProcessInstaller { get; set; }
ServiceInstaller ServiceInstaller { get; set; }
public SystemMonitorDInstaller()
{
ProcessInstaller = new ServiceProcessInstaller();
ServiceInstaller = new ServiceInstaller();
ProcessInstaller.Account = ServiceAccount.LocalSystem;
ServiceInstaller.StartType = ServiceStartMode.Manual;
ServiceInstaller.ServiceName = "SystemMonitorD";
Installers.Add(ServiceInstaller);
Installers.Add(ProcessInstaller);
}
}
}
One thing that makes life easier dealing with while debugging windows services is to use the Debug\Release flag for your service. To step through the logic as a non-service.
static void Main()
{
#if (!DEBUG)
//RELEASE FLAG
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
//DEBUG
MyService service = new MyService(); //<--Put breakpoint here before you run your service
service.OnStart(null);
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
I discovered my problem. I was missing
ServiceBase.Run(new SystemMonitorD()); in my Main() method. That solved the problem. I found this from this MSDN link.
Related
I'm using the Quartz.NET library to create a job in my C# application.
I have some registers in my database, so I have a table wich contains a column called "start_date". The job runs every 50 seconds, so I compare the dates from the column "start_date" with the date of my computer, and if the dates are equal, I want to instantiate a new Windows Form with a message and a button.
At the moment, the new Windows Form is opening at the right moment, but the message is not showed and the window stops to respond.
Basically, in my code I have something like this:
FormMessage.cs
public partial class FormMessage : Form
{
public FormMessage()
{
InitializeComponent();
}
public FormMessage(double minutes)
{
InitializeComponent();
string message = string.Format("You have {0} minutes!", minutes);
lblMessage.Text = message ;
}
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
}
JobMessage.cs
public class JobMessage: IJob
{
List<Information> informations;
public void Execute(IJobExecutionContext context)
{
//Class with methods to get registers from database.
InformationAPI infoAPI = new InformationAPI();
informations = infoAPI.GetInformations();
foreach (Information info in informations)
{
DateTime computerDateTime = DateTime.Now;
DateTime infoDateTime = info.StartDate;
double difference;
if (DateTime.Compare(computerDateTime, infoDateTime) < 0)
{
difference = Math.Round(infoDateTime.Subtract(computerDateTime).TotalMinutes);
if (difference == 5)
{
FormMessage formMessage = new FormMessage(difference);
formMessage.Show();
}
}
}
}
}
Someone have some idea of the reason why the FormMessage window stops to respond?
Thank you for your attention!
You can try Quartz Listeners to let them open the form to show the data and keep the execution out of the job scope:
Action<IJobExecutionContext, JobExecutionException> listenerAction = (c, e) => {
var dataMap = context.GetJobDetail().GetJobDataMap();
var difference = dataMap.GetIntValue("difference");
FormMessage formMessage = new FormMessage(difference);
formMessage.Show();
}
var listener = new SyncJobListener(listenerAction);
And add the listener in to the scheduler:
scheduler.ListenerManager.AddJobListener(listener,
GroupMatcher<JobKey>.GroupEquals("GroupName"));
Using this SyncJobListener:
public class SyncJobListener : IJobListener
{
private readonly Action<IJobExecutionContext, JobExecutionException> _syncExecuted;
public string Name { get; private set; }
public SyncJobListener(
Action<IJobExecutionContext, JobExecutionException> syncExecuted
)
{
Name = Guid.NewGuid().ToString();
_syncExecuted = syncExecuted;
}
public void JobToBeExecuted(IJobExecutionContext context)
{
}
public void JobExecutionVetoed(IJobExecutionContext context)
{
}
public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
{
_syncExecuted(context, jobException);
}
}
I have not tested this so if the dataMap does not have any data, you are going to need to allow the persistance:
[PersistJobDataAfterExecution]
[DisallowConcurrentExecution]
public class JobMessage: IJob {}
I am new in windows service c#. I have a class library called JobAdminLib which has a class call ArchiveAutomationAdministrator. This class has a method called CountJobs(). I have created a windows service which would run this particular method at the scheduled interval of time. But it does not seems to work for me. Log reports are saying its running but the function that the method is supposed to perform is not working.
I have attached code for reference
public class ArchiveAutomationAdministrator
{
JobRepository repository = new JobRepository();
public IEnumerable<LiveJobs> GetCurrentlyRetentionJobs(Func<LiveJobs, bool>
criteria = null)
{
return from job in repository.GetCurrentlyRetentionJobs() select job;
}
public void countJobs()
{
var count = from job in repository.GetCurrentlyRetentionJobs() select job;
int[] JobCount = new int[count.Count()];
for (int i = 1; i <= JobCount.Length; i++)
{
string jobnumber = repository.GetCurrentlyRetentionJobs().First().JobNumber;
JobAdministrator admin = new JobAdministrator(repository);
admin.ArchiveJob(jobnumber);
}
}
}
Following is my windows service
public partial class Scheduler : ServiceBase
{
private Timer timer1 = null;
public Scheduler()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1 = new Timer();
this.timer1.Interval = 5000;
this.timer1.Elapsed += new
System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
Library.WriteErrorLog("test windows service started");
}
public void timer1_Tick(object sender, ElapsedEventArgs e)
{
this.task();
Library.WriteErrorLog("Job running successfully");
}
protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteErrorLog("Service Stopped");
}
public void task()
{
Library.WriteErrorLog("Inside task");
ArchiveAutomationAdministrator admin = new ArchiveAutomationAdministrator();
admin.countJobs();
}
}
check if windows servers has the authority to run
if it Ok
go to windows service list
1- open run cmd
2- type services.msc
3- right click on your service name
4- in login tab click on Local System Account and Check Allow Service To Interact with desktop
That countJobs method has a crazy way of enumerating a list. Its hard to tell if this will work but try the below...
public void countJobs()
{
foreach (var job in repository.GetCurrentlyRetentionJobs())
{
Library.WriteErrorLog("Archiving job " + job.JobNumber);
string jobnumber = job.JobNumber;
JobAdministrator admin = new JobAdministrator(repository);
admin.ArchiveJob(jobnumber);
}
}
that way you will get logging inside the loop and you'll be able to tell if there is anything to actually process.
I'm new in Microsoft Message Queue in Windows Server, I need to push, if the EmployeeID is NULL.
The Employee Model Class is
public class Employee
{
public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
}
public void ValidationProcess(Employee emp)
{
if((emp != null) || (emp.EmployeeID == null))
{
// Push into Validation Exception Queue using MSMQ
}
}
Once the Data pushed into that Validation Exception Queue, it should be processed by separate process. Every 1hr the process need to initiate and it should call the following method
public void ValidationExceptionProcess(object obj)
{
// Some Inner Process
// Log the Error
}
Kindly guide me how to create and process it.
First Step:
Install MSMQs as a windows feature on the server/pc
Then:
- Create the queue if it does not exist
- Push the message in the queue asynchronously
Useful guide
Code example for pushing and retrieving messages from msmq:
public class ExceptionMSMQ
{
private static readonly string description = "Example description";
private static readonly string path = #".\Private$\myqueue";
private static MessageQueue exceptionQueue;
public static MessageQueue ExceptionQueue
{
get
{
if (exceptionQueue == null)
{
try
{
if (MessageQueue.Exists(path))
{
exceptionQueue = new MessageQueue(path);
exceptionQueue.Label = description;
}
else
{
MessageQueue.Create(path);
exceptionQueue = new MessageQueue(path);
exceptionQueue.Label = description;
}
}
catch
{
throw;
}
finally
{
exceptionQueue.Dispose();
}
}
return exceptionQueue;
}
}
public static void PushMessage(string message)
{
ExceptionQueue.Send(message);
}
private static List<string> RetrieveMessages()
{
List<string> messages = new List<string>();
using (ExceptionQueue)
{
System.Messaging.Message[] queueMessages = ExceptionQueue.GetAllMessages();
foreach (System.Messaging.Message message in queueMessages)
{
message.Formatter = new XmlMessageFormatter(
new String[] { "System.String, mscorlib" });
string msg = message.Body.ToString();
messages.Add(msg);
}
}
return messages;
}
public static void Main(string[] args)
{
ExceptionMSMQ.PushMessage("my exception string");
}
}
An other widely used way to do that would also be to use out of the box loggers which already contains this functionality like Enterprise Library or NLog which provide easy interfaces to do that.
For retrieving messages I would recommend a separate windows service which would periodically read messages and process them. An good example on how to do that is given here: Windows service with timer
Update: Windows Service Example:
MSMQConsumerService.cs
public partial class MSMQConsumerService : ServiceBase
{
private System.Timers.Timer timer;
public MSMQConsumerService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer(30000D); // 30000 milliseconds = 30 seconds
this.timer.AutoReset = true;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.ProcessQueueMessages);
this.timer.Start();
}
protected override void OnStop()
{
this.timer.Stop();
this.timer = null;
}
private void ProcessQueueMessages(object sender, System.Timers.ElapsedEventArgs e)
{
MessageProcessor.StartProcessing();
}
}
and the MessageProcessor.cs
public class MessageProcessor
{
public static void StartProcessing()
{
List<string> messages = ExceptionMSMQ.RetrieveMessages();
foreach(string message in messages)
{
//write message in database
}
}
}
I have developed a Windows Service whose task is actually to start a host with particular url and port. Below is what I have now.
Program.cs
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new WindowsDxService()
};
ServiceBase.Run(ServicesToRun);
}
ProjectInstaller.cs
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
}
WindowsDxService.cs
public partial class WindowsDxService : ServiceBase
{
public WindowsDxService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
var url = "http://127.0.0.1:9000";
using (var host = new NancyHost(new Uri(url)))
{
host.Start();
}
}
}
Configuration on serviceProcessInstaller1 and serviceInstaller1 in ProjectInstaller.cs [Design] file.
serviceProcessInstaller1
Account=LocalSystem
serviceInstaller1
StartType=Automatic
Library.cs
public class Library : NancyModule
{
public Library()
{
Get["/"] = parameters =>
{
return "Hello world";
};
Get["jsontest"] = parameters =>
{
var test = new
{
Name = "Guruprasad Rao",
Twitter="#kshkrao3",
Occupation="Software Developer"
};
return Response.AsJson(test);
};
}
}
Basically I followed this tutorial which actually shows how to do it with Console application which I succeeded though, but I wanted to have this as Windows Service which actually starts a host with specified port whenever the system starts. The service is started successfully and running but whenever I browse the url in the same system its not showing up the page, which means our basic This webpage is not available message. What else configuration I have to do so as to start the host? Hoping for a help.
You are disposing the host when you start your service. I would suggest something like this:
public partial class WindowsDxService : ServiceBase
{
private Host host;
public WindowsDxService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.host = new NancyHost(...)
this.host.Start();
}
protected override void OnStop()
{
this.host.Stop();
this.host.Dispose();
}
}
You'd probably find it a lot easier to write the service if you used TopShelf library.
I have a WCF service library (MyWCFService), which uses MEF to load plugins and hosted by Windows services (All .NET 4.0). I am now trying to run it in a new AppDomain and to enable ShadowCopyFiles in a hope that I can update plugins in the runtime. Here is the code in the Windows service project.
Program.cs
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
}
MyService.cs
public partial class MyService: ServiceBase
{
internal static ServiceHost MyServiceHost = null;
public MyService()
{
// this works but is deprecated..
AppDomain.CurrentDomain.SetShadowCopyFiles();
//this is not working.. DLLs still get locked. Require for a new AppDomain
//AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles = "true";
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if(MyServiceHost !=null)
{
MyServiceHost.Close();
}
try
{
MyServiceHost= new ServiceHost(typeof(MyWCFService));
MyServiceHost.Open();
}
catch(Exception)
{
}
}
protected override void OnStop()
{
if (MyServiceHost!= null)
{
MyServiceHost.Close();
MyServiceHost= null;
}
}
}
Is there any way of doing it? I have done a lot of search, but still don't know how to make it work with my current settings (or I just can't understand...)
I have tried to create a new AppDomain inside Main() and used
domain.DoCallBack(new CrossAppDomainDelegate(() => { ServiceBase.Run(ServicesToRun); })) to start the service but I can't start it and keep getting "Error 1053: The service did not respond to the start or control request in a timely fashion".
And then I tried to just enable Shadow copy for the current appdomain by setting AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles = "true"; in MyWCFService.cs just before InitializeComponent(); I can start the service but the dlls are still locked. however, if I use AppDomain.CurrentDomain.SetShadowCopyFiles(); (a deprecated method) to enable the shadow copy, everything works. I'm more confused.
OK, I ended up with creating a shell/proxy class inherited from MarshalByRefObject and start the service from there, and here is the code:
ServiceShell.cs
public class ServiceShell:MarshalByRefObject
{
internal static ServiceHost MyServiceHost = null;
public void Run()
{
if (MyServiceHost != null)
{
MyServiceHost.Close();
}
try
{
MyServiceHost = new ServiceHost(typeof(MyWCFService));
MyServiceHost.Open();
}
catch (Exception)
{
}
}
public void Stop()
{
if (MyServiceHost!= null)
{
MyServiceHost.Close();
MyServiceHost = null;
}
}
}
MyService.cs
public partial class MyService: ServiceBase
{
AppDomain domain;
ServiceShell runner;
public MyService()
{
var setup = new AppDomainSetup
{
ShadowCopyFiles = "true"
};
domain = AppDomain.CreateDomain("MyServiceHostDomain", AppDomain.CurrentDomain.Evidence, setup);
runner = (ServiceShell)domain.CreateInstanceAndUnwrap
(typeof(ServiceShell).Assembly.FullName, typeof(ServiceShell).FullName);
InitializeComponent();
}
protected override void OnStart(string[] args)
{
runner.Run();
}
protected override void OnStop()
{
runner.Stop();
AppDomain.Unload(domain);
}
}