public Task CloseAsync()
 {
     var tcsShutdown = new TaskCompletionSource<object>();
     this.Task.ContinueWith(tpc =>
     {
         if (!tpc.IsFaulted)
         {
             this.PeerConnection.CloseAsync().ContinueWith(t =>
             {
                 if (!t.IsFaulted)
                 {
                     tcsShutdown.SetResult(null); // complete
                 }
                 else
                 {
                     tcsShutdown.SetException(new TaskFailedException("Could not close (1).", t));
                 }
             });
         }
         else
         {
             tcsShutdown.SetException(new TaskFailedException("Could not close (2).", tpc));
         }
     });
     return tcsShutdown.Task;
 }
        private static void CopyAsync(byte[] buffer, FileStream inputStream, Stream outputStream, TaskCompletionSource<object> tcs)
        {
            inputStream.ReadAsync(buffer).Then(read =>
            {
                if (read > 0)
                {
                    outputStream.WriteAsync(buffer, 0, read)
                                .Then(() => CopyAsync(buffer, inputStream, outputStream, tcs))
                                .Catch(ex =>
                                {
                                    inputStream.Close();
                                    outputStream.Close();
                                    tcs.SetException(ex);
                                });
                }
                else
                {
                    inputStream.Close();
                    outputStream.Close();

                    tcs.SetResult(null);
                }
            })
            .Catch(ex =>
            {
                inputStream.Close();
                outputStream.Close();

                tcs.SetException(ex);
            });
        }
Beispiel #3
0
        public Task<SurveyNewsFeed> GetFeedAsync(string feedUrl) {
            // We can't use a simple WebRequest, because that doesn't have access
            // to the browser's session cookies.  Cookies are used to remember
            // which survey/news item the user has submitted/accepted.  The server 
            // checks the cookies and returns the survey/news urls that are 
            // currently available (availability is determined via the survey/news 
            // item start and end date).
            var tcs = new TaskCompletionSource<SurveyNewsFeed>();
            try {
                var thread = new Thread(() => {
                    var browser = new WebBrowser();
                    browser.DocumentCompleted += (sender, e) => {
                        try {
                            if (browser.Url == e.Url) {
                                SurveyNewsFeed feed = ParseFeed(browser);
                                tcs.SetResult(feed);

                                Application.ExitThread();
                            }
                        } catch (Exception ex2) {
                            tcs.SetException(ex2);
                        }
                    };
                    browser.Navigate(new Uri(feedUrl));
                    Application.Run();
                });
                thread.Name = "SurveyNewsFeedClient";
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            } catch (Exception ex1) {
                tcs.SetException(ex1);
            }

            return tcs.Task;
        }
