Ошибка 1064 при запуске службы

I wrote a Windows Service to run on Win10, and it worked perfectly fine until I decided to change it a bit. I rewrote some logic, tested it in both Debug and Release configurations, and everything ...

I wrote a Windows Service to run on Win10, and it worked perfectly fine until I decided to change it a bit. I rewrote some logic, tested it in both Debug and Release configurations, and everything was fine. Then I uninstalled the current version of the service using installutil.exe /u %servicename.exe% and reinstalled it again using installutil.exe %servicename.exe%.
For some reason, this new version cannot start, and it crashes with Error 1064. This is the full error text:

Windows could not start %servicename% service on Local Computer. Error 1064: An exception occurred in the service when handling the control request.

The last time I installed this service, I ran into some difficulties, but quickly fixed them by changing the Log On properties. This time, it is not working. Please help with this issue.

Thanks.

Update 1

Here are my Main() and OnStart() service methods:

Main()

static void Main()
{
#if DEBUG
    var service = new SalesforceToJiraService();
    service.OnDebug();
    Thread.Sleep(Timeout.Infinite);
#else
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new SalesforceToJiraService()
    };
     ServiceBase.Run(ServicesToRun);
#endif
}

OnStart()

protected override void OnStart(string[] args)
{
    this.ConfigureServices();

    this.timer.Start();
    this.logger.Information("SalesforceToJira service started.");
}

Update 2

More code:

ConfigureServices()

protected void ConfigureServices()
{
    this.configuration = ConfigurationHelper.LoadConfiguration(ConfigurationPath);
    this.logger = ConfigurationHelper.ConfigureLogger(this.configuration.Logs.LogsPath);

    this.timer = ConfigurationHelper.ConfigureTimer(this.configuration.ProcessInterval.TotalMilliseconds,
        (sender, eventArgs) => this.ProcessCasesAsync(sender, eventArgs).GetAwaiter().GetResult());

    this.salesforceClient = new SalesforceCliClient(this.configuration.Salesforce.CliPath);

    this.jiraClient = Jira.CreateRestClient(
        this.configuration.Jira.Url,
        this.configuration.Jira.Username,
        this.configuration.Jira.Password);
}

I’m using Newtonsoft.JSON for deserializing a JSON configuration file, Serilog for logging, System.Timers.Timer for periodic events, AtlassianSDK for the Jira API and some wrappers over Salesforce CLI for Salesforce.

3 / 3 / 1

Регистрация: 19.05.2019

Сообщений: 159

1

04.04.2021, 14:31. Показов 8424. Ответов 5


https://docs.microsoft.com/ru-… t-designer

выполнял код отсюда, значит код рабочий , уверен кто это делал сталкивался с этой проблемой и надеюсь решил.
Тоесть моя служба видна в списке служб , при ее запуске выскакивает такая ошибка.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



3 / 3 / 1

Регистрация: 19.05.2019

Сообщений: 159

04.04.2021, 14:36

 [ТС]

2

Увеличиваю сообщение до 3х символов

Миниатюры

Ошибка службы при обработке команды (1064)
 



0



2715 / 2026 / 374

Регистрация: 22.07.2011

Сообщений: 7,672

04.04.2021, 14:58

3

ДЛ имончик, пример кода в методе OnStart покажите.



0



ДЛ имончик

3 / 3 / 1

Регистрация: 19.05.2019

Сообщений: 159

04.04.2021, 16:44

 [ТС]

4

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
protected override void OnStart(string[] args)
        {
            ServiceStatus serviceStatus = new ServiceStatus();
            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint = 100000;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
            eventLog1.WriteEntry("In OnStart.");
            Timer timer = new Timer();
            timer.Interval = 60000; // 60 seconds
            timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
            timer.Start();
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
        }



0



2715 / 2026 / 374

Регистрация: 22.07.2011

Сообщений: 7,672

04.04.2021, 20:42

5

ДЛ имончик, оберни все это в try catch , наверняка тут падает , потому служба и не стартует.



0



ДЛ имончик

3 / 3 / 1

Регистрация: 19.05.2019

Сообщений: 159

05.04.2021, 13:08

 [ТС]

6

не помогло, служба запускается , грузится и тогда возникает ошибка (где то на 10%), она и раньше начинала запуск
У меня есть метод

