public void ContainsKeyTest()
 {
     builder = new SqlConnectionStringBuilder("SERVER=localhost;Network=DBMSSOCN");
     Assert.AreEqual(true, builder.ContainsKey("NETWORK"),
                     "#CKT1 should say true");
     Assert.AreEqual(false, builder.ContainsKey("ABCD"),
                     "#CKT2 should say false");
 }
        /// <summary>
        /// Ensures that credentials are provided for the given connection string object.
        /// </summary>
        /// <param name="connectionString">Input connection string object.</param>
        /// <param name="parameterName">Parameter name of the connection string object.</param>
        internal static void EnsureCredentials(SqlConnectionStringBuilder connectionString, string parameterName)
        {
            // Check for integrated authentication
            if (connectionString.IntegratedSecurity)
            {
                return;
            }

            // Check for active directory integrated authentication (if supported)
            if (connectionString.ContainsKey(ShardMapUtils.Authentication) &&
                connectionString[ShardMapUtils.Authentication].ToString().Equals(ShardMapUtils.ActiveDirectoryIntegratedStr))
            {
                return;
            }

            // UserID must be set when integrated authentication is disabled.
            if (string.IsNullOrEmpty(connectionString.UserID))
            {
                throw new ArgumentException(
                          StringUtils.FormatInvariant(
                              Errors._SqlShardMapManagerCredentials_ConnectionStringPropertyRequired,
                              "UserID"),
                          parameterName);
            }

            // Password must be set when integrated authentication is disabled.
            if (string.IsNullOrEmpty(connectionString.Password))
            {
                throw new ArgumentException(
                          StringUtils.FormatInvariant(
                              Errors._SqlShardMapManagerCredentials_ConnectionStringPropertyRequired,
                              "Password"),
                          parameterName);
            }
        }
예제 #3
0
        public string GetConnectionString(string name)
        {
            // Try to find entity connection.
            var cs = ConfigurationManager.ConnectionStrings[name];

            // If configuration section with not found then return.
            if (cs == null)
            {
                return(null);
            }
            var connectionString = cs.ConnectionString;

            if (string.Compare(cs.ProviderName, "System.Data.EntityClient", true) == 0)
            {
                // Get connection string from entity connection string.
                var ecsb = new System.Data.EntityClient.EntityConnectionStringBuilder(cs.ConnectionString);
                connectionString = ecsb.ProviderConnectionString;
            }
            var builder = new SqlConnectionStringBuilder(connectionString);

            if (!builder.ContainsKey("Application Name") || ".Net SqlClient Data Provider".Equals(builder["Application Name"]))
            {
                var asm = Assembly.GetEntryAssembly();
                if (asm == null)
                {
                    asm = Assembly.GetExecutingAssembly();
                }
                var appPrefix = asm.GetName().Name.Replace(".", "");
                var appName   = string.Format("{0}", appPrefix);
                builder.Add("Application Name", appName);
                connectionString = builder.ToString();
            }
            return(connectionString);
        }
예제 #4
0
        public static string GetProviderConnectionString(string connectionString, out bool isEntity)
        {
            isEntity = false;
#if NETSTANDARD  // .NET Standard
#elif NETCOREAPP // .NET Core
            // EF Core does not support EF specific connection strings (metadata=res:... < this kind of connection strings).
#else // .NET Framework
            if (string.Compare(connectionString, "metadata=", true) == 0)
            {
                // Get connection string from entity connection string.
                var ecsb = new System.Data.EntityClient.EntityConnectionStringBuilder(connectionString);
                connectionString = ecsb.ProviderConnectionString;
                isEntity         = true;
            }
#endif
            var builder = new SqlConnectionStringBuilder(connectionString);
            if (!builder.ContainsKey("Application Name") || ".Net SqlClient Data Provider".Equals(builder["Application Name"]))
            {
                var asm = Assembly.GetEntryAssembly();
                if (asm == null)
                {
                    asm = Assembly.GetExecutingAssembly();
                }
                var appPrefix = asm.GetName().Name.Replace(".", "");
                var appName   = string.Format("{0}", appPrefix);
                builder.Add("Application Name", appName);
                connectionString = builder.ToString();
            }
            return(connectionString);
        }
