Exemplo n.º 1
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();
        }
Exemplo n.º 2
0
        public void ReliableConnectionHelperTest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var            result     = LiveConnectionHelper.InitLiveConnectionInfo(null, queryTempFile.FilePath);
                ConnectionInfo connInfo   = result.ConnectionInfo;
                DbConnection   connection = connInfo.ConnectionTypeToConnectionMap[ConnectionType.Default];
                connection.Open();

                Assert.True(connection.State == ConnectionState.Open, "Connection should be open.");
                Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(connection));

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(builder, null));
                ReliableConnectionHelper.TryAddAlwaysOnConnectionProperties(builder, new SqlConnectionStringBuilder());

                Assert.NotNull(ReliableConnectionHelper.GetServerName(connection));
                Assert.NotNull(ReliableConnectionHelper.ReadServerVersion(connection));

                Assert.NotNull(ReliableConnectionHelper.GetAsSqlConnection(connection));

                ReliableConnectionHelper.ServerInfo info = ReliableConnectionHelper.GetServerVersion(connection);
                Assert.NotNull(ReliableConnectionHelper.IsVersionGreaterThan2012RTM(info));
            }
        }
Exemplo n.º 3
0
        public async void InvokeSqlAssessmentServerTest()
        {
            var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");

            var connection = liveConnection.ConnectionInfo.AllConnections.FirstOrDefault();

            Debug.Assert(connection != null, "Live connection is always expected providing a connection");

            var serverInfo = ReliableConnectionHelper.GetServerVersion(connection);

            var response = await CallAssessment <AssessmentResultItem>(
                nameof(SqlAssessmentService.InvokeSqlAssessment),
                SqlObjectType.Server,
                liveConnection);

            Assert.All(
                response.Items,
                i =>
            {
                Assert.NotNull(i.Message);
                Assert.NotEmpty(i.Message);
                Assert.Equal(serverInfo.ServerName, i.TargetName);

                if (i.Kind == 0)
                {
                    AssertInfoPresent(i);
                }
            });
        }
Exemplo n.º 4
0
        public async void GetDefinitionFromChildrenAndParents()
        {
            string queryString = "select * from master.sys.objects";
            // place the cursor on every token

            //cursor on objects
            TextDocumentPosition objectDocument = CreateTextDocPositionWithCursor(26, OwnerUri);

            //cursor on sys
            TextDocumentPosition sysDocument = CreateTextDocPositionWithCursor(22, OwnerUri);

            //cursor on master
            TextDocumentPosition masterDocument = CreateTextDocPositionWithCursor(17, OwnerUri);

            LiveConnectionHelper.TestConnectionResult connectionResult = LiveConnectionHelper.InitLiveConnectionInfo(null);
            ScriptFile     scriptFile = connectionResult.ScriptFile;
            ConnectionInfo connInfo   = connectionResult.ConnectionInfo;

            connInfo.RemoveAllConnections();
            var bindingQueue = new ConnectedBindingQueue();

            bindingQueue.AddConnectionContext(connInfo);
            scriptFile.Contents = queryString;

            var service = new LanguageService();

            service.RemoveScriptParseInfo(OwnerUri);
            service.BindingQueue = bindingQueue;
            await service.UpdateLanguageServiceOnConnection(connectionResult.ConnectionInfo);

            Thread.Sleep(2000);

            ScriptParseInfo scriptInfo = new ScriptParseInfo {
                IsConnected = true
            };

            service.ParseAndBind(scriptFile, connInfo);
            scriptInfo.ConnectionKey = bindingQueue.AddConnectionContext(connInfo);
            service.ScriptParseInfoMap.Add(OwnerUri, scriptInfo);

            // When I call the language service
            var objectResult = service.GetDefinition(objectDocument, scriptFile, connInfo);
            var sysResult    = service.GetDefinition(sysDocument, scriptFile, connInfo);
            var masterResult = service.GetDefinition(masterDocument, scriptFile, connInfo);

            // Then I expect the results to be non-null
            Assert.NotNull(objectResult);
            Assert.NotNull(sysResult);
            Assert.NotNull(masterResult);

            // And I expect the all results to be the same
            Assert.True(CompareLocations(objectResult.Locations, sysResult.Locations));
            Assert.True(CompareLocations(objectResult.Locations, masterResult.Locations));

            Cleanup(objectResult.Locations);
            Cleanup(sysResult.Locations);
            Cleanup(masterResult.Locations);
            service.ScriptParseInfoMap.Remove(OwnerUri);
            connInfo.RemoveAllConnections();
        }
