/// <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 Task CopyToAsync(Stream stream)
 {
     if (stream == null) {
         throw new ArgumentNullException("stream");
     }
     var tcs = new TaskCompletionSource<object>();
     try {
         var task = this.SerializeToStreamAsync(stream);
         if (task == null) {
             throw new InvalidOperationException();
         }
         task.ContinueWith(t => {
             if (t.IsFaulted) {
                 tcs.TrySetException(t.Exception.GetBaseException());
                 return;
             }
             if (t.IsCanceled) {
                 tcs.TrySetCanceled();
                 return;
             }
             tcs.TrySetResult(null);
         });
     }
     catch (Exception ex) {
         tcs.TrySetException(ex);
     }
     return tcs.Task;
 }
Example #3
0
        public static void SendLengthPrefixed <T>(this Socket socket, byte[] data, Action <Exception, Socket>?exceptionThrown, TaskCompletionSource <T>?taskCompletionSource)
        {
            byte[] lengthPrefixed = ArrayHelpers.CombineArrays(BitConverter.GetBytes(data.Length), data);

            try
            {
                socket.BeginSend(lengthPrefixed, 0, lengthPrefixed.Length, SocketFlags.None,
                                 (ar) =>
                {
                    try
                    {
                        socket.EndSend(ar);
                    }
                    catch (SocketException e)
                    {
                        exceptionThrown?.Invoke(e, socket);
                        taskCompletionSource?.TrySetException(e);
                    }
                }, socket);
            }
            catch (SocketException e)
            {
                exceptionThrown?.Invoke(e, socket);
                taskCompletionSource?.TrySetException(e);
            }
        }
        public static Task<RadioSong> GetCurrentSong()
        {
            var tcs = new TaskCompletionSource<RadioSong>();

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += (s, args) =>
            {
                if (args.Error == null)
                {
                    try
                    {
                        var json = JObject.Parse(args.Result);
                        var currentSong = new RadioSong();
                        currentSong.Album = json["album"].ToString();
                        currentSong.AlbumArt = json["album_art"].ToString();
                        currentSong.Artist = json["artist"].ToString();
                        currentSong.Title = json["title"].ToString();
                        tcs.TrySetResult(currentSong);
                    }
                    catch (Exception ex)
                    {
                        tcs.TrySetException(new HomeControllerApiException("Could not parse JSON response"));
                    }
                }
                else
                {
                    tcs.TrySetException(new HomeControllerApiException("Could not get current song"));
                }
            };
            wc.DownloadStringAsync(new Uri(BaseUrl + "music/nowplaying?nocache=" + Environment.TickCount.ToString(), UriKind.Absolute));

            return tcs.Task;
        }
Example #5
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;
        }
Example #6
0
        public async Task Connect(string host, int port) {
            TaskCompletionSource<object> connectSource = new TaskCompletionSource<object>();
            try {
                var args = new SocketAsyncEventArgs {RemoteEndPoint = new DnsEndPoint(host, port)};
                EventHandler<SocketAsyncEventArgs> connectHandler = delegate(object sender, SocketAsyncEventArgs eventArgs) {
                    try {
                        if (eventArgs.LastOperation == SocketAsyncOperation.Connect && eventArgs.SocketError == SocketError.Success) {
                            connectSource.TrySetResult(null);
                        } else {
                            connectSource.TrySetException(new TelegramSocketException("unable to connect to server: " + eventArgs.LastOperation + ", " + eventArgs.SocketError));
                        }
                    } catch (Exception e) {
                        connectSource.TrySetException(new TelegramSocketException("socket exception", e));
                    }
                };

                args.Completed += connectHandler;

                if (!socket.ConnectAsync(args)) {
                    connectHandler(this, args);
                }
            } catch (Exception e) {
                connectSource.TrySetException(new TelegramSocketException("socket exception", e));
            }

            await connectSource.Task;
        }
