Example #1
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;
        }
        public Task<bool> ShowDialogBox(string caption, string message, string leftbuttonContent, string rightButtonContent, Func<Task> leftButtonAction, Func<Task> rightButtonAction)
        {
            var messagebox = new CustomMessageBox()
            {
                Caption = caption,
                Message = message,
                LeftButtonContent = leftbuttonContent,
                RightButtonContent = rightButtonContent
            };

            var tcs = new TaskCompletionSource<bool>();
            messagebox.Dismissed += async (s, e) =>
            {
                switch (e.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                         await leftButtonAction();
                        tcs.SetResult(true);
                        break;
                    case CustomMessageBoxResult.RightButton:
                        await rightButtonAction();

                        tcs.SetResult(true);
                        break;
                    case CustomMessageBoxResult.None:

                        tcs.SetResult(false);
                        break;
                };
            };

            messagebox.Show();

            return tcs.Task;
        }
Example #3
0
 public static Task<bool> GetIssueRiskRelatedObjects()
 {
     var task = new TaskCompletionSource<bool>();
     if (CMS.Cache.IssueRiskRelatedObjects == null)
     {
         CMS.Cache.IssueRiskRelatedObjects = new IssueRiskRelatedObjects();
         var cee = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
         DateTime now = DateTime.Now;
         System.Diagnostics.Debug.WriteLine("InterlockRiskRelatedObjectsCache First {0}", now.ToString("G"));
         //ReportLinks
         cee.GetIssueRiskRelatedObjectsCompleted += (s, e) =>
         {
             CMS.Cache.IssueRiskRelatedObjects = e.Result;
             var elapsed = DateTime.Now - now;
             System.Diagnostics.Debug.WriteLine("InterlockRiskRelatedObjectsCache: {0}", elapsed.TotalSeconds);
             task.SetResult(true);
         };
         cee.GetIssueRiskRelatedObjectsAsync();
     }
     else
     {
         task.SetResult(true);
         return task.Task; //Already loaded
     }
     return task.Task;
 }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var tcs = new TaskCompletionSource<object>();
            if (content != null && content.Headers.ContentLength == 0) return null;

            try
            {
                var reader = new BsonReader(readStream);

                if (typeof(IEnumerable).IsAssignableFrom(type)) reader.ReadRootValueAsArray = true;

                using (reader)
                {
                    var jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                    var output = jsonSerializer.Deserialize(reader, type);
                    tcs.SetResult(output);
                }
            }
            catch (Exception)
            {
                tcs.SetResult(GetDefaultValueForType(type));
            }

            return tcs.Task;
        }
        static async Task<bool?> ShowCore(XmlDocument rpDocument)
        {
            var rCompletionSource = new TaskCompletionSource<bool?>();

            var rNotification = new ToastNotification(rpDocument);

            TypedEventHandler<ToastNotification, object> rActivated = (s, e) => rCompletionSource.SetResult(true);
            rNotification.Activated += rActivated;

            TypedEventHandler<ToastNotification, ToastDismissedEventArgs> rDismissed = (s, e) => rCompletionSource.SetResult(false);
            rNotification.Dismissed += rDismissed;

            TypedEventHandler<ToastNotification, ToastFailedEventArgs> rFailed = (s, e) => rCompletionSource.SetResult(null);
            rNotification.Failed += rFailed;

            r_Notifier.Show(rNotification);

            var rResult = await rCompletionSource.Task;

            rNotification.Activated -= rActivated;
            rNotification.Dismissed -= rDismissed;
            rNotification.Failed -= rFailed;

            return rResult;
        }
        public static Task<string> Display(string title, string text = null)
        {
            Popup popup = new Popup();
            popup.Height = 240;
            popup.Width = 480;
            popup.VerticalOffset = 100;
            popup.VerticalAlignment = VerticalAlignment.Center;
            InputDialog dialog = new InputDialog();
            dialog.lblTitle.Text = title;
            dialog.txtContent.Text = text ?? "";
            popup.Child = dialog;
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
            dialog.btnCancel.Click += (s, ea) =>
            {
                tcs.SetResult(null);
                popup.IsOpen = false;
            };

            dialog.btnOk.Click += (s, ea) =>
            {
                tcs.SetResult(dialog.txtContent.Text);
                popup.IsOpen = false;
            };

            popup.IsOpen = true;
            return tcs.Task;
        }
