Quantcast
Channel: Visual C forum
Viewing all 15302 articles
Browse latest View live

return after a CreateWindow throw an exception in the Winmain

$
0
0

Hello

Here is the beginning of the code in my winmain:

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: placez ici le code.

    // Initialise les chaînes globales
	WNDCLASSEXW wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wcex.lpfnWndProc = WndProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LUTHERIE));
	wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_LUTHERIE);
	wcex.lpszClassName = L"maclasse";
	wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	if (!RegisterClassExW(&wcex))
	{
		wchar_t err[256];
		memset(err, 0, 256);
		FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err, 255, NULL);
		MessageBoxW(NULL,err,(LPCWSTR)L"Erreur",	MB_OK);
		return -1;
	}
    // Effectue l'initialisation de l'application :
	hInst = hInstance; // Stocke le handle d'instance dans la variable globale
	hWindow = CreateWindowW(L"maclasse", L"Lignes de niveaux", WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

	if (!hWindow)
	{
		return FALSE;
	}
	return 0;
...
}

If I put the "return 0;" before CreateWindow (and leave the program, so) everything seems OK, but if I do like written in the code above, it throws a 0xC0000005 exception reading 0x00000000 with Kernel32.dll

Any idea, please

Thanks

Cathy L.


CreateProcess problems

$
0
0

I am having a couple of problems trying to run CreateProcess.   First problem, I created a test program in Visual Studio 2010 and it worked fine.  The expected type of the second parameter is LPWSTR.  Then I added a call to CreateProcess to a program that was converted from VC 6.0 to VS 2010.  In that converted program the expected type of the second parameter is LPSTR.  Why would the types be different between a converted VS 2010 program and one created with VS 2010?

The second problem I'm having is that I convert a CString to LPSTR for the second parameter.  When I look at the converted CString in the debugger, the LPSTR variable looks fine.  However, when I pass it to CreateProcess, the string gets truncated at the first space, and of course CreateProcess fails.  When I pass an LPWSTR to CreateProcess in my test program, the string doesn't get truncated at the first space, all spaces are preserved.

So I need to figure out either how to have a CreateProcess in my converted program that takes an LPWSTR parameter as the second parameter or how to create an LPSTR parameter with spaces that get preserved when calling CreateProcess.


genush

0x80010108 - RPC_E_DISCONNECTED

$
0
0

We are developing software for a machine, which has one main controller running windows server 2003, and 20 dedicated controllers running WES 2009. Communication is done using DCOM. We are currently upgrading the main controller to windows server 2012. The software runs fine for a few hours, but sometimes a DCOM call fails with HRESULT 0x80010108:

"The object invoked has disconnected from its clients"

This is not always to a call to the same object; multiple calls to multiple DCOM objects result in this error. The exact same software is running correctly on windows server 2003.

Is there a change in WS 2012 which may cause this problem? Any suggestions or hints at what the problem may be or how to find it?

Regards,

Simon

Issues when Integrating SQL API++ with Visual Studio 2008, when trying to make Database Connection from C++ Program to SQL Server 2005

$
0
0
Getting the following Error messages, when i build this code against SQL Server2005 using Windows Authentication.
1>------ Rebuild All started: Project: DALSASQLTest, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'DALSASQLTest', configuration 'Debug|Win32'
1>Compiling...
1>SQLTest.cpp
1>Linking...
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall SAConnection::~SAConnection(void)" (??1SAConnection@@UAE@XZ) referenced in function __catch$_main$0
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: __thiscall SAString::operator char const *(void)const " (??BSAString@@QBEPBDXZ) referenced in function __catch$_main$0
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: class SAString __thiscall SAException::ErrText(void)const " (?ErrText@SAException@@QBE?AVSAString@@XZ) referenced in function __catch$_main$0
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall SAConnection::Rollback(void)" (?Rollback@SAConnection@@QAEXXZ) referenced in function __catch$_main$0
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall SAConnection::Disconnect(void)" (?Disconnect@SAConnection@@QAEXXZ) referenced in function _main
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: __thiscall SAString::~SAString(void)" (??1SAString@@QAE@XZ) referenced in function _main
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall SAConnection::Connect(class SAString const &,class SAString const &,class SAString const &,enum SAClient_t,void (__cdecl*)(class SAConnection &,enum SAConnectionHandlerType_t))" (?Connect@SAConnection@@QAEXABVSAString@@00W4SAClient_t@@P6AXAAV1@W4SAConnectionHandlerType_t@@@Z@Z) referenced in function _main
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: __thiscall SAString::SAString(char const *)" (??0SAString@@QAE@PBD@Z) referenced in function _main
1>SQLTest.obj : error LNK2019: unresolved external symbol "public: __thiscall SAConnection::SAConnection(void)" (??0SAConnection@@QAE@XZ) referenced in function _main
1>MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup
1>C:\Users\aravind\Documents\Visual Studio 2008\Projects\DALSASQLTest\Debug\DALSASQLTest.exe : fatal error LNK1120: 10 unresolved externals
1>Build log was saved at "file://c:\Users\aravind\Documents\Visual Studio 2008\Projects\DALSASQLTest\DALSASQLTest\Debug\BuildLog.htm"
1>DALSASQLTest - 11 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
<br/>
Code is below:
#include <stdio.h> 
#include <SQLAPI.h> // main SQLAPI++ headerint main(int argc, char* argv[])
{
  SAConnection con; // create connection objecttry
  {// connect to database// in this example it is SQL Server,// but can also be Sybase, Informix, DB2
    con.Connect("Patient", // database name"",  // user name"",  // password
      SA_SQLServer_Client);

    printf("We are connected!\n");// Disconnect is optional// autodisconnect will ocur in destructor if needed
    con.Disconnect();

    printf("We are disconnected!\n");
  }catch(SAException &x)
  {// SAConnection::Rollback()// can also throw an exception// (if a network error for example),// we will be readytry
    {// on error rollback changes
      con.Rollback();
    }catch(SAException &)
    {
    }// print error message
    printf("%s\n", (constchar*)x.ErrText());
  }return 0;
}