Example #7
0
        public async Task<byte[]> Read() {
            var readSource = new TaskCompletionSource<byte[]>();
            try {
                var args = new SocketAsyncEventArgs();
                args.SetBuffer(new byte[1024 * 8], 0, 1024 * 8);
                EventHandler<SocketAsyncEventArgs> receiveHandler = delegate(object sender, SocketAsyncEventArgs eventArgs) {
                    try {

                        if (args.LastOperation == SocketAsyncOperation.Receive && args.SocketError == SocketError.Success) {
                            if (args.BytesTransferred == 0) {
                                readSource.TrySetException(new TelegramSocketException("disconnected"));
                            } else {
                                var chunk = new byte[args.BytesTransferred];
                                Array.Copy(eventArgs.Buffer, eventArgs.Offset, chunk, 0, eventArgs.BytesTransferred);
                                readSource.TrySetResult(chunk);
                            }
                        } else {
                            readSource.TrySetException(new TelegramSocketException("read error: " + args.LastOperation + ", " + args.SocketError));
                        }
                    } catch (Exception e) {
                        readSource.TrySetException(new TelegramSocketException("read error", e));
                    }
                };

                args.Completed += receiveHandler;

                if (!socket.ReceiveAsync(args)) {
                    receiveHandler(this, args);
                }
            } catch (Exception e) {
                readSource.TrySetException(new TelegramSocketException("read error", e));
            }

            return await readSource.Task;
        }
        protected override Task<string> LoginAsyncOverride()
        {
            var tcs = new TaskCompletionSource<string>();

            var auth = new WebRedirectAuthenticator (StartUri, EndUri);
            auth.ClearCookiesBeforeLogin = false;

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

            auth.Error += (sender, e) =>
            {
                string message = String.Format (CultureInfo.InvariantCulture, Resources.IAuthenticationBroker_AuthenticationFailed, e.Message);
                InvalidOperationException ex = (e.Exception == null)
                    ? new InvalidOperationException (message)
                    : new InvalidOperationException (message, e.Exception);

                tcs.TrySetException (ex);
            };

            auth.Completed += (sender, e) =>
            {
                if (!e.IsAuthenticated)
                    tcs.TrySetException (new InvalidOperationException (Resources.IAuthenticationBroker_AuthenticationCanceled));
                else
                    tcs.TrySetResult(e.Account.Properties["token"]);
            };

            context.StartActivity (intent);
            
            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 #10
0
        /// <summary>
        /// Get the string by URI.
        /// </summary>
        /// <param name="requestUri">The Uri the request is sent to.</param>
        /// <returns>string</returns>
        public Task<string> GetStringAsync(Uri requestUri)
        {
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

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

                this.DownloadStringAsync(requestUri);

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

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

            return tcs.Task;
        }
        /// <summary>
        /// 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;
        }
        public Task<string> LoadBikeStopDataById(string id)
        {
            var client = new WebClient();
              var tcs = new TaskCompletionSource<string>();
              client.Headers[HttpRequestHeader.Referer] = "http://www.youbike.com.tw/info.php";
              client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.35 (KHTML, like Gecko) Chrome/27.0.1448.0 Safari/537.35";

              try
              {
            client.DownloadStringCompleted += (s, e) =>
            {
              if (e.Error == null)
              {
            tcs.TrySetResult(e.Result);
              }
              else
              {
            tcs.TrySetException(e.Error);
              }
            };
            client.DownloadStringAsync(new Uri("http://www.youbike.com.tw/info3b.php?sno=" + id, UriKind.Absolute));
              }
              catch (Exception ex)
              {
            tcs.TrySetException(ex);
              }

              return tcs.Task;
        }
Example #13
0
 protected virtual void OnConnectResponse(Exception exception, Response response)
 {
     Response = response;
     Task.Run(() =>
     {
         if (exception != null)
         {
             OnWSConnected = false;
             mWScompletionSource?.TrySetException(exception);
         }
         else
         {
             if (response.Code == 101)
             {
                 OnWSConnected = true;
                 mWScompletionSource?.TrySetResult(true);
             }
             else
             {
                 OnWSConnected = false;
                 mWScompletionSource?.TrySetException(new BXException($"ws connect error {response.Code} {response.Message}"));
             }
         }
     });
 }
Example #14
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 #15
0
 internal void SetError(int code, string error, string description)
 {
     this.StatusCode       = code;
     this.Error            = error;
     this.ErrorDescription = description;
     tcs?.TrySetException(new Exception(error));
 }
 /// <summary>Sends an HTTP request to the inner handler to send to the server as an asynchronous operation.</summary>
 /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
 /// <param name="request">The HTTP request message to send to the server.</param>
 /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
 protected internal override sealed Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     Action<Task<HttpResponseMessage>> continuation = null;
     if (request == null)
     {
         throw new ArgumentNullException("request", SR.net_http_handler_norequest);
     }
     TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
     try
     {
         HttpRequestMessage newRequestMessage = this.ProcessRequest(request, cancellationToken);
         if (continuation == null)
         {
             continuation = delegate (Task<HttpResponseMessage> task) {
                 if (task.IsFaulted)
                 {
                     tcs.TrySetException(task.Exception.GetBaseException());
                 }
                 else if (task.IsCanceled)
                 {
                     tcs.TrySetCanceled();
                 }
                 else if (task.Result == null)
                 {
                     tcs.TrySetException(new InvalidOperationException(SR.net_http_handler_noresponse));
                 }
                 else
                 {
                     try
                     {
                         HttpResponseMessage message = this.ProcessResponse(task.Result, cancellationToken);
                         tcs.TrySetResult(message);
                     }
                     catch (OperationCanceledException exception)
                     {
                         HandleCanceledOperations(cancellationToken, tcs, exception);
                     }
                     catch (Exception exception2)
                     {
                         tcs.TrySetException(exception2);
                     }
                 }
             };
         }
         base.SendAsync(newRequestMessage, cancellationToken).ContinueWithStandard<HttpResponseMessage>(continuation);
     }
     catch (OperationCanceledException exception)
     {
         HandleCanceledOperations(cancellationToken, tcs, exception);
     }
     catch (Exception exception2)
     {
         tcs.TrySetException(exception2);
     }
     return tcs.Task;
 }
Example #17
0
 /// <summary>
 /// Disconnect Handler
 /// </summary>
 public async void OnBillingServiceDisconnected()
 {
     try
     {
         await ConnectAsync();
     }
     catch (Exception ex)
     {
         _tcsConnect?.TrySetException(ex);
     }
 }
