Beispiel #1
0
        /// <summary>
        /// Verifica che i metadati del task associato all'identificativo specificato siano esistenti ed eventualmente
        /// li copia in output e restituisce true. In caso contrario restituisce false ed imposta i metadati in output
        /// al valore null e un errore esplicativo.
        /// </summary>
        /// <param name="taskRequestId">l'identificativo univoco della richiesta di elaborazione</param>
        /// <param name="tm">la copia dei metadati relativi al task di cui è stata richiesta l'elaborazione</param>
        /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param>
        /// <returns>true se non si verificano errori durante il recupero dei metadati, altrimenti false</returns>
        /// <remarks>
        /// Se i metadati richiesti vengono trovati, l'oggetto dedicato all'eventuale errore è impostato al valore null,
        /// altrimenti al suo interno vengono impostati il codice d'errore e un identificativo univoco sul server, oltre
        /// ad effettuare il logging dell'errore.
        /// </remarks>
        public bool TryGetUserTask(string taskRequestId, out TaskMetadata tm, out ServiceFault error)
        {
            string taskProcId;

            if (!TryGetProcessingId(taskRequestId, out taskProcId))
            {
                string errorDetails = string.Format("TryGetUserTask: unable to find processing id for request id = {0}.", taskRequestId);
                HandleError(errorDetails, ServiceFaultCode.TaskResultsNotFound, out error);

                tm = null;
                return(false);
            }

            if (!m_TaskScheduler.TryGetUserTask(taskProcId, out tm))
            {
                string errorDetails = "TryGetUserTask: unable to find task for " +
                                      string.Format("request id = {0}, processing id = {1}.", taskRequestId, taskProcId);
                HandleError(errorDetails, ServiceFaultCode.TaskResultsNotFound, out error);

                tm = null;
                return(false);
            }

            error = null;
            return(true);
        }
Beispiel #2
0
        public async Task HandleSchemaCompareIncludeExcludeNodeRequest(SchemaCompareNodeParams parameters, RequestContext <ResultStatus> requestContext)
        {
            SchemaCompareIncludeExcludeNodeOperation operation = null;

            try
            {
                SchemaComparisonResult compareResult = schemaCompareResults.Value[parameters.OperationId];
                operation = new SchemaCompareIncludeExcludeNodeOperation(parameters, compareResult);
                SqlTask      sqlTask  = null;
                TaskMetadata metadata = new TaskMetadata();
                metadata.TaskOperation = operation;
                metadata.Name          = parameters.IncludeRequest ? SR.IncludeNodeTaskName : SR.ExcludeNodeTaskName;

                sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);

                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = true,
                    ErrorMessage = operation.ErrorMessage
                });
            }
            catch (Exception e)
            {
                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = false,
                    ErrorMessage = operation == null ? e.Message : operation.ErrorMessage,
                });
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////
        #region Public API

        /// <summary>
        /// Sets the task's priority, duration and execution token. Afterwards you can start the task.
        /// </summary>
        /// <param name="task">Task to be executed. The task object shouldn't be active(running) or previously registered. In case the task object was previously registered, you should wait for the task to finish befure queueing it again. Task has to be non null.</param>
        /// <param name="priority">Priority of the task, range 1-20 with 1 having biggest precedence and 20 the lowest.</param>
        /// <param name="durationInMilliseconds">Maximum duration of the task, task will be stopped after this durations elapses. Duration has to be positive. </param>
        /// <param name="executionToken">Execution token used for the task. Execution token shouldn't be mapped to any active, or previously registered non-completed task. Has to be non-null.</param>
        /// <returns>True if the task is registered correctly, false if any of the conditions are not fulfilled.</returns>
        public bool Register(Task task, int priority, int durationInMilliseconds, ExecutionToken executionToken)
        {
            if (priority < 1 || priority > 20 ||
                durationInMilliseconds <= 0 ||
                task == null ||
                executionToken == null)
            {
                return(false);
            }

            lock (resourcesLock)
            {
                if (taskToToken.ContainsKey(task) || tokenToTask.ContainsKey(executionToken))
                {
                    return(false);
                }
                taskToToken.Add(task, executionToken);
                tokenToTask.Add(executionToken, task);

                TaskMetadata taskMetadata = new TaskMetadata(duration: durationInMilliseconds, priority: priority, taskState: TaskMetadata.TaskState.Paused);
                taskToMetadata.Add(task, taskMetadata);

                taskHoldingResources.Add(task, new List <Object>());
                executionToken.SetRegisteredTrue();

                return(true);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Handles request to generate deploy script
        /// </summary>
        /// <returns></returns>
        public async Task HandleGenerateDeployScriptRequest(GenerateDeployScriptParams parameters, RequestContext <DacFxResult> requestContext)
        {
            try
            {
                ConnectionInfo connInfo;
                ConnectionServiceInstance.TryFindConnection(
                    parameters.OwnerUri,
                    out connInfo);
                if (connInfo != null)
                {
                    GenerateDeployScriptOperation operation = new GenerateDeployScriptOperation(parameters, connInfo);
                    SqlTask      sqlTask  = null;
                    TaskMetadata metadata = TaskMetadata.Create(parameters, SR.GenerateScriptTaskName, operation, ConnectionServiceInstance);

                    // want to show filepath in task history instead of server and database
                    metadata.ServerName   = parameters.ScriptFilePath;
                    metadata.DatabaseName = string.Empty;

                    sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);

                    await requestContext.SendResult(new DacFxResult()
                    {
                        OperationId  = operation.OperationId,
                        Success      = true,
                        ErrorMessage = string.Empty
                    });
                }
            }
            catch (Exception e)
            {
                await requestContext.SendError(e);
            }
        }
Beispiel #5
0
 private void AssertTask(TaskMetadata task, object expectedId, DateTime expectedAddedTime, int expecedIndex, Type expectedType)
 {
     Assert.Equal(expectedType.FullName, task.Type);
     Assert.Equal(expectedAddedTime, task.AddedTime);
     Assert.Equal(expecedIndex, task.IndexId);
     Assert.Equal(expectedId, task.Id);
 }
Beispiel #6
0
        /// <summary>
        /// Handles request for schema compare generate deploy script
        /// </summary>
        /// <returns></returns>
        public async Task HandleSchemaCompareGenerateScriptRequest(SchemaCompareGenerateScriptParams parameters, RequestContext <ResultStatus> requestContext)
        {
            SchemaCompareGenerateScriptOperation operation = null;

            try
            {
                SchemaComparisonResult compareResult = schemaCompareResults.Value[parameters.OperationId];
                operation = new SchemaCompareGenerateScriptOperation(parameters, compareResult);
                SqlTask      sqlTask  = null;
                TaskMetadata metadata = new TaskMetadata();
                metadata.TaskOperation     = operation;
                metadata.TaskExecutionMode = parameters.TaskExecutionMode;
                metadata.ServerName        = parameters.TargetServerName;
                metadata.DatabaseName      = parameters.TargetDatabaseName;
                metadata.Name = SR.GenerateScriptTaskName;

                sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);

                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = true,
                    ErrorMessage = operation.ErrorMessage
                });
            }
            catch (Exception e)
            {
                Logger.Write(TraceEventType.Error, "Failed to generate schema compare script. Error: " + e);
                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = false,
                    ErrorMessage = operation == null ? e.Message : operation.ErrorMessage,
                });
            }
        }
        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 #8
0
        /// <summary>
        /// Handles request to generate deploy script
        /// </summary>
        /// <returns></returns>
        public async Task HandleGenerateDeployScriptRequest(GenerateDeployScriptParams parameters, RequestContext <DacFxResult> requestContext)
        {
            try
            {
                ConnectionInfo connInfo;
                ConnectionServiceInstance.TryFindConnection(
                    parameters.OwnerUri,
                    out connInfo);
                if (connInfo != null)
                {
                    GenerateDeployScriptOperation operation = new GenerateDeployScriptOperation(parameters, connInfo);
                    SqlTask      sqlTask  = null;
                    TaskMetadata metadata = new TaskMetadata();
                    metadata.TaskOperation     = operation;
                    metadata.TaskExecutionMode = parameters.TaskExecutionMode;
                    metadata.ServerName        = connInfo.ConnectionDetails.ServerName;
                    metadata.DatabaseName      = parameters.DatabaseName;
                    metadata.Name = SR.GenerateScriptTaskName;

                    sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);

                    await requestContext.SendResult(new DacFxResult()
                    {
                        OperationId  = operation.OperationId,
                        Success      = true,
                        ErrorMessage = string.Empty
                    });
                }
            }
            catch (Exception e)
            {
                await requestContext.SendError(e);
            }
        }
Beispiel #9
0
        private void ExecuteOperation(DacFxOperation operation, DacFxParams parameters, string taskName, RequestContext <DacFxResult> requestContext)
        {
            Task.Run(async() =>
            {
                try
                {
                    TaskMetadata metadata = TaskMetadata.Create(parameters, taskName, operation, ConnectionServiceInstance);

                    // put appropriate database name since connection passed was to master
                    metadata.DatabaseName = parameters.DatabaseName;
                    SqlTask sqlTask       = SqlTaskManagerInstance.CreateTask <SqlTask>(metadata);

                    await sqlTask.RunAsync();
                    await requestContext.SendResult(new DacFxResult()
                    {
                        OperationId  = operation.OperationId,
                        Success      = sqlTask.TaskStatus == SqlTaskStatus.Succeeded,
                        ErrorMessage = string.Empty
                    });
                }
                catch (Exception e)
                {
                    await requestContext.SendResult(new DacFxResult()
                    {
                        OperationId  = operation.OperationId,
                        Success      = false,
                        ErrorMessage = e.Message
                    });
                }
            });
        }
Beispiel #10
0
        /// <summary>
        /// Prova a mettere il task specificato in coda per l'elaborazione associandolo all'identificativo specificato
        /// e restituisce true se l'inserimento viene completate con successo. In caso contrario, restituisce false ed
        /// imposta l'errore esplicativo.
        /// </summary>
        /// <param name="tm">i metadati relativi al task di cui è stata richiesta l'elaborazione</param>
        /// <param name="taskRequestId">l'identificativo univoco della richiesta di elaborazione</param>
        /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param>
        /// <returns>true se non si verificano errori durante l'accodamento del task, altrimenti false</returns>
        /// <remarks>
        /// Se il task viene accodato con successo, l'oggetto dedicato all'eventuale errore è impostato al valore null,
        /// altrimenti al suo interno vengono impostati il codice d'errore e un identificativo univoco sul server,
        /// oltre ad effettuare il logging dell'errore.
        /// </remarks>
        public bool TryQueueTask(TaskMetadata tm, string taskRequestId, out ServiceFault error)
        {
            bool result;

            string taskProcId;

            if (m_TaskScheduler.InsertUserTask(tm, out taskProcId))
            {
                if (TryInsertIdPair(taskRequestId, taskProcId))
                {
                    WriteToLog("TryQueueTask: task scheduled with request id = {0}, processing id = {1}.",
                               taskRequestId, taskProcId);
                    error  = null;
                    result = true;
                }
                else
                {
                    string errorDetails = "TryQueueTask: unable to insert task identifiers within table: " +
                                          string.Format("request id = {0}, processing id = {1}.", taskRequestId, taskProcId);
                    HandleError(errorDetails, ServiceFaultCode.InternalError, out error);
                    result = false;
                }
            }
            else
            {
                HandleError("TryQueueTask: unable to queue a new task.", ServiceFaultCode.InternalError, out error);
                result = false;
            }

            return(result);
        }
Beispiel #11
0
        public async Task VerifyCombinationRunAndCancelBackupTasks()
        {
            using (SqlTaskManager manager = new SqlTaskManager())
            {
                IBackupOperation backupOperation = new BackupOperationStub();
                TaskMetadata     taskMetaData    = this.CreateTaskMetaData(backupOperation);
                SqlTask          sqlTask         = manager.CreateTask <SqlTask>(taskMetaData);

                var          mockBackupOperation = new Mock <IBackupOperation>();
                TaskMetadata taskMetaData2       = this.CreateTaskMetaData(mockBackupOperation.Object);
                SqlTask      sqlTask2            = manager.CreateTask <SqlTask>(taskMetaData);

                Assert.NotNull(sqlTask);
                Assert.NotNull(sqlTask2);

                Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
                {
                    Assert.Equal(SqlTaskStatus.Canceled, sqlTask.TaskStatus);
                    Assert.Equal(sqlTask.IsCancelRequested, true);
                    ((BackupOperationStub)backupOperation).BackupSemaphore.Release();
                    manager.Reset();
                });

                Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
                {
                    Assert.Equal(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
                });

                manager.CancelTask(sqlTask.TaskId);
                await Task.WhenAll(taskToVerify, taskToVerify2);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Handles request for schema compare publish changes script
        /// </summary>
        /// <returns></returns>
        public async Task HandleSchemaComparePublishChangesRequest(SchemaComparePublishChangesParams parameters, RequestContext <ResultStatus> requestContext)
        {
            SchemaComparePublishChangesOperation operation = null;

            try
            {
                SchemaComparisonResult compareResult = schemaCompareResults.Value[parameters.OperationId];
                operation = new SchemaComparePublishChangesOperation(parameters, compareResult);
                SqlTask      sqlTask  = null;
                TaskMetadata metadata = new TaskMetadata();
                metadata.TaskOperation = operation;
                metadata.ServerName    = parameters.TargetServerName;
                metadata.DatabaseName  = parameters.TargetDatabaseName;
                metadata.Name          = SR.PublishChangesTaskName;

                sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);

                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = true,
                    ErrorMessage = operation.ErrorMessage
                });
            }
            catch (Exception e)
            {
                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = false,
                    ErrorMessage = operation == null ? e.Message : operation.ErrorMessage,
                });
            }
        }
Beispiel #13
0
        public async Task VerifyRunningMultipleBackupTasks()
        {
            using (SqlTaskManager manager = new SqlTaskManager())
            {
                var          mockBackupOperation = new Mock <IBackupOperation>();
                TaskMetadata taskMetaData        = this.CreateTaskMetaData(mockBackupOperation.Object);

                SqlTask sqlTask  = manager.CreateTask <SqlTask>(taskMetaData);
                SqlTask sqlTask2 = manager.CreateTask <SqlTask>(taskMetaData);
                Assert.NotNull(sqlTask);
                Assert.NotNull(sqlTask2);

                Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
                {
                    Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
                });

                Task taskToVerify2 = sqlTask2.RunAsync().ContinueWith(Task =>
                {
                    Assert.Equal(SqlTaskStatus.Succeeded, sqlTask2.TaskStatus);
                });

                await Task.WhenAll(taskToVerify, taskToVerify2);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Handles request for schema compare generate deploy script
        /// </summary>
        /// <returns></returns>
        public async Task HandleSchemaCompareGenerateScriptRequest(SchemaCompareGenerateScriptParams parameters, RequestContext <ResultStatus> requestContext)
        {
            SchemaCompareGenerateScriptOperation operation = null;

            try
            {
                SchemaComparisonResult compareResult = schemaCompareResults.Value[parameters.OperationId];
                operation = new SchemaCompareGenerateScriptOperation(parameters, compareResult);
                SqlTask      sqlTask  = null;
                TaskMetadata metadata = new TaskMetadata();
                metadata.TaskOperation = operation;
                // want to show filepath in task history instead of server and database
                metadata.ServerName   = parameters.ScriptFilePath;
                metadata.DatabaseName = string.Empty;
                metadata.Name         = SR.GenerateScriptTaskName;

                sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);

                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = true,
                    ErrorMessage = operation.ErrorMessage
                });
            }
            catch (Exception e)
            {
                await requestContext.SendResult(new ResultStatus()
                {
                    Success      = false,
                    ErrorMessage = operation == null ? e.Message : operation.ErrorMessage,
                });
            }
        }