C#
1
private void eventLog1_EntryWritten(object sender, EntryWrittenEventArgs e)

он пустой , но при этом есть такие команды

C#
1
 eventLog1.WriteEntry("File not found");

мб тут проблема?

Добавлено через 16 минут
не фигня, не прав



0



For some reason and to come to speed with all the Veeam components, I decided to revive my Veeam Lab and during the process, I encountered the following error “Error 1064 — An exception occurred in the service when handling the control request : No connection can be made because the active machine rejected it “. Before I proceed to fix this issue, I would love to discuss the capabilities of Veeam for anyone that may stumble on this article. 

Veeam Backup & Replication is comprehensive data protection and disaster recovery solution that provides a centralized console for administering backup, restore, replication operations in all supported platforms (virtual, physical, cloud). Regardless of what your needs are ranging from flexible hybrid cloud capabilities from AWS, Azure, and Google Cloud, or the most robust ransomware protection and recovery options. Veeam brings hardened immutable storage options, dependable cloud-native backup options, Continuous Data Protection, and much more all under one platform, with a single portable license for all workloads

Below are the images of the errors I get when i tried launching the Veeam Backup & Replication console.

The reason for this error was because my “SQL Server Evaluation period got expired”. This means, it exceeded the 180 days permitted. Also, I took a look at the log and found out that the Backup and Replication Server could not connect to the SQL Server as shown below.

[21.02.2022 21:59:45] <04> Info         [db] Connecting to SQL Server (CurrentUser=[TECHDIRECTARCHIChristian], ServerInstance=[MBAMSERV1MBAM], Options=[Direct])
[21.02.2022 21:59:45] <04> Info [db] Removing 'Initial Catalog' property from connection string
[21.02.2022 22:01:45] <04> Info [DB|ERROR] Failed to connect to server . (Microsoft.SqlServer.Management.Common.ConnectionFailureException)
[21.02.2022 22:01:45] <04> Info [DB|ERROR] at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
[21.02.2022 22:01:45] <04> Info [DB|ERROR] at Veeam.Backup.DBCreator.DatabaseConnector.Connect(DatabaseConnectorOptions options)
[21.02.2022 22:01:45] <04> Info [DB|ERROR] A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (System.Data.SqlClient.SqlException)

As you can see below, the error message from the Event Viewer with event ID 17051. Here is the link to my blogpost on how I resolved this issue.

To resolve this issues, I had to upgrade the SQL Server instance. here is a link to the complete blogpost.

  • Launch the Open the SQL Server Installation Center and click on the Maintenance link. You can also launch this by launching setup.exe on MS SQL server installation media as well

Upon clicking on the Installation Center, the following window will open up. Then click on the Maintenance Tab, and then on Edition Upgrade

This will open up the “upgrade the Edition for SQL Server” window as shown below,  

On the Product Key page, select ”Enter the product key,” and type the product key and click Next.

Accept the license terms and click Next.

Select the instance you want to upgrade. You can see the instance name and select that instance. In this case, MBAM instance, which pointed out with evaluation. Select the instance and click Next.

On the ”Ready to upgrade edition” page, please click upgrade.

The upgrade process will take a few minutes to complete. Once the upgrade is completed, you will get a complete status, “succeeded”

Next, let’s ensure we are able to start our services again. As you can see, the services are running again.

Note: If you stop at here without granting the Veeam Backup Service the right privilege, you will also not be able to start the services, and launch the VBR console. To fix this, you will need to grant the Veeam Backup Service local administrative rights. Here is a link on this blogpost.

Upon granting this Log On rights, I was able to start the Veeam Backup and Replication Console. 

Я написал службу Windows для работы на Win10, и она отлично работала, пока я не решил немного ее изменить. Я переписал некоторую логику, протестировал ее как в конфигурации Debug, так и в конфигурации Release, и все было в порядке. Затем я удалил текущую версию службы с помощью installutil.exe /u %servicename.exe% и заново установил ее с помощью installutil.exe %servicename.exe%.
По какой-то причине эта новая версия не запускается, и она вылетает с ошибкой 1064. Это полный текст ошибки:

Windows could not start %servicename% service on Local Computer. Error 1064: An exception occurred in the service when handling the control request.

В последний раз, когда я устанавливал эту службу, я столкнулся с некоторыми трудностями, но быстро исправил их, изменив свойства Log On. На этот раз это не работает. Пожалуйста, помогите с этой проблемой.