예제 #5
0
        /// <summary>
        /// Ensures that credentials are provided for the given connection string object.
        /// </summary>
        /// <param name="connectionString">
        /// Input connection string object.
        /// </param>
        /// <param name="parameterName">
        /// Parameter name of the connection string object.
        /// </param>
        /// <param name="secureCredential">
        /// Input secure SQL credential object.
        /// </param>
        /// <param name="accessTokenFactory">
        /// The access token factory.
        /// </param>
        internal static void EnsureCredentials(
            SqlConnectionStringBuilder connectionString,
            string parameterName,
            SqlCredential secureCredential,
            Func <string> accessTokenFactory)
        {
            // Check for integrated authentication
            if (connectionString.IntegratedSecurity)
            {
                return;
            }

            // Check for active directory integrated authentication (if supported)
            if (connectionString.ContainsKey(ShardMapUtils.Authentication))
            {
                string authentication = connectionString[ShardMapUtils.Authentication].ToString();
                if (authentication.Equals(ShardMapUtils.ActiveDirectoryIntegratedStr, StringComparison.OrdinalIgnoreCase) ||
                    authentication.Equals(ShardMapUtils.ActiveDirectoryInteractiveStr, StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }
            }

            // If secure credential not specified, verify that user/pwd are in the connection string. If secure credential
            // specified, verify user/pwd are not in insecurely in the connection string.
            bool expectUserIdPasswordInConnectionString = secureCredential == null && accessTokenFactory == null;

            EnsureHasCredential(
                connectionString,
                parameterName,
                expectUserIdPasswordInConnectionString);
        }
예제 #6
0
        public static string GetProviderConnectionString(string connectionString, out bool isEntity)
        {
            isEntity = false;
            if (string.Compare(connectionString, "metadata=", true) == 0)
            {
                // Get connection string from entity connection string.
                var ecsb = new System.Data.EntityClient.EntityConnectionStringBuilder(connectionString);
                connectionString = ecsb.ProviderConnectionString;
                isEntity         = true;
            }
            var builder = new SqlConnectionStringBuilder(connectionString);

            if (!builder.ContainsKey("Application Name") || ".Net SqlClient Data Provider".Equals(builder["Application Name"]))
            {
                var asm = Assembly.GetEntryAssembly();
                if (asm == null)
                {
                    asm = Assembly.GetExecutingAssembly();
                }
                var appPrefix = asm.GetName().Name.Replace(".", "");
                var appName   = string.Format("{0}", appPrefix);
                builder.Add("Application Name", appName);
                connectionString = builder.ToString();
            }
            return(connectionString);
        }
예제 #7
0
        public void TestSqlConnectionStringBuilderContainsKey(SqlConnectionColumnEncryptionSetting sqlConnectionColumnEncryptionSetting)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            // Key is "Column Encryption Setting" with spaces. So lookup for ColumnEncryptionSetting should return false.
            Assert.False(connectionStringBuilder.ContainsKey(@"ColumnEncryptionSetting"));

            // connectionStringBuilder should have the key Column Encryption Setting, even if value is not set.
            Assert.True(connectionStringBuilder.ContainsKey(@"Column Encryption Setting"));

            // set a value and check for the key again, it should exist.
            connectionStringBuilder.ColumnEncryptionSetting = sqlConnectionColumnEncryptionSetting;
            Assert.True(connectionStringBuilder.ContainsKey(@"Column Encryption Setting"));

            //also check attestatin url

            // Key is "Column Encryption Setting" with spaces. So lookup for Enclave Attestation URL should return false.
            Assert.False(connectionStringBuilder.ContainsKey(@"EnclaveAttestationUrl"));

            // connectionStringBuilder should have the key Enclave Attestation URL, even if value is not set.
            Assert.True(connectionStringBuilder.ContainsKey(@"Enclave Attestation Url"));

            // set a value and check for the key again, it should exist.
            connectionStringBuilder.EnclaveAttestationUrl = "www.foo.com";
            Assert.True(connectionStringBuilder.ContainsKey(@"Enclave Attestation Url"));

            //Aslo check attestation protocol

            // Key is "Attestation Protocol" with spaces. So lookup for AttestationProtocol should return false.
            Assert.False(connectionStringBuilder.ContainsKey(@"AttestationProtocol"));
        }