why does the preprocessor identifies the enum values with Borland C++ but not with visual C++?

$
0
0

I am trying to migrate a project from Borland C++ to Visual C++

I noticed a difference in treating enum as explained by this example

File : Test_enum.cpp

#ifdef  _MSC_VER
        #include <iostream>
    #else
        #include <iostream.h>
    #endif
    #include <conio.h>

    using namespace std;

    enum {

        ENUM_0 =0,
        ENUM_1,
        ENUM_2,
        ENUM_3
        } ;

     int main(int argc, char* argv[])
    {
        #ifdef  _MSC_VER
        cout << "Microsoft Visual compiler detected!" << endl;
        #elif defined(__BORLANDC__)
        cout << "Borland compiler detected!" << endl;
        #elif
        cout << "Other compiler detected!" << endl;
        #endif
        #if ENUM_1 > 0
        cout << "ENUM_1 is well defined at preprocessing time" << endl;
        #else
        cout << "No way to see enum variables at preprocessing time" << endl;
        #endif
        cout << "Type any character to exit..." << endl;

        #ifdef  _MSC_VER
            _getch();
        #else
            getch();
        #endif

        return 0;
    }

Runing the code in visual studio gives this output :

Microsoft Visual compiler detected!
No way to see enum variables at preprocessing time
Type any character to exit...

And by using Borland, i get :

Borland Compiler detected!
ENUM_1 is well defined at preprocessing time
Type any character to exit...

I want to know how Borland is able to recognize the enum ? Is it possible to do the same in visual?


C4005 APIENTRY Makro Neudefinition in minwindef.h and thus 2 unknown identifier

$
0
0

Hello, I'm working on VS2019, x64 Windows (SUBSYSTEM:WINDOWS). The compiler told me that a warning C4005 :APIENTRY Makro Neudefinition in minwindef.h was caused, and then C3861 2 identifiers (gluPerspective and gluLookAt) were thus caused bv the first warning(I saw the definition in glfw.h and glu.h, the both functions are declared like this syntax: #define APIENTRY gluPerspective(xxx,xxx,xxx,xxx) ,So i think it is related to the definition of APIENTRY) 

Should I change the source files ? What should i add or delete?

Looking forward your answer!

While trying to launch a process with credentials of the interactive user, GetTokenInformation returns error code 1312 on windows 10 even if UAC is turned on to the maximum

$
0
0

I am trying to launch a process from a windows service [running under local system account] with credentials of the interactive user but administrator privileges. This works if I start the PC and log in to an adminstrator user. However, it fails on normal users, as described below.

On some previous installations of Windows 10, I had faced the problem While trying to launch a process with credentials of the interactive user, GetTokenInformation returns error code 1312 on Windows 7 and some installations of windows 10 if UAC is turned off. I got the solution to that in https://social.msdn.microsoft.com/Forums/en-US/116f7616-b89f-4e6d-b41f-b6e5f79f2e16/while-trying-to-launch-a-process-with-credentials-of-the-interactive-user-gettokeninformation?forum=vcgeneral

I dont remember whether I tried the above solution with a non-administrator user. But at present,

I am facing a similar problem with a non-adminstrator user, in which GetTokenInformation fails with error 1312.

The code and log output are below.

The method GetTokenForProcessId fails on GetTokenInformation with error 1312, and SetTokenInformation fails with error 1375

GetProcessIdByNameAndSessionId

Method: LaunchProcessElevated

Process Name: ProcessMonitor-X64.exe
Explorer ProcessId: 10724
Winlogon ProcessId: 1820

Method:  GetTokenForProcessId

GetTokenForProcessId::10724
OpenProcess reurned Handle:464
OpenProcessToken reurned Handle:468
Token Inf Length:44
Failed to Get Primary Token:1312 
Explorer hTokenDst: 468

Method:  GetTokenForProcessId

GetTokenForProcessId::1820
OpenProcess reurned Handle:472
OpenProcessToken reurned Handle:476
Token Inf Length:28
Failed to Get Primary Token:1312
Winlogn hTokenSrc: 476

Method:  CopyPrivileges

CopyPrivileges: Original Tokens:476:468
GetImpersonationToken reurned Handle:476
DuplicateToken reurned Handle:480
GetImpersonationToken reurned Handle:468
DuplicateToken reurned Handle:484


CopyPrivileges: Impersonated Tokens:480:484
GetTokenPrivileges Buffer size:256
Privilege Count:5
Adjust Privileges Succeeded
SetTokenInformation succeded
Failed to SetTokenInformation:Error: 1375

Method:  CreateProcessWithToken

Failed to start Process Monitor Process

