Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
The code below works perfect when started directly. (double click on exe file)
When it is used as a service, it seems to be impossible to connect to a database.
What can be the solution for this problem?
Thanks in advance!
C++
// Notes:
// 1. Project setting: Configuration Properties -> Advanced -> Use of MFC => Set to: "Use MFC in Shared DLL"
// 2. This program assumes there is an ODBC database with name = "TEST", user id = "dba", password = "sql"
// 3. Info and working example about services: https://www.codeproject.com/Articles/499465/Simple-Windows-Service-in-Cplusplus
#include <iostream>
#include <fstream>
#include <afxdb.h>
using namespace std;

int main()
{
    ofstream logFile;
    logFile.open("C:\\Temp\\Logfile1.txt"); logFile << "This code is executed"; logFile.close();

    CDatabase ioDB;
    // The next line is the problem when used as a service.
    ioDB.Open(_T("TEST"), FALSE, FALSE, _T("ODBC;uid=dba;pwd=sql;dbn=TEST"), FALSE);
    
    // The next line will be executed when the program is directly executed.
    // The next line will NOT be executed when the program is executed as service.
    logFile.open("C:\\Temp\\Logfile2.txt"); logFile << "This code is never executed!"; logFile.close();

    // ... completely working service, but this code is never reached ...
}


What I have tried:

Using an account with administrator permissions (to start the service) does not solve the problem.
I tested with an "SQL Anywhere 16" database on "Windows 10" and on "Windows Server 2012 R2".
Posted
Updated 29-Jan-21 21:15pm

One possible reason is that the DSN you have used (TEST) is defined only for the user (you), not as system DSN. So if you're running the service under different user account, it cannot see the DSN.

In ODBC admin tool, try defining the data source as System DSN.
 
Share this answer
 
Quote:
One possible reason is that the DSN you have used (TEST) is defined only for the user (you), not as system DSN. So if you're running the service under different user account, it cannot see the DSN.

Great suggestion, but in my case ("SQL Anywhere 16" database) it didn’t solve the problem. A lot of trying all kind of things did not solve the problem.

So, I come with 3 work around solutions:
1. The combination "C#", "service", "SQL Anywhere 16" database gives no problem. (Tested)
2. Probably using another DB (e.g. SQL Server, ...) will solve the problem. (Not tested)
3. Forget services, and use “Task Scheduler” (see Windows Administrative Tools). It works simple and perfect for normal exe files! (Tested on "Windows Server 2019 Standard")
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900