Programmatically Invoking the OLEDB Data Link Config Dialog

Environment: VC6, MDAC 2.1 ( ADO 2.1 ), Win9x / NT

Introduction

I recently needed to allow a user to have the ability to configure a connection string for one of my applications that uses ADO. After searching relentlessly through the docs, there was absolutely no information available on how to do this, except for a knowledge base article (Q225132) that described a problem with the #import statements when going from MDAC 2.0 to 2.1. This spurred me into writing this short article to demonstrate how you can use the standard OLE DB Data link configuration dialog in your own applications.

The data link dialog is contained in oledb32.dll (in MDAC 2.1, MDAC 2.0 its in msdasc.dll ). And it really is extremely easy to use. By creating an instance of the IDataSourceLocator interface, you can pop up and configure ADO data sources very quickly.

Ok, so lets take a look at how to do it. Ive created a simple console app project that demonstrates how to do this, download it by following the link at the bottom of this article.

Importing the type libraries

Firstly load up the simple source project and open the one and only source file ( datalink.cpp ) contained therein. The source is quite well commented so it should be straight forward to read it, but here are the main points.

Note from Web Master: The following #import pragmas are broken only due to formatting reasons.

#import "c:\program files\common files\system\ado"
"\msado20.tlb" no_namespace rename("EOF", "IsEOF") 
rename("BOF", "IsBOF")

#import "c:\program files\common files\system\ole "
db\oledb32.dll" rename_namespace("oledb")

The #import statements at the top of the source file tell the compiler to generate some files that allow us to use smart pointers on the data link objects and the ADO objects. These import statements will allow us to use the ADO objects, and importantly for this article the Data Link properties dialog object.

Displaying the Data Link Properties Dialog

The function main() mostly contains some code to allow us to load and save a pre-configured connection string. I'm assuming you're familiar with the ios classes, so I'll skip this part as it was only put there to demonstrate you can display the dialog based on a pre-configured connection string.

