コード例 #1
0
        public static OdbcConnectionStringBuilder ConnectionString(string pathToDB)
        {
            OdbcConnectionStringBuilder cs = new OdbcConnectionStringBuilder();

            cs.Driver = "Microsoft Access Driver (*.mdb)";
            cs.Add("Dbq", pathToDB);
            cs.Add("Uid", "Admin");
            cs.Add("Pwd", "");
            return(cs);
        }
        public void Indexer_Keyword_Invalid()
        {
            string [] invalid_keywords = new string []
            {
                string.Empty,
                " ",
                " abc",
                "abc ",
                "\r",
                "ab\rc",
                ";abc",
                "a\0b"
            };

            OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

            for (int i = 0; i < invalid_keywords.Length; i++)
            {
                string keyword = invalid_keywords [i];
                try
                {
                    builder [keyword] = "abc";
                    Assert.Fail("#A1:" + i);
                }
                catch (ArgumentException ex)
                {
                    // Invalid keyword, contain one or more of 'no characters',
                    // 'control characters', 'leading or trailing whitespace'
                    // or 'leading semicolons'
                    Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#A2:" + i);
                    Assert.IsNull(ex.InnerException, "#A3:" + i);
                    Assert.IsNotNull(ex.Message, "#A4:" + i);
                    Assert.IsTrue(ex.Message.IndexOf("'" + keyword + "'") == -1, "#A5:" + i);
                    Assert.AreEqual(keyword, ex.ParamName, "#A6:" + i);
                }

                builder [keyword] = null;
                Assert.IsFalse(builder.ContainsKey(keyword), "#B");

                try
                {
                    object value = builder [keyword];
                    Assert.Fail("#C1:" + value + " (" + i + ")");
                }
                catch (ArgumentException ex)
                {
                    // Keyword not supported: '...'
                    Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#C2:" + i);
                    Assert.IsNull(ex.InnerException, "#C3:" + i);
                    Assert.IsNotNull(ex.Message, "#C4:" + i);
                    Assert.IsTrue(ex.Message.IndexOf("'" + keyword + "'") != -1, "#C5:" + i);
                    Assert.IsNull(ex.ParamName, "#C6:" + i);
                }
            }
        }
コード例 #3
0
ファイル: QuoteNeeded.cs プロジェクト: jhanisch/JUST-PO
        private static void ProcessQuotesNeeded()
        {
            OdbcConnection cn;
            var            notifiedlist = new ArrayList();

            // user_1 = receiving rack location
            // user_2 = Receiver
            // user_3 = Received Date
            // user_4 = Bin Cleared Date
            // user_5 = Notified
            //                POQuery = "Select icpo.buyer, icpo.ponum, icpo.user_1, icpo.user_2, icpo.user_3, icpo.user_4, icpo.user_5, icpo.defaultjobnum, vendor.name as vendorName, icpo.user_6, icpo.defaultworkorder, icpo.attachid from icpo inner join vendor on vendor.vennum = icpo.vennum where icpo.user_3 is not null and icpo.user_5 = 0 order by icpo.ponum asc";

            OdbcConnectionStringBuilder just = new OdbcConnectionStringBuilder
            {
                Driver = "ComputerEase"
            };

            just.Add("Dsn", "Company 0");
            just.Add("Uid", config.Uid);
            just.Add("Pwd", config.Pwd);

            cn = new OdbcConnection(just.ConnectionString);
            cn.Open();
            log.Info("[ProcessQuotesNeeded] Connection to database opened successfully");
            var dbRepository = new DatabaseRepository(cn, log, null);


            var x = dbRepository.GetQuotesNeeded();

            log.Info("[ProcessQuotesNeeded] Found " + x.Count.ToString() + " quotes to notify");
            var hvacQuotes     = x.FindAll(q => q.WorkOrder.StartsWith("H"));
            var plumbingQuotes = x.FindAll(q => !q.WorkOrder.StartsWith("H"));

            log.Info("[ProcessQuotesNeeded] Found " + hvacQuotes.Count.ToString() + " HVAC quotes to notify");
            log.Info("[ProcessQuotesNeeded] Found " + plumbingQuotes.Count.ToString() + " Plumbing quotes to notify");

            var emailSubject = string.Format(EmailSubject, RunDate);

            if (Utils.sendEmail(config, config.PlumbingEmailAddresses, emailSubject, FormatEmailBody(plumbingQuotes, dbRepository, DefaultPlumbingMessage)))
            {
                foreach (Quote quote in hvacQuotes)
                {
                    dbRepository.MarkQuoteAsNotified(quote);
                }
            }

            if (Utils.sendEmail(config, config.HVACEmailAddresses, emailSubject, FormatEmailBody(hvacQuotes, dbRepository, DefaultHVACMessage)))
            {
                foreach (Quote quote in plumbingQuotes)
                {
                    dbRepository.MarkQuoteAsNotified(quote);
                }
            }
        }
コード例 #4
0
        public ODBCLog(SessionSettings settings, SessionID sessionID)
        {
            _sessionID       = sessionID;
            _sessionSettings = settings;

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_USER))
            {
                _user = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_USER);
            }

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_PASSWORD))
            {
                _pwd = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_PASSWORD);
            }

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_INCOMING_TABLE))
            {
                incomingTable = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_INCOMING_TABLE);
            }

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_INCOMING_BACKUP_TABLE))
            {
                incomingBackupTable = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_INCOMING_BACKUP_TABLE);
            }

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_OUTGOING_TABLE))
            {
                outgoingTable = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_OUTGOING_TABLE);
            }

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_OUTGOING_BACKUP_TABLE))
            {
                outgoingBackupTable = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_OUTGOING_BACKUP_TABLE);
            }

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_EVENT_TABLE))
            {
                eventTable = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_EVENT_TABLE);
            }

            if (_sessionSettings.Get(sessionID).Has(SessionSettings.ODBC_LOG_EVENT_BACKUP_TABLE))
            {
                eventBackupTable = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_EVENT_BACKUP_TABLE);
            }

            _connectionString = _sessionSettings.Get(sessionID).GetString(SessionSettings.ODBC_LOG_CONNECTION_STRING);


            OdbcConnectionStringBuilder sb = new OdbcConnectionStringBuilder(_connectionString);

            sb["UID"] = _user;
            sb["PWD"] = _pwd;
            OdbcConnection odbc = GetODBCConnection();
        }
コード例 #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Database"/> class.
 ///     If you want to use ODBC  use this constructor.
 /// </summary>
 /// <param name="dsn">
 /// System or user DNS.
 /// </param>
 /// <param name="user">
 /// Username used for Identification.
 /// </param>
 /// <param name="password">
 /// Password for the user.
 /// </param>
 public Database(string dsn, string user, string password)
 {
     this.ConnectionType   = ConnType.ODBC;
     this.DatabaseUser     = user;
     this.DatabasePassword = password;
     this.strDsn           = dsn;
     this.connectionStringBuilderForOdbc     = new OdbcConnectionStringBuilder();
     this.connectionStringBuilderForOdbc.Dsn = dsn;
     this.connectionStringBuilderForOdbc.Add("UID", user);
     this.connectionStringBuilderForOdbc.Add("PWD", password);
 }
コード例 #6
0
        private OdbcConnection GetODBCConnection()
        {
            OdbcConnectionStringBuilder sb = new OdbcConnectionStringBuilder(_connectionString);

            sb["UID"] = _user;
            sb["PWD"] = _pwd;
            OdbcConnection odbc = new OdbcConnection(sb.ConnectionString);

            odbc.Open();
            return(odbc);
        }
コード例 #7
0
    static void Main()
    {
        OdbcConnectionStringBuilder builder =
            new OdbcConnectionStringBuilder();

        builder.Driver = "Microsoft Access Driver (*.mdb)";

        // Call the Add method to explicitly add key/value
        // pairs to the internal collection.
        builder.Add("Dbq", "C:\\info.mdb");
        builder.Add("Uid", "Admin");
        builder.Add("Pwd", "pass!word1");

        Console.WriteLine(builder.ConnectionString);
        Console.WriteLine();

        // Clear current values and reset known keys to their
        // default values.
        builder.Clear();

        // Pass the OdbcConnectionStringBuilder an existing
        // connection string, and you can retrieve and
        // modify any of the elements.
        builder.ConnectionString =
            "driver={IBM DB2 ODBC DRIVER};Database=SampleDB;" +
            "hostname=SampleServerName;port=SamplePortNum;" +
            "protocol=TCPIP;uid=Admin;pwd=pass!word1";

        Console.WriteLine("protocol = "
                          + builder["protocol"].ToString());
        Console.WriteLine();

        // Modify existing items.
        builder["uid"] = "NewUser";
        builder["pwd"] = "Pass@word2";

        // Call the Remove method to remove items from
        // the collection of key/value pairs.
        builder.Remove("port");

        // Note that calling Remove on a nonexistent item does not
        // throw an exception.
        builder.Remove("BadItem");
        Console.WriteLine(builder.ConnectionString);
        Console.WriteLine();

        // Setting the indexer adds the associated value, if
        // necessary.
        builder["NewKey"] = "newValue";
        Console.WriteLine(builder.ConnectionString);

        Console.WriteLine("Press Enter to finish.");
        Console.ReadLine();
    }
コード例 #8
0
        //get ODBC Connection String from configation file
        private string getConnStr()
        {
            OdbcConnectionStringBuilder ConnStr = new OdbcConnectionStringBuilder();

            config.init();                                        //Initialized config class
            ConnStr.Add("Driver", config.getValue("Driver"));     // read ODBC Driver
            ConnStr.Add("server", config.getValue("Server"));     // read database server
            ConnStr.Add("database", config.getValue("Database")); // read database name
            ConnStr.Add("uid", config.getValue("User"));          // read database user
            ConnStr.Add("password", config.getValue("Password")); //read database password
            return(ConnStr.ConnectionString.ToString());
        }
コード例 #9
0
    private DbConnection GetConnection(TimeSpan testConnectionTimeout)
    {
        var odbcBuilder = new OdbcConnectionStringBuilder {
            Dsn = ConnectionString.Value
        };
        var connectionString = odbcBuilder.ConnectionString;
        var odbcConn         = new OdbcConnection(connectionString)
        {
        };

        return(odbcConn);
    }
コード例 #10
0
ファイル: Form1.cs プロジェクト: PingSharp/fernSchule_CSharp
        public MySqlAbfrage()
        {
            InitializeComponent();

            this.odbcconnection = new OdbcConnection();

            OdbcConnectionStringBuilder A = new OdbcConnectionStringBuilder();

            A.Dsn = "LocalMySQL56";

            odbcconnection.ConnectionString = A.ConnectionString;
        }
コード例 #11
0
        public void ConnectionString()
        {
            OdbcConnectionStringBuilder builder;

            builder = new OdbcConnectionStringBuilder(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Northwind.mdb;Jet OLEDB:System Database=|DataDirectory|\System.mdw;");
            Assert.AreEqual("Microsoft.Jet.OLEDB.4.0", builder ["Provider"], "#A1");
            Assert.AreEqual(@"|DataDirectory|\Northwind.mdb", builder ["Data Source"], "#A2");
            Assert.AreEqual(@"|DataDirectory|\System.mdw", builder ["Jet OLEDB:System Database"], "#A3");

            builder = new OdbcConnectionStringBuilder();
            builder ["Data SourcE"]         = "(local)";
            builder ["Integrated SecuritY"] = true;
            builder.Driver = "SQL Server";
            builder ["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
            Assert.AreEqual("Driver={SQL Server};Data SourcE=(local);Integrated SecuritY=True;Initial Catalog={AdventureWorks;NewValue=Bad}",
                            builder.ConnectionString, "#B");

            builder = new OdbcConnectionStringBuilder();
            builder ["Integrated SecuritY"] = false;
            builder.Driver              = "SQL Server";
            builder ["Data SourcE"]     = "mother";
            builder ["Initial Catalog"] = "AdventureWorks;NewValue=OK";
            Assert.AreEqual("Driver={SQL Server};Integrated SecuritY=False;Data SourcE=mother;Initial Catalog={AdventureWorks;NewValue=OK}",
                            builder.ConnectionString, "#C");

            builder = new OdbcConnectionStringBuilder();
            builder ["Initial Catalog"] = "AdventureWorks;NewValue=OK";
            builder.Driver          = "SQL Server";
            builder.Dsn             = "NorthWind";
            builder ["Data Source"] = "mother";
            Assert.AreEqual("Dsn=NorthWind;Driver={SQL Server};Initial Catalog={AdventureWorks;NewValue=OK};Data Source=mother",
                            builder.ConnectionString, "#D1");
            builder.Driver = string.Empty;
            Assert.AreEqual("Dsn=NorthWind;Driver=;Initial Catalog={AdventureWorks;NewValue=OK};Data Source=mother",
                            builder.ConnectionString, "#D2");

            builder            = new OdbcConnectionStringBuilder();
            builder ["Driver"] = "MySQL";
            builder.Driver     = "SQL Server";
            builder.Dsn        = "NorthWind";
            builder ["Dsn"]    = "AdventureWorks";
            Assert.AreEqual("Dsn=AdventureWorks;Driver={SQL Server}", builder.ConnectionString, "#E1");
            builder ["Dsn"] = string.Empty;
            Assert.AreEqual("Dsn=;Driver={SQL Server}", builder.ConnectionString, "#E2");

            builder = new OdbcConnectionStringBuilder(@"Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\bin\book1.xls");
            Assert.AreEqual("{Microsoft Excel Driver (*.xls)}", builder ["Driver"], "#F1");
            Assert.AreEqual(@"c:\bin\book1.xls", builder ["DBQ"], "#F2");

            builder = new OdbcConnectionStringBuilder(@"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=c:\bin");
            Assert.AreEqual("{Microsoft Text Driver (*.txt; *.csv)}", builder ["Driver"], "#G1");
            Assert.AreEqual(@"c:\bin", builder ["DBQ"], "#G2");
        }
コード例 #12
0
        /// <inheritdoc/>
        protected override string GetConnectionStringWithLoginInfo(string userName, string password)
        {
            OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder(ConnectionString);

            builder.Remove("uid");
            builder.Add("uid", userName);

            builder.Remove("pwd");
            builder.Add("pwd", password);

            return(builder.ToString());
        }
コード例 #13
0
        /// <summary>
        /// Defines the Connection as an OdbcConnection object.
        /// </summary>
        /// <param name="directoryPath"></param>
        public IDbConnection SetOdbcConnection(string directoryPath)
        {
            var builder = new OdbcConnectionStringBuilder {
                Driver = "{Microsoft Text Driver (*.txt; *.csv)}"
            };

            builder.Add("Dbq", directoryPath);
            builder.Add("Extensions", "asc,csv,tab,txt");
            builder.Add("Persist Security Info", "False");

            Connection = new OdbcConnection(builder.ConnectionString);
            return(Connection);
        }
コード例 #14
0
ファイル: source.cs プロジェクト: zhimaqiao51/docs
    private static void DumpBuilderContents(string connectString)
    {
        OdbcConnectionStringBuilder builder =
            new OdbcConnectionStringBuilder(connectString);

        Console.WriteLine("=================");
        Console.WriteLine("Original connectString   = " + connectString);
        Console.WriteLine("builder.ConnectionString = " + builder.ConnectionString);
        foreach (string key in builder.Keys)
        {
            Console.WriteLine(key + "=" + builder[key].ToString());
        }
    }
コード例 #15
0
        public void FillPostBuildTable(string query)
        {
            query = query.Replace("{sc}", schemaName);
            var sqlConnectionStringBuilder = new OdbcConnectionStringBuilder(connectionString);

            using (var connection = SqlConnectionHelper.OpenOdbcConnection(sqlConnectionStringBuilder.ConnectionString))
            {
                using (var command = new OdbcCommand(query, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
コード例 #16
0
 static void TryRemove(OdbcConnectionStringBuilder builder,
                       string itemToRemove)
 {
     if (builder.Remove(itemToRemove))
     {
         Console.WriteLine("Removed '{0}'", itemToRemove);
     }
     else
     {
         Console.WriteLine("Unable to remove '{0}'", itemToRemove);
     }
     Console.WriteLine(builder.ConnectionString);
 }
コード例 #17
0
        private string GenerateConnectionString()
        {
            var builder = new OdbcConnectionStringBuilder
            {
                Dsn = "MS Access Database",
            };

            builder.Add("Dbq", DatabaseFile);
            builder.Add("Uid", "Admin");
            builder.Add("Pwd", Password);

            return(builder.ConnectionString);
        }
コード例 #18
0
ファイル: Connection.cs プロジェクト: easywon/personal_test
        // Create a connection to the SQL server
        public IDbConnection sqlSocket()
        {
            OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

            builder.Driver = "SQL Server";
            builder.Add("Server", "cougar5");
            builder.Add("Database", "SANDBOXMODEL_PETER");
            builder.Add("Trusted_Connection", "Yes");

            IDbConnection socket = new OdbcConnection(builder.ConnectionString);

            return(socket);
        }
コード例 #19
0
ファイル: Services.cs プロジェクト: rprudnikov-itrf/rosbuh
        public БанкСведения[] ПоискБанка(string БИК)
        {
            //SELECT        VKEY, `REAL`, PZN, UER, RGN, IND, TNP, NNP, ADR, RKC, NAMEP, NAMEN, NEWNUM, NEWKS, PERMFO, SROK, AT1, AT2, TELEF, REGN, OKPO, DT_IZM,
            //              CKS, KSNP, DATE_IN, DATE_CH, VKEYDEL
            //FROM            bnkseek
            //where NEWNUM = @bik

            var list          = new List <БанкСведения>();
            var stringBuilder = new OdbcConnectionStringBuilder(System.Configuration.ConfigurationManager.ConnectionStrings["БазаДанныхБанков"].ConnectionString)
            {
                Driver = "Microsoft dBASE Driver (*.dbf)"
            };

            using (var connection = new OdbcConnection(stringBuilder.ToString()))
            {
                var command = connection.CreateCommand();
                command.CommandText = string.Format("SELECT * FROM bnkseek.dbf WHERE NEWNUM = '{0}'", БИК);
                command.CommandType = CommandType.Text;

                try
                {
                    if (((command.Connection.State & System.Data.ConnectionState.Open) != System.Data.ConnectionState.Open))
                    {
                        command.Connection.Open();
                    }

                    using (OdbcDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            list.Add(new БанкСведения()
                            {
                                Название = Convert.ToString(reader["NAMEP"]),
                                КорСчет  = Convert.ToString(reader["KSNP"]),
                                БИК      = Convert.ToString(reader["NEWNUM"]),
                                Адрес    = Convert.ToString(reader["ADR"]),
                                Город    = Convert.ToString(reader["NNP"])
                            });
                        }
                    }
                }
                finally
                {
                    if ((command.Connection.State == System.Data.ConnectionState.Closed))
                    {
                        command.Connection.Close();
                    }
                }
            }
            return(list.ToArray());
        }
        private static string BuildConnectionString(SqlPassContext context)
        {
            OdbcConnectionStringBuilder connectionStringBuilder = new OdbcConnectionStringBuilder
            {
                Driver = context.Driver,
            };

            connectionStringBuilder.Add("Server", context.Server);
            connectionStringBuilder.Add("Database", context.Database);
            connectionStringBuilder.Add("User ID", context.UserId);
            connectionStringBuilder.Add("Password", context.Password);
            connectionStringBuilder.Add("Trusted_Connection", context.TrustedConnection);
            return(connectionStringBuilder.ConnectionString);
        }
        public string GetConnectionString()
        {
            try
            {
                OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();
                builder.ConnectionString = tbConnectionString.Text;
                _connectionString        = builder.ConnectionString;
            }
            catch
            {
            }

            return(_connectionString);
        }
コード例 #22
0
        private void btnAdvanced_Click(object sender, EventArgs e)
        {
            using (AdvancedConnectionPropertiesForm form = new AdvancedConnectionPropertiesForm())
            {
                OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder(ConnectionString);
                builder.BrowsableConnectionString = false;
                form.AdvancedProperties           = builder;

                if (form.ShowDialog() == DialogResult.OK)
                {
                    ConnectionString = form.AdvancedProperties.ToString();
                }
            }
        }
コード例 #23
0
        public void Remove_Keyword_Null()
        {
            OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

            try {
                builder.Remove(null);
                Assert.Fail("#1");
            } catch (ArgumentNullException ex) {
                Assert.AreEqual(typeof(ArgumentNullException), ex.GetType(), "#2");
                Assert.IsNull(ex.InnerException, "#3");
                Assert.IsNotNull(ex.Message, "#4");
                Assert.AreEqual("keyword", ex.ParamName, "#5");
            }
        }
コード例 #24
0
        public void Dsn_Value_Null()
        {
            OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

            try {
                builder.Dsn = null;
                Assert.Fail("#1");
            } catch (ArgumentNullException ex) {
                Assert.AreEqual(typeof(ArgumentNullException), ex.GetType(), "#2");
                Assert.IsNull(ex.InnerException, "#3");
                Assert.IsNotNull(ex.Message, "#4");
                Assert.AreEqual("Dsn", ex.ParamName, "#5");
            }
        }
コード例 #25
0
        public OdbcConnectionTest()
        {
            odbcconnection = new OdbcConnection();

            //List<string> MYTries = new List<string>();

            OdbcConnectionStringBuilder A = new OdbcConnectionStringBuilder();

            A.Driver = "MySQL ODBC 3.51 Driver;";
            A.Dsn    = "LocalMySQL56";
            //odbcconnection.ConnectionTimeout = 30;

            //A.Driver = "DRIVER={MySQL ODBC 5.2 ANSI Driver};";
            ////A.


            //MYTries.Add("Provider=MSDASQL;Driver={MySQL ODBC 5.2 ANSI Driver};Server=localhost;PORT = 3306" + "DATABASE = dbdemo2;UID = demo-user");
            //MYTries.Add("Driver={MySQL ODBC 5.2 ANSI Driver};Server=localhost;PORT = 3306;Database = dbdemo2; UID = demo-user ");


            /*
             * for (int idx = 0; idx < MYTries.Count; idx++)
             * {
             *  odbcconnection.ConnectionString = MYTries[idx];
             * }
             */
            odbcconnection.ConnectionString = "Dsn=LocalMySQL56;Driver=MySQL ODBC 3.51 Driver;"; // A.ConnectionString;

            string newLine = Environment.NewLine;

            try
            {
                odbcconnection.Open();
                MessageBox.Show("Die Verbindung wurde" + "erfolgreich hergestellt" +
                                newLine + "Server Version:" + odbcconnection.ServerVersion + newLine
                                + "Datenquelle:" + odbcconnection.DataSource + newLine + "Datenbank:"
                                + odbcconnection.Database + newLine +
                                "Connectiontimeout:" + odbcconnection.ConnectionTimeout);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + newLine + "Bitte ConnectionString-Parameter überprüfen");
            }
            finally
            {
                odbcconnection.Close();
                Console.WriteLine("Verbindung geschlossen");
            }
        }
コード例 #26
0
        private string CreateOdbcConnectionString(string userName, string password, string dataSource, string databaseName)
        {
            string serverName = GetServerName(dataSource);

            OdbcConnectionStringBuilder connectionStringBuilder = new OdbcConnectionStringBuilder
            {
                Driver = "SQL Server Native Client 11.0",
            };

            connectionStringBuilder["Server"]   = "tcp:" + dataSource;
            connectionStringBuilder["Database"] = databaseName;
            connectionStringBuilder["Uid"]      = userName + "@" + serverName;
            connectionStringBuilder["Pwd"]      = password;
            return(connectionStringBuilder.ConnectionString);
        }
コード例 #27
0
        public void Clear()
        {
            OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

            builder ["Dbq"] = "C:\\Data.xls";
            builder.Driver  = "SQL Server";
            builder.Dsn     = "AdventureWorks";
            builder.Add("Port", "56");
            builder.Clear();
            Assert.AreEqual(string.Empty, builder.ConnectionString, "#1");
            Assert.IsFalse(builder.ContainsKey("Dbq"), "#2");
            Assert.AreEqual(string.Empty, builder.Driver, "#3");
            Assert.AreEqual(string.Empty, builder.Dsn, "#4");
            Assert.IsFalse(builder.ContainsKey("Port"), "#5");
        }
コード例 #28
0
ファイル: TabPlayForm.cs プロジェクト: pjflip/TabPlay
        private void TabPlayForm_Load(object sender, EventArgs e)
        {
            Text = $"TabPlayStarter - Version {Assembly.GetExecutingAssembly().GetName().Version}";

            string argsString = "";

            string[] arguments = Environment.GetCommandLineArgs();

            // Parse command line args correctly to get DB path
            foreach (string s in arguments)
            {
                argsString = argsString + s + " ";
            }
            arguments = argsString.Split(new Char[] { '/' });
            foreach (string s in arguments)
            {
                if (s.StartsWith("f:["))
                {
                    pathToDB = s.Split(new char[] { '[', ']' })[1];
                    break;
                }
            }

            OdbcConnectionStringBuilder connectionString = null;

            if (pathToDB != "")
            {
                connectionString = Database.ConnectionString(pathToDB);
            }
            if (!Database.Initialize(connectionString))
            {
                AddDatabaseFileButton.Visible = true;   // No valid database in arguments
            }
            else
            {
                HandsList handsList = new HandsList(connectionString);
                if (handsList.Count == 0)
                {
                    PathToHandRecordFileLabel.Text  = "Please add a hand record (.pbn) file";
                    AddHandRecordFileButton.Visible = true;    // No hand records in database, so let user add them
                }
                else
                {
                    PathToHandRecordFileLabel.Text = "Included in Scoring Database";
                    StartSession();
                }
            }
        }
コード例 #29
0
        /// <summary>
        /// Converts ODBC connection string to the SQL Client (.NET).
        /// </summary>
        public static string OdbcToSqlClient(this string odbcString)
        {
            if (string.IsNullOrEmpty(odbcString))
            {
                return(null);
            }
            try {
                var odbc     = new OdbcConnectionStringBuilder(odbcString);
                var server   = odbc.GetValue(OdbcServerKey);
                var database = odbc.GetValue(OdbcDatabaseKey);
                if (!string.IsNullOrWhiteSpace(server) && !string.IsNullOrWhiteSpace(database))
                {
                    var sql = new SqlConnectionStringBuilder {
                        DataSource     = server,
                        InitialCatalog = database,
                    };

                    var userId = odbc.GetValue(OdbcUidKey);
                    if (!string.IsNullOrEmpty(userId))
                    {
                        sql.UserID = odbc.GetValue(OdbcUidKey);
                    }

                    var password = odbc.GetValue(OdbcPasswordKey);
                    if (!string.IsNullOrEmpty(password))
                    {
                        sql.Password = password;
                    }

                    // If no password and user name, assume integrated authentication
                    sql.IntegratedSecurity     = string.IsNullOrEmpty(sql.UserID) && string.IsNullOrEmpty(sql.Password);
                    sql.TrustServerCertificate = string.Compare(odbc.GetValue(OdbcTrustServerCertificateKey), "yes", StringComparison.OrdinalIgnoreCase) == 0;

                    // Translate authentication method
                    if (odbc.ContainsKey(OdbcAuthenticationKey))
                    {
                        SqlAuthenticationMethod authMethod;
                        if (Enum.TryParse(odbc.GetValue(OdbcAuthenticationKey), out authMethod))
                        {
                            sql.Authentication = authMethod;
                        }
                    }

                    return(sql.ConnectionString);
                }
            } catch (ArgumentException) { }
            return(null);
        }
コード例 #30
0
        public override ISaver Create(string connectionString)
        {
            var odbcConnection = new OdbcConnectionStringBuilder(connectionString);
            var sqlConnection  = new SqlConnectionStringBuilder();

            sqlConnection["Data Source"]     = odbcConnection["server"];
            sqlConnection["Initial Catalog"] = odbcConnection["database"];
            sqlConnection["User Id"]         = odbcConnection["uid"];
            sqlConnection["Password"]        = odbcConnection["pwd"];

            connection  = SqlConnectionHelper.OpenMSSQLConnection(sqlConnection.ConnectionString);
            transaction = connection.BeginTransaction();
            bulkCopy    = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction);

            return(this);
        }
コード例 #31
0
ファイル: TestProvider.cs プロジェクト: Huddle/Puddle
            /// <summary>
            /// The Windows PowerShell engine calls this method when the New-Drive 
            /// cmdlet is run. This provider creates a connection to the database 
            /// file and sets the Connection property in the PSDriveInfo.
            /// </summary>
            /// <param name="drive">
            /// Information describing the drive to create.
            /// </param>
            /// <returns>An object that describes the new drive.</returns>
            protected override PSDriveInfo NewDrive(PSDriveInfo drive)
            {
                // Check to see if the supplied drive object is null.
                if (drive == null)
                {
                    WriteError(new ErrorRecord(
                                   new ArgumentNullException("drive"),
                                   "NullDrive",
                                   ErrorCategory.InvalidArgument,
                                   null));

                    return null;
                }

                // Check to see if the drive root is not null or empty
                // and if it iss an existing file.
                if (String.IsNullOrEmpty(drive.Root) || (File.Exists(drive.Root) == false))
                {
                    WriteError(new ErrorRecord(
                                   new ArgumentException("drive.Root"),
                                   "NoRoot",
                                   ErrorCategory.InvalidArgument,
                                   drive));

                    return null;
                }

                // Create the new drive and create an ODBC connection
                // to the new drive.
                var accessDBPSDriveInfo = new AccessDBPSDriveInfo(drive);

                var builder = new OdbcConnectionStringBuilder();

                builder.Driver = "Microsoft Access Driver (*.mdb)";
                builder.Add("DBQ", drive.Root);

                var conn = new OdbcConnection(builder.ConnectionString);
                conn.Open();
                accessDBPSDriveInfo.Connection = conn;

                return accessDBPSDriveInfo;
            }