/// <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 #2
0
 public static Task Then(Task first, Func<Task> next)
 {
     var tcs = new TaskCompletionSource<object>();
     first.ContinueWith(_ =>
     {
         if (first.IsFaulted){
             tcs.TrySetException(first.Exception.InnerExceptions);
         }
         else if (first.IsCanceled){
             tcs.TrySetCanceled();
         }
         else
         {
             try
             {
                 next().ContinueWith(t =>  {
                     if (t.IsFaulted) {
                         tcs.TrySetException(t.Exception.InnerExceptions);
                     }
                     else if (t.IsCanceled) {
                         tcs.TrySetCanceled();
                     }
                     else {
                         tcs.TrySetResult(null);
                     }
                 }, TaskContinuationOptions.ExecuteSynchronously);
             }
             catch (Exception exc) { tcs.TrySetException(exc); }
         }
     }, TaskContinuationOptions.ExecuteSynchronously);
     return tcs.Task;
 }
Example #3
0
        public static Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count, 
            CancellationToken cancel = default(CancellationToken))
        {
            cancel.ThrowIfCancellationRequested();
            var tcs = new TaskCompletionSource<object>();
            var sr = stream.BeginWrite(buffer, offset, count, ar =>
            {
                if (ar.CompletedSynchronously)
                {
                    return;
                }
                try
                {
                    stream.EndWrite(ar);
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    // Assume errors were caused by cancelation.
                    if (cancel.IsCancellationRequested)
                    {
                        tcs.TrySetCanceled();
                    }

                    tcs.SetException(ex);
                }
            }, null);

            if (sr.CompletedSynchronously)
            {
                try
                {
                    stream.EndWrite(sr);
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    // Assume errors were caused by cancelation.
                    if (cancel.IsCancellationRequested)
                    {
                        tcs.TrySetCanceled();
                    }

                    tcs.SetException(ex);
                }
            }
            return tcs.Task;
        }
Example #4
0
        public void CancelledTaskHandledinServerSentEvents()
        {
            var tcs = new TaskCompletionSource<IResponse>();
            tcs.TrySetCanceled();

            var httpClient = new Mock<IHttpClient>();
            var connection = new Mock<IConnection>();

            httpClient.Setup(c => c.Get(It.IsAny<string>(), It.IsAny<Action<IRequest>>(), It.IsAny<bool>()))
                .Returns<string, Action<IRequest>, bool>((url, prepareRequest, isLongRunning) =>
                {
                    prepareRequest(Mock.Of<IRequest>());
                    return tcs.Task;
                });

            connection.SetupGet(c => c.ConnectionToken).Returns("foo");
            connection.SetupGet(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(15));

            var sse = new ServerSentEventsTransport(httpClient.Object);

            var exception = Assert.Throws<AggregateException>(
                () => sse.Start(connection.Object, string.Empty, CancellationToken.None).Wait(TimeSpan.FromSeconds(5)));

            Assert.IsType(typeof(OperationCanceledException), exception.InnerException);
        }
 public RSessionEvaluation(IReadOnlyList<IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken ct) {
     Contexts = contexts;
     _evaluator = evaluator;
     _tcs = new TaskCompletionSource<object>();
     _ct = ct;
     ct.Register(() => _tcs.TrySetCanceled());
 }
Example #6
0
        public IAsyncResult BeginJavascriptCallbackAsync(int browserId, long callbackId, object[] parameters, TimeSpan? timeout, AsyncCallback callback, object state)
        {
            var tcs = new TaskCompletionSource<JavascriptResponse>(state);
            var task = JavascriptCallbackAsync(browserId, callbackId, parameters, timeout);
            task.ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.TrySetException(t.Exception.InnerExceptions);
                }
                else if (t.IsCanceled)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    tcs.TrySetResult(t.Result);
                }

                if (callback != null)
                {
                    callback(tcs.Task);
                }
            });
            return tcs.Task;
        }
Example #7
0
        public Task WaitAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            lock (this.waitersQueue)
            {
                // Make sure we're not already cancelled.
                if (cancellationToken.IsCancellationRequested)
                    throw new TaskCanceledException();

                // If we already have tokens, we can return immediatly.
                if (this.currentCount > 0)
                {
                    this.currentCount--;
                    return CompletedTask;
                }
                
                // Otherwise, create the waiter and queue it.
                var waiter = new TaskCompletionSource<bool>();

                // Register on the cancellation token for the waiter cancellation.
                cancellationToken.Register(() => waiter.TrySetCanceled());

                // Make sure we haven't been canceled in the meantime.
                if (cancellationToken.IsCancellationRequested)
                    throw new TaskCanceledException();
                
                this.waitersQueue.Enqueue(waiter);
                return waiter.Task;
            } 
        }
		private async Task<Auth0User> SendLoginAsync(
			Context context, 
			string connection, 
			bool withRefreshToken,
			string scope)
		{
			// Launch server side OAuth flow using the GET endpoint
			scope = IncreaseScopeWithOfflineAccess(withRefreshToken, scope);

			var tcs = new TaskCompletionSource<Auth0User> ();
			var auth = await this.GetAuthenticator (connection, scope);

			auth.Error += (o, e) =>
			{
				var ex = e.Exception ?? new AuthException (e.Message);
				tcs.TrySetException (ex);
			};

			auth.Completed += (o, e) =>
			{
				if (!e.IsAuthenticated) 
				{
					tcs.TrySetCanceled();
					return;
				}

				this.SetupCurrentUser (e.Account.Properties);
				tcs.TrySetResult (this.CurrentUser);
			};

			Intent intent = auth.GetUI (context);
			context.StartActivity (intent);

			return await tcs.Task;
		}
        public static Task SmoothSetAsync(this FrameworkElement @this, DependencyProperty dp, double targetvalue,
            TimeSpan iDuration, CancellationToken iCancellationToken)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            DoubleAnimation anim = new DoubleAnimation(targetvalue, new Duration(iDuration));
            PropertyPath p = new PropertyPath("(0)", dp);
            Storyboard.SetTargetProperty(anim, p);
            Storyboard sb = new Storyboard();
            sb.Children.Add(anim);
            EventHandler handler = null;
            handler = delegate
            {
                sb.Completed -= handler;
                sb.Remove(@this);
                @this.SetValue(dp, targetvalue);
                tcs.TrySetResult(null);
            };
            sb.Completed += handler;
            sb.Begin(@this, true);

            iCancellationToken.Register(() =>
            {
                double v = (double)@this.GetValue(dp);  
                sb.Stop(); 
                sb.Remove(@this); 
                @this.SetValue(dp, v);
                tcs.TrySetCanceled();
            });

            return tcs.Task;
        }
        private static Task<string> GetInfoAsync(string uri)
        {
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
            var client = new HttpClient();
            var streamTask = client.GetStreamAsync(uri);

            streamTask.ContinueWith(
                _ =>
                {
                    if (streamTask.IsCompleted)
                    {
                        var result = streamTask.Result;
                        var stringResult = new StreamReader(result).ReadToEnd();
                        tcs.TrySetResult(stringResult);
                    }
                    else
                    {
                        if (streamTask.IsCanceled)
                        {
                            tcs.TrySetCanceled();
                        }
                        else
                        {
                            tcs.TrySetException(streamTask.Exception.InnerExceptions);
                        }
                    }
                }
            );

            return tcs.Task;
        }
 public static Task<object> RunWorkerTaskAsync(this BackgroundWorker backgroundWorker)
 {
     var tcs = new TaskCompletionSource<object>();
     RunWorkerCompletedEventHandler handler = null;
     handler = (sender, args) =>
     {
         if (args.Cancelled)
             tcs.TrySetCanceled();
         else if (args.Error != null)
             tcs.TrySetException(args.Error);
         else
             tcs.TrySetResult(args.Result);
     };
     backgroundWorker.RunWorkerCompleted += handler;
     try
     {
         backgroundWorker.RunWorkerAsync();
     }
     catch
     {
         backgroundWorker.RunWorkerCompleted -= handler;
         throw;
     }
     return tcs.Task;
 }