Example #7
0
 public Task<bool> SendReport(IReport report)
 {
     var tcs = new TaskCompletionSource<bool>();
     if (MFMailComposeViewController.CanSendMail)
     {
         var c = new MFMailComposeViewController();
         c.SetSubject(report.Title);
         c.SetToRecipients(new[] {_settings.DevelopersEmail});
         c.SetMessageBody(report.Body, false);
         NSData data = new NSString(report.Attachment).DataUsingEncoding(NSStringEncoding.UTF8);
         c.AddAttachmentData(data, "text/xml", "info.xml");
         _application.RootController.PresentViewController(c, true, null);
         c.Finished += (sender, e) =>
         {
             tcs.SetResult(e.Result == MFMailComposeResult.Sent);
             e.Controller.DismissViewController(true, null);
         };
     }
     else
     {
         var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
         alert.Clicked += (sender, args) => tcs.SetResult(false);
         alert.Show();
     }
     return tcs.Task;
 }
        public async Task Should_call_on_error()
        {
            var onErrorCalled = new TaskCompletionSource<ErrorContext>();

            OnTestTimeout(() => onErrorCalled.SetResult(null));

            await StartPump(context =>
            {
                // handler enlists a failing transaction enlistment to the DTC transaction which will fail when commiting the transaction.
                Transaction.Current.EnlistDurable(EnlistmentWhichFailesDuringPrepare.Id, new EnlistmentWhichFailesDuringPrepare(), EnlistmentOptions.None);

                return Task.FromResult(0);
            },
            context =>
            {
                onErrorCalled.SetResult(context);
                return Task.FromResult(ErrorHandleResult.Handled);
            }
            ,TransportTransactionMode.TransactionScope);

            await SendMessage(InputQueueName);

            var errorContext = await onErrorCalled.Task;

            Assert.IsInstanceOf<TransactionAbortedException>(errorContext.Exception);

            // since some transports doesn't have native retry counters we can't expect the attempts to be fully consistent since if
            // dispose throws the message might be picked up before the counter is incremented
            Assert.LessOrEqual(1, errorContext.ImmediateProcessingFailures);
        }
        private static Task<int?> PlatformShow(string title, string description, List<string> buttons)
        {
            // TODO: MessageDialog only supports two buttons
            if (buttons.Count == 3)
                throw new NotSupportedException("This platform does not support three buttons");

            tcs = new TaskCompletionSource<int?>();

            MessageDialog dialog = new MessageDialog(description, title);
            foreach (string button in buttons)
                dialog.Commands.Add(new UICommand(button, null, dialog.Commands.Count));

            dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                async () =>
                {
                    try
                    {
                        // PlatformSetResult will cancel the task, resulting in an exception
                        dialogResult = dialog.ShowAsync();
                        var result = await dialogResult;
                        if (!tcs.Task.IsCompleted)
                            tcs.SetResult((int)result.Id);
                    }
                    catch (TaskCanceledException)
                    {
                        if (!tcs.Task.IsCompleted)
                            tcs.SetResult(null);
                    }
                });

            return tcs.Task;
        }