STDMETHODIMP CProcessManager::LaunchProcessElevated(BSTR commandLine, DWORD* dwProcessId)
{
	logger->ClearLog();
	ZeroMemory(buffer, sizeof(buffer));


	CComBSTR temp(commandLine);
	LPWSTR lpszProcessName = temp.operator LPWSTR();
	Report(L"Process Name: %s", (LPCWSTR)lpszProcessName);
	DWORD dwSessionId = WTSGetActiveConsoleSessionId();
	DWORD dwProcessIdExplorer = GetProcessIdByNameAndSessionId(L"explorer.exe", dwSessionId);
	Report(L"Explorer ProcessId: %d", dwProcessIdExplorer);
	DWORD dwProcessIdWinLogon= GetProcessIdByNameAndSessionId(L"winlogon.exe", dwSessionId);
	Report(L"Winlogon ProcessId: %d", dwProcessIdWinLogon);

	HANDLE hTokenDst = GetTokenForProcessId(dwProcessIdExplorer);
	Report(L"Explorer hTokenDst: %d", hTokenDst);
	HANDLE hTokenSrc = GetTokenForProcessId(dwProcessIdWinLogon);
	Report(L"Winlogn hTokenSrc: %d", hTokenSrc);
	if (CopyPrivileges(hTokenSrc, hTokenDst)) {



		if (!SetTokenInformation(hTokenDst, TokenSessionId, &dwSessionId, sizeof(dwSessionId)))
		{
			Report(L"Failed to SetTokenInformation:Error: %d", GetLastError());
			return S_FALSE;

		}

		//Report(lpszProcessName);
		DWORD dwProcessIdNew = 0;
		if (CreateProcessWithToken(hTokenDst, lpszProcessName, (DWORD*)& dwProcessIdNew))
		{
			*dwProcessId = dwProcessIdNew;
			return S_OK;
		}
		else 
		{
			Report(L"Failed to CreateProcessWithToken: Error: %d", GetLastError());
			return S_FALSE;
		}

		
	}
	else 
	{
		Report(L"Failed to Copy Privileges:Error: %d", GetLastError());
		return S_FALSE;
	}
}
HANDLE CProcessManager::GetTokenForProcessId(UINT dwProcessId)
{
	ZeroMemory(buffer, sizeof(buffer));
	_ltow_s(dwProcessId, buffer, len, 10);
	Report(L"GetTokenForProcessId::%d", dwProcessId);
	HANDLE hProcess = 0;
	HANDLE hToken = 0;
	hProcess = OpenProcess(MAXIMUM_ALLOWED, 0, dwProcessId);
	if (hProcess == NULL) {
		Report(L"OpenProcess Returned Null: %d", GetLastError());
	}
	ZeroMemory(buffer, sizeof(buffer));
	_ltow_s((long)hProcess, buffer, len, 10);
	Report(L"OpenProcess reurned Handle:%s", buffer);
	// obtain a handle to the access token of the winlogon process
	if (!OpenProcessToken(hProcess, TOKEN_ALL_ACCESS | TOKEN_READ | TOKEN_WRITE | TOKEN_EXECUTE, &hToken))
	{
		ZeroMemory(buffer, sizeof(buffer));
		Report(L"OpenProcesToken Returned Null: %d", GetLastError());
		CloseHandle(hProcess);

		return 0;
	}
	ZeroMemory(buffer, sizeof(buffer));
	Report(L"OpenProcessToken reurned Handle:%d", hToken);
	DWORD TokenInfLength = 0;

	//-http://www.microsoft-questions.com/microsoft/Platform-SDK-Security/35984508/how-to-run-a-process-with-elevated-privileges-run-as-administrat.aspx
	// first call gets lenght of TokenInformation
	GetTokenInformation(hToken, TokenUser, 0, TokenInfLength, &TokenInfLength);
	Report(L"Token Inf Length:%d", TokenInfLength);

	HANDLE* TokenInformation = (HANDLE*)LocalAlloc(LMEM_ZEROINIT, TokenInfLength);
	TokenInfLength = sizeof(HANDLE);


	if (!GetTokenInformation(hToken, TokenLinkedToken, TokenInformation, TokenInfLength, &TokenInfLength))
	{
		DWORD err = GetLastError();Report(L"Failed to Get Primary Token:%d", err);
		return hToken;
	}
	else {
		HANDLE hPrimaryToken = *TokenInformation;
		Report(L"Primary Token:%d", hPrimaryToken);
		return hPrimaryToken;
	}
	return NULL;
}
DWORD GetProcessIdByNameAndSessionId(LPCWSTR lpszProcessName, DWORD sessionId)
{
	//LaunchDebugger();
	wchar_t* p = 0;
	wchar_t* q = 0;
	wchar_t* ProcessNameW = (wchar_t*)lpszProcessName;
	DWORD processId = 0;
	wchar_t lowerCaseInputProcess[512];
	ZeroMemory(lowerCaseInputProcess, sizeof(lowerCaseInputProcess));
	//Convert InputProcess to lower case
	p = ProcessNameW;
	q = lowerCaseInputProcess;

	for (; *p; ++p, ++q) * q = tolower(*p);

	//wprintf(L"Target:%s\n", lowerCaseInputProcess);


	NTSTATUS status;
	PVOID buffer;
	PSYSTEM_PROCESS_INFO spi;

	buffer = VirtualAlloc(NULL, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // We need to allocate a large buffer because the process list can be large.

	if (!buffer)
	{
	//	Report(L"\nError: Unable to allocate memory for process list: %d\n", GetLastError());
		return -1;
	}

	//Report(L"\nProcess list allocated at address %#x\n", buffer);
	spi = (PSYSTEM_PROCESS_INFO)buffer;

	if (!NT_SUCCESS(status = NtQuerySystemInformation(SystemProcessInformation, spi, 1024 * 1024, NULL)))
	{
		//Report(L"\nError: Unable to query process list (%#x)\n", status);

		VirtualFree(buffer, 0, MEM_RELEASE);
		return -1;
	}




	wchar_t imageName[512];
	wchar_t lowerCaseImageName[512];

	cout << "ok";

	while (spi->NextEntryOffset)
	{
		// Loop over the list until we reach the last entry.
		//The following wsprintf is necessary because any access , include wcslen , other than wprintf causes an exception
		//So copied buffer to another buffer for further processing.
		//Report(lowerCaseImageName, L"%s", spi->ImageName.Buffer);
		cout << spi->ImageName.Buffer << endl;
		p = spi->ImageName.Buffer;
		q = lowerCaseImageName;
		ZeroMemory(lowerCaseImageName, sizeof(lowerCaseImageName));
		if (p) {
			for (; *p; ++p, ++q) * q = tolower(*p);
		}
		//Compare Names
		if ((StrCmpCW(lowerCaseInputProcess, lowerCaseImageName)) == 0) {
			processId = (DWORD)spi->ProcessId;
			DWORD dwSessionId = 0;
			if (ProcessIdToSessionId(processId, &dwSessionId))
			{

				if (sessionId == dwSessionId) {

					//Report(L"Found a Match:%s\d", processId);
					VirtualFree(buffer, 0, MEM_RELEASE); // Free the allocated buff
					return processId;
				}
			}


		}
		spi = (PSYSTEM_PROCESS_INFO)((LPBYTE)spi + spi->NextEntryOffset); // Calculate the address of the next entry.
	}
	processId = 0;
	VirtualFree(buffer, 0, MEM_RELEASE); // Free the allocated buffer.

	return processId;
}
BOOL CProcessManager::CreateProcessWithToken(HANDLE hToken, LPCWSTR lpszCommandLine, DWORD* dwProcessId)
{


	_ltow_s((long)hToken, buffer, len, 10);
	wstring entry = wstring(L"CreateProcessWithToken:");
	entry += lpszCommandLine;
	Report(entry.c_str(), buffer);

	// By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
	// the window station has a desktop that is invisible and the process is incapable of receiving
	// user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user 
	// interaction with the new process.
	STARTUPINFO si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.lpDesktop = L"winsta0\\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop

										// flags that specify the priority and creation method of the process
	UINT dwCreationFlags = (int)(NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE);



	SECURITY_ATTRIBUTES sa;
	ZeroMemory(&sa, sizeof(sa));
	sa.nLength = sizeof(sa);
	PROCESS_INFORMATION pi;

	ZeroMemory(&pi, sizeof(pi));





	LPWSTR szCmdLine = _tcsdup(lpszCommandLine);
	Report(szCmdLine);
	//LPCWSTR commandLine = CharToWideChar(lpszCommandLine);

	//	MessageBox(0, lp, L"Path", MB_OK);
	BOOL result = CreateProcessAsUser(hToken,        // client's access token
		0,        // command line
		szCmdLine,                   // file to execute&sa,                 // pointer to process SECURITY_ATTRIBUTES&sa,                 // pointer to thread SECURITY_ATTRIBUTES
		0,                  // handles are not inheritable
		dwCreationFlags,        // creation flags
		0,            // pointer to new environment block 
		0,                   // name of current directory &si,                 // pointer to STARTUPINFO structure&pi            // receives information about new process
	);
	if (!result) {
		//_ltow_s((DWORD)GetLastError(), buffer, len, 10);
		//MessageBoxA(0, "OpenProces Returned Null",buffer, MB_OK);
		Report(L"CreateProcessAsUser Returned Null. Error:%d", GetLastError());
	}
	*dwProcessId = pi.dwProcessId;
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	return result;
}
BOOL CProcessManager::CopyPrivileges(HANDLE hTokenSrc, HANDLE hTokenDst)
{

	_ltow_s((long)hTokenSrc, buffer, len, 10);
	wstring entry = wstring(buffer);
	_ltow_s((long)hTokenDst, buffer, len, 10);
	entry += wstring(L":") + wstring(buffer);

	Report(L"CopyPrivileges: Original Tokens:%s", entry.c_str());

	hTokenSrc = GetImpersonationToken(hTokenSrc);
	hTokenDst = GetImpersonationToken(hTokenDst);


	_ltow_s((long)hTokenSrc, buffer, len, 10);
	entry = wstring(buffer);
	_ltow_s((long)hTokenDst, buffer, len, 10);
	entry += wstring(L":") + wstring(buffer);

	Report(L"CopyPrivileges: Impersonated Tokens:%s", entry.c_str());


	TOKEN_PRIVILEGES Priv;
	ZeroMemory(&Priv, sizeof(Priv));
	DWORD dwLen = 0;
	GetTokenInformation(hTokenSrc, TokenPrivileges, &Priv, sizeof(TOKEN_PRIVILEGES), &dwLen);
	if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
		/**///)
		//_ltow_s(GetLastError(), buffer, len, 10);
		Report(L"GetTokenPrivileges First Call Failed with Error:%d", GetLastError());

		return(0);
	}

	//_ltow_s(dwLen, buffer, len, 10);
	Report(L"GetTokenPrivileges Buffer size:%d", dwLen);

	PTOKEN_PRIVILEGES pPriv = (PTOKEN_PRIVILEGES)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLen * 10);
	if (!GetTokenInformation(hTokenDst, TokenPrivileges, (LPVOID)pPriv, dwLen * 10, &dwLen)) {
		//_ltow_s(GetLastError(), buffer, len, 10);
		Report(L"GetTokenPrivileges Failed with Error:%d", GetLastError());
		return(0);
	}
	//_ltow_s(pPriv->PrivilegeCount, buffer, len, 10);
	Report(L"Privilege Count:%d", pPriv->PrivilegeCount);

	if (!AdjustTokenPrivileges(hTokenDst, FALSE, pPriv, dwLen, NULL, NULL)) {
		//_ltow_s(GetLastError(), buffer, len, 10);
		Report(L"AdjustTokenPrivileges Failed with Error:%d", GetLastError());
		return false;
	}

	LUID luid;
	ZeroMemory(&luid, sizeof(luid));
	if (!LookupPrivilegeValue(0, SE_TCB_NAME, &luid))
	{
		//_ltow_s(GetLastError(), buffer, len, 10);
		Report(L"LookupPrivilegeValue Failed with Error:%d", GetLastError());
		return false;
	}
	TOKEN_PRIVILEGES tp;
	ZeroMemory(&tp, sizeof(tp));
	tp.PrivilegeCount = 1;
	tp.Privileges->Luid.HighPart = luid.HighPart;
	tp.Privileges->Luid.LowPart = luid.LowPart;

	DWORD dwReturn = 0;
	if (!AdjustTokenPrivileges(hTokenDst, SE_PRIVILEGE_ENABLED, &tp, sizeof(tp), 0, &dwReturn))
	{
		//_ltow_s(GetLastError(), buffer, len, 10);
		Report(L"AdjustTokenPrivileges for TCB_NAME Failed with Error:%d", GetLastError());
		return false;

	}

	Report(L"Adjust Privileges Succeeded");
	DWORD dwSessionId = WTSGetActiveConsoleSessionId();
	if (!SetTokenInformation(hTokenDst, TokenSessionId, &dwSessionId, sizeof(dwSessionId)))
	{
		//_ltow_s(GetLastError(), buffer, len, 10);Report(L"SetTokenInformation Failed with Error:%d", GetLastError());
		return false;;
	}
	Report(L"SetTokenInformation succeded");
	return true;
}