예제 #8
0
        private static int Main(string[] args)
        {
            var rootCommand = new RootCommand(ThisAssembly.AppName)
            {
                new Option <string>(new[] { "--connection-string", "-cs" }, "Contains the connection string to connect to the database"),
                new Option <string>(new[] { "--view-name", "-vn" }, "The name of the view to inline"),
                new Option <FileInfo>(new[] { "--view-path", "-vp" }, "The path of the view as a .sql file (including create statement)"),
                new Option <bool>(new[] { "--strip-unused-columns", "-suc" }, () => true),
                new Option <bool>(new[] { "--strip-unused-joins", "-suj" }),
                new Option <bool>("--generate-create-or-alter", () => true),
                // TODO: DatabaseView.parser (hardcoded to TSql150Parser)
            };

            rootCommand.Handler = CommandHandler.Create <string, string?, FileInfo?, bool, bool, bool>((connectionString, viewName, viewPath, stripUnusedColumns, stripUnusedJoins, generateCreateOrAlter) =>
            {
                var cs = new SqlConnectionStringBuilder(connectionString);
                if (!cs.ContainsKey(nameof(cs.ApplicationName)))
                {
                    cs.ApplicationName = ThisAssembly.AppName;
                    connectionString   = cs.ToString();
                }

                var connection = new DatabaseConnection(new SqlConnection(connectionString));

                string viewSql;
                if (!string.IsNullOrEmpty(viewName))
                {
                    viewSql = connection.GetViewDefinition(viewName);
                }
                else if (viewPath != null)
                {
                    viewSql = File.ReadAllText(viewPath.FullName);
                }
                else
                {
                    throw new InvalidOperationException("At least --view-name or --view-path is required.");
                }

                if (generateCreateOrAlter)
                {
                    viewSql = DatabaseView.CreateOrAlter(viewSql);
                }

                var inliner = new DatabaseViewInliner(connection, viewSql, new()
                {
                    StripUnusedColumns = stripUnusedColumns,
                    StripUnusedJoins   = stripUnusedJoins,
                });

                Console.WriteLine(inliner.Sql);
                return(inliner.Errors.Count > 0 ? -1 : 0);
            });

            return(rootCommand.Invoke(args));
        }
예제 #9
0
        public bool IsInMemoryDb()
        {
            var cb = new SqlConnectionStringBuilder(cn);

            if (!cb.ContainsKey(GlobalStrings.DataSource))
            {
                throw new ArgumentException("missing property from ConnectionString: Data Source", "ConnectionString");
            }
            return(GlobalStrings.SqlMemoryDb.Equals((string)cb[GlobalStrings.DataSource],
                                                    StringComparison.OrdinalIgnoreCase));
        }
예제 #10
0
        public bool IsInMemoryDb()
        {
            var cb = new SqlConnectionStringBuilder(cn);

            if (!cb.ContainsKey(GlobalStrings.DATA_SOURCE))
            {
                throw new ArgumentException("missing property of connecting string: data source", "ConnectionString");
            }

            return("memory".Equals((string)cb[GlobalStrings.DATA_SOURCE], StringComparison.OrdinalIgnoreCase));
        }
        static ShardMapUtils()
        {
            // Connection resiliency is supported if this SqlClient instance
            // allows setting the retry count on connection failure
            SqlConnectionStringBuilder bldr = new SqlConnectionStringBuilder();

            if (bldr.ContainsKey(ConnectRetryCount))
            {
                IsConnectionResiliencySupported = true;
            }
        }
    static void Main()
    {
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(GetConnectionString());

        Console.WriteLine("Connection string = " + builder.ConnectionString);

        // Keys you have provided return true.
        Console.WriteLine(builder.ContainsKey("Server"));

        // Comparison is case insensitive, and synonyms
        // are automatically converted to their "well-known"
        // names.
        Console.WriteLine(builder.ContainsKey("Database"));

        // Keys that are valid but have not been set return true.
        Console.WriteLine(builder.ContainsKey("Max Pool Size"));

        // Keys that do not exist return false.
        Console.WriteLine(builder.ContainsKey("MyKey"));

        Console.WriteLine("Press Enter to continue.");
        Console.ReadLine();
    }