Exemplo n.º 5
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)));
            }
        }
Exemplo n.º 6
0
        public void TestConnectSqlCmdCommand()
        {
            var            fileStreamFactory  = MemoryFileSystem.GetFileStreamFactory();
            var            liveConnection     = LiveConnectionHelper.InitLiveConnectionInfo("master");
            ConnectionInfo connInfo           = liveConnection.ConnectionInfo;
            string         serverName         = liveConnection.ConnectionInfo.ConnectionDetails.ServerName;
            string         sqlCmdQuerySuccess = $@"
:Connect {serverName}
select * from sys.databases where name = 'master'
GO";

            Query query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQuerySuccess, connInfo, fileStreamFactory, IsSqlCmd: true);

            Assert.True(query.Batches.Length == 1, $"Expected: 1 parsed batch, actual : {query.Batches.Length}");
            Assert.True(query.Batches[0].HasExecuted && !query.Batches[0].HasError && query.Batches[0].ResultSets.Count == 1, "Query should be executed and have one result set");

            string sqlCmdQueryFilaure = $@"
:Connect SomeWrongName
select * from sys.databases where name = 'master'
GO";

            query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQueryFilaure, connInfo, fileStreamFactory, IsSqlCmd: true);
            Assert.True(query.Batches.Length == 1, $"Expected: 1 parsed batch, actual : {query.Batches.Length}");
            Assert.True(query.Batches[0].HasError, "Query should have error");
        }
Exemplo n.º 7
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);
                    }
        }
Exemplo n.º 8
0
        public void VerifyOnErrorSqlCmd()
        {
            using (ExecutionEngine executionEngine = new ExecutionEngine())
            {
                var    liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
                string serverName     = liveConnection.ConnectionInfo.ConnectionDetails.ServerName;
                string sqlCmdQuery    = $@"
:on error ignore
GO
select * from sys.databases_wrong where name = 'master'
GO
select* from sys.databases where name = 'master'
GO
:on error exit
GO
select* from sys.databases_wrong where name = 'master'
GO
select* from sys.databases where name = 'master'
GO";
                var    condition      = new ExecutionEngineConditions()
                {
                    IsSqlCmd = true
                };
                using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
                    using (TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, sqlConn, condition))
                    {
                        testExecutor.Run();

                        Assert.True(testExecutor.ResultCountQueue.Count == 1, $"Unexpected number of ResultCount items - expected only 1 since the later should not be executed but got {testExecutor.ResultCountQueue.Count}");
                        Assert.True(testExecutor.ErrorMessageQueue.Count == 2, $"Unexpected number error messages from test executor expected 2, actual : {string.Join(Environment.NewLine, testExecutor.ErrorMessageQueue)}");
                    }
            }
        }
Exemplo n.º 9
0
        public void TestOnErrorSqlCmdCommand()
        {
            var            fileStreamFactory  = MemoryFileSystem.GetFileStreamFactory();
            var            liveConnection     = LiveConnectionHelper.InitLiveConnectionInfo("master");
            ConnectionInfo connInfo           = liveConnection.ConnectionInfo;
            string         sqlCmdQuerySuccess = $@"
:on error ignore
GO
select * from sys.databases_wrong where name = 'master'
GO
select * from sys.databases where name = 'master'
GO";

            Query query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQuerySuccess, connInfo, fileStreamFactory, IsSqlCmd: true);

            Assert.True(query.Batches[0].HasExecuted && query.Batches[0].HasError, "first batch should be executed and have error");
            Assert.True(query.Batches[1].HasExecuted, "last batch should be executed");


            string sqlCmdQueryFilaure = $@"