Спасибо.

Обновление 1

Вот мои методы обслуживания Main() и OnStart():

Main()

static void Main()
{
#if DEBUG
    var service = new SalesforceToJiraService();
    service.OnDebug();
    Thread.Sleep(Timeout.Infinite);
#else
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new SalesforceToJiraService()
    };
     ServiceBase.Run(ServicesToRun);
#endif
}

OnStart()

protected override void OnStart(string[] args)
{
    this.ConfigureServices();

    this.timer.Start();
    this.logger.Information("SalesforceToJira service started.");
}

Обновление 2

Больше кода:

ConfigureServices()

protected void ConfigureServices()
{
    this.configuration = ConfigurationHelper.LoadConfiguration(ConfigurationPath);
    this.logger = ConfigurationHelper.ConfigureLogger(this.configuration.Logs.LogsPath);

    this.timer = ConfigurationHelper.ConfigureTimer(this.configuration.ProcessInterval.TotalMilliseconds,
        (sender, eventArgs) => this.ProcessCasesAsync(sender, eventArgs).GetAwaiter().GetResult());

    this.salesforceClient = new SalesforceCliClient(this.configuration.Salesforce.CliPath);

    this.jiraClient = Jira.CreateRestClient(
        this.configuration.Jira.Url,
        this.configuration.Jira.Username,
        this.configuration.Jira.Password);
}

Я использую Newtonsoft.JSON для десериализации файла конфигурации JSON, Serilog для ведения журнала, System.Timers.Timer для периодических событий, AtlassianSDK для Jira API и некоторые оболочки над Salesforce CLI для Salesforce.


Ответы
8

У меня была такая же ошибка 1064 при запуске моей службы. Для меня пользователь, у которого была зарегистрирована служба, не был действительным пользователем в базе данных. После добавления он отлично работал.

Благодаря комментарию @Siderite Zackwehdex я смог найти полную трассировку стека основного исключения в EventViewer в разделе:

Windows LogsApplication

В моем случае моя служба называется «HttpDispatcher», которая отображается в столбце «Источник» на верхней панели.

Я сразу понял, что это произошло из-за проблемы с зависимостью, когда мой проект .NET 4.7.2 не работал с моими ссылками на .NET Standard. (Этот каштан).

Я столкнулся с той же проблемой. Причина в том, что я забыл правильно настроить соединение с базой данных в конфигурациях.

У меня также была такая же ошибка в моей службе Windows.
Причина в том, что он не может прочитать параметр конфигурации, поэтому он аварийно завершает работу.

Добавив некоторую проверку (исправление ошибок), Службы Windows могут запустить его правильно.

Я тоже столкнулся с этой проблемой. В моем случае это связано с ошибкой подключения к базе данных. Я думаю, это связано с тем, что код вызывает исключение.

Моя ошибка:
Windows не может запустить службу service1 на локальном компьютере.

Ошибка 1064: исключение в службе при обработке запроса управления

Я исправил свою проблему, обновив стороннюю DLL.

Я столкнулся с той же проблемой, вот как я решил ее после устранения неполадок.

  • Если вы запускаете службу на сервере с несколькими пользователями, сделайте
    обязательно запустите службу от имени администратора. Нажмите на услугу
    properties, а затем на вкладке «Вход в систему» ​​щелкните эту учетную запись и укажите
    имя пользователя и пароль администратора.

  • И если ваша служба обращается к какому-то общему диску, убедитесь, что
    у вас есть общий пользователь на всех серверах для доступа к общему
    диски и добавить пользователя в качестве локального администратора.

В моем случае ошибка возникла из-за проблем с именем журнала событий

Это было исправлено после того, как я перешел на RegEdit и удалил старое имя службы из HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices.

Для меня это произошло, когда я попытался перезапустить процесс. Оказалось, что процесс зависал в «Остановке», поэтому мне пришлось убить его вручную через командную строку и PID.

Другие вопросы по теме

Понравилась статья? Поделить с друзьями:
  • Ошибка 1064 ошибка службы при обработке команды как исправить
  • Ошибка 1064 sql как исправить
  • Ошибка 1064 mysql как исправить
  • Ошибка 1063 радмин впн
  • Ошибка 1062 служба не запущена