Ejemplo n.º 1
0
        public void SqlLocalDbInstance_Delete_Deletes_Instance()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            string instanceName = Guid.NewGuid().ToString();

            SqlLocalDbApi.CreateInstance(instanceName);

            Mock <ISqlLocalDbInstance> mock = new Mock <ISqlLocalDbInstance>();

            mock.Setup((p) => p.Name).Returns(instanceName);

            ISqlLocalDbInstanceInfo info = SqlLocalDbApi.GetInstanceInfo(instanceName);

            Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
            Assert.IsTrue(info.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect.");

            ISqlLocalDbInstance instance = mock.Object;

            // Act
            SqlLocalDbInstance.Delete(instance);

            // Assert
            info = SqlLocalDbApi.GetInstanceInfo(instanceName);
            Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
            Assert.IsFalse(info.Exists, "The SQL LocalDB instance was not deleted.");

            string path = Path.Combine(SqlLocalDbApi.GetInstancesFolderPath(), instanceName);

            Assert.IsTrue(Directory.Exists(path), "The instance folder was deleted.");
            Assert.AreNotEqual(0, Directory.GetFiles(path).Length, "The instance files were deleted.");
        }
        public GrainStorageTests(ITestOutputHelper output)
        {
            timingFactor = CalibrateTimings();

            this.output = output;

            var rnd = new Random();

            dbNames = new Dictionary <string, SqlConnectionStringBuilder>();

            dbInstanceName = rnd.Next().ToString();

            ISqlLocalDbProvider provider = new SqlLocalDbProvider();

            instance = provider.GetOrCreateInstance(dbInstanceName);

            instance.Start();

            //do the database setups
            dbNames.Add("basic", CreateADatabase(rnd));
            dbNames.Add("SimpleSQLStore", CreateADatabase(rnd));

            //this is the call to start up the test cluster
            base.Initialize();
        }
Ejemplo n.º 3
0
        public void SqlLocalDbInstance_Delete_If_SqlLocalDbApi_AutomaticallyDeleteInstanceFiles_Is_True()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            Helpers.InvokeInNewAppDomain(
                () =>
            {
                SqlLocalDbApi.AutomaticallyDeleteInstanceFiles = true;

                string instanceName = Guid.NewGuid().ToString();

                SqlLocalDbApi.CreateInstance(instanceName);

                Mock <ISqlLocalDbInstance> mock = new Mock <ISqlLocalDbInstance>();
                mock.Setup((p) => p.Name).Returns(instanceName);

                ISqlLocalDbInstanceInfo info = SqlLocalDbApi.GetInstanceInfo(instanceName);
                Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
                Assert.IsTrue(info.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect.");

                ISqlLocalDbInstance instance = mock.Object;

                // Act
                SqlLocalDbInstance.Delete(instance);

                // Assert
                info = SqlLocalDbApi.GetInstanceInfo(instanceName);
                Assert.IsNotNull(info, "SqlLocalDbApi.GetInstanceInfo() returned null.");
                Assert.IsFalse(info.Exists, "The SQL LocalDB instance was not deleted.");

                string path = Path.Combine(SqlLocalDbApi.GetInstancesFolderPath(), instanceName);
                Assert.IsFalse(Directory.Exists(path), "The instance folder was not deleted.");
            });
        }
