public void ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true };
            HttpResponseMessage response = new HttpResponseMessage();
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response);
            tcs.TrySetException(exception);
            mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task);
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);
            Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" },
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "ExecuteAuthorizationFilterAsync" }
            };

            // Act & Assert
            Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
 public Task<Socket> ConnectAsync(IPEndPoint remoteEndPoint)
 {
     _connectTcs = new TaskCompletionSource<Socket>();
     var task = _connectTcs.Task;
     Connect(remoteEndPoint);
     return task;
 }
        private async Task<bool> SaveServerCreds(ServerCredentials configuration)
        {
            var tsc = new TaskCompletionSource<bool>();
            Deployment.Current.Dispatcher.BeginInvoke(async () =>
            {
                await Lock.WaitAsync();

                try
                {
                    var json = JsonConvert.SerializeObject(configuration);

                    await _storageService.WriteAllTextAsync(Constants.Settings.ServerCredentialSettings, json).ConfigureAwait(false);
                }
                finally
                {
                    Lock.Release();
                }

                Debug.WriteLine("SaveCreds, Server count: " + (configuration != null && configuration.Servers != null ? configuration.Servers.Count : 0));

                tsc.SetResult(true);
            });

            return await tsc.Task;
        }
Example #4
0
 public Task CopyToAsync(Stream stream)
 {
     if (stream == null) {
         throw new ArgumentNullException("stream");
     }
     var tcs = new TaskCompletionSource<object>();
     try {
         var task = this.SerializeToStreamAsync(stream);
         if (task == null) {
             throw new InvalidOperationException();
         }
         task.ContinueWith(t => {
             if (t.IsFaulted) {
                 tcs.TrySetException(t.Exception.GetBaseException());
                 return;
             }
             if (t.IsCanceled) {
                 tcs.TrySetCanceled();
                 return;
             }
             tcs.TrySetResult(null);
         });
     }
     catch (Exception ex) {
         tcs.TrySetException(ex);
     }
     return tcs.Task;
 }