Example #12
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;
        }
        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;
        }
Example #14
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;
 }
 public override Task<object> ReadFromStreamAsync(Type type, HttpContentHeaders headers, Stream stream)
 {
     var tcs = new TaskCompletionSource<object>();
     try {
         var serializer = GetSerializerForType(type);
         if (serializer == null) {
             tcs.TrySetException(new InvalidOperationException(string.Format("Can not create serializer for {0}", type)));
         }
         else {
             Task<object>.Factory.StartNew(() => serializer.Deserialize(stream))
                 .ContinueWith(t => {
                     if (t.IsFaulted) {
                         tcs.TrySetException(t.Exception.GetBaseException());
                     }
                     else if (t.IsCanceled) {
                         tcs.TrySetCanceled();
                     }
                     else {
                         tcs.TrySetResult(t.Result);
                     }
                 }, TaskContinuationOptions.ExecuteSynchronously);
         }
     }
     catch (Exception ex) {
         tcs.TrySetException(ex);
     }
     return tcs.Task;
 }
Example #16
0
 public async Task RunAsync(Graph graph, Stream outputStream, RendererLayouts layout, RendererFormats format, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     var fileName = Path.Combine(graphvizBin, GetRendererLayoutExecutable(layout));
     var arguments = GetRendererFormatArgument(format);
     var startInfo = new ProcessStartInfo
     {
         FileName = fileName,
         Arguments = arguments,
         UseShellExecute = false,
         CreateNoWindow = true,
         RedirectStandardInput = true,
         RedirectStandardOutput = true,
         RedirectStandardError = true
     };
     var tcs = new TaskCompletionSource<object>();
     using (var process = Process.Start(startInfo))
     {
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.Register(() =>
         {
             tcs.TrySetCanceled();
             process.CloseMainWindow();
         });
         using (var standardInput = process.StandardInput)
         {
             graph.WriteTo(standardInput);
         }
         using (var standardOutput = process.StandardOutput)
         {
             await Task.WhenAny(tcs.Task, standardOutput.BaseStream.CopyToAsync(outputStream, 4096, cancellationToken));
         }
     }
     cancellationToken.ThrowIfCancellationRequested();
 }
