Как создать полноценную службу в одном исполнимом модуле? Есть готовое приложение (можно взять нулевое winforms). Добавляю services.cs, и ничего не работает, никаких исключений.
ManagedInstallerClass.InstallHelper - читал - не получилось. Пробовал ставить через RunInstaller - тоже не работает.
Пробовал установить через sc create (в командной строке) - ставится.
Текст services.cs
using System;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;
namespace CaiNiaoServiceWinForms{
class Service:ServiceBase {
static string myname = "AMyService";
public Service()
{
this.ServiceName = myname;
this.CanStop = true;
this.CanPauseAndContinue = false;
this.AutoLog = true;
}
static public void Run() {
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service() };
ServiceBase.Run(ServicesToRun);
}
protected override void OnStart(string[] args){ // TODO: add startup stuff
}
protected override void OnStop(){
// TODO: add shutdown stuff
}
//---------------------------------
// Service config for UI
// тут работает
static ServiceController GetService() {
foreach (ServiceController item in ServiceController.GetServices())
if (item.ServiceName == myname) return item;
return null;
}
public static bool Installed {
get { // тут работает
return (GetService()!=null);
}
set { // тут не работает
string servicePath = System.Reflection.Assembly.GetEntryAssembly().Location;
if (value) { /*install*/
MyInstaller inst = new MyInstaller();
//inst.Install(dict); не работает, даже если создать словарь
//inst.Commit(dict);
}
//ManagedInstallerClass.InstallHelper(new[] { "/i" , servicePath, "/SERVICE" });
//ManagedInstallerClass.InstallHelper(new[] { servicePath , "/SERVICE" });
} else { /*uninstall*/
ManagedInstallerClass.InstallHelper(new[] { "/u" , servicePath, "/SERVICE" });
}
}
}
public static void DoStart () {
if (Installed) GetService().Start();
}
public static void DoStop () {
if (Installed) GetService().Stop();
}
}
//------------------
[System.ComponentModel.RunInstaller(true)]
public partial class MyInstaller: Installer {
// https://docs.microsoft.com/ru-ru/dotnet/api/system.serviceprocess.serviceinstaller
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public MyInstaller() {
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Manual;
serviceInstaller.Context =
new System.Configuration.Install.InstallContext(null, new string[]{"/SERVICE"});
}
}
}
И мой main (program.cs)
static void Main(string[] args)
{
try {
if (args.Length > 0) {
if (args[0] == "/SERVICE") {
Service.Run();
return;
}
if (args[0].ToUpper() == "/INSTALL") {
Service.Installed = true;
return;
}
if (args[0].ToUpper() == "/UNINSTALL") {
Service.Installed = false;
return;
}
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(args));
} catch (Exception e) {
MessageBox.Show(e.ToString());
}
}
Запуск службы... Для запуска службы по словам microsoft должен делаться вручную специнструментами или их специальной утилитой (при использовании InstallHelper и т п). Для установки использовал WMI.
P.S. Для установки запуска службы, программа должна быть запущена из-под админа (в том числе оснастка).
"Шаблон" службы получился такой
using System;
using System.ServiceProcess;
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;
using System.Threading;
using System.Management;
public partial class Service:ServiceBase {
static string myname = "CMyService";
public Service()
{
this.ServiceName = myname;
this.CanStop = true;
this.CanPauseAndContinue = false;
}
static public bool Run() {
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service() };
ServiceBase.Run(ServicesToRun);
return true;
}
static private volatile bool _Working;
static private volatile bool _Worked;
static public bool Working { get { return _Working; }}
static void MyThread(){
while (_Working){
Worker.current.Work();
}
_Worked = true;
}
protected override void OnStart(string[] args)
{
_Working = true;
_Worked = false;
(new Thread(new ThreadStart(MyThread))).Start();
}
protected override void OnStop()
{
_Working = false;
while (!_Worked) Thread.Sleep(1000);
}
//-----------------------------------------------------------
// Service config for UI
static ServiceController GetService() {
foreach (ServiceController item in ServiceController.GetServices())
if (item.ServiceName == myname) return item;
return null;
}
public static bool Installed {
get { return (GetService()!=null);}
set {
int q = 0;
string servicePath = System.Reflection.Assembly.GetEntryAssembly().Location;
//ManagementObject serv = new ManagementObject(new ManagementScope(@"root\CIMV2"),new ManagementPath( "Win32_Service"),null);
ManagementScope sc = new ManagementScope("root\\CIMV2");
sc.Connect();
if (value) { /*install*/
ManagementObject serv = new ManagementClass(sc, new ManagementPath("Win32_Service"),null);
q =Convert.ToInt32( serv.InvokeMethod("Create",new object[]
{ myname, myname, servicePath /*+" /SERVICE" /**/, 16/*own*/, 0, "Manual", 0 , ".\\LocalSystem", "", null }));
} else { /*uninstall*/
foreach(ManagementObject item in (new ManagementObjectSearcher(sc,new ObjectQuery("select * from Win32_Service"))).Get()){
if (item["Name"].ToString() == myname)
q =Convert.ToInt32( item.InvokeMethod("Delete",null));
}
}
string[] errors = {null, "The request is not supported" ,"Access denied","The service cannot be stopped because other services that are running are dependent on it",
"The requested control code is not valid, or it is unacceptable to the service","The requested control code cannot be sent to the service because the state of the service 0,1,2",
"The service has not been started","The service did not respond to the start request in a timely fashion",
"Unknown failure when starting the service","path was not found",
"The service is already running","The database to add a new service is locked.",
"A dependency this service relies on has been removed from the system",
"The service failed to find the service needed from a dependent service",
"The service has been disabled from the system","The service does not have the correct authentication to run on the system.",
"This service is being removed from the system.","The service has no execution thread.","The service has circular dependencies when it starts.",
"A service is running under the same name.","The service name has invalid characters.","Invalid parameters have been passed to the service.",
"The account under which this service runs is either invalid or lacks the permissions to run the service.",
"The service exists in the database of services available from the system.", "The service is currently paused in the system."};
if (q != 0) MessageBox.Show(q > 24? q.ToString():errors[q]);
}
}
public static void DoStart () {
if (Installed) GetService().Start();
}
public static void DoStop () {
if (Installed) GetService().Stop();
}
}
И текст программы такой
static void Main(string[] args)
{
int q = 0;
try {
q = System.Diagnostics.Process.GetCurrentProcess().SessionId;
} catch {};
if ((q == 0)?Service.Run() : false) return;
if (args.Length > 0) {
if (args[0].ToUpper() == "/INSTALL") { Service.Installed = true;return;}
if (args[0].ToUpper() == "/UNINSTALL"){Service.Installed = false;return;}
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(args));
}
Айфон мало держит заряд, разбираемся с проблемой вместе с AppLab
Обращаюсь к другому скрипту, подключенному к другому объекту, но выдает такую ошибку:
Задана две таблицы (mysql),
Подскажите пожалуйста, возможно каким-то образом, выводить время выполнения методов заданного класса ?