예제 #1
0
        public async void DeployWithSqlCmdVariables()
        {
            var       result   = GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, query : storedProcScript, dbNamePrefix : "DacFxDeploySqlCmdVarsTest");

            SqlTestDb targetDb = null;

            try
            {
                DacFxService service = new DacFxService();
                // First extract a db to have a dacpac to deploy later
                string dacpacPath = InitialExtract(service, sourceDb, result);

                // Deploy the created dacpac with SqlCmdVars
                var deployParams = new DeployParams
                {
                    PackageFilePath          = dacpacPath,
                    DatabaseName             = string.Concat(sourceDb.DatabaseName, "-deployed"),
                    UpgradeExisting          = false,
                    SqlCommandVariableValues = new Dictionary <string, string>()
                    {
                        { databaseRefVarName, "OtherDatabase" },
                        { filterValueVarName, "Employee" }
                    }
                };

                DeployOperation deployOperation = new DeployOperation(deployParams, result.ConnectionInfo);
                service.PerformOperation(deployOperation, TaskExecutionMode.Execute);
                targetDb = SqlTestDb.CreateFromExisting(deployParams.DatabaseName);

                string deployedProc;

                using (SqlConnection conn = new SqlConnection(targetDb.ConnectionString))
                {
                    try
                    {
                        await conn.OpenAsync();

                        deployedProc = (string)ReliableConnectionHelper.ExecuteScalar(conn, "SELECT OBJECT_DEFINITION (OBJECT_ID(N'Procedure1'));");
                    }
                    finally
                    {
                        conn.Close();
                    }
                }

                Assert.Contains(deployParams.SqlCommandVariableValues[databaseRefVarName], deployedProc);
                Assert.Contains(deployParams.SqlCommandVariableValues[filterValueVarName], deployedProc);

                VerifyAndCleanup(dacpacPath);
            }
            finally
            {
                sourceDb.Cleanup();
                if (targetDb != null)
                {
                    targetDb.Cleanup();
                }
            }
        }
        public async void ExportBacpac()
        {
            var       result = GetLiveAutoCompleteTestObjects();
            SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                var exportParams = new ExportParams
                {
                    DatabaseName    = testdb.DatabaseName,
                    PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", testdb.DatabaseName))
                };

                DacFxService    service   = new DacFxService();
                ExportOperation operation = new ExportOperation(exportParams, result.ConnectionInfo);
                service.PerformOperation(operation, TaskExecutionMode.Execute);

                VerifyAndCleanup(exportParams.PackageFilePath);
            }
            finally
            {
                testdb.Cleanup();
            }
        }
예제 #3
0
        public async void RestorePlanShouldCreatedSuccessfullyOnExistingDatabaseGivenReplaceOption()
        {
            SqlTestDb testDb = null;

            try
            {
                testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "RestoreTest");

                //Create a backup from a test db but don't delete the database
                await VerifyBackupFileCreated();

                bool canRestore = true;
                Dictionary <string, object> options = new Dictionary <string, object>();
                options.Add(RestoreOptionsHelper.ReplaceDatabase, true);

                await VerifyRestore(new string[] { fullBackupFilePath }, null, canRestore, TaskExecutionModeFlag.ExecuteAndScript, testDb.DatabaseName, null, options);
            }
            finally
            {
                if (testDb != null)
                {
                    testDb.Cleanup();
                }
            }
        }