Beispiel #4
0
        public static Task<JObject> ReadJObject(this Socket socket)
        {
            var tcs = new TaskCompletionSource<JObject>();
            socket.ReadBuffer(4)
                .ContinueWith(task =>
                {
                    try
                    {
                        var len = BitConverter.ToInt32(task.Result.Array, task.Result.Offset);
                        if(len > TenMB)
                            throw new InvalidOperationException("Got a reply for single JObject > 10 MB, rejecting as invalid");

                        socket.ReadBuffer(len)
                            .ContinueWith(readLenTask =>
                            {
                                try
                                {
                                    var ms = new MemoryStream(readLenTask.Result.Array, readLenTask.Result.Offset,
                                                              readLenTask.Result.Count);

                                    tcs.SetResult(ms.ToJObject());
                                }
                                catch (Exception e)
                                {
                                    tcs.SetException(e);
                                }
                            });
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                });
            return tcs.Task;
        }
        Task<ALAsset> GetAsset (AssetDescription description, CancellationToken token)
        {
            var tcs = new TaskCompletionSource<ALAsset> ();

            Task.Factory.StartNew (() => {
                if (token.IsCancellationRequested) {
                    tcs.SetCanceled ();
                    return;
                }

                _library.Value.AssetForUrl (new NSUrl (description.AssetUrl), (asset) => {
                    if (asset == null) {
                        tcs.SetException (new Exception ("No asset found for url"));
                        return;
                    }

                    if (asset.DefaultRepresentation == null) {
                        tcs.SetException (new Exception ("No representation found for the asset"));
                        return;
                    }

                    tcs.SetResult (asset);
                }, error => {
                    tcs.SetException (new Exception (error.ToString ()));
                });
            }, token).RouteExceptions (tcs);

            return tcs.Task;
        }
        public Task<RunSummary> RunAsync(IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
        {
            
            var tcs = new TaskCompletionSource<RunSummary>();



#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed


            // Run on the UI thread
            Device.BeginInvokeOnMainThread(
                () =>
                {
                    try
                    {
                        var result = testCase.RunAsync(diagnosticMessageSink, messageBus, constructorArguments, aggregator, cancellationTokenSource);
                        result.ContinueWith(t =>
                                            {
                                                if (t.IsFaulted)
                                                    tcs.SetException(t.Exception);

                                                tcs.SetResult(t.Result);
                                            });
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }

                });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            return tcs.Task;
        }
        public Task<RedisConnection> CreateRedisConnection()
        {
            var settings = RedisConnectionProvider.Instance.ConnectionsSettings;
            var redisConnection = new RedisConnection(host: settings["host"], port: Convert.ToInt32(settings["port"]), password: settings["password"]);
            var taskCreateConnection = new TaskCompletionSource<RedisConnection>();

            try
            {
                redisConnection.Open().ContinueWith((task) =>
                    {
                        if (!task.IsFaulted)
                        {
                            taskCreateConnection.SetResult(redisConnection);
                        }
                        else
                        {
                            task.Exception.Handle(x => true);
                            taskCreateConnection.SetException(task.Exception);
                        }
                    }, TaskScheduler.Default);
            }
            catch (Exception ex)
            {
                taskCreateConnection.SetException(ex);
            }

            return taskCreateConnection.Task;
        }
Beispiel #8
0
        public Task AddHandler(string key, Func<string, IObservable<RedisObject>> handler, PublishOptions options)
        {
            var tcs = new TaskCompletionSource<object>();
            try
            {
                _req.Create(key).Subscribe(req =>
                {
                    try
                    {
                        if (req == null && !tcs.Task.IsCompleted)
                        {
                            tcs.SetResult(null);
                            return;
                        }

                        var ob = handler(req);
                        if (ob != null)
                            ob.ToRedis(req, _db);
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                });
            }
            catch (Exception e)
            {
                tcs.SetException(e);
            }
            return tcs.Task;
        }
        public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
        {
            var tcs = new TaskCompletionSource<HttpWebResponse>();

            try
            {
                request.BeginGetResponse(iar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(iar);
                        tcs.SetResult(response);
                    }
                    catch (Exception exc)
                    {
                        tcs.SetException(exc);
                    }
                }, null);
            }
            catch (Exception exc)
            {
                tcs.SetException(exc);
            }

            return tcs.Task;
        }
 public static Task<ReadableArticleViewModel> LoadAtLeastOne(ISimpleHttpService httpService, string url, string linkId)
 {
     TaskCompletionSource<ReadableArticleViewModel> result = new TaskCompletionSource<ReadableArticleViewModel>();
     var articleViewModel = new ReadableArticleViewModel { ArticleUrl = url, ArticleParts = new ObservableCollection<object>(), LinkId = linkId, ContentIsFocused = true };
     LoadOneImpl(httpService, url, articleViewModel.ArticleParts).ContinueWith(async (task) =>
         {
             try
             {
                 if (task.IsCompleted)
                 {
                     Tuple<string, string> tpl = await task;
                     var nextPage = tpl.Item1;
                     articleViewModel.Title = tpl.Item2;
                     result.SetResult(articleViewModel);
                     if (!string.IsNullOrEmpty(nextPage))
                     {
                         var remainingParts = await Task.Run(() => LoadFullyImpl(httpService, nextPage));
                         foreach (var part in remainingParts.Item2)
                         {
                             
                             articleViewModel.ArticleParts.Add(part);
                         }
                     }
                 }
                 else if (task.Exception != null)
                     result.SetException(task.Exception);
             }
             catch (Exception ex)
             {
                 result.SetException(ex);
             }
         }, TaskScheduler.FromCurrentSynchronizationContext());
     return result.Task;
     
 }
		public static Task<int> StartProcess (ProcessStartInfo psi, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken)
		{
			var tcs = new TaskCompletionSource<int> ();
			if (cancellationToken.CanBeCanceled && cancellationToken.IsCancellationRequested) {
				tcs.SetCanceled ();
				return tcs.Task;
			}

			psi.UseShellExecute = false;
			if (stdout != null) {
				psi.RedirectStandardOutput = true;
			}
			if (stderr != null) {
				psi.RedirectStandardError = true;
			}
			var p = Process.Start (psi);
			if (cancellationToken.CanBeCanceled)
				cancellationToken.Register (() => {
					try {
						if (!p.HasExited) {
							p.Kill ();
						}
					} catch (InvalidOperationException ex) {
						if (ex.Message.IndexOf ("already exited") < 0)
							throw;
					}
				});
			p.EnableRaisingEvents = true;
			if (psi.RedirectStandardOutput) {
				bool stdOutInitialized = false;
				p.OutputDataReceived += (sender, e) => {
					try {
						if (stdOutInitialized)
							stdout.WriteLine ();
						stdout.Write (e.Data);
						stdOutInitialized = true;
					} catch (Exception ex) {
						tcs.SetException (ex);
					}
				};
				p.BeginOutputReadLine ();
			}
			if (psi.RedirectStandardError) {
				bool stdErrInitialized = false;
				p.ErrorDataReceived += (sender, e) => {
					try {
						if (stdErrInitialized)
							stderr.WriteLine ();
						stderr.Write (e.Data);
						stdErrInitialized = true;
					} catch (Exception ex) {
						tcs.SetException (ex);
					}
				};
				p.BeginErrorReadLine ();
			}
			p.Exited += (sender, e) => tcs.SetResult (p.ExitCode);

			return tcs.Task;
		}
Beispiel #12
0
        public static Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count)
        {
            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)
                {
                    tcs.SetException(ex);
                }
            }, null);

            if (sr.CompletedSynchronously)
            {
                try
                {
                    stream.EndWrite(sr);
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }
            return tcs.Task;
        }
Beispiel #13
0
        public Task<string> GetContentAsync(string url)
        {
            var tcs = new TaskCompletionSource<string>();

            try
            {
                var client = new RestClient(url);

                client.GetAsync(new RestRequest(), (response, handle) =>
                {
                    if ((int)response.StatusCode >= 400)
                    {
                        tcs.SetException(new Exception(response.StatusDescription));
                    }
                    else
                    {
                        tcs.SetResult(response.Content);
                    }
                });
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }

            return tcs.Task;
        }
        public Task<Response> Dispatch(NancyContext context, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<Response>();

            if (cancellationToken.IsCancellationRequested)
            {
                tcs.SetException(new OperationCanceledException());
                return tcs.Task;
            }

            if (context == null)
            {
                tcs.SetException(new ArgumentException("context is null"));
                return tcs.Task;
            }

            var response = IsAdminRequest(context.Request) ?
                                    _adminRequestHandler.Handle(context) :
                                    _requestHandler.Handle(context);

            context.Response = response;
            tcs.SetResult(context.Response);

            return tcs.Task;
        }
        /// <summary>
        /// Async method for getting web request.
        /// </summary>
        /// <param name="request">The HttpWebRequest instance.</param>
        /// <returns>The request stream asynchronuously.</returns>
        public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
        {
            Contract.Requires<ArgumentNullException>(request != null);

            var tcs = new TaskCompletionSource<Stream>();

            try
            {
                request.BeginGetRequestStream(iar =>
                {
                    try
                    {
                        var response = request.EndGetRequestStream(iar);
                        tcs.SetResult(response);
                    }
                    catch (Exception exc)
                    {
                        tcs.SetException(exc);
                    }
                }, null);
            }
            catch (Exception exc)
            {
                tcs.SetException(exc);
            }

            return tcs.Task;
        }
        /// <summary>
        /// Closes an AMQP object asynchronously.
        /// </summary>
        /// <param name="amqpObject">The object to close.</param>
        /// <param name="timeout">The timeout in seconds.</param>
        /// <returns></returns>
        public static Task CloseAsync(this AmqpObject amqpObject, int timeout = 60000)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            try
            {
                amqpObject.Closed += (o, e) =>
                {
                    if (e != null)
                    {
                        tcs.SetException(new AmqpException(e));
                    }
                    else
                    {
                        tcs.SetResult(null);
                    }
                };

                amqpObject.Close(0);
            }
            catch (Exception exception)
            {
                tcs.SetException(exception);
            }

            return tcs.Task;
        }
        public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
        {
            if (timeoutMs > 0)
            {
                return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
            }

            var tcs = new TaskCompletionSource<WebResponse>();

            try
            {
                request.BeginGetResponse(iar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(iar);
                        tcs.SetResult(response);
                    }
                    catch (Exception exc)
                    {
                        tcs.SetException(exc);
                    }
                }, null);
            }
            catch (Exception exc)
            {
                tcs.SetException(exc);
            }

            return tcs.Task;
        }
