Beispiel #1
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)}");
                    }
            }
        }
Beispiel #2
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();
        }
        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);
        }
Beispiel #4
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)}");
                    }
            }
        }
Beispiel #5
0
        internal async Task TestDeletingUpdatedJob()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var service          = new AgentService();
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                //seting up a temp notebook job
                var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
                //verifying that the notebook is created
                Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));

                var originalName = notebook.Name;
                //Changing the notebookName
                notebook.Name = "myTestNotebookJob" + Guid.NewGuid().ToString();

                Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));

                await AgentNotebookHelper.UpdateNotebook(
                    service,
                    connectionResult.ConnectionInfo.OwnerUri,
                    originalName,
                    notebook,
                    null,
                    ManagementUtils.asRunType(0)
                    );

                Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));

                //cleaning up the job
                await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);
            }
        }
Beispiel #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");
        }
Beispiel #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);
                    }
        }
Beispiel #8
0
        internal async Task TestUpdateWithGarbagePath()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var service          = new AgentService();
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                //seting up a temp notebook job
                var notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
                //verifying that the notebook is created
                Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));

                var updateNotebookContext = new Mock <RequestContext <UpdateAgentNotebookResult> >();
                updateNotebookContext.Setup(x => x.SendResult(It.IsAny <UpdateAgentNotebookResult>())).Returns(Task.FromResult(new object()));
                //calling the endpoint with a garbage path
                await service.HandleUpdateAgentNotebookRequest(new UpdateAgentNotebookParams()
                {
                    OwnerUri         = connectionResult.ConnectionInfo.OwnerUri,
                    Notebook         = notebook,
                    TemplateFilePath = "garbargepath"
                }, updateNotebookContext.Object);

                //the enpoint should return false
                updateNotebookContext.Verify(x => x.SendResult(It.Is <UpdateAgentNotebookResult>(p => p.Success == false)));

                //cleaning up the job
                await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);

                Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
            }
        }
Beispiel #9
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);
                }
            });
        }
Beispiel #10
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));
            }
        }
Beispiel #11
0
        public async void VerifyExternalLanguageStatusRequest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                ExternalLanguageStatusResponseParams result = null;
                var requestContext = RequestContextMocks.Create <ExternalLanguageStatusResponseParams>(r => result = r).AddErrorHandling(null);

                ExternalLanguageStatusRequestParams requestParams = new ExternalLanguageStatusRequestParams
                {
                    OwnerUri     = connectionResult.ConnectionInfo.OwnerUri,
                    LanguageName = "Python"
                };

                await ExternalLanguageService.Instance.HandleExternalLanguageStatusRequest(requestParams, requestContext.Object);

                Assert.NotNull(result);

                ExternalLanguageService.Instance.ConnectionServiceInstance.Disconnect(new DisconnectParams
                {
                    OwnerUri = queryTempFile.FilePath,
                    Type     = ServiceLayer.Connection.ConnectionType.Default
                });
            }
        }
Beispiel #12
0
        public async Task TestHandleUpdateAgentScheduleRequest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                // setup
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                var service = new AgentService();
                var job     = await AgentTestUtils.SetupJob(connectionResult);

                var schedule = AgentTestUtils.GetTestScheduleInfo();
                await AgentTestUtils.DeleteAgentSchedule(service, connectionResult, schedule);

                await AgentTestUtils.CreateAgentSchedule(service, connectionResult, schedule);

                // test
                schedule.IsEnabled = !schedule.IsEnabled;
                await AgentTestUtils.UpdateAgentSchedule(service, connectionResult, schedule.Name, schedule);

                // cleanup
                await AgentTestUtils.DeleteAgentSchedule(service, connectionResult, schedule);

                await AgentTestUtils.CleanupJob(connectionResult, job);
            }
        }
        public async Task TestHandleUpdateAgentProxyRequest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                // setup
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                var credential = await SecurityTestUtils.SetupCredential(connectionResult);

                var service = new AgentService();
                var proxy   = AgentTestUtils.GetTestProxyInfo();
                await AgentTestUtils.DeleteAgentProxy(service, connectionResult, proxy);

                await AgentTestUtils.CreateAgentProxy(service, connectionResult, proxy);

                // test
                string originalProxyName = proxy.AccountName;
                proxy.AccountName = proxy.AccountName + " Updated";
                await AgentTestUtils.UpdateAgentProxy(service, connectionResult, originalProxyName, proxy);

                // cleanup
                await AgentTestUtils.DeleteAgentProxy(service, connectionResult, proxy);

                await SecurityTestUtils.CleanupCredential(connectionResult, credential);
            }
        }
