Ошибка 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 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.

Помогаю со студенческими работами здесь

Ошибка 1064 при создании базы
Создана модель базы в workbench. При создании базы из модели выходит ошибка

Executing SQL script…

Ошибка 1064 при создании триггера
Всем привет. Помогите исправить ошибку, возникающей при создании триггера в phpMyAdmin

Ошибка 1064 при импорте базы
Собственно сабж.
Вот ошибка:
SQL-запрос:

CREATE TABLE Клиент_6(

ФИО VARCHAR( ) NULL ,…

Ошибка 1064 при создании таблицы в phpmyadmin
Выдает ошибку 1064 при нажатии на кнопку "Сохранить"

вот sql написанный самим сервисом
CREATE…

Ошибка #1064 при переносе с другого хостинга
Здравствуйте.
Захотел перенести сайт на другой хостинг. Изначально был 100ms.ru, переносил на…

Ошибка 1064 при выполнении запроса на update с select
Есть две таблицы: actual_general и reg_smsp
Обе таблицы содержат поля INN, а также поле "А" в…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

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.

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. 

3 / 3 / 1

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

Сообщений: 155

1

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


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

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

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

0

3 / 3 / 1

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

Сообщений: 155

04.04.2021, 14:36

 [ТС]

2

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

Миниатюры

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

0

2715 / 2026 / 374

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

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

04.04.2021, 14:58

3

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

0

ДЛ имончик

3 / 3 / 1

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

Сообщений: 155

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,671

04.04.2021, 20:42

5

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

0

ДЛ имончик

3 / 3 / 1

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

Сообщений: 155

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

Hi,

I’m running into a little behavior that I cannot explain. I’ve build a C# Service that watches the Security EventLog for specific events and generates a little report based on them. 

The application runs on a Windows 2008 R2 Standard Server with .NET 4.8 installed. The target framework is .NET 4.7.2 and the service runs as Local System. 

So far the application works like a charm but… in the wrong folder and I seem unable to change it. The default folder is «C:WindowsSysWow64», normal for a 32-bits service. But I’d like to point it to another folder «C:TestAppsEventLogGuard»
as a working directory. 

I’ve tried to change the working directory or path it writes files to in two ways (both resulting in the same error):

1. By changing the working directory

string path = @"C:TestAppsEventLogGuard";
Directory.SetCurrentDirectory(path);

2. By changing the path I’m writing to in a streamwriter to:

string fileName = @"C:TestAppsEventLogGuardIPList.txt"; string fileLog = @"C:TestAppsEventLogGuardEventLogGuard.log";

using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{

~~~~~~

}

As soon as either option is added I’m getting an error 1064 on-start. In the Windows EventLog I can see the following error displayed:

Problem signature:
P1: EventLogGuardSVC.exe
P2: 1.0.0.0
P3: f8080359
P4: mscorlib
P5: 4.8.3761.0
P6: 5c9c6e98
P7: 168e
P8: fc
P9: System.IO.DirectoryNotFound
P10: 

Does anyone have an idea what may be causing this behavior or experienced something similar? 

Edit: The directory exists and I do have a check added if the path exists as well, makes no difference.

  • Edited by

    Friday, October 25, 2019 8:44 AM

Hi,

I’m running into a little behavior that I cannot explain. I’ve build a C# Service that watches the Security EventLog for specific events and generates a little report based on them. 

The application runs on a Windows 2008 R2 Standard Server with .NET 4.8 installed. The target framework is .NET 4.7.2 and the service runs as Local System. 

So far the application works like a charm but… in the wrong folder and I seem unable to change it. The default folder is «C:WindowsSysWow64», normal for a 32-bits service. But I’d like to point it to another folder «C:TestAppsEventLogGuard»
as a working directory. 

I’ve tried to change the working directory or path it writes files to in two ways (both resulting in the same error):

1. By changing the working directory

string path = @"C:TestAppsEventLogGuard";
Directory.SetCurrentDirectory(path);

2. By changing the path I’m writing to in a streamwriter to:

string fileName = @"C:TestAppsEventLogGuardIPList.txt"; string fileLog = @"C:TestAppsEventLogGuardEventLogGuard.log";

using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{

~~~~~~

}

As soon as either option is added I’m getting an error 1064 on-start. In the Windows EventLog I can see the following error displayed:

Problem signature:
P1: EventLogGuardSVC.exe
P2: 1.0.0.0
P3: f8080359
P4: mscorlib
P5: 4.8.3761.0
P6: 5c9c6e98
P7: 168e
P8: fc
P9: System.IO.DirectoryNotFound
P10: 

Does anyone have an idea what may be causing this behavior or experienced something similar? 

Edit: The directory exists and I do have a check added if the path exists as well, makes no difference.

  • Edited by

    Friday, October 25, 2019 8:44 AM

Я написал службу 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.

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

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. 

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.

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. 

I have a problem with Running the Windows Service. Service is connecting DB and through DataAdapter it creates local XML file. Then it transfer the file to the FTP server.
Get error 1064 when trying to start the service.

I checked and the error occurs when trying to create XML file from DB. I guese it’s DB connection but don’t know how to fix it.

When i run this code as Console app it works pretty well, no errors occures, but when i run it as windows service it is occuring :/ Maybe it is something with Connection string? or with Creating XML file throught DataAdapter? What’s the difference here between Console App and windows service Connection to DB?

To check it, I commented out the part with connection to DB (CreateXML() method) and it works too, so FTP connection is not an issue.

I marked with comment the line of code which throw an error, it’s located in the CreateXML() Method.

You have full code here

EDIT (solution):
If you have the same problem change Service to use your win account. Works without errors now.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Timers;

namespace XMLShopService
{
    public partial class XMLShopService : ServiceBase
    {
        Timer timer = new Timer();

        //TIME MULTIPLIERS 
        private static int seconds = 1000;          //miliseconds to SECONDS multiplier -- DON'T TOUCH --
        private static int minutes = 60000;         //miliseconds to MINUTES multiplier -- DON'T TOUCH --
        private static int hours = 3600000;         //miliseconds to HOURS multiplier -- DON'T TOUCH --

        //TIME INTERVAL SETTINGS
        private int timeInterval = 3;              //SET HERE - time interval in (SECONDS or MINUTES or HOURS), then pick timeMultiplier below
        private int timeMultiplier = minutes;       //SET HERE - time format you would like to use in timer as interval (SECONDS or MINUTES or HOURS) pick one from above and implement after "="

        public XMLShopService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Debugger.Launch();

            WriteToFile("START : " + DateTime.Now);

            CreateXML();
            FtpFileUpload();

            //TIMER
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            timer.Interval = timeInterval * timeMultiplier;             // -- DON'T TOUCH -- Represent time interval in MILISECONDS  
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
           WriteToFile("STOP : " + DateTime.Now);
        }




        //FUNCTIONS USED
        private void OnTimedEvent(object sender, ElapsedEventArgs e)
        {
            WriteToFile("ReStart script at : " + DateTime.Now);

            CreateXML();
            FtpFileUpload();

            WriteToFile("Script finished at : " + DateTime.Now);

        }





        private void CreateXML()
        {
            //XML file settings
            string fileName = "file.xml";                                           //SET HERE - XML local file name
            string localFilePath = @"path" + fileName;                //SET HERE - XML local file path (full) 
            double priceMultiplier = 3;                                             //SET HERE - price multiplier

            //SQL Query - products codes & prices * multiplier
            string queryString = "SELECT ItemCode, Price * " + priceMultiplier + " FROM database WHERE PriceList = 1 AND Price > 0";

            //SQL connection string
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = @"Server=server;" +            //SET HERE - SQL Server
                                     "Initial Catalog=database;" +           //SET HERE - Server database
                                     "Integrated Security=true";

            //Creating XML file in the specific location, overwriting old file
            try
            {
                using (SqlCommand sqlComm = new SqlCommand(queryString, conn) { CommandType = CommandType.Text })
                {
                    WriteToFile("SQL 1: " + DateTime.Now);

                    SqlDataAdapter da = new SqlDataAdapter(sqlComm);
                    WriteToFile("SQL 2: " + DateTime.Now);

                    DataSet ds = new DataSet();
                    da.Fill(ds);                              //!!!---THIS IS WHERE ERROR OCCURS---!!!
                    WriteToFile("SQL 3: " + DateTime.Now);

                    ds.Tables[0].WriteXml(localFilePath);     
                    WriteToFile("SQL 4: " + DateTime.Now);
                }
                WriteToFile("DB connection ok: " + DateTime.Now);
            }
            catch (Exception)
            {
                WriteToFile("ERROR - create file: " + DateTime.Now);
                throw;
            }

        }

        private void FtpFileUpload()
        {
            string ftpUsername = "userName";                                                //SET HERE - FTP username
            string ftpPassword = "pass";                                                           //SET HERE - FTP Password

            string ftpFolderPath = @"ftpServerPath/test/";          //SET HERE - FTP folder dir   -- TODO: TEST FOLDER PATH TO CHANGE --
            string fileName = "file.xml";                                                               //SET HERE - XML local file name
            string localFilePath = @"path" + fileName;                                    //SET HERE - XML local file dir (full)


            //DELETE old file
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFolderPath + fileName);
                request.Method = WebRequestMethods.Ftp.DeleteFile;
                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    WriteToFile(response.StatusDescription + " " + DateTime.Now);
                }
            }

            //Throw on errors
            catch (Exception)
            {
                WriteToFile("ERROR - delete old file: " + DateTime.Now);
                throw;
            }


            //UPLOAD UpToDate file
            try
            {
                //Set request
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFolderPath + fileName);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = true;

                //Load file
                FileStream stream = File.OpenRead(localFilePath);
                byte[] buffer = new byte[stream.Length];

                stream.Read(buffer, 0, buffer.Length);
                stream.Close();

                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();

                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    WriteToFile(response.StatusDescription + " " + DateTime.Now);
                }
                request = null;
            }

            //Throw on errors
            catch (Exception)
            {
                WriteToFile("ERROR - upload UpToDate file: " + DateTime.Now);
                throw;
            }
        }


        //SCRIPT LOGS
        public void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "LogsServiceLog.txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}

