Beispiel #1
0
        private async Task EvaluateAsync()
        {
            try {
                await TaskUtilities.SwitchToBackgroundThread();

                var debugSession = await VsAppShell.Current.ExportProvider.GetExportedValue <IDebugSessionProvider>().GetDebugSessionAsync(_rSession);

                const DebugEvaluationResultFields fields = DebugEvaluationResultFields.Classes
                                                           | DebugEvaluationResultFields.Expression
                                                           | DebugEvaluationResultFields.TypeName
                                                           | (DebugEvaluationResultFields.Repr | DebugEvaluationResultFields.ReprStr)
                                                           | DebugEvaluationResultFields.Dim
                                                           | DebugEvaluationResultFields.Length;

                var result = await debugSession.EvaluateAsync(_evaluation.Expression, fields);

                var wrapper = new EvaluationWrapper(result);

                VsAppShell.Current.DispatchOnUIThread(() => SetEvaluation(wrapper));
            } catch (Exception ex) {
                VsAppShell.Current.DispatchOnUIThread(() => SetError(ex.Message));
            }
        }
Beispiel #2
0
        /// <inheritdoc />
        public byte[] ReadAllBytes(string fileName, string[] path)
        {
            #region validation

            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            #endregion

            CloudFileDirectory cloudFileDirectory = CloudFileShare.GetDirectoryReference(path: path);

            CloudFile cloudFile = cloudFileDirectory.GetFileReference(fileName);

            TaskUtilities.ExecuteSync(cloudFile.FetchAttributesAsync());

            var cloudFileBytes = new byte[cloudFile.Properties.Length];

            TaskUtilities.ExecuteSync(cloudFile.DownloadToByteArrayAsync(cloudFileBytes, 0));

            return(cloudFileBytes);
        }
        /// <inheritdoc />
        protected override async Task CompleteAsync(CancellationToken cancellation)
        {
            if (this.inParallel)
            {
                cancellation.ThrowIfCancellationRequested();
                var completions = new List <Task>();
                foreach (var cancelable in this.cancelables)
                {
                    cancelable.Complete();
                    completions.Add(cancelable.Completion);
                }

                await TaskUtilities.WhenAll(cancellation, completions).DontMarshallContext();
            }
            else
            {
                foreach (var cancelable in this.cancelables)
                {
                    cancellation.ThrowIfCancellationRequested();
                    await cancelable.CompleteAndAwaitAsync().DontMarshallContext();
                }
            }
        }
Beispiel #4
0
        private async Task StartHostAsyncBackground(RHostStartupInfo startupInfo, IRSessionCallback callback, IBinaryAsyncLockToken lockToken, int timeout, CancellationToken cancellationToken)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            _callback    = callback;
            _startupInfo = startupInfo;
            RHost host;

            try {
                var connectionInfo = new BrokerConnectionInfo(startupInfo.Name, this, startupInfo.RHostCommandLineArguments, timeout);
                host = await BrokerClient.ConnectAsync(connectionInfo, cancellationToken);
            } catch (OperationCanceledException ex) {
                _initializationTcs.TrySetCanceled(ex);
                lockToken.Reset();
                throw;
            } catch (Exception ex) {
                _initializationTcs.TrySetException(ex);
                lockToken.Reset();
                throw;
            }

            await StartHostAsyncBackground(host, lockToken, cancellationToken);
        }
Beispiel #5
0
        /// <summary>
        /// Collects filtered content of all directories and dedupes the list before returning it.
        /// </summary>
        private async Task <Possible <List <SealedDirectoryFile> > > GetUniqueFilteredDirectoryContentAsync(
            string[] directoryPaths,
            string[] directoryIds,
            Regex[] contentFilters,
            FilterKind[] filterKinds = null)
        {
            // TODO: add counter to measure the time spent getting dir content
            var getContentTasks = Enumerable
                                  .Range(0, directoryPaths.Length)
                                  .Select(i => GetDirectoryContentAndApplyFilterAsync(directoryPaths[i], directoryIds[i], contentFilters[i], filterKinds?[i] ?? FilterKind.Include)).ToArray();

            var getContentResults = await TaskUtilities.SafeWhenAll(getContentTasks);

            if (getContentResults.Any(r => !r.Succeeded))
            {
                return(new Failure <string>(string.Join("; ", getContentResults.Where(r => !r.Succeeded).Select(r => r.Failure.Describe()))));
            }

            // dedupe collected files using file artifact as a key
            var dedupedFiles = getContentResults.SelectMany(res => res.Result).GroupBy(file => file.Artifact).Select(group => group.First());

            return(dedupedFiles.ToList());
        }