Beispiel #14
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();
        }
Beispiel #15
0
        private void ValidatePeekTest(string databaseName, string objectName, string objectType, string schemaName, bool shouldReturnValidResult)
        {
            // Get live connectionInfo and serverConnection
            ConnectionInfo   connInfo         = LiveConnectionHelper.InitLiveConnectionInfoForDefinition(databaseName);
            ServerConnection serverConnection = LiveConnectionHelper.InitLiveServerConnectionForDefinition(connInfo);

            Scripter scripter = new Scripter(serverConnection, connInfo);

            Location[] locations = scripter.GetSqlObjectDefinition(objectName, schemaName, objectType);
            if (shouldReturnValidResult)
            {
                Assert.NotNull(locations);
                Cleanup(locations);
            }
            else
            {
                Assert.Null(locations);
            }

            var connectionService = LiveConnectionHelper.GetLiveTestConnectionService();

            connectionService.Disconnect(new DisconnectParams
            {
                OwnerUri = connInfo.OwnerUri
            });
        }
Beispiel #16
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();
        }
        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();
                }
            }
        }
Beispiel #18
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");
        }
Beispiel #19
0
        internal async Task TestDeleteAgentNotebookHandler()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var service          = new AgentService();
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                //creating a notebook job
                AgentNotebookInfo notebook = AgentTestUtils.SetupNotebookJob(connectionResult).Result;
                //verifying it's getting created
                Assert.Equal(true, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
                //deleting the notebook job
                var deleteNotebookContext = new Mock <RequestContext <ResultStatus> >();
                deleteNotebookContext.Setup(x => x.SendResult(It.IsAny <ResultStatus>())).Returns(Task.FromResult(new object()));
                await service.HandleDeleteAgentNotebooksRequest(new DeleteAgentNotebookParams()
                {
                    OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                    Notebook = notebook
                }, deleteNotebookContext.Object);

                deleteNotebookContext.Verify(x => x.SendResult(It.Is <ResultStatus>(p => p.Success == true)));
                //verifying if the job is deleted
                Assert.Equal(false, AgentTestUtils.VerifyNotebook(connectionResult, notebook));
            }
        }
Beispiel #20
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)));
            }
        }
Beispiel #21
0
        internal async Task TestDuplicateJobCreation()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var service          = new AgentService();
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                AgentNotebookInfo notebook = AgentTestUtils.GetTestNotebookInfo("myTestNotebookJob" + Guid.NewGuid().ToString(), "master");
                var createNotebookContext  = new Mock <RequestContext <CreateAgentNotebookResult> >();
                createNotebookContext.Setup(x => x.SendResult(It.IsAny <CreateAgentNotebookResult>())).Returns(Task.FromResult(new object()));
                await service.HandleCreateAgentNotebookRequest(new CreateAgentNotebookParams()
                {
                    OwnerUri         = connectionResult.ConnectionInfo.OwnerUri,
                    Notebook         = notebook,
                    TemplateFilePath = AgentTestUtils.CreateTemplateNotebookFile()
                }, createNotebookContext.Object);

                createNotebookContext.Verify(x => x.SendResult(It.Is <CreateAgentNotebookResult>(p => p.Success == true)));
                await service.HandleCreateAgentNotebookRequest(new CreateAgentNotebookParams()
                {
                    OwnerUri         = connectionResult.ConnectionInfo.OwnerUri,
                    Notebook         = notebook,
                    TemplateFilePath = AgentTestUtils.CreateTemplateNotebookFile()
                }, createNotebookContext.Object);

                createNotebookContext.Verify(x => x.SendResult(It.Is <CreateAgentNotebookResult>(p => p.Success == false)));
                await AgentTestUtils.CleanupNotebookJob(connectionResult, notebook);
            }
        }
        public async Task TestHandleUpdateAgentOperatorRequest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var createContext = new Mock <RequestContext <CreateAgentOperatorResult> >();

                var service      = new AgentService();
                var operatorInfo = new AgentOperatorInfo()
                {
                    Id           = 10,
                    Name         = "Joe DBA",
                    EmailAddress = "*****@*****.**"
                };

                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                await service.HandleCreateAgentOperatorRequest(new CreateAgentOperatorParams
                {
                    OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                    Operator = operatorInfo
                }, createContext.Object);

                createContext.VerifyAll();
            }
        }
