コード例 #1
0
        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();
                }
            }
        }
コード例 #2
0
        public static async Task <TestConnectionResult> TestConnectionAsync(string machineName, CancellationTokenSource tokenSource, CancellationToken token, int timeout)
        {
            Task <TestConnectionResult> testConnection = Task <TestConnectionResult> .Factory.StartNew(() =>
            {
                TestConnectionResult result = TestConnection(machineName);
                return(result);
            }, tokenSource.Token);


            if (await Task.WhenAny(testConnection, Task.Delay(timeout, token)) == testConnection)
            {
                await testConnection;
                return(testConnection.Result);
            }
            else
            {
                return(new TestConnectionResult()
                {
                    Exception = new TimeoutException(),
                    Successful = false,
                    ErrorCode = ErrorCodes.TIMEOUT,
                    Message = "Connection timed out while trying to connect to " + machineName
                });
            }
        }
コード例 #3
0
 public static async Task CleanupCredential(
     TestConnectionResult connectionResult,
     CredentialInfo credential)
 {
     var service = new SecurityService();
     await SecurityTestUtils.DeleteCredential(service, connectionResult, credential);
 }
コード例 #4
0
        public async Task TestConnectionAsyncSuccessTest()
        {
            string machineName          = System.Environment.MachineName;
            TestConnectionResult result = await RegistryCompare.TestConnectionAsync(machineName);

            Assert.IsTrue(result.Successful);
        }
コード例 #5
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);
                }));
            }
        }
コード例 #6
0
        public static async Task <AgentNotebookInfo> SetupNotebookJob(
            TestConnectionResult connectionResult,
            AgentNotebookInfo notebook = null)
        {
            var service = new AgentService();

            if (notebook == null)
            {
                notebook = GetTestNotebookInfo("myTestNotebookJob" + Guid.NewGuid().ToString(), "master");
            }
            string tempNotebookPath = CreateTemplateNotebookFile();

            await AgentNotebookHelper.CreateNotebook(
                service,
                connectionResult.ConnectionInfo.OwnerUri,
                notebook,
                tempNotebookPath,
                ManagementUtils.asRunType(0)
                );

            var createdNotebook = GetNotebook(connectionResult, notebook.Name);

            File.Delete(tempNotebookPath);
            return(createdNotebook);
        }
コード例 #7
0
        public void TestConnectionSuccessTest()
        {
            string machineName          = System.Environment.MachineName;
            TestConnectionResult result = RegistryCompare.TestConnection(machineName);

            Assert.IsTrue(result.Successful);
        }
コード例 #8
0
        public void GetDefinitionTimeoutTest()
        {
            // Given a binding queue that will automatically time out
            var languageService = new LanguageService();
            Mock <ConnectedBindingQueue> queueMock = new Mock <ConnectedBindingQueue>();

            languageService.BindingQueue = queueMock.Object;
            ManualResetEvent mre      = new ManualResetEvent(true); // Do not block
            Mock <QueueItem> itemMock = new Mock <QueueItem>();

            itemMock.Setup(i => i.ItemProcessed).Returns(mre);

            DefinitionResult timeoutResult = null;

            queueMock.Setup(q => q.QueueBindingOperation(
                                It.IsAny <string>(),
                                It.IsAny <Func <IBindingContext, CancellationToken, object> >(),
                                It.IsAny <Func <IBindingContext, object> >(),
                                It.IsAny <int?>(),
                                It.IsAny <int?>()))
            .Callback <string, Func <IBindingContext, CancellationToken, object>, Func <IBindingContext, object>, int?, int?>(
                (key, bindOperation, timeoutOperation, t1, t2) =>
            {
                timeoutResult          = (DefinitionResult)timeoutOperation((IBindingContext)null);
                itemMock.Object.Result = timeoutResult;
            })
            .Returns(() => itemMock.Object);

            TextDocumentPosition textDocument = new TextDocumentPosition
            {
                TextDocument = new TextDocumentIdentifier {
                    Uri = OwnerUri
                },
                Position = new Position
                {
                    Line      = 0,
                    Character = 20
                }
            };
            TestConnectionResult connectionResult = TestObjects.InitLiveConnectionInfo();
            ScriptFile           scriptFile       = connectionResult.ScriptFile;
            ConnectionInfo       connInfo         = connectionResult.ConnectionInfo;

            scriptFile.Contents = "select * from dbo.func ()";

            ScriptParseInfo scriptInfo = new ScriptParseInfo {
                IsConnected = true
            };

            languageService.ScriptParseInfoMap.Add(OwnerUri, scriptInfo);

            // When I call the language service
            var result = languageService.GetDefinition(textDocument, scriptFile, connInfo);

            // Then I expect null locations and an error to be reported
            Assert.NotNull(result);
            Assert.True(result.IsErrorResult);
            // Check timeout message
            Assert.Equal(SR.PeekDefinitionTimedoutError, result.Message);
        }
コード例 #9
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();
                }
            }
        }
コード例 #10
0
        public static async Task CleanupJob(
            TestConnectionResult connectionResult,
            AgentJobInfo job)
        {
            var service = new AgentService();

            await DeleteAgentJob(service, connectionResult, job);
        }
コード例 #11
0
 public static async Task CleanupNotebookJob(TestConnectionResult connectionResult, AgentNotebookInfo notebook)
 {
     var service = new AgentService();
     await AgentNotebookHelper.DeleteNotebook(
         service,
         connectionResult.ConnectionInfo.OwnerUri,
         notebook,
         ManagementUtils.asRunType(0)
         );
 }
コード例 #12
0
        public async Task TestConnectionAsyncTimeoutTest()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken       cancellationToken       = cancellationTokenSource.Token;
            int    timeout              = 100000000;
            string machineName          = System.Environment.MachineName;
            TestConnectionResult result = await RegistryCompare.TestConnectionAsync(machineName, cancellationTokenSource, cancellationToken, timeout);

            Assert.IsTrue(result.Successful);
        }
コード例 #13
0
        public static async Task <CredentialInfo> SetupCredential(TestConnectionResult connectionResult)
        {
            var service    = new SecurityService();
            var credential = SecurityTestUtils.GetTestCredentialInfo();
            await SecurityTestUtils.DeleteCredential(service, connectionResult, credential);

            await SecurityTestUtils.CreateCredential(service, connectionResult, credential);

            return(credential);
        }
コード例 #14
0
        public static async Task <AgentJobInfo> SetupJob(TestConnectionResult connectionResult)
        {
            var service = new AgentService();
            var job     = GetTestJobInfo();

            await DeleteAgentJob(service, connectionResult, job);
            await CreateAgentJob(service, connectionResult, job);

            return(job);
        }
コード例 #15
0
        private async Task VerifyScriptAs(string query, ScriptingObject scriptingObject, string scriptCreateDrop, string expectedScript)
        {
            var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query, "ScriptingTests");

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

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

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

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


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

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

                    requestContext.Verify(x => x.SendResult(It.Is <ScriptingResult>(r => VerifyScriptingResult(r, expectedScript))));
                    connectionService.Disconnect(new ServiceLayer.Connection.Contracts.DisconnectParams
                    {
                        OwnerUri = queryTempFile.FilePath
                    });
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                await testDb.CleanupAsync();
            }
        }