Example #10
0
        public Task<DiscoveryResult> DiscoverAddress(string webAPI)
        {
            var completionSource = new TaskCompletionSource<DiscoveryResult>();

            var baseUri = new Uri(webAPI, UriKind.Absolute);
            var requestUri = new Uri(baseUri, "rsd.xml");
            var rsdFileRequest = webRequestFactory.Create(requestUri);

            // Kick off the async discovery workflow
            rsdFileRequest.GetResponseAsync()
                .ContinueWith<DiscoveryResult>(ProcessRsdResponse)
                .ContinueWith(c =>
                {
                    if (c.Result.Success)
                        completionSource.SetResult(c.Result);
                    else
                    {
                        Trace.WriteLine(string.Format(
                            "Rsd.xml does not exist, trying to discover via link. Error was {0}", c.Result.FailMessage), "INFO");

                        DiscoverRsdLink(webAPI)
                            .ContinueWith(t => completionSource.SetResult(t.Result));
                    }
                });

            return completionSource.Task;
        }
        static int PICK_CONTACT_REQUEST = 42; // The request code
        
        protected void OnActivityResult(TaskCompletionSource<ContactInfo> tcs, ActivityResultEventArgs e) //int requestCode, Android.App.Result resultCode, Intent data)
        {
            // Check which request it is that we're responding to
            if (e.requestCode == PICK_CONTACT_REQUEST)
            {
                // Make sure the request was successful
                if (e.resultCode == Android.App.Result.Ok)
                {
                    var loader = new CursorLoader(MainActivity.Instance, e.data.Data, projection, null, null, null);
                    var cursor = (Android.Database.ICursor)loader.LoadInBackground();

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

            tcs.SetResult(null);
        }
        public async Task Should_retry_immediately(TransportTransactionMode transactionMode)
        {
            var messageRetried = new TaskCompletionSource<bool>();

            OnTestTimeout(() => messageRetried.SetResult(false));

            var hasBeenCalled = false;

            await StartPump(
                context =>
                {
                    if (hasBeenCalled)
                    {
                        messageRetried.SetResult(true);
                        return Task.FromResult(0);
                    }
                    hasBeenCalled = true;
                    throw new Exception("Simulated exception");
                },
                context => Task.FromResult(ErrorHandleResult.RetryRequired), transactionMode);

            await SendMessage(InputQueueName);

            Assert.True(await messageRetried.Task, "Should retry if asked so");
        }
        public async Task Should_retry_immediately(TransportTransactionMode transactionMode)
        {
            var messageRedelivered = new TaskCompletionSource<bool>();

            OnTestTimeout(() => messageRedelivered.SetResult(false));

            var hasBeenCalled = false;
            var onErrorCalled = false;

            await StartPump(
                context =>
                {
                    if (hasBeenCalled)
                    {
                        messageRedelivered.SetResult(true);
                        return Task.FromResult(0);
                    }
                    hasBeenCalled = true;
                    context.ReceiveCancellationTokenSource.Cancel();

                    return Task.FromResult(0);
                },
                context =>
                {
                    onErrorCalled = true;
                    return Task.FromResult(ErrorHandleResult.RetryRequired);
                }, transactionMode);

            await SendMessage(InputQueueName);

            Assert.True(await messageRedelivered.Task, "Should redeliver message");
            Assert.False(onErrorCalled, "Abort should not invoke on error");
        }
        /// <summary>
        /// Asynchronously deserializes an object of the specified type.
        /// </summary>
        /// <param name="type">The type of the object to deserialize.</param>
        /// <param name="readStream">The <see cref="T:System.IO.Stream" /> to read.</param>
        /// <param name="content">The <see cref="T:System.Net.Http.HttpContent" />, if available. It may be null.</param>
        /// <param name="formatterLogger">The <see cref="T:System.Net.Http.Formatting.IFormatterLogger" /> to log events to.</param>
        /// <returns>
        /// A <see cref="T:System.Threading.Tasks.Task" /> whose result will be an object of the given type.
        /// </returns>
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            var tcs = new TaskCompletionSource<object>();

            try
            {
                var reader = GetJsonReader(readStream);
                using (reader)
                {
                    var jsonSerializerSettings = new JsonSerializerSettings();
                    jsonSerializerSettings.Converters.Add(new HyperNewtonsoftJsonConverter());
                    var jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
                    var output = jsonSerializer.Deserialize(reader, type);
                    if (formatterLogger != null)
                    {
                        jsonSerializer.Error += (sender, e) =>
                            {
                                var exception = e.ErrorContext.Error;
                                formatterLogger.LogError(e.ErrorContext.Path, exception.Message);
                                e.ErrorContext.Handled = true;
                            };
                    }
                    tcs.SetResult(output);
                }
            }
            catch (Exception e)
            {
                if (formatterLogger == null) throw;
                formatterLogger.LogError(String.Empty, e.Message);
                tcs.SetResult(GetDefaultValueForType(type));
            }

            return tcs.Task;
        }
        /// <summary>
        /// Navigates to the given source URI and waits for the loading to complete or fail.
        /// </summary>
        public static async Task NavigateAsync(this WebView webView, Uri source)
        {
            var tcs = new TaskCompletionSource<object>();

            // Need to set it to null so that the compiler does not
            // complain about use of unassigned local variable.
            WebViewNavigationFailedEventHandler nfeh = null;
            LoadCompletedEventHandler lceh = null;

            //webView.NavigationFailed
            //webView.LoadCompleted

            nfeh = (s, e) =>
            {
                webView.NavigationFailed -= nfeh;
                webView.LoadCompleted -= lceh;
                tcs.SetResult(null);
            };

            lceh = (s, e) =>
            {
                webView.NavigationFailed -= nfeh;
                webView.LoadCompleted -= lceh;
                tcs.SetResult(null);
            };

            webView.NavigationFailed += nfeh;
            webView.LoadCompleted += lceh;

            webView.Navigate(source);

            await tcs.Task; 
        }
Example #16
0
        public static Task LoadAreasCache()
        {
            var task = new TaskCompletionSource<bool>();
            if (CMS.Cache.Areas == null)
            {
                CMS.Cache.Areas = new ObservableCollection<Area>();
                var cee = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                DateTime now = DateTime.Now;
                System.Diagnostics.Debug.WriteLine("LoadAreasCache First {0}", now.ToString("G"));

                //AREAS
                cee.GetAreasCompleted += (s1, e1) =>
                {
                    CMS.Cache.Areas = new ObservableCollection<Area>(e1.Result.OrderBy(x => x.AreaNumber));
                    var elapsed = DateTime.Now - now;
                    System.Diagnostics.Debug.WriteLine("LoadAreasCache: {0}", elapsed.TotalSeconds);
                    task.SetResult(true);
                };
                cee.GetAreasAsync();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("-----------------------------------------------------------");
                System.Diagnostics.Debug.WriteLine("LoadAreasCache: ALREADY LOADED !!!");
                System.Diagnostics.Debug.WriteLine("-----------------------------------------------------------");
                task.SetResult(true);
                return task.Task; //Already loaded
            }

            return task.Task;
        }
        public static Task<bool> DisplayYesNo(string text)
        {
            Popup popup = new Popup();
            popup.Height = 240;
            popup.Width = 480;
            popup.VerticalOffset = 100;
            popup.VerticalAlignment = VerticalAlignment.Center;
            InputDialog dialog = new InputDialog();
            dialog.lblTitle.Text = "Question";
            dialog.txtContent.Text = text;
            dialog.btnCancel.Content = "No";
            dialog.btnOk.Content = "Yes";
            popup.Child = dialog;
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            dialog.btnCancel.Click += (s, ea) =>
            {
                tcs.SetResult(false);
                popup.IsOpen = false;
            };

            dialog.btnOk.Click += (s, ea) =>
            {
                tcs.SetResult(true);
                popup.IsOpen = false;
            };

            popup.IsOpen = true;
            return tcs.Task;
        }
Example #18
0
 /// <summary>
 /// If automatic update checking is enabled, checks if there are any updates available.
 /// Returns the download URL if an update is available.
 /// Returns null if no update is available, or if no check was performed.
 /// </summary>
 public static Task<string> CheckForUpdatesIfEnabledAsync(ILSpySettings spySettings)
 {
     var tcs = new TaskCompletionSource<string>();
     UpdateSettings s = new UpdateSettings(spySettings);
     if (s.AutomaticUpdateCheckEnabled) {
         // perform update check if we never did one before;
         // or if the last check wasn't in the past 7 days
         if (s.LastSuccessfulUpdateCheck == null
             || s.LastSuccessfulUpdateCheck < DateTime.UtcNow.AddDays(-7)
             || s.LastSuccessfulUpdateCheck > DateTime.UtcNow)
         {
             GetLatestVersionAsync().ContinueWith(
                 delegate (Task<AvailableVersionInfo> task) {
                     try {
                         s.LastSuccessfulUpdateCheck = DateTime.UtcNow;
                         AvailableVersionInfo v = task.Result;
                         if (v.Version > currentVersion)
                             tcs.SetResult(v.DownloadUrl);
                         else
                             tcs.SetResult(null);
                     } catch (AggregateException) {
                         // ignore errors getting the version info
                         tcs.SetResult(null);
                     }
                 });
         } else {
             tcs.SetResult(null);
         }
     } else {
         tcs.SetResult(null);
     }
     return tcs.Task;
 }
        public Task Publish(string queue, byte[] data)
        {
            var tcs = new TaskCompletionSource<int>();
            lock (_pending)
                _pending.Add(tcs.Task);

            Func<byte[], Task> handler;
            lock (_handlers)
            {
                handler = _handlers[queue];
            }
            ThreadPool.QueueUserWorkItem(async _ =>
            {
                try
                {
                    await handler(data);
                }
                catch (Exception e)
                {
                    lock (_pending)
                        _pending.Remove(tcs.Task);
                    tcs.SetResult(0);
                    _logger("Error executing handler", e);
                    return;
                }
                lock (_pending)
                    _pending.Remove(tcs.Task);
                tcs.SetResult(0);

            });
            return Task.FromResult(0);
        }
Example #20
0
        public static async Task<JObject> GetJson(String url)
        {
            var tcs = new TaskCompletionSource<string>();
            var client = new WebClient();
            client.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    tcs.SetResult(e.Result);
                }
                else
                {
                    tcs.SetResult(null);
                }
            };

            client.DownloadStringAsync(new Uri(url));

            return await tcs.Task.ContinueWith<JObject>((task) =>
                {
                    if (task.Result != null)
                    {
                        return JObject.Parse(task.Result);
                    }
                    else
                    {
                        return null;
                    }
                });
        }