Beispiel #23
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();
                }
            }
        }
Beispiel #24
0
        public async Task CancelRestorePlanRequestShouldCancelSuccessfully()
        {
            await VerifyBackupFileCreated();

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                string filePath = GetBackupFilePath(fullBackupFilePath);

                RestoreParams restoreParams = new RestoreParams
                {
                    BackupFilePaths = filePath,
                    OwnerUri        = queryTempFile.FilePath
                };

                await RunAndVerify <RestorePlanResponse>(
                    test : (requestContext) => service.HandleRestorePlanRequest(restoreParams, requestContext),
                    verify : ((result) =>
                {
                    restoreParams.SessionId = result.SessionId;
                    Assert.True(result.DbFiles.Any());
                }));

                await RunAndVerify <bool>(
                    test : (requestContext) => service.HandleCancelRestorePlanRequest(restoreParams, requestContext),
                    verify : ((result) =>
                {
                    Assert.True(result);
                }));
            }
        }
Beispiel #25
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;
 }
        /// <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());
        }
        public async Task TestHandleUpdateAgentProxyRequest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var createContext = new Mock <RequestContext <CreateAgentProxyResult> >();
                var updateContext = new Mock <RequestContext <UpdateAgentProxyResult> >();
                var deleteContext = new Mock <RequestContext <DeleteAgentProxyResult> >();

                var service = new AgentService();
                var proxy   = new AgentProxyInfo()
                {
                    Id             = 10,
                    AccountName    = "Test Proxy 2",
                    CredentialName = "User",
                    Description    = "",
                    IsEnabled      = true
                };

                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                await service.HandleDeleteAgentProxyRequest(new DeleteAgentProxyParams()
                {
                    OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                    Proxy    = proxy
                }, deleteContext.Object);

                deleteContext.VerifyAll();

                await service.HandleCreateAgentProxyRequest(new CreateAgentProxyParams
                {
                    OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                    Proxy    = proxy
                }, createContext.Object);

                createContext.VerifyAll();

                string originalProxyName = proxy.AccountName;
                proxy.AccountName = proxy.AccountName + " Updated";
                await service.HandleUpdateAgentProxyRequest(new UpdateAgentProxyParams()
                {
                    OwnerUri          = connectionResult.ConnectionInfo.OwnerUri,
                    OriginalProxyName = originalProxyName,
                    Proxy             = proxy
                }, updateContext.Object);

                updateContext.VerifyAll();

                await service.HandleDeleteAgentProxyRequest(new DeleteAgentProxyParams()
                {
                    OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                    Proxy    = proxy
                }, deleteContext.Object);

                deleteContext.VerifyAll();
            }
        }
Beispiel #29
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();
        }
        private ConnectParams CreateConnectParams()
        {
            ConnectParams connectParams = TestServiceProvider.Instance.ConnectionProfileService.GetConnectionParameters(TestServerType.OnPrem, "master");

            connectParams.OwnerUri = LiveConnectionHelper.GetTestSqlFile();
            connectParams.Connection.DatabaseName        = null;
            connectParams.Connection.DatabaseDisplayName = null;

            return(connectParams);
        }