Beispiel #15
0
        public void ShouldWork(string requestedStorage)
        {
            using (var storage = NewTransactionalStorage(requestedStorage))
            {
                storage.Batch(accessor => Assert.Equal(0, accessor.Tasks.GetPendingTasksForDebug().Count()));

                var date1 = DateTime.Now;
                var date2 = date1.AddMinutes(1);

                storage.Batch(accessor => accessor.Tasks.AddTask(new RemoveFromIndexTask()
                {
                    Index = 1
                }, date1));

                storage.Batch(accessor =>
                {
                    var tasks = accessor.Tasks
                                .GetPendingTasksForDebug()
                                .ToList();

                    Assert.Equal(1, tasks.Count);

                    var task = tasks[0];

                    AssertTask(task, task.Id is Etag ? (object)Etag.Parse("08000000-0000-0000-0000-000000000001") : 1, date1, 1, typeof(RemoveFromIndexTask));
                });

                storage.Batch(accessor => accessor.Tasks.AddTask(new TouchMissingReferenceDocumentTask
                {
                    Index = 2
                }, date2));

                storage.Batch(accessor =>
                {
                    var tasks = accessor.Tasks
                                .GetPendingTasksForDebug()
                                .ToList();

                    Assert.Equal(2, tasks.Count);

                    TaskMetadata t1 = null;
                    TaskMetadata t2 = null;
                    if (tasks[0].IndexId == 1)
                    {
                        t1 = tasks[0];
                        t2 = tasks[1];
                    }
                    else
                    {
                        t1 = tasks[1];
                        t2 = tasks[0];
                    }

                    AssertTask(t1, t1.Id is Etag ? (object)Etag.Parse("08000000-0000-0000-0000-000000000001") : 1, date1, 1, typeof(RemoveFromIndexTask));
                    AssertTask(t2, t2.Id is Etag ? (object)Etag.Parse("08000000-0000-0000-0000-000000000002") : 2, date2, 2, typeof(TouchMissingReferenceDocumentTask));
                });
            }
        }
        /// <summary>
        /// Handles a restore request
        /// </summary>
        internal async Task HandleRestoreRequest(
            RestoreParams restoreParams,
            RequestContext <RestoreResponse> requestContext)
        {
            RestoreResponse response = new RestoreResponse();

            try
            {
                ConnectionInfo connInfo;
                bool           supported = IsBackupRestoreOperationSupported(restoreParams, out connInfo);

                if (supported && connInfo != null)
                {
                    try
                    {
                        RestoreDatabaseTaskDataObject restoreDataObject = this.restoreDatabaseService.CreateRestoreDatabaseTaskDataObject(restoreParams);

                        if (restoreDataObject != null)
                        {
                            // create task metadata
                            TaskMetadata metadata = new TaskMetadata();
                            metadata.ServerName   = connInfo.ConnectionDetails.ServerName;
                            metadata.DatabaseName = connInfo.ConnectionDetails.DatabaseName;
                            metadata.Name         = SR.RestoreTaskName;
                            metadata.IsCancelable = true;
                            metadata.Data         = restoreDataObject;

                            // create restore task and perform
                            SqlTask sqlTask = SqlTaskManager.Instance.CreateAndRun(metadata, this.restoreDatabaseService.RestoreTaskAsync, restoreDatabaseService.CancelTaskAsync);
                            response.TaskId = sqlTask.TaskId.ToString();
                        }
                        else
                        {
                            response.ErrorMessage = SR.RestorePlanFailed;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.ErrorMessage = ex.Message;
                    }
                }
                else
                {
                    response.ErrorMessage = SR.RestoreNotSupported;
                }

                await requestContext.SendResult(response);
            }
            catch (Exception ex)
            {
                response.Result       = false;
                response.ErrorMessage = ex.Message;
                await requestContext.SendResult(response);
            }
        }
Beispiel #17
0
        private TaskMetadata CreateTaskMetaData(IBackupOperation data)
        {
            TaskMetadata taskMetaData = new TaskMetadata
            {
                ServerName    = "server name",
                DatabaseName  = "database name",
                Name          = "backup database",
                TaskOperation = data
            };

            return(taskMetaData);
        }
        public void ExecuteTest()
        {
            var subject      = new GenerateScriptOperation(SampleParams);
            var taskMetadata = new TaskMetadata();

            using (var sqlTask = new SqlTask(taskMetadata, DummyOpFunction, DummyOpFunction))
            {
                subject.SqlTask      = sqlTask;
                sqlTask.ScriptAdded += ValidateScriptAdded;
                subject.Execute(TaskExecutionMode.Script);
            }
        }
        /// <summary>
        /// Handles a restore request
        /// </summary>
        internal async Task HandleRestoreRequest(
            RestoreParams restoreParams,
            RequestContext <RestoreResponse> requestContext)
        {
            RestoreResponse response = new RestoreResponse();

            try
            {
                ConnectionInfo connInfo;
                bool           supported = IsBackupRestoreOperationSupported(restoreParams.OwnerUri, out connInfo);

                if (supported && connInfo != null)
                {
                    try
                    {
                        RestoreDatabaseTaskDataObject restoreDataObject = this.restoreDatabaseService.CreateRestoreDatabaseTaskDataObject(restoreParams, connInfo);

                        if (restoreDataObject != null)
                        {
                            restoreDataObject.LockedDatabaseManager = ConnectionServiceInstance.LockedDatabaseManager;
                            // create task metadata
                            TaskMetadata metadata = TaskMetadata.Create(restoreParams, SR.RestoreTaskName, restoreDataObject, ConnectionServiceInstance);
                            metadata.DatabaseName = restoreParams.TargetDatabaseName;

                            // create restore task and perform
                            SqlTask sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);
                            response.TaskId = sqlTask.TaskId.ToString();
                        }
                        else
                        {
                            response.ErrorMessage = SR.RestorePlanFailed;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.ErrorMessage = ex.Message;
                    }
                }
                else
                {
                    response.ErrorMessage = SR.RestoreNotSupported;
                }

                await requestContext.SendResult(response);
            }
            catch (Exception ex)
            {
                response.Result       = false;
                response.ErrorMessage = ex.Message;
                await requestContext.SendResult(response);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Permette il trasferimento dei dati relativi al task da elaborare ed imposta una stringa contenente
        /// l'identificativo univoco associato alla richiesta di elaborazione, necessario per ottenere in seguito
        /// i risultati dell'elaborazione.
        /// </summary>
        /// <param name="data">i dati relativi al task di cui si richiede l'elaborazione</param>
        /// <param name="id">l'identificativo associato alla richiesta di elaborazione</param>
        public void SubmitData(TaskData data, out string id)
        {
            m_Container.WriteToLog("SubmitData: receiving data, name = {0}.", data.Name);

            ServiceFault fault = null;

            // Genera un ID univoco da associare alla richiesta.
            string taskRequestId;

            if (!m_Container.TryGetRandomId(out taskRequestId, out fault))
            {
                throw new FaultException <ServiceFault>(fault);
            }

            m_Container.WriteToLog("SubmitData: task request id = {0}.", taskRequestId);

            string tdFilePath = m_Container.GetTaskDataFilePath();   // task data file path

            // Salva i dati ricevuti sul task da elaborare.
            if (!m_Container.TrySaveDataToFile(data.Contents, tdFilePath, out fault))
            {
                throw new FaultException <ServiceFault>(fault);
            }

            m_Container.WriteToLog("SubmitData: task request id = {0}, file saved to {1}.", taskRequestId, tdFilePath);

            // Verifica che la risorsa sia disponibile.
            string className, classVersion;

            if (!m_Container.TrySearchResource(tdFilePath, out className, out classVersion, out fault))
            {
                throw new FaultException <ServiceFault>(fault);
            }

            string trFilePath = m_Container.GetTaskResultsFilePath(); // task results file path

            // Prepara il task da elaborare.
            TaskMetadata tm = new TaskMetadata(className, classVersion, tdFilePath, trFilePath);

            tm.UpdateOnReady(DateTime.Now);

            // Inserisce il task in coda allo scheduler.
            if (!m_Container.TryQueueTask(tm, taskRequestId, out fault))
            {
                throw new FaultException <ServiceFault>(fault);
            }

            m_Container.WriteToLog("SubmitData: task scheduled with request id = {0}, target file = {1}.",
                                   taskRequestId, trFilePath);

            id = taskRequestId;
        }
Beispiel #21
0
        private TaskMetadata CreateTaskMetaData(object data)
        {
            TaskMetadata taskMetaData = new TaskMetadata
            {
                ServerName   = "server name",
                DatabaseName = "database name",
                Name         = "backup database",
                IsCancelable = true,
                Data         = data
            };

            return(taskMetaData);
        }
Beispiel #22
0
        public Models.Task ChangeTaskModel(TaskMetadata task)
        {
            Models.Task newTask = new Models.Task();

            newTask.TaskName       = task.TaskName;
            newTask.UserID         = task.UserID;
            newTask.User           = task.User;
            newTask.PrijectName    = task.PrijectName;
            newTask.SupervisorName = task.SupervisorName;
            newTask.StartDate      = task.StartDate;
            newTask.EndTime        = task.EndTime;

            return(newTask);
        }
Beispiel #23
0
        public ActionResult Create([Bind(Exclude = "User")] TaskMetadata task)
        {
            var  identity = User.Identity.Name;
            User user     = userService.FindByEmail(identity);

            task.User   = user;
            task.UserID = user.UserID;


            taskService.Add(task);


            return(RedirectToAction("Index"));
        }
Beispiel #24
0
        /// <summary>
        /// Restituisce il tempo impiegato per elaborare il task descritto dai metadati specificati.
        /// </summary>
        /// <param name="tm">i metadati relativi al task</param>
        /// <returns>il tempo impiegato per elaborare il task</returns>
        /// <remarks>
        /// Se l'oggetto contenente i metadati è null oppure se in essi non sono stati impostati l'istante
        /// di completamento dell'elaborazione e/o l'istante di inizio dell'elaborazione, viene restituito
        /// il valore TimeSpan.Zero.
        /// </remarks>
        public TimeSpan GetProcessingTime(TaskMetadata tm)
        {
            if (tm != null && tm.CompletionTime.HasValue && tm.StartingTime.HasValue)
            {
                DateTime t1 = tm.StartingTime.Value;
                DateTime t2 = tm.CompletionTime.Value;

                if (t2 > t1)
                {
                    return(t2.Subtract(t1));
                }
            }
            return(TimeSpan.Zero);
        }
        /// <summary>
        /// This gets all tasks found in configuration blocks and dynamically creates real task definitions from them
        /// and registers them with the task manager with the trigger name of the package they were found in
        /// </summary>
        /// <param name="context"></param>
        public override void Execute(TaskExecutionContext context)
        {
            using (DisposableTimer.TraceDuration <ConfigurationTaskBuilder>("Building configuration tasks", "End building configuration tasks"))
            {
                //get all tasks in configuration
                foreach (var t in ApplicationContext.Settings.Tasks)
                {
                    //create a new config task context with the configuration task's parameters
                    var configTaskContext = new ConfigurationTaskContext(ApplicationContext, t.Parameters, t);

                    //create a new instance of the configuration task
                    var task = (ConfigurationTask)Activator.CreateInstance(t.TaskType, new[] { configTaskContext });
                    var meta = new TaskMetadata(null)
                    {
                        ComponentType   = task.GetType(),
                        ContinueOnError = true,
                        Id = Guid.NewGuid(),
                    };
                    //now we need to check the trigger name, if it is either post-package-install or pre-package-uninstall
                    //then we need to check if this task has been registered with a package. If so, then we change the trigger
                    //to be PackageFolderName-post-package-install so that the task only executes for the current packages installation
                    //changes. If its neither of these names, then we just use the normal trigger
                    if ((t.Trigger.InvariantEquals(TaskTriggers.PostPackageInstall) || t.Trigger.InvariantEquals(TaskTriggers.PrePackageUninstall)) &&
                        !t.PackageFolder.IsNullOrWhiteSpace())
                    {
                        var parts          = t.PackageFolder.Split(Path.DirectorySeparatorChar);
                        var packageName    = parts[parts.Length - 1];
                        var newTriggername = packageName + "-" + t.Trigger;
                        var t1             = t;
                        LogHelper.TraceIfEnabled <ConfigurationTaskBuilder>("Found {0} config task of type {1} for package, registering it as {2}", () => t1.Trigger, () => t1.TaskType.Name, () => newTriggername);
                        //ok, we've got a task declared on a package for post package install or pre package uninstall, so need to update the trigger accordingly
                        meta.TriggerName = newTriggername;
                    }
                    else
                    {
                        //nope, this is a task declared in config that is not a package... unexpected but i guess it could happen
                        //so we just use the normal trigger that it was declared with.
                        var t1 = t;
                        LogHelper.TraceIfEnabled <ConfigurationTaskBuilder>("Found {0} config task of type {1} outside of a package", () => t1.Trigger, () => t1.TaskType.Name);
                        meta.TriggerName = t.Trigger;
                    }

                    //create a new task definition
                    var taskDefinition = new Lazy <AbstractTask, TaskMetadata>(() => task, meta);
                    //add the definition to the manager
                    ApplicationContext.FrameworkContext.TaskManager.AddTask(taskDefinition);
                }
            }
        }
Beispiel #26
0
        protected override TaskMetadata Execute(TaskSettings taskSettings)
        {
            TaskMetadata metadata = CreateMetadata();

            if (taskSettings.CaptureSettings.CaptureTransparent && !taskSettings.CaptureSettings.CaptureClientArea)
            {
                metadata.Image = TaskHelpers.GetScreenshot(taskSettings).CaptureActiveWindowTransparent();
            }
            else
            {
                metadata.Image = TaskHelpers.GetScreenshot(taskSettings).CaptureActiveWindow();
            }

            return(metadata);
        }
        private async Task ExecuteOperation(DacFxOperation operation, DacFxParams parameters, string taskName, RequestContext <DacFxResult> requestContext)
        {
            SqlTask      sqlTask  = null;
            TaskMetadata metadata = TaskMetadata.Create(parameters, taskName, operation, ConnectionServiceInstance);

            // put appropriate database name since connection passed was to master
            metadata.DatabaseName = parameters.DatabaseName;

            sqlTask = SqlTaskManagerInstance.CreateAndRun <SqlTask>(metadata);

            await requestContext.SendResult(new DacFxResult()
            {
                OperationId  = operation.OperationId,
                Success      = true,
                ErrorMessage = string.Empty
            });
        }
Beispiel #28
0
        public async Task VerifyRunningBackupTask()
        {
            using (SqlTaskManager manager = new SqlTaskManager())
            {
                DisasterRecoveryService service  = new DisasterRecoveryService();
                var          mockBackupOperation = new Mock <IBackupOperation>();
                TaskMetadata taskMetaData        = this.CreateTaskMetaData(mockBackupOperation.Object);
                SqlTask      sqlTask             = manager.CreateTask <SqlTask>(taskMetaData);
                Assert.NotNull(sqlTask);
                Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
                {
                    Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
                });

                await taskToVerify;
            }
        }
Beispiel #29
0
        public async Task VerifyScriptBackupTask()
        {
            using (SqlTaskManager manager = new SqlTaskManager())
            {
                var          mockBackupOperation = new Mock <IBackupOperation>();
                TaskMetadata taskMetaData        = this.CreateTaskMetaData(mockBackupOperation.Object);
                taskMetaData.TaskExecutionMode = TaskExecutionMode.Script;

                SqlTask sqlTask = manager.CreateTask <SqlTask>(taskMetaData);
                Assert.NotNull(sqlTask);
                Task taskToVerify = sqlTask.RunAsync().ContinueWith(Task =>
                {
                    Assert.Equal(SqlTaskStatus.Succeeded, sqlTask.TaskStatus);
                });

                await taskToVerify;
            }
        }
Beispiel #30
0
        public System.Collections.Generic.IEnumerable <TaskMetadata> GetPendingTasksForDebug()
        {
            if (!HasTasks)
            {
                yield break;
            }

            using (var taskIterator = tableStorage.Tasks.Iterate(Snapshot, writeBatch.Value))
            {
                if (!taskIterator.Seek(Slice.BeforeAllKeys))
                {
                    yield break;
                }

                do
                {
                    ushort version;
                    var    taskData = LoadJson(tableStorage.Tasks, taskIterator.CurrentKey, writeBatch.Value, out version);
                    if (taskData == null)
                    {
                        throw new InvalidOperationException("Retrieved a pending task object, but was unable to parse it. This is probably a data corruption or a bug.");
                    }

                    TaskMetadata pendingTasksForDebug;
                    try
                    {
                        pendingTasksForDebug = new TaskMetadata
                        {
                            Id        = Etag.Parse(taskData.Value <byte[]>("id")),
                            AddedTime = DateTime.Parse(taskData.Value <string>("time")),
                            Type      = taskData.Value <string>("type"),
                            IndexId   = taskData.Value <int>("index")
                        };
                    }
                    catch (Exception e)
                    {
                        throw new InvalidOperationException("The pending task record was parsed, but contained invalid values. See more details at inner exception.", e);
                    }

                    yield return(pendingTasksForDebug);
                } while (taskIterator.MoveNext());
            }
        }