Hi,

I’m running into a little behavior that I cannot explain. I’ve build a C# Service that watches the Security EventLog for specific events and generates a little report based on them. 

The application runs on a Windows 2008 R2 Standard Server with .NET 4.8 installed. The target framework is .NET 4.7.2 and the service runs as Local System. 

So far the application works like a charm but… in the wrong folder and I seem unable to change it. The default folder is «C:WindowsSysWow64», normal for a 32-bits service. But I’d like to point it to another folder «C:TestAppsEventLogGuard»
as a working directory. 

I’ve tried to change the working directory or path it writes files to in two ways (both resulting in the same error):

1. By changing the working directory

string path = @"C:TestAppsEventLogGuard";
Directory.SetCurrentDirectory(path);

2. By changing the path I’m writing to in a streamwriter to:

string fileName = @"C:TestAppsEventLogGuardIPList.txt"; string fileLog = @"C:TestAppsEventLogGuardEventLogGuard.log";

using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{

~~~~~~

}

As soon as either option is added I’m getting an error 1064 on-start. In the Windows EventLog I can see the following error displayed:

Problem signature:
P1: EventLogGuardSVC.exe
P2: 1.0.0.0
P3: f8080359
P4: mscorlib
P5: 4.8.3761.0
P6: 5c9c6e98
P7: 168e
P8: fc
P9: System.IO.DirectoryNotFound
P10: 

