Установка сервисной службы Windows программно
-
27-10-2019 - |
Вопрос
Я пытаюсь установить сервис программно через C#, но я столкнулся с проблемой, которую я не могу передать.
После прочтения множества документации я в тот момент, где я считаю, что у Microsoft есть ошибка (но мы все знаем, что это не так).
Итак, вот Main
моего приложения.
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 });
Console.Read();
break;
case "/uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase.Run(new ProxyMonitor());
}
}
При выполнении в CMD в соответствии с привилегиями администрирования, как SO SO ProxyMonitor /install
Шаг в линию переходит к линии:
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
Как и ожидалось, а затем прыгает в мой класс установки, как так:
namespace Serco.Services.ProxyMonitor
{
[RunInstaller(true)]
public class ManagedInstallation : ServiceInstaller
{
public ManagedInstallation()
{
var ProcessInstaller = new ServiceProcessInstaller();
var ServiceInstaller = new ServiceInstaller();
//set the information and privileges
ProcessInstaller.Account = ServiceConfiguration.AccountType;
ServiceInstaller.DisplayName = ServiceConfiguration.DisplayName;
ServiceInstaller.StartType = ServiceConfiguration.StartType;
ServiceInstaller.Description = ServiceConfiguration.Description;
ServiceInstaller.ServiceName = ServiceConfiguration.ServiceName;
Installers.Add(ProcessInstaller);
Installers.Add(ServiceInstaller);
}
}
}
После проверки файла отладки я получаю следующее:
Installing assembly 'C:\Users\Robert\documents\visual studio 2010\Projects\ProxyMonitor\ProxyMonitor\bin\Debug\ProxyMonitor.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\Users\Robert\documents\visual studio 2010\Projects\ProxyMonitor\ProxyMonitor\bin\Debug\ProxyMonitor.InstallLog
assemblypath = C:\Users\Robert\documents\visual studio 2010\Projects\ProxyMonitor\ProxyMonitor\bin\Debug\ProxyMonitor.exe
Installing service ...
Creating EventLog source in log Application...
Rolling back assembly 'C:\Users\Robert\documents\visual studio 2010\Projects\ProxyMonitor\ProxyMonitor\bin\Debug\ProxyMonitor.exe'.
Affected parameters are:
logtoconsole =
logfile = C:\Users\Robert\documents\visual studio 2010\Projects\ProxyMonitor\ProxyMonitor\bin\Debug\ProxyMonitor.InstallLog
assemblypath = C:\Users\Robert\documents\visual studio 2010\Projects\ProxyMonitor\ProxyMonitor\bin\Debug\ProxyMonitor.exe
Restoring event log to previous state for source .
Я также получаю исключение в рамках следующего вызова:
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
Заявляя:
Установка не удалась, и откат был выполнен. Должен указать значение для источника.
Обновления:
Класс конфигурации
namespace Serco.Services.ProxyMonitor
{
class ServiceConfiguration
{
public static string DisplayName
{
get { return "Serco Proxy Monitor"; }
}
public static string ServiceName
{
get { return "Serco Proxy Monitor"; }
}
public static string Description
{
get
{
return "Serco ProxyMonitor is a helper developed to manage the state of the proxy for the employess whilst of the internal network.";
}
}
public static ServiceStartMode StartType
{
get{return ServiceStartMode.Automatic;}
}
public static ServiceAccount AccountType
{
get{return ServiceAccount.LocalSystem;}
}
/*.. /Snip/ ..*/
}
}
Решение
Похоже, источник журнала нулевый; Вы уверены, что ServiceConfiguration.ServiceName
определено и имеет значение?
Другие советы
Я понял это и подумал, что опубликую, что у других может быть такая же проблема.
Это была комбинация нескольких вещей, но я просто быстро покажу вам их:
public static string ServiceName
{
get { return "Serco Proxy Monitor"; }
}
- Должен был стать
return "SercoProxyMonitor";
Из -за пространств - Удалил
UnhandledException
которые затем показали более глубокие следы стека - Нужно иметь полные права администратора.
Я думаю, что главная проблема заключалась в том, что ServiceInstaller
использовал ServiceName
создать и EventLogSource
, И как были места в EventLogSource
Это выбрасывало подгонок.