Beispiel #18
0
        public static async Task Until(
            Func<bool> until,
            TimeSpan? pollInterval = null,
            TimeSpan? timeout = null)
        {
            if (Debugger.IsAttached)
            {
                timeout = timeout ?? TimeSpan.FromMinutes(5);
            }
            else
            {
                timeout = timeout ?? TimeSpan.FromSeconds(20);
            }

            pollInterval = pollInterval ?? TimeSpan.FromMilliseconds(100);

            var tcs = new TaskCompletionSource<bool>();

            var timer = new Stopwatch();
            timer.Start();

            Task.Run(async () =>
            {
                while (!tcs.Task.IsCompleted &&
                       !tcs.Task.IsFaulted &&
                       !tcs.Task.IsCanceled)
                {
                    if (timer.Elapsed >= timeout)
                    {
                        tcs.SetException(new TimeoutException());
                        break;
                    }

                    try
                    {
                        if (until())
                        {
                            tcs.SetResult(true);
                        }
                        else
                        {
                            await Task.Delay(pollInterval.Value);
                        }
                    }
                    catch (Exception exception)
                    {
                        tcs.SetException(exception);
                    }
                }
            });

            await tcs.Task;

            if (tcs.Task.IsFaulted)
            {
                throw tcs.Task.Exception;
            }
        }
Beispiel #19
0
        public static Task<string> DownloadPackageFromFeed(string packageId, string version, string operation = "Install")
        {           
            HttpClient client = new HttpClient();
            string requestUri = UrlHelper.V2FeedRootUrl + @"Package/" + packageId + @"/" + version;

            CancellationTokenSource cts = new CancellationTokenSource();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);
            request.Headers.Add("user-agent", "TestAgent");
            request.Headers.Add("NuGet-Operation", operation);
            Task<HttpResponseMessage> responseTask = client.SendAsync(request);

            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
            responseTask.ContinueWith((rt) =>
            {
                HttpResponseMessage responseMessage = rt.Result;
                if (responseMessage.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        string filename;
                        ContentDispositionHeaderValue contentDisposition = responseMessage.Content.Headers.ContentDisposition;
                        if (contentDisposition != null)
                        {
                            filename = contentDisposition.FileName;
                        }
                        else
                        {
                            filename = packageId; // if file name not present set the package Id for the file name.
                        }
                        FileStream fileStream = File.Create(filename);
                        Task contentTask = responseMessage.Content.CopyToAsync(fileStream);
                        contentTask.ContinueWith((ct) =>
                        {
                            try
                            {
                                fileStream.Close();
                                tcs.SetResult(filename);
                            }
                            catch (Exception e)
                            {
                                tcs.SetException(e);
                            }
                        });
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                }
                else
                {
                    string msg = string.Format("Http StatusCode: {0}", responseMessage.StatusCode);
                    tcs.SetException(new ApplicationException(msg));
                }
            });

            return tcs.Task;
        }
        public static Task<string> GetAsync(string url)
        {
            var tcs = new TaskCompletionSource<string>();
            try
            {

                var request = (HttpWebRequest)WebRequest.Create(url);
                string proxyAddress = ConfigurationSettings.AppSettings["proxyAddress"];
                string username = ConfigurationSettings.AppSettings["username"];
                string password = ConfigurationSettings.AppSettings["password"];
                int timeOut = 0;
                int.TryParse(ConfigurationSettings.AppSettings["proxyTimeOut"], out timeOut);
                if ((!string.IsNullOrWhiteSpace(proxyAddress)) && (!string.IsNullOrWhiteSpace(username)) && (!string.IsNullOrWhiteSpace(password)))
                {
                    WebProxy proxy = new WebProxy();
                    proxy.Address = new Uri(proxyAddress);
                    proxy.Credentials = new NetworkCredential(username, password);
                    request.Proxy = proxy;
                }
                if (timeOut > 0)
                    request.Timeout = timeOut;
                else
                    request.Timeout = 10000;

                try
                {
                    request.BeginGetResponse(iar =>
                    {
                        HttpWebResponse response = null;
                        try
                        {
                            response = (HttpWebResponse)request.EndGetResponse(iar);
                            tcs.SetResult((Convert.ToInt32( response.StatusCode).ToString()+"," + request.RequestUri.ToString()));
                        }
                        catch (Exception exc)
                        {
                            tcs.SetException(exc);
                        }
                        finally
                        {
                            if (response != null) response.Close();
                        }
                    }, null);
                }
                catch (Exception exc)
                {
                    tcs.SetException(exc);
                }
            }
            catch (Exception e)
            {
                tcs.SetException(e);
            }
            return tcs.Task;
        }
Beispiel #21
0
 public void Do()
 {
     try
     {
         Action !();
         Complete?.SetResult();
     }
     catch (Exception e)
     {
         Complete?.SetException(e);
     }
 }
        public Task<Response> Dispatch(NancyContext context, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<Response>();

            if (cancellationToken.IsCancellationRequested)
            {
                tcs.SetException(new OperationCanceledException());
                return tcs.Task;
            }

            if (context == null)
            {
                tcs.SetException(new ArgumentException("context is null"));
                return tcs.Task;
            }

            Response response;

            try
            {
                response = IsAdminRequest(context.Request) ?
                    _adminRequestHandler.Handle(context) :
                    _requestHandler.Handle(context);
            }
            catch (Exception ex)
            {
                if (ex.GetType() != typeof(PactFailureException))
                {
                    _log.ErrorException("Failed to handle the request", ex);
                }

                var exceptionMessage = String.Format("{0} See {1} for details.",
                    JsonConvert.ToString(ex.Message).Trim('"'),
                    !String.IsNullOrEmpty(_pactConfig.LoggerName) ? LogProvider.CurrentLogProvider.ResolveLogPath(_pactConfig.LoggerName) : "logs");

                response = new Response
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    ReasonPhrase = exceptionMessage,
                    Contents = s =>
                    {
                        var bytes = Encoding.UTF8.GetBytes(exceptionMessage);
                        s.Write(bytes, 0, bytes.Length);
                        s.Flush();
                    }
                };
            }

            context.Response = response;
            tcs.SetResult(context.Response);

            return tcs.Task;
        }