Example #18
0
        /// <summary>
        /// Sku/Product details Handler
        /// </summary>
        /// <param name="billingResult"></param>
        /// <param name="skuDetails"></param>
        public void OnSkuDetailsResponse(BillingResult billingResult, IList <SkuDetails> skuDetails)
        {
            try
            {
                InAppBillingProducts = new List <InAppBillingProduct>();
                if (billingResult.ResponseCode == BillingResponseCode.Ok)
                {
                    // List<string> unavailableSkus = args.UnavailableSkus;
                    if (skuDetails?.Count > 0)
                    {
                        foreach (var product in skuDetails)
                        {
                            InAppBillingProducts.Add(new InAppBillingProduct
                            {
                                Description                = product.Description,
                                LocalizedPrice             = product.Price,
                                LocalizedIntroductoryPrice = product.IntroductoryPrice,
                                CurrencyCode               = product.PriceCurrencyCode,
                                MicrosIntroductoryPrice    = product.IntroductoryPriceAmountMicros,
                                MicrosPrice                = product.PriceAmountMicros,
                                ProductId                 = product.Sku,
                                Name                      = product.Title,
                                Type                      = product.Type,
                                IconUrl                   = product.IconUrl,
                                IsRewarded                = product.IsRewarded,
                                IntroductoryPrice         = product.IntroductoryPrice,
                                IntroductoryPriceCycles   = product.IntroductoryPriceCycles,
                                IntroductoryPricePeriod   = product.IntroductoryPricePeriod,
                                SubscriptionPeriod        = product.SubscriptionPeriod,
                                FreeTrialPeriod           = product.FreeTrialPeriod,
                                OriginalPrice             = product.OriginalPrice,
                                OriginalPriceAmountMicros = product.OriginalPriceAmountMicros
                            });
                        }

                        ProductToPurcase = skuDetails[0];
                    }
                }

                var errorCode = GetErrorCode(billingResult.ResponseCode);
                if (errorCode != null) //No error
                {
                    _tcsProducts?.TrySetException(errorCode);
                }
                else
                {
                    _tcsProducts?.TrySetResult(InAppBillingProducts);
                }
            }
            catch (Exception ex)
            {
                _tcsProducts?.TrySetException(ex);
            }
        }
        private void WsClient_Closed(object sender, EventArgs e)
        {
            Debug.Assert(InnerClientInternal.State == WebSocketState.Closed);

            if (_closeTaskSrc == null)
            {
                OnClosed(CloseStatusCode.Normal, "closed event pass.");
            }

            _openTaskSrc?.TrySetException(new Exception("打开期间收到Closed事件."));
            _closeTaskSrc?.TrySetResult(true);
        }
Example #20
0
        public async Task Start(string arguments, Action<string> processData, CancellationTokenWrapper token)
        {
            var tcs = new TaskCompletionSource<object>();

            _act = (s, e) =>
            {
                _output.AppendLine(e.Data);

                try
                {
                    processData(e.Data);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            };

            var process = new Process();

            process.Exited += (s, e) => ExitedMethod((Process)s, tcs);

            process.StartInfo = CreateStartInfo(arguments);
            process.EnableRaisingEvents = true;
            process.ErrorDataReceived += _act;
            process.OutputDataReceived += _act;

            _output.Clear();

            try
            {
                process.Start();
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                token.Register(() => tcs.TrySetCanceled());
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            try
            {
                await tcs.Task;
            }
            finally
            {
                TryKillProcess(process);
                process.Dispose();
            }
        }
Example #21
0
        private async Task WatchdogOperationAsync(CancellationToken cancellationToken)
        {
            IsTriggered = false;
            var firstPetTime = FreeRunningTimer.ElapsedTime;

            while (!cancellationToken.IsCancellationRequested && !IsDisposed)
            {
                var timeTaken = FreeRunningTimer.ElapsedTime - _lastPetTime;
                var sleepTime = (int)PetTimeout.TotalMilliseconds - (int)timeTaken.TotalMilliseconds;

                // if we are configured to have a max time until triggered, check to see if we need to adjust our sleep time to take into
                // account the max available time left.  We take whichever time is less and use it as our sleep time.  If sleepTime is already
                // less then 0 then we don't have to check as we know the watchdog needs to be triggered!
                //
                if (PetMaxTimeUntilTriggered > TimeSpan.Zero && sleepTime > 0)
                {
                    var maxSleepTime = (int)PetMaxTimeUntilTriggered.TotalMilliseconds - (int)(FreeRunningTimer.ElapsedTime - firstPetTime).TotalMilliseconds;
                    if (maxSleepTime < sleepTime)
                    {
                        sleepTime = maxSleepTime;
                    }
                }

                if (sleepTime <= 0)
                {
                    break;
                }

                await sleepTime.TryDelay(cancellationToken);
            }

            lock (_lock)
            {
                if (IsDisposed)
                {
                    _triggerTcs?.TrySetException(new WatchdogDisposedException());
                    return;
                }

                if (IsCanceled)
                {
                    return;
                }

                IsTriggered = true;
                try { _triggerCallback?.Invoke(); } catch { /* ignored */ }
                _triggerTcs?.TrySetResult(true);
            }
        }
        /// <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 void SendAsync_Traces_And_Faults_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
            tcs.TrySetException(exception);
            TestTraceWriter traceWriter = new TestTraceWriter();
            RequestMessageHandlerTracer tracer = new RequestMessageHandlerTracer(traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer returns a Task that throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { return tcs.Task; });
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.Begin },
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Error) { Kind = TraceKind.End }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Task<HttpResponseMessage> task =
                method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;

            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