:on error exit
GO
select * from sys.databases_wrong where name = 'master'
GO
select * from sys.databases where name = 'master'
GO";

            query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQueryFilaure, connInfo, fileStreamFactory, IsSqlCmd: true);
            Assert.True(query.Batches[0].HasExecuted && query.Batches[0].HasError, "first batch should be executed and have error");
            Assert.False(query.Batches[1].HasExecuted, "last batch should NOT be executed");
        }
Exemplo n.º 10
0
        public void DatabaseChangesWhenCallingUseDatabase()
        {
            const string master   = "master";
            const string tempdb   = "tempdb";
            const string useQuery = "USE {0}";

            // Given a connection to a live database
            var            result   = LiveConnectionHelper.InitLiveConnectionInfo();
            ConnectionInfo connInfo = result.ConnectionInfo;
            DbConnection   connection;

            connInfo.TryGetConnection(ConnectionType.Default, out connection);

            var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(new Dictionary <string, byte[]>());

            // If I use master, the current database should be master
            CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);
            Assert.Equal(master, connection.Database);

            // If I use tempdb, the current database should be tempdb
            CreateAndExecuteQuery(string.Format(useQuery, tempdb), connInfo, fileStreamFactory);
            Assert.Equal(tempdb, connection.Database);

            // If I switch back to master, the current database should be master
            CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);
            Assert.Equal(master, connection.Database);
        }
Exemplo n.º 11
0
        public void VerifyRunSqlCmd()
        {
            using (ExecutionEngine executionEngine = new ExecutionEngine())
            {
                const string sqlCmdQuery = @"
:setvar __var1 1
:setvar __var2 2
:setvar __IsSqlCmdEnabled " + "\"True\"" + @"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
    BEGIN
        PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
                SET NOEXEC ON;
                END
GO
select $(__var1) + $(__var2) as col
GO";

                var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
                var condition      = new ExecutionEngineConditions()
                {
                    IsSqlCmd = true
                };
                using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
                    using (TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, sqlConn, condition))
                    {
                        testExecutor.Run();

                        Assert.True(testExecutor.ResultCountQueue.Count >= 1, $"Unexpected number of ResultCount items - expected 0 but got {testExecutor.ResultCountQueue.Count}");
                        Assert.True(testExecutor.ErrorMessageQueue.Count == 0, $"Unexpected error messages from test executor : {string.Join(Environment.NewLine, testExecutor.ErrorMessageQueue)}");
                    }
            }
        }
Exemplo n.º 12
0
        public async void OpenFileBrowserTest()
        {
            var liveConnection         = LiveConnectionHelper.InitLiveConnectionInfo();
            FileBrowserService service = new FileBrowserService();

            var openParams = new FileBrowserOpenParams
            {
                OwnerUri    = liveConnection.ConnectionInfo.OwnerUri,
                ExpandPath  = "",
                FileFilters = new[] { "*" }
            };

            var efv = 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);
            })
                      .Complete();
            await service.RunFileBrowserOpenTask(openParams, efv.Object);

            efv.Validate();
        }
Exemplo n.º 13
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();
            }
        }
        /// <summary>
        /// Verify  the profiler service XEvent session factory
        /// </summary>
        //[Fact]
        public void TestCreateXEventSession()
        {
            var             liveConnection  = LiveConnectionHelper.InitLiveConnectionInfo("master");
            ProfilerService profilerService = new ProfilerService();
            IXEventSession  xeSession       = profilerService.CreateXEventSession(liveConnection.ConnectionInfo);

            Assert.NotNull(xeSession);
            Assert.NotNull(xeSession.GetTargetXml());
        }