Example #21
0
        public Task OpenEmailManager(string[] emails, string subject, string text, string[] attachments)
        {
            var tcs = new TaskCompletionSource<bool>();
            if (MFMailComposeViewController.CanSendMail)
            {
                var c = new MFMailComposeViewController();
                c.SetToRecipients(emails);
                c.SetSubject(subject ?? "");
                c.SetMessageBody(text ?? "", false);
                foreach (string attachment in attachments)
                {
                    NSData data = NSData.FromFile(attachment);
                    if (data != null)
                        c.AddAttachmentData(data, GetMimeType(attachment), Path.GetFileName(attachment));
                }

                _application.RootController.PresentViewController(c, true, null);
                c.Finished += (sender, e) =>
                {
                    tcs.SetResult(e.Result == MFMailComposeResult.Sent);
                    _application.InvokeOnMainThread(() => e.Controller.DismissViewController(true, null));
                };
            }
            else
            {
                var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
                alert.Clicked += (sender, args) => tcs.SetResult(false);
                alert.Show();
            }
            return tcs.Task;
        }
Example #22
0
        public Task ContinueWith(Action<Task> continuationAction)
        {
            //Console.WriteLine("enter __Task.ContinueWith " + new { this.IsCompleted, continuationAction });

            var x = new TaskCompletionSource<object>();

            if (this.IsCompleted)
            {
                continuationAction(this);
                x.SetResult(null);
            }
            else
            {
                InternalContinueWithAfterIsCompleted +=
                    delegate
                    {
                        if (x == null)
                            return;

                        continuationAction(this);
                        x.SetResult(null);
                        x = null;
                    };
            }


            //Console.WriteLine("exit __Task.ContinueWith " + new { this.IsCompleted, continuationAction });
            return x.Task;
        }
        public async Task Should_dispatch_the_message(TransportTransactionMode transactionMode)
        {
            var messageReceived = new TaskCompletionSource<bool>();

            OnTestTimeout(() => messageReceived.SetResult(false));

            await StartPump(
                context =>
                {
                    if (context.Headers.ContainsKey("FromOnError"))
                    {
                        messageReceived.SetResult(true);
                        return Task.FromResult(0);
                    }

                    throw new Exception("Simulated exception");
                },
                async context =>
                {
                    await SendMessage(InputQueueName, new Dictionary<string, string> { { "FromOnError", "true" } }, context.TransportTransaction);

                    return ErrorHandleResult.Handled;
                }, transactionMode);

            await SendMessage(InputQueueName);

            Assert.True(await messageReceived.Task, "Message not dispatched properly");
        }
 static TaskCompletionSource<bool?> GenerateTcs(ToastNotification notification) {
     var tcs = new TaskCompletionSource<bool?>();
     notification.Dismissed += (sender, args) => tcs.SetResult(false);
     notification.Activated += (sender, args) => tcs.SetResult(true);
     notification.Failed += (sender, args) => tcs.SetException(args.ErrorCode);
     return tcs;
 }
        public async static Task<ExceptionRoutedEventArgs> WaitForLoadedAsync(this BitmapImage bitmapImage)
        {
            var tcs = new TaskCompletionSource<ExceptionRoutedEventArgs>();

            // Need to set it to noll so that the compiler does not
            // complain about use of unassigned local variable.
            RoutedEventHandler reh = null;
            ExceptionRoutedEventHandler ereh = null;

            reh = (s, e) =>
            {
                bitmapImage.ImageOpened -= reh;
                bitmapImage.ImageFailed -= ereh;
                tcs.SetResult(null);
            };


            ereh = (s, e) =>
            {
                bitmapImage.ImageOpened -= reh;
                bitmapImage.ImageFailed -= ereh;
                tcs.SetResult(e);
            };

            bitmapImage.ImageOpened += reh;
            bitmapImage.ImageFailed += ereh;

            return await tcs.Task;
        }
        private static Task<string> PlatformShow(string title, string description, string defaultText, bool usePasswordMode)
        {
            tcs = new TaskCompletionSource<string>();

            var keyboardViewController = new KeyboardInputViewController(
                title, description, defaultText, usePasswordMode, gameViewController);

            UIApplication.SharedApplication.InvokeOnMainThread(delegate
            {
                gameViewController.PresentViewController(keyboardViewController, true, null);

                keyboardViewController.View.InputAccepted += (sender, e) =>
                {
                    gameViewController.DismissViewController(true, null);

                    if (!tcs.Task.IsCompleted)
                        tcs.SetResult(keyboardViewController.View.Text);
                };

                keyboardViewController.View.InputCanceled += (sender, e) =>
                {
                    gameViewController.DismissViewController(true, null);

                    if (!tcs.Task.IsCompleted)
                        tcs.SetResult(null);
                };
            });

            return tcs.Task;
        }
        public static Task<string> AuthenticateAsync(Uri uri)
        {
            var tcs = new TaskCompletionSource<string>();

              var w = new WebView
              {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            VerticalAlignment = VerticalAlignment.Stretch,
            Margin = new Thickness(30.0),
              };

              var b = new Border
              {
            Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)),
            Width = Window.Current.Bounds.Width,
            Height = Window.Current.Bounds.Height,
            Child = w
              };

              var p = new Popup
              {
            Width = Window.Current.Bounds.Width,
            Height = Window.Current.Bounds.Height,
            Child = b,
            HorizontalOffset = 0.0,
            VerticalOffset = 0.0
              };

              Window.Current.SizeChanged += (s, e) =>
              {
            p.Width = e.Size.Width;
            p.Height = e.Size.Height;
            b.Width = e.Size.Width;
            b.Height = e.Size.Height;
              };

              w.Source = uri;

              w.NavigationCompleted += (sender, args) =>
              {
            if (args.Uri != null)
            {
              if (args.Uri.OriginalString.Contains("access_token"))
              {
            tcs.SetResult(args.Uri.ToString());
            p.IsOpen = false;
              }
              if (args.Uri.OriginalString.Contains("error=access_denied"))
              {
            tcs.SetResult(null);
            p.IsOpen = false;
              }
            }
              };

              p.IsOpen = true;
              return tcs.Task;
        }
 public Task<bool> PromptYesNo(string title, string message)
 {
     var tcs = new TaskCompletionSource<bool>();
     var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
     alert.AddAction(UIAlertAction.Create("No", UIAlertActionStyle.Cancel, x => tcs.SetResult(false)));
     alert.AddAction(UIAlertAction.Create("Yes", UIAlertActionStyle.Default, x => tcs.SetResult(true)));
     ViewController.PresentViewController(alert, true, null);
     return tcs.Task;
 }
Example #29
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            var tcs = new TaskCompletionSource<object>();

            if (!_write(new ArraySegment<byte>(buffer, offset, count), () => tcs.SetResult(null)))
                tcs.SetResult(null);

            return tcs.Task;
        }
 public static void Dispose_ThenUseTaskCompletionSource()
 {
     var tcs = new TaskCompletionSource<int>();
     tcs.SetResult(1);
     tcs.Task.Dispose();
     Assert.Throws<InvalidOperationException>(() => tcs.SetResult(2));
     Assert.Throws<InvalidOperationException>(() => tcs.SetCanceled());
     Assert.Throws<InvalidOperationException>(() => tcs.SetException(new Exception()));
     Assert.Equal(1, tcs.Task.Result);
 }
Example #31
0
 public void Do()
 {
     try
     {
         Action !();
         Complete?.SetResult();
     }
     catch (Exception e)
     {
         Complete?.SetException(e);
     }
 }
Example #32
0
        private void ExecuteSynchronously(
            TaskCompletionSource <object> completion,
            SendOrPostCallback d,
            object state)
        {
            // Anything run on the sync context should actually be dispatched as far as Photino
            // is concerned, so that it's safe to interact with the native window/WebView.
            _invokeMethodInfo.Invoke(_window, new Action[] { () =>
                                                             {
                                                                 var original = Current;
                                                                 try
                                                                 {
                                                                     _state.IsBusy = true;
                                                                     SetSynchronizationContext(this);
                                                                     d(state);
                                                                 }
                                                                 finally
                                                                 {
                                                                     _state.IsBusy = false;
                                                                     SetSynchronizationContext(original);

                                                                     completion?.SetResult(null);
                                                                 }
                                                             } });
        }
Example #33
0
        private async void ScheduleTimeout()
        {
            try
            {
                await Task.Delay(TimeSpan.FromMilliseconds(_sendTimeout), _cts.Token);
            }
            catch (TaskCanceledException)
            {
                return;
            }
            TaskCompletionSource <CommandError> ctl = null;
            var isSending = false;

            //spin lock
            while (Interlocked.CompareExchange(ref _taskLockTag, CASHelper.LockUsed, CASHelper.LockFree) != CASHelper.LockFree)
            {
            }
            if (_lastCommand != null)
            {
                isSending       = true;
                _lastCommand    = null;
                ctl             = _currentTaskCtl;
                _currentTaskCtl = null;
            }
            //free lock
            Interlocked.CompareExchange(ref _taskLockTag, CASHelper.LockFree, CASHelper.LockUsed);

            if (!isSending)
            {
                return;
            }

            ctl?.SetResult(CommandError.Timeout);
        }