Example #24
0
 public void OnError(string error)
 {
     if (!HasCompleted)
     {
         tokenTask?.TrySetException(new Exception(error));
     }
 }
 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;
 }
        /// <summary>Creates the enumerable to iterate through with Iterate.</summary>
        /// <param name="functions">
        /// The functions that generate the tasks through which to iterate sequentially.
        /// Iteration will cease if a task faults.
        /// </param>
        /// <param name="tcs">The TaskCompletionSource to resolve with the asynchronous results.</param>
        /// <returns>The enumerable through which to iterate.</returns>
        private static IEnumerable<Task> TrackedSequenceInternal(
            IEnumerable<Func<Task>> functions, TaskCompletionSource<IList<Task>> tcs)
        {
            // Store a list of all tasks iterated through.  This will be provided
            // to the resulting task when we're done.
            var tasks = new List<Task>();

            // Run seqeuentially through all of the provided functions.
            foreach (var func in functions)
            {
                // Get the next task.  If we get an exception while trying to do so,
                // an invalid function was provided.  Fault the TCS and break out.
                Task nextTask = null;
                try { nextTask = func(); } catch (Exception exc) { tcs.TrySetException(exc); }
                if (nextTask == null) yield break;

                // Store the task that was generated and yield it from the sequence.  If the task
                // faults, break out of the loop so that no more tasks are processed.
                tasks.Add(nextTask);
                yield return nextTask;
                if (nextTask.IsFaulted) break;
            }

            // We're done.  Transfer all tasks we iterated through.
            tcs.TrySetResult(tasks);
        }
        /// <summary>
        /// Initializes static members of the <see cref="InvocationController"/> class.
        /// </summary>
        static InvocationController()
        {
            var assemblies = new List<Assembly> { typeof(ICalculatorActor).Assembly, typeof(IManagementGrain).Assembly };

            Actors =
                new Lazy<Dictionary<string, ActorDescription>>(
                    () => ActorDescriptionGenerator.GetActorDescriptions(assemblies));
            var dispatcherCompletion = new TaskCompletionSource<IEventDispatcher>();
            var sourceCompletion = new TaskCompletionSource<string>();
            Dispatcher = dispatcherCompletion.Task;
            DispatcherSource = sourceCompletion.Task;

            // Generate the dispatchers asynchronously.
            Task.Run(
                () =>
                {
                    try
                    {
                        string source;
                        var dispatcher = EventDispatcherGenerator.GetDispatcher(Actors.Value.Values.ToList(), out source);
                        dispatcherCompletion.TrySetResult(dispatcher);
                        sourceCompletion.TrySetResult(source);
                    }
                    catch (Exception e)
                    {
                        dispatcherCompletion.TrySetException(e);
                        sourceCompletion.TrySetException(e);
                    }
                });
        }
        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 #29
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;
        }
Example #30
0
 /// <summary>
 /// Called by <see cref="DataPortal" /> to create a
 /// new business object.
 /// </summary>
 /// <param name="objectType">Type of business object to create.</param>
 /// <param name="criteria">Criteria object describing business object.</param>
 /// <param name="context">
 /// <see cref="Server.DataPortalContext" /> object passed to the server.
 /// </param>
 /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
 public async Task<DataPortalResult> Create(
   Type objectType, object criteria, DataPortalContext context, bool isSync)
 {
   if (isSync || Csla.ApplicationContext.LogicalExecutionLocation == ApplicationContext.LogicalExecutionLocations.Server)
   {
     return await _portal.Create(objectType, criteria, context, isSync);
   }
   else
   {
     var tcs = new TaskCompletionSource<DataPortalResult>();
     var bw = new Csla.Threading.BackgroundWorker();
     bw.DoWork += (s, o) =>
     {
       o.Result = _portal.Create(objectType, criteria, context, isSync).Result;
     };
     bw.RunWorkerCompleted += (s, o) =>
     {
       if (o.Error == null)
         tcs.TrySetResult((DataPortalResult)o.Result);
       else
         tcs.TrySetException(o.Error);
     };
     bw.RunWorkerAsync();
     return await tcs.Task;
   }
 }
        public override void RestoreCompletedTransactionsFinished(SKPaymentQueue queue)
        {
            Debug.WriteLine("RestoreCompletedTransactionsFinished called...");

            try
            {
                // This is called after all restored transactions have hit UpdatedTransactions and are removed from the Queue
                // Convert all Restored transactions to the InAppBillingPurchases and return
                List <InAppPurchaseResult> purchases = _restoredTransactions.Select(rt =>
                                                                                    rt.ToInAppPurchase()).ToList();

                // Clear out the list of incoming restore transactions for future requests
                _restoredTransactions.Clear();

                _transactionsRestored?.TrySetResult(purchases);
                _transactionsRestored = null;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception {ex.ToString()}");

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

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

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
Example #33
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 void ExecuteExceptionFilterAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>() { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);
            tcs.TrySetException(exception);
            mockFilter.Setup(a => a.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task);
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            ExceptionFilterTracer tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteExceptionFilterAsync" },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "ExecuteExceptionFilterAsync" }
            };

            // Act
            Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);


            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
        /// <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;
        }