Beispiel #23
0
        public Task Build(DeploymentContext context)
        {
            var tcs = new TaskCompletionSource<object>();

            ILogger innerLogger = context.Logger.Log(Resources.Log_CopyingFiles);

            try
            {
                using (context.Tracer.Step("Copying files to output directory"))
                {
                    // Copy to the output path and use the previous manifest if there
                    DeploymentHelper.CopyWithManifest(_sourcePath, context.OutputPath, context.PreviousMainfest);
                }

                using (context.Tracer.Step("Building manifest"))
                {
                    // Generate a manifest from those build artifacts
                    context.ManifestWriter.AddFiles(_sourcePath);
                }

                // Log the copied files from the manifest
                innerLogger.LogFileList(context.ManifestWriter.GetPaths());
            }
            catch (Exception ex)
            {
                context.Tracer.TraceError(ex);

                innerLogger.Log(ex);

                tcs.SetException(ex);

                // Bail out early
                return tcs.Task;
            }

            try
            {
                // Download node packages
                DownloadNodePackages(context);

                tcs.SetResult(null);
            }
            catch (Exception ex)
            {
                context.Tracer.TraceError(ex);

                tcs.SetException(ex);
            }

            return tcs.Task;
        }
        /// <summary>
        /// Invokes the specified <paramref name="route"/> with the provided <paramref name="parameters"/>.
        /// </summary>
        /// <param name="route">The route that should be invoked.</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <param name="parameters">The parameters that the route should be invoked with.</param>
        /// <param name="context">The context of the route that is being invoked.</param>
        /// <returns>A <see cref="Response"/> instance that represents the result of the invoked route.</returns>
        public Task<Response> Invoke(Route route, CancellationToken cancellationToken, DynamicDictionary parameters, NancyContext context)
        {
            var tcs = new TaskCompletionSource<Response>();

            var result = route.Invoke(parameters, cancellationToken);

            result.WhenCompleted(
                completedTask =>
                {
                    var returnResult = completedTask.Result;
                    if (!(returnResult is ValueType) && returnResult == null)
                    {
                        context.WriteTraceLog(
                            sb => sb.AppendLine("[DefaultRouteInvoker] Invocation of route returned null"));

                        returnResult = new Response();
                    }

                    try
                    {
                        var response = this.negotiator.NegotiateResponse(returnResult, context);

                        tcs.SetResult(response);
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                },
                faultedTask =>
                {
                    var earlyExitException = GetEarlyExitException(faultedTask);

                    if (earlyExitException != null)
                    {
                        context.WriteTraceLog(
                            sb =>
                            sb.AppendFormat(
                                "[DefaultRouteInvoker] Caught RouteExecutionEarlyExitException - reason {0}",
                                earlyExitException.Reason));
                        tcs.SetResult(earlyExitException.Response);
                    }
                    else
                    {
                        tcs.SetException(faultedTask.Exception);
                    }
                });

            return tcs.Task;
        }
Beispiel #25
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;
        }
        private void DiscoverEndPoint(TaskCompletionSource <object> completionTask)
        {
            LogDebug("DiscoverEndPoint");

            if (_state != ConnectionState.Connecting)
            {
                return;
            }
            if (_connectingPhase != ConnectingPhase.Reconnecting)
            {
                return;
            }

            _connectingPhase = ConnectingPhase.EndPointDiscovery;

            _endPointDiscoverer.DiscoverAsync(_connection != null ? _connection.RemoteEndPoint : null).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    EnqueueMessage(new CloseConnectionMessage("Failed to resolve TCP end point to which to connect.", t.Exception));
                    completionTask?.SetException(new CannotEstablishConnectionException("Cannot resolve target end point.", t.Exception));
                }
                else
                {
                    EnqueueMessage(new EstablishTcpConnectionMessage(t.Result));
                    completionTask?.SetResult(null);
                }
            });
        }
Beispiel #27
0
 private void FilterTestCases(xua.IMessageSinkMessage message)
 {
     try
     {
         if (message is xua.ITestCaseDiscoveryMessage testDiscovered)
         {
             if (_filter?.Pass(Wrap(testDiscovered.TestCase)) != false)
             {
                 _testsToRun.Add(testDiscovered.TestCase);
             }
         }
         else if (message is xua.IDiscoveryCompleteMessage discoveryComplete)
         {
             _tcsFilter.SetResult(_testsToRun.Count);
         }
         else if (message is xua.IErrorMessage errorMessage)
         {
             Console.WriteLine($"Error ocurred {errorMessage.ToString()}");
         }
         else
         {
             Console.WriteLine($"Unhandled message of type {message.GetType()}");
         }
     }
     catch (Exception ex)
     {
         _tcsFilter?.SetException(ex);
         _tcsRun?.SetException(ex);
         _tcs?.SetException(ex);
     }
 }
