When I run my Windows Service with --console from a command prompt the console.txt file gets created so I know the ConsoleMode() method is being fired but nothing gets written to the console window. I know that Windows Services can't write to the console but shouldn't it just be running as a normal Console app since I bypass ServiceBase.Run?
using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ShowCheckerService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(params string[] args)
{
#if DEBUG
Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
if (Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
case "--console":
ConsoleMode();
break;
}
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
#endif
}
private static void ConsoleMode()
{
System.IO.File.Create(#"C:\ProgramData\ShowChecker\console.txt");
Console.WriteLine("asdf");
}
}
}
Had to change this in the properties:
A Windows service can actually Write A Console buffer, in fact i had once a console.read() and my service hung on that line look here https://stackoverflow.com/a/8793030/5601607
Related
Ok so im trying to make a program that checks if a program is currently running. It is giving me a error when ever i declare a void. I am new to C# so im sorry if its a stupid.
using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.VisualBasic.ApplicationServices;
namespace IsProgramRunning
{
private void IsRunning()
{
Process[] pname = Process.GetProcessesByName("VLC Player");
if (pname.Length > 0)
{
MessageBox.Show("Process Running");
}
else
{
MessageBox.Show("Process Not running");
}
System.Threading.Thread.Sleep(5 * 1000);
}
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
If im going about this all wrong and there is a easy way to do it in c++ that would be good to
To have instance members and methods, you need a class. You have confused a namespace with a class
namespace MyAwesomeNameSpace
{
public class ProgramRunningHelper
{
// put your class code here
}
}
Compiler Error CS0116
A namespace cannot directly contain members such as fields or methods.
A namespace can contain other namespaces, structs, and classes.
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 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();
}
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 have read this question. I have same issue, but I don't understand the answer from lubos hasko. How exactly can I do it? Can you someone post me full walkthrough?
When I run code below, something is installed, but in list of service, I could not find it.
I have this, but this not work:
using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
public class Service1 : ServiceBase
{
public Service1()
{
File.AppendAllText("sss.txt", "ccccc");
}
protected override void OnStart(string[] args)
{
File.AppendAllText("sss.txt", "asdfasdf");
}
protected override void OnStop()
{
File.AppendAllText("sss.txt", "bbbbb");
}
static void Main(string[] args)
{
if (System.Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase.Run(new Service1());
}
Console.ReadKey();
}
}
}
I dont understad this either:
if (System.Environment.UserInteractive) ...
This is my complete solution, and it works. It is basically the same answer as in this question.
using System;
using System.Configuration.Install;
using System.Reflection;
using System.ServiceProcess;
using System.IO;
namespace ConsoleApplication1
{
class Program : ServiceBase
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
if (System.Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase.Run(new Program());
}
}
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
File.AppendAllText(#"C:\Temp\error.txt", ((Exception)e.ExceptionObject).Message + ((Exception)e.ExceptionObject).InnerException.Message);
}
public Program()
{
this.ServiceName = "My Service";
File.AppendAllText(#"C:\Temp\sss.txt", "aaa");
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
File.AppendAllText(#"C:\Temp\sss.txt", "bbb");
}
protected override void OnStop()
{
base.OnStop();
File.AppendAllText(#"C:\Temp\sss.txt", "ccc");
}
}
}
and in same project create this class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace ConsoleApplication1
{
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "My Service";
serviceInstaller.StartType = ServiceStartMode.Automatic;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = "My Service";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}
}
Run this program with parameters --install/--uninstall as Administrator on Windows 7. Check the error log in temp. Check working log on the same path.
First of all, in your Service1 constructor set ServiceName property.
Excerpt from MSDN:
The minimum you need to implement in the constructor for a class inherited from ServiceBase is to set the ServiceName on your component. No other processing is specifically required in the constructor. You should handle most initialization in OnStart rather than in the constructor.
Second of all you need to pass arguments to your service when running it from command line. --install for install, --uninstall for uninstall - look at your switch statement it's doing it on input arguments.
System.Environment.UserInteractive property tells you that
whether a Windows process or a service like IIS that runs without a user interface.
If this property is false, do not display modal dialogs or message boxes because there is no graphical user interface for the user to interact with.
Source
Check this article as well.