Example #34
0
        public Task <OfflinePack[]> GetPacks()
        {
            var tsc           = new TaskCompletionSource <OfflinePack[]>();
            var sharedStorage = MGLOfflineStorage.SharedOfflineStorage;
            var packs         = sharedStorage.Packs;

            if (packs == null)
            {
                /*
                 * This property is set to nil, indicating that the receiver does not yet know the existing packs,
                 * for an undefined amount of time starting from the moment the shared offline storage object is initialized
                 * until the packs are fetched from the database. After that point, this property is always non-nil,
                 * but it may be empty to indicate that no packs are present.
                 * To detect when the shared offline storage object has finished loading its packs property,
                 * observe KVO change notifications on the packs key path. The initial load results in an NSKeyValueChangeSetting change.
                 */
                getPacksTask        = tsc;
                packsObservingToken = sharedStorage.AddObserver("packs", NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, (obj) => {
                    var allPacks = sharedStorage.Packs;
                    if (allPacks != null)
                    {
                        getPacksTask?.SetResult(allPacks?.Select((arg) => arg.ToFormsPack()).ToArray());
                        packsObservingToken?.Dispose();
                        packsObservingToken = null;
                        getPacksTask        = null;
                    }
                });
            }
            else
            {
                tsc.SetResult(packs.Select((arg) => arg.ToFormsPack()).ToArray());
            }
            return(tsc.Task);
        }
Example #35
0
        private void WriterRelease()
        {
            TaskCompletionSource <Releaser> toWake = null;
            bool toWakeIsWriter = false;

            lock (_waitingWriters)
            {
                if (_waitingWriters.Count > 0)
                {
                    toWake         = _waitingWriters.Dequeue();
                    toWakeIsWriter = true;
                }
                else if (_readersWaiting > 0)
                {
                    toWake          = _waitingReader;
                    _status         = _readersWaiting;
                    _readersWaiting = 0;
                    _waitingReader  = new TaskCompletionSource <Releaser>();
                }
                else
                {
                    _status = 0;
                }
            }

            _reset(this);

            toWake?.SetResult(new Releaser(this, toWakeIsWriter));
        }
Example #36
0
        /// <summary>
        /// Executes at the end of each work cycle on the same task scheduler.
        /// </summary>
        private void CheckForMoreWork()
        {
            TaskCompletionSource <Task> signal = null;
            Task taskToSignal = null;

            lock (_lockable)
            {
                if (_moreWork)
                {
                    _moreWork = false;

                    // see if someone created a promise for waiting for the next work cycle
                    // if so, take it and remove it
                    signal = this._nextWorkCyclePromise;
                    this._nextWorkCyclePromise = null;

                    // start the next work cycle
                    Start();

                    // the current cycle is what we need to signal
                    taskToSignal = _currentWorkCycle;
                }
                else
                {
                    _currentWorkCycle = null;
                }
            }

            // to be safe, must do the signalling out here so it is not under the lock
            signal?.SetResult(taskToSignal);
        }
Example #37
0
            /// <inheritdoc />
            public void OnDataReceived(BinaryReader reader)
            {
                string command = reader.ReadString();

                DebugLog($"Received command: {command}");
                switch (command)
                {
                case MarkerVisualLocalizationSettings.CoordinateAssignedHeader:
                    coordinateId = reader.ReadString();
                    DebugLog($"Assigned coordinate id: {coordinateId}");
                    coordinateAssigned?.SetResult(coordinateId);
                    break;

                case MarkerVisualLocalizationSettings.CoordinateFoundHeader:
                    string detectedId = reader.ReadString();
                    if (coordinateId == detectedId)
                    {
                        DebugLog($"Ending discovery: {coordinateId}");
                        discoveryCTS?.Cancel();

                        DebugLog($"Coordinate was found: {coordinateId}");
                        coordinateFound?.SetResult(detectedId);
                    }
                    else
                    {
                        DebugLog($"Unexpected coordinate found, expected: {coordinateId}, detected: {detectedId}");
                    }
                    break;

                default:
                    DebugLog($"Sent unknown command: {command}");
                    break;
                }
            }
        /// <summary>
        /// 设置一个信号量,让一个waitone获得信号,每次调用 <see cref="Set"/> 方法最多只有一个等待通过
        /// </summary>
        public void Set()
        {
            TaskCompletionSource <bool> releaseSource = null;
            bool result;

            lock (_locker)
            {
                if (_waitQueue.Count > 0)
                {
                    releaseSource = _waitQueue.Dequeue();
                }

                if (releaseSource is null)
                {
                    if (!_isSignaled)
                    {
                        _isSignaled = true;
                    }
                }

                // 如果这个类被释放了,那么返回 false 值
                result = !_isDisposed;
            }

            releaseSource?.SetResult(result);
        }
        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);
                }
            });
        }
