Exemple #1
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));
            }
        }
        public async Task ConnectOnPremTest()
        {
            TestServerType serverType = TestServerType.OnPrem;

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
                {
                    const string query = Scripts.TestDbSimpleSelectQuery;
                    testService.WriteToFile(queryTempFile.FilePath, query);

                    DidOpenTextDocumentNotification openParams = new DidOpenTextDocumentNotification
                    {
                        TextDocument = new TextDocumentItem
                        {
                            Uri        = queryTempFile.FilePath,
                            LanguageId = "enu",
                            Version    = 1,
                            Text       = query
                        }
                    };

                    await testService.RequestOpenDocumentNotification(openParams);

                    Thread.Sleep(500);
                    var connected = await testService.CalculateRunTime(async() =>
                    {
                        var connectParams = testService.GetConnectionParameters(serverType, Common.PerfTestDatabaseName);
                        return(await testService.Connect(queryTempFile.FilePath, connectParams));
                    }, true);

                    Assert.True(connected, "Connection was not successful");
                }
        }
Exemple #3
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));
            }
        }
        public async Task NoOpQueryReturnsMessage()
        {
            // Given queries that do nothing (no-ops)...
            var queries = new string[]
            {
                "-- no-op",
                "GO",
                "GO -- no-op"
            };

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                using (TestHelper testHelper = new TestHelper())
                {
                    foreach (var query in queries)
                    {
                        Assert.True(await testHelper.Connect(queryTempFile.FilePath, ConnectionTestUtils.LocalhostConnection));

                        // If the queries are executed...
                        var queryResult = await testHelper.RunQueryAsync(queryTempFile.FilePath, query);

                        // Then I expect messages that the commands were completed successfully to be in the result
                        Assert.NotNull(queryResult);
                        Assert.NotNull(queryResult.Messages);
                        Assert.Equal("Commands completed successfully.", queryResult.Messages);

                        await testHelper.Disconnect(queryTempFile.FilePath);
                    }
                }
        }
        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();
                }
            }
        }
Exemple #6
0
        public async Task ChangeConfigurationTest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                using (TestHelper testHelper = new TestHelper())
                {
                    bool connected = await testHelper.Connect(queryTempFile.FilePath, ConnectionTestUtils.LocalhostConnection);

                    Assert.True(connected, "Connection was not successful");

                    Thread.Sleep(500);

                    var settings = new SqlToolsSettings();
                    settings.SqlTools.IntelliSense.EnableIntellisense = false;
                    DidChangeConfigurationParams <SqlToolsSettings> configParams = new DidChangeConfigurationParams <SqlToolsSettings>()
                    {
                        Settings = settings
                    };

                    await testHelper.RequestChangeConfigurationNotification(configParams);

                    Thread.Sleep(2000);

                    await testHelper.Disconnect(queryTempFile.FilePath);
                }
        }
Exemple #7
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));
            }
        }
Exemple #8
0
        public async Task ScriptSelectTable()
        {
            using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
                using (SelfCleaningTempFile tempFile = new SelfCleaningTempFile())
                {
                    await testService.Connect(tempFile.FilePath, testService.TestConnectionService.GetConnectionParameters(serverType: TestServerType.OnPrem));

                    ScriptingParams requestParams = new ScriptingParams
                    {
                        ScriptDestination = "ToEditor",
                        OwnerUri          = tempFile.FilePath,
                        ScriptOptions     = new ScriptOptions
                        {
                            ScriptCreateDrop = "ScriptSelect"
                        },
                        ScriptingObjects = new List <ScriptingObject>
                        {
                            new ScriptingObject
                            {
                                Type   = "Table",
                                Schema = "dbo",
                                Name   = "Customers",
                            }
                        }
                    };
                    ScriptingResult result = await testService.Script(requestParams);

                    Assert.True(result.Script.Contains("SELECT"));
                }
        }
 public void VerifyCreateLanguageWithLocalFile()
 {
     using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
     {
         ExternalLanguageOperations operations  = new ExternalLanguageOperations();
         ExternalLanguage           newLanguage = new ExternalLanguage()
         {
             Name     = "newLang",
             Contents = new List <ExternalLanguageContent>()
             {
                 new ExternalLanguageContent
                 {
                     IsLocalFile     = true,
                     PathToExtension = queryTempFile.FilePath
                 }
             }
         };
         Verify(null, (connection, lang, commandMock) =>
         {
             operations.UpdateLanguage(connection, newLanguage);
             commandMock.VerifySet(x => x.CommandText = It.Is <string>(s => s.Contains(ExternalLanguageOperations.CreateScript)));
             return(true);
         });
     }
 }