Example #36
0
        static Task <Contact> PlatformPickContactAsync()
        {
            var uiView = Platform.GetCurrentViewController();

            if (uiView == null)
            {
                throw new ArgumentNullException($"The View Controller can't be null.");
            }

            var source = new TaskCompletionSource <Contact>();

            var picker = new CNContactPickerViewController
            {
                Delegate = new ContactPickerDelegate(phoneContact =>
                {
                    try
                    {
                        source?.TrySetResult(ConvertContact(phoneContact));
                    }
                    catch (Exception ex)
                    {
                        source?.TrySetException(ex);
                    }
                })
            };

            uiView.PresentViewController(picker, true, null);

            return(source.Task);
        }
Example #37
0
        public override void DidAuthorizePayment(PKPaymentAuthorizationViewController controller, PKPayment payment, Action <PKPaymentAuthorizationStatus> completion)
        {
            var applePayClient = new BTApplePayClient(braintreeClient);

            applePayClient.TokenizeApplePayPayment(payment, (tokenizedApplePayPayment, error) =>
            {
                if (error == null)
                {
                    if (string.IsNullOrEmpty(tokenizedApplePayPayment.Nonce))
                    {
                        payTcs?.SetCanceled();
                    }
                    else
                    {
                        OnTokenizationSuccessful?.Invoke(this, tokenizedApplePayPayment.Nonce);
                        payTcs?.TrySetResult(tokenizedApplePayPayment.Nonce);
                    }

                    completion(PKPaymentAuthorizationStatus.Success);
                }
                else
                {
                    OnTokenizationError?.Invoke(this, "Error - Payment tokenization failed");
                    payTcs?.TrySetException(new Exception("Error - Payment tokenization failed"));

                    completion(PKPaymentAuthorizationStatus.Failure);
                }
            });
        }
Example #38
0
 /// <summary>
 /// Marks the specified {@code promise} as failure.  If the {@code promise} is done already, log a message.
 /// </summary>
 public static void SafeSetFailure(TaskCompletionSource promise, Exception cause)
 {
     if (promise != TaskCompletionSource.Void && !promise.TrySetException(cause))
     {
         ChannelEventSource.Log.Warning(string.Format("Failed to mark a promise as failure because it's done already: {0}", promise), cause);
     }
 }
Example #39
0
 public void OnComplete(Android.Gms.Tasks.Task task)
 {
     try {
         if (task.IsSuccessful)
         {
             var token = task.Result.ToString();
             _tokenTcs?.TrySetResult(token);
         }
         else
         {
             _tokenTcs?.TrySetException(task.Exception);
         }
     } catch (Exception ex) {
         _tokenTcs?.TrySetException(ex);
     }
 }
Example #40
0
        public Task <Contact> PickContactAsync()
        {
            var vc = WindowStateManager.Default.GetCurrentUIViewController(true);

            var source = new TaskCompletionSource <Contact>();

            var picker = new CNContactPickerViewController
            {
                Delegate = new ContactPickerDelegate(phoneContact =>
                {
                    try
                    {
                        source?.TrySetResult(ConvertContact(phoneContact));
                    }
                    catch (Exception ex)
                    {
                        source?.TrySetException(ex);
                    }
                })
            };

            if (picker.PresentationController != null)
            {
                picker.PresentationController.Delegate =
                    new UIPresentationControllerDelegate(() => source?.TrySetResult(null));
            }

            vc.PresentViewController(picker, true, null);

            return(source.Task);
        }
        public static Task RunCommandsAsync(this Pipeline pipeline)
        {
            if (pipeline == null)
            {
                throw new ArgumentNullException("pipeline");
            }

            if (pipeline.PipelineStateInfo.State == PipelineState.Completed)
            {
                return Task.FromResult<object>(null);
            }
             
            var tcs = new TaskCompletionSource<object>();
            EventHandler<PipelineStateEventArgs> stateHandler = null;
            stateHandler = (sender, args) =>
            {
                switch (args.PipelineStateInfo.State)
                {
                    case PipelineState.Stopped:
                    case PipelineState.Completed:
                        pipeline.StateChanged -= stateHandler;
                        tcs.TrySetResult(null);
                        break;
                    case PipelineState.Failed:
                        pipeline.StateChanged -= stateHandler;
                        tcs.TrySetException(args.PipelineStateInfo.Reason);
                        break;
                }
            };
            pipeline.StateChanged += stateHandler;
            pipeline.InvokeAsync();

            return tcs.Task;
        }