예제 #13
0
        public static void BackupBDTrigger([TimerTrigger("0 59 23 * * 0", RunOnStartup = true)] TimerInfo myTimer, TextWriter log)
        {
            try
            {
                CloudStorageAccount storageAccount = AzureStorageAccount.DefaultAccount;
                CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

                CloudBlobContainer blobContainer = blobClient.GetContainerReference(AzureStorageContainer.BackupsBD);
                blobContainer.CreateIfNotExists();

                BlobContainerPermissions permissions = blobContainer.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                blobContainer.SetPermissions(permissions);

                string         storageName = $"backup_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.bacpac";
                CloudBlockBlob backupFile  = blobContainer.GetBlockBlobReference(storageName);

                string cnn    = ConfigurationManager.ConnectionStrings["Limbs"].ConnectionString;
                string dbName = null;

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(cnn);
                if (builder != null && builder.ContainsKey("Database"))
                {
                    dbName = builder["Database"] as string;

                    if (string.IsNullOrEmpty(dbName))
                    {
                        dbName = builder["Initial Catalog"] as string;
                    }
                }

                string tempFile = $"{Path.GetTempPath()}{backupFile.Name}";

                DacServices services = new DacServices(cnn);
                services.ExportBacpac(tempFile, dbName);

                backupFile.UploadFromFile(tempFile);

                log.WriteLine($"URL PRIMARIA BLOB: {backupFile.StorageUri.PrimaryUri}");
                log.WriteLine($"URL PRIMARIA BLOB: {backupFile.StorageUri.SecondaryUri}");

                File.Delete(tempFile);
            }
            catch (Exception ex)
            {
                log.WriteLine($"OCURRIO UN ERROR: {ex.Message}");
            }
        }
        private void ExecuteConnectionStringTests(string connectionString)
        {
            SqlConnectionStringBuilder builder  = new SqlConnectionStringBuilder(connectionString);
            string retrievedString              = builder.ConnectionString;
            SqlConnectionStringBuilder builder2 = new SqlConnectionStringBuilder(retrievedString);

            Assert.Equal(builder, builder2);
            Assert.NotNull(builder.Values);
            Assert.True(builder.Values.Count > 0);
            foreach (string key in builder2.Keys)
            {
                Assert.True(builder.TryGetValue(key, out object valueBuilder1));
                Assert.True(builder2.TryGetValue(key, out object valueBuilder2));
                Assert.Equal(valueBuilder1, valueBuilder2);
                Assert.True(builder2.ContainsKey(key));
            }
        }
예제 #15
0
        private static bool CheckCatalog(Session session, string dbTitle, string connectionString)
        {
            var result = false;

            if (!string.IsNullOrEmpty(connectionString))
            {
                var builder = new SqlConnectionStringBuilder(connectionString);
                result = builder.ContainsKey(INITIAL_CATALOG) && !string.IsNullOrEmpty(builder.InitialCatalog);
                if (!result)
                {
                    session["DIALOG_ERROR_MESSAGE"] = string.Format("В строке подключения к {0} отсутствует имя БД", dbTitle);
                }
            }
            else
            {
                session["DIALOG_ERROR_MESSAGE"] = string.Format("Не указана строка подлкючения к {0}", dbTitle);
            }
            return(result);
        }
