示例#1
0
        public static string GetBuiltConnectionString(string inputConnectionString)
        {
            MSDASC.DataLinks oDL = null;
            string           res = string.Empty;

            try
            {
                oDL = new MSDASC.DataLinksClass();
                ADODB.Connection conn = new ADODB.ConnectionClass();

                conn.ConnectionString = inputConnectionString;
                object oConn = (object)conn;
                if (oDL.PromptEdit(ref oConn))
                {
                    res = conn.ConnectionString;
                }
            }
            catch
            {
                try
                {
                    ADODB._Connection oConn = (ADODB._Connection)oDL.PromptNew();
                    if (oConn != null)
                    {
                        res = oConn.ConnectionString.ToString();
                    }
                }
                catch (Exception ex)
                {
                    MyExceptionHandler.NewEx(ex);
                }
            }

            return(string.IsNullOrEmpty(res) ? null : res);
        }
示例#2
0
        private static string PromptConnectionString(string initial, IntPtr handle)
        {
            bool ok = false;

            ADODB.Connection conn   = null;
            MSDASC.DataLinks dlinks = null;
            try
            {
                // create objects we'll need
                dlinks = new MSDASC.DataLinks();
                conn   = new ADODB.ConnectionClass();

                // initialize object
                if (initial != null && initial.Length > 0)
                {
                    conn.ConnectionString = initial;
                }

                // show connection picker dialog
                object obj = conn;
                dlinks.hWnd = (int)handle;                 // << make it modal
                ok          = dlinks.PromptEdit(ref obj);
            }
            catch (Exception x)
            {
                MessageBox.Show("Cannot build connection string because:\r\n" + x.Message);
            }

            // return what we got
            return((ok)? conn.ConnectionString: initial);
        }
        private void BtnBuild_OnClick(object sender, RoutedEventArgs e)
        {
            // Using COM interop with the OLE DB Service Component to display the Data Link Properties dialog box.
            //
            // Add reference to the Primary Interop Assembly (PIA) for ADO provided in the file ADODB.DLL:
            // select adodb from the .NET tab in Visual Studio .NET's Add Reference Dialog.
            // You'll also need a reference to the Microsoft OLE DB Service Component 1.0 Type Library
            // from the COM tab in Visual Studio .NET's Add Reference Dialog.

            try
            {
                var dlg             = new MSDASC.DataLinks();
                var adodbConnection = new ADODB.Connection {
                    ConnectionString = _connectionString
                };
                object connection = adodbConnection;

                if (dlg.PromptEdit(ref connection))
                {
                    _connectionString       = adodbConnection.ConnectionString;
                    tbConnectionString.Text = _connectionString;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show("Failed to show OLEDB Data Link Properties dialog box.\n" +
                                "Perhaps you have no required components installed or they are outdated.\n" +
                                "Try to rebuild this demo from the source code.\n\n" +
                                exception.Message);
            }
        }
        public static string GetConnectionString(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                return(GetConnectionString());
            }
            try
            {
                // C:\Program Files\Common Files\System\Ole DB\OLEDB32.DLL
                MSDASC.DataLinks dataLinks = new MSDASC.DataLinks();

                // C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies\adodb.dll
                ADODB._Connection connection;

                connection = new ADODB.Connection();
                connection.ConnectionString = connectionString;

                object oConnection = connection;

                if (dataLinks.PromptEdit(ref oConnection))
                {
                    return(connection.ConnectionString);
                }
            }
            catch (Exception)
            {
            }
            return(null);
        }
示例#5
0
        private void txtBaglantiCumle_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ADODB._Connection ADOcon;
            MSDASC.DataLinks  mydlg = new MSDASC.DataLinks();
            ADOcon = (ADODB._Connection)mydlg.PromptNew();

            if (txtSQLSunucusu.Text == "" || txtSQLSunucusu.Text == null)
            {
                MessageBox.Show("Lütfen SQL Sunucusu seçin!");
                txtSQLSunucusu.Focus();
            }
            else
            {
                ADOcon.Open(txtSQLSunucusu.Text, "Makrosoft", "Makrosoft", 0);
            }


            if (ADOcon.State == 1)
            {
                MessageBox.Show("Bağlantı açıldı");
                ADOcon.Close();
            }
            else
            {
                MessageBox.Show("Bağlantı açılamadı!!");
            }
        }