Beispiel #28
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;
 }
        public async Task ImportFromWeb(string url)
        {
            WebClient webClient = new WebClient();
            var       data      = await Task.Run(() => webClient.DownloadString(url));

            data = FindCardsData(data);
            if (!String.IsNullOrWhiteSpace(data))
            {
                Cards = new List <CardInstance>();
                sbErrors.Clear();

                try
                {
                    ImportFromTextProcess(data);

                    taskCompletonSource?.SetResult(true);
                }
                catch (Exception ex)
                {
                    taskCompletonSource?.SetResult(false);
                    taskCompletonSource?.SetException(ex);
                }
            }
            else
            {
                sbErrors.AppendLine("No cards found on page.");
                taskCompletonSource?.SetResult(false);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Handler for records obtained through the subscription
        /// </summary>
        private void ApplyRecord(JournalRecord record)
        {
            TaskCompletionSource <object> completion = null;

            try
            {
                var command        = record.Command;
                var isLocalCommand = _pendingLocalCommands.TryRemove(command.Id, out completion);
                if (isLocalCommand)
                {
                    _pendingCommandsChanged.Set();
                }

                _logger.LogDebug("ApplyRecord: {0}/{1}, isLocal: {2}", record.RecordNumber, command.GetType().Name, isLocalCommand);
                long expected = Interlocked.Increment(ref _lastRecordNumber);
                if (expected != record.RecordNumber)
                {
                    _logger.LogError("ApplyRecord: RecordNumber out of order. Expected {0}, got {1}", expected, record.RecordNumber);
                }

                object result = _kernel.Execute(record.Command);
                completion?.SetResult(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(default(EventId), ex, "ApplyRecord failed: {0}/{1}", record.RecordNumber, record.Command.GetType().Name);
                completion?.SetException(ex);
            }
        }
 public static Task ConnectAsync(this Tcp tcp, string ipAddress, int port)
 {
     var tcs = new TaskCompletionSource<object>();
     try {
         tcp.Connect(ipAddress, port, (e) => {
             if (e == null) {
                 tcs.SetResult(null);
             } else {
                 tcs.SetException(e);
             }
         });
     } catch (Exception e) {
         tcs.SetException(e);
     }
     return tcs.Task;
 }
        /// <summary>
        /// Invalidate every resource due to a critical event
        /// </summary>
        /// <param name="codeErrorMessage">Message for cancelled codes</param>
        /// <returns>Asynchronous task</returns>
        public static async Task InvalidateData(string codeErrorMessage)
        {
            // Close every open file. This closes the internal macro files as well
            await Print.Cancel();

            // Resolve pending macros, unbuffered (system) codes and flush requests
            foreach (CodeChannel channel in CodeChannels)
            {
                MacroFile.AbortAllFiles(channel);

                using (await Channels[channel].LockAsync())
                {
                    Channels[channel].Invalidate(codeErrorMessage);
                }
            }
            _bytesReserved = _bufferSpace = 0;

            // Resolve pending heightmap requests
            using (await _heightmapLock.LockAsync())
            {
                _getHeightmapRequest?.SetException(new OperationCanceledException(codeErrorMessage));
                _heightmapRequested = false;

                _setHeightmapRequest?.SetException(new OperationCanceledException(codeErrorMessage));
                _heightmapToSet = null;
            }
        }
 public static Task ConnectAsync(this Tcp tcp, IPEndPoint ep)
 {
     var tcs = new TaskCompletionSource<object>();
     try {
         tcp.Connect(ep, (e) => {
             if (e == null) {
                 tcs.SetResult(null);
             } else {
                 tcs.SetException(e);
             }
         });
     } catch (Exception e) {
         tcs.SetException(e);
     }
     return tcs.Task;
 }
Beispiel #34
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;
                });
            }
        }
        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);
            }
        }
        public async Task Connect()
        {
            var taskSource = new TaskCompletionSource <bool>();

            _webSocket.OnOpen  += (sender, args) => { taskSource?.SetResult(true); };
            _webSocket.OnError += (sender, args) => { taskSource?.SetException(args.Exception); };
            _webSocket.Connect();
            await taskSource.Task;
        }
Beispiel #37
0
 public void Stop()
 {
     lock (_lockObject)
     {
         _stopped = true;
         _queue.Clear();
         _awaitingTask?.SetException(new Exception("Publisher subscriber is stopping"));
         _awaitingTask = null;
     }
 }
Beispiel #38
0
        /// <summary>
        /// Handler for records obtained through the subscription
        /// </summary>
        private void ApplyRecord(JournalRecord record)
        {
            TaskCompletionSource <object> completion = null;

            try
            {
                var command = record.Command;

                var isLocalCommand = _pendingLocalCommands.TryRemove(command.Id, out completion);

                if (isLocalCommand)
                {
                    _metrics.PendingLocalCommands(_pendingLocalCommands.Count);

                    _pendingCommandsChanged.Set();
                }

                _logger.LogDebug("ApplyRecord: {0}/{1}, isLocal: {2}", record.RecordNumber, command.GetType().Name, isLocalCommand);

                var expected = Interlocked.Increment(ref _lastRecordNumber);

                if (expected != record.RecordNumber)
                {
                    if (!_settings.AllowBrokenSequence)
                    {
                        _stopped = true;

                        throw new Exception($"Broken sequence, expected {expected}, got {record.RecordNumber}");
                    }

                    _logger.LogWarning(
                        "ApplyRecord: RecordNumber out of order. Expected {0}, got {1}",
                        expected,
                        record.RecordNumber);
                }

                var events = new List <Event>();

                var result = _kernel.Execute(record.Command, events.Add);

                NotifyCommandExecuted(record, isLocalCommand, events);

                completion?.SetResult(result);

                _metrics.CommandExecuted();
            }
            catch (Exception ex)
            {
                _metrics.CommandFailed();

                _logger.LogError(default(EventId), ex, "ApplyRecord failed: {0}/{1}", record.RecordNumber, record.Command.GetType().Name);

                completion?.SetException(ex);
            }
        }
 public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
 {
     if (user != null && error == null)
     {
         _tcs?.SetResult(GoogleAuthProvider.GetCredential(user.Authentication.IdToken, user.Authentication.AccessToken));
     }
     else
     {
         _tcs?.SetException(new NSErrorException(error));
     }
 }
Beispiel #40
0
        private async Task HandleSignInResultAsync(GmsTask signInAccountTask)
        {
            if (signInAccountTask.IsSuccessful)
            {
                var signInAccount = await signInAccountTask.AsAsync <GoogleSignInAccount>();

                _tcs?.SetResult(GoogleAuthProvider.GetCredential(signInAccount.IdToken, null));
            }
            else
            {
                _tcs?.SetException(signInAccountTask.Exception);
            }
        }