What is the difference between Factory method design pattern and Bridge pattern?

$
0
0

Hello All,

Could someone please explain me the difference between Factory method design pattern and Bridge pattern? 

Because from my understanding both these design patterns are using to separate interface and implementation:

Decoupling abstraction from implementation. Abstraction separates the client code from the implementation. So, the implementation can be changed without affecting the client code and the client code need not be compiled when the implementation changes. 

Factory Method:

Problem without Factory method:

There are cases where we have a library with some classes to implement the client business logic. From the client application we create objects of the library classes to complete the task.

But sometimes, based on the client requirement to incorporate additional functionality, we might need to add additional classes in the library. Then we need to create objects of the new classes in the client application.

So, each time a new change is made at the library side, Client would need to make some corresponding changes at its end and recompile the code.

Using Factory Method:

To avoid this problem, we decouple object creation from client application using Factory method. Client just needs to make call to library’s factory method without worrying about the actual implementation of creation of objects.

So we create Factory method to create objects and move it to the separate implementation file.
Now the implementation file is the only one that requires knowledge of the derived classes. Thus, if a change is made to any derived class, or any new class is added, the implementation file is the only file that needs to be recompiled. Everyone who uses the factory will only care about the interface, which should remain consistent throughout the life of the application.

Client Application interacts -> Factory method and calls--> Implementation

