CDatabase bug in MFC in VS2012

After migrating an MFC application from Visual Studio 2008 to Visual Studio 2012 I run into an unexpected error: the application was having problem fetching data from the SQL Server database. After debugging it turned out that function CDatabase::GetConnect that I was using to retrieve the connection string after opening the database (for different purposes) was suddenly returning an empty string. It turned out this was a known MFC bug, reported on Microsoft Connect. The cause of the problem is that CDatabase encrypts the connection string, and then empties it. Here is a snippet of OpenEx:

Though Microsoft promised to be solved the bug in the next major version I needed a fix now. So here is my fix.

CDatabase has a protected member m_strConnect which is supposed to keep the connection string in plain text, and one called m_blobConnect that represents the encrypted connection string. However, there is no method in CDatabase to return this blob. Getting the blob would allow you to decrypt it and get the actual connection string. So the solution is to derive CDatabase, provide a method to return the connection string, and in your code replace CDatabase with this derived class and the call to GetConnect() to this new method.

, , , , Hits for this post: 13034 .
Trackback

6 comments untill now

  1. Gravatar
    Grant Gussie @ 2013-03-10 19:05

    The line

    if (CryptUnprotectData(&m_blobConnect, NULL, NULL, NULL, NULL, 0, &connectBlob))

    is returnng the error for me

    error C2664: ‘CryptUnprotectData’ : cannot convert parameter 1 from ‘const DATA_BLOB *’ to ‘DATA_BLOB *’

  2. Gravatar
    Grant Gussie @ 2013-03-11 17:45

    If I modify the code with a simple data cast, however, everything is fine…

    if (CryptUnprotectData((DATA_BLOB*)(&m_blobConnect), NULL, NULL, NULL, NULL, 0, &connectBlob))

  3. Gravatar

    m_blocConnect is not const, so I have no idea why you get that error. It compiles perfectly fine for me.

  4. Gravatar
    Daniel Remedi @ 2013-08-09 04:55

    Thank you very much. You are a genius!

  5. Gravatar

    u saved my friday :- )

  6. Gravatar

    I found this blog since I encountered CDatabase::OpenEx() StackHash crash under pressure test, and tried to looking for if any known bug or solution.

    My environment is using VS2005 SP1 + SQLServer native client 10.0 + MSSQL 2008.

    According to VS2005 IDE call stack window, at the crash point, it is a little odd that there were about 20 levels of call stack from CDatabase::OpenEx to crash function in sqlncli10.dll.

    I doubt if that a known problem?

    Best regards,

    Alan

Add your comment now