示例#6
0
        private string PromptForConnectionString(MetaConnection connection, string currentConnectionString, string initialConnectionString)
        {
            MSDASC.DataLinks dataLinks = new MSDASC.DataLinks();

            string generatedConnectionString = currentConnectionString;
            string resultConnectionString    = "";

            ADODB.Connection dialogConnection = (ADODB.Connection)dataLinks.PromptNew();
            if (dialogConnection != null)
            {
                connection.UserName       = "";
                connection.ClearPassword  = "";
                generatedConnectionString = dialogConnection.ConnectionString.ToString();

                if (dialogConnection.Properties["Password"] != null && dialogConnection.Properties["Password"].Value != null && !generatedConnectionString.Contains("Password="******";Password={0}", dialogConnection.Properties["Password"].Value);
                }

                foreach (string config in generatedConnectionString.Split(';'))
                {
                    if (config.StartsWith("User ID="))
                    {
                        connection.UserName = config.Replace("User ID=", "").Replace("\"", "");
                        continue;
                    }
                    if (config.StartsWith("Password="******"Password="******"");
                        continue;
                    }
                    if (resultConnectionString != "")
                    {
                        resultConnectionString += ";";
                    }
                    resultConnectionString += config;
                }

                if (!string.IsNullOrEmpty(connection.UserName) && string.IsNullOrEmpty(connection.ClearPassword))
                {
                    MessageBox.Show("Note that the Password is empty (Perhaps did you not check the option 'Allow Saving Password')", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                DatabaseType newType = GetDatabaseType(resultConnectionString);
                if (newType != connection.DatabaseType)
                {
                    connection.DatabaseType = newType;
                    MessageBox.Show(string.Format("The database type has been set to {0}", newType), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                resultConnectionString = initialConnectionString;
            }
            return(resultConnectionString);
        }
示例#7
0
 /// <summary>
 /// ConnectionString builder for source
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ConnectionStringSourceBtn_Click(object sender, EventArgs e)
 {
     object _con = null;
     MSDASC.DataLinks _link = new MSDASC.DataLinks();
     _con = _link.PromptNew();
     if (_con != null)
     {
         sourceConnectionString = ((ADODB.Connection)_con).ConnectionString;
     }
 }
示例#8
0
        private void button1_Click(object sender, EventArgs e)
        {
            ADODB.Connection conn  = new ADODB.Connection();
            object           oConn = (object)conn;

            MSDASC.DataLinks dlg = new MSDASC.DataLinks();
            dlg.PromptEdit(ref oConn);

            sourceConnection = conn.ConnectionString;
        }
示例#9
0
 private void brnCSDialog_Click(object sender, EventArgs e)
 {
     MSDASC.DataLinks  csDlg = new MSDASC.DataLinks();
     ADODB._Connection ADOCon;
     ADOCon     = (ADODB._Connection)csDlg.PromptNew();
     tbxCS.Text = (string)ADOCon.ConnectionString;
     if (ADOCon.State == 1)
     {
         ADOCon.Close();
     }
 }
        public void ShowConnectionBuilder()
        {
            var MSDASCObj  = new MSDASC.DataLinks();
            var connection = new ADODB.Connection();

            MSDASCObj.PromptEdit(connection);

            if (!string.IsNullOrEmpty(connection.ConnectionString))
            {
                ConnectionString.Text = connection.ConnectionString;
            }
        }
示例#11
0
        public void ChangeConnectionString()
        {
            MSDASC.DataLinks dlg = new MSDASC.DataLinks();
            object result = dlg.PromptNew();

            string connectionString = "";
            if (result != null) {
                ADODB.Connection adodbConn = (ADODB.Connection)result;
                connectionString = adodbConn.ConnectionString;
            }
            _Form.ConnectionString = connectionString;
        }
示例#12
0
文件: Util.cs 项目: rsdgjb/GRP
        public static void configGrReporting()
        {
            MSDASC.DataLinks dls = new MSDASC.DataLinks();
            ADODB.Connection conn = new ADODB.Connection();
            conn.ConnectionString = tempConnStr;

            Object obj = conn;
            //ADODB.Connection conn = dls.PromptNew();
            dls.PromptEdit(ref obj);

            tempConnStr = conn.ConnectionString;

            NotePad.runNotePad(tempConnStr);
        }
示例#13
0
        private string PromptForConnectionString(MetaConnection connection, string currentConnectionString, string initialConnectionString)
        {
            MSDASC.DataLinks dataLinks = new MSDASC.DataLinks();

            string generatedConnectionString = currentConnectionString;
            string resultConnectionString = "";

            ADODB.Connection dialogConnection = (ADODB.Connection)dataLinks.PromptNew();
            if (dialogConnection != null)
            {
                connection.UserName = "";
                connection.ClearPassword = "";
                generatedConnectionString = dialogConnection.ConnectionString.ToString();

                if (dialogConnection.Properties["Password"] != null && dialogConnection.Properties["Password"].Value != null && !generatedConnectionString.Contains("Password="******";Password={0}", dialogConnection.Properties["Password"].Value);
                }

                foreach (string config in generatedConnectionString.Split(';'))
                {
                    if (config.StartsWith("User ID="))
                    {
                        connection.UserName = config.Replace("User ID=", "").Replace("\"", "");
                        continue;
                    }
                    if (config.StartsWith("Password="******"Password="******"");
                        continue;
                    }
                    if (resultConnectionString != "") resultConnectionString += ";";
                    resultConnectionString += config;
                }

                if (!string.IsNullOrEmpty(connection.UserName) && string.IsNullOrEmpty(connection.ClearPassword)) MessageBox.Show("Note that the Password is empty (Perhaps did you not check the option 'Allow Saving Password')", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                DatabaseType newType = GetDatabaseType(resultConnectionString);
                if (newType != connection.DatabaseType)
                {
                    connection.DatabaseType = newType;
                    MessageBox.Show(string.Format("The database type has been set to {0}", newType), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                resultConnectionString = initialConnectionString;
            }
            return resultConnectionString;
        }
示例#14
0
 public static string GetConnectionStringDialog()
 {
     ADODB.Connection adoCon = new ADODB.Connection();
       object connection = (object)adoCon;
       MSDASC.DataLinks dlg = new MSDASC.DataLinks();
       if (dlg.PromptEdit(ref connection))
       {
     return adoCon.ConnectionString;
       }
       else
       {
     return String.Empty;
       }
 }
示例#15
0
        public static string GetConnectionStringDialog()
        {
            ADODB.Connection adoCon     = new ADODB.Connection();
            object           connection = (object)adoCon;

            MSDASC.DataLinks dlg = new MSDASC.DataLinks();
            if (dlg.PromptEdit(ref connection))
            {
                return(adoCon.ConnectionString);
            }
            else
            {
                return(String.Empty);
            }
        }
示例#16
0
        /// <summary>
        /// Displays a Connection String Builder (DataLinks) dialog.
        ///
        /// Credits:
        /// http://www.codeproject.com/cs/database/DataLinks.asp
        /// http://www.codeproject.com/cs/database/DataLinks.asp?df=100&forumid=33457&select=1560237#xx1560237xx
        ///
        /// Required COM references:
        /// %PROGRAMFILES%\Microsoft.NET\Primary Interop Assemblies\adodb.dll
        /// %PROGRAMFILES%\Common Files\System\Ole DB\OLEDB32.DLL
        /// </summary>
        /// <param name="currentConnectionString">Previous database connection string</param>
        /// <returns>Selected connection string</returns>
        private string PromptForConnectionString(string currentConnectionString)
        {
            MSDASC.DataLinks dataLinks = new MSDASC.DataLinksClass();
            ADODB.Connection dialogConnection;
            string           generatedConnectionString = string.Empty;

            if (currentConnectionString == String.Empty)
            {
                dialogConnection          = (ADODB.Connection)dataLinks.PromptNew();
                generatedConnectionString = dialogConnection.ConnectionString.ToString();
            }
            else
            {
                dialogConnection          = new ADODB.Connection();
                dialogConnection.Provider = "SQLOLEDB.1";
                ADODB.Property persistProperty = dialogConnection.Properties["Persist Security Info"];
                persistProperty.Value = true;

                dialogConnection.ConnectionString = currentConnectionString;
                dataLinks = new MSDASC.DataLinks();

                object objConn = dialogConnection;

                if (dataLinks.PromptEdit(ref objConn))
                {
                    generatedConnectionString = dialogConnection.ConnectionString.ToString();
                }
            }

            generatedConnectionString = generatedConnectionString.Replace("Provider=SQLOLEDB.1;", string.Empty);

            if
            (
                !generatedConnectionString.Contains("Integrated Security=SSPI") &&
                !generatedConnectionString.Contains("Trusted_Connection=True") &&
                !generatedConnectionString.Contains("Password="******"Pwd=")
            )
            {
                // BSG: Updated for null check on Value not only Password Property.
                if (dialogConnection.Properties["Password"].Value != null)
                {
                    generatedConnectionString += ";Password="******"Password"].Value.ToString();
                }
            }

            return(generatedConnectionString);
        }
        static public IConnection CreateFromDataConnectionLink()
        {
            ADODB._Connection AdoConnection;
            MSDASC.DataLinks  dataLink   = new MSDASC.DataLinks();
            IConnection       connection = null;

            AdoConnection = null;
            AdoConnection = (ADODB._Connection)dataLink.PromptNew();

            if ((AdoConnection != null) && (AdoConnection.ConnectionString != ""))
            {
                connection = CreateConnectionObject(AdoConnection.ConnectionString);
            }

            return(connection);
        }
        static public IConnection UpDateFromDataConnectionLink(IConnection oldConnection)
        {
            object AdoConnection;

            MSDASC.DataLinks dataLink   = new MSDASC.DataLinks();
            IConnection      connection = null;

            AdoConnection = new ADODB.Connection();
            (AdoConnection as ADODB.Connection).ConnectionString = oldConnection.ConnectionString;

            if (dataLink.PromptEdit(ref AdoConnection))
            {
                connection = CreateConnectionObject((AdoConnection as ADODB.Connection).ConnectionString);
            }

            return(connection);
        }
示例#19
0
        private void btn_crear_ocon_Click(object sender, EventArgs e)
        {
            MSDASC.DataLinks dataLinks = new MSDASC.DataLinks();

            ADODB._Connection connection;

            try
            {
                connection = (ADODB._Connection)dataLinks.PromptNew();

                this.txtCadConExt.Text = connection.ConnectionString.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
示例#20
0
文件: Conn.cs 项目: ABTecheg/GL
        private static bool CreateCon()
        {
            bool flage = false;

            while (true)
            {
                try
                {
                    try
                    {
                        mycon = new SqlConnection(con);
                    }
                    catch
                    {
                        con   = con.Remove(0, con.IndexOf(";") + 1);
                        mycon = new SqlConnection(con);
                    }
                    mycon.Open();
                    mycon.Close();
                    flage = true;
                    break;
                }
                catch
                {
                    ADODB.Connection adodbConnection =
                        new ADODB.Connection();
                    object connection = (object)adodbConnection;

                    MSDASC.DataLinks dlg = new MSDASC.DataLinks();
                    //dlg.PromptEdit(ref connection);
                    if (dlg.PromptEdit(ref connection))
                    {
                        con = adodbConnection.ConnectionString.ToString();
                    }
                    else
                    {
                        if (DialogResult.Yes == MessageBox.Show("The connection is field, Do you want exit program ?", "Installment Program", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            return(flage = false);
                        }
                    }
                }
            }

            return(flage);
        }
示例#21
0
 public static string GetConnectionString()
 {
     try
     {
         dynamic          _con  = null;
         MSDASC.DataLinks _link = new MSDASC.DataLinks();
         _con = _link.PromptNew();
         if (_con != null)
         {
             // sourceConnectionString = ((ADODB.Connection)_con).ConnectionString;
             return(_con.ConnectionString);
         }
     }
     catch (Exception)
     {
     }
     return(null);
 }
示例#22
0
        /// <summary>
        /// Prompts the user and gets a connection string.
        /// </summary>
        //public static string GetConnectionString(IWin32Window owner)
        //{
        //    return EditConnectionString(owner, string.Empty);
        //}
        /// <summary>
        /// Prompts the user and edits a connection string.
        /// </summary>
        public static string EditConnectionString(Window owner, string connString)
        {
            try
            {
                // create objects we'll need
                var dlinks = new MSDASC.DataLinks();
                var conn   = new ADODB.Connection();

                // sanity
                if (dlinks == null || conn == null)
                {
                    //Warning(owner, Properties.Resources.ErrDataLinks);
                    return(connString);
                }

                // initialize object
                if (!string.IsNullOrEmpty(connString))
                {
                    conn.ConnectionString = connString;
                }

                // show connection picker dialog
                object obj = conn;
                if (owner != null)
                {
                    dlinks.hWnd = (int)new WindowInteropHelper(owner).Handle;
                }
                if (dlinks.PromptEdit(ref obj))
                {
                    connString = conn.ConnectionString;
                }
            }
            catch (Exception x)
            {
                //Warning(owner, Properties.Resources.ErrConnectionString, x.Message);
            }

            // done
            return(connString);
        }
示例#23
0
文件: Util.cs 项目: rsdgjb/dbtool
 public static void configDataSet(DbName name, DbType type)
 {
     String key = getAppKey(name, type);
     if (name != DbName.WinCE)
     {
         Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
         MSDASC.DataLinks mydlg = new MSDASC.DataLinks();
         ADODB.Connection ADOcon = new ADODB.Connection();
         ADOcon.ConnectionString = config.AppSettings.Settings[key].Value;
         Dictionary<string, string> ht = splitConnectionString(ADOcon.ConnectionString);
         //Cast the generic object that PromptNew returns to an ADODB.Connection.
         //ADOcon = (ADODB.Connection)mydlg.PromptNew();
         Object obj = ADOcon;
         if (mydlg.PromptEdit(ref obj))
         {
             if (name == DbName.MySql)
                 config.AppSettings.Settings[key].Value = ADOcon.ConnectionString + ";Ip=" + ht["ip"];
             else
                 config.AppSettings.Settings[key].Value = ADOcon.ConnectionString;
             //调试的时候外部App.config文件不修改
             config.Save();
         }
     }
     else
     {
         Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
         String connectString = config.AppSettings.Settings[key].Value;
         Dictionary<string, string> ht = splitConnectionString(connectString);
         OpenFileDialog openFileDialog1 = new OpenFileDialog();
         openFileDialog1.FileName = "";
         openFileDialog1.Filter = "*.sdf | *.sdf";
         if (openFileDialog1.ShowDialog() == DialogResult.OK) {
             config.AppSettings.Settings[key].Value = "Persist Security Info = " + ht["persist security info"] + "; Password = '******'; Max Database Size = " + ht["max database size"] + "; Max Buffer Size = " + ht["max buffer size"] + ";Data Source='" + openFileDialog1.FileName + "'";
             config.Save();
         }
     }
 }
示例#24
0
        /// <summary>
        /// Задаёт строку соединения с базой и определяет версию SQL-сервера
        /// </summary>
        /// <returns>true - выполнена успешно; false - произошла ошибка</returns>
        /// <remarks>На машине пользователя должны быть установлены "Microsoft ActiveX Data... 2.7" и "Microsoft OLEDB 1.0 Service..." </remarks>
        public bool setConStr()
        {
            sqlVer = SqlVer.UNKNOWN;
            conStr = "";
            try
            {
                //нужно подключить Microsoft ActiveX Data... 2.7 и Microsoft OLEDB 1.0 Service..."
                MSDASC.DataLinks  conDlg = new MSDASC.DataLinks();
                ADODB._Connection adoCon = (ADODB._Connection)conDlg.PromptNew();
                if (adoCon == null)
                {
                    return(false);
                }
                conStr = adoCon.ConnectionString;
                //выясняем какая версия MS SQL Server используется
                if (conStr.IndexOf("SQLOLEDB") >= 0)
                {
                    sqlVer = SqlVer.MSSQL2000;
                }
                if (conStr.IndexOf("SQLNCLI") >= 0)
                {
                    sqlVer = SqlVer.MSSQL2005;
                }
                if (sqlVer == SqlVer.UNKNOWN)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                return(false);
            }

            return(true);
        }
		static public IConnection CreateFromDataConnectionLink()
		{
			ADODB._Connection AdoConnection;
			MSDASC.DataLinks dataLink = new MSDASC.DataLinks();
			IConnection connection = null;

			AdoConnection = null;
			AdoConnection = (ADODB._Connection)dataLink.PromptNew();

			if ((AdoConnection != null) && (AdoConnection.ConnectionString != ""))
			{
				connection = CreateConnectionObject(AdoConnection.ConnectionString);
			}

			return connection;
		}
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Queries data source (used system dialog).
        /// </summary>
        /// <param name="fromFile">Data source is file flag.</param>
        /// <param name="owner">Dialog owner (can be null).</param>
        /// <param name="type">Data source files filter type.</param>
        /// <returns>TRUE only if real DataSource selected.
        /// FALSE - error detected or cancel selected.</returns>
        /// <remarks>Recall supported.</remarks>
        public static bool QueryDataSource(bool fromFile, Window owner, FilterType type)
        {
            if (fromFile)
            {   // User select file
                // show Open File Dialog (NOTE: WPF not supported WinForms)
                var ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.RestoreDirectory = true;

                switch (type)
                {
                    case FilterType.AllSupported:
                        ofd.Filter = OPENFILE_DIALOG_FILTER_ALLTYPES;
                        ofd.FilterIndex = 8;
                        break;

                    case FilterType.WithoutShape:
                        ofd.Filter = OPENFILE_DIALOG_FILTER_WITHSHAPE;
                        ofd.FilterIndex = 7;
                        break;

                    case FilterType.OnlyShape:
                        ofd.Filter = OPENFILE_DIALOG_FILTER_ONLYSHAPE;
                        ofd.FilterIndex = 2;
                        break;

                    default:
                        Debug.Assert(false); // NOTE: not supported
                        break;
                }

                if (true != ofd.ShowDialog(owner)) // Result could be true, false, or null
                    return false;

                FilePath = ofd.FileName;
            }
            else
            {   // User select data source/server

                // Reference DataLinks
                // NOTE: Reference
                //    COM.Microsoft OLE DB Service Component 1.0 Type Library
                //    (Was MSDASC.dll)
                // SEE:
                //    http://support.microsoft.com:80/support/kb/articles/Q225/1/32.asp

                // show Data Links Properties dialog
                var dataLinks = new MSDASC.DataLinks();
                WindowInteropHelper helper = new WindowInteropHelper(owner);
                HwndSource _hwndSource = HwndSource.FromHwnd(helper.Handle);
                dataLinks.hWnd = (int)_hwndSource.Handle;
                var connection = dataLinks.PromptNew() as ADODB.Connection;
                if (null == connection)
                    return false;

                ConnectionString = connection.ConnectionString;
            }

            return true;
        }
示例#27
0
        private string PromptForConnectionString(MetaConnection connection, string currentConnectionString, string initialConnectionString)
        {
            // Try with DataConnectionDialog, but unable to select OleDbSource first... we keep MSDASC :-(
            //Update with VS 2017, still no easy/standard way to do it... we keep MSDASC :-(

            /*    DataConnectionDialog dcd = new DataConnectionDialog();
             *
             * DataSource.AddStandardDataSources(dcd);
             * dcd.SelectedDataSource = DataSource.OdbcDataSource;
             *
             * //            dcd.DataSources.Add(DataSource.OdbcDataSource);
             * //            dcd.DataSources.Add(DataSource.);
             *
             * if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
             * {
             * }
             *
             */
            MSDASC.DataLinks dataLinks = new MSDASC.DataLinks();

            string generatedConnectionString = currentConnectionString;
            string resultConnectionString    = "";

            ADODB.Connection dialogConnection = (ADODB.Connection)dataLinks.PromptNew();
            if (dialogConnection != null)
            {
                connection.UserName       = "";
                connection.ClearPassword  = "";
                generatedConnectionString = dialogConnection.ConnectionString.ToString();

                if (dialogConnection.Properties["Password"] != null && dialogConnection.Properties["Password"].Value != null && !generatedConnectionString.Contains("Password="******";Password={0}", dialogConnection.Properties["Password"].Value);
                }

                foreach (string config in generatedConnectionString.Split(';'))
                {
                    if (config.StartsWith("User ID="))
                    {
                        connection.UserName = config.Replace("User ID=", "").Replace("\"", "");
                        continue;
                    }
                    if (config.StartsWith("Password="******"Password="******"");
                        continue;
                    }
                    if (resultConnectionString != "")
                    {
                        resultConnectionString += ";";
                    }
                    resultConnectionString += config;
                }

                if (!string.IsNullOrEmpty(connection.UserName) && string.IsNullOrEmpty(connection.ClearPassword))
                {
                    MessageBox.Show("Note that the Password is empty (Perhaps did you not check the option 'Allow Saving Password')", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                DatabaseType newType = GetDatabaseType(resultConnectionString);
                if (newType != connection.DatabaseType)
                {
                    connection.DatabaseType = newType;
                    MessageBox.Show(string.Format("The database type has been set to {0}", newType), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                resultConnectionString = initialConnectionString;
            }
            return(resultConnectionString);
        }
示例#28
0
        private void toolStripButtonConnect_Click(object sender, EventArgs e)
        {
            MSDASC.DataLinks mydlg  = new MSDASC.DataLinks();
            CDataAdaHelper   OleCon = new CDataAdaHelper();

            ADODB._Connection ADOcon;
            bool bEdit = false;

            //OleCon.ConnectString = CAppOption.m_sDbConnectString;
            if (CAppOption.m_sDbConnectString == String.Empty)
            {
                try
                {
                    //Cast the generic object that PromptNew returns to an ADODB._Connection.
                    ADOcon = (ADODB._Connection)mydlg.PromptNew();
                    OleCon.ConnectString = ADOcon.ConnectionString;

                    bEdit = true;
                }
                catch (Exception ex)
                {
                    CGlobalInstance.Instance.WriteErrorLog(YyLogger.LogSeverity.error, "设置数据库连接", ex);
                }
            }
            else
            {
                ADOcon = new ADODB.ConnectionClass();
                ADOcon.ConnectionString = CAppOption.m_sDbConnectString;
                //set local COM compatible data type
                object oConnection = ADOcon;
                try
                {
                    //prompt user to edit the given connect string
                    if ((bool)mydlg.PromptEdit(ref oConnection))
                    {
                        //处理
                    }
                    OleCon.ConnectString = ADOcon.ConnectionString;

                    bEdit = true;
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("服务连接不成功,请重新设置连接!");
                    CGlobalInstance.Instance.WriteErrorLog(YyLogger.LogSeverity.error, "设置数据库连接", ex);
                }
            }

            if (bEdit == true)
            {
                try
                {
                    //OleCon.Db.Open();
                    OleCon.Open();

                    if (OleCon.IsOpen)
                    {
                        CAppOption.m_sDbConnectString = OleCon.ConnectString;
                        //OleCon.Db.Close();
                        OleCon.Close();


                        CGlobalInstance.Instance.DbAdaHelper.ConnectString = CAppOption.m_sDbConnectString;
                        CAppOption.SaveData();
                    }
                    else
                    {
                        MessageBox.Show("连接无效,无法连接数据库");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接无效,无法连接数据库(注意请选择允许保存密码)!");
                    CGlobalInstance.Instance.WriteErrorLog(YyLogger.LogSeverity.error, "设置数据库连接", ex);
                }
            }
        }
示例#29
0
 // http://stackoverflow.com/questions/2205993/winforms-connection-properties-dialog-for-configuration-string
 private string getConnectionString()
 {
     string strConnString = "";
     object _con = null;
     MSDASC.DataLinks _link = new MSDASC.DataLinks();
     _con = _link.PromptNew();
     if (_con == null)
     {
         strConnString = string.Empty;
     }
     else
     {
         strConnString = ((ADODB.Connection)_con).ConnectionString;
     }
     return strConnString;
 }
		static public IConnection UpDateFromDataConnectionLink(IConnection oldConnection)
		{
			object AdoConnection;
			MSDASC.DataLinks dataLink = new MSDASC.DataLinks();
			IConnection connection = null;

			AdoConnection = new ADODB.Connection();
			(AdoConnection as ADODB.Connection).ConnectionString = oldConnection.ConnectionString;

			if (dataLink.PromptEdit(ref AdoConnection))
			{
				connection = CreateConnectionObject((AdoConnection as ADODB.Connection).ConnectionString);
			}

			return connection;
		}
示例#31
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Queries data source (used system dialog).
        /// </summary>
        /// <param name="fromFile">Data source is file flag.</param>
        /// <param name="owner">Dialog owner (can be null).</param>
        /// <param name="type">Data source files filter type.</param>
        /// <returns>TRUE only if real DataSource selected.
        /// FALSE - error detected or cancel selected.</returns>
        /// <remarks>Recall supported.</remarks>
        static public bool QueryDataSource(bool fromFile, Window owner, FilterType type)
        {
            if (fromFile)
            {   // User select file
                // show Open File Dialog (NOTE: WPF not supported WinForms)
                var ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.RestoreDirectory = true;

                switch (type)
                {
                case FilterType.AllSupported:
                    ofd.Filter      = OPENFILE_DIALOG_FILTER_ALLTYPES;
                    ofd.FilterIndex = 8;
                    break;

                case FilterType.WithoutShape:
                    ofd.Filter      = OPENFILE_DIALOG_FILTER_WITHSHAPE;
                    ofd.FilterIndex = 7;
                    break;

                case FilterType.OnlyShape:
                    ofd.Filter      = OPENFILE_DIALOG_FILTER_ONLYSHAPE;
                    ofd.FilterIndex = 2;
                    break;

                default:
                    Debug.Assert(false);     // NOTE: not supported
                    break;
                }

                if (true != ofd.ShowDialog(owner)) // Result could be true, false, or null
                {
                    return(false);
                }

                FilePath = ofd.FileName;
            }
            else
            {   // User select data source/server
                // Reference DataLinks
                // NOTE: Reference
                //    COM.Microsoft OLE DB Service Component 1.0 Type Library
                //    (Was MSDASC.dll)
                // SEE:
                //    http://support.microsoft.com:80/support/kb/articles/Q225/1/32.asp

                // show Data Links Properties dialog
                var dataLinks = new MSDASC.DataLinks();
                WindowInteropHelper helper      = new WindowInteropHelper(owner);
                HwndSource          _hwndSource = HwndSource.FromHwnd(helper.Handle);
                dataLinks.hWnd = (int)_hwndSource.Handle;
                var connection = dataLinks.PromptNew() as ADODB.Connection;
                if (null == connection)
                {
                    return(false);
                }

                ConnectionString = connection.ConnectionString;
            }

            return(true);
        }
示例#32
0
        /// <summary>
        /// Displays a Connection String Builder (DataLinks) dialog.
        /// 
        /// Credits:
        /// http://www.codeproject.com/cs/database/DataLinks.asp
        /// http://www.codeproject.com/cs/database/DataLinks.asp?df=100&forumid=33457&select=1560237#xx1560237xx
        /// 
        /// Required COM references:
        /// %PROGRAMFILES%\Microsoft.NET\Primary Interop Assemblies\adodb.dll
        /// %PROGRAMFILES%\Common Files\System\Ole DB\OLEDB32.DLL
        /// </summary>
        /// <param name="currentConnectionString">Previous database connection string</param>
        /// <returns>Selected connection string</returns>
        private string PromptForConnectionString(string currentConnectionString)
        {
            MSDASC.DataLinks dataLinks = new MSDASC.DataLinksClass();
            ADODB.Connection dialogConnection;
            string generatedConnectionString = string.Empty;

            if (currentConnectionString == String.Empty)
            {
                dialogConnection = (ADODB.Connection)dataLinks.PromptNew();
                generatedConnectionString = dialogConnection.ConnectionString.ToString();
            }
            else
            {
                dialogConnection = new ADODB.Connection();
                dialogConnection.Provider = "SQLOLEDB.1";
                ADODB.Property persistProperty = dialogConnection.Properties["Persist Security Info"];
                persistProperty.Value = true;

                dialogConnection.ConnectionString = currentConnectionString;
                dataLinks = new MSDASC.DataLinks();

                object objConn = dialogConnection;
                if (dataLinks.PromptEdit(ref objConn))
                {
                    generatedConnectionString = dialogConnection.ConnectionString.ToString();
                }
                else
                {
                    return currentConnectionString;
                }
            }
            generatedConnectionString = generatedConnectionString.Replace("Provider=SQLOLEDB.1;", string.Empty);
            if (
                    !generatedConnectionString.Contains("Integrated Security=SSPI")
                    && !generatedConnectionString.Contains("Trusted_Connection=True")
                    && !generatedConnectionString.Contains("Password="******"Pwd=")
                )
            {
                if (dialogConnection.Properties["Password"] != null)
                    generatedConnectionString += ";Password="******"Password"].Value;
            }

            return generatedConnectionString;
        }