예제 #4
0
        public async void ExtractDBToFileTarget()
        {
            var       result = GetLiveAutoCompleteTestObjects();
            SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, doNotCleanupDb : false, databaseName : null, query : SourceScript, dbNamePrefix : "DacFxExtractDBToFileTarget");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                var extractParams = new ExtractParams
                {
                    DatabaseName       = testdb.DatabaseName,
                    PackageFilePath    = Path.Combine(folderPath, string.Format("{0}.sql", testdb.DatabaseName)),
                    ApplicationName    = "test",
                    ApplicationVersion = "1.0.0.0",
                    ExtractTarget      = DacExtractTarget.File
                };

                DacFxService     service   = new DacFxService();
                ExtractOperation operation = new ExtractOperation(extractParams, result.ConnectionInfo);
                service.PerformOperation(operation, TaskExecutionMode.Execute);

                VerifyAndCleanup(extractParams.PackageFilePath);
            }
            finally
            {
                testdb.Cleanup();
            }
        }
        public async Task VerifyTaskWithExecutionMode(TaskExecutionMode executionMode, bool makeTaskFail = false)
        {
            serviceHostMock.AddEventHandling(TaskStatusChangedNotification.Type, null);

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                //To make the task fail don't create the schema so create table fails
                string query = string.Empty;
                if (!makeTaskFail)
                {
                    query = $"CREATE SCHEMA [test]";
                }
                SqlTestDb testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query, "TaskService");

                try
                {
                    TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync(testDb.DatabaseName, queryTempFile.FilePath);

                    string          taskName    = "task name";
                    Server          server      = CreateServerObject(connectionResult.ConnectionInfo);
                    RequstParamStub requstParam = new RequstParamStub
                    {
                        TaskExecutionMode = executionMode,
                        OwnerUri          = queryTempFile.FilePath
                    };
                    SmoScriptableTaskOperationStub taskOperation = new SmoScriptableTaskOperationStub(server);
                    taskOperation.DatabaseName = testDb.DatabaseName;
                    taskOperation.TableName    = "newTable";
                    TaskMetadata taskMetadata = TaskMetadata.Create(requstParam, taskName, taskOperation, ConnectionService.Instance);
                    SqlTask      sqlTask      = service.TaskManager.CreateTask <SqlTask>(taskMetadata);
                    Task         taskToVerify = sqlTask.RunAsync().ContinueWith(task =>
                    {
                        if (!makeTaskFail)
                        {
                            if (executionMode == TaskExecutionMode.Script || executionMode == TaskExecutionMode.ExecuteAndScript)
                            {
                                serviceHostMock.Verify(x => x.SendEvent(TaskStatusChangedNotification.Type,
                                                                        It.Is <TaskProgressInfo>(t => !string.IsNullOrEmpty(t.Script))), Times.AtLeastOnce());
                            }

                            //Verify if the table created if execution mode includes execute
                            bool expected         = executionMode == TaskExecutionMode.Execute || executionMode == TaskExecutionMode.ExecuteAndScript;
                            Server serverToverfiy = CreateServerObject(connectionResult.ConnectionInfo);
                            bool actual           = serverToverfiy.Databases[testDb.DatabaseName].Tables.Contains(taskOperation.TableName, "test");
                            Assert.Equal(expected, actual);
                        }
                        else
                        {
                            serviceHostMock.Verify(x => x.SendEvent(TaskStatusChangedNotification.Type,
                                                                    It.Is <TaskProgressInfo>(t => t.Status == SqlTaskStatus.Failed)), Times.AtLeastOnce());
                        }
                    });
                    await taskToVerify;
                }
                finally
                {
                    testDb.Cleanup();
                }
            }
        }
        private async Task <Mock <RequestContext <SchemaCompareResult> > > SendAndValidateSchemaCompareRequestDacpacToDacpacWithOptions(string sourceScript, string targetScript, DeploymentOptions nodiffOption, DeploymentOptions shouldDiffOption)
        {
            var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            var schemaCompareRequestContext = new Mock <RequestContext <SchemaCompareResult> >();

            schemaCompareRequestContext.Setup(x => x.SendResult(It.IsAny <SchemaCompareResult>())).Returns(Task.FromResult(new object()));

            // create dacpacs from databases
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, sourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, targetScript, "SchemaCompareTarget");

            try
            {
                string sourceDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(sourceDb);
                string targetDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(targetDb);

                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                sourceInfo.PackageFilePath = sourceDacpacFilePath;
                targetInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                targetInfo.PackageFilePath = targetDacpacFilePath;

                var schemaCompareParams1 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = nodiffOption
                };

                SchemaCompareOperation schemaCompareOperation1 = new SchemaCompareOperation(schemaCompareParams1, null, null);
                schemaCompareOperation1.Execute(TaskExecutionMode.Execute);
                Assert.True(schemaCompareOperation1.ComparisonResult.IsEqual);

                var schemaCompareParams2 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = shouldDiffOption,
                };

                SchemaCompareOperation schemaCompareOperation2 = new SchemaCompareOperation(schemaCompareParams2, null, null);
                schemaCompareOperation2.Execute(TaskExecutionMode.Execute);
                Assert.False(schemaCompareOperation2.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation2.ComparisonResult.Differences);

                // cleanup
                SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath);
                SchemaCompareTestUtils.VerifyAndCleanup(targetDacpacFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }

            return(schemaCompareRequestContext);
        }
예제 #7
0
        private async Task <Mock <RequestContext <DacFxResult> > > SendAndValidateExportRequest()
        {
            var result         = GetLiveAutoCompleteTestObjects();
            var requestContext = new Mock <RequestContext <DacFxResult> >();

            requestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            var exportParams = new ExportParams
            {
                DatabaseName    = testdb.DatabaseName,
                PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", testdb.DatabaseName))
            };

            DacFxService    service   = new DacFxService();
            ExportOperation operation = new ExportOperation(exportParams, result.ConnectionInfo);

            service.PerformOperation(operation);

            // cleanup
            VerifyAndCleanup(exportParams.PackageFilePath);
            testdb.Cleanup();

            return(requestContext);
        }
예제 #8
0
        public async void RestoreShouldFailIfThereAreOtherConnectionsToDatabase2()
        {
            await GetBackupFilesToRecoverDatabaseCreated();

            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "RestoreTest");

            ConnectionService connectionService = LiveConnectionHelper.GetLiveTestConnectionService();

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                //OE connection will be closed after conneced
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync(testDb.DatabaseName, queryTempFile.FilePath, ConnectionType.ObjectExplorer);

                //Opening a connection to db to lock the db
                ConnectionService.OpenSqlConnection(connectionResult.ConnectionInfo);

                try
                {
                    bool restoreShouldFail = true;
                    Dictionary <string, object> options = new Dictionary <string, object>();
                    options.Add(RestoreOptionsHelper.ReplaceDatabase, true);
                    await VerifyRestore(null, databaseNameToRestoreFrom, true, TaskExecutionModeFlag.Execute, testDb.DatabaseName, null, options, null, restoreShouldFail);
                }
                finally
                {
                    connectionService.Disconnect(new ServiceLayer.Connection.Contracts.DisconnectParams
                    {
                        OwnerUri = queryTempFile.FilePath,
                        Type     = ConnectionType.Default
                    });
                    testDb.Cleanup();
                }
            }
        }
        private async Task <Mock <RequestContext <SchemaCompareResult> > > SendAndValidateSchemaCompareRequestDatabaseToDatabaseWithOptions(string sourceScript, string targetScript, DeploymentOptions nodiffOption, DeploymentOptions shouldDiffOption)
        {
            var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            var schemaCompareRequestContext = new Mock <RequestContext <SchemaCompareResult> >();

            schemaCompareRequestContext.Setup(x => x.SendResult(It.IsAny <SchemaCompareResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, sourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, targetScript, "SchemaCompareTarget");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SchemaCompareTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType = SchemaCompareEndpointType.Database;
                sourceInfo.DatabaseName = sourceDb.DatabaseName;
                targetInfo.EndpointType = SchemaCompareEndpointType.Database;
                targetInfo.DatabaseName = targetDb.DatabaseName;

                var schemaCompareParams1 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = nodiffOption
                };

                SchemaCompareOperation schemaCompareOperation1 = new SchemaCompareOperation(schemaCompareParams1, result.ConnectionInfo, result.ConnectionInfo);
                schemaCompareOperation1.Execute(TaskExecutionMode.Execute);

                Assert.True(schemaCompareOperation1.ComparisonResult.IsValid);
                Assert.True(schemaCompareOperation1.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation1.ComparisonResult.Differences);

                var schemaCompareParams2 = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo,
                    DeploymentOptions  = shouldDiffOption,
                };

                SchemaCompareOperation schemaCompareOperation2 = new SchemaCompareOperation(schemaCompareParams2, result.ConnectionInfo, result.ConnectionInfo);
                schemaCompareOperation2.Execute(TaskExecutionMode.Execute);
                Assert.False(schemaCompareOperation2.ComparisonResult.IsEqual);
                Assert.NotNull(schemaCompareOperation2.ComparisonResult.Differences);
            }
            finally
            {
                // cleanup
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
            return(schemaCompareRequestContext);
        }
예제 #10
0
        private async Task <Mock <RequestContext <SchemaCompareResult> > > SendAndValidateSchemaCompareGenerateScriptRequestDacpacToDatabase()
        {
            var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            var schemaCompareRequestContext = new Mock <RequestContext <SchemaCompareResult> >();

            schemaCompareRequestContext.Setup(x => x.SendResult(It.IsAny <SchemaCompareResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SchemaCompareTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                string sourceDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(sourceDb);

                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                sourceInfo.PackageFilePath = sourceDacpacFilePath;
                targetInfo.EndpointType    = SchemaCompareEndpointType.Database;
                targetInfo.DatabaseName    = targetDb.DatabaseName;

                var schemaCompareParams = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo
                };

                SchemaCompareOperation schemaCompareOperation = new SchemaCompareOperation(schemaCompareParams, result.ConnectionInfo, result.ConnectionInfo);

                // generate script
                var generateScriptParams = new SchemaCompareGenerateScriptParams
                {
                    TargetDatabaseName = targetDb.DatabaseName,
                    OperationId        = schemaCompareOperation.OperationId,
                    ScriptFilePath     = Path.Combine(folderPath, string.Concat(sourceDb.DatabaseName, "_", "Update.publish.sql"))
                };

                ValidateSchemaCompareScriptGenerationWithExcludeIncludeResults(schemaCompareOperation, generateScriptParams);

                // cleanup
                SchemaCompareTestUtils.VerifyAndCleanup(generateScriptParams.ScriptFilePath);
                SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
            return(schemaCompareRequestContext);
        }
예제 #11
0
        private async Task VerifyRestoreMultipleBackupSets(string[] backupFiles, int backupSetIndexToDelete, int[] expectedSelectedIndexes, TaskExecutionModeFlag executionMode = TaskExecutionModeFlag.ExecuteAndScript)
        {
            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "RestoreTest");

            try
            {
                string targetDbName = testDb.DatabaseName;
                bool   canRestore   = true;
                var    response     = await VerifyRestore(backupFiles, null, canRestore, TaskExecutionModeFlag.None, targetDbName, null, null);

                Assert.True(response.BackupSetsToRestore.Count() >= 2);
                var allIds = response.BackupSetsToRestore.Select(x => x.Id).ToList();
                if (backupSetIndexToDelete >= 0)
                {
                    allIds.RemoveAt(backupSetIndexToDelete);
                }
                string[] selectedIds = allIds.ToArray();
                Dictionary <string, object> options = new Dictionary <string, object>();
                options.Add(RestoreOptionsHelper.ReplaceDatabase, true);
                response = await VerifyRestore(backupFiles, null, canRestore, executionMode, targetDbName, selectedIds, options, (database) =>
                {
                    if (executionMode.HasFlag(TaskExecutionModeFlag.Execute))
                    {
                        bool tablesFound = true;
                        for (int i = 0; i < tableNames.Length; i++)
                        {
                            string tableName = tableNames[i];
                            if (!database.Tables.Contains(tableName, "test") && expectedSelectedIndexes.Contains(i))
                            {
                                tablesFound = false;
                                break;
                            }
                        }
                        bool numberOfTableCreatedIsCorrect = database.Tables.Count == expectedSelectedIndexes.Length;
                        return(numberOfTableCreatedIsCorrect && tablesFound);
                    }
                    return(true);
                });

                for (int i = 0; i < response.BackupSetsToRestore.Count(); i++)
                {
                    DatabaseFileInfo databaseInfo = response.BackupSetsToRestore[i];
                    Assert.Equal(databaseInfo.IsSelected, expectedSelectedIndexes.Contains(i));
                }
            }
            finally
            {
                if (testDb != null)
                {
                    testDb.Cleanup();
                }
            }
        }
예제 #12
0
        private async Task VerifyScriptAs(string query, ScriptingObject scriptingObject, string scriptCreateDrop, string expectedScript)
        {
            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query, "ScriptingTests");

            try
            {
                var requestContext = new Mock <RequestContext <ScriptingResult> >();
                requestContext.Setup(x => x.SendResult(It.IsAny <ScriptingResult>())).Returns(Task.FromResult(new object()));
                ConnectionService connectionService = LiveConnectionHelper.GetLiveTestConnectionService();
                using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                {
                    //Opening a connection to db to lock the db
                    TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync(testDb.DatabaseName, queryTempFile.FilePath, ConnectionType.Default);

                    var scriptingParams = new ScriptingParams
                    {
                        OwnerUri          = queryTempFile.FilePath,
                        ScriptDestination = "ToEditor"
                    };

                    scriptingParams.ScriptOptions = new ScriptOptions
                    {
                        ScriptCreateDrop = scriptCreateDrop,
                    };

                    scriptingParams.ScriptingObjects = new List <ScriptingObject>
                    {
                        scriptingObject
                    };


                    ScriptingService service = new ScriptingService();
                    await service.HandleScriptingScriptAsRequest(scriptingParams, requestContext.Object);

                    Thread.Sleep(2000);
                    await service.ScriptingTask;

                    requestContext.Verify(x => x.SendResult(It.Is <ScriptingResult>(r => VerifyScriptingResult(r, expectedScript))));
                    connectionService.Disconnect(new ServiceLayer.Connection.Contracts.DisconnectParams
                    {
                        OwnerUri = queryTempFile.FilePath
                    });
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                await testDb.CleanupAsync();
            }
        }
예제 #13
0
        private async Task <Mock <RequestContext <DacFxResult> > > SendAndValidateGenerateDeployScriptRequest()
        {
            // first extract a dacpac
            var result = GetLiveAutoCompleteTestObjects();
            var extractRequestContext = new Mock <RequestContext <DacFxResult> >();

            extractRequestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxGenerateScriptTest");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            var extractParams = new ExtractParams
            {
                DatabaseName       = sourceDb.DatabaseName,
                PackageFilePath    = Path.Combine(folderPath, string.Format("{0}.dacpac", sourceDb.DatabaseName)),
                ApplicationName    = "test",
                ApplicationVersion = "1.0.0.0"
            };

            DacFxService     service          = new DacFxService();
            ExtractOperation extractOperation = new ExtractOperation(extractParams, result.ConnectionInfo);

            service.PerformOperation(extractOperation);

            // generate script
            var generateScriptRequestContext = new Mock <RequestContext <DacFxResult> >();

            generateScriptRequestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));


            var generateScriptParams = new GenerateDeployScriptParams
            {
                PackageFilePath = extractParams.PackageFilePath,
                DatabaseName    = string.Concat(sourceDb.DatabaseName, "-deployed"),
                ScriptFilePath  = Path.Combine(folderPath, string.Concat(sourceDb.DatabaseName, "_", "UpgradeDACScript.sql"))
            };

            GenerateDeployScriptOperation generateScriptOperation = new GenerateDeployScriptOperation(generateScriptParams, result.ConnectionInfo);

            service.PerformOperation(generateScriptOperation);
            SqlTestDb targetDb = SqlTestDb.CreateFromExisting(generateScriptParams.DatabaseName);

            // cleanup
            VerifyAndCleanup(generateScriptParams.ScriptFilePath);
            VerifyAndCleanup(extractParams.PackageFilePath);
            sourceDb.Cleanup();
            targetDb.Cleanup();

            return(generateScriptRequestContext);
        }
        public async void GenerateDeployPlan()
        {
            var       result   = GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "DacFxGenerateDeployPlanTest");

            SqlTestDb    targetDb   = null;
            DacFxService service    = new DacFxService();
            string       folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                var extractParams = new ExtractParams
                {
                    DatabaseName       = sourceDb.DatabaseName,
                    PackageFilePath    = Path.Combine(folderPath, string.Format("{0}.dacpac", sourceDb.DatabaseName)),
                    ApplicationName    = "test",
                    ApplicationVersion = "1.0.0.0"
                };

                ExtractOperation extractOperation = new ExtractOperation(extractParams, result.ConnectionInfo);
                service.PerformOperation(extractOperation, TaskExecutionMode.Execute);

                // generate deploy plan for deploying dacpac to targetDb
                targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "DacFxGenerateDeployPlanTestTarget");

                var generateDeployPlanParams = new GenerateDeployPlanParams
                {
                    PackageFilePath = extractParams.PackageFilePath,
                    DatabaseName    = targetDb.DatabaseName,
                };

                GenerateDeployPlanOperation generateDeployPlanOperation = new GenerateDeployPlanOperation(generateDeployPlanParams, result.ConnectionInfo);
                service.PerformOperation(generateDeployPlanOperation, TaskExecutionMode.Execute);
                string report = generateDeployPlanOperation.DeployReport;
                Assert.NotNull(report);
                Assert.Contains("Create", report);
                Assert.Contains("Drop", report);
                Assert.Contains("Alter", report);

                VerifyAndCleanup(extractParams.PackageFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                if (targetDb != null)
                {
                    targetDb.Cleanup();
                }
            }
        }
