Click here to Skip to main content
Click here to Skip to main content
Go to top

Using ADO.NET in MFC Projects

, 9 Aug 2003
Rate this:
Please Sign up or sign in to vote.
Mixing managed and unmanaged code and using .NET library in MFC projects
<!-- Article image -->

Sample Image - adonetinmfc.gif

<!-- Add the rest of your HTML here -->

Introduction

The main goal of writing this article is to explain how we can mix the .NET library with the MFC library in very easy steps, gaining the benefits of .NET in unmanaged code such as MFC projects. So for this reason I’ve added ADO.NET in a MFC project to use the simple, type-safe and powerful functionalities of that library.

ADO.NET

In designing tools and technologies to meet the needs of today's developer, Microsoft recognized that an entirely new programming model for data access was needed, one that is built upon the .NET Framework. Building on the .NET Framework ensures that the data access technology would be uniform, components would share a common type system, design patterns and naming conventions. ADO.NET was designed to meet the needs of this new programming model: disconnected data architecture, tight integration with XML, common data representation with the ability to combine data from multiple and varied data sources, and optimized facilities for interacting with a database, all native to the .NET Framework.

Mixing Managed and Unmanaged code

To use managed code in a MFC projects we must change some MFC project settings and add some code to declare the .NET library.

Changing Configuration

To alter the configuration of your MFC project to use unmanaged code, change the following items in the Configuration Properties dialog box.

General - Use Managed Extensions = YES

C/C++ - General - Debug Information Format = Program Database (/Zi)

C/C++ - General - Compile As Managed = Assembly Support (/clr)

C/C++ - Code Generation - Enable Minimal Rebuild = No

C/C++ - Code Generation - Basic Runtime Checks = Default

The /clr compiler option provides module-level control for compiling functions either as managed or unmanaged. Now you must add the following code wherever you want to use managed code. If you want use managed code in several classes of your project it is better that you add this code to the stdafx.h file.

#pragma managed

#using <mscorlib.dll>
#using <System.dll>
#using <system.data.dll>

#using namespace System;
#using namespace System::Data;
#using namespace System::Data::OleDb;

The managed pragma enables function-level control for compiling functions as managed. An unmanaged function will be compiled for the native platform, and execution of that portion of the program will be passed to the native platform by the common language runtime.

Because we are using ADO.NET in our project so we have to add System::Data and since we want to use the MS Access database we have added System::Data::OleDb.

__gc Pointers in Unmanaged Classes

To declare a managed pointer as member in a class we must use __gc pointers. It is illegal to declare a member of an unmanaged class to have __gc pointer type. In order to point to a managed object from the C++ heap, the header file vcclr.h provides the type-safe wrapper template gcroot. Use of this template allows the programmer to embed a virtual __gc pointer in an unmanaged class and treat it as if it were the underlying type. The header file vcclr.h is included in VS.NET by default and you don’t need to include it to your application. Anyway this file can be found in the \Microsoft Visual Studio .NET\Vc7\include directory.

Therefore for declaring pointers of OleDB classes as members we must writing something like this.
gcroot<OleDbConnection*> m_OleDbConnection;
gcroot<OleDbCommand*>    m_OleDb;
gcroot<OleDbDataReader*> m_Reader;

Writing Managed Code

Now it is time to write managed code in an unmanaged function.

#pragma push_macro("new")
#undef new

try
{
    m_OleDbConnection = new OleDbConnection(
                 S"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\test.mdb"
            );
    m_OleDbConnection->Open();    // Open up the connection
    m_OleDb = new OleDbCommand(S"select * from Persons", m_OleDbConnection);
    m_Reader = m_OleDb->ExecuteReader();

    int count = 0;

    while (m_Reader->Read())
    {
        AddToList(count,m_Reader->get_Item("First Name")->ToString(),
                  m_Reader->get_Item("Last Name")->ToString(),
                  m_Reader->get_Item("Phone Number")->ToString()
        );
        count++;
    }
}
catch(Exception *e)
{
    AfxMessageBox(CString(e->ToString()));
}
__finally
{
    m_Reader->Close();
    m_OleDbConnection->Close();
}

#pragma pop_macro("new")

the #pragma push_macro("new"), #undef new and #pragma pop_macro("new") are used when your project is in debug mode. Otherwise you will get errors saying placement arguments not allowed while creating instances of managed classes.

This was a small sample that indicates how we can use .NET library in MFC based projects. By following this sample You can write more complicated projects and using more benefits of .NET. It is easy to cope with and entirely feasible to extend your own MFC applications with managed code.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Majid Shahabfar
Software Developer (Senior)
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Majid is a well-experienced .NET developer who directs his own community PersiaDevelopers.com which is a Microsoft software development technology community for Persian native developers.
He is involved in many kind of software projects and also doing some tasks on High Performance Computing including massive parallel computing and GPU programming.
He is working as a software designer and developer and also as a consultant for some IT related companies.