If I take the below sample program, after adding any class or any change in the class is it enough to recompile only Vehicle.cpp file?

And also when creating factory method, do we use static method?

Vehicle.h

#include <iostream> 
using namespace std; 

enum VehicleType { 
    VT_TwoWheeler,    VT_ThreeWheeler,    VT_FourWheeler 
}; 

// Library classes 
class Vehicle { 
public: 
    virtual void printVehicle() = 0; 
    static Vehicle* Create(VehicleType type); 
}; 
class TwoWheeler : public Vehicle { 
public: 
    void printVehicle() { 
        cout << "I am two wheeler" << endl; 
    } 
}; 
class ThreeWheeler : public Vehicle { 
public: 
    void printVehicle() { 
        cout << "I am three wheeler" << endl; 
    } 
}; 
class FourWheeler : public Vehicle { 
    public: 
    void printVehicle() { 
        cout << "I am four wheeler" << endl; 
    } 
}; 


Vehicle.cpp (Implementation file)


// Factory method to create objects of different types. 
// Change is required only in this function to create a new object type 
Vehicle* Vehicle::Create(VehicleType type) { 
    if (type == VT_TwoWheeler) 
        return new TwoWheeler(); 
    else if (type == VT_ThreeWheeler) 
        return new ThreeWheeler(); 
    else if (type == VT_FourWheeler) 
        return new FourWheeler(); 
    else return NULL; 


Client.h file

// Client class 
class Client { 
public: 

    // Client doesn't explicitly create objects 
    // but passes type to factory method "Create()" 
    Client() 
    { 
        VehicleType type = VT_ThreeWheeler; 
        pVehicle = Vehicle::Create(type); 
    } 
    ~Client() { 
        if (pVehicle) { 
            delete[] pVehicle; 
            pVehicle = NULL; 
        } 
    } 
    Vehicle* getVehicle()  { 
        return pVehicle; 
    } 

private: 
    Vehicle *pVehicle; 
}; 

// Driver program 

int main() { 
    Client *pClient = new Client(); 
    Vehicle * pVehicle = pClient->getVehicle(); 
    pVehicle->printVehicle(); 
    return 0; 

Thanks in advance.





              

VS 2019 16.2 missing - "using _Pairib        = typename _Mybase::_Pairib"

$
0
0

We migrated our source from VS 2010 to VS 2019 16.0 ,everything was working fine , once we updated the latest VS 2019 16.2 builds are failing , we believe below mentioned part is not supported in the latest version VS 2019 16.2 for some reason ,

"using _Pairib        = typename _Mybase::_Pairib"

Is it intermediate removal? from VS 2019 builds ?

Thanks.

Open a new dialog from A window toaster click in c++

$
0
0

HI,

I have used Windows code (https://github.com/WindowsNotifications/desktop-toasts)and implemened a new toaster message message for Win32. is there any way to open another exe when i click on the toaster message?

Generally Shellexecute can open in c++ win32 but i am not able to open using the same when i am handling on toaster click event.

Thank you for the help!!

 



Regards, Ravi Raj Nukala

How to separate english words such as : I've = I have, etc.

$
0
0
// I'm trying to move this code from *.c file compiling on Borland to VS.
//I get many errors.
// Could you, please, tell me which are the right include files and what changes must be made in the code ? I am trying to separate english words such as : I've = I have, we've = we have, etc. ?
// Is there a new, better way to do that, so that the program knows that I is a Personal Pronoun, have is auxiliary verb, etc. ?

// added incl.files
#include <ctype.h>
#include <stdio.h>
#include <conio.h>

struct C_TAB *contr_analys(char *word, int wl, WORD *wrd);
struct C_TAB *contr_analys(char *word, int wl, WORD *wrd)
{
	struct C_TAB *mor;
	int lf, i;
	WORD *new;

	for (mor = CTAB; mor->mflex; mor++) {
		if ((lf = isflex(word, wl, mor->mflex)) > 0) {
			wl -= lf;
			wrd->stat = 1;

			switch (mor->mgram[0]) {
			case 'M':
				wl = 3;
				word[wl] = '\0';
				break;

			case 'X':

				if (!strcmp(word, "there\'s") ||
					!strcmp(word, "here\'s") ||
					!strcmp(word, "what\'s") ||
					!strcmp(word, "that\'s") ||
					!strcmp(word, "who\'s"))
				{
					word[wl] = '\0';
					break;
				}
				else { /* pronoun or possessive case */
					word[wl] = '\0';
					for (i = 0; PRTAB[i].mflex; i++)
						if (strcmp(PRTAB[i].mflex, word) == 0) break;

					if (PRTAB[i].mflex == NULL && mor->cond == 3) {
						/*  possessive case */
						word[wl] = '\'';
						wrd->stat = 0;
						return NULL;
					}
					/* pronoun */
				}
				break;

			case 'T':
				word[wl] = '\0';
				if (word[0] != 'i')
				{  /* are */
					for (i = 1; PRTAB[i].mflex; i++)
						if (strcmp(PRTAB[i].mflex, word) == 0) break;

					if (PRTAB[i].mflex == NULL) i = 1;
				}
				break;

			default:  /* not */
				if (!strcmp(word, "can\'t"))
					wl++;
				else if (!strncmp(word, "arn", 3)) {
					strcpy(wrd->inword + 1, "re");
					strcpy(word + 1, "re");
					wl = 3;
				}
				else if (!strncmp(word, "sha", 3)) {
					strcpy(wrd->inword + 3, "ll");
					strcpy(word + 3, "ll");
					wl = 5;
				}
				else if (mor->cond == 2) /* cannot */
					wl = 3;
				wrd->wl = wl;
				word[wl] = '\0';
				break;

			} /* end switch */

			new = enque_word(NULL, mor->mgram[0], mor->ow);
			if (new == NULL) {
				wrd->stat = -1;
				break;
			}
			strcpy(new->inword, mor->iw);
			new->stat = 1;
			if (new->syn == 'X') new->cflag = '\'';
			/*new->esyn = new->syn;*/
			new->wl = strlen(mor->iw);
			new->next = wrd->next;
			wrd->next = new;
			wrd->inword[wl] = '\0';
			wrd->wl = wl;
			/*wnprintf("\nword=\"%s\", wl=%d @ word=\"%s\", wl=%d ",
			wrd->inword, wrd->wl, new->inword, new->wl);*/

			return mor;
		}
	}

	return NULL;
}


error LNK2019: unresolved external symbol _D2D1CreateFactory@16

$
0
0

I am working my way through MSDN's Windows Graphics guide from Learn to Program for Windows in C++. I have downloaded Direct2D Circle Sample project which works fine. Just to make sure I've got everything right I tried to replicate myself Direct2D Circle by "upgrading" BaseWindow Sample (Direct2D Circle is derived from BaseWindow).

The problem is that as soon as I put in BaseWindow

 

#include<d2d1.h>

ID2D1Factory *pFactory; //MainWindow class
MainWnd() : pFactory(NULL) {};

if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory))) { //inside case WM_CREATE:
return -1;} 


 

I get this error message:

1>main.obj : error LNK2019: unresolved external symbol _D2D1CreateFactory@16 referenced in function "long __cdecl D2D1CreateFactory(enum D2D1_FACTORY_TYPE,struct _GUID const &,void * *)" (?D2D1CreateFactory@@YAJW4D2D1_FACTORY_TYPE@@ABU_GUID@@PAPAX@Z)
1>C:\Users\JP\Documents\Visual Studio 2010\Projects\FirstWnd\Debug\FirstWnd.exe : fatal error LNK1120: 1 unresolved externals

I've found Unresolved Symbol?? thread where Somesh Nanda describes the same problem. The solution mentioned over there is to link D2d1.lib which actually solves the problem. The first thing I did after finding the solution was to look if D2d1.lib is present in "Additional dependencies" of Direct2D Circle to confirm this is the actual problem. Surprisingly there was no link to D2d1.lib in that project.

Just to double check if the problem is caused by any settings in project properties, I have copied the code from Direct2D Circle  over the code in my version of BaseWindow. I didn't add D2d1.lib into "Additional dependencies" and I didn't do any other changes. The code compiled OK.

The question:

Why does Direct2D Circle compile fine without D2d1.lib whereas my version of BaseWindow gives me error described above? As Direct2D Circle code works fine when copied over into BaseWindow it suggests that the answer is somewhere in the code itself.