Example #17
0
 /// MONO completely lacks SmtpClient.SendAsync, so this is a copy -----------------------------------------------------------------------------
 /// <summary>
 /// 
 /// </summary>
 /// <param name="tcs"></param>
 /// <param name="e"></param>
 /// <param name="handler"></param>
 /// <param name="client"></param>
 static void HandleCompletion(TaskCompletionSource<object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
 {
     if (e.UserState == tcs)
     {
         try
         {
             client.SendCompleted -= handler;
         }
         finally
         {
             if (e.Error != null)
             {
                 tcs.TrySetException(e.Error);
             }
             else if (!e.Cancelled)
             {
                 tcs.TrySetResult(null);
             }
             else
             {
                 tcs.TrySetCanceled();
             }
         }
     }
 }
Example #18
0
        public static Task<bool> DownloadFileAsyncCore(WebClient webClient, Uri address, string fileName)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(webClient);
              AsyncCompletedEventHandler handler = null;

              handler = (sender, e) =>
              {
            if (e.UserState != webClient) return;

            if (e.Cancelled) tcs.TrySetCanceled();
            else if (e.Error != null) tcs.TrySetException(e.Error);
            else tcs.TrySetResult(true);

            webClient.DownloadFileCompleted -= handler;
              };

              webClient.DownloadFileCompleted += handler;
              try
              {
            webClient.DownloadFileAsync(address, fileName, webClient);
              }
              catch (Exception ex)
              {
            webClient.DownloadFileCompleted -= handler;
            tcs.TrySetException(ex);
              }

              return tcs.Task;
        }
 public Task ClientCancellationBeforeResponseHeadersReceived_ResetSent()
 {
     ManualResetEvent waitForRequest = new ManualResetEvent(false);
     ManualResetEvent waitForClientCancel = new ManualResetEvent(false);
     ManualResetEvent waitForServerCancel = new ManualResetEvent(false);
     bool serverCancelled = false;
     return RunSessionAsync(
         (AppFunc)(env =>
         {
             TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
             CancellationToken token = (CancellationToken)env["owin.CallCancelled"];
             token.Register(() =>
                 {
                     serverCancelled = true;
                     waitForServerCancel.Set();
                     tcs.TrySetCanceled();
                 });
             waitForRequest.Set();
             return tcs.Task;
         }),
         async (clientSession, serverSession) =>
         {
             CancellationTokenSource clientCancel = new CancellationTokenSource();
             IList<KeyValuePair<string, string>> requestPairs = GenerateHeaders("GET");
             Http2ClientStream clientProtocolStream = clientSession.SendRequest(requestPairs, null, 3, false, clientCancel.Token);
             Task<IList<KeyValuePair<string, string>>> responseTask = clientProtocolStream.GetResponseAsync();
             waitForRequest.WaitOne();
             clientCancel.Cancel();
             Assert.True(responseTask.IsCanceled);
             waitForClientCancel.Set();
             waitForServerCancel.WaitOne();
             Assert.True(serverCancelled);
         });
 }
        /// <summary>
        /// Login a user into an Auth0 application by showing an embedded browser window either showing the widget or skipping it by passing a connection name
        /// </summary>
        /// <param name="owner">The owner window</param>
        /// <param name="connection">Optional connection name to bypass the login widget</param>
        /// <param name="scope">Optional. Scope indicating what attributes are needed. "openid" to just get the user_id or "openid profile" to get back everything.
        /// <remarks>When using openid profile if the user has many attributes the token might get big and the embedded browser (Internet Explorer) won't be able to parse a large URL</remarks>
        /// </param>
        /// <returns>Returns a Task of Auth0User</returns>
        public Task<Auth0User> LoginAsync(IWin32Window owner, string connection = "", string scope = "openid")
        {
            var tcs = new TaskCompletionSource<Auth0User>();
            var auth = this.GetAuthenticator(connection, scope);

            auth.Error += (o, e) =>
            {
                var ex = e.Exception ?? new UnauthorizedAccessException(e.Message);
                tcs.TrySetException(ex);
            };

            auth.Completed += (o, e) =>
            {
                if (!e.IsAuthenticated)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    if (this.State != e.Account.State)
                    {
                        tcs.TrySetException(new UnauthorizedAccessException("State does not match"));
                    }
                    else
                    {
                        this.SetupCurrentUser(e.Account);
                        tcs.TrySetResult(this.CurrentUser);
                    }
                }
            };

            auth.ShowUI(owner);

            return tcs.Task;
        }
        /// <summary>
        /// Download a file into a stream.
        /// </summary>
        /// <param name="path">relative or absolute uri to the file to be downloaded.</param>
        /// <param name="ct">a cancellation token</param>
        /// <param name="progress">a progress event callback handler</param>
        public Task<LiveDownloadOperationResult> DownloadAsync(
            string path,
            CancellationToken ct,
            IProgress<LiveOperationProgress> progress)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(path, "path");

            var tcs = new TaskCompletionSource<LiveDownloadOperationResult>();
            var op = new DownloadOperation(
                this,
                this.GetResourceUri(path, ApiMethod.Download),
                progress,
                null);

            op.OperationCompletedCallback = (LiveDownloadOperationResult result) =>
            {
                if (result.IsCancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (result.Error != null)
                {
                    tcs.TrySetException(result.Error);
                }
                else
                {
                    tcs.TrySetResult(result);
                }
            };

            ct.Register(op.Cancel);
            op.Execute();

            return tcs.Task;
        }
 public Task<Stream> DownloadFile(Uri url)
 {
     var tcs = new TaskCompletionSource<Stream>();
     var wc = new WebClient();
     wc.OpenReadCompleted += (s, e) =>
     {
         if (e.Error != null)
         {
             tcs.TrySetException(e.Error);
             return;
         }
         else if (e.Cancelled)
         {
             tcs.TrySetCanceled();
             return;
         }
         else tcs.TrySetResult(e.Result);
     };
     wc.OpenReadAsync(url);
     MessageBoxResult result = MessageBox.Show("Started downloading media. Do you like to stop the download ?", "Purpose Color", MessageBoxButton.OKCancel);
     if( result == MessageBoxResult.OK )
     {
         progress.HideProgressbar();
         wc.CancelAsync();
         return null;
     }
     return tcs.Task;
 }
Example #23
0
        public static Task<int> GetIntAsync(CancellationToken token = default(CancellationToken))
        {
            var tcs = new TaskCompletionSource<int>();

            if (token.IsCancellationRequested)
            {
                tcs.SetCanceled();
                return tcs.Task;
            }

            var timer = new System.Timers.Timer(3000);
            timer.AutoReset = false;
            timer.Elapsed += (s, e) =>
            {
                tcs.TrySetResult(10);
                timer.Dispose();
            };

            if (token.CanBeCanceled)
            {
                token.Register(() => {
                    tcs.TrySetCanceled();
                    timer.Dispose();
                });
            }

            timer.Start();
            return tcs.Task;
        }
        /// <summary>
        /// A Task extension method that converts this object to an IAsyncResult.
        /// </summary>
        /// <remarks>
        /// Mark, 19/06/2012.
        /// Props to Stephen Toub for this blog post:
        /// http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx
        /// </remarks>
        /// <param name="task"> The task to act on.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state.</param>
        /// <returns>
        /// The given data converted to an IAsyncResult-y Task.
        /// </returns>
        public static Task ToApm(this Task task, AsyncCallback callback, object state)
        {
            task = task ?? MakeCompletedTask();
            var tcs = new TaskCompletionSource<object>();
            task.ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        tcs.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        tcs.TrySetCanceled();
                    }
                    else
                    {
                        tcs.TrySetResult(null);
                    }

                    if (callback != null)
                    {
                        callback(tcs.Task);
                    }
                }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
            return tcs.Task;
        }
		public void DecodeRefreshToken() {
			var refreshTokenSource = new TaskCompletionSource<string>();
			var coordinator = new OAuth2Coordinator<WebServerClient>(
				AuthorizationServerDescription,
				AuthorizationServerMock,
				new WebServerClient(AuthorizationServerDescription),
				client => {
					try {
						var authState = new AuthorizationState(TestScopes) {
							Callback = ClientCallback,
						};
						client.PrepareRequestUserAuthorization(authState).Respond();
						var result = client.ProcessUserAuthorization();
						Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
						Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
						refreshTokenSource.SetResult(result.RefreshToken);
					} catch {
						refreshTokenSource.TrySetCanceled();
					}
				},
				server => {
					var request = server.ReadAuthorizationRequest();
					Assert.That(request, Is.Not.Null);
					server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
					server.HandleTokenRequest().Respond();
					var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result);
					Assert.That(authorization, Is.Not.Null);
					Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername));
				});
			coordinator.Run();
		}
Example #26
0
        /// <summary>
        /// Get's the primary workspace asynchronously.
        /// </summary>
        public static Task<Workspace> GetWorkspaceAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            using (s_registryGate.DisposableWrite())
            {
                if (s_primaryWorkspace != null)
                {
                    return Task<Workspace>.FromResult(s_primaryWorkspace);
                }
                else
                {
                    var taskSource = new TaskCompletionSource<Workspace>();

                    if (cancellationToken.CanBeCanceled)
                    {
                        try
                        {
                            var registration = cancellationToken.Register(() =>
                            {
                                taskSource.TrySetCanceled();
                            });

                            taskSource.Task.ContinueWith(_ => registration.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                        }
                        catch
                        {
                        }
                    }

                    s_primaryWorkspaceTaskSourceList.Add(taskSource);
                    return taskSource.Task;
                }
            }
        }
Example #27
0
        public async void ConnectRetriesOnError()
        {
            int invokationCount = 0;
            var wh = new ManualResetEventSlim();
            var redisConnection = GetMockRedisConnection();

            var tcs = new TaskCompletionSource<object>();
            tcs.TrySetCanceled();

            redisConnection.Setup(m => m.ConnectAsync(It.IsAny<string>(), It.IsAny<TraceSource>())).Returns<string, TraceSource>((connectionString, trace) =>
            {
                if (++invokationCount == 2)
                {
                    wh.Set();
                    return Task.FromResult(0);
                }
                else
                {
                    return tcs.Task;
                }
            });

            var redisMessageBus = new RedisMessageBus(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty),
            redisConnection.Object, false);

            await redisMessageBus.ConnectWithRetry();

            Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
            Assert.Equal(RedisMessageBus.State.Connected, redisMessageBus.ConnectionState);
        }
Example #28
0
		internal static Task ToApm(this Task task, AsyncCallback callback, object state) {
			if (task == null) {
				throw new ArgumentNullException("task");
			}

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

					if (callback != null) {
						callback(tcs.Task);
					}
				},
				CancellationToken.None,
				TaskContinuationOptions.None,
				TaskScheduler.Default);

			return tcs.Task;
		}
        public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken = default(CancellationToken)) {
            // Validate arguments
            if (factory == null)
                throw new ArgumentNullException(nameof(factory));
            if (millisecondsDelay < 0)
                throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));

            // Create the timed task
            var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
            var ctr = default(CancellationTokenRegistration);

            // Create the timer but don't start it yet.  If we start it now,
            // it might fire before ctr has been set to the right registration.
            var timer = new Timer(self => {
                // Clean up both the cancellation token and the timer, and try to transition to completed
                ctr.Dispose();
                (self as Timer)?.Dispose();
                tcs.TrySetResult(null);
            }, null, -1, -1);

            // Register with the cancellation token.
            if (cancellationToken.CanBeCanceled) {
                // When cancellation occurs, cancel the timer and try to transition to canceled.
                // There could be a race, but it's benign.
                ctr = cancellationToken.Register(() => {
                    timer.Dispose();
                    tcs.TrySetCanceled();
                });
            }

            // Start the timer and hand back the task...
            timer.Change(millisecondsDelay, Timeout.Infinite);
            return tcs.Task;
        }
        protected override sealed IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var cts = new CancellationTokenSource();
            context.UserState = cts;

            var tcs = new TaskCompletionSource<bool>(state);

            ExecuteAsync(context, cts.Token).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.TrySetResult(false);
                    tcs.TrySetException(t.Exception.InnerExceptions);
                }
                else if (t.IsCanceled)
                {
                    tcs.TrySetResult(false);
                    tcs.TrySetCanceled();
                }
                else tcs.TrySetResult(true);

                if (callback != null)
                    callback(tcs.Task);
            });
            return tcs.Task;
        }
Example #31
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _outputPromise?.TrySetCanceled();
                    if (Task)
                    {
                        Task.Enabled = false;
                        Task.Dispose();
                    }
                    FlaxEngine.Object.Destroy(Task);
                    Task = null;
                }

                _disposedValue = true;
            }
        }
Example #32
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _socket?.Dispose();
            _receiveSocketAsyncEventArgs.Dispose();
            _sendSocketAsyncEventArgs.Dispose();
            _currentReceiveTaskCompletionSource?.TrySetCanceled();
            _currentSendTaskCompletionSource?.TrySetCanceled();

            _socket = null;
            _currentReceiveTaskCompletionSource = null;
            _currentSendTaskCompletionSource    = null;

            _disposed = true;
        }
Example #33
0
        /// <inheritdoc />
        public async Task <INetworkStream> AcceptNetworkStreamAsync(
            string certificateName,
            bool noDelay,
            CancellationToken token)
        {
            if (!string.IsNullOrWhiteSpace(certificateName))
            {
                throw new NotSupportedException(
                          "Authenticated server connections not supported on Windows Universal Platform.");
            }

            await(_streamTcs?.Task ?? Task.FromResult(default(INetworkStream))).ConfigureAwait(false);
            _tokenRegistration.Dispose();

            _streamTcs         = new TaskCompletionSource <INetworkStream>();
            _tokenRegistration = token.Register(() => _streamTcs?.TrySetCanceled(token), false);

            return(await _streamTcs.Task);
        }
Example #34
0
        // AuthenticationManager.ChallengeHandler function that prompts the user for login information to create a credential.
        private Task <Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            // Ignore token or certificate challenges (needs additional code and UI).
            if (info.AuthenticationType != AuthenticationType.NetworkCredential)
            {
                Console.WriteLine("Skipped authentication for " + info.ServiceUri.Host);
                return(null);
            }

            // See if authentication is already in progress.
            if (_loginTaskCompletionSrc != null)
            {
                return(null);
            }

            // Create a new TaskCompletionSource for the login operation.
            // Passing the CredentialRequestInfo object to the constructor will make it available from its AsyncState property.
            _loginTaskCompletionSrc = new TaskCompletionSource <Credential>(info);

            // Create a dialog (fragment) with login controls.
            LoginDialogFragment enterLoginDialog = new LoginDialogFragment();

            // Handle the login and the cancel events.
            enterLoginDialog.OnLoginClicked  += LoginClicked;
            enterLoginDialog.OnLoginCanceled += (s, e) =>
            {
                _loginTaskCompletionSrc?.TrySetCanceled();
                _loginTaskCompletionSrc = null;
            };

            // Begin a transaction to show a UI fragment (the login dialog).
            FragmentTransaction transax = FragmentManager.BeginTransaction();

            enterLoginDialog.Show(transax, "login");

            // Return the login task, the result will be ready when completed (user provides login info and clicks the "Login" button).
            return(_loginTaskCompletionSrc.Task);
        }
        /// <summary>
        /// Requests an app review.
        /// </summary>
        public async Task RequestReview(bool testMode)
        {
            tcs?.TrySetCanceled();
            tcs = new TaskCompletionSource <bool>();

            if (testMode)
            {
                manager = new FakeReviewManager(Application.Context);
            }
            else
            {
                manager = ReviewManagerFactory.Create(Application.Context);
            }

            forceReturn = false;
            var request = manager.RequestReviewFlow();

            request.AddOnCompleteListener(this);
            await tcs.Task;

            manager.Dispose();
            request.Dispose();
        }
        private async Task <RpcPipelineClient?> ResetConnectionAsync(RpcConnectionState state, Exception?ex)
        {
            TaskCompletionSource <RpcPipelineClient>?connectionTcs;
            RpcPipelineClient?connectedClient;

            lock (this.SyncRoot)
            {
                if (this.ConnectionState == RpcConnectionState.Disconnected)
                {
                    // Already disconnected
                    Debug.Assert(this.connectedClient == null);
                    return(null);
                }

                connectedClient      = this.connectedClient;
                this.connectedClient = null;


                connectionTcs      = this.connectionTcs;
                this.connectionTcs = null;

                this.OnConnectionResetSynchronized();

                this.SetConnectionState(state);
            }

            connectionTcs?.TrySetCanceled();

            // TODO: wait for unfinished frames?
            if (connectedClient != null)
            {
                connectedClient.ReceiveLoopFaulted -= this.ConnectedClient_ReceiveLoopFaulted;
                await connectedClient.CloseAsync(TranslateConnectionException(ex, state)).ContextFree();
            }

            return(connectedClient);
        }
Example #37
0
        /// <summary>
        /// Begins to get messages of specified member asynchronously.
        /// </summary>
        /// <param name="teamName">Name of the Scrum team.</param>
        /// <param name="memberName">Name of the member.</param>
        /// <param name="lastMessageId">ID of last message the member received.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <returns>
        /// List of messages.
        /// </returns>
        public Task <IList <Message> > GetMessages(string teamName, string memberName, long lastMessageId, CancellationToken cancellationToken)
        {
            return(InvokeOperation(async() =>
            {
                await EnsureConnected(cancellationToken);

                try
                {
                    Task <IList <Message> > getMessagesTask;

                    lock (_getMessagesLock)
                    {
                        if (_getMessagesTask != null)
                        {
                            throw new InvalidOperationException("GetMessages is already in progress.");
                        }

                        _getMessagesTask = new TaskCompletionSource <IList <Message> >();
                        getMessagesTask = _getMessagesTask.Task;
                    }

                    await _hubConnection.InvokeAsync("GetMessages", teamName, memberName, lastMessageId, cancellationToken);

                    var result = await getMessagesTask;
                    ScrumTeamMapper.ConvertMessages(result);
                    return result;
                }
                finally
                {
                    lock (_getMessagesLock)
                    {
                        _getMessagesTask?.TrySetCanceled();
                        _getMessagesTask = null;
                    }
                }
            }));
        }
Example #38
0
        // Aqui fazemos a animaçao do botao se tornar o ActivityIndicator
        private async Task ShowLoadingAsync()
        {
            // Aqui definimos que a animação de loading vai começar
            // e deve ser aguardada antes de iniciar outra animaçao
            loadingAnimationTask?.TrySetCanceled();
            loadingAnimationTask = new TaskCompletionSource <bool>();

            try
            {
                // Tornamos visivel o frame do login que usa o mesmo tamanho/formato do botão
                // Utilizei aqui o Frame, ao inves de manipular diretamente o botão porque achei mais facil
                // de alterar sem precisar ocultar texto ou outrar propriedaes do botão
                LoginFrame.IsVisible = true;

                // Criamos uma animaçao onde o frame vai ficar com a cor de fundo igual a do botao
                // e o botão faz um Fade, ficando totalmente transparente, ficando assim
                // apenas visivel o frame que contém o ActivityIndicator dentro
                _ = await Task.WhenAll(
                    LoginFrame.BackgroundColorTo(LoginButton.BackgroundColor, 50),
                    LoginButton.FadeTo(0, 100));

                // Calculamos a nova posição do frame, após reduzir a largura dele para 50
                var anchorX = (LoginFrame.Width / 2) - (LOADING_WIDTH / 2);

                // Criamos então a posição/tamanho final do frame (layout)
                var rectTo = new Rectangle(anchorX, LoginFrame.Y, LOADING_WIDTH, LoginFrame.Height);

                // Fazemos a transição que vai manipular a posicão/tamanho do frame
                _ = await LoginFrame.LayoutTo(rectTo, easing : Easing.SpringOut);
            }
            finally
            {
                // Por fim definimos que a animação de loading foi finalizada
                loadingAnimationTask.SetResult(true);
            }
        }
Example #39
0
        public async Task <AuthResult> Authorize(ContentView authViewContainer)
        {
            if (authViewContainer == null)
            {
                throw new ArgumentNullException();
            }

            _authViewContainer      = authViewContainer;
            _authWebView.Navigated += OnAuthWebViewNavigated;
            _storedContent          = authViewContainer.Content;

            _authWebViewWaiter?.TrySetCanceled();
            _authWebViewWaiter = new TaskCompletionSource <AuthResult>();

            authViewContainer.Content = _authWebView;

            var webAuthResult = await _authWebViewWaiter.Task;

            _storedContent          = null;
            _authViewContainer      = null;
            _authWebView.Navigated -= OnAuthWebViewNavigated;

            return(webAuthResult);
        }
Example #40
0
 private void OnCanceled()
 {
     // Notify anyone listening that we're never going to be active
     _isImplicitlyActiveSource.TrySetCanceled();
 }
Example #41
0
 public override void Disappeared()
 {
     _tcs?.TrySetCanceled();
     base.Disappeared();
 }
Example #42
0
 void TryCancel()
 {
     speechSynthesizer?.StopSpeaking(AVSpeechBoundary.Word);
     currentSpeak?.TrySetCanceled();
 }
        public async Task PostChat(BasicChatPostObject chatPostObject)
        {
            if (!CanPost)
            {
                throw new NotSupportedException("Posting is not supprted on this ChatCollectService");
            }

            if (lastThreadTag == null || lastResNum == -1 || socketStream == null || postingResult != null)
            {
                throw new ChatPostException("コメントが投稿できる状態にありません。しばらく待ってから再試行してください。");
            }

            //postkey取得
            string postKey = await httpClient.GetStringAsync($"/api/v2/getpostkey?thread={lastThreadTag.Thread}&block_no={(lastResNum + 1) / 100}");

            postKey = postKey.Substring(postKey.IndexOf('=') + 1);

            // vposは10msec単位 サーバ時刻を基準に計算
            int vpos = (int)(lastThreadTag.ServerTime - lastThreadTag.Thread) * 100 + (int)((getDateTimeJstNow() - lastThreadTag.ReceivedTime).Value.TotalMilliseconds) / 10;

            string mail = (chatPostObject as ChatPostObject)?.Mail ?? "";

            XElement postXml = new XElement("chat",
                                            new XAttribute("thread", lastThreadTag.Thread),
                                            new XAttribute("ticket", lastThreadTag.Ticket),
                                            new XAttribute("vpos", vpos),
                                            new XAttribute("postkey", postKey),
                                            new XAttribute("mail", mail),
                                            new XAttribute("user_id", userId),
                                            new XAttribute("premium", isPremium ? "1" : "0"),
                                            new XAttribute("staff", "0"),
                                            new XText(chatPostObject.Text));

            byte[] postData = utf8Encoding.GetBytes(postXml.ToString(SaveOptions.DisableFormatting) + "\0"); //最後にnull文字が必要

            postingResult = new TaskCompletionSource <int>();                                                //コメント受信側で投稿の結果応答を入れてもらう
            await socketStream.WriteAsync(postData, 0, postData.Length);

            int result;

            using (new Timer((_) => postingResult?.TrySetCanceled(), null, 5000, Timeout.Infinite))//結果応答を5秒以内に受信できなければタイムアウト
            {
                try
                {
                    await postingResult.Task;//結果が来るまで待つ
                    result = postingResult.Task.Result;
                }
                catch (OperationCanceledException)
                {
                    //タイムアウトした
                    throw new ChatPostException("コメントを送信しましたがサーバーから結果応答を受信できませんでした。");
                }
                finally
                {
                    postingResult = null;
                }
            }

            if (result != 0)
            {
                throw new ChatPostException($"コメント投稿でサーバーからエラーが返されました。エラーコードは'{result}'です。");
            }
        }
        /// <summary>
        /// Plays audio using Vector's speakers.
        /// </summary>
        /// <param name="stream">16bit audio byte stream containing 1 channel.</param>
        /// <param name="frameRate">The frame rate between 8000-16025 hz.</param>
        /// <param name="volume">The audio playback volume level (0-100).</param>
        /// <returns>A task that represents the asynchronous operation; the task result contains the result from the robot.</returns>
        public async Task <PlaybackResult> PlayStream(Stream stream, uint frameRate, uint volume = 50)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            if (frameRate < 8000 || frameRate > 16025)
            {
                throw new ArgumentOutOfRangeException(nameof(volume), "Volume must be between 0 and 100");
            }
            if (volume > 100)
            {
                throw new ArgumentOutOfRangeException(nameof(volume), "Volume must be between 0 and 100");
            }

            playbackResult?.TrySetCanceled();
            playbackResult = new TaskCompletionSource <PlaybackResult>();

            // Send preparation message
            await playbackFeed.Call(new ExternalAudioStreamRequest()
            {
                AudioStreamPrepare = new ExternalAudioStreamPrepare()
                {
                    AudioFrameRate = frameRate,
                    AudioVolume    = volume
                }
            }).ConfigureAwait(false);

            var startTime = DateTime.Now;
            int dataCount = 0;

            var chunkBuffer = new byte[MaxRobotAudioChunkSize];

            while (playbackFeed.IsActive)
            {
                int chunkSize = await stream.ReadAsync(chunkBuffer, 0, MaxRobotAudioChunkSize).ConfigureAwait(false);

                if (chunkSize == 0)
                {
                    break;
                }
                dataCount += chunkSize;

                await playbackFeed.Call(new ExternalAudioStreamRequest()
                {
                    AudioStreamChunk = new ExternalAudioStreamChunk()
                    {
                        AudioChunkSizeBytes = (uint)chunkSize,
                        AudioChunkSamples   = Google.Protobuf.ByteString.CopyFrom(chunkBuffer, 0, chunkSize)
                    }
                }).ConfigureAwait(false);

                if (chunkSize != MaxRobotAudioChunkSize)
                {
                    break;
                }

                var elapsed           = DateTime.Now.Subtract(startTime).TotalSeconds;
                var expectedDataCount = elapsed * frameRate * 2;
                var timeAhead         = (dataCount - expectedDataCount) / frameRate;
                if (timeAhead > 1.0)
                {
                    await Task.Delay((int)((timeAhead - 0.5) * 1000)).ConfigureAwait(false);
                }
            }

            if (playbackFeed.IsActive)
            {
                await playbackFeed.Call(new ExternalAudioStreamRequest()
                {
                    AudioStreamComplete = new ExternalAudioStreamComplete()
                }).ConfigureAwait(false);
            }

            return(await playbackResult.Task.ConfigureAwait(false));
        }
        /// <summary>
        /// Gets position async with specified parameters
        /// </summary>
        /// <param name="timeout">Timeout to wait, Default Infinite</param>
        /// <param name="cancelToken">Cancelation token</param>
        /// <param name="includeHeading">If you would like to include heading</param>
        /// <returns>Position</returns>
        public async Task <Position> GetPositionAsync(TimeSpan?timeout, CancellationToken?cancelToken = null, bool includeHeading = false)
        {
#if __IOS__
            var permission    = Permission.Location;
            var hasPermission = await CheckPermissions(permission);

            if (!hasPermission)
            {
                throw new GeolocationException(GeolocationError.Unauthorized);
            }
#endif

            var timeoutMilliseconds = timeout.HasValue ? (int)timeout.Value.TotalMilliseconds : Timeout.Infinite;

            if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive or Timeout.Infinite");
            }

            if (!cancelToken.HasValue)
            {
                cancelToken = CancellationToken.None;
            }

            TaskCompletionSource <Position> tcs;
            if (!IsListening)
            {
                var m = GetManager();
                m.DesiredAccuracy = DesiredAccuracy;
#if __IOS__
                // permit background updates if background location mode is enabled
                if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                {
                    var backgroundModes = NSBundle.MainBundle.InfoDictionary[(NSString)"UIBackgroundModes"] as NSArray;
                    var allow           = backgroundModes != null && (backgroundModes.Contains((NSString)"Location") || backgroundModes.Contains((NSString)"location"));

                    if (allow)
                    {
                        allow = await CheckPermissions(Permission.LocationAlways);
                    }
                    m.AllowsBackgroundLocationUpdates = allow;
                }

                // always prevent location update pausing since we're only listening for a single update.
                if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
                {
                    m.PausesLocationUpdatesAutomatically = false;
                }
#endif

                tcs = new TaskCompletionSource <Position>(m);
                var singleListener = new GeolocationSingleUpdateDelegate(m, DesiredAccuracy, includeHeading, timeoutMilliseconds, cancelToken.Value);
                m.Delegate = singleListener;

#if __IOS__ || __MACOS__
                m.StartUpdatingLocation();
#elif __TVOS__
                m.RequestLocation();
#endif


#if __IOS__
                if (includeHeading && SupportsHeading)
                {
                    m.StartUpdatingHeading();
                }
#endif

                return(await singleListener.Task);
            }


            tcs = new TaskCompletionSource <Position>();
            if (lastPosition == null)
            {
                if (cancelToken != CancellationToken.None)
                {
                    cancelToken.Value.Register(() => tcs.TrySetCanceled());
                }

                EventHandler <PositionErrorEventArgs> gotError = null;
                gotError = (s, e) =>
                {
                    tcs.TrySetException(new GeolocationException(e.Error));
                    PositionError -= gotError;
                };

                PositionError += gotError;

                EventHandler <PositionEventArgs> gotPosition = null;
                gotPosition = (s, e) =>
                {
                    tcs.TrySetResult(e.Position);
                    PositionChanged -= gotPosition;
                };

                PositionChanged += gotPosition;
            }
            else
            {
                tcs.SetResult(lastPosition);
            }


            return(await tcs.Task);
        }
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            // Try to cancel any existing authentication task.
            _taskCompletionSource?.TrySetCanceled();

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();
#if __ANDROID__ || __IOS__
#if __ANDROID__
            // Get the current Android Activity.
            Activity activity = (Activity)ArcGISRuntime.Droid.MainActivity.Instance;