Exemple #10
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);
            }
        }
Exemple #11
0
        private async Task QueryResultFirstOnPremTest(TestServerType serverType, string query, [CallerMemberName] string testName = "")
        {
            await TestServiceDriverProvider.RunTestIterations(async (timer) =>
            {
                using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                    using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
                    {
                        await testService.ConnectForQuery(serverType, query, queryTempFile.FilePath, SqlTestDb.MasterDatabaseName);
                        testService.WriteToFile(queryTempFile.FilePath, query);
                        await testService.RunQueryAndWaitToStart(queryTempFile.FilePath, 50000);
                        await testService.ExecuteWithTimeout(timer, 500000, async() =>
                        {
                            var queryResult = await testService.ExecuteSubset(queryTempFile.FilePath, 0, 0, 0, 50);
                            if (queryResult != null)
                            {
                                Assert.NotNull(queryResult);
                                Assert.NotNull(queryResult.ResultSubset);
                                Assert.True(queryResult.ResultSubset.Rows.Any());
                            }
                            return(queryResult != null);
                        }, TimeSpan.FromMilliseconds(10));

                        await testService.Disconnect(queryTempFile.FilePath);
                    }
            }, testName);
        }
 private Task RunFileSaveTest(Func<string, Task> doSave)
 {
     using (SelfCleaningTempFile tempFile = new SelfCleaningTempFile())
     {
         return doSave(tempFile.FilePath);
     }
 }
Exemple #13
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 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();
            }
        }
        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);
            }
        }
Exemple #16
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
                });
            }
        }
Exemple #17
0
        public async Task NoOpQueryReturnsMessage(string query)
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
                {
                    Assert.True(await testService.Connect(TestServerType.OnPrem, queryTempFile.FilePath));
                    // If: the query is executed...
                    var queryResult = await testService.RunQueryAsync(queryTempFile.FilePath, query);

                    var message = await testService.WaitForMessage();

                    // Then:
                    // ... I expect a query result to indicate successfully started query
                    Assert.NotNull(queryResult);

                    // ... I expect a non-error message to be returned without a batch associated with it
                    Assert.NotNull(message);
                    Assert.NotNull(message.Message);
                    Assert.NotNull(message.Message.Message);
                    Assert.False(message.Message.IsError);
                    Assert.Null(message.Message.BatchId);

                    await testService.Disconnect(queryTempFile.FilePath);
                }
        }