When you want to display the dialog, you simply declare a IDataSourceLocatorPtr smart pointer object ( created from the #import statements ), and create an instance of it. You are then free to call its PromptNew() and PromptEdit( IDispatch *ptr ) methods.

For example, this code segment shows how to display the dialog for creating a new connection string (error checking etc has been removed for brevity);

 oledb::IDataSourceLocatorPtr    p_IDSL = NULL;
 _ConnectionPtr                  p_conn = NULL;

 p_IDSL.CreateInstance( __uuidof( oledb::DataLinks ));

 p_conn = p_IDSL->PromptNew();

The PromptNew function will display a fresh dialog for all the parameters to be entered by the user, and upon return, p_conn will be set to either NULL, indicating the user clicked cancel, or it will contain a created Connection object with its data member ConnectionString set to the ADO connection string that represents the users choices.

To display the dialog, based upon a pre-existing connection string, its slightly more convoluted. Here's an example;

oledb::IDataSourceLocatorPtr    p_IDSL = NULL;
_ConnectionPtr                  p_conn = NULL;

p_IDSL.CreateInstance( __uuidof( oledb::DataLinks ));
p_conn.CreateInstance( "ADODB.Connection" );

p_conn->ConnectionString = _bstr_t("your connection string");

IDispatch * p_Dispatch = NULL;
p_conn.QueryInterface( IID_IDispatch, (LPVOID*) & p_Dispatch );

p_IDSL->PromptEdit( &p_Dispatch );

p_Dispatch->Release();

The edit version of the dialog needs these extra steps. Firstly you need to create a Connection object and set its connection string yourself, this is then converted into an IDispatch pointer using QueryInterface, and passed into the PromptEdit function.

PromptEdit returns a BOOL as TRUE if the user clicked OK, or FALSE if cancel was clicked. If it's TRUE the p_conn object's ConnectionString property will be set to the new connection parameters defined by the user.

Wrapping up

My use of these functions involved using the registry to store and retrieve the connection string. By adding this functionality to your application, you can give the user the ability to easily configure their ADO data source. I hope it helps some of you....it certainly helped me.

Downloads

Download source - 43 Kb


Comments

  • Goal

    Posted by snareenactina on 12/01/2012 08:16pm

    geping WebMD Mobile Drug Information App These flexible online degrees could help you go to school on your terms. A major feature of Nigeria's economy in the 1980s, as in the 1970s, was its dependence on petroleum, which accounted for 87 percent of export receipts and 77 percent of the federal government's current revenue in 1988. Falling oil output and prices contributed to another noteworthy aspect of the economy in the 1980s—the decline in per capita real gross national product, which persisted until oil prices began to rise in 1990. Indeed, GNP per capita per year decreased 4.8 percent from 1980 to 1987, which led in 1989 to Nigeria's classification by the World Bank as a low-income country (based on 1987 data) for the first time since the annual World Development Report was instituted in 1978. In 1989 the World Bank also declared Nigeria poor enough to be eligible (along with countries such as Bangladesh, Ethiopia, Chad, and Mali) for concessional aid from an affiliate, the International Development Association (IDA). yongnian One would expect nicer behavior from the corporate chieftains who run our economy. Over the last 15 years transnational corporations have gotten basically everything they wanted: the collapse of communism, free trade agreements, deregulation, lower taxes, the weakening of trade unions and the pushing down of wage rates. Yet while profits and the stock market soar, the standard of living for most Americans is plummeting. There is a dangerous dynamic at work. In an effort to cut costs and boost profits, AT&T announced in September 1995 that they were laying off 40,000 workers. The company's share price on Wall Street immediately jumped higher. Because the salaries of top AT&T executives are partly made up of share ownership, the executives are personally benefiting from the suffering of thousands of dislocated families. emmett I\’d think that three variations on the same theme is quite enough for one week. However Kerri\’s idea of freezing portions is quite common in some households I know. It allows them to start maybe on a Sunday and have ready meals from the freezer for later in the week that just need a quick tweak – a great idea if you have to go to work. So much nicer than buying some of the convenience foods from the supermarket at a price that reflects in the price the fact that it has all been cooked, packed, frozen and transported. My bedrock recipe at the moment is the standard vegetable soup recipe using up the vegetables from the allotment as the gluts happen. Large pot of soup – helping for the day and the rest frozen down. When defrosted you can tweak it with a dash of sauce, herbs or available spices, add a different can of beans. As I use vegetable stock cubes that are suitable for vegans, this would work for Gabrielle and she could add whatever suits her to change the recipe for the day. weeksmix The respective governments have the onus responsibilities in mobilizing credit/loan facilities to the marginal agriculturalists so that they could mechanize their cultivation technique and contribute more in social and economic expansion in their countries. potato I kid you not, Romney's pick for Vice Pres. ACTUALLY DROVE THE WEINERMOBILE!!! True story. pamala In 2008, Nigeria's external debt was an estimated US$3.3 billion. sharples In the news: mdcouncilor Script section containing code for Liveperson Chat Solution

    Reply
  • New one

    Posted by snareenactina on 11/12/2012 05:02am

    turnstone Gun-shy after witnessing the wealth destruction after the global financial crisis, Australians are worried. All NEU students will gain life time access to the information, as well as any improvements and enhancements made over time. Hungary stefanis South Africa has made remarkable strides toward building a prosperous and peaceful democracy since 1994, but faces many challenges, including unemployment, HIV/AIDS, crime, and corruption. U.S. assistance focuses on improving healthcare, increasing education standards and teacher training, building capacity in agriculture to address regional food security, and developing clean energy to adapt to global climate changes. Improving the capacity of South Africa's security force will enable it to take a lead role in regional stability and security efforts. homeroom These sites provide critical commentary on the press for those who would like reporting itself questioned malpractices The Facebook ticker is one example. If the Facebook newsfeed updated in real time, then it might move too quickly for the average user. But by moving real-time updates to the periphery, the user has a more calm and satisfying Facebook experience. bhue When it comes to languages: Most Europeans speak English as well as their native language. In small countries in Europe (less than 20m people) most people understand and speak English well enough to communicate to each other. As a total (including the large countries) almost everybody in a decision making role will master the English language comparable to an American high school student, with a big portion comparable to the US university level. athleteswhen Now don't stop there. Say why. kresge Connecting to %s weekfor Ethnic tensions have erupted into violence in Tibet and mainly Muslim Xinjiang

    Reply
  • HOW TO: Build a Connection String Programmatically in ADO.NET

    Posted by Legacy on 08/01/2003 12:00am

    Originally posted by: Jose Maria Tejedor

    Just see the following: "Microsoft Knowledge Base Article - 310083".

    Reply
  • Error

    Posted by Legacy on 03/29/2003 12:00am

    Originally posted by: Brad Bruce

    p_Dispatch->Release();
    results in an error. The error code is -2147217805

    Any suggestions?

    Thanks

    Reply
  • Works in C# too

    Posted by Legacy on 01/21/2002 12:00am

    Originally posted by: Will Baldwin

    //Set a reference to the oledb32.dll and ADO
    //It will create the MSDASC Wrapper for you...

    private void PromptNew_Click(object sender, System.EventArgs e)
    {
    MSDASC.DataLinks objDataSourceDlg = new MSDASC.DataLinks();
    ADODB._Connection adoConnection;
    adoConnection = (ADODB._Connection)objDataSourceDlg.PromptNew();
    objDataSourceDlg.WriteStringToStorage(@"Connection.UDL",
    adoConnection.ConnectionString, 2 );

    //CREATE_NEW 1, CREATE_ALWAYS 2, OPEN_EXISTING 3,
    //OPEN_ALWAYS 4, TRUNCATE_EXISTING 5
    }

    private void PromptEdit_Click(object sender, System.EventArgs e)
    {
    MSDASC.DataLinks objDataSourceDlg = new MSDASC.DataLinks();
    ADODB.Connection objADOConn = new ADODB.Connection();
    object objTempConn = null;
    string strConnectionString;
    objDataSourceDlg.LoadStringFromStorage(@"Connection.UDL", out
    strConnectionString);
    objADOConn.ConnectionString = strConnectionString;
    objTempConn = (object)objADOConn;
    bool bSuccess = objDataSourceDlg.PromptEdit(ref objTempConn);
    if (bSuccess)
    {
    objDataSourceDlg.WriteStringToStorage(@"SentinelDB_Connection.UDL",
    objADOConn.ConnectionString, 2);
    }
    }

    Reply
  • Finaly found a way to use PromptEdit !!

    Posted by Legacy on 11/02/2001 12:00am

    Originally posted by: P�r Gradin

    This is the only page on the net that describes the correct way to use PromptEdit in c++. I've been searching alot of newsgroups. 
    
    

    Important thing though:
    If the connection is open when PromptEdit is used, be sure to close it before the PromptEdit call:

    if (p_conn->GetState()==adStateOpen) p_conn->Close();

    The datalinks dialog reported an error when I tried to edit my already opend connection!

    Thanx !!

    Reply
  • www.geocities.com/gemedany

    Posted by Legacy on 10/12/2001 12:00am

    Originally posted by: geme

    how can i get the password properties??(without chek "allow saving password)"

    Reply
  • Even easier way

    Posted by Legacy on 02/07/2001 12:00am

    Originally posted by: John Smith

    Use the OLE DB Consumer, use the following code

    CDataSource ds;
    ds.Open();

    2 lines of code, will open the Datalink Dialog.

    Reply
  • Storing Bitmap to Database

    Posted by Legacy on 01/23/2001 12:00am

    Originally posted by: Rajasekhar

    Hello!

    I am developing an application for PocketPC using eVC and the backend is SQLServer CE 2000 for Windows CE.The deveice database is SQLCE and using ADOCE 3.1.I am loading a bitmap into my view(CView), after that i am drawing some lines, typing some text and erasing some portion(pasting white color) on to the bmp.I want to save the frame however it's looking on the PocketPC to the dabatase.The datatype for the field on the database is image.

    I also want to read back it and display as it is in the view.Is is possible.I didn't found any way to do this.


    I want to implement WYSIWYG(What You See Is What You Get)while storing and retrieving the bitmap.

    Any help in this regard will be appreciated.

    Please email to chavasekhar@rediffmail.com

    Regards...
    Rajasekhar

    Reply
  • Storing Bitmap to Database

    Posted by Legacy on 01/23/2001 12:00am

    Originally posted by: Rajasekhar

    Hello!

    I am developing an application for PocketPC using eVC and the backend is SQLServer CE 2000 for Windows CE.The deveice database is SQLCE and using ADOCE 3.1.I am loading a bitmap into my view(CView), after that i am drawing some lines, typing some text and erasing some portion(pasting white color) on to the bmp.I want to save the frame however it's looking on the PocketPC to the dabatase.The datatype for the field on the database is image.

    I also want to read back it and display as it is in the view.Is is possible.I didn't found any way to do this.


    I want to implement WYSIWYG(What You See Is What You Get)while storing and retrieving the bitmap.

    Any help in this regard will be appreciated.

    Please email to chavasekhar@rediffmail.com

    Regards...
    Rajasekhar

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • When it comes to desktops – physical or virtual – it's all about the applications. Cloud-hosted virtual desktops are growing fast because you get local data center-class security and 24x7 access with the complete personalization and flexibility of your own desktop. Organizations make five common mistakes when it comes to planning and implementing their application management strategy. This eBook tells you what they are and how to avoid them, and offers real-life case studies on customers who didn't …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds