示例#1
0
        public void CreateBackupTest()
        {
            DisasterRecoveryService service = new DisasterRecoveryService();
            string databaseName             = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999);

            var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);

            using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
                using (DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true))
                    using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
                    {
                        string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);

                        BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName,
                                                                        BackupType.Full,
                                                                        new List <string>()
                        {
                            backupPath
                        },
                                                                        new Dictionary <string, int>()
                        {
                            { backupPath, (int)DeviceType.File }
                        });
                        BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfo, helper.DataContainer, sqlConn);

                        // Backup the database
                        service.PerformBackup(backupOperation);

                        VerifyAndCleanBackup(sqlConn, backupPath);
                    }
        }
示例#2
0
        //[Fact]
        public void ScriptBackupTest()
        {
            DisasterRecoveryService service   = new DisasterRecoveryService();
            string             databaseName   = "testbackup_" + new Random().Next(10000000, 99999999);
            SqlTestDb          testDb         = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);
            var                liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
            DatabaseTaskHelper helper         = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
            SqlConnection      sqlConn        = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);
            string             backupPath     = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);

            BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName,
                                                            BackupType.Full,
                                                            new List <string>()
            {
                backupPath
            },
                                                            new Dictionary <string, int>()
            {
                { backupPath, (int)DeviceType.File }
            });
            BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfo, helper.DataContainer, sqlConn);

            // Generate script for backup
            service.ScriptBackup(backupOperation);
            string script = backupOperation.ScriptContent;

            Assert.True(!string.IsNullOrEmpty(script));

            // Execute the script
            testDb.RunQuery(script);

            VerifyAndCleanBackup(backupPath);
            testDb.Cleanup();
        }
示例#3
0
        /// <summary>
        /// Get backup configuration info
        /// </summary>
        /// Test is failing in code coverage runs. Reenable when stable.
        ///[Fact]
        public async void GetBackupConfigInfoTest()
        {
            string databaseName = "testbackup_" + new Random().Next(10000000, 99999999);

            using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
            {
                var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);

                var requestContext = new Mock <RequestContext <BackupConfigInfoResponse> >();
                requestContext.Setup(x => x.SendResult(It.IsAny <BackupConfigInfoResponse>()))
                .Returns(Task.FromResult(new object()));

                var dbParams = new DefaultDatabaseInfoParams
                {
                    OwnerUri = liveConnection.ConnectionInfo.OwnerUri
                };

                DisasterRecoveryService service = new DisasterRecoveryService();
                await service.HandleBackupConfigInfoRequest(dbParams, requestContext.Object);

                requestContext.Verify(x => x.SendResult(It.Is <BackupConfigInfoResponse>
                                                            (p => p.BackupConfigInfo.RecoveryModel != string.Empty &&
                                                            p.BackupConfigInfo.DefaultBackupFolder != string.Empty)));
            }
        }