예제 #15
0
        private async Task <Mock <RequestContext <DacFxResult> > > SendAndValidateGenerateDeployPlanRequest()
        {
            var       result   = GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "DacFxGenerateDeployPlanTest");

            DacFxService service    = new DacFxService();
            string       folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            var extractParams = new ExtractParams
            {
                DatabaseName       = sourceDb.DatabaseName,
                PackageFilePath    = Path.Combine(folderPath, string.Format("{0}.dacpac", sourceDb.DatabaseName)),
                ApplicationName    = "test",
                ApplicationVersion = "1.0.0.0"
            };

            ExtractOperation extractOperation = new ExtractOperation(extractParams, result.ConnectionInfo);

            service.PerformOperation(extractOperation);

            // generate deploy plan for deploying dacpac to targetDb
            var generateDeployPlanRequestContext = new Mock <RequestContext <DacFxResult> >();

            generateDeployPlanRequestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "DacFxGenerateDeployPlanTestTarget");

            var generateDeployPlanParams = new GenerateDeployPlanParams
            {
                PackageFilePath = extractParams.PackageFilePath,
                DatabaseName    = targetDb.DatabaseName,
            };

            GenerateDeployPlanOperation generateDeployPlanOperation = new GenerateDeployPlanOperation(generateDeployPlanParams, result.ConnectionInfo);

            service.PerformOperation(generateDeployPlanOperation);
            string report = generateDeployPlanOperation.DeployReport;

            Assert.NotNull(report);
            Assert.Contains("Create", report);
            Assert.Contains("Drop", report);
            Assert.Contains("Alter", report);

            // cleanup
            VerifyAndCleanup(extractParams.PackageFilePath);
            sourceDb.Cleanup();
            targetDb.Cleanup();

            return(generateDeployPlanRequestContext);
        }
        private async Task <Mock <RequestContext <DacFxResult> > > SendAndValidateDeployRequest()
        {
            // first extract a db to have a dacpac to import later
            var result = GetLiveAutoCompleteTestObjects();
            var extractRequestContext = new Mock <RequestContext <DacFxResult> >();

            extractRequestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxDeployTest");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            var extractParams = new ExtractParams
            {
                DatabaseName       = sourceDb.DatabaseName,
                PackageFilePath    = Path.Combine(folderPath, string.Format("{0}.dacpac", sourceDb.DatabaseName)),
                ApplicationName    = "test",
                ApplicationVersion = new Version(1, 0)
            };

            SqlConnection    sqlConn          = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Deploy");
            DacFxService     service          = new DacFxService();
            ExtractOperation extractOperation = new ExtractOperation(extractParams, sqlConn);

            service.PerformOperation(extractOperation);

            // deploy the created dacpac
            var deployRequestContext = new Mock <RequestContext <DacFxResult> >();

            deployRequestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));


            var deployParams = new DeployParams
            {
                PackageFilePath = extractParams.PackageFilePath,
                DatabaseName    = string.Concat(sourceDb.DatabaseName, "-deployed"),
                UpgradeExisting = false
            };

            DeployOperation deployOperation = new DeployOperation(deployParams, sqlConn);

            service.PerformOperation(deployOperation); SqlTestDb targetDb = SqlTestDb.CreateFromExisting(deployParams.DatabaseName);

            // cleanup
            VerifyAndCleanup(extractParams.PackageFilePath);
            sourceDb.Cleanup();
            targetDb.Cleanup();

            return(deployRequestContext);
        }
        private async Task ExecuteAndValidatePeekTest(string query, string objectName, string objectType, string schemaName = "dbo")
        {
            if (!string.IsNullOrEmpty(query))
            {
                SqlTestDb testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query);

                ValidatePeekTest(testDb.DatabaseName, objectName, objectType, schemaName, true);
                await testDb.CleanupAsync();
            }
            else
            {
                ValidatePeekTest(null, objectName, objectType, schemaName, false);
            }
        }
        private async Task <Mock <RequestContext <DacFxResult> > > SendAndValidateImportRequest()
        {
            // first export a bacpac
            var result = GetLiveAutoCompleteTestObjects();
            var exportRequestContext = new Mock <RequestContext <DacFxResult> >();

            exportRequestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxImportTest");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            var exportParams = new ExportParams
            {
                DatabaseName    = sourceDb.DatabaseName,
                PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", sourceDb.DatabaseName))
            };

            SqlConnection   sqlConn         = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Import");
            DacFxService    service         = new DacFxService();
            ExportOperation exportOperation = new ExportOperation(exportParams, sqlConn);

            service.PerformOperation(exportOperation);

            // import the created bacpac
            var importRequestContext = new Mock <RequestContext <DacFxResult> >();

            importRequestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));

            var importParams = new ImportParams
            {
                PackageFilePath = exportParams.PackageFilePath,
                DatabaseName    = string.Concat(sourceDb.DatabaseName, "-imported")
            };

            ImportOperation importOperation = new ImportOperation(importParams, sqlConn);

            service.PerformOperation(importOperation);
            SqlTestDb targetDb = SqlTestDb.CreateFromExisting(importParams.DatabaseName);

            // cleanup
            VerifyAndCleanup(exportParams.PackageFilePath);
            sourceDb.Cleanup();
            targetDb.Cleanup();

            return(importRequestContext);
        }
        public async void GenerateDeployScript()
        {
            // first extract a dacpac
            var       result   = GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "DacFxGenerateScriptTest");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxGenerateScriptTest");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                var extractParams = new ExtractParams
                {
                    DatabaseName       = sourceDb.DatabaseName,
                    PackageFilePath    = Path.Combine(folderPath, string.Format("{0}.dacpac", sourceDb.DatabaseName)),
                    ApplicationName    = "test",
                    ApplicationVersion = "1.0.0.0"
                };

                DacFxService     service          = new DacFxService();
                ExtractOperation extractOperation = new ExtractOperation(extractParams, result.ConnectionInfo);
                service.PerformOperation(extractOperation, TaskExecutionMode.Execute);

                // generate script
                var generateScriptParams = new GenerateDeployScriptParams
                {
                    PackageFilePath = extractParams.PackageFilePath,
                    DatabaseName    = targetDb.DatabaseName
                };

                // Generate script for deploying source dacpac to target db
                GenerateDeployScriptOperation generateScriptOperation = new GenerateDeployScriptOperation(generateScriptParams, result.ConnectionInfo);
                service.PerformOperation(generateScriptOperation, TaskExecutionMode.Script);

                // Verify script was generated
                Assert.NotEmpty(generateScriptOperation.Result.DatabaseScript);
                Assert.Contains("CREATE TABLE", generateScriptOperation.Result.DatabaseScript);

                VerifyAndCleanup(extractParams.PackageFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
        }
        public async void DeployDacpac()
        {
            // first extract a db to have a dacpac to import later
            var       result   = GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxDeployTest");

            SqlTestDb targetDb   = null;
            string    folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                var extractParams = new ExtractParams
                {
                    DatabaseName       = sourceDb.DatabaseName,
                    PackageFilePath    = Path.Combine(folderPath, string.Format("{0}.dacpac", sourceDb.DatabaseName)),
                    ApplicationName    = "test",
                    ApplicationVersion = "1.0.0.0"
                };

                DacFxService     service          = new DacFxService();
                ExtractOperation extractOperation = new ExtractOperation(extractParams, result.ConnectionInfo);
                service.PerformOperation(extractOperation, TaskExecutionMode.Execute);

                // deploy the created dacpac
                var deployParams = new DeployParams
                {
                    PackageFilePath = extractParams.PackageFilePath,
                    DatabaseName    = string.Concat(sourceDb.DatabaseName, "-deployed"),
                    UpgradeExisting = false
                };

                DeployOperation deployOperation = new DeployOperation(deployParams, result.ConnectionInfo);
                service.PerformOperation(deployOperation, TaskExecutionMode.Execute);
                targetDb = SqlTestDb.CreateFromExisting(deployParams.DatabaseName);

                VerifyAndCleanup(extractParams.PackageFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                if (targetDb != null)
                {
                    targetDb.Cleanup();
                }
            }
        }