#endif
#if __IOS__
            // Get the current iOS ViewController.
            UIViewController viewController = null;
            Device.BeginInvokeOnMainThread(() => { viewController = UIApplication.SharedApplication.KeyWindow.RootViewController; });
#endif
            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
#if __IOS__
                    // Dismiss the OAuth UI when complete.
                    viewController.DismissViewController(true, null);
#endif

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    authenticator.OnCancelled();
                }
                finally
                {
                    // Dismiss the OAuth login.
#if __ANDROID__
                    activity.FinishActivity(99);
#endif
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    _taskCompletionSource?.TrySetCanceled();
#if __ANDROID__
                    activity.FinishActivity(99);
#endif
                }

                // Cancel authentication.
                authenticator.OnCancelled();
            };

            // Present the OAuth UI so the user can enter user name and password.
#if __ANDROID__
            Android.Content.Intent intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);
#endif
#if __IOS__
            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            Device.BeginInvokeOnMainThread(() => { viewController.PresentViewController(authenticator.GetUI(), true, null); });
#endif
#endif // (If Android or iOS)
            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
Example #47
0
 /// <summary>
 /// Finaliza o stream e libera os recursos alocados.
 /// As leituras pendentes são canceladas.
 /// </summary>
 void IDisposable.Dispose()
 {
     m_MoveNext?.TrySetCanceled();
     m_MoveNext = null;
 }