Example #5
0
        public static Task<ResponseMessage> Execute(this WebClient client,
                                                    RequestMessage requestMessage,
                                                    Uri uri,
                                                    string productName,
                                                    TaskCompletionSource<string> tcs) {
            client.ShouldNotBeNull("client");
            requestMessage.ShouldNotBeNull("requestMessage");

            try {
                var responseText = ResolveRequestSerializer(productName).Serialize(requestMessage).Base64Encode();

                return
                    client
                        .UploadStringTask(uri, "POST", responseText)
                        .ContinueWith(task => {
                                          var responseBytes = task.Result;
                                          return ResolveResponseSerializer(productName).Deserialize(responseBytes.Base64Decode());
                                      });
            }
            catch(Exception ex) {
                if(log.IsErrorEnabled)
                    log.ErrorException("WebClient를 통한 요청이 실패했습니다.", ex);

                throw;
            }
        }
        /// <summary>
        /// Get the string by URI.
        /// </summary>
        /// <param name="requestUri">The Uri the request is sent to.</param>
        /// <returns>string</returns>
        public Task<string> GetStringAsync(Uri requestUri)
        {
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

            try
            {
                this.DownloadStringCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        tcs.TrySetResult(e.Result);
                    }
                    else
                    {
                        tcs.TrySetException(e.Error);
                    }
                };

                this.DownloadStringAsync(requestUri);

            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            if (tcs.Task.Exception != null)
            {
                throw tcs.Task.Exception;             
            }

            return tcs.Task;
        }
        /// <summary>
        /// A helper method for mocking APM (classic) asynchronous methods with on TAP (modern) asynchronous methods.
        /// </summary>
        /// <remarks>
        /// This is based on <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx"/> 
        /// and <a href="http://msdn.microsoft.com/en-us/library/hh873178.aspx"/>.
        /// </remarks>
        public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
        {
            Debug.Assert(task != null, "task");

            var taskCompletionSource = new TaskCompletionSource<object>(state);
            task.ContinueWith(
                t =>
                {
                    if (t.IsFaulted)
                    {
                        taskCompletionSource.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else
                    {
                        taskCompletionSource.SetResult(null);
                    }

                    if (callback != null)
                    {
                         callback(taskCompletionSource.Task);
                    }
                },
                TaskScheduler.Default);

            return taskCompletionSource.Task;
        }
Example #8
0
		private Task<bool> DoWork(
			DoWorkArguments arguments)
		{
			Console.WriteLine("{0:mm:ss.ffffff} [{1}] Doing work for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
			var _result = new TaskCompletionSource<bool>();

			new Task(() =>
				{
					Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Starting for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
					Thread.Sleep(arguments.SleepInterval);

					if (arguments.ShouldThrowException)
					{
						Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Sequence {2} is exceptional !", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
						var _exception = new ApplicationException("Bang !");
						_result.SetException(_exception);
					}
					else
					{
						_result.SetResult(arguments.ResultToReturn);
					}
					Console.WriteLine("{0:mm:ss.ffffff} [{1}] :: Completed for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
				}).Start();

			Console.WriteLine("{0:mm:ss.ffffff} [{1}] Exiting for sequence {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, arguments.Sequence);
			return _result.Task;
		}
Example #9
0
		async Task<bool> SignIn()
		{
			var tcs = new TaskCompletionSource<bool> ();
			var alert = new UIAlertView ("Please sign in", "", null, "Cancel", "Ok");
			alert.AlertViewStyle = UIAlertViewStyle.SecureTextInput;
			var tb = alert.GetTextField(0);
			tb.ShouldReturn = (t)=>{

				alert.DismissWithClickedButtonIndex(1,true);
				signIn(tcs,tb.Text);
				return true;
			};

			alert.Clicked += async (object sender, UIButtonEventArgs e) => {
				if(e.ButtonIndex == 0)
				{
					tcs.TrySetResult(false);
					alert.Dispose();
					return;
				}

				var id = tb.Text;
				signIn(tcs,id);
			
			
			};
			alert.Show ();
			return await tcs.Task;
		}
Example #10
0
        public async Task InteractDuringBrowse() {
            using (var debugSession = new DebugSession(_session)) {
                using (var sf = new SourceFile("x <- 'old'; browser()")) {
                    var browse = new TaskCompletionSource<bool>();
                    debugSession.Browse += (s, e) => {
                        browse.TrySetResult(true);
                    };

                    await sf.Source(_session);
                    await browse.Task;

                    using (var inter = await _session.BeginInteractionAsync()) {
                        await inter.RespondAsync("x <- 'new'\n");
                    }

                    REvaluationResult x;
                    using (var eval = await _session.BeginEvaluationAsync()) {
                        x = await eval.EvaluateAsync("x");
                    }

                    x.StringResult.Should().Be("new");
                }
            }

        }
Example #11
0
		public Task<bool> RunMultipleTasksWithSingleResult()
		{
			var _result = new TaskCompletionSource<bool>();

			var _arguments = new []
				{
					new DoWorkArguments { Sequence = 1, SleepInterval = TimeSpan.FromMilliseconds(5000), ResultToReturn = false, ShouldThrowException = false },
					new DoWorkArguments { Sequence = 2, SleepInterval = TimeSpan.FromMilliseconds(25), ResultToReturn = true, ShouldThrowException = true },
					new DoWorkArguments { Sequence = 3, SleepInterval = TimeSpan.FromMilliseconds(50), ResultToReturn = true, ShouldThrowException = false }
				};
			
			var _tasks = new List<Task<bool>>();
			Parallel.ForEach(_arguments, argument => _tasks.Add(this.DoWork(argument)));

			Task.WhenAll(_tasks).ContinueWith(taskResults =>
				{
					Console.WriteLine("{0:mm:ss.ffffff} [{1}] ---> Processing result ({2})", DateTime.Now, Thread.CurrentThread.ManagedThreadId, taskResults.Status);
					if (taskResults.IsFaulted)
					{
						_result.SetException(taskResults.Exception);
					}
					else
					{
						var _allGood = taskResults.Result.All(result => result);
						_result.SetResult(_allGood);
					}
				});

			Console.WriteLine("{0:mm:ss.ffffff} [{1}] About to return task completion result", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
			return _result.Task;
		}
        public async Task IsEventEditableForTest()
        {
            var tcs = new TaskCompletionSource<Event>();
            string userId = "u1";
            string userId2 = "u2";
            Guid e1Id = new Guid("00000000-0000-0000-0000-000000000000");
            Guid e2Id = new Guid("00000000-0000-0000-0000-000000000001");
            Event e1 = new Event { Id = e1Id, Title = "New Event", OthersCanEdit = true };
            Event e2 = new Event { Id = e2Id, Title = "New Event2", OthersCanEdit = false, OrganizerId = userId };
            tcs.SetResult(e1);

            _eventRepository.Setup(mock => mock.GetEventInfo(e1Id)).Returns(tcs.Task);
            var task = await _userService.IsEventEditableFor(e1Id, userId);
            _eventRepository.Verify(mock => mock.GetEventInfo(e1Id), Times.Once());
            Assert.AreEqual(true, task, "This event should be editable, but the method IsEventEditable returns false.");

            var tcs2 = new TaskCompletionSource<Event>();
            tcs2.SetResult(e2);
            _eventRepository.Setup(mock => mock.GetEventInfo(e2Id)).Returns(tcs2.Task);
            var task2 = await _userService.IsEventEditableFor(e2Id, userId);
            _eventRepository.Verify(mock => mock.GetEventInfo(e2Id), Times.Once(), "Method GetEventInfo was not called or was called more than once (or its parameters were wrong).");
            Assert.AreEqual(true, task2, "This event should be editable, but the method IsEventEditable returns false.");

            _eventRepository.Setup(mock => mock.GetEventInfo(e2Id)).Returns(tcs2.Task);
            var task3 = await _userService.IsEventEditableFor(e2Id, userId2);
            _eventRepository.Verify(mock => mock.GetEventInfo(e2Id), Times.Exactly(2), "Method GetEventInfo was not called or was called more than once (or its parameters were wrong).");
            Assert.AreEqual(false, task3, "This event should not be editable, but the method IsEventEditable returns true.");
        }
        static int PICK_CONTACT_REQUEST = 42; // The request code
        
        protected void OnActivityResult(TaskCompletionSource<ContactInfo> tcs, ActivityResultEventArgs e) //int requestCode, Android.App.Result resultCode, Intent data)
        {
            // Check which request it is that we're responding to
            if (e.requestCode == PICK_CONTACT_REQUEST)
            {
                // Make sure the request was successful
                if (e.resultCode == Android.App.Result.Ok)
                {
                    var loader = new CursorLoader(MainActivity.Instance, e.data.Data, projection, null, null, null);
                    var cursor = (Android.Database.ICursor)loader.LoadInBackground();

                    var contactList = new List<ContactInfo>();
                    if (cursor.MoveToFirst())
                    {
                        do
                        {
                            contactList.Add(GetContactInfoFromCursor(cursor));
                        } while (cursor.MoveToNext());
                    }
                    tcs.SetResult(contactList.FirstOrDefault());
                    return;
                }
            }

            tcs.SetResult(null);
        }
 public override IChannelHandler CreateNewInstance()
 {
     // TODO correct? shares references...
     var tcsRconResponse = new TaskCompletionSource<Message.Message>(_tcsRconResponse.Task.AsyncState);
     var tcsResponse = new TaskCompletionSource<Message.Message>(_tcsResponse.Task.AsyncState);
     return new RconInboundHandler(tcsRconResponse, tcsResponse);
 }
 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
     CancellationToken cancellationToken)
 {
     TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
     tcs.SetResult(new HttpResponseMessage());
     return tcs.Task;
 }
Example #16
0
 public TaskSupervisor()
 {
     _stopping = new TaskCompletionSource<IStopEvent>();
     _stoppingToken = new CancellationTokenSource();
     _participants = new List<Participant>();
     _stopToken = new CancellationTokenSource();
 }
            protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsyncCore(
                HttpRequestMessage request, CancellationToken cancellationToken)
            {
                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                var response = new HttpResponseMessage();

                response.StatusCode = HttpStatusCode.Redirect;
                response.Headers.Location = new Uri(Location + Calls);
                response.RequestMessage = request;

                if (Calls == 1)
                {
                    // First call the message should contain If-* headers
                    Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location)));
                    Assert.That(request.Headers.IfMatch.Count == 1);
                    Assert.That(request.Headers.IfNoneMatch.Count == 1);
                    Assert.That(request.Headers.IfModifiedSince.HasValue);
                    Assert.That(request.Headers.IfUnmodifiedSince.HasValue);
                }
                else
                {
                    // After first call the message should not contain If-* headers
                    Assert.That(request.RequestUri, Is.EqualTo(new Uri(Location + (Calls - 1))));
                    Assert.That(request.Headers.IfMatch.Count == 0);
                    Assert.That(request.Headers.IfNoneMatch.Count == 0);
                    Assert.IsNull(request.Headers.IfModifiedSince);
                    Assert.IsNull(request.Headers.IfUnmodifiedSince);
                }

                tcs.SetResult(response);
                return tcs.Task;
            }
        public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            try
            {
                var result = new TokenAuthenticator().Authenticate(actionContext, _authenticator);
            }
            catch (Exception e)
            {
                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetException(e);
                return tcs.Task;
            }

            if (actionContext.Response != null)
            {
                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetResult(actionContext.Response);
                return tcs.Task;
            }
            else
            {
                return continuation().ContinueWith<HttpResponseMessage>((tsk) =>
                {
                    HttpResponseMessage response = tsk.Result;
                    return response;

                }, TaskContinuationOptions.OnlyOnRanToCompletion);
            }
        }
        internal static Task<Report> CreateReport(string projectPath, CancellationToken cancellationToken, IProgress<string> progress, ICodeInspectSettings codeInspectSettings)
        {
            TaskCompletionSource<Report> completedTask = new TaskCompletionSource<Report>();
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    completedTask.TrySetCanceled();
                    return completedTask.Task;
                }

                if (projectPath.EndsWith("xml"))
                {
                    completedTask.TrySetResult(CreateReportFromXml(projectPath));
                }
                else
                {
                    return CreateReportFromProject(
                            codeInspectSettings.InspectCodePath,
                            projectPath,
                            Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), DateTime.Now.Ticks + ".xml"),
                            progress: progress);
                }
            }
            catch (Exception ex)
            {
                completedTask.TrySetException(ex);
            }

            return completedTask.Task;
        }
		private void OnPopupClosed(object sender, object e)
		{
			if (_tcs != null && !_tcs.Task.IsCompleted)
				_tcs.SetException(new OperationCanceledException()); // user closed the window
			_tcs = null;
			_popup = null;
		}