Exemple #18
0
        public async Task ScriptProvidedOutputPath()
        {
            // Setup:
            // ... Create a session with a proper query and metadata
            EditSession s = await GetBasicSession();

            // ... Add two mock edits that will generate a script
            Mock <RowEditBase> edit = new Mock <RowEditBase>();

            edit.Setup(e => e.GetScript()).Returns("test");
            s.EditCache[0] = edit.Object;
            s.EditCache[1] = edit.Object;

            using (SelfCleaningTempFile file = new SelfCleaningTempFile())
            {
                // If: I script the edit cache to a local output path
                string outputPath = s.ScriptEdits(file.FilePath);

                // Then:
                // ... The output path used should be the same as the one we provided
                Assert.Equal(file.FilePath, outputPath);

                // ... The written file should have two lines, one for each edit
                Assert.Equal(2, File.ReadAllLines(outputPath).Length);
            }
        }
        public async Task ScriptDatabaseSchemaAndData()
        {
            using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
                using (SelfCleaningTempFile tempFile = new SelfCleaningTempFile())
                {
                    ScriptingParams requestParams = new ScriptingParams
                    {
                        FilePath         = tempFile.FilePath,
                        ConnectionString = this.Northwind.ConnectionString,
                        ScriptOptions    = new ScriptOptions
                        {
                            TypeOfDataToScript = "SchemaAndData",
                        },
                    };

                    ScriptingResult result = await testService.Script(requestParams);

                    ScriptingPlanNotificationParams planEvent = await testService.Driver.WaitForEvent(ScriptingPlanNotificationEvent.Type, TimeSpan.FromSeconds(30));

                    ScriptingCompleteParams completeParameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(30));

                    Assert.True(completeParameters.Success);
                    Assert.Equal <int>(ScriptingFixture.ObjectCountWithDatabase, planEvent.Count);
                    Assert.True(File.Exists(tempFile.FilePath));
                    Assert.True(new FileInfo(tempFile.FilePath).Length > 0);
                    AssertSchemaInFile(tempFile.FilePath, assert: true);
                    AssertTableDataInFile(tempFile.FilePath, assert: true);
                }
        }
Exemple #20
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();
                }
            }
        }
Exemple #21
0
        public async Task FunctionSignatureCompletionReturnsCorrectParametersAtEachPosition()
        {
            string sqlText = "EXEC sys.fn_isrolemember 1, 'testing', 2";

            using (SelfCleaningTempFile tempFile = new SelfCleaningTempFile())
                using (TestHelper testHelper = new TestHelper())
                {
                    string ownerUri = tempFile.FilePath;
                    File.WriteAllText(ownerUri, sqlText);

                    // Connect
                    await testHelper.Connect(ownerUri, ConnectionTestUtils.LocalhostConnection);

                    // Wait for intellisense to be ready
                    var readyParams = await testHelper.Driver.WaitForEvent(IntelliSenseReadyNotification.Type, 30000);

                    Assert.NotNull(readyParams);
                    Assert.Equal(ownerUri, readyParams.OwnerUri);

                    // Verify all parameters when the cursor is inside of parameters and at separator boundaries (,)
                    await VerifyFunctionSignatureHelpParameter(testHelper, ownerUri, 25, "fn_isrolemember", 0, "@mode int");
                    await VerifyFunctionSignatureHelpParameter(testHelper, ownerUri, 26, "fn_isrolemember", 0, "@mode int");
                    await VerifyFunctionSignatureHelpParameter(testHelper, ownerUri, 27, "fn_isrolemember", 1, "@login sysname");
                    await VerifyFunctionSignatureHelpParameter(testHelper, ownerUri, 30, "fn_isrolemember", 1, "@login sysname");
                    await VerifyFunctionSignatureHelpParameter(testHelper, ownerUri, 37, "fn_isrolemember", 1, "@login sysname");
                    await VerifyFunctionSignatureHelpParameter(testHelper, ownerUri, 38, "fn_isrolemember", 2, "@tranpubid int");
                    await VerifyFunctionSignatureHelpParameter(testHelper, ownerUri, 39, "fn_isrolemember", 2, "@tranpubid int");

                    await testHelper.Disconnect(ownerUri);
                }
        }