Beispiel #6
0
        private Task <IAsyncReaderWriterLockToken> ExclusiveReaderLockAsync(ExclusiveReaderLock erLock, CancellationToken cancellationToken = default(CancellationToken))
        {
            TaskUtilities.AssertIsOnBackgroundThread();

            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.FromCanceled <IAsyncReaderWriterLockToken>(cancellationToken));
            }

            var source = new ExclusiveReaderLockSource(this, erLock);

            _queue.AddExclusiveReader(source, out var isAddedAfterWriterOrExclusiveReader);
            if (isAddedAfterWriterOrExclusiveReader)
            {
                source.RegisterCancellation(cancellationToken);
            }
            else
            {
                source.Release();
            }

            return(source.Task);
        }
Beispiel #7
0
        public async Task WhenAllCancelOnFailure_NoCancellation()
        {
            var index = 0;

            Func <CancellationToken, Task> function1 = async ct => {
                await Task.Delay(100, ct);

                Interlocked.Exchange(ref index, 1);
                throw new InvalidOperationException("1");
            };

            Func <CancellationToken, Task> function2 = async ct => {
                await Task.Delay(50, ct);

                Interlocked.Exchange(ref index, 2);
                throw new InvalidOperationException("2");
            };

            Func <Task> f = () => TaskUtilities.WhenAllCancelOnFailure(new [] { function1, function2 }, CancellationToken.None);

            (await f.ShouldThrowAsync <InvalidOperationException>()).WithMessage("2");
            index.Should().Be(2);
        }
Beispiel #8
0
        private static async Task <bool> WaitForProcessExitAsync(Process process, CancellationToken cancellationToken)
        {
            // Helps to get notified either when the server is ready or in case server failed to initialize properly
            using (var safeWaitHandle = new SafeWaitHandle(process.Handle, false))
            {
                using (var processWaitHandle = new AutoResetEvent(false)
                {
                    SafeWaitHandle = safeWaitHandle
                })
                {
                    var completedIndex = await TaskUtilities.ToTask(new WaitHandle[] { processWaitHandle, cancellationToken.WaitHandle });

                    if (completedIndex == 0)
                    {
                        await Task.Run(() => process.WaitForExit(), cancellationToken);

                        return(process.ExitCode == 0);
                    }

                    return(false);
                }
            }
        }
Beispiel #9
0
        private async Task <string> ReadNextRequest(string prompt, int len, CancellationToken ct)
        {
            TaskUtilities.AssertIsOnBackgroundThread();

            var requestSource = await _pendingRequestSources.ReceiveAsync(ct);

            TaskCompletionSource <string> requestTcs = new TaskCompletionSource <string>();

            Interlocked.Exchange(ref _currentRequestSource, requestSource);

            requestSource.Request(_contexts, prompt, len, requestTcs);
            using (ct.Register(() => requestTcs.TrySetCanceled())) {
                var response = await requestTcs.Task;

                Debug.Assert(response.Length < len); // len includes null terminator
                if (response.Length >= len)
                {
                    response = response.Substring(0, len - 1);
                }

                return(response);
            }
        }