Example #48
0
        /// <inheritdoc/>
        public async Task StartAsync()
        {
            if (_isActive)
            {
                return;
            }

            _isActive  = true;
            _queue     = new ConcurrentQueue <ReqInfo>();
            _startStop = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
            _          = Task.Run(async() =>
            {
                while (true)
                {
                    if (!_queue.TryDequeue(out var data))
                    {
                        if (await Task.WhenAny(Task.Delay(100), _startStop.Task) == _startStop.Task)
                        {
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (!data.Background)
                    {
                        if (data.Timeout !.IsCompleted)
                        {
                            continue;
                        }
                    }
                    _rsp?.TrySetCanceled();
                    _rsp = new TaskCompletionSource <TRsp>(TaskCreationOptions.RunContinuationsAsynchronously);
                    try
                    {
                        await _port.SendAsync(data.Req);
                        if (OnSentData is not null)
                        {
                            try
                            {
                                await OnSentData(data.Req);
                            }
                            catch { }
                        }
                    }
                    catch (Exception ex)
                    {
                        data.Rsp.TrySetException(new TilesSendException("", ex));
                        continue;
                    }
                    if (data.NeedRsp)
                    {
                        var tasks = new List <Task>()
                        {
                            _rsp.Task, _startStop.Task
                        };
                        if (data.Background)
                        {
                            data.Timeout = Task.Delay(data.Time);
                            tasks.Add(data.Timeout);
                        }
                        var task = await Task.WhenAny(tasks);
                        if (task == _startStop.Task)
                        {
                            data.Rsp.TrySetException(new CrowStopWorkingException());
                        }
                        else if (task == _rsp.Task)
                        {
                            var rsp = await _rsp.Task;
                            data.Rsp.TrySetResult(rsp);
                            if (OnReceivedData is not null)
                            {
                                try
                                {
                                    await OnReceivedData(rsp);
                                }
                                catch { }
                            }
                        }
                        else if (data.Background && (task == data.Timeout))
                        {
                            data.Rsp.TrySetException(new TimeoutException($"background timeout"));
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        data.Rsp.TrySetResult(default);
Example #49
0
 public void ConnectionClosed()
 {
     _tcs?.TrySetCanceled();
 }
Example #50
0
        async Task Speak(CancellationToken?cancelToken)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                //return Task.CompletedTask;
                return;
            }

            if (language.HasValue && !string.IsNullOrWhiteSpace(language.Value.Language))
            {
                Locale locale = null;
                if (!string.IsNullOrWhiteSpace(language.Value.Country))
                {
                    locale = new Locale(language.Value.Language, language.Value.Country);
                }
                else
                {
                    locale = new Locale(language.Value.Language);
                }

                var result = textToSpeech.IsLanguageAvailable(locale);
                if (result == LanguageAvailableResult.CountryAvailable)
                {
                    textToSpeech.SetLanguage(locale);
                }
                else
                {
                    Console.WriteLine("Locale: " + locale + " was not valid, setting to default.");
                    SetDefaultLanguage();
                }
            }
            else
            {
                SetDefaultLanguage();
            }

            var tcs  = new TaskCompletionSource();
            var flag = new AsyncManualResetEvent();

            var utteranceID = Guid.NewGuid().ToString();
            var doneTask    = listener.ListenFor(utteranceID);

            cancelToken?.Register(() =>
            {
                textToSpeech.Stop();
                tcs?.TrySetCanceled();
                listener?.completionSources?[utteranceID]?.TrySetCanceled();
            });

            var utteranceProgressListenerDictionary = new Dictionary <string, string>();

            utteranceProgressListenerDictionary.Add(Android.Speech.Tts.TextToSpeech.Engine.KeyParamUtteranceId, utteranceID);
            utteranceProgressListenerDictionary.Add(Android.Speech.Tts.TextToSpeech.Engine.KeyParamVolume, volume.ToString());

            textToSpeech.SetPitch(pitch);
            textToSpeech.SetSpeechRate(speakRate);

            //textToSpeech.SetOnUtteranceProgressListener(new TtsProgressListener(flag));

            //var bundle = new Android.OS.Bundle();
            //bundle.PutFloat(Android.Speech.Tts.TextToSpeech.Engine.KeyParamVolume, 1.0f);

#pragma warning disable CS0618 // Type or member is obsolete
            //textToSpeech.Speak(text, QueueMode.Flush, bundle, text);
            textToSpeech.Speak(text, QueueMode.Flush, utteranceProgressListenerDictionary);
#pragma warning restore CS0618 // Type or member is obsolete

            //return tcs.Task;
            //return Task.WhenAny(tcs.Task, flag.WaitAsync());
            //return listener.IsDone();

            //int i = 0;
            //var sw = new System.Diagnostics.Stopwatch();
            //sw.Start();
            //while (doneTask.Status != TaskStatus.RanToCompletion)
            //{
            //    Task.Delay(100).Wait(101);
            //    //await Task.Delay(100, CancellationTokenHelpers.Timeout(105).Token);
            //    Android.Util.Log.Debug("Speech", $"Iteration {i}, {sw.ElapsedMilliseconds} ms - status is {doneTask.Status}.");
            //    i++;
            //}

            //return doneTask;
            await doneTask;
        }
Example #51
0
 public void Canceled()
 {
     tcsSignIn?.TrySetCanceled();
 }
Example #52
0
 public void Cancel()
 {
     tcs?.TrySetCanceled();
 }
        private void InternalExecuteQueryAsync(AseCommand command, AseTransaction transaction, TaskCompletionSource <DbDataReader> readerSource, CommandBehavior behavior)
        {
            AssertExecutionStart();
#if ENABLE_SYSTEM_DATA_COMMON_EXTENSIONS
            var dataReader = new AseDataReader(command, behavior, EventNotifier);
#else
            var dataReader = new AseDataReader(behavior, EventNotifier);
#endif
            try
            {
                SendPacket(new NormalPacket(BuildCommandTokens(command, behavior)));

                var envChangeTokenHandler         = new EnvChangeTokenHandler(_environment, _parameters.Charset);
                var doneHandler                   = new DoneTokenHandler();
                var dataReaderHandler             = new StreamingDataReaderTokenHandler(readerSource, dataReader, EventNotifier);
                var responseParameterTokenHandler = new ResponseParameterTokenHandler(command.AseParameters);

                Logger.Instance?.WriteLine();
                Logger.Instance?.WriteLine("---------- Receive Tokens ----------");
                try
                {
#if ENABLE_ARRAY_POOL
                    using (var tokenStream = new TokenReceiveStream(_networkStream, _environment, _arrayPool))
#else
                    using (var tokenStream = new TokenReceiveStream(_networkStream, _environment))
#endif
                    {
                        foreach (var receivedToken in _reader.Read(tokenStream, _environment))
                        {
                            if (envChangeTokenHandler.CanHandle(receivedToken.Type))
                            {
                                envChangeTokenHandler.Handle(receivedToken);
                            }

                            if (doneHandler.CanHandle(receivedToken.Type))
                            {
                                doneHandler.Handle(receivedToken);
                            }

                            if (dataReaderHandler.CanHandle(receivedToken.Type))
                            {
                                dataReaderHandler.Handle(receivedToken);
                            }

                            if (responseParameterTokenHandler.CanHandle(receivedToken.Type))
                            {
                                responseParameterTokenHandler.Handle(receivedToken);
                            }
                        }
                    }
                }
                finally
                {
                    LastActive = DateTime.UtcNow;
                }

                // This tells the data reader to stop waiting for more results.
                dataReader.CompleteAdding();

                AssertExecutionCompletion(doneHandler);

                if (transaction != null && doneHandler.TransactionState == TranState.TDS_TRAN_ABORT)
                {
                    transaction.MarkAborted();
                }

                dataReaderHandler.AssertNoErrors();

                if (doneHandler.Canceled)
                {
                    readerSource.TrySetCanceled(); // If we have already begun returning data, then this will get lost.
                }
                else
                {
                    readerSource.TrySetResult(dataReader); // Catchall - covers cases where no data is returned by the server.
                }
            }
            catch (Exception ex)
            {
                readerSource.TrySetException(ex); // If we have already begun returning data, then this will get lost.
            }
        }
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            // Try to cancel any existing authentication process.
            _taskCompletionSource?.TrySetCanceled();

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            _auth = new OAuth2Authenticator(
                clientId: _appClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: new Uri(_oAuthRedirectUrl))
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            _auth.Completed += (o, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete.
                    InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); });

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    _auth.OnCancelled();
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            _auth.Error += (o, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    _taskCompletionSource?.TrySetCanceled();
                }

                // Cancel authentication.
                _auth.OnCancelled();
                _auth = null;
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(_auth.GetUI(), true, null); });

            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
Example #55
0
        public void Cancel()
        {
            TaskCompletionSource?.TrySetCanceled();

            ContainedProcess.Kill();
        }
Example #56
0
 public Task <Process> WaitUntilGameAsync(CancellationToken cancellation)
 {
     _processTcs = new TaskCompletionSource <Process>();
     cancellation.Register(() => _processTcs?.TrySetCanceled());
     return(_processTcs.Task);
 }
Example #57
0
 void SetDropCanceled()
 {
     dropUiPayTcs?.TrySetCanceled();
 }
 public static void Cancelled()
 => tcsResponse?.TrySetCanceled();
Example #59
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            // Try to cancel any existing authentication task.
            _taskCompletionSource?.TrySetCanceled();

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Get the current Android Activity.
            Activity activity = this;

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    authenticator.OnCancelled();
                }
                finally
                {
                    // Dismiss the OAuth login.
                    activity.FinishActivity(99);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
                        activity.FinishActivity(99);
                    }
                }

                // Cancel authentication.
                authenticator.OnCancelled();
            };

            // Present the OAuth UI so the user can enter user name and password.
            Android.Content.Intent intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);

            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
Example #60
0
 public void OnCancelled()
 {
     HasCompleted = true;
     tokenTask?.TrySetCanceled();
 }