Exemplo n.º 15
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();
        }
Exemplo n.º 16
0
        public void PrepopulateCommonMetadata()
        {
            var result   = LiveConnectionHelper.InitLiveConnectionInfo();
            var connInfo = result.ConnectionInfo;

            ScriptParseInfo scriptInfo = new ScriptParseInfo {
                IsConnected = true
            };

            LanguageService.Instance.PrepopulateCommonMetadata(connInfo, scriptInfo, null);
        }
Exemplo n.º 17
0
        public void VerifyExecute()
        {
            Batch batch          = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15);
            var   liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");

            using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
            {
                var executionResult = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
                Assert.Equal <ScriptExecutionResult>(ScriptExecutionResult.Success, executionResult);
            }
        }
Exemplo n.º 18
0
        public void TestBatchExecutionTime()
        {
            var            result              = LiveConnectionHelper.InitLiveConnectionInfo();
            ConnectionInfo connInfo            = result.ConnectionInfo;
            var            fileStreamFactory   = MemoryFileSystem.GetFileStreamFactory();
            Query          query               = CreateAndExecuteQuery("select * from sys.databases", connInfo, fileStreamFactory);
            DateTime       elapsedTime         = Convert.ToDateTime(query.Batches[0].ExecutionElapsedTime);
            Query          mutipleQuery        = CreateAndExecuteQuery("select * from sys.databases\r\nGO 15", connInfo, fileStreamFactory);
            DateTime       multipleElapsedTime = Convert.ToDateTime(mutipleQuery.Batches[0].ExecutionElapsedTime);

            Assert.True(multipleElapsedTime > elapsedTime);
        }
Exemplo n.º 19
0
        public void VerifyCancel()
        {
            ScriptExecutionResult result = ScriptExecutionResult.All;
            Batch batch          = new Batch(sqlText: "SELECT 1+1", isResultExpected: true, execTimeout: 15);
            var   liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");

            using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
            {
                batch.Cancel();
                result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
            }
            Assert.Equal <ScriptExecutionResult>(result, ScriptExecutionResult.Cancel);
        }
Exemplo n.º 20
0
        public void ValidateDefaultBackupFolderPath()
        {
            var liveConnection            = LiveConnectionHelper.InitLiveConnectionInfo("master");
            DatabaseTaskHelper helper     = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
            SqlConnection      sqlConn    = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);
            string             backupPath = GetDefaultBackupFolderPath(helper.DataContainer, sqlConn);

            bool isFolder;
            bool result = DisasterRecoveryFileValidator.IsPathExisting(sqlConn, backupPath, out isFolder);

            Assert.True(isFolder);
            Assert.True(result);
        }
Exemplo n.º 21
0
        public void VerifyHandleExceptionMessage()
        {
            Batch batch          = new Batch(sqlText: "SEL@ECT 1+1", isResultExpected: true, execTimeout: 15);
            var   liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");

            using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
            {
                ScriptExecutionResult result = batch.Execute(sqlConn, ShowPlanType.AllShowPlan);
            }
            ScriptExecutionResult finalResult = (batch.RowsAffected > 0) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure;

            Assert.Equal <ScriptExecutionResult>(finalResult, ScriptExecutionResult.Failure);
        }
        private StorageDataReader GetTestStorageDataReader(string query)
        {
            var          result = LiveConnectionHelper.InitLiveConnectionInfo();
            DbConnection connection;

            result.ConnectionInfo.TryGetConnection(ConnectionType.Default, out connection);

            var command = connection.CreateCommand();

            command.CommandText = query;
            DbDataReader reader = command.ExecuteReader();

            return(new StorageDataReader(reader));
        }
        public void PrepopulateCommonMetadata()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var result   = LiveConnectionHelper.InitLiveConnectionInfo("master", queryTempFile.FilePath);
                var connInfo = result.ConnectionInfo;

                ScriptParseInfo scriptInfo = new ScriptParseInfo {
                    IsConnected = true
                };

                LanguageService.Instance.PrepopulateCommonMetadata(connInfo, scriptInfo, null);
            }
        }