Example #21
0
		public void RunAsync_Cancel()
		{
			bool canComplete = false;

			IAsyncAction action = null;
			action = ThreadPool.RunAsync(a =>
			{
				while (!canComplete)
					Thread.Sleep(10);
			});

			var tcs = new TaskCompletionSource<AsyncStatus>();
			action.Completed = (a, s) =>
			{
				tcs.SetResult(s);
			};

			action.Cancel();
			Thread.Sleep(100);
			Assert.AreEqual(AsyncStatus.Canceled, action.Status);
			canComplete = true;

			Assert.IsTrue(SpinWait.SpinUntil(() => tcs.Task.IsCompleted, millisecondsTimeout: 400), "Task did not complete under 400ms.");
			Assert.AreEqual(AsyncStatus.Canceled, action.Status, "Task should not change status after cancel");
		}
Example #22
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var tcs = new TaskCompletionSource<object>();

            context.ApplicationInstance.CompleteRequest();
            var clientId = new Guid(context.Request["clientId"]);

            var jsons = new List<CommandMessage>();

            var bus = SheepJaxComet.PollingCommandBus;
            var obs = bus.GetObservable(clientId).Replay();
            var subscription = obs.Connect();
            obs.TakeUntil(Observable.Interval(LongPollTimeout))
                .TakeUntil(obs.Take(1).Delay(BatchInterval))
                .Subscribe(jsons.Add, context.AddError, ()=>
                    {
                        try
                        {
                            subscription.Dispose();
                            context.Response.Write("[" + string.Join(",", jsons.Select(x => x.Message)) + "]");
                            bus.Consumed(jsons.LastOrDefault());
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("SheepJax exception thrown while writing to long-polling connection", ex);
                        }
                        finally
                        {
                            tcs.SetResult(null);
                            cb(tcs.Task);
                        }
                    });

            return tcs.Task;
        }
Example #23
0
 public Task<byte[]> ReadAsBufferAsync()
 {
     var tcs = new TaskCompletionSource<byte[]>();
     try {
         Stream stream = new MemoryStream();
         this.SerializeToStreamAsync(stream).ContinueWith(copyTask => {
             try {
                 if (copyTask.IsFaulted) {
                     stream.Dispose();
                     tcs.SetException(copyTask.Exception.GetBaseException());
                 }
                 else {
                     if (copyTask.IsCanceled) {
                         stream.Dispose();
                         tcs.SetCanceled();
                     }
                     else {
                         stream.Seek(0, SeekOrigin.Begin);
                         var buff = new byte[stream.Length];
                         Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buff, 0, buff.Length, null).ContinueWith(readTask => tcs.SetResult(buff));
                     }
                 }
             }
             catch (Exception ex) {
                 stream.Dispose();
                 tcs.SetException(ex);
             }
         });
     }
     catch (Exception ex) {
         tcs.SetException(ex);
     }
     return tcs.Task;
 }
        /// <summary>
        /// Check for simple binding parameters in POST data. Bind POST
        /// data as well as query string data
        /// </summary>
        /// <param name="metadataProvider"></param>
        /// <param name="actionContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                                    HttpActionContext actionContext,
                                                    CancellationToken cancellationToken)
        {
            string stringValue = null;

            NameValueCollection col = TryReadBody(actionContext.Request);
            if (col != null)
                stringValue = col[Descriptor.ParameterName];

            // try reading query string if we have no POST/PUT match
            if (stringValue == null)
            {
                var query = actionContext.Request.GetQueryNameValuePairs();
                if (query != null)
                {
                    var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower());
                    var keyValuePairs = matches as IList<KeyValuePair<string, string>> ?? matches.ToList();
                    if (keyValuePairs.Any())
                        stringValue = keyValuePairs.First().Value;
                }
            }

            object value = StringToType(stringValue);

            // Set the binding result here
            SetValue(actionContext, value);

            // now, we can return a completed task with no result
            TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
            tcs.SetResult(default(AsyncVoid));
            return tcs.Task;
        }
        public Task PlaySoundAsync(string filename)
        {
            // Create media player
            var player = new MediaPlayer();

            // Create task completion source to support async/await
            var tcs = new TaskCompletionSource<bool> ();

            // Open the resource
            var fd = Xamarin.Forms.Forms.Context.Assets.OpenFd (filename);

            // Hook up some events
            player.Prepared += (s, e) => {
                player.Start();
            };

            player.Completion += (sender, e) => {
                tcs.SetResult(true);
            };

            // Initialize
            player.SetDataSource (fd.FileDescriptor);
            player.Prepare ();

            return tcs.Task;
        }