Beispiel #41
0
        public Task ProcessEventsAsync(StoreEvent storeEvent)
        {
            var storeId = storeEvent.StoreId;

            string operation = storeEvent.Operation;
            var    opId      = storeEvent.OperationId;
            var    strict    = storeEvent.Strict;

            TaskCompletionSource <bool> tc = null;

            if (opId != null)
            {
                _completions.TryGetValue(opId, out tc);
            }

            try {
                var data = storeEvent.Data;
                switch (operation)
                {
                case EventType.POST:
                    _storeProcessor.Assert(storeId, data, strict);
                    break;

                case EventType.PATCH_JSON:
                    _storeProcessor.PatchJson(storeId, data);
                    break;

                case EventType.PATCH_TRIPLE:
                    var patch = (JObject)storeEvent.Data;
                    _storeProcessor.PatchTriple(storeId, patch);
                    break;

                case EventType.DELETE:
                    _storeProcessor.Delete(storeId, data);
                    break;

                default:
                    throw new InvalidOperationException($"Unknown operation {operation}");
                }
                tc?.SetResult(true);
            } catch (Exception exception) {
                tc?.SetException(exception);
            } finally {
                if (tc != null)
                {
                    _completions.Remove(opId, out _);
                }
            }
            return(Task.CompletedTask);
        }
        private void MessagePump()
        {
            try
            {
                if (_wndClassResult == null)
                {
                    throw new Exception("Woops, this isn't supposed to happen :(");
                }
                Console.WriteLine("Window Thread start!");
                Handle = Win32.CreateWindowEx(0, new IntPtr((int)(uint)_wndClassResult.Value), "XTouchMiniSimconnectBridgeMessagePump", 0, 0, 0, 0, 0, Win32.HWND_MESSAGE, IntPtr.Zero, _wndClass.hInstance, IntPtr.Zero);
                Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
                Console.WriteLine($"Handle: {Handle:X16}");
                _windows.Add(Handle, this);
            }
            catch (Exception ex)
            {
                _createTaskCompletionSource?.SetException(ex);
                throw;
            }
            _createTaskCompletionSource?.SetResult(true);
            MSG   msg;
            sbyte getMsgResult;

            while ((getMsgResult = GetMessage(out msg, IntPtr.Zero, 0, 0)) != 0)
            {
                if (getMsgResult == -1)
                {
                    break;
                }
                else
                {
                    //TranslateMessage(ref msg);
                    try
                    {
                        DispatchMessage(ref msg);
                    }
#pragma warning disable IDE0079
#pragma warning disable CS0618 // Type or member is obsolete -- well, it does raise it Sadge
                    catch (ExecutionEngineException)
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning restore IDE0079
                    {
                        break;
                    }
                }
            }
            MessagePumpDestroyed?.Invoke(this, new System.EventArgs());
            Console.WriteLine("Window Thread exit!");
        }
Beispiel #43
0
        private void FinishUpload(Exception remoteStreamReadException)
        {
            if (remoteStreamReadException == null)
            {
                _eofWaitTask?.SetResult(true);
            }
            else
            {
                _eofWaitTask?.SetException(remoteStreamReadException);
            }

            _eofWaitTask = null;
            _remoteStreamWaitTask?.TrySetCanceled();
            _remoteStreamWaitTask = null;
            _remoteStream         = null;
        }
Beispiel #44
0
        private Task HubConnectionOnClosed(Exception arg)
        {
            var exception = arg ?? new InvalidOperationException();

            lock (_reconnectingLock)
            {
                _reconnectingTask?.SetException(exception);
                _reconnectingTask = null;
            }

            lock (_getMessagesLock)
            {
                _getMessagesTask?.TrySetException(exception);
            }

            return(Task.CompletedTask);
        }
Beispiel #45
0
        private void InternalExecuteAsync(AseCommand command, AseTransaction transaction, TaskCompletionSource <int> rowsAffectedSource = null, TaskCompletionSource <DbDataReader> readerSource = null, CommandBehavior behavior = CommandBehavior.Default)
        {
            AssertExecutionStart();

            try
            {
                SendPacket(new NormalPacket(BuildCommandTokens(command, behavior)));

                var doneHandler       = new DoneTokenHandler();
                var messageHandler    = new MessageTokenHandler(EventNotifier);
                var dataReaderHandler = readerSource != null ? new DataReaderTokenHandler() : null;

                ReceiveTokens(
                    new EnvChangeTokenHandler(_environment),
                    messageHandler,
                    dataReaderHandler,
                    new ResponseParameterTokenHandler(command.AseParameters),
                    doneHandler);

                AssertExecutionCompletion(doneHandler);

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

                messageHandler.AssertNoErrors();

                if (doneHandler.Canceled)
                {
                    rowsAffectedSource?.SetCanceled();
                    readerSource?.SetCanceled();
                }
                else
                {
                    rowsAffectedSource?.SetResult(doneHandler.RowsAffected);
                    readerSource?.SetResult(new AseDataReader(dataReaderHandler.Results(), command, behavior));
                }
            }
            catch (Exception ex)
            {
                rowsAffectedSource?.SetException(ex);
                readerSource?.SetException(ex);
            }
        }
Beispiel #46
0
        private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (!(sender is SerialPort port))
            {
                return;
            }

            var n = port.BytesToRead;

            if (n < ResponseSizeInBytes)
            {
                return;
            }

            if (n > ResponseSizeInBytes)
            {
                // This should not happen as step motors through out
                // `ResponseSizeInBytes` bytes after each command.
                // If response is larger, something went wrong, or interfering,
                // or there is an unexpected race condition.
                // Rare case, no need for optimization
                var buff = ArrayPool <byte> .Shared.Rent(n);

                try
                {
                    port.Read(buff, 0, n);
                    _taskSource?.SetException(new StepMotorException("Unexpected content in the motor's buffer.",
                                                                     buff.AsSpan(0, n)));
                    return;
                }
                finally
                {
                    ArrayPool <byte> .Shared.Return(buff);
                }
            }

            var span = _commandBuffer.AsSpan();

            span.Fill(0);
            port.Read(_commandBuffer, 0, ResponseSizeInBytes);
            var reply = new Reply(_commandBuffer);

            span.Fill(0);
            _taskSource?.SetResult(reply);
        }
        void RequestPaymentAuthorization(PKPaymentRequest paymentRequest, IDictionary <string, double> summaryItems, string merchantId)
        {
            UserDialogs.Instance.ShowLoading("Loading");

            paymentRequest.MerchantIdentifier   = merchantId;
            paymentRequest.MerchantCapabilities = PKMerchantCapability.ThreeDS;
            paymentRequest.CountryCode          = "US";
            paymentRequest.CurrencyCode         = "USD";

            if (summaryItems != null)
            {
                paymentRequest.PaymentSummaryItems = summaryItems.Select(i => new PKPaymentSummaryItem()
                {
                    Label  = i.Key,
                    Amount = new NSDecimalNumber(i.Value)
                }).ToArray();
            }

            var window          = UIApplication.SharedApplication.KeyWindow;
            var _viewController = window.RootViewController;

            while (_viewController.PresentedViewController != null)
            {
                _viewController = _viewController.PresentedViewController;
            }


            pKPaymentAuthorizationViewController = new PKPaymentAuthorizationViewController(paymentRequest);
            UserDialogs.Instance.HideLoading();
            if (pKPaymentAuthorizationViewController != null)
            {
                pKPaymentAuthorizationViewController.Delegate = this;
                _viewController?.PresentViewController(pKPaymentAuthorizationViewController, true, null);
            }
            else
            {
                if (!isDropUI)
                {
                    OnTokenizationError?.Invoke(this, "Error: Payment request is invalid.");
                }

                payTcs?.SetException(new Exception("Error: Payment request is invalid."));
            }
        }