How do I setup Visual Studio Community 2019 for MASM?

$
0
0

I'm a die-hard masm coder.  I've waited patiently for years for Microsoft to get around to addressing the lack of good instructions to setup Visual Studio for MASM.  Isn't time to let certified MASM coders write a good procedure for that purpose?

I first tried to learn how to do that task with vs2015, and eventually I did.  Then when you released vs2017, to my chagrin I had to relearn it all over again.  Now with vs2019, I had to scrap my learning because vs2017 code doesn't properly apply to vs2019.  Should I wonder whether I'm wasting my time/money waiting?

Anyway, I think Visual Studio has grown enormously since its first release.  Properly managed it should become your best source of revenue.  Just don't forget all your ancient MASM coders...PLEASE!!!

Meanwhile, I guess I'll have to keep waiting, or eventually switch to Linux or Nasm.

 

What is the purpose of the `template MyAlloc(const MyAlloc&) { }` in the example below?

$
0
0

You'll find this example here (see my note at the bottom):

               

#include <stdlib.h>
#include <new>

template <typename T> struct MyAlloc {
    typedef T value_type;

    MyAlloc() { }
template <typename U> MyAlloc(const MyAlloc<U>&) { }

    bool operator==(const MyAlloc&) const { return true; }
    bool operator!=(const MyAlloc&) const { return false; }

    T * allocate(const size_t n) const {
        if (n == 0) {
            return nullptr;
        }

        if (n > static_cast<size_t>(-1) / sizeof(T)) {
            throw std::bad_array_new_length();
        }

        void * const pv = malloc(n * sizeof(T));

        if (!pv) {
            throw std::bad_alloc();
        }

        return static_cast<T *>(pv);
    }

    void deallocate(T * const p, size_t) const {
        free(p);
    }
};

#include <vector>
using MyIntVector = std::vector<int, MyAlloc<int>>;

#include <iostream>

int main ()
{
    MyIntVector foov = { 1701, 1764, 1664 };

    for (auto a: foov) std::cout << a << " ";
    std::cout << "\n";

    return 0;
}

I tried to set up a link in the word "here" above, but Visual C++ didn't allow me to do that. But you can find the example in

C++ Language Reference > Basic concepts > Declarations and definitions > Aliases and typedefs

deployment c++ app

$
0
0

Hi 

I want to deploy my C dll. I was informed that there is a visual c++ redistributable 2017 installed on the target machine.  Should I try somehow match to the redistributable through configuring visual studio tools (which I have never done and it was difficult to find how to do on in the Internet) or should I install the redistributable provided by VS that was used to build the dll? What would be the best practice?

Thanks



(solve)return after a CreateWindow throw an exception in the Winmain

$
0
0

Hello

Here is the beginning of the code in my winmain:

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: placez ici le code.

    // Initialise les chaînes globales
	WNDCLASSEXW wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wcex.lpfnWndProc = WndProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LUTHERIE));
	wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_LUTHERIE);
	wcex.lpszClassName = L"maclasse";
	wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	if (!RegisterClassExW(&wcex))
	{
		wchar_t err[256];
		memset(err, 0, 256);
		FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err, 255, NULL);
		MessageBoxW(NULL,err,(LPCWSTR)L"Erreur",	MB_OK);
		return -1;
	}
    // Effectue l'initialisation de l'application :
	hInst = hInstance; // Stocke le handle d'instance dans la variable globale
	hWindow = CreateWindowW(L"maclasse", L"Lignes de niveaux", WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

	if (!hWindow)
	{
		return FALSE;
	}
	return 0;
...
}

If I put the "return 0;" before CreateWindow (and leave the program, so) everything seems OK, but if I do like written in the code above, it throws a 0xC0000005 exception reading 0x00000000 with Kernel32.dll

Any idea, please

Thanks

Cathy L.


A problem with a crashing .bat installer!

$
0
0

HI, i am currently modding my Fallout 4 game and i had to integrate some graphic mods. 