Example #42
0
        static ResultParameters WrapBodyDelegate(ResultParameters result)
        {
            if (result.Body != null)
            {
                var nestedBody = result.Body;
                result.Body = stream =>
                {
                    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
                    ExecutionContext.SuppressFlow();
                    ThreadPool.QueueUserWorkItem(
                        _ => nestedBody(stream)
                            .Then(() => { bool ignored = tcs.TrySetResult(null); })
                            .Catch(errorInfo =>
                            {
                                bool ignored = tcs.TrySetException(errorInfo.Exception);
                                return errorInfo.Handled();
                            }),
                        null);
                    ExecutionContext.RestoreFlow();
                    return tcs.Task;
                };
            }

            return result;
        }
Example #43
0
        protected override Task<IEnumerable<ICharacteristic>> GetCharacteristicsNativeAsync()
        {
            //TODO: review: is this correct? Event was not used, yet
            var tcs = new TaskCompletionSource<IEnumerable<ICharacteristic>>();
            EventHandler<CBServiceEventArgs> handler = null;

            handler = (sender, args) =>
            {
                _device.DiscoveredCharacteristic -= handler;
                if (args.Error == null)
                {
                    var characteristics = _service.Characteristics.Select(characteristic => new Characteristic(characteristic, _device));
                    tcs.TrySetResult(characteristics);
                }
                else
                {
                    Trace.Message("Could not discover characteristics: {0}", args.Error.Description);
                    // TODO: use proper exception
                    tcs.TrySetException(new Exception());
                }
            };

            _device.DiscoveredCharacteristic += handler;
            _device.DiscoverCharacteristics(_service);

            return tcs.Task;
        }
Example #44
0
        private async Task DispatchInternalAsync(ICommit commit, TaskCompletionSource <object> tcs, CancellationToken cancellation)
        {
            var bucket = commit.BucketId;

            // The commit is not in our scope.
            // TODO: Remove the dependency on EntityStorageEngine. Add a type for bucket-id to type and type to bucket-id translation.
            if (!EntityStorageEngine.IsInScope(bucket, _options.Scope, out var typeName))
            {
                return;
            }

            var maxNumberOfCommitAttempts = int.MaxValue;

            for (var attempt = 1; attempt <= maxNumberOfCommitAttempts; attempt++)
            {
                try
                {
                    if (attempt == 1)
                    {
                        _logger?.LogDebug($"Dispatching commit '{commit.Headers[EntityStorageEngine.ConcurrencyTokenHeaderKey]}' of stream '{commit.StreamId}'.");
                    }
                    else
                    {
                        _logger?.LogDebug($"Dispatching commit '{commit.Headers[EntityStorageEngine.ConcurrencyTokenHeaderKey]}' of stream '{commit.StreamId}' ({attempt}. attempt).");
                    }

                    var projection = ProjectAsync(typeName, commit.StreamId, tcs, cancellation);
                    var dispatch   = DispatchCoreAsync(commit, cancellation);

                    await Task.WhenAll(projection, dispatch);

                    var success = await dispatch;

                    if (success)
                    {
                        await _persistence.MarkCommitAsDispatchedAsync(commit, cancellation);

                        Task.Run(() => tcs?.TrySetResult(null)).HandleExceptions();
                        return;
                    }
                }
                catch (OperationCanceledException) when(cancellation.IsCancellationRequested)
                {
                    throw;
                }
                catch (Exception exc)
                {
                    _logger?.LogWarning(exc, $"Dispatching commit '{commit.Headers[EntityStorageEngine.ConcurrencyTokenHeaderKey]}' of stream '{commit.StreamId}' failed.");

                    Task.Run(() => tcs?.TrySetException(exc)).HandleExceptions();
                }

                // Calculate wait time in seconds
                var timeToWait = TimeSpan.FromSeconds(Pow(2, attempt - 1));

                await Task.Delay(timeToWait);
            }

            _logger?.LogError($"Dispatching commit '{commit.Headers[EntityStorageEngine.ConcurrencyTokenHeaderKey]}' of stream '{commit.StreamId}' finally failed.");
        }
 internal void SetCanceled()
 {
     _isComplete = true;
     if (!CancellationToken.IsCancellationRequested)
         CancellationToken = CancellationTokenEx.Canceled;
     _resumeEnumerationTcs?.TrySetException(new AsyncEnumerationCanceledException());
     _moveNextCompleteTcs?.TrySetCanceled();
 }
Example #46
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);
        }
Example #47
0
 public Task OnDownloadFullDatabaseFailedAsync(string message)
 {
     lock (_gate)
     {
         _taskCompletionSource?.TrySetException(new Exception(message));
         return(Task.CompletedTask);
     }
 }
Example #48
0
 public void OnComplete(Android.Gms.Tasks.Task task)
 {
     try
     {
         if (task.IsSuccessful)
         {
             string token = task.Result.JavaCast <IInstanceIdResult>().Token;
             _tokenTcs?.TrySetResult(token);
         }
         else
         {
             _tokenTcs?.TrySetException(task.Exception);
         }
     }catch (Exception ex)
     {
         _tokenTcs?.TrySetException(ex);
     }
 }