Comments and Discussions

 
Generalwho do use datagrid in this project Pinmembersoheaila12-Jan-09 20:07 
GeneralRe: who do use datagrid in this project PinmemberMajid Shahabfar13-Jan-09 3:23 
Questionhow can use it on 8.mdf file? Pinmembervahid_m_200816-Dec-08 3:51 
QuestionI can't find some options in VS2005?! PinmemberDONinLIVE11-Nov-07 17:05 
GeneralTHIS CODE DOES NOT WORK IN LIBRARY Pinmembersteveusa39200013-May-07 8:35 
AnswerRe: THIS CODE DOES NOT WORK IN LIBRARY PinmemberHimanshu R. Swami5-Mar-08 4:47 
GeneralHi Pinmembervoorugonda prashanth20-Apr-07 5:03 
QuestionCString -> System::String __gc * Pinmembersung-jun, choi22-Nov-06 20:07 
AnswerRe: CString -> System::String __gc * PinmemberMajid Shahabfar24-Nov-06 2:10 
AnswerRe: CString -> System::String __gc * Pinmemberhanszeh13-Sep-07 22:55 
AnswerRe: CString -> System::String __gc * Pinmemberhaoke01612-Sep-12 3:29 
GeneralFinding the Columns that make up an Index PinmemberAlexEvans12-Oct-06 21:36 
AnswerRe: Finding the Columns that make up an Index PinmemberHimanshu R. Swami5-Mar-08 4:42 
Generalkalak Pinmemberhadez80310-Sep-06 13:20 
GeneralRe: kalak PinmemberMajid Shahabfar10-Sep-06 18:54 
GeneralRe: kalak Pinmemberhadez80314-Sep-06 8:45 
QuestionWhat's mean "S" ? Pinmembersnowume30-Jul-06 19:40 
AnswerRe: What's mean "S" ? PinmemberHimanshu R. Swami5-Mar-08 4:35 
GeneralRe: What's mean "S" ? Pinmembersnowume7-Mar-10 21:28 
QuestionADO.NET in Visual Studio 6.0 PinmemberShai`tan7-Jul-06 3:59 
Hi
 
We still have a project that haven't yet been ported to VS.NET or VS2005 and we would like to use SQL Server Everywhere. It is only available through ADO.NET or OLE DB. OLE DB seems to be a bit complex for us at the moment, so I was curious if it is possible to use the ADO.NET assemblies through a wrapper from MFC in VS 6.0.
 
Best regards
 
Bjørnar
AnswerRe: ADO.NET in Visual Studio 6.0 PinmemberMajid Shahabfar7-Jul-06 5:50 
GeneralRe: ADO.NET in Visual Studio 6.0 PinmemberShai`tan7-Jul-06 10:55 
GeneralRe: ADO.NET in Visual Studio 6.0 PinmemberShai`tan7-Jul-06 11:00 
GeneralRe: ADO.NET in Visual Studio 6.0 PinmemberMajid Shahabfar7-Jul-06 22:20 
Generalusing my own NET.dll lib in MFC Pinmemberd00_ape21-Feb-06 0:42 
GeneralRe: using my own NET.dll lib in MFC PinmemberIC1827-Jun-06 7:30 
AnswerRe: using my own NET.dll lib in MFC [modified] PinmemberHimanshu R. Swami5-Mar-08 4:31 
Questionvs2005? Pinmemberjiva27-Dec-05 16:06 
AnswerRe: vs2005? PinmemberHimanshu R. Swami5-Mar-08 4:30 
GeneralExcellent PinmemberDr. Dennis17-Apr-05 18:39 
Questionwindows forms in MFC projects? Pinmembercess25-Jan-05 5:51 
AnswerRe: windows forms in MFC projects? PinmemberMajid Shahabfar26-Jan-05 4:24 
AnswerRe: windows forms in MFC projects? Pinmemberearlgraham27-Oct-06 9:46 
Generali can't find the /clr in the evc Pinmemberherime12-Jan-04 20:03 
GeneralRe: i can't find the /clr in the evc PinmemberHimanshu R. Swami5-Mar-08 4:22 
GeneralRecommend DLL PinmemberAbraxas2312-Dec-03 1:30 
GeneralWorks great, except for CTreeCtrl PinmemberAbraxas2310-Dec-03 9:41 
GeneralRe: Works great, except for CTreeCtrl PinsussAnonymous18-Mar-04 7:09 
GeneralRe: Works great, except for CTreeCtrl Pinmemberrammreddy22-Mar-06 13:09 
Generalperformance issue PinmemberFHT9-Oct-03 0:22 
GeneralGood Work! PinmemberA. Riazi11-Aug-03 20:05 
GeneralRe: Good Work! PinmemberMajid Shahabfar11-Aug-03 20:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 10 Aug 2003
Article Copyright 2003 by Majid Shahabfar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid