Esempio n. 1
0
        public static string GetDatabaseName(string connectionString, DatabaseType dbType)
        {
            var builder = new DbConnectionStringBuilder();

            builder.ConnectionString = connectionString;

            if (builder.TryGetValue("Initial Catalog", out object catalog))
            {
                return(catalog.ToString());
            }

            if (builder.TryGetValue("Database", out object database))
            {
                return(database.ToString());
            }

            if (builder.TryGetValue("Data Source", out object dataSource))
            {
                return(dataSource.ToString());
            }

            if (builder.TryGetValue("DataSource", out object dataSource2))
            {
                return(dataSource2.ToString());
            }
            return(dbType.ToString());
        }
Esempio n. 2
0
        private void Parse(String source)
        {
            var cnnStrName = source ?? DEFAULT_CONNECTION_STRING;
            var cnnStr     = ConfigurationManager.ConnectionStrings[cnnStrName]?.ConnectionString;

            if (cnnStr == null)
            {
                throw new AzureStorageException($"ConnectionString '{cnnStrName}' not found");
            }
            var csb = new DbConnectionStringBuilder()
            {
                ConnectionString = cnnStr
            };

            if (csb.TryGetValue("DefaultEndpointsProtocol", out Object proto))
            {
                Protocol = proto.ToString();
            }
            if (csb.TryGetValue("AccountName", out Object accName))
            {
                AccountName = accName.ToString();
            }
            if (csb.TryGetValue("AccountKey", out Object accKey))
            {
                AccountKey = accKey.ToString();
            }
            if (csb.TryGetValue("EndpointSuffix", out Object endp))
            {
                EndpointSuffix = endp.ToString();
            }
        }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            string connectionStringName = config.Properties["ConnectionStringName"];

            if (string.IsNullOrEmpty(connectionStringName))
            {
                this.Log.Info("Starting RavenDB Storage Provider InMemory");
                return(this.InMemoryMode());
            }

            var settings = ConfigurationManager.ConnectionStrings[connectionStringName];

            var connectionStringBuilder = new DbConnectionStringBuilder
            {
                ConnectionString = settings.ConnectionString
            };

            object url;

            if (connectionStringBuilder.TryGetValue("Url", out url))
            {
                this.Log.Info("Starting RavenDB Storage Provider attached to server {0}", url);
                return(this.ServerMode(connectionStringName));
            }

            object dataDir;

            if (connectionStringBuilder.TryGetValue("DataDir", out dataDir))
            {
                this.Log.Info("Starting RavenDB Storage Provider embedded in directory {0}", dataDir);
                return(this.LocalMode(connectionStringName));
            }

            return(TaskDone.Done);
        }
Esempio n. 4
0
        /// <summary>
        /// This function returns login and password of user for a passed NpgsqlConnection
        /// </summary>
        /// <param name="connection">the current opened DbConnection</param>
        /// <param name="login">returned login corresponding to the NpgsqlConnection passed</param>
        /// <param name="password">returned password corresponding to the NpgsqlConnection passed</param>
        /// <returns>true if succeed, false otherwise (connection null or not opened)</returns>
        public static bool GetConnectionInformationsFrom(
            IDbConnection connection,
            out string login,
            out string password)
        {
            login    = string.Empty;
            password = string.Empty;

            if ((connection != null) && (connection.State == System.Data.ConnectionState.Open))
            {
                DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
                builder.ConnectionString = connection.ConnectionString;

                if (builder != null)
                {
                    object value  = null;
                    bool   result = builder.TryGetValue("User Id", out value);
                    if (result)
                    {
                        login = value.ToString();
                    }

                    result &= builder.TryGetValue("Password", out value);
                    if (result)
                    {
                        password = value.ToString();
                    }

                    builder.Clear();
                    return(result);
                }
            }

            return(false);
        }
Esempio n. 5
0
        public static string GetDatabasePassword(this DbConnectionStringBuilder builder, DataAccessProviderType?providerType = null)
        {
            if (providerType == DataAccessProviderType.OleDb ||
                IsOleDb(builder))
            {
                return(builder.TryGetValue("Jet OLEDB:Database Password", out var value)
                    ? (string)value
                    : null);
            }

            // MAJOR ISSUE: PWD seems to be used for the datbase password AND the workgroup user password.
            //              See https://stackoverflow.com/questions/65025810/how-to-specify-mdw-username-and-password-user-level-security-and-the-database
            //              As a workaround, we will assume the PWD field to contain the database password, if no SYSTEMDB has been specified.
            //              Otherwise, we will handle the field as the workgroup user password.

            if (providerType == DataAccessProviderType.Odbc ||
                IsOdbc(builder))
            {
                return(string.IsNullOrEmpty(builder.GetSystemDatabase(providerType))
                    ? builder.TryGetValue("PWD", out var value)
                        ? (string)value
                        : null
                    : null);
            }

            return(builder.TryGetValue("Jet OLEDB:Database Password", out var oleDbValue)
                ? (string)oleDbValue
                : string.IsNullOrEmpty(builder.GetSystemDatabase(providerType))
                    ? builder.TryGetValue("PWD", out var odbcValue)
                        ? (string)odbcValue
                        : null
                    : null);
        }
Esempio n. 6
0
    void ParseRabbitConnectionString(string connectionString)
    {
        var connectionStringBuilder = new DbConnectionStringBuilder {
            ConnectionString = connectionString
        };

        if (connectionStringBuilder.TryGetValue("username", out var value))
        {
            UserName = value.ToString();
        }
        else if (connectionStringBuilder.TryGetValue("user", out var userValue))
        {
            UserName = userValue.ToString();
        }

        if (connectionStringBuilder.TryGetValue("password", out value))
        {
            Password = value.ToString();
        }

        if (connectionStringBuilder.TryGetValue("virtualhost", out value))
        {
            VirtualHost = value.ToString();
        }

        if (connectionStringBuilder.TryGetValue("host", out value))
        {
            HostName = value.ToString();
        }
        else
        {
            throw new Exception("The connection string doesn't contain a value for 'host'.");
        }
    }
Esempio n. 7
0
        static string GetDefaultCatalog(SettingsHolder settings, string connectionString)
        {
            if (settings.TryGet(SettingsKeys.ConnectionFactoryOverride, out Func <Task <SqlConnection> > factoryOverride))
            {
                using (var connection = factoryOverride().GetAwaiter().GetResult())
                {
                    connectionString = connection.ConnectionString;
                }
            }
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception("Either connection string or connection factory has to be specified in the SQL Server transport configuration.");
            }
            var parser = new DbConnectionStringBuilder
            {
                ConnectionString = connectionString
            };

            if (parser.TryGetValue("Initial Catalog", out var catalog) ||
                parser.TryGetValue("database", out catalog))
            {
                return((string)catalog);
            }
            throw new Exception("Initial Catalog property is mandatory in the connection string.");
        }
Esempio n. 8
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)
        {
            // Issue a query against Cosmos that forces a native assembly to load.

            string cosmosConnection = _config.GetConnectionString("CosmosDB");
            var    builder          = new DbConnectionStringBuilder()
            {
                ConnectionString = cosmosConnection
            };

            builder.TryGetValue("AccountEndpoint", out object dbUri);
            builder.TryGetValue("AccountKey", out object dbKey);

            var client  = new DocumentClient(new Uri(dbUri.ToString()), dbKey.ToString());
            Uri collUri = UriFactory.CreateDocumentCollectionUri("ItemDb", "ItemCollection");

            var options = new FeedOptions
            {
                EnableCrossPartitionQuery = true
            };

            IDocumentQuery <Document> documentQuery = client.CreateDocumentQuery <Document>(collUri, "SELECT * FROM c WHERE STARTSWITH(c.id, @PartitionLeasePrefix)", options).AsDocumentQuery <Document>();

            await documentQuery.ExecuteNextAsync();

            return(new OkResult());
        }
Esempio n. 9
0
        public static string GetSavedConnectionName(string connectionString, DatabaseType dbType)
        {
            if (dbType == DatabaseType.SQLServer)
            {
                return(PathFromConnectionString(connectionString));
            }

            var builder = new DbConnectionStringBuilder();

            builder.ConnectionString = connectionString;

            var result = string.Empty;

            if (builder.TryGetValue("Data Source", out object dataSource))
            {
                result += dataSource.ToString();
            }

            if (builder.TryGetValue("DataSource", out object dataSource2))
            {
                result += dataSource2.ToString();
            }

            if (builder.TryGetValue("Database", out object database))
            {
                result += "." + database.ToString();
            }

            return(result);
        }
        /// <summary>
        /// Initializes a new instance from the specified connection string.
        /// </summary>
        /// <remarks>
        /// The connection string should contain a URI, an ApiUser, and a Password for connecting to Tethr.
        /// For example, uri=https://YourCompanyNameHere.Audio.Tethr.io/;ApiUser=YourUserNameHere;Password=YourPasswordHere
        /// </remarks>
        /// <param name="connectionString">The Tethr connection string.</param>
        /// <returns></returns>
        public static TethrSessionOptions InitializeFromConnectionString(string connectionString)
        {
            var builder = new DbConnectionStringBuilder();

            builder.ConnectionString = connectionString;

            if (!builder.TryGetValue("uri", out var uri))
            {
                throw new InvalidOperationException("Could not find the URI value in the connection string.");
            }

            if (!builder.TryGetValue("ApiUser", out var apiUser))
            {
                throw new InvalidOperationException("Could not find the ApiUser value in the connection string.");
            }

            if (!builder.TryGetValue("Password", out var password))
            {
                throw new InvalidOperationException("Could not find the Password value in the connection string.");
            }

            return(new TethrSessionOptions
            {
                Uri = uri as string ?? uri.ToString(),
                ApiUser = apiUser as string ?? apiUser.ToString(),
                Password = password as string ?? password.ToString()
            });
        }
Esempio n. 11
0
 private static string ExtractConnectInfo(string connectionString)
 {
     if (connectionString.Contains("Data Source="))
     {
         string str4 = "";
         try
         {
             object obj2;
             object obj3;
             DbConnectionStringBuilder builder = new DbConnectionStringBuilder {
                 ConnectionString = connectionString
             };
             if (!builder.TryGetValue("data source", out obj2) || !builder.TryGetValue("initial catalog", out obj3))
             {
                 return(connectionString.ToLower());
             }
             string str2 = (obj2 != null) ? obj2.ToString().ToLower() : null;
             string str3 = (obj3 != null) ? obj3.ToString().ToLower() : null;
             if (string.IsNullOrEmpty(str2) || string.IsNullOrEmpty(str3))
             {
                 return(connectionString.ToLower());
             }
             if ((str2 == "localhost") || (str2 == "127.0.0.1"))
             {
                 str2 = "(local)";
             }
             str4 = str2 + "_" + str3;
         }
         catch (ArgumentException)
         {
         }
         return(str4);
     }
     return(connectionString.ToLower());
 }
Esempio n. 12
0
        protected void ParseConnectionString()
        {
            DbConnectionStringBuilder dbConnectionStringBuilders = new DbConnectionStringBuilder()
            {
                ConnectionString = this.CertificateConnectionStringName
            };

            if (dbConnectionStringBuilders.TryGetValue("StoreName", out object storeName))
            {
                this.StoreName = (StoreName)Enum.Parse(typeof(StoreName), (string)storeName, true);
            }

            if (dbConnectionStringBuilders.TryGetValue("StoreLocation", out object storeLocation))
            {
                this.StoreLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), (string)storeLocation, true);
            }

            if (dbConnectionStringBuilders.TryGetValue("FindType", out object findType))
            {
                this.FindType = (X509FindType)Enum.Parse(typeof(X509FindType), (string)findType, true);
            }

            if (dbConnectionStringBuilders.TryGetValue("FindValue", out object findValue))
            {
                this.FindValue = (string)findValue;
            }

            if (dbConnectionStringBuilders.TryGetValue("AllowInvalidClientCertificates", out object allowInvalidClientCertificate))
            {
                this.AllowInvalidClientCertificates = (bool)allowInvalidClientCertificate;
            }
        }
Esempio n. 13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            services.AddHttpClient();

            services.AddScoped <ITelegramBotClient>(provider =>
            {
                var key = Configuration.GetSection("Telegram").GetValue <string>("BotKey");
                return(new TelegramBotClient(key, provider.GetService <HttpClient>()));
            });

            var builder = new DbConnectionStringBuilder()
            {
                ConnectionString = Configuration.GetConnectionString("CosmosSettings")
            };

            builder.TryGetValue("AccountEndpoint", out object endpoint);
            builder.TryGetValue("AccountKey", out object key);

            services.AddDbContext <GameContext>(option => option.UseCosmos(endpoint?.ToString() ?? "", key?.ToString() ?? "", "snikmorder"));

            services.AddScoped <MessageHandler>();
            services.AddScoped <AdminStateMachine>();
            services.AddScoped <ITelegramSender, TelegramSender>();
            services.AddScoped <PlayerStateMachine>();
            services.AddScoped <GameService>();
            services.AddScoped <IGameRepository, GameRepository>();
            services.AddApplicationInsightsTelemetry();
        }
        public static DocumentClient Create(string connectionString)
        {
            var builder = new DbConnectionStringBuilder()
            {
                ConnectionString = connectionString
            };

            string authKey;
            Uri    serviceEndpoint;

            if (builder.TryGetValue("AccountKey", out var key))
            {
                authKey = key.ToString();
            }
            else
            {
                throw new ArgumentException(
                          "Connectionstring does not contain AccountKey",
                          nameof(connectionString));
            }

            if (builder.TryGetValue("AccountEndpoint", out var uri))
            {
                serviceEndpoint = new Uri(uri.ToString());
            }
            else
            {
                throw new ArgumentException(
                          "Connectionstring does not contain AccountEndpoint",
                          nameof(connectionString));
            }

            return(new DocumentClient(serviceEndpoint, authKey));
        }
        private void TrySetValuesFromConnectionString(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                return;
            }

            var builder = new DbConnectionStringBuilder();

            try
            {
                builder.ConnectionString = connectionString;
            }
            catch (ArgumentException)
            {
                return;
            }

            object tmp;

            if (builder.TryGetValue("AccountEndpoint", out tmp) && tmp is string)
            {
                _endpoint = (string)tmp;
            }
            if (builder.TryGetValue("AccountKey", out tmp) && tmp is string)
            {
                _key = (string)tmp;
            }
            SetNameFromEndpoint();
        }
Esempio n. 16
0
        internal static string GetInitialCatalog(string connectionToUse, bool overrideMySqlSkip = false)
        {
            if (Manager.ConnectionType == ConnectionTypes.MySQL && !overrideMySqlSkip)
            {
                return("def");
            }

            DbConnectionStringBuilder builder = new DbConnectionStringBuilder
            {
                ConnectionString = GetValueFromConfiguration(connectionToUse, ConfigurationTypes.ConnectionString)
            };

            bool dbNameFound = false;

            dbNameFound = builder.TryGetValue("Initial Catalog", out object dbName);
            if (dbNameFound == false)
            {
                dbNameFound = builder.TryGetValue("Database", out dbName);
            }
            if (dbNameFound == false)
            {
                throw new Exception("Failed to extract database name from connection string.");
            }

            return(Convert.ToString(dbName));
        }
        /// <summary>
        /// Connect to the Cosmos database using the local variables
        /// so it can be used for "reconnecting" if the connection breaks
        /// </summary>
        /// <returns>The newly created document client</returns>
        private async Task <DocumentClient> ConnectInternal()
        {
            // Items derived from the connection string
            String authKey         = String.Empty;
            Uri    serviceEndPoint = null;

            // The newly created document client that will override the global one
            DocumentClient client = null;

            // Create a new instance of the connection builder to pull out the attributes needed
            DbConnectionStringBuilder builder = new DbConnectionStringBuilder
            {
                ConnectionString = this.ConnectionString
            };

            // Get the Account key from the connection string, leave it as empty for
            // validation if it cannot be found
            if (builder.TryGetValue("AccountKey", out object key))
            {
                authKey = key.ToString();
            }

            // Get the Uri of the account from the connection string, leave it as "null"
            // if it cannot be found for validation later
            if (builder.TryGetValue("AccountEndpoint", out object uri))
            {
                serviceEndPoint = new Uri(uri.ToString());
            }

            // If we found all the bits needed to connect then connect ..
            if (authKey != String.Empty && serviceEndPoint != null)
            {
                client = new DocumentClient(serviceEndPoint, authKey);
            }

            // Create the required database if it does not already exist
            await client.CreateDatabaseIfNotExistsAsync(
                new Database
            {
                Id = DatabaseName
            });

            // Create the required collection if it does not already exist
            await client.CreateDocumentCollectionIfNotExistsAsync(
                UriFactory.CreateDatabaseUri(DatabaseName),
                new DocumentCollection
            {
                Id = DataCollection
            });

            // Cache the collection link for use later
            this.collectionLink = UriFactory.CreateDocumentCollectionUri(DatabaseName, DataCollection);

            // Log that we have connected
            logger.LogInformation($"Successfully Connected Document Handler to Cosmos DB - {DatabaseName}/{DataCollection}");

            // Send the new document client back to use
            return(client);
        }
        private object olvColumnPropertyValue_AspectGetter(object rowObject)
        {
            string key   = rowObject.ToString();
            object value = null;

            m_ConnectionStringBuilder.TryGetValue(key, out value);
            return(value);
        }
Esempio n. 19
0
        bool SetServiceData(string connStr, GxHttpClient restClient)
        {
            DbConnectionStringBuilder builder = new DbConnectionStringBuilder(false);

            builder.ConnectionString = connStr;
            object serviceUri = "";
            object userID     = "";
            object password   = "";

            if (builder.TryGetValue("User Id", out userID))
            {
                if (builder.TryGetValue("Password", out password))
                {
                    restClient.AddAuthentication(0, "", userID.ToString(), password.ToString());
                }
            }
            object ds_data  = "";
            object uri_data = "";

            if (builder.TryGetValue("Data Source", out ds_data))
            {
                serviceUri = ds_data;
            }
            else
            if (builder.TryGetValue("uri", out uri_data))
            {
                serviceUri = uri_data;
            }
            else
            {
                serviceUri = null;
            }

            if (serviceUri != null)
            {
                String   urlstring = "";
                String[] parts     = serviceUri.ToString().Split(new String[] { "://" }, StringSplitOptions.None);
                if (parts.Length > 1)
                {
                    if (parts[0].Equals("https"))
                    {
                        restClient.Secure = 1;
                    }
                    urlstring = parts[1];
                }
                else
                {
                    urlstring = parts[0];
                }
                int position = urlstring.IndexOf("/");
                restClient.Host    = urlstring.Substring(0, position);
                restClient.BaseURL = urlstring.Substring(position);
                restClient.Timeout = ConnectionTimeout;
                restClient.AddHeader("Content-Type", "application/json");
                return(true);
            }
            return(false);
        }
        private static string ParseProviderName(DbConnectionStringBuilder builder)
        {
            if ((builder.TryGetValue("Data Source", out var dataSource) || builder.TryGetValue("DataSource", out dataSource)) &&
                dataSource?.ToString().EndsWith(".sdf", StringComparison.OrdinalIgnoreCase) == true)
            {
                return(Constants.DbProviderNames.SqlCe);
            }

            return(Constants.DbProviderNames.SqlServer);
        }
Esempio n. 21
0
    static void PurgeQueues(DbConnectionStringBuilder connectionStringBuilder, QueueBindings queueBindings)
    {
        if (connectionStringBuilder == null)
        {
            return;
        }

        var connectionFactory = new ConnectionFactory
        {
            AutomaticRecoveryEnabled  = true,
            UseBackgroundThreadsForIO = true
        };

        if (connectionStringBuilder.TryGetValue("username", out var value))
        {
            connectionFactory.UserName = value.ToString();
        }

        if (connectionStringBuilder.TryGetValue("password", out value))
        {
            connectionFactory.Password = value.ToString();
        }

        if (connectionStringBuilder.TryGetValue("virtualhost", out value))
        {
            connectionFactory.VirtualHost = value.ToString();
        }

        if (connectionStringBuilder.TryGetValue("host", out value))
        {
            connectionFactory.HostName = value.ToString();
        }
        else
        {
            throw new Exception("The connection string doesn't contain a value for 'host'.");
        }

        var queues = queueBindings.ReceivingAddresses.Concat(queueBindings.SendingAddresses);

        using (var connection = connectionFactory.CreateConnection("Test Queue Purger"))
            using (var channel = connection.CreateModel())
            {
                foreach (var queue in queues)
                {
                    try
                    {
                        channel.QueuePurge(queue);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unable to clear queue {0}: {1}", queue, ex);
                    }
                }
            }
    }
Esempio n. 22
0
        public ArangoContext(string cs)
        {
            User        = new ArangoUserModule(this);
            Collection  = new ArangoCollectionModule(this);
            View        = new ArangoViewModule(this);
            Database    = new ArangoDatabaseModule(this);
            Graph       = new ArangoGraphModule(this);
            Transaction = new ArangoTransactionModule(this);
            Document    = new ArangoDocumentModule(this);
            Query       = new ArangoQueryModule(this);
            Index       = new ArangoIndexModule(this);
            Analyzer    = new ArangoAnalyzerModule(this);
            Function    = new ArangoFunctionModule(this);

            var builder = new DbConnectionStringBuilder {
                ConnectionString = cs
            };

            builder.TryGetValue("Server", out var s);
            builder.TryGetValue("Realm", out var r);
            builder.TryGetValue("User ID", out var uid);
            builder.TryGetValue("User", out var u);
            builder.TryGetValue("Password", out var p);

            var server   = s as string;
            var user     = u as string ?? uid as string;
            var password = p as string;
            var realm    = r as string;

            if (string.IsNullOrWhiteSpace(server))
            {
                throw new ArgumentException("Server invalid");
            }

            if (string.IsNullOrWhiteSpace(user))
            {
                throw new ArgumentException("User invalid");
            }

            if (string.IsNullOrWhiteSpace(realm))
            {
                Realm = string.Empty;
            }
            else
            {
                Realm = realm + "-";
            }

            Server    = server;
            _user     = user;
            _password = password;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="connectionProperties"></param>
        public OpenConnectionForm(ConnectionProperties connectionProperties)
        {
            InitializeComponent();
            HandleCreated += OpenConnectionForm_HandleCreated;

            _stopwatch.Start();
            _timer.Enabled = true;

            var dbConnectionStringBuilder = new DbConnectionStringBuilder();

            dbConnectionStringBuilder.ConnectionString = connectionProperties.ConnectionString;
            object dataSourceObject;
            var    contains = dbConnectionStringBuilder.TryGetValue(ConnectionStringKeyword.DataSource, out dataSourceObject);
            object userId;

            dbConnectionStringBuilder.TryGetValue(ConnectionStringKeyword.UserId, out userId);
            var dataSource = (string)dataSourceObject;

            _textBox.Text         = $@"Connection name: {connectionProperties.ConnectionName}
Provider name: {connectionProperties.ProviderName}
{ConnectionStringKeyword.DataSource}: {dataSource}
{ConnectionStringKeyword.UserId}: {userId}";
            _connectionProperties = connectionProperties;
            Cursor = Cursors.AppStarting;

            if (_connectionProperties.Provider == null)
            {
                _connectionProperties.Provider = ProviderFactory.CreateProvider(_connectionProperties.ProviderName);
            }

            var connection = _connectionProperties.Provider.CreateConnection(connectionProperties.ConnectionString);

            _cancellationTokenSource = new CancellationTokenSource();

            var stopwatch = Stopwatch.StartNew();

            _task = Task.Factory.StartNew(() =>
            {
                var task = connection.OpenAsync(_cancellationTokenSource.Token);
                task.ContinueWith(t =>
                {
                    Duration = stopwatch.ElapsedTicks;

                    if (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        connectionProperties.Connection = connection;
                        EndConnectionOpen(task.Exception);
                    }
                });
            });
        }
Esempio n. 24
0
        private void InitializeDBConnection()
        {
            DbConnectionStringBuilder builder = new DbConnectionStringBuilder(false);

            builder.ConnectionString = this.ConnectionString;
            if (builder.TryGetValue(CLIENT_ID, out object clientId) && builder.TryGetValue(CLIENT_SECRET, out object clientSecret))
            {
                mCredentials = new BasicAWSCredentials(clientId.ToString(), clientSecret.ToString());
            }
            if (builder.TryGetValue(REGION, out object region))
            {
                mRegion = RegionEndpoint.GetBySystemName(region.ToString());
            }
        }
Esempio n. 25
0
        public string GetDataBaseName(DbConnectionStringBuilder builder)
        {
            object database = "";

            builder.TryGetValue("database", out database);
            if (database == null || string.IsNullOrEmpty(database.ToString()))
            {
                builder.TryGetValue("initial catalog", out database);
            }
            if (database == null || string.IsNullOrEmpty(database.ToString()))
            {
                throw new Exception(ProviderName + " must have database;" + builder.ConnectionString);
            }
            return(database.ToString().FirstLetterToUpper());
        }
Esempio n. 26
0
        internal static bool IsAccessConnectionString(string providerInvariantName, string providerConnectionString)
        {
            if (null == providerInvariantName ||
                null == providerConnectionString)
            {
                return(false);
            }

            if (0 == string.CompareOrdinal(providerInvariantName, PROVIDER_NAME_OLEDB))
            {
                // This is an OleDb connection string, verify if it is using the Jet provider.
                var providerConnectionStringBuilder = new DbConnectionStringBuilder();
                providerConnectionStringBuilder.ConnectionString = providerConnectionString;
                object oleDbProviderObject;
                providerConnectionStringBuilder.TryGetValue(CONNECTION_PROPERTY_PROVIDER, out oleDbProviderObject);
                var oleDbProvider = oleDbProviderObject as string;

                Debug.Assert(oleDbProvider != null, "Expected the provider connection string to contain a 'provider' property.");
                if (!string.IsNullOrEmpty(oleDbProvider))
                {
                    if (oleDbProvider.StartsWith(PROVIDER_NAME_JET, StringComparison.OrdinalIgnoreCase) ||
                        oleDbProvider.StartsWith(PROVIDER_NAME_ACE, StringComparison.OrdinalIgnoreCase))
                    {
                        // This is a Jet or Ace connection string.
                        return(true);
                    }
                }
            }

            return(false);
        }
Esempio n. 27
0
        public static DB2iSeriesNamingConvention GetNamingConvetion(this DataConnection dataConnection)
        {
            if (dataConnection.DataProvider is DB2iSeriesDataProvider iSeriesDataProvider &&
                iSeriesDataProvider.ProviderType != DB2iSeriesProviderType.DB2)
            {
                var namingConventionKey = iSeriesDataProvider.ProviderType switch
                {
#if NETFRAMEWORK
                    DB2iSeriesProviderType.AccessClient => "Naming",
#endif
                    DB2iSeriesProviderType.Odbc => "NAM",
                    DB2iSeriesProviderType.OleDb => "Naming Convention",
                    _ => throw ExceptionHelper.InvalidAdoProvider(iSeriesDataProvider.ProviderType)
                };

                var csb = new DbConnectionStringBuilder()
                {
                    ConnectionString = dataConnection.ConnectionString
                };

                if (csb.TryGetValue(namingConventionKey, out var namingConvention))
                {
                    if (!(namingConvention is string namingConventionString))
                    {
                        namingConventionString = ((int)namingConvention).ToString();
                    }

                    return(namingConventionString == "1" ? DB2iSeriesNamingConvention.System : DB2iSeriesNamingConvention.Sql);
                }
            }

            return(DB2iSeriesNamingConvention.Sql);
        }
Esempio n. 28
0
    private static void DisplayValue(
        DbConnectionStringBuilder builder, string key)
    {
        object value = null;

        // Although TryGetValue handles missing keys,
        // it doesn't handle passing in a null
        // key. This example traps for that particular error, but
        // bubbles any other unknown exceptions back out to the
        // caller.
        try
        {
            if (builder.TryGetValue(key, out value))
            {
                Console.WriteLine("{0}={1}", key, value);
            }
            else
            {
                Console.WriteLine(@"Unable to retrieve value for '{0}'", key);
            }
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("Unable to retrieve value for null key.");
        }
    }
Esempio n. 29
0
        public void Open()
        {
            var sb = new DbConnectionStringBuilder();

            sb.ConnectionString = _connectionString;
            var    contains = sb.TryGetValue(ConnectionStringKeyword.DataSource, out var value);
            string dataSource;

            if (contains)
            {
                dataSource = (string)value;
            }
            else
            {
                dataSource = null;
            }

            DataSource = dataSource;
            //ManagementPath path = ManagementPath.DefaultPath;
            //path.Server = dataSource;
            //scope = new ManagementScope( path );

            var path = DataSource;

            Scope = new ManagementScope(path);
        }
Esempio n. 30
0
    public static string GetValue(this DbConnectionStringBuilder dbConnectionStringBuilder, string keyword)
    {
        var contains = dbConnectionStringBuilder.TryGetValue(keyword, out var valueObject);
        var value    = contains ? (string)valueObject : null;

        return(value);
    }