5,448,416 members and growing! (18,520 online)
Email Password   helpLost your password?
Database » Database » ADO.NET     Intermediate

Using ADO.NET in MFC Projects

By Majid Shahabfar

Mixing managed and unmanaged code and using .NET library in MFC projects
C++/CLI, VC6, VC7, VC7.1, C++, .NET, Windows, Win2K, WinXP, Win2003, MFC, VS.NET2002, Visual Studio, Dev

Posted: 9 Aug 2003
Updated: 9 Aug 2003
Views: 95,668
Bookmarked: 30 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
32 votes for this Article.
Popularity: 5.94 Rating: 3.94 out of 5
3 votes, 9.4%
1
1 vote, 3.1%
2
1 vote, 3.1%
3
6 votes, 18.8%
4
21 votes, 65.6%
5

Sample Image - adonetinmfc.gif

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

About the Author

Majid Shahabfar


My programming experience includes Visual C++, C#, ASP.NET, Web Services and GDI+. I'm developing software application under .NET technology now and I enjoy keeping my skills up-to-date.

Occupation: Web Developer
Location: Iran, Islamic Republic Of Iran, Islamic Republic Of

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 40 (Total in Forum: 40) (Refresh)FirstPrevNext
Subject  Author Date 
QuestionI can't find some options in VS2005?!memberDONinLIVE18:05 11 Nov '07  
GeneralTHIS CODE DOES NOT WORK IN LIBRARYmembersteveusa3920009:35 13 May '07  
AnswerRe: THIS CODE DOES NOT WORK IN LIBRARYmemberHimanshu R. Swami5:47 5 Mar '08  
GeneralHimembervoorugonda prashanth6:03 20 Apr '07  
QuestionCString -> System::String __gc *membersung-jun, choi21:07 22 Nov '06  
AnswerRe: CString -> System::String __gc *memberMajid Shahabfar3:10 24 Nov '06  
AnswerRe: CString -> System::String __gc *memberhanszeh23:55 13 Sep '07  
GeneralFinding the Columns that make up an IndexmemberAlexEvans22:36 12 Oct '06  
AnswerRe: Finding the Columns that make up an IndexmemberHimanshu R. Swami5:42 5 Mar '08  
Generalkalakmemberhadez80314:20 10 Sep '06  
GeneralRe: kalakmemberMajid Shahabfar19:54 10 Sep '06  
GeneralRe: kalakmemberhadez8039:45 14 Sep '06  
GeneralWhat's mean "S" ?membersnowume20:40 30 Jul '06  
AnswerRe: What's mean "S" ?memberHimanshu R. Swami5:35 5 Mar '08  
QuestionADO.NET in Visual Studio 6.0memberShai`tan4:59 7 Jul '06  
AnswerRe: ADO.NET in Visual Studio 6.0memberMajid Shahabfar6:50 7 Jul '06  
GeneralRe: ADO.NET in Visual Studio 6.0memberShai`tan11:55 7 Jul '06  
GeneralRe: ADO.NET in Visual Studio 6.0memberShai`tan12:00 7 Jul '06  
GeneralRe: ADO.NET in Visual Studio 6.0memberMajid Shahabfar23:20 7 Jul '06  
Generalusing my own NET.dll lib in MFCmemberd00_ape1:42 21 Feb '06  
GeneralRe: using my own NET.dll lib in MFCmemberIC188:30 27 Jun '06  
AnswerRe: using my own NET.dll lib in MFC [modified]memberHimanshu R. Swami5:31 5 Mar '08  
Generalvs2005?memberjiva17:06 27 Dec '05  
AnswerRe: vs2005?memberHimanshu R. Swami5:30 5 Mar '08  
GeneralExcellentmemberDr. Dennis19:39 17 Apr '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Aug 2003
Editor: Rob Manderson
Copyright 2003 by Majid Shahabfar
Everything else Copyright © CodeProject, 1999-2008
Web08 | Advertise on the Code Project