예제 #16
0
        public static string GetConnectionString(string name, out bool isEntity)
        {
            isEntity = false;
            string connectionString = null;

#if !NETSTANDARD
            // Try to find entity connection.
            var cs = ConfigurationManager.ConnectionStrings[name];
            connectionString = cs.ConnectionString;
#endif
            // If configuration section with not found then return.
            // EF Core does not support EF specific connection strings (metadata=res:... < this kind of connection strings).
#if NETFRAMEWORK // .NET Framework
            if (string.Compare(cs.ProviderName, "System.Data.EntityClient", true) == 0)
            {
                // Get connection string from entity connection string.
                var ecsb = new System.Data.EntityClient.EntityConnectionStringBuilder(cs.ConnectionString);
                connectionString = ecsb.ProviderConnectionString;
                isEntity         = true;
            }
#endif
            if (connectionString == null)
            {
                return(null);
            }
            var builder = new SqlConnectionStringBuilder(connectionString);
            if (!builder.ContainsKey("Application Name") || ".Net SqlClient Data Provider".Equals(builder["Application Name"]))
            {
                var asm = Assembly.GetEntryAssembly();
                if (asm == null)
                {
                    asm = Assembly.GetExecutingAssembly();
                }
                var appPrefix = asm.GetName().Name.Replace(".", "");
                var appName   = string.Format("{0}", appPrefix);
                builder.Add("Application Name", appName);
                connectionString = builder.ToString();
            }
            return(connectionString);
        }
예제 #17
0
        public static string ConnectionBuilder(Dictionary <string, string> parmcoll)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();


            foreach (var parameter in parmcoll.Keys)
            {
                string cmd = parameter.Trim().Replace("_", " ");

                if (builder.ContainsKey(cmd))
                {
                    builder[cmd] = parmcoll[parameter].Trim().Replace(";", "");
                }
            }


            if (Arguments.GetValByKey("ShowConnectionString").Length > 0)
            {
                Console.WriteLine(builder.ConnectionString);
            }


            return(builder.ConnectionString);;
        }
        /// <summary>
        /// Ensures that credentials are provided for the given connection string object.
        /// </summary>
        /// <param name="connectionString">
        /// Input connection string object.
        /// </param>
        /// <param name="parameterName">
        /// Parameter name of the connection string object.
        /// </param>
        /// <param name="secureCredential">
        /// Input secure SQL credential object.
        /// </param>
        internal static void EnsureCredentials(SqlConnectionStringBuilder connectionString, string parameterName, SqlCredential secureCredential)
        {
            // Check for integrated authentication
            if (connectionString.IntegratedSecurity)
            {
                return;
            }

            // Check for active directory integrated authentication (if supported)
            if (connectionString.ContainsKey(ShardMapUtils.Authentication) &&
                connectionString[ShardMapUtils.Authentication].ToString().Equals(ShardMapUtils.ActiveDirectoryIntegratedStr))
            {
                return;
            }

            // If secure credential not specified, verify that user/pwd are in the connection string. If secure credential
            // specified, verify user/pwd are not in insecurely in the connection string.
            if (secureCredential == null)
            {
                // UserID must be set when integrated authentication is disabled.
                if (string.IsNullOrEmpty(connectionString.UserID))
                {
                    throw new ArgumentException(
                              StringUtils.FormatInvariant(
                                  Errors._SqlShardMapManagerCredentials_ConnectionStringPropertyRequired,
                                  "UserID"),
                              parameterName);
                }

                // Password must be set when integrated authentication is disabled.
                if (string.IsNullOrEmpty(connectionString.Password))
                {
                    throw new ArgumentException(
                              StringUtils.FormatInvariant(
                                  Errors._SqlShardMapManagerCredentials_ConnectionStringPropertyRequired,
                                  "Password"),
                              parameterName);
                }
            }
            else
            {
                // UserID must NOT be set when a secure SQL credential is provided.
                if (!string.IsNullOrEmpty(connectionString.UserID))
                {
                    throw new ArgumentException(
                              StringUtils.FormatInvariant(
                                  Errors._SqlShardMapManagerCredentials_ConnectionStringPropertyNotAllowed,
                                  "UserID"),
                              parameterName);
                }

                // Password must NOT be set when a secure SQL credential is provided.
                if (!string.IsNullOrEmpty(connectionString.Password))
                {
                    throw new ArgumentException(
                              StringUtils.FormatInvariant(
                                  Errors._SqlShardMapManagerCredentials_ConnectionStringPropertyNotAllowed,
                                  "Password"),
                              parameterName);
                }
            }
        }
 public bool ContainsKey(string keyword)
 {
     return(csb.ContainsKey(keyword));
 }