Beispiel #10
0
        private async Task StartHostAsyncBackground(RHostStartupInfo startupInfo, IRSessionCallback callback, IUIService ui, int timeout, CancellationToken cancellationToken)
        {
            TaskUtilities.AssertIsOnBackgroundThread();

            _callback    = callback;
            _startupInfo = startupInfo ?? new RHostStartupInfo();
            RHost host;

            try {
                // ui?.LogMessage($"Making connection info {Name}");
                var connectionInfo = new HostConnectionInfo(Name, this, _startupInfo.UseRHostCommandLineArguments, _startupInfo.IsInteractive, timeout);
                // ui?.LogMessage($"Connecting to broker {Name}");
                host = await BrokerClient.ConnectAsync(connectionInfo, cancellationToken);
            } catch (OperationCanceledException ex) {
                _hostStartedTcs.TrySetCanceled(ex);
                throw;
            } catch (Exception ex) {
                _hostStartedTcs.TrySetException(ex);
                throw;
            }

            await StartHostAsyncBackground(host, cancellationToken);
        }
Beispiel #11
0
        private async Task <bool> EvaluateAll(IReadOnlyList <IRContext> contexts, bool mutated, CancellationToken ct)
        {
            TaskUtilities.AssertIsOnBackgroundThread();

            try {
                RSessionEvaluationSource source;
                while (!ct.IsCancellationRequested && _pendingEvaluationSources.TryReceive(out source))
                {
                    mutated |= source.IsMutating;
                    await source.BeginEvaluationAsync(contexts, _host, ct);
                }
            } catch (OperationCanceledException) {
                // Host is being shut down, so there's no point in raising the event anymore.
                mutated = false;
            } finally {
                if (mutated)
                {
                    OnMutated();
                }
            }

            return(mutated);
        }
            public virtual async Task ShutdownAsync()
            {
                await TaskUtilities.SafeWhenAll(
                    Sessions.Select(async(session, index) =>
                {
                    if (!session.ShutdownCompleted)
                    {
                        await session.ShutdownAsync(StoreContexts[index]).ThrowIfFailure();
                    }
                }));

                foreach (var session in Sessions)
                {
                    session.Dispose();
                }

                if (_traceStoreStatistics)
                {
                    await LogStatsAsync();
                }

                await ShutdownStoresAsync();
            }
Beispiel #13
0
        public async Task WithTimeoutShouldTriggerGivenCancellationTokenAndFailWithTimeoutException()
        {
            bool cancellationRequested = false;
            var  task = TaskUtilities.WithTimeoutAsync(
                async token =>
            {
                try
                {
                    await Task.Delay(/* milliseconds */ 200000, token);
                }
                catch (TaskCanceledException) { }

                cancellationRequested = token.IsCancellationRequested;
                return(42);
            },
                TimeSpan.FromMilliseconds(10),
                default);

            // Timeout should happen here, and the callback should see that a given cancellation token is triggered
            await Assert.ThrowsAsync <TimeoutException>(async() => await task);

            XAssert.IsTrue(cancellationRequested);
        }
Beispiel #14
0
        private static async Task CreateCsvAndStartProcess(IREvaluationResultInfo result, IRSession session, string fileName, IFileSystem fileSystem, IProgress <ProgressDialogData> progress)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            using (var e = await session.BeginEvaluationAsync()) {
                var csvDataBlobId = await e.EvaluateAsync <ulong>($"rtvs:::export_to_csv({result.Expression}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal);

                using (DataTransferSession dts = new DataTransferSession(session, fileSystem)) {
                    var total = await session.GetBlobSizeAsync(csvDataBlobId, CancellationToken.None);

                    progress.Report(new ProgressDialogData(0, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV));
                    await dts.FetchFileAsync(new RBlobInfo(csvDataBlobId), fileName, true, new Progress <long>(b => {
                        var step = (int)(b * 100 / total);
                        progress.Report(new ProgressDialogData(step, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV));
                    }));

                    progress.Report(new ProgressDialogData(100, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV));
                }
            }
        }
        /// <summary>
        /// Asynchronously fetches RD data on the function from R.
        /// </summary>
        public async Task<string> GetFunctionRdDataAsync(string functionName, string packageName) {
            if(packageName.EqualsOrdinal("rtvs")) {
                return GetRtvsFunctionRdData(functionName);
            }

            await TaskUtilities.SwitchToBackgroundThread();
            await _host.StartSessionAsync();

            string command = GetCommandText(functionName, packageName);
            try {
                return await _host.Session.EvaluateAsync<string>(command, REvaluationKind.Normal);
            } catch (RException) { }

            // Sometimes there is no information in a specific package.
            // For example, Matrix exports 'as.matrix' and base does it as well.
            // However, help('as.matrix', 'Matrix') will fail while help('as.matrix' will succeed.
            command = GetCommandText(functionName, null);
            try {
                return await _host.Session.EvaluateAsync<string>(command, REvaluationKind.Normal);
            } catch (RException) { }

            return string.Empty;
        }