Beispiel #48
0
        private void SwitchToPubSubWatchDog(TaskCompletionSource <bool> completionSource)
        {
            _watchDogSync.EnterWriteLock();

            try
            {
                _logger.Info("Switching to Slave node");
                _watchDogCancellationTokenSource?.Cancel();
                if (_cancellationToken.IsCancellationRequested)
                {
                    _logger.Info("Bus stopped, can't switch to slave node");
                    return;
                }

                _watchDogCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken);

                var pubSubWatchDog = new PubSubWatchDog(_logger, _stateManager, PubSubFactory, _cancellationToken, EventAggregator);
                _watchDogPipeline = new Pipeline <IWatchDogMessage>(pubSubWatchDog);

                _watchDogCancellationTokenSource.Token.Register(() =>
                {
                    _logger.Info("Slave node ended");
                    _logger.Debug("Slave node ended");
                    pubSubWatchDog.Dispose();
                });

                completionSource?.SetResult(true);
                _logger.Info("Switching to Slave node complete");
                _logger.Debug("Running Slave node");
                _processRepository.InvokeOnSlave();

                _leaderManager.InitializationComplete();
            }
            catch (Exception e)
            {
                _logger.Error("Error switching watchdog to secondary node", e);
                completionSource?.SetException(e);
            }
            finally
            {
                _watchDogSync.ExitWriteLock();
            }
        }
Beispiel #49
0
        public static Task <T> BeginInvokeOnMainThreadAsync <T>(Func <Task <T> > method)
        {
            var tcs = new TaskCompletionSource <T>();

            Device.BeginInvokeOnMainThread(async() =>
            {
                try
                {
                    var task = method?.Invoke();
                    tcs?.SetResult(await task);
                }
                catch (Exception e)
                {
                    DebugHelpers.PrintException(e);
                    tcs?.SetException(e);
                }
            });

            return(tcs?.Task);
        }
Beispiel #50
0
        /// <summary>
        /// Handler for records obtained through the subscription
        /// </summary>
        private void OnRecordReceived(JournalRecord record)
        {
            if (_stopped)
            {
                return;
            }
            TaskCompletionSource <object> completion = null;

            try
            {
                var command        = record.Command;
                var isLocalCommand = _pendingLocalCommands.TryRemove(command.Id, out completion);

                if (isLocalCommand)
                {
                    _metrics.PendingLocalCommands(_pendingLocalCommands.Count);
                    _pendingCommandsChanged.Set();
                }

                _logger.LogDebug("OnRecordReceived: {0}/{1}, isLocal: {2}", record.RecordNumber, command.GetType().Name, isLocalCommand);

                VerifyRecordSequence(record.RecordNumber);

                var ctx = ExecutionContext.Current;
                ctx.Reset(record.RecordNumber);

                var result = _kernel.Execute(record.Command);
                Interlocked.Exchange(ref _lastRecordNumber, record.RecordNumber);
                NotifyCommandExecuted(record, isLocalCommand, ctx.Events);

                completion?.SetResult(result);
                _metrics.CommandExecuted();
            }
            catch (Exception ex)
            {
                _metrics.CommandFailed();
                _logger.LogError(default(EventId), ex, "OnRecordReceived failed: {0}/{1}", record.RecordNumber, record.Command.GetType().Name);
                completion?.SetException(ex);
            }
        }
        public static Task <T> BeginInvokeOnMainThreadAsync <T>(Func <T> a)
        {
            lock (_locker)
            {
                var tcs = new TaskCompletionSource <T>();

                Device.BeginInvokeOnMainThread(() =>
                {
                    try
                    {
                        var result = a();
                        tcs?.SetResult(result);
                    }
                    catch (Exception ex)
                    {
                        tcs?.SetException(ex);
                        DebugHelpers.PrintException(ex);
                    }
                });
                return(tcs?.Task);
            }
        }
Beispiel #52
0
        public async Task MemoizeAsync_BackgroundRefreshFails_NextRequestAfterDelayTriggersRefresh()
        {
            TimeSpan refreshTime        = TimeSpan.FromMinutes(1);
            TimeSpan failedRefreshDelay = TimeSpan.FromSeconds(1);
            var      refreshTask        = new TaskCompletionSource <Thing>();
            var      args       = new object[] { "someString" };
            var      dataSource = CreateDataSource(5, refreshTask, 7);

            IMemoizer memoizer = CreateMemoizer(CreateCache());

            (await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetPolicy())).Id.ShouldBe(5);

            // fake that refreshTime has passed
            TimeFake.UtcNow += refreshTime;

            // Should trigger refresh task that won't be completed yet, should get old value (5)
            (await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetPolicy())).Id.ShouldBe(5);

            // Fail the first refresh task and verify old value (5) still returned.
            // FailedRefreshDelay hasn't passed so shouldn't trigger refresh.
            refreshTask.SetException(new Exception("Boo!!"));
            (await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetPolicy())).Id.ShouldBe(5);

            TimeFake.UtcNow += TimeSpan.FromMilliseconds(failedRefreshDelay.TotalMilliseconds * 0.7);

            // FailedRefreshDelay still hasn't passed so shouldn't trigger refresh.
            (await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetPolicy())).Id.ShouldBe(5);

            TimeFake.UtcNow += TimeSpan.FromMilliseconds(failedRefreshDelay.TotalMilliseconds * 0.7);

            // FailedRefreshDelay passed so should trigger refresh.
            (await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetPolicy())).Id.ShouldBe(5);

            // Second refresh should succeed, should get new value (7);
            (await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetPolicy())).Id.ShouldBe(7);
        }