Example #26
0
        private void OnError(int? contextId, string error)
        {
            var exception = new InvalidOperationException(error);
            if (contextId == null || contextId == -1)
            {
                _projectContexts.TrySetException(exception);
                _shutdown.RequestShutdown();
            }
            else
            {
                _compileResponses.AddOrUpdate(contextId.Value,
                _ =>
                {
                    var tcs = new TaskCompletionSource<CompileResponse>();
                    tcs.SetException(exception);
                    return tcs;
                },
                (_, existing) =>
                {
                    if (!existing.TrySetException(exception))
                    {
                        var tcs = new TaskCompletionSource<CompileResponse>();
                        tcs.TrySetException(exception);
                        return tcs;
                    }

                    return existing;
                });
            }
        }
Example #27
0
        public Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationTokenSource cancellationToken)
        {
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;

            var tcs = new TaskCompletionSource<ProcessResults>();

            var standardOutput = new List<string>();
            var standardError = new List<string>();

            var process = new Process
            {
                StartInfo = processStartInfo,
                EnableRaisingEvents = true
            };

            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardOutput.Add(args.Data);
                }
            };

            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardError.Add(args.Data);
                }
            };

            
            cancellationToken.Token.ThrowIfCancellationRequested();

            _log.Debug("Registering cancellation for " + cancellationToken.GetHashCode());

            cancellationToken.Token.Register(() =>
            {
                tcs.TrySetCanceled();
                KillProcessAndChildren(process.Id);
            });


               process.Exited += (sender, args) =>
               {
                   tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError));
               };

            if (process.Start() == false)
            {
                tcs.TrySetException(new InvalidOperationException("Failed to start process"));
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
Example #28
0
        public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
        {
            if (processStartInfo == null)
            {
                throw new ArgumentNullException("processStartInfo");
            }

            // force some settings in the start info so we can capture the output
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.CreateNoWindow = true;

            var tcs = new TaskCompletionSource<ProcessResults>();

            var standardOutput = new List<string>();
            var standardError = new List<string>();

            var process = new Process
            {
                StartInfo = processStartInfo,
                EnableRaisingEvents = true,
            };

            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardOutput.Add(args.Data);
                }
            };

            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardError.Add(args.Data);
                }
            };

            process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError));

            cancellationToken.Register(() =>
            {
                tcs.TrySetCanceled();
                process.CloseMainWindow();
            });

            cancellationToken.ThrowIfCancellationRequested();

            if (process.Start() == false)
            {
                tcs.TrySetException(new InvalidOperationException("Failed to start process"));
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
        private Task<string> GetStringAsycTaskCompletionSource(string url)
        {

            var tcs= new TaskCompletionSource<string>();
            Func<string,string> getstring = GetString;

            try
            {
                getstring.BeginInvoke(url, (a) =>
                {
                    
                    var result = getstring.EndInvoke(a);
                    tcs.SetResult(result);
                }, null);


            }
            catch (Exception ex)
            {

                tcs.TrySetException(ex);
            }
           
            return tcs.Task;
        }
		public async void Should_Forward_Context_On_Rpc()
		{
			/* Setup */
			var tcs = new TaskCompletionSource<bool>();
			MessageContext firstContext = null;
			MessageContext secondContext = null;
			var requester = BusClientFactory.CreateDefault();
			var firstResponder = BusClientFactory.CreateDefault();
			var secondResponder = BusClientFactory.CreateDefault();

			firstResponder.RespondAsync<FirstRequest, FirstResponse>(async (req, c) =>
			{
				firstContext = c;
				var resp = await firstResponder.RequestAsync<SecondRequest, SecondResponse>(new SecondRequest(), c.GlobalRequestId);
				return new FirstResponse { Infered = resp.Source };
			});
			secondResponder.RespondAsync<SecondRequest, SecondResponse>((req, c) =>
			{
				secondContext = c;
				tcs.SetResult(true);
				return Task.FromResult(new SecondResponse { Source = Guid.NewGuid() });
			});

			/* Test */
			requester.RequestAsync<FirstRequest, FirstResponse>();
			await tcs.Task;

			/* Assert */
			Assert.Equal(firstContext.GlobalRequestId, secondContext.GlobalRequestId);
		}