Beispiel #16
0
        public void AwaitFailure()
        {
            int    i             = 0;
            string exceptionText = "Boom";

            try
            {
                var result = TaskUtilities.AwaitWithProgressReportingAsync(
                    task: Task.Run(() => TestMethod(exceptionText)),
                    period: TimeSpan.FromHours(24),
                    action: (time) => Interlocked.Increment(ref i),
                    reportImmediately: false,
                    reportAtEnd: false).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                XAssert.AreEqual(exceptionText, e.GetLogEventMessage());
                XAssert.AreEqual(0, i);
                return;
            }

            XAssert.Fail("Should have thrown an exception");
        }
Beispiel #17
0
        public static async Task <IGridData <string> > GetGridDataAsync(string expression, GridRange?gridRange, ISortOrder sortOrder = null)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var rSession = VsAppShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>().GetInteractiveWindowRSession();

            string rows    = gridRange?.Rows.ToRString();
            string columns = gridRange?.Columns.ToRString();

            using (var evaluator = await rSession.BeginEvaluationAsync()) {
                try {
                    string exp;
                    if (sortOrder != null && !sortOrder.IsEmpty)
                    {
                        if (gridRange.Value.Columns.Count > 1)
                        {
                            string dataFrameSortExpression = sortOrder.GetDataFrameSortFunction();
                            exp = Invariant($"rtvs:::grid_data({expression}, {rows}, {columns}, {dataFrameSortExpression.ToRStringLiteral()})");
                        }
                        else
                        {
                            int sortType = sortOrder.IsPrimaryDescending ? 2 : 1;
                            exp = Invariant($"rtvs:::grid_data({expression}, {rows}, {columns}, NULL, {sortType})");
                        }
                    }
                    else
                    {
                        exp = Invariant($"rtvs:::grid_data({expression}, {rows}, {columns})");
                    }
                    return(await evaluator.EvaluateAsync <GridData>(exp, REvaluationKind.Normal));
                } catch (RException ex) {
                    var message = Invariant($"Grid data evaluation failed:{Environment.NewLine}{ex.Message}");
                    GeneralLog.Write(message);
                    return(null);
                }
            }
        }
        private static void InitializeUtilities(CommandLineParameters parms)
        {
            ReconciliationLib.Utilities.Init();

            // wire events
            ReconciliationLib.Utilities.OnError += new EventHandler <ErrorEventArgs>(Utilities_OnError);
            ReconciliationLib.Utilities.OnInfo  += new EventHandler <InfoEventArgs>(Utilities_OnInfo);
            TaskUtilities.OnError += new EventHandler <ErrorEventArgs>(Utilities_OnError);
            TaskUtilities.OnInfo  += new EventHandler <InfoEventArgs>(Utilities_OnInfo);

            // get Hugo connection
            Gargoyle.Utils.DBAccess.DBAccess dbAccess = Gargoyle.Utils.DBAccess.DBAccess.GetDBAccessOfTheCurrentUser(applicationName);
            ReconciliationLib.Utilities.Connection = dbAccess.GetConnection(databaseName);
            s_taskUtilities = new TaskUtilities(ReconciliationLib.Utilities.Connection);


            if (s_logger != null)
            {
                s_logger.Info("Connecting to " + ReconciliationLib.Utilities.Connection.ConnectionString);
            }

            // set account group
            if (!String.IsNullOrEmpty(parms.AccountGroupName))
            {
                ReconciliationLib.Utilities.AccountGroupName = parms.AccountGroupName;

                // if we have not specified a clearing house, use the one associated with the account group
                if (parms.ClearingHouse == ClearingHouse.None)
                {
                    parms.ClearingHouse = ReconciliationLib.Utilities.ClearingHouse;
                }
            }

            // set dates
            ReconciliationLib.Utilities.ImportDate   = parms.GetImportDateOverride() ?? DateTime.Today;
            ReconciliationLib.Utilities.PreviousDate = ReconciliationLib.Utilities.CalculatePreviousBusinessDay(ReconciliationLib.Utilities.ImportDate.Value);
        }