Exemple #22
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);
                }));
            }
        }
        public async Task ScriptTableDoesNotExist()
        {
            using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
                using (SelfCleaningTempFile tempFile = new SelfCleaningTempFile())
                {
                    ScriptingParams requestParams = new ScriptingParams
                    {
                        FilePath         = tempFile.FilePath,
                        ConnectionString = this.Northwind.ConnectionString,
                        ScriptOptions    = new ScriptOptions
                        {
                            TypeOfDataToScript = "SchemaOnly",
                        },
                        ScriptingObjects = new List <ScriptingObject>
                        {
                            new ScriptingObject
                            {
                                Type   = "Table",
                                Schema = "dbo",
                                Name   = "TableDoesNotExist",
                            },
                        }
                    };

                    ScriptingResult result = await testService.Script(requestParams);

                    ScriptingCompleteParams parameters = await testService.Driver.WaitForEvent(ScriptingCompleteEvent.Type, TimeSpan.FromSeconds(15));

                    Assert.True(parameters.HasError);
                    Assert.Equal("An error occurred while scripting the objects.", parameters.ErrorMessage);
                    Assert.Contains("The Table '[dbo].[TableDoesNotExist]' does not exist on the server.", parameters.ErrorDetails);
                }
        }
Exemple #24
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);
            }
        }
        internal static async Task ExecuteQuery(string query)
        {
            // create a temporary "workspace" file
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                // create the client helper which wraps the client driver objects
                using (ClientHelper testHelper = new ClientHelper())
                {
                    // connnection details
                    ConnectParams connectParams = new ConnectParams();
                    connectParams.Connection                    = new ConnectionDetails();
                    connectParams.Connection.ServerName         = "localhost";
                    connectParams.Connection.DatabaseName       = "master";
                    connectParams.Connection.AuthenticationType = "Integrated";

                    // connect to the database
                    await testHelper.Connect(queryTempFile.FilePath, connectParams);

                    // execute the query
                    QueryExecuteCompleteParams queryComplete =
                        await testHelper.RunQuery(queryTempFile.FilePath, query);

                    if (queryComplete.BatchSummaries != null && queryComplete.BatchSummaries.Length > 0)
                    {
                        var batch = queryComplete.BatchSummaries[0];
                        if (batch.ResultSetSummaries != null && batch.ResultSetSummaries.Length > 0)
                        {
                            var resultSet = batch.ResultSetSummaries[0];

                            // retrive the results
                            QueryExecuteSubsetResult querySubset = await testHelper.ExecuteSubset(
                                queryTempFile.FilePath, batch.Id,
                                resultSet.Id, 0, (int)resultSet.RowCount);

                            // print the header
                            foreach (var column in resultSet.ColumnInfo)
                            {
                                Console.Write(column.ColumnName + ", ");
                            }
                            Console.Write(Environment.NewLine);

                            // print the rows
                            foreach (var row in querySubset.ResultSubset.Rows)
                            {
                                for (int i = 0; i < resultSet.ColumnInfo.Length; ++i)
                                {
                                    Console.Write(row.GetValue(i) + ", ");
                                }
                                Console.Write(Environment.NewLine);
                            }
                        }
                    }

                    // close database connection
                    await testHelper.Disconnect(queryTempFile.FilePath);
                }
        }
Exemple #26
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);
                }
        }
        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();
            }
        }
Exemple #28
0
 public async Task BindingCacheWarmOnPremComplexQuery()
 {
     using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
         using (TestHelper testHelper = new TestHelper())
         {
             string query = Scripts.TestDbComplexSelectQueries;
             const TestServerType serverType = TestServerType.OnPrem;
             await VerifyBindingLoadScenario(testHelper, serverType, query, true);
         }
 }
Exemple #29
0
 public async Task BindingCacheWarmAzureComplexQuery()
 {
     using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
         using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
         {
             string query = Scripts.TestDbComplexSelectQueries;
             const TestServerType serverType = TestServerType.Azure;
             await VerifyBindingLoadScenario(testService, serverType, query, true);
         }
 }
Exemple #30
0
        public async Task BindingCacheWarmAzureSimpleQuery()
        {
            TestServerType serverType = TestServerType.Azure;

            using (TestHelper testHelper = new TestHelper())
                using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                {
                    const string query = Scripts.TestDbSimpleSelectQuery;
                    await VerifyBindingLoadScenario(testHelper, serverType, query, true);
                }
        }