예제 #21
0
        private async Task <Mock <RequestContext <SchemaCompareResult> > > SendAndValidateSchemaCompareRequestDacpacToDacpac()
        {
            var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            var schemaCompareRequestContext = new Mock <RequestContext <SchemaCompareResult> >();

            schemaCompareRequestContext.Setup(x => x.SendResult(It.IsAny <SchemaCompareResult>())).Returns(Task.FromResult(new object()));

            // create dacpacs from databases
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");

            try
            {
                string sourceDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(sourceDb);
                string targetDacpacFilePath = SchemaCompareTestUtils.CreateDacpac(targetDb);

                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                sourceInfo.PackageFilePath = sourceDacpacFilePath;
                targetInfo.EndpointType    = SchemaCompareEndpointType.Dacpac;
                targetInfo.PackageFilePath = targetDacpacFilePath;

                var schemaCompareParams = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo
                };

                SchemaCompareOperation schemaCompareOperation = new SchemaCompareOperation(schemaCompareParams, null, null);
                ValidateSchemaCompareWithExcludeIncludeResults(schemaCompareOperation);

                // cleanup
                SchemaCompareTestUtils.VerifyAndCleanup(sourceDacpacFilePath);
                SchemaCompareTestUtils.VerifyAndCleanup(targetDacpacFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }

            return(schemaCompareRequestContext);
        }