Beispiel #19
0
        public TaskResult Execute(TaskInstance taskInstance)
        {
            var  taskResult = new TaskResult();
            Guid runId      = Guid.Empty;

            try
            {
                StartActiveNotifier(taskInstance.Id);

                TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.InProgress, null);

                // Read parameters
                runId = new Guid(taskInstance.Parameters["RunId"].ToString());
                var runInstances = _runManager.AllScenariosStartRun(runId);

                TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.CompletedSuccess, DateTime.UtcNow);
                taskResult.Status = TaskInstanceStatues.CompletedSuccess;
            }
            catch (Exception exception)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, $"{exception.StackTrace}"));///testing
                _auditEventRepository.Insert(
                    AuditEventFactory.CreateAuditEventForException(0, 0, $"Error executing task for start run (TaskInstanceID={taskInstance.Id.ToString()}, RunID={runId.ToString()})",
                                                                   exception)
                    );

                TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.CompletedError, DateTime.UtcNow);
                taskResult.Status    = TaskInstanceStatues.CompletedError;
                taskResult.Exception = exception;
            }
            finally
            {
                StopActiveNotifier();
            }

            return(taskResult);
        }
Beispiel #20
0
        private async Task ShowDialog(Message request, MessageButtons buttons, CancellationToken ct)
        {
            TaskUtilities.AssertIsOnBackgroundThread();

            request.ExpectArguments(2);
            var contexts = GetContexts(request);
            var s        = request.GetString(1, "s", allowNull: true);

            MessageButtons input = await _callbacks.ShowDialog(contexts, s, buttons, ct);

            ct.ThrowIfCancellationRequested();

            string response;

            switch (input)
            {
            case MessageButtons.No:
                response = "N";
                break;

            case MessageButtons.Cancel:
                response = "C";
                break;

            case MessageButtons.Yes:
                response = "Y";
                break;

            default: {
                FormattableString error = $"YesNoCancel: callback returned an invalid value: {input}";
                Trace.Fail(Invariant(error));
                throw new InvalidOperationException(Invariant(error));
            }
            }

            await RespondAsync(request, ct, response);
        }
Beispiel #21
0
 protected override Task <DependencyResult <TDependencyInstance> > ResolveNewDependencyInstanceAsync(IDependencyResolutionContext context)
 {
     try {
         var specs =
             context
             .EnsureNotNull(nameof(context))
             .Value
             .Specs;
         //
         var factoryArgs = ReadDA(ref _factoryArgs);
         if (factoryArgs == null)
         {
             if ((factoryArgs = specs.NewInstanceFactoryArgs as IArgsTuple <TArg1, TArg2, TArg3, TArg4>) == null || factoryArgs.ArgsCount != __ArgsCount)
             {
                 return(TaskUtilities.FromResult(DependencyResult <TDependencyInstance> .None));
             }
         }
         else if (specs.NewInstanceFactoryArgs != null)
         {
             return(TaskUtilities.FromResult(DependencyResult <TDependencyInstance> .None));
         }
         //
         return
             (TaskUtilities
              .FromResult(
                  result:
                  new DependencyResult <TDependencyInstance>(
                      instance:
                      ReadDA(ref _getDependencyCtor)
                          ()
                          (factoryArgs.Arg1, factoryArgs.Arg2, factoryArgs.Arg3, factoryArgs.Arg4),
                      isNewInstance: true)));
     }
     catch (Exception firstException) {
         return(Task.FromException <DependencyResult <TDependencyInstance> >(firstException));
     }
 }