Ejemplo n.º 4
0
        private bool CheckSqlServer()
        {
            try
            {
                ISqlLocalDbProvider provider = new SqlLocalDbProvider();
                ISqlLocalDbInstance instance = provider.GetOrCreateInstance(Global.Product);
                instance.Start();
            } catch (Exception e)
            {
                MessageBox.Show("LocalDB Instance could not be started:\n\n" + e.Message, $"{Global.Product}", MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            // create Database and Files if MDF not exists
            if (!File.Exists(Global.DatabaseMdfPath))
            {
                DbCreator.Create(Global.Product, Global.DatabaseFolder);
            }

            using (SqlConnection c = new SqlConnection(Properties.Settings.Default.SQLEXPRESS))
            {
                try
                {
                    c.Open();
                    return(true);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error opening Database:\n\n" + e.Message, $"{Global.Product}", MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }
            }
        }
Ejemplo n.º 5
0
        public void SqlLocalDbProvider_As_ISqlLocalDbFactory_GetInstance_Returns_Specified_Instance()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            ISqlLocalDbProvider target = new SqlLocalDbProvider();
            string instanceName        = Guid.NewGuid().ToString();

            // Act
            SqlLocalDbApi.CreateInstance(instanceName);

            try
            {
                // Assert
                ISqlLocalDbInstance result = target.GetInstance(instanceName);

                Assert.IsNotNull(result, "CreateInstance() returned null.");
                Assert.AreEqual(instanceName, result.Name, "SqlLocalDbInstance.Name is incorrect.");

                ISqlLocalDbInstanceInfo info = result.GetInstanceInfo();

                Assert.IsTrue(info.Exists, "ISqlLocalDbInstanceInfo.Exists is incorrect.");
                Assert.IsFalse(info.IsRunning, "ISqlLocalDbInstanceInfo.IsRunning is incorrect.");

                Assert.IsTrue(Guid.TryParse(result.Name, out Guid unused), "SqlLocalDbInstance.Name is not a valid GUID.");
            }
            finally
            {
                SqlLocalDbApi.DeleteInstance(instanceName);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TemporarySqlLocalDbInstance"/> class.
        /// </summary>
        /// <param name="instanceName">The name of the temporary SQL LocalDB instance.</param>
        /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use to create the temporary instance.</param>
        /// <param name="deleteFiles">Whether to delete the file(s) associated with the SQL LocalDB instance when deleted.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instanceName"/> or <paramref name="provider"/> is <see langword="null"/>.
        /// </exception>
        public TemporarySqlLocalDbInstance(string instanceName, ISqlLocalDbProvider provider, bool deleteFiles)
        {
            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }

            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            _instance    = provider.CreateInstance(instanceName);
            _deleteFiles = deleteFiles;

            try
            {
                _instance.Start();
            }
            catch (Exception)
            {
                SqlLocalDbInstance.Delete(_instance, throwIfNotFound: true, deleteFiles: _deleteFiles);
                throw;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Deletes the specified <see cref="ISqlLocalDbInstance"/> instance.
        /// </summary>
        /// <param name="instance">The LocalDB instance to delete.</param>
        /// <param name="throwIfNotFound">
        /// Whether to throw an exception if the SQL LocalDB instance
        /// associated with <paramref name="instance"/> cannot be found.
        /// </param>
        /// <param name="deleteFiles">
        /// Whether to delete the file(s) associated with the SQL LocalDB instance.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="SqlLocalDbException">
        /// The SQL Server LocalDB instance specified by <paramref name="instance"/> could not be deleted.
        /// </exception>
        internal static void Delete(ISqlLocalDbInstance instance, bool throwIfNotFound, bool deleteFiles)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            try
            {
                SqlLocalDbApi.DeleteInstanceInternal(instance.Name, throwIfNotFound, deleteFiles);
            }
            catch (SqlLocalDbException ex)
            {
                string message = SRHelper.Format(
                    SR.SqlLocalDbInstance_DeleteFailedFormat,
                    instance.Name);

                Logger.Error(Logger.TraceEvent.DeleteFailed, message);

                throw new SqlLocalDbException(
                          message,
                          ex.ErrorCode,
                          ex.InstanceName,
                          ex);
            }
        }
        //public override void SetUp()
        //{
        //    try
        //    {
        //        base.SetUp();

        //        // Start a Local DB instance.
        //        _SqlLocalDbInstance = _SqlLocalDbProvider.GetOrCreateInstance("SchemaTesting");
        //        _SqlLocalDbInstance.Start();

        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e.ToString());
        //        throw;
        //    }

        //}

        private void PrepareTestData()
        {
            _SqlLocalDbProvider = new SqlLocalDbProvider();
            _SqlLocalDbInstance = _SqlLocalDbProvider.GetOrCreateInstance("SchemaTesting");
            _SqlLocalDbInstance.Start();

            // Get the SQL to create a couple of differen tables
            string tableOneName;
            string createTableSql1 = GetCreateTestTableSql(out tableOneName);

            TestEntityName = tableOneName;

            string table2Name;
            string createTableSql2 = GetCreateTestTableSql(out table2Name);

            TestEntityName2 = table2Name;

            // create a foreign key column between them.
            var alterTableAddForeignKey = string.Format("ALTER TABLE {0} ADD {1}Id UNIQUEIDENTIFIER CONSTRAINT {0}_{1} REFERENCES {1}", tableOneName, table2Name);


            //  CreateTestEntity();

            // Create table in LocalDB
            using (SqlConnection connection = _SqlLocalDbInstance.CreateConnection())
            {
                connection.Open();

                // create the first table
                var command = connection.CreateCommand();
                command.CommandType = CommandType.Text;

                Console.WriteLine("Executing local db command " + createTableSql1);
                command.CommandText = createTableSql1;

                var result = command.ExecuteNonQuery();
                Assert.AreEqual(result, -1);

                // create the second table
                command.CommandText = createTableSql2;
                result = command.ExecuteNonQuery();
                Assert.AreEqual(result, -1);

                // create a column in the first table that is a foreign key so it references the second table
                command.CommandText = alterTableAddForeignKey;
                result = command.ExecuteNonQuery();
                Assert.AreEqual(result, -1);
            }

            // Create first table in Crm
            ExecuteCrmNonQuery(createTableSql1, -1);

            // Create second table in Crm
            ExecuteCrmNonQuery(createTableSql2, -1);

            // create a column in the first table that is a foreign key so it references the second table
            ExecuteCrmNonQuery(alterTableAddForeignKey, -1);
        }
Ejemplo n.º 9
0
        private void Initialize(string instanceName, string databaseName)
        {
            this.databaseName = databaseName;
            this.instanceName = instanceName;

            var existing = SqlLocalDbApi.GetInstanceInfo(instanceName);

            if (existing.Exists)
            {
                if (existing.IsRunning)
                {
                    SqlLocalDbApi.StopInstance(instanceName);
                }
                SqlLocalDbApi.DeleteInstance(instanceName);
            }


            ISqlLocalDbProvider provider = new SqlLocalDbProvider();

            this.instance = provider.GetOrCreateInstance(instanceName);

            instance.Start();


            var connectionStringBuilder = instance.CreateConnectionStringBuilder();

            using (var conn = new SqlConnection(connectionStringBuilder.ConnectionString))
            {
                var serverConnection = new ServerConnection(conn);

                // By default, LocalDB stores database files in the user's home folder. Messy for temporary test databases.
                // Store them in the user's temp folder instead.
                var testDatabasesDirectory = Path.Combine(Path.GetTempPath(), "TestDatabases");

                if (!Directory.Exists(testDatabasesDirectory))
                {
                    Directory.CreateDirectory(testDatabasesDirectory);
                }

                // Generate a unique name for our mdf file to avoid clashing with other ongoing test runs.
                var databaseFileNameRoot = string.Format("{0}_{1}_{2}", databaseName, DateTime.Now.ToString("yyyyMMdd_HHmmss"), Guid.NewGuid().ToString("N"));

                var mdfFileName = databaseFileNameRoot + ".mdf";
                var ldfFileName = databaseFileNameRoot + "_log.ldf";

                this.mdfFilePath = Path.Combine(testDatabasesDirectory, mdfFileName);
                this.ldfFilePath = Path.Combine(testDatabasesDirectory, ldfFileName);

                var sql = string.Format("CREATE DATABASE {0} ON (NAME = N'{0}', FILENAME = '{1}')", databaseName, this.mdfFilePath);

                Console.WriteLine(string.Format("Creating database {0} at {1}", databaseName, this.mdfFilePath));
                serverConnection.ExecuteNonQuery(sql);
            }

            connectionStringBuilder.InitialCatalog = this.databaseName;
            this.connectionString = connectionStringBuilder.ConnectionString;
        }
Ejemplo n.º 10
0
        private static string GetConnectionString(ISqlLocalDbInstance instance, string pathToModel)
        {
            var sqlConnectionStringBuilder = instance.CreateConnectionStringBuilder();

            sqlConnectionStringBuilder.InitialCatalog     = Path.GetFileNameWithoutExtension(pathToModel);
            sqlConnectionStringBuilder.IntegratedSecurity = true;
            sqlConnectionStringBuilder.AttachDBFilename   = pathToModel;
            return(sqlConnectionStringBuilder.ToString());
        }
Ejemplo n.º 11
0
        public void SqlLocalDbInstance_Delete_Throws_If_Instance_Is_Null()
        {
            // Arrange
            ISqlLocalDbInstance instance = null;

            // Act and Assert
            throw ErrorAssert.Throws <ArgumentNullException>(
                      () => SqlLocalDbInstance.Delete(instance),
                      "instance");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Restarts the specified <see cref="ISqlLocalDbInstance"/> instance.
        /// </summary>
        /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> instance to restart.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        public static void Restart(this ISqlLocalDbInstance instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            instance.Stop();
            instance.Start();
        }
Ejemplo n.º 13
0
        private static string CreateConnectionString(ISqlLocalDbInstance localDbInstance, string databaseName)
        {
            var connectionStringBuilder = localDbInstance.CreateConnectionStringBuilder();

            connectionStringBuilder.MultipleActiveResultSets = true;
            connectionStringBuilder.IntegratedSecurity       = true;
            connectionStringBuilder.InitialCatalog           = databaseName;

            return(connectionStringBuilder.ToString());
        }
        public SqlLocalDbTestEnvironmentBootstrapper(IDbMigrator dbMigrator,
            ITestDatabaseInstaller testDatabaseInstaller, ISqlLocalDbInstance sqlLocalDbInstance)
        {
            if (dbMigrator == null) throw new ArgumentNullException(nameof(dbMigrator));
            if (testDatabaseInstaller == null) throw new ArgumentNullException(nameof(testDatabaseInstaller));
            if (sqlLocalDbInstance == null) throw new ArgumentNullException(nameof(sqlLocalDbInstance));

            _dbMigrator = dbMigrator;
            _testDatabaseInstaller = testDatabaseInstaller;
            _sqlLocalDbInstance = sqlLocalDbInstance;
        }
        public MsSqlEventStoreFixture()
        {
            var localDbProvider = new SqlLocalDbProvider
            {
                Version = "11.0"
            };
            _localDbInstance = localDbProvider.GetOrCreateInstance("CedarEventStoreTests");
            _localDbInstance.Start();

            var uniqueName = Guid.NewGuid().ToString().Replace("-", string.Empty);
            _databaseName = $"CedarEventStoreTests_{uniqueName}";
        }
        private static void AssertThrowsObjectDisposedException(Action <TemporarySqlLocalDbInstance> action)
        {
            // Arrange
            ISqlLocalDbInstance instance = CreateMockInstance();

            using (TemporarySqlLocalDbInstance target = new TemporarySqlLocalDbInstance(instance))
            {
                target.Dispose();

                // Act
                action(target);
            }
        }
Ejemplo n.º 17
0
 private static ITestEnvironmentBootstrapper GetBootstrapper(IDbMigrator dbMigrator, ISqlLocalDbInstance sqlLocalDbInstance)
 {
     // Poor-man's Dependency Injection
     var embeddedTextResourceReader = new EmbeddedTextResourceReader();
     var sqlBatchExtractor = new SqlBatchExtractor();
     var tsqltInstaller = new EmbeddedResourceTsqltInstaller(embeddedTextResourceReader, sqlBatchExtractor);
     var sqlCommandExecutor = new SqlCommandExecutor();
     var databaseDropper = new DatabaseDropper(sqlCommandExecutor);
     var testDatabaseCreator = new TestDatabaseCreator(DatabaseName, databaseDropper, sqlCommandExecutor);
     var testDatabaseInstaller = new TestDatabaseInstaller(tsqltInstaller, testDatabaseCreator);
     return new SqlLocalDbTestEnvironmentBootstrapper(dbMigrator ?? new DefaultDbMigrator(),
         testDatabaseInstaller, sqlLocalDbInstance);
 }
        public void TemporarySqlLocalDbInstance_Unshare_Invokes_Wrapped_Instance()
        {
            // Arrange
            ISqlLocalDbInstance instance = CreateMockInstance();

            using (TemporarySqlLocalDbInstance target = new TemporarySqlLocalDbInstance(instance))
            {
                // Act
                target.Unshare();

                // Assert
                Mock.Get(instance).Verify((p) => p.Unshare(), Times.Once());
            }
        }
        public void TemporarySqlLocalDbInstance_Share_Invokes_Wrapped_Instance()
        {
            // Arrange
            ISqlLocalDbInstance instance = CreateMockInstance();

            using (TemporarySqlLocalDbInstance target = new TemporarySqlLocalDbInstance(instance))
            {
                string sharedName = Guid.NewGuid().ToString();

                // Act
                target.Share(sharedName);

                // Assert
                Mock.Get(instance).Verify((p) => p.Share(sharedName), Times.Once());
            }
        }
        public MsSqlEventStoreFixture(string schema)
        {
            _schema = schema;
            var localDbProvider = new SqlLocalDbProvider
            {
                Version = "11.0"
            };

            _localDbInstance = localDbProvider.GetOrCreateInstance("CedarEventStoreTests");
            _localDbInstance.Start();

            var uniqueName = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString().PadLeft(20, '0');

            _databaseName = $"CedarEventStoreTests_{uniqueName}";

            ConnectionString = CreateConnectionString();
        }
Ejemplo n.º 21
0
        public MsSqlStreamStoreFixture(string schema)
        {
            _schema = schema;
            var localDbProvider = new SqlLocalDbProvider
            {
                Version = s_sqlLocalDbProviderVersionToUse
            };

            _localDbInstance = localDbProvider.GetOrCreateInstance("StreamStoreTests");
            _localDbInstance.Start();

            var uniqueName = Guid.NewGuid().ToString().Replace("-", string.Empty);

            _databaseName = $"StreamStoreTests-{uniqueName}";

            ConnectionString = CreateConnectionString();
        }
Ejemplo n.º 22
0
        public SqlServerTests()
        {
            _localDb = new SqlLocalDbApiWrapper();
            ISqlLocalDbProvider provider = new SqlLocalDbProvider();
            string instanceName          = Guid.NewGuid().ToString();

            _instance = provider.CreateInstance(instanceName);

            _instance.Start();

            _connection = _instance.CreateConnection();
            _connection.Open();

            _database = new Database(_connection);

            _database.Execute("create database [SqlServerTests]");
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates an instance of <see cref="DbConnectionStringBuilder"/> that can be used to connect to the SQL LocalDB instance.
        /// </summary>
        /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> to get the connection string builder for.</param>
        /// <param name="modelConnectionStringName">The name of the connection string for the model in the application configuration file.</param>
        /// <param name="initialCatalog">The optional name to use for the Initial Catalog in the provider connection string to override the default, if present.</param>
        /// <returns>
        /// The created instance of <see cref="DbConnectionStringBuilder"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// No connection string with the name specified by <paramref name="modelConnectionStringName"/> can be found in the application configuration file.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The value of the <see cref="ISqlLocalDbInstance.NamedPipe"/> property of <paramref name="instance"/> is <see langword="null"/> or the empty string.
        /// </exception>
        public static DbConnectionStringBuilder GetConnectionStringForModel(this ISqlLocalDbInstance instance, string modelConnectionStringName, string initialCatalog)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            var connectionStringSettings = ConfigurationManager.ConnectionStrings
                                           .OfType <ConnectionStringSettings>()
                                           .Where((p) => string.Equals(p.Name, modelConnectionStringName, StringComparison.Ordinal))
                                           .FirstOrDefault();

            if (connectionStringSettings == null)
            {
                throw new ArgumentException(SRHelper.Format(SR.Extensions_NoConnectionStringFormat, modelConnectionStringName), nameof(modelConnectionStringName));
            }

            return(CreateBuilder(connectionStringSettings, instance.NamedPipe, initialCatalog));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Teste l'existence d'une base de donnée de KL2 dans l'instance par défault
        /// </summary>
        /// <returns></returns>
        public static async Task <bool> LocalDB_KL2DataBase_Exists()
        {
            try
            {
                ISqlLocalDbInstance instance = (new SqlLocalDbProvider()).GetInstance(Const.InstanceName_v3);
                using (var conn = instance.CreateConnection())
                {
                    await conn.OpenAsync();

                    conn.ChangeDatabase(Const.DataBaseName_v3);
                    conn.Close();
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public PubSubStoreTests(ITestOutputHelper output) : base()
        {
            this.output = output;

            var rnd = new Random();

            dbNames = new Dictionary <string, string>()
            {
                { "PubSubStore", rnd.Next().ToString() },
            };

            dbInstanceName = rnd.Next().ToString();

            ISqlLocalDbProvider provider = new SqlLocalDbProvider();

            instance = provider.GetOrCreateInstance(dbInstanceName);

            instance.Start();

            Initialize();
        }
        public PubSubStoreTests(ITestOutputHelper output) : base()
        {
            this.output = output;

            var rnd = new Random();

            dbNames = new Dictionary<string, string>()
            {
                { "PubSubStore", rnd.Next().ToString() },
                { "basic", rnd.Next().ToString() },
            };

            dbInstanceName = rnd.Next().ToString();

            ISqlLocalDbProvider provider = new SqlLocalDbProvider();
            instance = provider.GetOrCreateInstance(dbInstanceName);

            instance.Start();

            Initialize();
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates an instance of <see cref="DbConnectionStringBuilder"/> that can be used to connect to the SQL LocalDB instance
        /// using the only connection string configured in the current application configuration file.
        /// </summary>
        /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> to get the connection string builder for.</param>
        /// <param name="initialCatalog">The optional name to use for the Initial Catalog in the provider connection string to override the default, if present.</param>
        /// <returns>
        /// The created instance of <see cref="DbConnectionStringBuilder"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// No connection strings are configured in the application configuration file, more than one
        /// connection string is configured in the application configuration file or the value of the
        /// <see cref="ISqlLocalDbInstance.NamedPipe"/> property of <paramref name="instance"/> is
        /// <see langword="null"/> or the empty string.
        /// </exception>
        /// <remarks>
        /// Connection strings may be inherited from outside the current application's configuration file, such as from
        /// <c>machine.config</c>.  To use this overload it is recommended that, unless otherwise needed, a <c>&lt;clear/&gt;</c>
        /// element is added to the <c>&lt;connectionStrings&gt;</c> section of your application configuration file to
        /// prevent the default connection strings from being inherited.
        /// </remarks>
        public static DbConnectionStringBuilder GetConnectionStringForDefaultModel(this ISqlLocalDbInstance instance, string initialCatalog)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            var connectionStrings = ConfigurationManager.ConnectionStrings
                                    .OfType <ConnectionStringSettings>()
                                    .ToList();

            if (connectionStrings.Count < 1)
            {
                throw new InvalidOperationException(SR.Extensions_NoConnectionStrings);
            }
            else if (connectionStrings.Count > 1)
            {
                throw new InvalidOperationException(SR.Extensions_NoSingleConnectionString);
            }

            return(CreateBuilder(connectionStrings[0], instance.NamedPipe, initialCatalog));
        }
Ejemplo n.º 28
0
        public void SqlLocalDbInstance_Delete_Throws_If_Instance_Is_Invalid()
        {
            // Arrange
            Helpers.EnsureLocalDBInstalled();

            const string InstanceName = "\\\\";

            Mock <ISqlLocalDbInstance> mock = new Mock <ISqlLocalDbInstance>();

            mock.Setup((p) => p.Name).Returns(InstanceName);

            ISqlLocalDbInstance instance = mock.Object;

            // Act
            SqlLocalDbException error = ErrorAssert.Throws <SqlLocalDbException>(
                () => SqlLocalDbInstance.Delete(instance));

            // Assert
            Assert.AreEqual(SqlLocalDbErrors.InvalidInstanceName, error.ErrorCode, "SqlLocalDbException.ErrorCode is incorrect.");
            Assert.AreEqual(InstanceName, error.InstanceName, "SqlLocalDbException.InstanceName is incorrect.");

            throw error;
        }
Ejemplo n.º 29
0
        private void SetupLocalDbInstance(ProviderConfiguration config)
        {
            var localDbApi = new SqlLocalDbApiWrapper();

            if (!localDbApi.IsLocalDBInstalled())
            {
                throw new InvalidOperationException("LocalDB is not installed on this machine.");
            }

            if (!string.IsNullOrWhiteSpace(config.LocalDbInstanceName))
            {
                LogAction("Preparing LocalDb instance: " + config.LocalDbInstanceName);

                ISqlLocalDbInstance localDbInstance =
                    GetAppropriateLocalDbInstance(
                        localDbApi,
                        config.LocalDbInstanceName,
                        config.Versions
                        .Cast <LocalDbAllowedVersion>()
                        .Select(v => v.Version));

                localDbInstance.Start();
            }
            else if (!string.IsNullOrWhiteSpace(config.ConnectionString))
            {
                LogAction("LocalDb instance name was not provided so we must assume it is already set up.");

                // SQL Server instance must already be set up.
                return;
            }
            else
            {
                throw new InvalidOperationException(
                          "IsLocalDbInstance was true in configuration but no instance name or connection string was configured.");
            }
        }
        public GrainStorageTests(ITestOutputHelper output)
        {
            timingFactor = CalibrateTimings();

            this.output = output;

            var rnd = new Random();

            dbNames = new Dictionary<string, SqlConnectionStringBuilder>();

            dbInstanceName = rnd.Next().ToString();

            ISqlLocalDbProvider provider = new SqlLocalDbProvider();
            instance = provider.GetOrCreateInstance(dbInstanceName);

            instance.Start();

            //do the database setups
            dbNames.Add("basic", CreateADatabase(rnd));
            dbNames.Add("SimpleSQLStore", CreateADatabase(rnd));

            //this is the call to start up the test cluster 
            base.Initialize();
        }
        public void WriteSchemaFilesForComparison()
        {
            PrepareTestData();

            var sut = new SchemaCollectionsProvider();

            _SqlLocalDbInstance = _SqlLocalDbProvider.GetOrCreateInstance("SchemaTesting");
            _SqlLocalDbInstance.Start();

            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            var builder = GetStringBuilder();

            using (var conn = new CrmDbConnection(connectionString.ConnectionString))
            {
                // Output common schema collections (https://msdn.microsoft.com/en-us/library/ms254501(v=vs.110).aspx)

                // and also sql local db sql server schema collections (https://msdn.microsoft.com/en-us/library/ms254501(v=vs.110).aspx)
                using (SqlConnection connection = _SqlLocalDbInstance.CreateConnection())
                {
                    connection.Open();

                    // for each connection, we are writing its schema collection to CSV format for easy comparison.
                    // We are writing sql server first, followed by crmado's.

                    WriteDataTableToCsv("Sql MetaDataCollections", builder, connection.GetSchema("MetaDataCollections"));
                    WriteDataTableToCsv("CrmAdo MetaDataCollections", builder, sut.GetMetadataCollections());

                    WriteDataTableToCsv("Sql DataSourceInformation", builder, connection.GetSchema("DataSourceInformation"));
                    WriteDataTableToCsv("CrmAdo DataSourceInformation", builder, sut.GetDataSourceInfo(conn));

                    WriteDataTableToCsv("Sql DataTypes", builder, connection.GetSchema("DataTypes"));
                    WriteDataTableToCsv("CrmAdo DataTypes", builder, sut.GetDataTypes());

                    WriteDataTableToCsv("Sql Restrictions", builder, connection.GetSchema("Restrictions"));
                    WriteDataTableToCsv("CrmAdo Restrictions", builder, sut.GetRestrictions());

                    WriteDataTableToCsv("Sql ReservedWords", builder, connection.GetSchema("ReservedWords"));
                    WriteDataTableToCsv("CrmAdo ReservedWords", builder, sut.GetReservedWords());

                    WriteDataTableToCsv("Sql Tables", builder, connection.GetSchema("Tables"));
                    WriteDataTableToCsv("CrmAdo Tables", builder, sut.GetTables(conn, null));

                    WriteDataTableToCsv("Sql Columns", builder, connection.GetSchema("Columns"));
                    WriteDataTableToCsv("CrmAdo Columns", builder, sut.GetColumns(conn, null));

                    WriteDataTableToCsv("Sql Views", builder, connection.GetSchema("Views"));
                    WriteDataTableToCsv("CrmAdo Views", builder, sut.GetViews(conn, null));

                    WriteDataTableToCsv("Sql ViewColumns", builder, connection.GetSchema("ViewColumns"));
                    WriteDataTableToCsv("CrmAdo View Columns", builder, sut.GetViewColumns(conn, null));

                    WriteDataTableToCsv("Sql Indexes", builder, connection.GetSchema("Indexes"));
                    WriteDataTableToCsv("CrmAdo Indexes", builder, sut.GetIndexes(conn, null));

                    WriteDataTableToCsv("Sql IndexColumns", builder, connection.GetSchema("IndexColumns"));
                    WriteDataTableToCsv("CrmAdo IndexColumns", builder, sut.GetIndexColumns(conn, null));

                    WriteDataTableToCsv("Sql ForeignKeys", builder, connection.GetSchema("ForeignKeys"));
                    WriteDataTableToCsv("CrmAdo ForeignKeys", builder, sut.GetForeignKeys(conn, null));

                    WriteDataTableToCsv("Sql Users", builder, connection.GetSchema("Users"));
                    WriteDataTableToCsv("CrmAdo Users", builder, sut.GetUsers(conn, null));

                    WriteDataTableToCsv("Sql Databases", builder, connection.GetSchema("Databases"));
                    WriteDataTableToCsv("CrmAdo Databases", builder, sut.GetDatabases(conn, null));
                }

                _SqlLocalDbInstance.Stop();

            }

            // save the csv file to disk

            var path = System.IO.Path.Combine(Environment.CurrentDirectory, "schema comparison report" + ".csv");
            System.IO.File.WriteAllText(path, builder.ToString());
            Console.WriteLine("comparison report written to: " + path);
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Creates an instance of <see cref="DbConnectionStringBuilder"/> that can be used to connect to the SQL LocalDB instance.
 /// </summary>
 /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> to get the connection string builder for.</param>
 /// <param name="modelConnectionStringName">The name of the connection string for the model in the application configuration file.</param>
 /// <returns>
 /// The created instance of <see cref="DbConnectionStringBuilder"/>.
 /// </returns>
 /// <exception cref="ArgumentException">
 /// No connection string with the name specified by <paramref name="modelConnectionStringName"/> can be found in the application configuration file.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="instance"/> is <see langword="null"/>.
 /// </exception>
 public static DbConnectionStringBuilder GetConnectionStringForModel(this ISqlLocalDbInstance instance, string modelConnectionStringName) => instance.GetConnectionStringForModel(modelConnectionStringName, null);
        /// <summary>
        /// Initializes a new instance of the <see cref="TemporarySqlLocalDbInstance"/> class.
        /// </summary>
        /// <param name="instanceName">The name of the temporary SQL LocalDB instance.</param>
        /// <param name="provider">The <see cref="ISqlLocalDbProvider"/> to use to create the temporary instance.</param>
        /// <param name="deleteFiles">Whether to delete the file(s) associated with the SQL LocalDB instance when deleted.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instanceName"/> or <paramref name="provider"/> is <see langword="null"/>.
        /// </exception>
        public TemporarySqlLocalDbInstance(string instanceName, ISqlLocalDbProvider provider, bool deleteFiles)
        {
            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }

            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            _instance = provider.CreateInstance(instanceName);
            _deleteFiles = deleteFiles;

            try
            {
                _instance.Start();
            }
            catch (Exception)
            {
                SqlLocalDbInstance.Delete(_instance, throwIfNotFound: true, deleteFiles: _deleteFiles);
                throw;
            }
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Creates an instance of <see cref="DbConnectionStringBuilder"/> that can be used to connect to the SQL LocalDB instance
 /// using the only connection string configured in the current application configuration file.
 /// </summary>
 /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> to get the connection string builder for.</param>
 /// <returns>
 /// The created instance of <see cref="DbConnectionStringBuilder"/>.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="instance"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// No connection strings are configured in the application configuration file or more than one
 /// connection string is configured in the application configuration file.
 /// </exception>
 /// <remarks>
 /// Connection strings may be inherited from outside the current application's configuration file, such as from
 /// <c>machine.config</c>.  To use this overload it is recommended that, unless otherwise needed, a <c>&lt;clear/&gt;</c>
 /// element is added to the <c>&lt;connectionStrings&gt;</c> section of your application configuration file to
 /// prevent the default connection strings from being inherited.
 /// </remarks>
 public static DbConnectionStringBuilder GetConnectionStringForDefaultModel(this ISqlLocalDbInstance instance) => instance.GetConnectionStringForDefaultModel(null);
Ejemplo n.º 35
0
        /// <summary>
        /// Creates an instance of <see cref="DbConnection"/> that can be used to connect to the SQL LocalDB instance.
        /// </summary>
        /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> to get the connection string builder for.</param>
        /// <param name="modelConnectionStringName">The name of the connection string for the model in the application configuration file.</param>
        /// <param name="initialCatalog">The optional name to use for the Initial Catalog in the provider connection string to override the default, if present.</param>
        /// <returns>
        /// The created instance of <see cref="DbConnectionStringBuilder"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// No connection string with the name specified by <paramref name="modelConnectionStringName"/> can be found in the application configuration file.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        public static DbConnection GetConnectionForModel(this ISqlLocalDbInstance instance, string modelConnectionStringName, string initialCatalog)
        {
            DbConnectionStringBuilder builder = instance.GetConnectionStringForModel(modelConnectionStringName, initialCatalog);

            return(CreateConnection(builder.ConnectionString));
        }
Ejemplo n.º 36
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            ISqlLocalDbApi localDB = new SqlLocalDbApiWrapper();

            if (!localDB.IsLocalDBInstalled())
            {
                MessageBox.Show("Máy tính của bạn phải cài đặt SQL Server LocalDB hoặc phiên bản Express để có thể sử dụng phần mềm.");
                return;
            }

            string uuid = "nhom7-928cf731-171f-464f-aa55-24e814eeb224";

            ISqlLocalDbProvider provider = new SqlLocalDbProvider();

            IList <ISqlLocalDbInstanceInfo> instances = provider.GetInstances();

            bool flag = false;

            foreach (ISqlLocalDbInstanceInfo instanceInfo in instances)
            {
                if (instanceInfo.Name == uuid)
                {
                    flag = true;
                    break;
                }
            }

            if (!flag)
            {
                WaitForm frm = new WaitForm();
                frm.Show();
                ISqlLocalDbInstance instance = provider.CreateInstance(uuid);
                instance.Start();

                try
                {
                    if (IsCurrentUserAdmin())
                    {
                    }
                    try
                    {
                        using (SqlConnection connection = instance.CreateConnection())
                        {
                            connection.Open();
                            try
                            {
                                string   scriptText   = Resources.script.ToString();
                                string[] splitter     = new string[] { "\r\nGO\r\n" };
                                string[] commandTexts = scriptText.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
                                foreach (string commandText in commandTexts)
                                {
                                    using (SqlCommand command = new SqlCommand(commandText, connection))
                                    {
                                        command.ExecuteNonQuery();
                                    }
                                }
                            }
                            finally
                            {
                                connection.Close();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                    finally
                    {
                        if (IsCurrentUserAdmin())
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    instance.Stop();
                }

                frm.Close();
            }
            else
            {
                ISqlLocalDbInstance instance = provider.GetInstance(uuid);
            }

            Global.connstring = @"Data Source=(LocalDB)\nhom7-928cf731-171f-464f-aa55-24e814eeb224;Initial Catalog=QUANLYTHUVIEN_Nhom7_14521100_15520048_15520062_15520115;Integrated Security=True";

            Application.Run(new frmDangNhap());
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Deletes the specified <see cref="ISqlLocalDbInstance"/> instance.
        /// </summary>
        /// <param name="instance">The LocalDB instance to delete.</param>
        /// <param name="throwIfNotFound">
        /// Whether to throw an exception if the SQL LocalDB instance
        /// associated with <paramref name="instance"/> cannot be found.
        /// </param>
        /// <param name="deleteFiles">
        /// Whether to delete the file(s) associated with the SQL LocalDB instance.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="SqlLocalDbException">
        /// The SQL Server LocalDB instance specified by <paramref name="instance"/> could not be deleted.
        /// </exception>
        internal static void Delete(ISqlLocalDbInstance instance, bool throwIfNotFound, bool deleteFiles)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            try
            {
                SqlLocalDbApi.DeleteInstanceInternal(instance.Name, throwIfNotFound, deleteFiles);
            }
            catch (SqlLocalDbException ex)
            {
                string message = SRHelper.Format(
                    SR.SqlLocalDbInstance_DeleteFailedFormat,
                    instance.Name);

                Logger.Error(Logger.TraceEvent.DeleteFailed, message);

                throw new SqlLocalDbException(
                    message,
                    ex.ErrorCode,
                    ex.InstanceName,
                    ex);
            }
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Deletes the specified <see cref="ISqlLocalDbInstance"/> instance.
 /// </summary>
 /// <param name="instance">The LocalDB instance to delete.</param>
 /// <param name="throwIfNotFound">
 /// Whether to throw an exception if the SQL LocalDB instance
 /// associated with <paramref name="instance"/> cannot be found.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="instance"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="SqlLocalDbException">
 /// The SQL Server LocalDB instance specified by <paramref name="instance"/> could not be deleted.
 /// </exception>
 internal static void Delete(ISqlLocalDbInstance instance, bool throwIfNotFound)
 {
     Delete(instance, throwIfNotFound, SqlLocalDbApi.AutomaticallyDeleteInstanceFiles);
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Deletes the specified <see cref="ISqlLocalDbInstance"/> instance.
 /// </summary>
 /// <param name="instance">The LocalDB instance to delete.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="instance"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="SqlLocalDbException">
 /// The SQL Server LocalDB instance specified by <paramref name="instance"/> could not be deleted.
 /// </exception>
 public static void Delete(ISqlLocalDbInstance instance)
 {
     Delete(instance, throwIfNotFound: true);
 }
        //public override void SetUp()
        //{
        //    try
        //    {
        //        base.SetUp();
        //        // Start a Local DB instance.
        //        _SqlLocalDbInstance = _SqlLocalDbProvider.GetOrCreateInstance("SchemaTesting");
        //        _SqlLocalDbInstance.Start();
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e.ToString());
        //        throw;
        //    }
        //}
        private void PrepareTestData()
        {
            _SqlLocalDbProvider = new SqlLocalDbProvider();
            _SqlLocalDbInstance = _SqlLocalDbProvider.GetOrCreateInstance("SchemaTesting");
            _SqlLocalDbInstance.Start();

            // Get the SQL to create a couple of differen tables
            string tableOneName;
            string createTableSql1 = GetCreateTestTableSql(out tableOneName);
            TestEntityName = tableOneName;

            string table2Name;
            string createTableSql2 = GetCreateTestTableSql(out table2Name);
            TestEntityName2 = table2Name;

            // create a foreign key column between them.
            var alterTableAddForeignKey = string.Format("ALTER TABLE {0} ADD {1}Id UNIQUEIDENTIFIER CONSTRAINT {0}_{1} REFERENCES {1}", tableOneName, table2Name);

            //  CreateTestEntity();

            // Create table in LocalDB
            using (SqlConnection connection = _SqlLocalDbInstance.CreateConnection())
            {
                connection.Open();

                // create the first table
                var command = connection.CreateCommand();
                command.CommandType = CommandType.Text;

                Console.WriteLine("Executing local db command " + createTableSql1);
                command.CommandText = createTableSql1;

                var result = command.ExecuteNonQuery();
                Assert.AreEqual(result, -1);

                // create the second table
                command.CommandText = createTableSql2;
                result = command.ExecuteNonQuery();
                Assert.AreEqual(result, -1);

                // create a column in the first table that is a foreign key so it references the second table
                command.CommandText = alterTableAddForeignKey;
                result = command.ExecuteNonQuery();
                Assert.AreEqual(result, -1);

            }

            // Create first table in Crm
            ExecuteCrmNonQuery(createTableSql1, -1);

            // Create second table in Crm
            ExecuteCrmNonQuery(createTableSql2, -1);

            // create a column in the first table that is a foreign key so it references the second table
            ExecuteCrmNonQuery(alterTableAddForeignKey, -1);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Creates an instance of <see cref="DbConnection"/> that can be used to connect to the SQL LocalDB instance
        /// using the only connection string configured in the current application configuration file.
        /// </summary>
        /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> to get the connection string builder for.</param>
        /// <returns>
        /// The created instance of <see cref="DbConnectionStringBuilder"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// No connection strings are configured in the application configuration file or more than one
        /// connection string is configured in the application configuration file.
        /// </exception>
        /// <remarks>
        /// Connection strings may be inherited from outside the current application's configuration file, such as from
        /// <c>machine.config</c>.  To use this overload it is recommended that, unless otherwise needed, a <c>&lt;clear/&gt;</c>
        /// element is added to the <c>&lt;connectionStrings&gt;</c> section of your application configuration file to
        /// prevent the default connection strings from being inherited.
        /// </remarks>
        public static DbConnection GetConnectionForDefaultModel(this ISqlLocalDbInstance instance)
        {
            DbConnectionStringBuilder builder = instance.GetConnectionStringForDefaultModel();

            return(CreateConnection(builder.ConnectionString));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TemporarySqlLocalDbInstance"/> class.
 /// </summary>
 /// <param name="instance">The <see cref="ISqlLocalDbInstance"/> instance to use.</param>
 /// <remarks>
 /// Used for unit testing.
 /// </remarks>
 internal TemporarySqlLocalDbInstance(ISqlLocalDbInstance instance)
 {
     _instance = instance;
 }