예제 #22
0
        private async Task <Mock <RequestContext <SchemaCompareResult> > > SendAndValidateSchemaCompareGenerateScriptRequestDatabaseToDatabase()
        {
            var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            var schemaCompareRequestContext = new Mock <RequestContext <SchemaCompareResult> >();

            schemaCompareRequestContext.Setup(x => x.SendResult(It.IsAny <SchemaCompareResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");

            try
            {
                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType = SchemaCompareEndpointType.Database;
                sourceInfo.DatabaseName = sourceDb.DatabaseName;
                targetInfo.EndpointType = SchemaCompareEndpointType.Database;
                targetInfo.DatabaseName = targetDb.DatabaseName;

                var schemaCompareParams = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo
                };

                SchemaCompareOperation schemaCompareOperation = new SchemaCompareOperation(schemaCompareParams, result.ConnectionInfo, result.ConnectionInfo);

                // generate script params
                var generateScriptParams = new SchemaCompareGenerateScriptParams
                {
                    TargetDatabaseName = targetDb.DatabaseName,
                    OperationId        = schemaCompareOperation.OperationId,
                };

                ValidateSchemaCompareScriptGenerationWithExcludeIncludeResults(schemaCompareOperation, generateScriptParams);
            }
            finally
            {
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
            return(schemaCompareRequestContext);
        }
        public async void ImportBacpac()
        {
            // first export a bacpac
            var       result   = GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxImportTest");

            SqlTestDb targetDb   = null;
            string    folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                var exportParams = new ExportParams
                {
                    DatabaseName    = sourceDb.DatabaseName,
                    PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", sourceDb.DatabaseName))
                };

                DacFxService    service         = new DacFxService();
                ExportOperation exportOperation = new ExportOperation(exportParams, result.ConnectionInfo);
                service.PerformOperation(exportOperation, TaskExecutionMode.Execute);

                // import the created bacpac
                var importParams = new ImportParams
                {
                    PackageFilePath = exportParams.PackageFilePath,
                    DatabaseName    = string.Concat(sourceDb.DatabaseName, "-imported")
                };

                ImportOperation importOperation = new ImportOperation(importParams, result.ConnectionInfo);
                service.PerformOperation(importOperation, TaskExecutionMode.Execute);
                targetDb = SqlTestDb.CreateFromExisting(importParams.DatabaseName);

                VerifyAndCleanup(exportParams.PackageFilePath);
            }
            finally
            {
                sourceDb.Cleanup();
                if (targetDb != null)
                {
                    targetDb.Cleanup();
                }
            }
        }
        private async Task <Mock <RequestContext <DacFxResult> > > ValidateExportCancellation()
        {
            var result         = GetLiveAutoCompleteTestObjects();
            var requestContext = new Mock <RequestContext <DacFxResult> >();

            requestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");

            Directory.CreateDirectory(folderPath);

            var exportParams = new ExportParams
            {
                DatabaseName    = testdb.DatabaseName,
                PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", testdb.DatabaseName))
            };

            SqlConnection   sqlConn   = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Export");
            DacFxService    service   = new DacFxService();
            ExportOperation operation = new ExportOperation(exportParams, sqlConn);

            // set cancellation token to cancel
            operation.Cancel();
            OperationCanceledException expectedException = null;

            try
            {
                service.PerformOperation(operation);
            }
            catch (OperationCanceledException canceledException)
            {
                expectedException = canceledException;
            }

            Assert.NotNull(expectedException);

            // cleanup
            testdb.Cleanup();

            return(requestContext);
        }
예제 #25
0
        public async Task <string> CreateBackupFile()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                SqlTestDb testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "RestoreTest");

                var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(testDb.DatabaseName, queryTempFile.FilePath);

                // Initialize backup service
                DatabaseTaskHelper helper  = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
                SqlConnection      sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);

                // Get default backup pathS
                BackupConfigInfo backupConfigInfo = DisasterRecoveryService.Instance.GetBackupConfigInfo(helper.DataContainer, sqlConn, sqlConn.Database);
                string           backupPath       = Path.Combine(backupConfigInfo.DefaultBackupFolder, testDb.DatabaseName + ".bak");

                BackupInfo backupInfo = CreateBackupInfo(testDb.DatabaseName,
                                                         BackupType.Full,
                                                         new List <string>()
                {
                    backupPath
                },
                                                         new Dictionary <string, int>()
                {
                    { backupPath, (int)DeviceType.File }
                });

                var backupParams = new BackupParams
                {
                    OwnerUri          = liveConnection.ConnectionInfo.OwnerUri,
                    BackupInfo        = backupInfo,
                    TaskExecutionMode = TaskExecutionMode.Execute
                };

                // Backup the database
                BackupOperation backupOperation = DisasterRecoveryService.Instance.CreateBackupOperation(helper.DataContainer, sqlConn, backupParams.BackupInfo);
                DisasterRecoveryService.Instance.PerformBackup(backupOperation);

                // Clean up the database
                testDb.Cleanup();
                return(backupPath);
            }
        }
예제 #26
0
        private async Task <Mock <RequestContext <SchemaCompareResult> > > SendAndValidateSchemaCompareRequestDatabaseToDatabase()
        {
            var result = SchemaCompareTestUtils.GetLiveAutoCompleteTestObjects();
            var schemaCompareRequestContext = new Mock <RequestContext <SchemaCompareResult> >();

            schemaCompareRequestContext.Setup(x => x.SendResult(It.IsAny <SchemaCompareResult>())).Returns(Task.FromResult(new object()));

            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "SchemaCompareSource");

            SqlTestDb targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "SchemaCompareTarget");

            string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SchemaCompareTest");

            Directory.CreateDirectory(folderPath);

            try
            {
                SchemaCompareEndpointInfo sourceInfo = new SchemaCompareEndpointInfo();
                SchemaCompareEndpointInfo targetInfo = new SchemaCompareEndpointInfo();

                sourceInfo.EndpointType = SchemaCompareEndpointType.Database;
                sourceInfo.DatabaseName = sourceDb.DatabaseName;
                targetInfo.EndpointType = SchemaCompareEndpointType.Database;
                targetInfo.DatabaseName = targetDb.DatabaseName;

                var schemaCompareParams = new SchemaCompareParams
                {
                    SourceEndpointInfo = sourceInfo,
                    TargetEndpointInfo = targetInfo
                };

                SchemaCompareOperation schemaCompareOperation = new SchemaCompareOperation(schemaCompareParams, result.ConnectionInfo, result.ConnectionInfo);
                ValidateSchemaCompareWithExcludeIncludeResults(schemaCompareOperation);
            }
            finally
            {
                // cleanup
                sourceDb.Cleanup();
                targetDb.Cleanup();
            }
            return(schemaCompareRequestContext);
        }
