I Have following code, which does not executed when windows service starts
I found solutions here but they didn't work for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration;
using System.Threading.Tasks;
namespace TFS_JIRA_sync
{
public partial class SyncProcess : ServiceBase
{
public SyncProcess()
{
InitializeComponent();
}
private System.Timers.Timer timer = new System.Timers.Timer();
protected override void OnStart(string[] args)
{
this.timer.Interval = ScanPeriod.period * 60000; //turn minutes to miliseconds
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);//OnTimer;
this.timer.Enabled = true;
this.timer.AutoReset = true;
this.timer.Start();
}
private void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
{
Processing proc = new Processing();
proc.doProcess();
}
protected override void OnStop()
{
}
}
}
In Programm:
using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Threading.Tasks;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace TFS_JIRA_sync
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SyncProcess()
};
ServiceBase.Run(ServicesToRun);
//Processing proc = new Processing();
//proc.doProcess();
}
}
}
When I comment part starting "ServiceBase[]..." and uncomment "Processing ..." in Programm class it works fine.
But when my code run as Windows service - Nothing happens
As I see your service is not going to run all the time
this.timer.Interval = ScanPeriod.period * 60000;. For your scenario
rather than having a windows service with a timer (and spending time on resolving the issue), I'd recommended to use a scheduled task (as suggested by this answer).
It references a Jon Gallow's article, that gives a lot of reasons why it is better to use a scheduled task.
If you're writing a Windows Service that runs a timer, you should re-evaluate your solution.
Put Console.ReadLine() in your code:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SyncProcess()
};
ServiceBase.Run(ServicesToRun);
Console.ReadLine();
}
Related
I have following problem with the windows service I was writing:
When I start the service it stops immediately. When I was using a console app it wasn't crushing. I have no idea what's the cause of this problem.
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration;
using System.Configuration.Install;
using WindowsService;
namespace WS
{
[ServiceContract(Namespace = "http://WS")]
public interface INewsReader
{
}
public class NewsReaderService : INewsReader
{
public NewsReaderService()
{
var config = new Config();
var scheduled = new Schedule(config);
scheduled.ExecuteScheduledEvents();
while (true)
{
System.Threading.Thread.Sleep(1000);
int i = 0;
}
}
}
public class NewsReaderWindowsService : ServiceBase
{
public ServiceHost serviceHost = null;
public NewsReaderWindowsService()
{
ServiceName = "NewsReaderWindowsService";
}
public static void Main()
{
ServiceBase.Run(new NewsReaderWindowsService());
}
protected override void OnStart(string[] args)
{
var thread = new System.Threading.Thread(() =>
{
while (true)
{
int i = 0;
System.Threading.Thread.Sleep(1000);
}
});
thread.Start();
serviceHost = new ServiceHost(typeof(NewsReaderService));
serviceHost.Open();
}
protected override void OnStop()
{
}
}
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller process;
private ServiceInstaller service;
public ProjectInstaller()
{
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "NewsReaderWindowsService";
Installers.Add(process);
Installers.Add(service);
}
}
}
Well, first of all I think your OnStart method is written badly. I can't see the reason for creating a, basicly, empty thread. You should there only initialize service (If necessary), immediately start a new thread that will work for whole time and leave the OnStart method.
Second of all use try catch block, because in my opinion somewhere in there is exception and that's why your windows service stops.
Thirdly see this example WCF Hosting with Windows Service
I have development a WindowsServices, but I have a problem when I try to run it.
This is the code of windows service:
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Threading;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ScriptServices
{
public partial class Service1 : ServiceBase
{
public EventLog eventLog1;
public System.Timers.Timer timer1;
private static readonly ILog log = log4net.LogManager.GetLogger
(MethodBase.GetCurrentMethod().DeclaringType);
//read the parameter from config file
static int hours = 0;
static int minutes = 0;
//read the parameter
static int hoursFrequency = 24;
static int minutesFrequency = 0;
static int secondsFrequency = 0;
static int elapsedTimeBetween2BatchFile = 0;
public Service1()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("AutomaticallyRunScript"))
{
System.Diagnostics.EventLog.CreateEventSource(
"AutomaticallyRunScript", "MyNewLog");
}
timer1 = new System.Timers.Timer();
timer1.Interval = 1000; //Intervallo di 10 seconti
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Enabled = true;
}
/// <summary>
/// ogni x secondi partirà un thread per andare a sincronizzare il database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//eventLog1.WriteEntry("Thread partiti");
try
{
int i = 0;
int x = i + 100;
log.Info("entrato");
log.Info("i vale: " + i);
}
catch (Exception exc)
{
log.Error(exc);
//EventLog.WriteEntry("Errore: "+exc.StackTrace, EventLogEntryType.Error);
}
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("GestoreService start");
}
protected override void OnStop()
{
eventLog1.WriteEntry("GestoreService stop");
}
}
}
This is the main class:
using System.Text;
using System.Threading.Tasks;
namespace ScriptServices
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
I try to install it through InstallUtile, it works. But if I see the TaskManager, I see the services is stopped, so I try to run it manually, then I received this error
I'm creating a checkout system for a supermarket. It consists of a checkout, server and MIS program an operates WCF services between them. The problem I have is that the checkout program, which is a windows form, does a few neccessaries in it's application_load method and then just quits.
Here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CheckoutLibrary;
using Checkout.ServerLibraryService;
using Checkout.MarketService;
namespace Checkout
{
public partial class theForm : Form
{
private static int checkoutID = 3;
private Product[] allProducts;
public theForm()
{
InitializeComponent();
}
private void theForm_Load(object sender, EventArgs e)
{
// First cache all products
SupermarketServiceSoapClient marketService = new SupermarketServiceSoapClient();
allProducts = marketService.GetAllProducts();
// Load the service provided by the server
ServiceClient serverService = new ServiceClient();
// Load the event handlers for the bar code scanner
BarcodeScanner scanner = new BarcodeScanner();
scanner.ItemScanned += new BarcodeScanner.ItemScannedHandler(scanner_ItemScanned);
scanner.AllItemsScanned += new BarcodeScanner.AllItemsScannedHandler(scanner_AllItemsScanned);
scanner.Start(checkoutID);
}
void scanner_AllItemsScanned(EventArgs args)
{
throw new NotImplementedException();
}
void scanner_ItemScanned(ScanEventArgs args)
{
itemTextBox.Text = "Scanned " + GetItemName(args.Barcode);
}
private void scanItemButton_Click(object sender, EventArgs e)
{
scanner_ItemScanned(new ScanEventArgs(GetRandBarcode()));
}
// A barcode -> product name look up method
public string GetItemName(int barcode)
{
return allProducts[barcode].Description + " # " + allProducts[barcode].Price;
}
// Method to grab a random barcode for simulation
private int GetRandBarcode()
{
Random rand = new Random();
return rand.Next(0,500);
}
}
}
And program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Checkout
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new theForm());
}
}
}
Thanks for any insight.
In WinForms, if your form_load throws an exception, it quits without displaying anything. Annoying, but I'm guessing that's the problem.
You can try a try/catch, or you can hit CTRL+ALT+E and check the Thrown Column for Common Language Runtime Exceptions to see the error.
UPDATE:
Based on comments, here's a sample way to execute something on another thread.
ThreadStart ts = new ThreadStart(() => {
try {
scanner.Start(checkoutID);
} catch {
// Log error
}
});
Thread t = new Thread(ts);
t.Start();
I am trying to create a simple service in C# using VS2008 that creates a text file when the computer goes into sleep mode. My current code throws out the following error:
'SleepNotifierService.WqlEventQuery' does not contain a constructor that takes '1' arguments
Now I looked in the Object browser, and it looks like it does take in one argument. This is what the browser had to say:
public WqlEventQuery(string queryOrEventClassName)
Here is my code:
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.Management;
using System.IO;
namespace SleepNotifierService
{
public class WqlEventQuery : EventQuery { }
public partial class Service1 : ServiceBase
{
ManagementEventWatcher _watcher;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();
}
protected override void OnStop()
{
_watcher.Stop();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
//Log(ex.Message);
}
}
public void Sleep()
{
StreamWriter SW;
SW = File.CreateText("c:\\MyTextFile.txt");
SW.WriteLine("Sleep mode initiated");
SW.Close();
}
public void Resume()
{
}
}
}
Am I interpreting that object browser wrong? I'm new to creating services and C#/.NET in general so it might be something trivial.
Appreciate any help,
Tomek
You're using wrong WqlEventQuery. There's one defined in System.Management and it indeed has a one-argument constructor, but there's also your custom WqlEventQuery class.
If you want to use .NET BCL's class, you'll have to fully qualify it:
var query = new System.Management.WqlEventQuery("Win32_PowerManagementEvent");
or even prefix it with global keyword:
var query = new global::System.Management.WqlEventQuery("Win32_PowerManagementEvent");
I have the VS2005 standard edition and MS says this:
Note: The Windows Service Application
project templates and associated
functionality are not available in the
Standard Edition of Visual Basic and
Visual C# .NET...
Is it possible to write a Windows Service application without upgrading my VS2005 Standard edition?
If you can cut and paste, an example is enough.
A simple service to periodically log the status of another service. The example does not include the ServiceInstaller class (to be called by the install utility when installing a service application), so installing is done manually.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace SrvControl
{
public partial class Service1 : ServiceBase
{
Timer mytimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (mytimer == null)
mytimer = new Timer(5 * 1000.0);
mytimer.Elapsed += new ElapsedEventHandler(mytimer_Elapsed);
mytimer.Start();
}
void mytimer_Elapsed(object sender, ElapsedEventArgs e)
{
var srv = new ServiceController("MYSERVICE");
AppLog.Log(string.Format("MYSERVICE Status {0}", srv.Status));
}
protected override void OnStop()
{
mytimer.Stop();
}
}
public static class AppLog
{
public static string z = "SrvControl";
static EventLog Logger = null;
public static void Log(string message)
{
if (Logger == null)
{
if (!(EventLog.SourceExists(z)))
EventLog.CreateEventSource(z, "Application");
Logger = new EventLog("Application");
Logger.Source = z;
}
Logger.WriteEntry(message, EventLogEntryType.Information);
}
}
}
Yes, look here:
http://www.codeproject.com/KB/system/WindowsService.aspx
Sure, you just need to write the code yourself. It's not actually very hard. Here are a couple of references to how to do it:
http://msdn.microsoft.com/en-us/magazine/cc301845.aspx
http://www.aspfree.com/c/a/C-Sharp/Creating-a-Windows-Service-with-C-Sharp-introduction/