so i did everithing as it should be done and tested. The game worked and everithing and there was only the last step which is to use the installer.bat file but upon opening it it crashes. NOW!!!! The mod author had stated that the problem is coming from outdated Visual C++ and gave us a link to the 2015 update. I updated but it still didn't open and then i tried installing the 2017 and 2019 versions without removing the 2015 version but it still didn't work. I asked in their discord and they pointed me to the site and told me to ask here. ( Sorry for my grammar )

IDL and COM question, I get error Parameter not optional

$
0
0

I have a ATL COM object

import "oaidl.idl";
import "ocidl.idl";
[
 object,
 uuid(0220a616-bff9-40ae-8bb5-03935836f1eb),
 dual,
 nonextensible,
 pointer_default(unique)
]
interface IIDLTestObj : IDispatch
{
 [helpstring("DoIt method."), helpcontext(0)]
 HRESULT DoIt([in] VARIANT_BOOL Ex,
  [in, defaultvalue(2)] long Mode,
  [in, optional] VARIANT B,
  [out, retval] long* Status);
};
[
 uuid(eb1809cf-87d0-4ef3-8365-231d9afa8104),
 version(1.0),
]
library IDLTestLib
{
 importlib("stdole2.tlb");
 [
  uuid(44092e2c-6585-4c17-8daa-e63d3ffb3043)
 ]
 coclass IDLTestObj
 {
  [default] interface IIDLTestObj;
 };
};

import "shobjidl.idl";

and a user MFC dialog has two handlers

void CIDLTestUserDlg::OnBnClickedOk() // I get error Parameter not optional
{
 CComPtr<IDispatch> pDisp;
 HRESULT hr = pDisp.CoCreateInstance(L"IDLTest.IDLTestObj");
 CComDispatchDriver d(pDisp);
 CComVariant vArgs[3];
 vArgs[0] = VARIANT_TRUE;
 vArgs[1] = CComVariant(long(2));
 vArgs[2] = vtMissing;
 hr = d.InvokeN((LPCOLESTR)_bstr_t(L"DoIt"), &vArgs[0], 3);
 if (FAILED(hr)) {
  CComPtr<IErrorInfo> pIErrorInfo;
  ::GetErrorInfo(0, &pIErrorInfo);
  _com_error error(hr, pIErrorInfo);
  pIErrorInfo.Detach();
  CString strError(L"DoIt  : ");
  strError += error.ErrorMessage();
  MessageBox(strError);
 }
}

void CIDLTestUserDlg::OnBnClickedButton1() // This works
{
 CComVariant v = vtMissing;
 IDLTestLib::IIDLTestObjPtr pTest;
 HRESULT hr = pTest.CreateInstance(L"IDLTest.IDLTestObj");
 long n = pTest->DoIt(VARIANT_TRUE, 2, v);

}

why do I get  error Parameter not optional

on dispatch call?

Is it safe to rely on registry key Dependencies\Microsoft.VS.VC_RuntimeMinimumVSU_x86,v14 to determine if VC++ 2015 or higher installed?

$
0
0
I am working on an installer which needs to check if VC++ 2015 or higher is installed on the system. I came across this registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Dependencies\Microsoft.VS.VC_RuntimeMinimumVSU_x86,v14\Version". It contains the VC++ Redistributable version installed on the system, for example in my case it's value is "14.21.27702" which is the version for VC++ 2015-2019 Redistributable bundle. So far it has worked well for me. I found the behavior consistent on 3 different machines that I tried on, and also with different VC++ Redistributables. The key was missing when VC++ 2015 (or higher) was not installed.

My question is - Is it safe to rely on this registry key or is there any other key that I can rely upon? I browsed a lot for a solution to determine if VC++ 2015 or higher is installed, came across certain threads but nowhere I found any mention of this registry key.
I already went through these related posts:
https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/64ab36ba-641a-4426-9e05-053f6c8ef737/how-to-determine-whether-msvc-2015-redistributable-32-or-64bit-is-already-installed?forum=vcgeneral
https://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed

Is unique_ptr constructor initializes the raw pointer and also unique_ptr Destructor deletes the associated raw pointer?

$
0
0

Hello All,

First time I am using smart pointers in my project. While using unique_ptr, I got some doubts regarding unique_ptr and raw pointer combination. And the way unique_ptr works internally.

Could some one please explain/answer based on my understanding as mentioned below, so that I can go ahead and use the smart pointers.

Below is the example:

class A 

public: 
    void show() 
    { 
        cout<<"A::show()"<<endl; 
    } 
}; 
  
int main() 

    unique_ptr<A> p1 (new A); 

    p1 -> show(); 
  
    // returns the memory address of p1 
    cout << p1.get(); 

   retrun 0;

}
 
From the above example,
 
1. When creating unique_ptr object "p1" we are providing raw pointer. Internally, unique_ptr constructor will initialize the unique_ptr with the raw pointer. Is my understanding correct?

2. As per the unique_ptr definition, "The pointer is exclusively owned by one object or a resource".

 Based on the above statement, in our scenario, "raw pointer" is exclusively owned by the unique_ptr object "p1". Am I correct?

3. And also after the statement, cout << p1.get(); (In the above sample program) as it is going out of scope, internally, the destructor of the unique_ptr called and it deletes the associated raw pointer. Is my understanding correct?

4. Finally, once deletes the associated raw pointer is the unique_ptr object will become empty?


Thanks in advance.

Viewing all 15302 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>