Beispiel #22
0
        private static async Task CreateCsvAndStartProcess(
            IREvaluationResultInfo result,
            IRSession session,
            ICoreShell coreShell,
            string fileName,
            IFileSystem fileSystem,
            IProgress <ProgressDialogData> progress,
            CancellationToken cancellationToken)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            try {
                var csvDataBlobId = await session.EvaluateAsync <ulong>($"rtvs:::export_to_csv({result.Expression}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal, cancellationToken);

                using (DataTransferSession dts = new DataTransferSession(session, fileSystem)) {
                    await dts.FetchAndDecompressFileAsync(csvDataBlobId, fileName, progress, Resources.Status_WritingCSV, cancellationToken);
                }
            } catch (RException) {
                await coreShell.ShowErrorMessageAsync(Resources.Error_CannotExportToCsv, cancellationToken);
            }
        }
Beispiel #23
0
        public void Initialize()
        {
            _fileContainer = new AzureFileContainer(CONNECTION_STRING, SHARE_NAME);

            _cloudStorageAccount = CloudStorageAccount.Parse(CONNECTION_STRING);

            _cloudFileShare = _cloudStorageAccount.GetShareReference(SHARE_NAME);

            _cloudFileRootDirectory = _cloudFileShare.GetRootDirectoryReference();

            _cloudFileSourceDirectory = _cloudFileShare.GetDirectoryReference(path: new[] { SOURCE_DIRECTORY }, createIfNotExists: true);

            _cloudFileShare.GetDirectoryReference(path: new[] { SOURCE_DIRECTORY, DUMMY_DIRECTORY }, createIfNotExists: true);

            _cloudFileShare.GetDirectoryReference(path: new[] { TARGET_DIRECTORY }, createIfNotExists: true);

            _cloudRootFile = _cloudFileRootDirectory.GetFileReference(FILE_NAME);

            _cloudSourceFile = _cloudFileSourceDirectory.GetFileReference(FILE_NAME);

            TaskUtilities.ExecuteSync(_cloudRootFile.UploadTextAsync(FILE_CONTENT));

            TaskUtilities.ExecuteSync(_cloudSourceFile.UploadTextAsync(FILE_CONTENT));
        }
 protected override Task <DependencyResult <TDependencyInstance> > ResolveNewDependencyInstanceAsync(IDependencyResolutionContext context)
 {
     try {
         var specs = context.EnsureNotNull(nameof(context)).Value.Specs;
         //
         if ((specs.NewInstanceFactoryArgs?.ArgsCount ?? 0) != __ArgsCount)
         {
             return(TaskUtilities.FromResult(DependencyResult <TDependencyInstance> .None));
         }
         else
         {
             return
                 (TaskUtilities
                  .FromResult(
                      result:
                      new DependencyResult <TDependencyInstance>(
                          instance: ReadDA(ref _getDependencyCtor, considerDisposeRequest: true)()(),
                          isNewInstance: true)));
         }
     }
     catch (Exception exception) {
         return(Task.FromException <DependencyResult <TDependencyInstance> >(exception));
     }
 }
Beispiel #25
0
        public async Task <bool> ExecuteBrowserCommandAsync(string command, Func <IRSessionInteraction, Task <bool> > prepare = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            ThrowIfDisposed();
            await TaskUtilities.SwitchToBackgroundThread();

            using (var inter = await RSession.BeginInteractionAsync(isVisible: true, cancellationToken: cancellationToken)) {
                if (prepare != null)
                {
                    if (!await prepare(inter))
                    {
                        return(false);
                    }
                }

                if (inter.Contexts.IsBrowser())
                {
                    await inter.RespondAsync(command + "\n");

                    return(true);
                }
            }

            return(false);
        }
Beispiel #26
0
        private Task RunManyForStoreAcrossServerRestartAsync(Func <Context, IContentStore, Task> requestFunc)
        {
            return(RunStoreTestAsync(async(context, store) =>
            {
                // Launch a bunch of duplicate requests in the background, with server restart mixed in.
                var tasks = new List <Task>(101);
                tasks.AddRange(Enumerable.Range(0, 50).Select(i => Task.Run(() =>
                                                                            requestFunc(new Context(Logger), store))));
                tasks.Add(((ITestServiceClientContentStore)store).RestartServerAsync(context));
                tasks.AddRange(Enumerable.Range(0, 50).Select(i => Task.Run(() =>
                                                                            requestFunc(new Context(Logger), store))));

                try
                {
                    await TaskUtilities.SafeWhenAll(tasks);
                }
                catch (AggregateException ex)
                {
                    AggregateException singleException = ex.Flatten();
                    string failureMessage = string.Join(",", singleException.InnerExceptions.Select(x => x.Message));
                    Assert.True(false, failureMessage);
                }
            }));
        }