示例#4
0
        public void ScriptBackupWithDifferentActionTypesTest()
        {
            string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999);

            using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
            {
                // Create Full backup script
                string script = GenerateScriptForBackupType(BackupType.Full, databaseName);

                // Validate Full backup script
                Assert.Contains("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase);
                Assert.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase);
                Assert.DoesNotContain("DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase);

                // Create log backup script
                script = GenerateScriptForBackupType(BackupType.TransactionLog, databaseName);

                // Validate Log backup script
                Assert.Contains("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase);
                Assert.DoesNotContain("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase);
                Assert.DoesNotContain("DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase);

                // Create differential backup script
                script = GenerateScriptForBackupType(BackupType.Differential, databaseName);

                // Validate differential backup script
                Assert.Contains("BACKUP DATABASE", script, StringComparison.OrdinalIgnoreCase);
                Assert.DoesNotContain("BACKUP LOG", script, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("WITH  DIFFERENTIAL", script, StringComparison.OrdinalIgnoreCase);
            }
        }
示例#5
0
        public async Task RebuildIntellisenseCacheClearsScriptParseInfoCorrectly()
        {
            var testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, null, null, "LangSvcTest");

            try
            {
                var connectionInfoResult = LiveConnectionHelper.InitLiveConnectionInfo(testDb.DatabaseName);

                var langService = LanguageService.Instance;
                await langService.UpdateLanguageServiceOnConnection(connectionInfoResult.ConnectionInfo);

                var queryText = "SELECT * FROM dbo.";
                connectionInfoResult.ScriptFile.SetFileContents(queryText);

                var textDocumentPosition =
                    connectionInfoResult.TextDocumentPosition ??
                    new TextDocumentPosition()
                {
                    TextDocument = new TextDocumentIdentifier
                    {
                        Uri = connectionInfoResult.ScriptFile.ClientFilePath
                    },
                    Position = new Position
                    {
                        Line      = 0,
                        Character = queryText.Length
                    }
                };

                // First check that we don't have any items in the completion list as expected
                var initialCompletionItems = await langService.GetCompletionItems(
                    textDocumentPosition, connectionInfoResult.ScriptFile, connectionInfoResult.ConnectionInfo);

                Assert.True(initialCompletionItems.Length == 0, $"Should not have any completion items initially. Actual : [{string.Join(',', initialCompletionItems.Select(ci => ci.Label))}]");

                // Now create a table that should show up in the completion list
                testDb.RunQuery("CREATE TABLE dbo.foo(col1 int)");

                // And refresh the cache
                await langService.HandleRebuildIntelliSenseNotification(
                    new RebuildIntelliSenseParams()
                {
                    OwnerUri = connectionInfoResult.ScriptFile.ClientFilePath
                },
                    new TestEventContext());

                // Now we should expect to see the item show up in the completion list
                var afterTableCreationCompletionItems = await langService.GetCompletionItems(
                    textDocumentPosition, connectionInfoResult.ScriptFile, connectionInfoResult.ConnectionInfo);

                Assert.True(afterTableCreationCompletionItems.Length == 1, $"Should only have a single completion item after rebuilding Intellisense cache. Actual : [{string.Join(',', initialCompletionItems.Select(ci => ci.Label))}]");
                Assert.True(afterTableCreationCompletionItems[0].InsertText == "foo", $"Expected single completion item 'foo'. Actual : [{string.Join(',', initialCompletionItems.Select(ci => ci.Label))}]");
            }
            finally
            {
                testDb.Cleanup();
            }
        }
 // helper method to set up a Sql Connection to a database
 private SqlConnection SetUpConnection(string name)
 {
     SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, name);
     ConnectionInfo connInfo = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(testDb.DatabaseName);
     string connectionString = ConnectionService.BuildConnectionString(connInfo.ConnectionDetails);
     SqlConnection resultConnection = new SqlConnection(connectionString);
     resultConnection.Open();
     return resultConnection;
 }
示例#7
0
        /// <summary>
        /// Test creating backup with advanced options set.
        /// </summary>
        //[Fact]
        public void ScriptBackupWithAdvancedOptionsTest()
        {
            DisasterRecoveryService service   = new DisasterRecoveryService();
            string             databaseName   = "testbackup_" + new Random().Next(10000000, 99999999);
            SqlTestDb          testDb         = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);
            var                liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
            DatabaseTaskHelper helper         = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
            SqlConnection      sqlConn        = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);
            string             backupPath     = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);

            string certificateName         = CreateCertificate(testDb);
            string cleanupCertificateQuery = string.Format(CleanupCertificateQueryFormat, certificateName);

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

            backupInfo.FormatMedia         = true;
            backupInfo.SkipTapeHeader      = true;
            backupInfo.Initialize          = true;
            backupInfo.MediaName           = "backup test media";
            backupInfo.MediaDescription    = "backup test";
            backupInfo.EncryptionAlgorithm = (int)BackupEncryptionAlgorithm.Aes128;
            backupInfo.EncryptorType       = (int)BackupEncryptorType.ServerCertificate;
            backupInfo.EncryptorName       = certificateName;

            BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfo, helper.DataContainer, sqlConn);

            // Backup the database
            Console.WriteLine("Generate script for backup operation..");
            service.ScriptBackup(backupOperation);
            string script = backupOperation.ScriptContent;

            // Run the script
            Console.WriteLine("Execute the script..");
            testDb.RunQuery(script);

            // Remove the backup file
            Console.WriteLine("Verify the backup file exists and remove..");
            VerifyAndCleanBackup(backupPath);

            // Delete certificate and master key
            Console.WriteLine("Remove certificate and master key..");
            testDb.RunQuery(cleanupCertificateQuery);

            // Clean up the database
            Console.WriteLine("Clean up database..");
            testDb.Cleanup();
        }