Example #49
0
            public void OnConnectionFailed(ConnectionResult result)
            {
                connectedTask?.TrySetResult(false);
                googleApiClient?.Disconnect();
                var message = GoogleApiAvailability.Instance.GetErrorDialog(CurrentActivity, result.ErrorCode, SIGN_IN_REQUEST_CODE);

                message.Show();
                Console.WriteLine(message);
                tcsSignIn?.TrySetException(new Exception(result.ErrorMessage));
            }
Example #50
0
 /// <summary>
 /// Stops the system task with an error.
 /// </summary>
 /// <param name="message">Error message.</param>
 protected void StopWithError(string message)
 {
     try
     {
         _taskCompletionSource?.TrySetException(new Exception(message));
     }
     catch (ObjectDisposedException)
     {
     }
 }
Example #51
0
        /// <summary>
        /// Purchase History Response Handler
        /// </summary>
        /// <param name="billingResult"></param>
        /// <param name="purchases"></param>
        public void OnPurchaseHistoryResponse(BillingResult billingResult, IList <PurchaseHistoryRecord> purchases)
        {
            try
            {
                PurchaseHistoryResult = new List <PurchaseResult>();
                if (billingResult.ResponseCode == BillingResponseCode.Ok || billingResult.ResponseCode == BillingResponseCode.ItemAlreadyOwned)
                {
                    if (purchases?.Count > 0)
                    {
                        foreach (var purchase in purchases)
                        {
                            var purchaseHistory = new PurchaseResult
                            {
                                Sku           = purchase.Sku,
                                PurchaseToken = purchase.PurchaseToken
                            };


                            if (purchase.PurchaseTime > 0)
                            {
                                purchaseHistory.PurchaseDate = DateTimeOffset.FromUnixTimeMilliseconds(purchase.PurchaseTime).DateTime;
                            }

                            purchaseHistory.DeveloperPayload = purchase.DeveloperPayload;

                            PurchaseHistoryResult.Add(purchaseHistory);
                        }
                    }
                    _tcsPurchaseHistory?.TrySetResult(PurchaseHistoryResult);
                }
                else
                {
                    var errorCode = GetErrorCode(billingResult.ResponseCode);

                    _tcsPurchaseHistory?.TrySetException(errorCode);
                }
            }
            catch (Exception ex)
            {
                _tcsPurchaseHistory?.TrySetException(ex);
            }
        }
Example #52
0
 protected override void OnActivityResult(Int32 requestCode, Result resultCode, Intent data)
 {
     try
     {
         PromiseResult result = PluginBridge.GetPromiseResultFromActivityResult(this, requestCode, (int)resultCode, data);
         if (result.IsError)
         {
             currentTask?.TrySetException(new Exception(result.ErrorMessage));
         }
         else
         {
             var pdfUrl = result.Result["pdfUrl"].ToString();
             currentTask?.TrySetResult(pdfUrl);
         }
     }
     catch (Exception e)
     {
         currentTask?.TrySetException(e);
     }
 }
 internal void Terminate()
 {
     lock (syncLock)
     {
         onQueueExhaustedTcs?.TrySetException(new ObjectDisposedException(nameof(AsyncEnumerableBuffer <T>)));
         onYieldTcs?.TrySetException(new ObjectDisposedException(nameof(AsyncEnumerableBuffer <T>)));
         onQueueExhaustedTcs = null;
         onYieldTcs          = null;
         queue = null;
     }
 }
Example #54
0
        /// <summary>
        /// Purchase Acknowledge Handler
        /// </summary>
        /// <param name="billingResult">returns BillingResult</param>
        public void OnAcknowledgePurchaseResponse(BillingResult billingResult)
        {
            try
            {
                var isAcknowledged = billingResult.ResponseCode == BillingResponseCode.Ok;

                var errorCode = GetErrorCode(billingResult.ResponseCode);
                if (errorCode != null) //No error
                {
                    _tcsAcknowledge?.TrySetException(errorCode);
                }
                else
                {
                    _tcsAcknowledge?.TrySetResult(isAcknowledged);
                }
            }
            catch (Exception ex)
            {
                _tcsAcknowledge?.TrySetException(ex);
            }
        }
Example #55
0
        /// <summary>
        /// Purchase Handler
        /// </summary>
        /// <param name="billingResult"></param>
        /// <param name="purchases"></param>
        public async void OnPurchasesUpdated(BillingResult billingResult, IList <Purchase> purchases)
        {
            try
            {
                PurchaseResult purchaseResult = await GetPurchaseResult(billingResult, purchases);

                var errorCode = GetErrorCode(billingResult.ResponseCode);
                if (errorCode != null) //No error
                {
                    _tcsPurchase?.TrySetException(errorCode);
                }
                else
                {
                    _tcsPurchase?.TrySetResult(purchaseResult);
                }
            }
            catch (Exception ex)
            {
                _tcsPurchase?.TrySetException(ex);
            }
        }
Example #56
0
        public async void OnConsumeResponse(BillingResult billingResult, String purchaseToken)
        {
            try
            {
                PurchaseResult purchaseResult = await GetPurchaseResult(billingResult, null);

                var errorCode = GetErrorCode(billingResult.ResponseCode);
                if (errorCode != null) //No error
                {
                    _tcsConsume?.TrySetException(errorCode);
                }
                else
                {
                    _tcsConsume?.TrySetResult(purchaseResult);
                }
            }
            catch (Exception ex)
            {
                _tcsConsume?.TrySetException(ex);
            }
        }