Example #40
0
        /// <summary>处理收到的数据</summary>
        /// <param name="stream"></param>
        /// <param name="remote"></param>
        internal override void OnReceive(Stream stream, IPEndPoint remote)
        {
            // 过滤自己广播的环回数据。放在这里,兼容UdpSession
            if (!Loopback && remote.Port == Port)
            {
                if (!Local.Address.IsAny())
                {
                    if (remote.Address.Equals(Local.Address))
                    {
                        return;
                    }
                }
                else
                {
                    foreach (var item in NetHelper.GetIPsWithCache())
                    {
                        if (remote.Address.Equals(item))
                        {
                            return;
                        }
                    }
                }
            }

#if !__MOBILE__
            // 更新全局远程IP地址
            NewLife.Web.WebHelper.UserHost = remote.ToString();
#endif
            // 分析处理
            var e = new ReceivedEventArgs();
            e.Stream    = stream;
            e.UserState = remote;

            // 同步匹配
            _recv?.SetResult(e);
            _recv = null;

            // 为该连接单独创建一个会话,方便直接通信
            var session = CreateSession(remote);
            // 数据直接转交给会话,不再经过事件,那样在会话较多时极为浪费资源
            var us = session as UdpSession;
            if (us != null)
            {
                us.OnReceive(e);
            }
            else
            {
                // 没有匹配到任何会话时,才在这里显示日志。理论上不存在这个可能性
                if (Log.Enable && LogReceive)
                {
                    WriteLog("Recv [{0}]: {1}", e.Length, e.ToHex());
                }
            }

            if (session != null)
            {
                RaiseReceive(session, e);
            }
        }
Example #41
0
 private void inputTextBox_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         StringTaskCompletionSource?.SetResult(inputTextBox.Text);
         inputTextBox.Text = String.Empty;
     }
 }
Example #42
0
        private async void lv_opcion_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var entidad = ((ListView)sender).SelectedItem as ent_mensaje;

            _tcs?.SetResult(entidad.cod_mensaje);
            //_ent?.SetResult(entidad);
            await Navigation.PopAllPopupAsync();
        }
        void OnLoggedOn(SteamUser.LoggedOnCallback callback)
        {
            _steamAccount.SteamId = _client.SteamID;
            bool isSteamGuard = callback.Result == EResult.AccountLogonDenied;
            bool is2Fa        = callback.Result == EResult.AccountLoginDeniedNeedTwoFactor;

            tryLoginCount++;
            if (tryLoginCount > 5)
            {
                _loginTcs?.SetResult(callback.Result);
            }
            if (isSteamGuard || is2Fa)
            {
                // Console.WriteLine("This account is SteamGuard protected!");

                if (is2Fa)
                {
                    _twoFactorAuth = _steamAccount.MobileAuth.GenerateSteamGuardCode();
                }
                else
                {
                    throw new NotImplementedException("Not inplemented auth code. Only mobile auth");
                }
                return;
            }

            if (callback.Result != EResult.OK)
            {
                if (callback.Result == EResult.InvalidPassword)
                {
                    _steamAccount.LoginKey = null;
                    _steamAccount.Save();
                }
                else if (callback.Result == EResult.NoConnection)
                {
                    SteamServerList.SetBadServer(_serverRecord);
                    _serverRecord = SteamServerList.GetServerRecord();
                }

                Console.WriteLine("Unable to logon to Steam: {0} / {1}", callback.Result, callback.ExtendedResult);
                return;
            }

            Console.WriteLine("Successfully logged on!");
            _loginTcs?.SetResult(callback.Result);
        }
 /// <summary>
 /// Require lock.
 /// </summary>
 /// <param name="m"></param>
 /// <param name="packetId"></param>
 void FreeId(IInputLogger?m, int packetId)
 {
     lock ( _idStore )
     {
         _idStore.FreeId(m, packetId);
         _idFullTCS?.SetResult(null);
     }
 }
Example #45
0
 private void LockedUpdateEnqueueAccess()
 {
     for (int i = ItemsQueue.Count; EnqueueAccess.Count > 0 && (ThrottleLevelLimiter == null || i < ThrottleLevelLimiter); i++)
     {
         TaskCompletionSource <object> tcs = EnqueueAccess.Dequeue();
         tcs?.SetResult(null);
     }
 }
Example #46
0
        public void ExtractResultJson(MethodResult result)
        {
            switch (result.Method.Name)
            {
            case MethodType.CheckBle:
                if (bool.TryParse(result.Result, out bool bleOK))
                {
                    bleTsc?.SetResult(bleOK);
                }
                else
                {
                    bleTsc?.SetResult(false);
                }
                break;

            case MethodType.Scan:
                if (string.IsNullOrEmpty(result.Result))
                {
                    scanTsc?.SetResult(new string[0]);
                }
                else
                {
                    scanTsc?.SetResult(result.Result.Split(','));
                }
                break;

            case MethodType.Connect:
                var id = result.Method.Param;
                if (connectTscDict.ContainsKey(id))
                {
                    if (bool.TryParse(result.Result, out bool success))
                    {
                        connectTscDict[id]?.SetResult(success);
                    }
                    else
                    {
                        connectTscDict[id]?.SetResult(false);
                    }
                }
                break;

            default:
                // Do Nothing
                break;
            }
        }
Example #47
0
 private void HandlePong(Packet msg)
 {
     if (Logger.IsTraceEnabled)
     {
         Logger.Trace($"{P2PSession.RemoteNodeId} P2P pong on {P2PSession.RemotePort} ({RemoteClientId})");
     }
     _pongCompletionSource?.SetResult(msg);
 }