예제 #27
0
        public async void RestoreShouldRestoreFromAnotherDatabase()
        {
            await GetBackupFilesToRecoverDatabaseCreated();

            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "RestoreTest");

            try
            {
                Dictionary <string, object> options = new Dictionary <string, object>();
                options.Add(RestoreOptionsHelper.ReplaceDatabase, true);
                await VerifyRestore(null, databaseNameToRestoreFrom, true, TaskExecutionModeFlag.ExecuteAndScript, testDb.DatabaseName, null, options, (database) =>
                {
                    return(database.Tables.Contains("tb1", "test"));
                });
            }
            finally
            {
                testDb.Cleanup();
            }
        }
예제 #28
0
        public async void GenerateDeployPlan()
        {
            var       result   = GetLiveAutoCompleteTestObjects();
            SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, SourceScript, "DacFxGenerateDeployPlanTest");

            SqlTestDb targetDb = null;

            try
            {
                DacFxService service    = new DacFxService();
                string       dacpacPath = InitialExtract(service, sourceDb, result);

                // generate deploy plan for deploying dacpac to targetDb
                targetDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, TargetScript, "DacFxGenerateDeployPlanTestTarget");

                var generateDeployPlanParams = new GenerateDeployPlanParams
                {
                    PackageFilePath = dacpacPath,
                    DatabaseName    = targetDb.DatabaseName,
                };

                GenerateDeployPlanOperation generateDeployPlanOperation = new GenerateDeployPlanOperation(generateDeployPlanParams, result.ConnectionInfo);
                service.PerformOperation(generateDeployPlanOperation, TaskExecutionMode.Execute);
                string report = generateDeployPlanOperation.DeployReport;
                Assert.NotNull(report);
                Assert.Contains("Create", report);
                Assert.Contains("Drop", report);
                Assert.Contains("Alter", report);

                VerifyAndCleanup(dacpacPath);
            }
            finally
            {
                sourceDb.Cleanup();
                if (targetDb != null)
                {
                    targetDb.Cleanup();
                }
            }
        }
예제 #29
0
        private async Task VerifyMetadataListCore(string query, List <ObjectMetadata> expectedMetadataList)
        {
            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query, "MetadataTests");

            try
            {
                var requestContext = new Mock <RequestContext <MetadataQueryResult> >();
                requestContext.Setup(x => x.SendResult(It.IsAny <MetadataQueryResult>())).Returns(Task.FromResult(new object()));
                ConnectionService connectionService = LiveConnectionHelper.GetLiveTestConnectionService();
                using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                {
                    //Opening a connection to db to lock the db
                    TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync(testDb.DatabaseName, queryTempFile.FilePath, ConnectionType.Default);

                    MetadataService service = new MetadataService();
                    await service.HandleMetadataListRequest(new MetadataQueryParams
                    {
                        OwnerUri = queryTempFile.FilePath
                    }, requestContext.Object);

                    Thread.Sleep(2000);
                    await service.MetadataListTask;

                    requestContext.Verify(x => x.SendResult(It.Is <MetadataQueryResult>(r => VerifyResult(r, expectedMetadataList))));
                    connectionService.Disconnect(new ServiceLayer.Connection.Contracts.DisconnectParams
                    {
                        OwnerUri = queryTempFile.FilePath
                    });
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                await testDb.CleanupAsync();
            }
        }
예제 #30
0
        public async void RestoreShouldCloseOtherConnectionsBeforeExecuting()
        {
            await GetBackupFilesToRecoverDatabaseCreated();

            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "RestoreTest");

            ConnectionService    connectionService = LiveConnectionHelper.GetLiveTestConnectionService();
            TestConnectionResult connectionResult;

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                //OE connection will be closed after conneced
                connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync(testDb.DatabaseName, queryTempFile.FilePath, ConnectionType.ObjectExplorer);

                //Opening a connection to db to lock the db

                connectionService.ConnectionQueue.AddConnectionContext(connectionResult.ConnectionInfo, "", true);

                try
                {
                    Dictionary <string, object> options = new Dictionary <string, object>();
                    options.Add(RestoreOptionsHelper.ReplaceDatabase, true);
                    await VerifyRestore(null, databaseNameToRestoreFrom, true, TaskExecutionModeFlag.Execute, testDb.DatabaseName, null, options
                                        , (database) =>
                    {
                        return(database.Tables.Contains("tb1", "test"));
                    });
                }
                finally
                {
                    connectionService.Disconnect(new ServiceLayer.Connection.Contracts.DisconnectParams
                    {
                        OwnerUri = queryTempFile.FilePath,
                        Type     = ConnectionType.Default
                    });
                    testDb.Cleanup();
                }
            }
        }