Example #57
0
        // TODO: Put strings into the resources.
        //
        protected virtual Task <IVh <StreamInfo> > GetSourceStreamAsync(ISubjectFileLoadContext ctx)
        {
            var taskProxy = default(TaskCompletionSource <IVh <StreamInfo> >);

            try {
                taskProxy = new TaskCompletionSource <IVh <StreamInfo> >();
                //
                ctx.EnsureNotNull(nameof(ctx));
                //
                Uri readUri;
                try {
                    readUri = ctx.BaseUri.Arg($"{nameof(ctx)}.{nameof(ctx.BaseUri)}").EnsureAbsolute().EnsureScheme(UriUtilities.UriSchemeFile).EnsureLoopbackOrUnc().Value;
                }
                catch (Exception exception) {
                    throw
                        new ArgumentException(
                            message: $"Указанный контекст загрузки имеет недопустимый базовый URI загрузки (свойство '{nameof(ctx)}.{nameof(ctx.BaseUri)}').{Environment.NewLine}\tИмя параметра:{Environment.NewLine}{nameof(ctx).IndentLines2()}{Environment.NewLine}\tКонтекст загрузки (параметр):{Environment.NewLine}{ctx.FmtStr().G().IndentLines2()}",
                            innerException: exception);
                }
                //
                var file = new FileInfo(readUri.LocalPath);
                if (file.Exists)
                {
                    taskProxy
                    .SetResult(
                        result:
                        new StreamInfo(
                            stream: new FileStream(path: file.FullName, mode: FileMode.Open, access: FileAccess.Read, share: FileShare.Read),
                            ownsStream: true)
                        .ToValueHolder(ownsValue: true));
                }
                else
                {
                    throw
                        new FileNotFoundException(
                            message: FormatXResource(locator: typeof(FileNotFoundException), subpath: null, args: new string[] { file.FullName }),
                            fileName: file.FullName);
                }
                //
                return(taskProxy.Task);
            }
            catch (Exception exception) {
                if (taskProxy?.TrySetException(exception) == true)
                {
                    return(taskProxy.Task);
                }
                else
                {
                    return(Task.FromException <IVh <StreamInfo> >(exception));
                }
            }
        }
Example #58
0
        public void OnError(Java.Lang.Exception error)
        {
            if (error is ErrorWithResponse)
            {
                ErrorWithResponse errorWithResponse = (ErrorWithResponse)error;
                BraintreeError    cardErrors        = errorWithResponse.ErrorFor("creditCard");
                if (cardErrors != null)
                {
                    BraintreeError expirationMonthError = cardErrors.ErrorFor("expirationMonth");
                    if (expirationMonthError != null)
                    {
                        OnTokenizationError?.Invoke(this, expirationMonthError.Message);
                        payTcs?.TrySetException(new System.Exception(expirationMonthError.Message));
                    }
                    else
                    {
                        OnTokenizationError?.Invoke(this, cardErrors.Message);
                        payTcs?.TrySetException(new System.Exception(cardErrors.Message));
                    }
                }
            }

            mBraintreeFragment.RemoveListener(this);
        }
        internal static void _CompleteAsyncInvoke <T>(IAsyncResult ar)
        {
            EventHandler <T>            r   = (ar as AsyncResult)?.AsyncDelegate as EventHandler <T>;
            TaskCompletionSource <bool> tcs = (ar as AsyncResult)?.AsyncState as TaskCompletionSource <bool>;

            try
            {
                r.EndInvoke(ar);
            } catch (OperationCanceledException) {
                tcs?.TrySetCanceled();
            } catch (Exception ex)
            {
                tcs?.TrySetException(ex);
            }
            tcs?.TrySetResult(true);
        }
Example #60
0
        /// <inheritdoc />
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Yield();

            TaskCompletionSource <bool>?currentTcs = null;

            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    var queueItem = _notificationQueue.Take(stoppingToken);

                    var notifications = queueItem.Notification;
                    var tcs           = queueItem.TaskCompletionSource;
                    currentTcs = tcs;

                    try
                    {
                        await ProcessNotificationAsync(notifications, stoppingToken);

                        tcs.SetResult(true);
                    }
                    catch (Exception e)
                    {
                        Logger.LogError(e, $"Error while sending notification via channel \"{ChannelType}\". Reason: {e.Message}");
                        tcs.SetException(e);
                    }

                    currentTcs = null;
                }
            }
            // Stopping, alright
            catch (Exception) when(stoppingToken.IsCancellationRequested)
            {
                _isChannelReady = false;
                Logger.LogInformation($"Processing notification by channel \"{ChannelType}\" was canceled");
                currentTcs?.TrySetCanceled();
                ProcessQueueOnChannelStop(true);
            }
            catch (Exception ex)
            {
                _isChannelReady = false;
                Logger.LogError(ex, $"Error while processing notifications by channel \"{ChannelType}\". Reason: {ex.Message}");
                currentTcs?.TrySetException(ex);
                ProcessQueueOnChannelStop(false, ex);
            }
        }