Exemplo n.º 24
0
 // Verify whether the batchParser execute SqlCmd.
 //[Fact]   //  This Testcase should execute and pass, But it is failing now.
 public void VerifyIsSqlCmd()
 {
     using (ExecutionEngine executionEngine = new ExecutionEngine())
     {
         string query          = @"sqlcmd -Q ""select 1 + 2 as col"" ";
         var    liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");
         using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
         {
             TestExecutor testExecutor = new TestExecutor(query, sqlConn, new ExecutionEngineConditions());
             testExecutor.Run();
             Assert.True(testExecutor.ResultCountQueue.Count >= 1);
         }
     }
 }
        public async void GetCurrentConnectionStringTest()
        {
            // If we make a connection to a live database
            ConnectionService service = ConnectionService.Instance;
            var result         = LiveConnectionHelper.InitLiveConnectionInfo();
            var requestContext = new Mock <SqlTools.Hosting.Protocol.RequestContext <string> >();
            var requestParams  = new GetConnectionStringParams()
            {
                OwnerUri = result.ConnectionInfo.OwnerUri
            };

            await service.HandleGetConnectionStringRequest(requestParams, requestContext.Object);

            requestContext.VerifyAll();
        }
Exemplo n.º 26
0
        //[Fact]
        public void ValidatorShouldReturnFalseForInvalidPath()
        {
            var liveConnection        = LiveConnectionHelper.InitLiveConnectionInfo("master");
            DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);

            string message;
            bool   result = DisasterRecoveryFileValidator.ValidatePaths(new FileBrowserValidateEventArgs
            {
                ServiceType = FileValidationServiceConstants.Backup,
                OwnerUri    = liveConnection.ConnectionInfo.OwnerUri,
                FilePaths   = new string[] { Guid.NewGuid().ToString() }
            }, out message);

            Assert.False(result);
            Assert.True(!string.IsNullOrEmpty(message));
        }
        private LiveConnectionHelper.TestConnectionResult GetLiveAutoCompleteTestObjects()
        {
            var textDocument = new TextDocumentPosition
            {
                TextDocument = new TextDocumentIdentifier { Uri = Test.Common.Constants.OwnerUri },
                Position = new Position
                {
                    Line = 0,
                    Character = 0
                }
            };

            var result = LiveConnectionHelper.InitLiveConnectionInfo();
            result.TextDocumentPosition = textDocument;
            return result;
        }
Exemplo n.º 28
0
        public async void GetAssessmentItemsDatabaseTest()
        {
            const string DatabaseName   = "tempdb";
            var          liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(DatabaseName);
            var          response       = await CallAssessment <CheckInfo>(
                nameof(SqlAssessmentService.GetAssessmentItems),
                SqlObjectType.Database,
                liveConnection);

            Assert.All(
                response.Items,
                i =>
            {
                StringAssert.EndsWith(":" + DatabaseName, i.TargetName);
                AssertInfoPresent(i);
            });
        }
Exemplo n.º 29
0
        public async void HandleFileBrowserCloseRequestTest()
        {
            var liveConnection         = LiveConnectionHelper.InitLiveConnectionInfo();
            FileBrowserService service = new FileBrowserService();
            var requestContext         = new Mock <RequestContext <FileBrowserCloseResponse> >();

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

            var inputParams = new FileBrowserCloseParams
            {
                OwnerUri = liveConnection.ConnectionInfo.OwnerUri
            };

            await service.HandleFileBrowserCloseRequest(inputParams, requestContext.Object);

            requestContext.Verify(x => x.SendResult(It.Is <FileBrowserCloseResponse>(p => p.Succeeded == true)));
        }
Exemplo n.º 30
0
        /// 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();
        }