示例#8
0
        public async Task DiagnosticsTests()
        {
            TestServerType serverType = TestServerType.OnPrem;

            SqlTestDb.CreateNew(serverType, doNotCleanupDb: true, databaseName: Common.PerfTestDatabaseName, query: Scripts.CreateDatabaseObjectsQuery);

            using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
                using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                {
                    await testService.ConnectForQuery(serverType, Scripts.TestDbSimpleSelectQuery, queryTempFile.FilePath, Common.PerfTestDatabaseName);

                    Thread.Sleep(500);
                    var contentChanges = new TextDocumentChangeEvent[1];
                    contentChanges[0] = new TextDocumentChangeEvent()
                    {
                        Range = new Range
                        {
                            Start = new Position
                            {
                                Line      = 0,
                                Character = 5
                            },
                            End = new Position
                            {
                                Line      = 0,
                                Character = 6
                            }
                        },
                        RangeLength = 1,
                        Text        = "z"
                    };
                    DidChangeTextDocumentParams changeParams = new DidChangeTextDocumentParams
                    {
                        ContentChanges = contentChanges,
                        TextDocument   = new VersionedTextDocumentIdentifier
                        {
                            Version = 2,
                            Uri     = queryTempFile.FilePath
                        }
                    };

                    TestTimer timer = new TestTimer()
                    {
                        PrintResult = true
                    };
                    await testService.RequestChangeTextDocumentNotification(changeParams);

                    await testService.ExecuteWithTimeout(timer, 60000, async() =>
                    {
                        var completeEvent = await testService.Driver.WaitForEvent(PublishDiagnosticsNotification.Type, 15000);
                        return(completeEvent?.Diagnostics != null && completeEvent.Diagnostics.Length > 0);
                    });

                    await testService.Disconnect(queryTempFile.FilePath);
                }
        }
示例#9
0
 private void ExecuteAndValidatePeekTest(string query, string objectName, string objectType, string schemaName = "dbo")
 {
     if (!string.IsNullOrEmpty(query))
     {
         using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, query))
         {
             ValidatePeekTest(testDb.DatabaseName, objectName, objectType, schemaName, true);
         }
     }
     else
     {
         ValidatePeekTest(null, objectName, objectType, schemaName, false);
     }
 }
        /// Test is failing in code coverage runs. Reenable when stable.
        ///[Fact]
        public void CreateBackupTest()
        {
            string    databaseName   = "testbackup_" + new Random().Next(10000000, 99999999);
            SqlTestDb testDb         = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);
            var       liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);

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

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

            BackupInfo backupInfo = CreateBackupInfo(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
            };

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

            DisasterRecoveryService.Instance.PerformBackup(backupOperation);

            // Remove the backup file
            if (File.Exists(backupPath))
            {
                File.Delete(backupPath);
            }

            // Clean up the database
            testDb.Cleanup();
        }
 public ScriptingFixture()
 {
     this.Database = SqlTestDb.CreateNew(TestServerType.OnPrem);
     this.Database.RunQuery(Scripts.CreateNorthwindSchema, throwOnError: true);
     Console.WriteLine("Northwind setup complete, database name: {0}", this.Database.DatabaseName);
 }