Beispiel #27
0
        private Task ValidateState(CancellationToken cancellationToken)
        {
            switch (_state)
            {
            case FrameStreamState.Open:
                if (cancellationToken.IsCancellationRequested)
                {
                    return(TaskUtilities.GetCancelledTask(cancellationToken));
                }
                break;

            case FrameStreamState.Closed:
                throw new ObjectDisposedException(nameof(FrameResponseStream));

            case FrameStreamState.Aborted:
                if (cancellationToken.IsCancellationRequested)
                {
                    // Aborted state only throws on write if cancellationToken requests it
                    return(TaskUtilities.GetCancelledTask(cancellationToken));
                }
                break;
            }
            return(null);
        }
Beispiel #28
0
        /// <summary>
        /// Evaluates all named values that are declared locally and collects the evaluation tasks.
        /// </summary>
        private async Task <bool> EvaluateAllNamedValuesAsync(ImmutableContextBase context)
        {
            Contract.Requires(context != null);

            var evaluateTasks = new List <Task <object> >();

            EvaluateAllNamedValues(context, evaluateTasks);

            object[] results = await TaskUtilities.WithCancellationHandlingAsync(
                context.LoggingContext,
                Task.WhenAll(evaluateTasks),
                (loggingContext) =>
            {
                // Many modules are potentially being evaluated at the same time. Only log the cancelation event once.
                if (Interlocked.Increment(ref context.Logger.EvaluationCancelledFirstLogged) == 1)
                {
                    context.Logger.EvaluationCanceled(loggingContext);
                }
            },
                s_errorValueAsObjectArray,
                context.EvaluationScheduler.CancellationToken);

            return(results.All(result => !result.IsErrorValue()));
        }
Beispiel #29
0
        public async Task WhenAllCancelOnFailure_CancellationThenFailure()
        {
            var index = 0;

            Func <CancellationToken, Task> function1 = async ct => {
                await Task.Delay(150, ct);

                Interlocked.Exchange(ref index, 1);
                throw new InvalidOperationException("1");
            };

            Func <CancellationToken, Task> function2 = async ct => {
                await Task.Delay(100, ct);

                Interlocked.Exchange(ref index, 2);
                throw new InvalidOperationException("2");
            };

            var         cts = new CancellationTokenSource(50);
            Func <Task> f   = () => TaskUtilities.WhenAllCancelOnFailure(new [] { function1, function2 }, cts.Token);
            await f.ShouldThrowAsync <OperationCanceledException>();

            index.Should().Be(0);
        }
        public TaskResult Execute(TaskInstance taskInstance)
        {
            var taskResult = new TaskResult();

            try
            {
                StartActiveNotifier(taskInstance.Id);

                TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.InProgress, null);

                int instanceConfigurationId = Convert.ToInt16(taskInstance.Parameters["InstanceConfigurationId"]);
                var newAutoBook             = new AutoBookDomainObject()
                {
                    TimeCreated             = DateTime.UtcNow,
                    Locked                  = false,
                    Status                  = AutoBookStatuses.Provisioning,
                    InstanceConfigurationId = instanceConfigurationId
                };

                _autoBooks.Create(newAutoBook);

                TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.CompletedSuccess, DateTime.UtcNow);
                taskResult.Status = TaskInstanceStatues.CompletedSuccess;
            }
            catch (Exception exception)
            {
                TaskUtilities.UpdateTaskInstanceStatus(taskInstance.Id, _repositoryFactory, TaskInstanceStatues.CompletedError, DateTime.UtcNow);
                taskResult.Status    = TaskInstanceStatues.CompletedError;
                taskResult.Exception = exception;
            }
            finally
            {
                StopActiveNotifier();
            }
            return(taskResult);
        }