Does anyone have an idea what may be causing this behavior or experienced something similar? 

Edit: The directory exists and I do have a check added if the path exists as well, makes no difference.

  • Edited by

    Friday, October 25, 2019 8:44 AM

Помогаю со студенческими работами здесь

Ошибка 1064 при создании базы
Создана модель базы в workbench. При создании базы из модели выходит ошибка

Executing SQL script…

Ошибка 1064 при создании триггера
Всем привет. Помогите исправить ошибку, возникающей при создании триггера в phpMyAdmin

Ошибка 1064 при импорте базы
Собственно сабж.
Вот ошибка:
SQL-запрос:

CREATE TABLE Клиент_6(

ФИО VARCHAR( ) NULL ,…

Ошибка 1064 при создании таблицы в phpmyadmin
Выдает ошибку 1064 при нажатии на кнопку &quot;Сохранить&quot;

вот sql написанный самим сервисом
CREATE…

Ошибка #1064 при переносе с другого хостинга
Здравствуйте.
Захотел перенести сайт на другой хостинг. Изначально был 100ms.ru, переносил на…

Ошибка 1064 при выполнении запроса на update с select
Есть две таблицы: actual_general и reg_smsp
Обе таблицы содержат поля INN, а также поле &quot;А&quot; в…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

If you’ve been using WordPress for a while, you may have decided to get into more advanced database management. This often involves using the MySQL command line, which can, in turn, lead to confusing problems such as MySQL 1064 errors.

Fortunately, while resolving this error can be confusing at first due to its many potential causes, its solutions tend to be relatively simple. Once you determine the reason behind the database error you’re seeing, you should be able to fix it fairly quickly.

In this post, we’ll cover the various possible causes of the MySQL 1064 error. Then we’ll share solutions for each common situation, to help you get your database and your site back up and running.

Let’s get started!

Why the MySQL 1064 Error Occurs

The MySQL 1064 error is a syntax error. This means the reason there’s a problem is because MySQL doesn’t understand what you’re asking it to do. However, there are many different situations that can lead to this type of miscommunication between you and your database.

The simplest cause is that you’ve made a mistake while typing in a command and MySQL can’t understand your request. Alternatively, you may be attempting to use outdated or even obsolete commands that can’t be read.

In other cases, you may have attempted to include a ‘reserved word’ in one of your commands. Reserved words are terms that can only be used in specific contexts in MySQL. If you attempt to use them in other ways, you’ll be faced with an error.

It’s also possible that there is some data missing from your database. When you make a request via MySQL which references data that isn’t where it’s supposed to be, you’ll also see the 1064 error. Finally, transferring your WordPress database to another server can also lead to the same issue.

As you can see, there are many potential causes for this problem, which can make it tricky to resolve. Unless you’re in the process of moving your database or taking some other action that points to a specific cause, you’ll likely need to try a few different solutions before you land on the right one. Fortunately, none of them are too difficult to execute, as we’ll see next.

Oh no, you’re getting the MySQL 1064 Error…😭 Don’t despair! Here are 5 proven solutions to get it fixed immediately 🙏Click to Tweet

How to Fix the MySQL 1064 Error (5 Methods)

If you already have an idea of what’s causing your MySQL 1064 error, you can simply skip down to the resolution for your specific situation. However, if you’re not sure why the error has occurred, the simplest strategy is to try the easiest solution first.

In that case, we’d suggest testing out the five most likely fixes in the following order.

1. Correct Mistyped Commands

The good thing about MySQL typos is that they’re the simplest explanation for syntax issues such as the 1064 error. Unfortunately, they can also be the most tedious to correct. Generally speaking, your best option is to manually proofread your code and look for any mistakes you may have made.

We suggest using the MySQL Manual as a reference while you do so, double-checking anything you’re not sure about. As you might imagine, this can get pretty time-consuming, especially if you’ve been working in the MySQL command line for a while or if you’re new to this task.

An alternative to manually checking your work is to employ a tool such as EverSQL:

MySQL 1064 Error: EverSQL syntax checker

EverSQL syntax checker

With this solution, you can simply input your MySQL to check for errors automatically. However, keep in mind that these platforms aren’t always perfect and you may still want to validate the results yourself.

2. Replace Obsolete Commands

As platforms grow and change, some commands that were useful in the past are replaced by more efficient ones. MySQL is no exception. If you’re working on your database following a recent update or have referenced an outdated source during your work, it’s possible that one or more of your commands are no longer valid.

You can check to see whether this is the case using the MySQL Reference Manual. You’ll find mentions of commands that have been made obsolete by each MySQL version in the relevant sections:

MySQL 1064 Error: Manually removing obsolete commands

Manually removing obsolete commands

Once you’ve determined which command is likely causing the problem, you can simply use the ‘find and replace’ function to remove the obsolete command and add in the new version. For example, if you were using storage_engine and find that it no longer works, you could simply replace all instances with the new default_storage_engine command.

3. Designate Reserved Words

In MySQL, using a reserved word out of context will result in a syntax error, as it will be interpreted as incorrect. However, you can still use reserved words however you please by containing them within backticks, like this: `select`

Each version of MySQL has its own reserved words, which you can read up on in the MySQL Reference Manual. A quick find and replace should enable you to resolve this issue if you think it may be causing your 1064 error.

4. Add Missing Data

If your latest MySQL query attempts to reference information in a database and can’t find it, you’re obviously going to run into problems. In the event that none of the preceding solutions resolves your MySQL 1064 error, it may be time to go looking for missing data.

Unfortunately, this is another solution that can be quite tedious and has to be done by hand. The best thing you can do in this situation is to work backward, starting with your most recent query. Check each database it references, and make sure all the correct information is present. Then move on to the next most recent query, until you come to the one that’s missing some data.

5. Use Compatibility Mode to Transfer WordPress Databases

This final 1064 error solution isn’t as straightforward as the others on our list. However, if you’re migrating your WordPress site to a new host or otherwise moving it to a different server, you’ll need to take extra steps to avoid causing problems with your database.

The simplest solution is to use a migration plugin that includes a compatibility mode, such as WP Migrate DB:

WP Migrate DB WordPress plugin

WP Migrate DB WordPress plugin

This will enable an auto-detection feature that will make sure your latest site backup and database are compatible with multiple versions of MySQL. You can access the compatibility mode setting by navigating to Tools > Migrate DB > Advanced Options:

WP Migrate DB settings

WP Migrate DB settings

Check the box next to Compatible with older versions of MySQL before starting your site migration. This way, you should be able to avoid any issues during the process.

Summary

Database errors can throw a wrench in your plans, and may even compromise your website’s stability. Knowing how to resolve issues such as the MySQL 1064 error can help you react quickly, and minimize downtime on your site.

There are five methods you can try to fix the MySQL 1064 error when you encounter it, depending on its most likely cause:

  1. Correct mistyped commands.
  2. Replace obsolete commands.
  3. Designate reserved words.
  4. Add missing data.
  5. Transfer WordPress databases in compatibility mode.

Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Get started with a free trial of our Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Понравилась статья? Поделить с друзьями:
  • Ошибка 1064 mysql при создании таблицы
  • Ошибка 1064 mysql workbench как исправить
  • Ошибка 1064 mariadb
  • Ошибка 10635 тигуан
  • Ошибка 1063 туарег