コード例 #16
0
        private static void ShowFailedConnectionTestMessage(TestConnectionResult connectionResult)
        {
            string message = string.Format("Test database failed.\r\nReason:{0}", connectionResult.ErroMessage);

            //if (connectionResult.IsMinimalVersion)
            //{
            //    message += "\r\n\r\nThe specified database does include a versions table.\r\n" +
            //               "Change the name of the database and click 'Create New' to create a new database on the server, " +
            //               "or just hit 'Create New' to deploy into this existing database.";
            //}
            MessageBox.Show(message, MESSAGE_HEADER, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
コード例 #17
0
        public static AgentNotebookInfo GetNotebook(TestConnectionResult connectionResult, string name)
        {
            var notebookList = AgentNotebookHelper.GetAgentNotebooks(connectionResult.ConnectionInfo).Result;

            foreach (AgentNotebookInfo n in notebookList)
            {
                if (n.Name == name)
                {
                    return(n);
                }
            }
            return(null);
        }
コード例 #18
0
        public static bool VerifyNotebook(TestConnectionResult connectionResult, AgentNotebookInfo notebook)
        {
            var notebookList = AgentNotebookHelper.GetAgentNotebooks(connectionResult.ConnectionInfo).Result;

            foreach (AgentNotebookInfo n in notebookList)
            {
                if (NotebookObjectEquals(notebook, n))
                {
                    return(true);
                }
            }
            return(false);
        }
コード例 #19
0
        internal static async Task DeleteCredential(
            SecurityService service,
            TestConnectionResult connectionResult,
            CredentialInfo credential)
        {
            var context = new Mock <RequestContext <ResultStatus> >();
            await service.HandleDeleteCredentialRequest(new DeleteCredentialParams
            {
                OwnerUri   = connectionResult.ConnectionInfo.OwnerUri,
                Credential = credential
            }, context.Object);

            context.VerifyAll();
        }
コード例 #20
0
        internal static async Task CreateAgentJob(
            AgentService service,
            TestConnectionResult connectionResult,
            AgentJobInfo job)
        {
            var context = new Mock <RequestContext <CreateAgentJobResult> >();
            await service.HandleCreateAgentJobRequest(new CreateAgentJobParams
            {
                OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                Job      = job
            }, context.Object);

            context.VerifyAll();
        }
コード例 #21
0
        internal static async Task DeleteAgentSchedule(
            AgentService service,
            TestConnectionResult connectionResult,
            AgentScheduleInfo schedule)
        {
            var context = new Mock <RequestContext <ResultStatus> >();
            await service.HandleDeleteAgentScheduleRequest(new DeleteAgentScheduleParams()
            {
                OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                Schedule = schedule
            }, context.Object);

            context.VerifyAll();
        }
コード例 #22
0
        internal static async Task DeleteAgentProxy(
            AgentService service,
            TestConnectionResult connectionResult,
            AgentProxyInfo proxy)
        {
            var context = new Mock <RequestContext <ResultStatus> >();
            await service.HandleDeleteAgentProxyRequest(new DeleteAgentProxyParams()
            {
                OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                Proxy    = proxy
            }, context.Object);

            context.VerifyAll();
        }
コード例 #23
0
        internal static async Task DeleteAgentOperator(
            AgentService service,
            TestConnectionResult connectionResult,
            AgentOperatorInfo operatorInfo)
        {
            var context = new Mock <RequestContext <ResultStatus> >();
            await service.HandleDeleteAgentOperatorRequest(new DeleteAgentOperatorParams
            {
                OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                Operator = operatorInfo
            }, context.Object);

            context.VerifyAll();
        }
コード例 #24
0
        internal static async Task DeleteAgentJobStep(
            AgentService service,
            TestConnectionResult connectionResult,
            AgentJobStepInfo stepInfo)
        {
            var context = new Mock <RequestContext <ResultStatus> >();
            await service.HandleDeleteAgentJobStepRequest(new DeleteAgentJobStepParams
            {
                OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                Step     = stepInfo
            }, context.Object);

            context.VerifyAll();
        }
コード例 #25
0
        internal static async Task UpdateAgentJob(
            AgentService service,
            TestConnectionResult connectionResult,
            AgentJobInfo job)
        {
            job.Description = "Update job description";
            var context = new Mock <RequestContext <UpdateAgentJobResult> >();
            await service.HandleUpdateAgentJobRequest(new UpdateAgentJobParams
            {
                OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                Job      = job
            }, context.Object);

            context.VerifyAll();
        }
コード例 #26
0
        internal static async Task UpdateAgentSchedule(
            AgentService service,
            TestConnectionResult connectionResult,
            string originalScheduleName,
            AgentScheduleInfo schedule)
        {
            var context = new Mock <RequestContext <AgentScheduleResult> >();
            await service.HandleUpdateAgentScheduleRequest(new UpdateAgentScheduleParams()
            {
                OwnerUri             = connectionResult.ConnectionInfo.OwnerUri,
                OriginalScheduleName = originalScheduleName,
                Schedule             = schedule
            }, context.Object);

            context.VerifyAll();
        }
コード例 #27
0
        internal static async Task UpdateAgentProxy(
            AgentService service,
            TestConnectionResult connectionResult,
            string originalProxyName,
            AgentProxyInfo proxy)
        {
            var context = new Mock <RequestContext <AgentProxyResult> >();
            await service.HandleUpdateAgentProxyRequest(new UpdateAgentProxyParams()
            {
                OwnerUri          = connectionResult.ConnectionInfo.OwnerUri,
                OriginalProxyName = originalProxyName,
                Proxy             = proxy
            }, context.Object);

            context.VerifyAll();
        }
コード例 #28
0
 internal static AgentJobStepInfo GetTestJobStepInfo(
     TestConnectionResult connectionResult,
     AgentJobInfo job,
     string stepName = "Test Job Step1")
 {
     return(new AgentJobStepInfo()
     {
         Id = 1,
         JobName = job.Name,
         StepName = stepName,
         SubSystem = "T-SQL",
         Script = "SELECT @@VERSION",
         DatabaseName = connectionResult.ConnectionInfo.ConnectionDetails.DatabaseName,
         DatabaseUserName = connectionResult.ConnectionInfo.ConnectionDetails.UserName,
         Server = connectionResult.ConnectionInfo.ConnectionDetails.ServerName
     });
 }
コード例 #29
0
        private async Task <RestorePlanResponse> VerifyRestore(string backupFileName, bool canRestore, bool execute = false, string targetDatabase = null)
        {
            string filePath = GetBackupFilePath(backupFileName);

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

                RestoreDatabaseHelper service = new RestoreDatabaseHelper();
                var request = new RestoreParams
                {
                    BackupFilePath = filePath,
                    DatabaseName   = targetDatabase,
                    OwnerUri       = queryTempFile.FilePath
                };

                var restoreDataObject = service.CreateRestoreDatabaseTaskDataObject(request);
                var response          = service.CreateRestorePlanResponse(restoreDataObject);

                Assert.NotNull(response);
                Assert.Equal(response.CanRestore, canRestore);
                if (canRestore)
                {
                    Assert.True(response.DbFiles.Any());
                    if (string.IsNullOrEmpty(targetDatabase))
                    {
                        targetDatabase = response.DatabaseName;
                    }
                    Assert.Equal(response.DatabaseName, targetDatabase);

                    if (execute)
                    {
                        await DropDatabase(targetDatabase);

                        Thread.Sleep(2000);
                        request.RelocateDbFiles = response.RelocateFilesNeeded;
                        service.ExecuteRestore(restoreDataObject);
                        Assert.True(restoreDataObject.Server.Databases.Contains(targetDatabase));
                        await DropDatabase(targetDatabase);
                    }
                }

                return(response);
            }
        }
コード例 #30
0
        internal static async Task DeleteAgentJob(
            AgentService service,
            TestConnectionResult connectionResult,
            AgentJobInfo job,
            bool verify = true)
        {
            var context = new Mock <RequestContext <ResultStatus> >();
            await service.HandleDeleteAgentJobRequest(new DeleteAgentJobParams
            {
                OwnerUri = connectionResult.ConnectionInfo.OwnerUri,
                Job      = job
            }, context.Object);

            if (verify)
            {
                context.VerifyAll();
            }
        }
コード例 #31
0
 protected TestConnectionResult(TestConnectionResult connectionResult)
 {
     this.Successful = connectionResult.Successful;
     this.ErroMessage = connectionResult.ErroMessage;
 }