Beispiel #53
0
        private static Task <string> GetHtmlStringAsync(string url)
        {
            var tcs = new TaskCompletionSource <string>();

            var client = new WebClient()
            {
                Encoding = DBCSEncoding.GetDBCSEncoding("gb2312")
            };

            client.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    tcs.SetResult(e.Result);
                }
                else
                {
                    tcs.SetException(e.Error);
                }
            };

            client.DownloadStringAsync(new Uri(url));
            return(tcs.Task);
        }
Beispiel #54
0
                public Task <bool> ReadAsync(CancellationToken cancellationToken)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        var task = new TaskCompletionSource <bool>();
#if NET6_0_OR_GREATER
                        task.SetCanceled(cancellationToken);
#else
                        task.SetCanceled();
#endif
                        return(task.Task);
                    }

                    try
                    {
                        return(DataReader.Read() ? TaskCache.True : TaskCache.False);
                    }
                    catch (Exception ex)
                    {
                        var task = new TaskCompletionSource <bool>();
                        task.SetException(ex);
                        return(task.Task);
                    }
                }
        public async Task <string> GetAccessTokenAsync()
        {
            var taskCompletionSource = new TaskCompletionSource <string>();
            var loginCallback        = new LoginCallback()
            {
                OnSuccess = (string accessToken) => taskCompletionSource.SetResult(accessToken),
                OnFailure = (string exception) => taskCompletionSource.SetException(new Exception(exception))
            };

            using (var authFragment = new AndroidJavaClass("io.loomx.unity3d.AuthFragment"))
            {
                authFragment.CallStatic("start"); // attach to current Unity activity
                var config = JsonConvert.SerializeObject(new AuthConfig
                {
                    ClientId = this.ClientId,
                    Domain   = this.Domain,
                    Scheme   = this.Scheme,
                    Audience = this.Audience,
                    Scope    = this.Scope
                });
                authFragment.CallStatic("login", config, loginCallback);
            }
            return(await taskCompletionSource.Task);
        }
        /// <summary>
        /// Downloads data as a string from a URL.
        /// </summary>
        /// <param name="url">URL that points to data to download.</param>
        /// <returns>A string with the data.</returns>
        public static Task<string> GetStringAsync(Uri url)
        {
            var tcs = new TaskCompletionSource<string>();

            var request = HttpWebRequest.Create(url);
            request.BeginGetResponse((a) =>
            {
                try
                {
                    var r = (HttpWebRequest)a.AsyncState;
                    HttpWebResponse response = (HttpWebResponse)r.EndGetResponse(a);
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        tcs.SetResult(reader.ReadToEnd());
                    }
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }, request);

            return tcs.Task;
        }
Beispiel #57
0
        public Task <string> DoWork()
        {
            var tcs = new TaskCompletionSource <string>();

            var aTimer = new Timer();

            aTimer.Interval  = 1000;
            aTimer.AutoReset = false;
            aTimer.Enabled   = true;

            aTimer.Elapsed += (o, e) =>
            {
                if (e.SignalTime.DayOfWeek == DayOfWeek.Sunday)
                {
                    tcs.SetException(new Exception("Today is Sunday!"));
                }
                else
                {
                    tcs.SetResult("Test");
                }
            };

            return(tcs.Task);
        }
        public async Task UploadDoesWorkOnComplete(ChannelReader <string> source)
        {
            var tcs = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously);

            Context.Items[nameof(UploadDoesWorkOnComplete)] = tcs.Task;

            try
            {
                while (await source.WaitToReadAsync())
                {
                    while (source.TryRead(out var item))
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }
            finally
            {
                tcs.TrySetResult(42);
            }
        }
        public static Task <int> SendAsync(this Socket socket, byte[] buffer,
                                           int offset        = 0, int size = -1,
                                           SocketFlags flags = SocketFlags.None)
        {
            if (size < 0)
            {
                size = buffer.Length;
            }

            var source = new TaskCompletionSource <int>(socket);

            socket.BeginSend(buffer, offset, size, flags, state =>
            {
                try
                {
                    source.SetResult(socket.EndSend(state));
                }
                catch (Exception e)
                {
                    source.SetException(e);
                }
            }, source);
            return(source.Task);
        }
        private async void FindServer(TaskCompletionSource<IPEndPoint> taskCompletionSource, int timeout)
        {
            // Create a udp client
            var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort()));

            client.Client.ReceiveTimeout = timeout;

            // Construct the message the server is expecting
            var bytes = Encoding.UTF8.GetBytes("who is MediaBrowserServer?");

            // Send it - must be IPAddress.Broadcast, 7359
            var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359);

            // Send the broadcast
            await client.SendAsync(bytes, bytes.Length, targetEndPoint).ConfigureAwait(false);

            try
            {
                // Get a result back
                var result = await client.ReceiveAsync().ConfigureAwait(false);

                if (result.RemoteEndPoint.Port == targetEndPoint.Port)
                {
                    // Convert bytes to text
                    var text = Encoding.UTF8.GetString(result.Buffer);

                    // Expected response : MediaBrowserServer|192.168.1.1:1234
                    // If the response is what we're expecting, proceed
                    if (text.StartsWith("mediabrowserserver", StringComparison.OrdinalIgnoreCase))
                    {
                        text = text.Split('|')[1];

                        var vals = text.Split(':');

                        var endpoint = new IPEndPoint(IPAddress.Parse(vals[0]), int.Parse(vals[1]));

                        taskCompletionSource.SetResult(endpoint);
                        return;
                    }
                }

                taskCompletionSource.SetException(new ArgumentException("Unexpected response"));
            }
            catch (SocketException ex)
            {
                taskCompletionSource.SetException(ex);
            }
        }