示例#12
0
        //[Fact]
        public async void BackupFileBrowserTest()
        {
            string    databaseName = "testfilebrowser_" + new Random().Next(10000000, 99999999);
            SqlTestDb testDb       = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);

            // Initialize backup service
            var liveConnection              = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
            DatabaseTaskHelper      helper  = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
            SqlConnection           sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);
            DisasterRecoveryService disasterRecoveryService = new DisasterRecoveryService();
            BackupConfigInfo        backupConfigInfo        = disasterRecoveryService.GetBackupConfigInfo(helper.DataContainer, sqlConn, sqlConn.Database);

            // Create backup file
            string backupPath = Path.Combine(backupConfigInfo.DefaultBackupFolder, databaseName + ".bak");
            string query      = $"BACKUP DATABASE [{databaseName}] TO  DISK = N'{backupPath}' WITH NOFORMAT, NOINIT, NAME = N'{databaseName}-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
            await TestServiceProvider.Instance.RunQueryAsync(TestServerType.OnPrem, "master", query);

            FileBrowserService service = new FileBrowserService();

            string[] backupFilters = new string[2] {
                "*.bak", "*.trn"
            };
            var openParams = new FileBrowserOpenParams
            {
                OwnerUri    = liveConnection.ConnectionInfo.OwnerUri,
                ExpandPath  = backupConfigInfo.DefaultBackupFolder,
                FileFilters = backupFilters
            };

            var openBrowserEventFlowValidator = new EventFlowValidator <bool>()
                                                .AddEventValidation(FileBrowserOpenedNotification.Type, eventParams =>
            {
                Assert.True(eventParams.Succeeded);
                Assert.NotNull(eventParams.FileTree);
                Assert.NotNull(eventParams.FileTree.RootNode);
                Assert.NotNull(eventParams.FileTree.RootNode.Children);
                Assert.True(eventParams.FileTree.RootNode.Children.Count > 0);
                Assert.True(ContainsFileInTheFolder(eventParams.FileTree.SelectedNode, backupPath));
            })
                                                .Complete();

            await service.RunFileBrowserOpenTask(openParams, openBrowserEventFlowValidator.Object);

            // Verify complete notification event was fired and the result
            openBrowserEventFlowValidator.Validate();

            var expandParams = new FileBrowserExpandParams
            {
                OwnerUri   = liveConnection.ConnectionInfo.OwnerUri,
                ExpandPath = backupConfigInfo.DefaultBackupFolder
            };


            var expandEventFlowValidator = new EventFlowValidator <bool>()
                                           .AddEventValidation(FileBrowserExpandedNotification.Type, eventParams =>
            {
                Assert.True(eventParams.Succeeded);
                Assert.NotNull(eventParams.Children);
                Assert.True(eventParams.Children.Length > 0);
            })
                                           .Complete();

            // Expand the node in file browser
            await service.RunFileBrowserExpandTask(expandParams, expandEventFlowValidator.Object);

            // Verify result
            expandEventFlowValidator.Validate();

            var validateParams = new FileBrowserValidateParams
            {
                OwnerUri      = liveConnection.ConnectionInfo.OwnerUri,
                ServiceType   = FileValidationServiceConstants.Backup,
                SelectedFiles = new[] { backupPath }
            };

            var validateEventFlowValidator = new EventFlowValidator <bool>()
                                             .AddEventValidation(FileBrowserValidatedNotification.Type, eventParams => Assert.True(eventParams.Succeeded))
                                             .Complete();

            // Validate selected files in the browser
            await service.RunFileBrowserValidateTask(validateParams, validateEventFlowValidator.Object);

            // Verify complete notification event was fired and the result
            validateEventFlowValidator.Validate();

            // Remove the backup file
            if (File.Exists(backupPath))
            {
                File.Delete(backupPath);
            }
        }
 public override void Before(MethodInfo methodUnderTest)
 {
     SqlTestDb.CreateNew(ServerType, doNotCleanupDb: true, databaseName: Common.PerfTestDatabaseName, query: Scripts.CreateDatabaseObjectsQuery);
 }
        public void CreateBackupWithAdvancedOptionsTest()
        {
            string    databaseName            = "testbackup_" + new Random().Next(10000000, 99999999);
            SqlTestDb testDb                  = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);
            string    certificateName         = "backupcertificate" + new Random().Next(10000000, 99999999);
            string    masterkeyPassword       = Guid.NewGuid().ToString();
            string    createCertificateQuery  = string.Format(CreateCertificateQueryFormat, masterkeyPassword, certificateName);
            string    cleanupCertificateQuery = string.Format(CleanupCertificateQueryFormat, certificateName);

            // create master key and certificate
            Console.WriteLine("Create master key and certificate..");
            testDb.RunQuery(createCertificateQuery);

            var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);

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

            // Get default backup path
            Console.WriteLine("Get default backup path..");
            BackupConfigInfo backupConfigInfo = DisasterRecoveryService.Instance.GetBackupConfigInfo(helper.DataContainer, sqlConn, sqlConn.Database);
            string           backupPath       = Path.Combine(backupConfigInfo.DefaultBackupFolder, databaseName + ".bak");

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

            // Set advanced options
            backupInfo.ContinueAfterError = true;
            backupInfo.FormatMedia        = true;
            backupInfo.SkipTapeHeader     = true;
            backupInfo.Initialize         = true;
            backupInfo.MediaName          = "backup test media";
            backupInfo.MediaDescription   = "backup test";
            backupInfo.RetainDays         = 90;
            backupInfo.CompressionOption  = (int)BackupCompressionOptions.On;

            // Set encryption
            backupInfo.EncryptionAlgorithm = (int)BackupEncryptionAlgorithm.Aes128;
            backupInfo.EncryptorType       = (int)BackupEncryptorType.ServerCertificate;
            backupInfo.EncryptorName       = certificateName;

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

            // Backup the database
            Console.WriteLine("Perform backup operation..");
            BackupOperation backupOperation = DisasterRecoveryService.Instance.SetBackupInput(helper.DataContainer, sqlConn, backupParams.BackupInfo);

            DisasterRecoveryService.Instance.PerformBackup(backupOperation);

            // Verify backup file is created
            Assert.True(File.Exists(backupPath));

            // Remove the backup file
            Console.WriteLine("Remove backup file..");
            if (File.Exists(backupPath))
            {
                File.Delete(backupPath);
            }

            // Delete certificate and master key
            Console.WriteLine("Remove certificate and master key..");
            testDb.RunQuery(cleanupCertificateQuery);

            // Clean up the database
            Console.WriteLine("Clean up database..");
            testDb.Cleanup();
        }