Example #48
0
        void BtnSend(System.Object sender, System.EventArgs e)
        {
            PopupNavigation.Instance.PopAsync();
            Contact contact = new Contact();

            contact.Name = txtFName.Text + " " + txtLName.Text;
            _tcs?.SetResult(contact);
        }
        public Command(string command, string workingDirectory = "", params string[] args)
        {
            _process = new Process();

            _process.StartInfo.CreateNoWindow = true;
            _process.StartInfo.WindowStyle    = ProcessWindowStyle.Hidden;

            _process.StartInfo.UseShellExecute = false;

            _process.StartInfo.RedirectStandardOutput = true;
            _process.StartInfo.RedirectStandardInput  = true;
            _process.StartInfo.RedirectStandardError  = true;

            _process.StartInfo.FileName = command;

            if (args != null && args.Length > 0)
            {
                _process.StartInfo.Arguments = string.Join(" ", args);
            }

            if (!string.IsNullOrEmpty(workingDirectory))
            {
                _process.StartInfo.WorkingDirectory = workingDirectory;
            }

            _process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                if (!(e.Data == null))
                {
                    stringBuilderError.AppendLine(e.Data);
                    if (string.IsNullOrEmpty(lastOutput) || lastOutput.Trim() == "")
                    {
                        lastOutput = e.Data;
                    }
                }
                else
                {
                    errorCloseEvent?.SetResult(true);
                }
            });

            _process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                if (!(e.Data == null))
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        lastOutput = e.Data;
                        outputList.Add(e.Data);
                    }
                    outputList.Add(Environment.NewLine);
                }
                else
                {
                    completeCloseEvent?.SetResult(true);
                }
            });
        }
Example #50
0
        public void Update(ExchangeTypesItemsExchangerDescriptionForUserMessage message)
        {
            if (!MercyBotMain.Instance.Server.IsSubscribedToTouch || !MercyBotMain.Instance.Server.HasExtension(ExtensionsEnum.HDV))
            {
                return;
            }

            _itemDescriptionTcs?.SetResult(message.ItemTypeDescriptions);
        }
 /// <summary>
 /// Process a received height map
 /// </summary>
 /// <returns>Asynchronous task</returns>
 private static async Task HandleHeightMap()
 {
     DataTransfer.ReadHeightMap(out Heightmap map);
     using (await _heightmapLock.LockAsync())
     {
         _getHeightmapRequest?.SetResult(map);
         _getHeightmapRequest = null;
     }
 }
        private static void PlatformCancel(string?result)
        {
            if (_dialog != null)
            {
                _dialog.Close();
            }

            _tcs?.SetResult(result);
        }
Example #53
0
        private void WebSocketOnClosed(object sender, EventArgs e)
        {
            if (_response?.Task.Status != TaskStatus.RanToCompletion)
            {
                _response?.SetResult(string.Empty);
            }

            Closed?.Invoke(this, e);
        }
Example #54
0
        public void OnCancelled(object sender, EventArgs args)
        {
            TaskCompletionSource <FileData> tcs = Interlocked.Exchange(ref this.completionSource, null);

            FilePickerActivity.FilePicked        -= this.OnCompleted;
            FilePickerActivity.FilePickCancelled -= this.OnCancelled;

            tcs?.SetResult(null);
        }
Example #55
0
        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;
        }
Example #56
0
 public BaseViewAnimator()
 {
     AnimatorAgent = CAAnimationGroup.CreateAnimation();
     AnimatorAgent.AnimationStarted += (sender, e) => { };
     AnimatorAgent.AnimationStopped += (sender, e) =>
     {
         tcs?.SetResult(true);
     };
 }
        private void OutputProduced(IProjectVersionedValue <DesignTimeInputSnapshot> val)
        {
            _outputProduced.Add(val.Value);

            if (_outputProduced.Count == _expectedOutput)
            {
                _outputProducedSource?.SetResult(true);
            }
        }
Example #58
0
        /// <summary>
        /// Sets dialog invocation result.
        /// Completes the task awaited in <see cref="AwaitResult{TResult}"/>.
        /// </summary>
        /// <param name="result">The object to return to the caller. It should be of <see cref="AwaitedResultType"/> type.</param>
        /// <exception cref="ArgumentException">Thrown when given <see cref="result"/> doesn't match <see cref="AwaitedResultType"/></exception>
        public void SetResult(object result)
        {
            if (AwaitedResultType != result.GetType())
            {
                throw new ArgumentException($"Result should be of {AwaitedResultType.Name} type.");
            }

            _resultCompletionSource?.SetResult(result);
        }
        void RootPush(Page newPage, TaskCompletionSource <bool> pushInfoOnCompletedTask = null)
        {
            Device.BeginInvokeOnMainThread(async() =>
            {
                try
                {
                    if (Application.Current.MainPage == null)
                    {
                        var masterPage = GetInitializedPage(AppPages.Main.ToString());
                        //Xamarin.Forms return exception when master page title is null
                        //this title not visible in app
                        masterPage.Title             = nameof(masterPage);
                        var detailPage               = new NavigationPage(newPage);
                        Application.Current.MainPage = new MasterDetailPage
                        {
                            Master = masterPage,
                            Detail = detailPage
                        };
                    }
                    else if (Application.Current.MainPage is MasterDetailPage mp)
                    {
                        mp.IsPresented = false;
                        await Task.Delay(250);
                        if (mp.Detail is NavigationPage navigationPage)
                        {
                            var navigation      = navigationPage.Navigation;
                            var navigationStack = navigationPage.Navigation.NavigationStack;
                            if (navigationStack.Any())
                            {
                                navigation.InsertPageBefore(newPage, navigationStack.FirstOrDefault());
                                await navigation.PopToRootAsync();
                            }
                        }

                        pushInfoOnCompletedTask?.SetResult(true);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    pushInfoOnCompletedTask?.SetResult(false);
                }
            });
        }
Example #60
0
        private Task HubConnectionOnReconnected(string arg)
        {
            lock (_reconnectingLock)
            {
                _reconnectingTask?.SetResult(true);
                _reconnectingTask = null;
            }

            return(Task.CompletedTask);
        }