public Task <Request> Execute(RequestSetting requestSetting) { taskCompletionSource = new System.Threading.Tasks.TaskCompletionSource <Request>(); Status = RequestStatus.Requesting; mClient.Client.Connect(); if (mClient.Client.IsConnected) { try { PipeStream pipeStream = mClient.Client.Stream.ToPipeStream(); Status = RequestStatus.Responding; requestSetting.Write(pipeStream); mClient.Client.Stream.Flush(); } catch (Exception e_) { try { if (mClient.Client != null) { mClient.Client.DisConnect(); } Code = REQUEST_WRITE_ERROR; } finally { OnCompleted(); } } } return(taskCompletionSource.Task); }
public Task <ReceivedUdpData> ReceiveAsync() { ThrowIfDisposed(); var taskCompletionSource = new System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>(); byte[] buffer = new byte[SsdpConstants.DefaultUdpSocketBufferSize]; _UdpClient.BeginReceiveFromGroup(buffer, 0, buffer.Length, (asyncResult) => { IPEndPoint receivedFromEndPoint; _UdpClient.EndReceiveFromGroup(asyncResult, out receivedFromEndPoint); var tcs = asyncResult.AsyncState as System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>; var result = new ReceivedUdpData() { ReceivedFrom = new UdpEndPoint() { IPAddress = receivedFromEndPoint.Address.ToString(), Port = receivedFromEndPoint.Port }, Buffer = buffer, ReceivedBytes = buffer.Length }; tcs.SetResult(result); }, taskCompletionSource ); return(taskCompletionSource.Task); }
public void TaskToObservable_NonVoid_ArgumentChecking() { ReactiveAssert.Throws<ArgumentNullException>(() => TaskObservableExtensions.ToObservable((System.Threading.Tasks.Task<int>)null)); var tcs = new System.Threading.Tasks.TaskCompletionSource<int>(); var task = tcs.Task; ReactiveAssert.Throws<ArgumentNullException>(() => task.ToObservable().Subscribe(null)); }
public Task <bool> DisplayChildForm(Action <Form> setupChildForm, int height = 600, int width = 800, Func <Form, bool?> onClosing = null, Action <Form> onDisplay = null, bool useIsolatedModelForThisChildForm = false, bool isDialog = false) { var promise = new System.Threading.Tasks.TaskCompletionSource <bool>(); // default to use the parent's model, but some child will use a DataContext and need an isolated model var childFormModel = this.Model; if (useIsolatedModelForThisChildForm == true) { childFormModel = new BindableDynamicDictionary(); } var childForm = new Form(_parentForm: this, _model: childFormModel); setupChildForm(childForm); childForm.Display_Internal(height: height, width: width, onClosing: onClosing, onDisplay: onDisplay, isDialog: isDialog) .ContinueWith(t => { promise.SetResult(t.Result); }); return(promise.Task); }
// Parallelized merge sort algorithm. Uses Task infrastructure to spread sort across available resources private static async Task ParallelSort(TDataStructure arrayToSort, int index, int length, TComparer comparer) { if (length < ParallelSortThreshold) { SequentialSort(arrayToSort, index, length, comparer); } else { TDataStructureAccessor accessor = default(TDataStructureAccessor); int halfLen = length / 2; TaskCompletionSource <bool> rightSortComplete = new System.Threading.Tasks.TaskCompletionSource <bool>(); _ = Task.Run(async() => { await ParallelSort(arrayToSort, index + halfLen, length - halfLen, comparer); rightSortComplete.SetResult(true); }); T[] localCopyOfHalfOfArray = new T[halfLen]; accessor.Copy(arrayToSort, index, localCopyOfHalfOfArray, 0, halfLen); await MergeSortCore <T, T[], ArrayAccessor <T>, TComparer, TCompareAsEqualAction> .ParallelSort(localCopyOfHalfOfArray, 0, halfLen, comparer); await rightSortComplete.Task; Merge(localCopyOfHalfOfArray, arrayToSort, index, halfLen, length, comparer); } }
public Task<ReceivedUdpData> ReceiveAsync() { ThrowIfDisposed(); var taskCompletionSource = new System.Threading.Tasks.TaskCompletionSource<ReceivedUdpData>(); byte[] buffer = new byte[SsdpConstants.DefaultUdpSocketBufferSize]; _UdpClient.BeginReceiveFromGroup(buffer, 0, buffer.Length, (asyncResult) => { IPEndPoint receivedFromEndPoint; _UdpClient.EndReceiveFromGroup(asyncResult, out receivedFromEndPoint); var tcs = asyncResult.AsyncState as System.Threading.Tasks.TaskCompletionSource<ReceivedUdpData>; var result = new ReceivedUdpData() { ReceivedFrom = new UdpEndPoint() { IPAddress = receivedFromEndPoint.Address.ToString(), Port = receivedFromEndPoint.Port }, Buffer = buffer, ReceivedBytes = buffer.Length }; tcs.SetResult(result); }, taskCompletionSource ); return taskCompletionSource.Task; }
private static Task HandleOverlayOnHide(MetroDialogSettings settings, MetroWindow window) { Task result = null; if (!window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().Any()) { result = (settings == null || settings.AnimateHide ? window.HideOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.HideOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); result = tcs.Task; } result.ContinueWith(task => { window.Invoke(() => { if (window.metroActiveDialogContainer.Children.Count == 0) { window.SetValue(MetroWindow.IsCloseButtonEnabledWithDialogPropertyKey, BooleanBoxes.TrueBox); window.RestoreFocus(); } else { var onTopShownDialogSettings = window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().LastOrDefault()?.DialogSettings; var isCloseButtonEnabled = window.ShowDialogsOverTitleBar || onTopShownDialogSettings == null || onTopShownDialogSettings.OwnerCanCloseWithDialog; window.SetValue(MetroWindow.IsCloseButtonEnabledWithDialogPropertyKey, BooleanBoxes.Box(isCloseButtonEnabled)); } }); }); return(result); }
private static void TransferCompletionToTask <T>(System.Threading.Tasks.TaskCompletionSource <T> tcs, System.ComponentModel.AsyncCompletedEventArgs e, Func <T> getResult, Action unregisterHandler) { if (e.UserState != tcs) { return; } try { unregisterHandler(); } finally { if (e.Cancelled) { tcs.TrySetCanceled(); } else if (e.Error != null) { tcs.TrySetException(e.Error); } else { tcs.TrySetResult(getResult()); } } }
static System.Threading.Tasks.Task Delay(int milliseconds) { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); new System.Threading.Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1); return(tcs.Task); }
public virtual Task <RoleLeaveZoneResponse> DoPlayerLeaveAsync(AreaZonePlayer player, RoleLeaveZoneRequest leave) { var tcs = new System.Threading.Tasks.TaskCompletionSource <RoleLeaveZoneResponse>(); this.node.PlayerLeave(player, (c) => { tcs.TrySetResult(new RoleLeaveZoneResponse() { lastScenePos = new Data.ZonePosition() { x = c.Actor.X, y = c.Actor.Y, z = c.Actor.Z, }, curHP = c.Actor.CurrentHP, curMP = c.Actor.CurrentMP, LeaveZoneSaveData = c.LastZoneSaveData, }); }, (e) => { tcs.TrySetResult(new RoleLeaveZoneResponse() { s2c_code = RoleLeaveZoneResponse.CODE_ERROR, s2c_msg = e.Message, }); }); return(tcs.Task); }
/// <summary> /// Ожидает пока окно не будет готово к взаимодействию /// </summary> /// <returns>Задача представляющая операцию и ее статус</returns> public System.Threading.Tasks.Task WaitForLoadAsync() { Dispatcher.VerifyAccess(); if (this.IsLoaded) { return(new System.Threading.Tasks.Task(() => { })); } System.Threading.Tasks.TaskCompletionSource <object> tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); RoutedEventHandler handler = null; handler = (sender, args) => { this.Loaded -= handler; this.Focus(); tcs.TrySetResult(null); }; this.Loaded += handler; return(tcs.Task); }
private static Task HandleOverlayOnShow(MetroDialogSettings settings, MetroWindow window) { return(Task.Factory.StartNew(() => { window.Invoke(() => { var isCloseButtonEnabled = window.ShowDialogsOverTitleBar || settings == null || settings.OwnerCanCloseWithDialog; window.SetValue(MetroWindow.IsCloseButtonEnabledWithDialogPropertyKey, BooleanBoxes.Box(isCloseButtonEnabled)); }); }) .ContinueWith(task => { return window.Invoke(() => { if (!window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().Any()) { return (settings == null || settings.AnimateShow ? window.ShowOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.ShowOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return tcs.Task; } }); }) .Unwrap()); }
public InputAlertDialogBase(View contentBody, bool overrideBackButton) { Content = contentBody; ShouldOverrideBackButton = overrideBackButton; // init the task completion source PageClosedTaskCompletionSource = new System.Threading.Tasks.TaskCompletionSource <T>(); this.BackgroundColor = new Color(0, 0, 0, 0.4); }
public void TaskToObservable_Void_ArgumentChecking() { ReactiveAssert.Throws <ArgumentNullException>(() => TaskObservableExtensions.ToObservable((System.Threading.Tasks.Task)null)); var tcs = new System.Threading.Tasks.TaskCompletionSource <int>(); System.Threading.Tasks.Task task = tcs.Task; ReactiveAssert.Throws <ArgumentNullException>(() => task.ToObservable().Subscribe(null)); }
public Task <ReceivedUdpData> ReceiveAsync() { ThrowIfDisposed(); var taskCompletionSource = new System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>(); byte[] buffer = new byte[SsdpConstants.DefaultUdpSocketBufferSize]; try { _UdpClient.BeginReceiveFromGroup(buffer, 0, buffer.Length, (asyncResult) => { IPEndPoint receivedFromEndPoint; try { _UdpClient.EndReceiveFromGroup(asyncResult, out receivedFromEndPoint); var tcs = asyncResult.AsyncState as System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>; var result = new ReceivedUdpData() { ReceivedFrom = new UdpEndPoint() { IPAddress = receivedFromEndPoint.Address.ToString(), Port = receivedFromEndPoint.Port }, Buffer = buffer, ReceivedBytes = buffer.Length }; tcs.SetResult(result); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.Shutdown || se.SocketErrorCode == SocketError.OperationAborted || se.SocketErrorCode == SocketError.NotConnected) { throw new SocketClosedException(se.Message, se); } throw; } }, taskCompletionSource ); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.Shutdown || se.SocketErrorCode == SocketError.OperationAborted || se.SocketErrorCode == SocketError.NotConnected) { throw new SocketClosedException(se.Message, se); } throw; } return(taskCompletionSource.Task); }
public void SetUpApp(UIApplication app) { try { Strings.Culture = new System.Globalization.CultureInfo(NSLocale.CurrentLocale.LanguageCode); } catch (Exception ex) { LogManager.Shared.Log($"Error setting Culture {System.Threading.Thread.CurrentThread.CurrentCulture}"); } SimpleAuth.OnePassword.Activate(); ApiManager.Shared.Load(); App.AlertFunction = (t, m) => { new UIAlertView(t, m, null, "Ok").Show(); }; App.Invoker = app.BeginInvokeOnMainThread; App.OnPlaying = () => { if (playingBackground != 0) { return; } playingBackground = app.BeginBackgroundTask(() => { app.EndBackgroundTask(playingBackground); playingBackground = 0; }); }; App.OnStopped = () => { if (playingBackground == 0) { return; } app.EndBackgroundTask(playingBackground); playingBackground = 0; }; App.OnShowSpinner = (title) => { BTProgressHUD.ShowContinuousProgress(title, ProgressHUD.MaskType.Clear); }; App.OnDismissSpinner = BTProgressHUD.Dismiss; App.OnCheckForOffline = (message) => { var tcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); new AlertView(Strings.DoYouWantToContinue, message) { { Strings.Continue, () => tcs.TrySetResult(true) }, { Strings.Nevermind, () => tcs.TrySetResult(false), true }, }.Show(window.RootViewController); return(tcs.Task); }; NotificationManager.Shared.LanguageChanged += (s, e) => { window.RootViewController = new RootViewController(); }; #pragma warning disable 4014 App.Start(); #pragma warning restore 4014 AutolockPowerWatcher.Shared.CheckStatus(); }
public virtual async Task <RoleEnterZoneResponse> DoPlayerEnterAsync(AreaZonePlayer player, RoleEnterZoneRequest enter) { if (await player.OnEnterAsync() == false) { log.Error("Can Not Find Session Or Logic : " + enter.roleSessionName + " : " + enter.roleUUID); } try { player.SessionReconnect(); var tcs = new System.Threading.Tasks.TaskCompletionSource <RoleEnterZoneResponse>(); this.node.PlayerEnter(player, ToAddUnit(enter), client => { if (HasAddPlayer == false) { HasAddPlayer = true; } client.Actor.SetAttribute(nameof(AreaZonePlayer.RoleSessionName), player.RoleSessionName); tcs.TrySetResult(new RoleEnterZoneResponse() { s2c_code = RoleEnterZoneResponse.CODE_OK, mapTemplateID = this.MapTemplateID, zoneUUID = this.ZoneUUID, zoneTemplateID = this.ZoneTemplateID, roleBattleData = enter.roleData, roleDisplayName = enter.roleDisplayName, roleUnitTemplateID = enter.roleUnitTemplateID, roleScenePos = new ZonePosition() { x = client.Actor.X, y = client.Actor.Y, z = client.Actor.Z }, areaName = service.SelfAddress.ServiceName, areaNode = service.SelfAddress.ServiceNode, guildUUID = enter.guildUUID, }); }, err => { tcs.TrySetResult(new RoleEnterZoneResponse() { s2c_code = RoleEnterZoneResponse.CODE_ERROR, s2c_msg = err.Message, }); }); return(await tcs.Task); } catch (Exception err) { log.Error(err); return(new RoleEnterZoneResponse() { s2c_code = RoleEnterZoneResponse.CODE_ERROR, s2c_msg = err.Message, }); } }
public Task <bool> AddAsync(string key, object value) { Guard.Against.NullOrWhiteSpace(key, "key"); Guard.Against.Null(value, "value"); _cache.Set(key, value); TaskCompletionSource <bool> tcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); tcs.SetResult(true); return(tcs.Task); }
public LanguageModalPage() { BindingContext = this; TapCommand = new Command <string>(async(language) => await SetLanguageSetting(language)); tcs = new System.Threading.Tasks.TaskCompletionSource <string>(); InitializeComponent(); }
/// <summary> /// Creates an async-compatible manual-reset event. /// </summary> /// <param name="set">Whether the manual-reset event is initially set or unset.</param> public AsyncManualResetEvent(bool set) { _sync = new object(); _tcs = new TaskCompletionSource <object>(); if (set) { //Enlightenment.Trace.AsyncManualResetEvent_Set(this, _tcs.Task); _tcs.SetResult(null); } }
public SelectTrackFilePage(string routeId) { InitializeComponent(); _vm = new SelectTrackFileViewModel(routeId) { Navigation = this.Navigation }; BindingContext = _vm; tcs = new System.Threading.Tasks.TaskCompletionSource <OperationResult>(); }
/// <summary> /// Resets the event. If the event is already reset, this method does nothing. /// </summary> public void Reset() { lock (_sync) { if (_tcs.Task.IsCompleted) { _tcs = new TaskCompletionSource <object>(); } //Enlightenment.Trace.AsyncManualResetEvent_Reset(this, _tcs.Task); } }
static void Main(string[] args) { Options options = null; try { options = Args.Parse <Options>(args); } catch (ArgException e) { Console.WriteLine(string.Format("Problems with the command line options: {0}", e.Message)); Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <Options>()); return; } var url = options.Server; // Blynk server address var authorization = options.Authorization; // Authorization token using (var client = new Client(url, authorization)) { client.Connect(); var tcs = new TaskCompletionSource <bool>(); client.OnAuthorized += v => tcs.SetResult(v); client.Login(); var authorized = tcs.Task.Result; if (authorized) { Console.WriteLine("Hardware client is authorized with given token"); client.OnVirtualWritePin += (id, value) => { Console.WriteLine($"Write Pin {id} has value {value}"); }; var counter = 0; client.OnVirtualReadPin += id => { Console.WriteLine($"Read Pin {id}"); client.WriteVirtualPin(id, counter++); }; var closeTcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); Console.CancelKeyPress += (o, e) => { closeTcs.SetResult(true); }; Console.WriteLine("Test server is active. Press CTRL+C to stop."); closeTcs.Task.Wait(); Console.WriteLine("Stopping Test server."); } else { Console.WriteLine("Cannot authorize client with given token."); } client.Disconnect(); } }
private Task <bool> Display_Internal(int height, int width, Func <Form, bool?> onClosing = null, Action <Form> onDisplay = null, bool isDialog = false) { var promise = new System.Threading.Tasks.TaskCompletionSource <bool>(); win.Height = height; win.Width = width; win.Content = this.Host; win.Closing += (_sender, _args) => { log.Debug("Window is closing"); /* * _args.Cancel = true => stops the window from closing + So what we do if they didn't specif an onClosing, is we set cancel to false */ _args.Cancel = onClosing?.Invoke(this) ?? false; if (_args.Cancel == false && promise.Task.IsCompleted == false) { promise.SetResult(true); // window is closed } }; onDisplay?.Invoke(this); // showing the form, so notify people if they wanted notification if (isDialog) { if (parentForm != null) { parentForm._Internal_ShowDialog(win) .ContinueWith(t => { if (!promise.Task.IsCompleted) { promise.SetResult(true); } }); } else { throw new Exception( "Cannot show window as ShowDialog unless you have a parent form. parentForm was null"); } } else { win.Show(); } return(promise.Task); }
private static Task HandleOverlayOnHide(MetroDialogSettings settings, MetroWindow window) { if (window.metroDialogContainer.Children.Count == 0) { return(settings == null || settings.AnimateHide ? window.HideOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.HideOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return(tcs.Task); } }
private static Task HandleOverlayOnShow(MetroDialogSettings settings, MetroWindow window) { if (!window.metroActiveDialogContainer.Children.OfType <BaseMetroDialog>().Any()) { return(settings == null || settings.AnimateShow ? window.ShowOverlayAsync() : Task.Factory.StartNew(() => window.Dispatcher.Invoke(new Action(window.ShowOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return(tcs.Task); } }
public void TaskToObservable_NonVoid_ArgumentChecking() { var s = Scheduler.Immediate; ReactiveAssert.Throws<ArgumentNullException>(() => TaskObservableExtensions.ToObservable((Task<int>)null)); ReactiveAssert.Throws<ArgumentNullException>(() => TaskObservableExtensions.ToObservable((Task<int>)null, s)); ReactiveAssert.Throws<ArgumentNullException>(() => TaskObservableExtensions.ToObservable(doneTask, default(IScheduler))); var tcs = new System.Threading.Tasks.TaskCompletionSource<int>(); var task = tcs.Task; ReactiveAssert.Throws<ArgumentNullException>(() => task.ToObservable().Subscribe(null)); }
/// <summary> /// Begins to show the MetroWindow's overlay effect. /// </summary> /// <returns>A task representing the process.</returns> public System.Threading.Tasks.Task ShowOverlayAsync() { if (_OverlayBox == null) { throw new InvalidOperationException("OverlayBox can not be founded in this MetroWindow's template. Are you calling this before the window has loaded?"); } var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); if (IsOverlayVisible() && _OverlayStoryboard == null) { //No Task.FromResult in .NET 4. tcs.SetResult(null); return(tcs.Task); } Dispatcher.VerifyAccess(); _OverlayBox.Visibility = Visibility.Visible; var sb = (Storyboard)this.Template.Resources["OverlayFastSemiFadeIn"]; sb = sb.Clone(); EventHandler completionHandler = null; completionHandler = (sender, args) => { sb.Completed -= completionHandler; if (_OverlayStoryboard == sb) { _OverlayStoryboard = null; if (IsContentDialogVisible == false) { IsContentDialogVisible = true; } } tcs.TrySetResult(null); }; sb.Completed += completionHandler; _OverlayBox.BeginStoryboard(sb); _OverlayStoryboard = sb; return(tcs.Task); }
private Task HandleOverlayOnHide(IMetroWindow metroWindow , IMetroDialogFrameSettings settings) { if (!metroWindow.MetroActiveDialogContainer.Children.OfType <IBaseMetroDialogFrame>().Any()) { return(settings == null || settings.AnimateHide ? metroWindow.HideOverlayAsync() : Task.Factory.StartNew(() => metroWindow.Dispatcher.Invoke(new Action(metroWindow.HideOverlay)))); } else { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); tcs.SetResult(null); return(tcs.Task); } }
public void TaskToObservable_Void_ArgumentChecking() { var s = Scheduler.Immediate; ReactiveAssert.Throws <ArgumentNullException>(() => TaskObservableExtensions.ToObservable((Task)null)); ReactiveAssert.Throws <ArgumentNullException>(() => TaskObservableExtensions.ToObservable((Task)null, s)); ReactiveAssert.Throws <ArgumentNullException>(() => TaskObservableExtensions.ToObservable((Task)doneTask, default(IScheduler))); var tcs = new System.Threading.Tasks.TaskCompletionSource <int>(); System.Threading.Tasks.Task task = tcs.Task; ReactiveAssert.Throws <ArgumentNullException>(() => task.ToObservable().Subscribe(null)); }
/// <summary> /// Finds the receipt associated with the specified CustomTransactionID for the currently logged in user. /// </summary> /// <param name="customTransactionID">The CustomTransactionID of the transaction. For Facebook payments this is the OrderID of the transaction.</param> /// <returns>A Task<IEnumerable<Receipt> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<Receipt>> GetReceiptForUserAndTransactionIDAsync(this Buddy.Commerce commerce, string customTransactionID) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Receipt>>(); commerce.GetReceiptForUserAndTransactionIDInternal(customTransactionID, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Saves a receipt for the purchase of an item made to the application's store. /// </summary> /// <param name="totalCost">The total cost for the items purchased in the transaction.</param> /// <param name="totalQuantity">The total number of items purchased.</param> /// <param name="storeItemID">The store ID of the item of the item being purchased.</param> /// <param name="storeName">The name of the application's store to be saved with the transaction. This field is used by the commerce analytics to track purchases.</param> /// <param name="receiptData">Optional information to store with the receipt such as notes about the transaction.</param> /// <param name="customTransactionID">An optional app-specific ID to associate with the purchase.</param> /// <param name="appData">Optional metadata to associate with the transaction.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> SaveReceiptAsync(this Buddy.Commerce commerce, string totalCost, int totalQuantity, int storeItemID, string storeName, string receiptData = "", string customTransactionID = "", string appData = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); commerce.SaveReceiptInternal(totalCost, totalQuantity, storeItemID, storeName, receiptData, customTransactionID, appData, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Retrieves a sound from the Buddy sound library, and returns a Stream. Your application should perisist this stream locally in a location such as IsolatedStorage. /// </summary> /// <param name="soundName">The name of the sound file. See the Buddy Developer Portal "Sounds" page to find sounds and get their names.</param> /// <param name="quality">The quality level of the file to retrieve.</param> public Task<Stream> GetSoundAsync(string soundName, Buddy.Sounds.SoundQuality quality) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Stream>(); this.GetSoundInternal(soundName, quality, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Finds the receipt list based on the FromDateTime parameter for the currently logged in user. /// </summary> /// <param name="fromDateTime">The starting date and time to get receipts from, leave this blank to get all the receipts.</param> /// <returns>A Task<IEnumerable<Receipt> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<Receipt>> GetReceiptsForUserAsync(this Buddy.Commerce commerce, System.Nullable<System.DateTime> fromDateTime = null) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Receipt>>(); commerce.GetReceiptsForUserInternal(fromDateTime, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
internal static Task <FileStream> FromFile(Bridge.Internal.Html5.File file) { var completer = new System.Threading.Tasks.TaskCompletionSource <FileStream>(); var fileReader = new FileReader(); fileReader.OnLoad = () => { completer.SetResult(new FileStream(fileReader.Result, file.Name)); }; fileReader.OnError = (e) => { completer.SetException(new ErrorException(e.As <dynamic>().target.error.As <string>())); }; fileReader.ReadAsArrayBuffer(file); return(completer.Task); }
/// <summary> /// Retrieves a sound from the Buddy sound library, and returns a Stream. Your application should perisist this stream locally in a location such as IsolatedStorage. /// </summary> /// <param name="soundName">The name of the sound file. See the Buddy Developer Portal "Sounds" page to find sounds and get their names.</param> /// <param name="quality">The quality level of the file to retrieve.</param> public Task <Stream> GetSoundAsync(string soundName, Buddy.Sounds.SoundQuality quality) { var tcs = new System.Threading.Tasks.TaskCompletionSource <Stream>(); this.GetSoundInternal(soundName, quality, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return(tcs.Task); }
public void SetUpApp(UIApplication app) { SimpleAuth.OnePassword.Activate(); ApiManager.Shared.Load(); App.AlertFunction = (t, m) => { new UIAlertView(t, m, null, "Ok").Show(); }; App.Invoker = app.BeginInvokeOnMainThread; App.OnPlaying = () => { if (playingBackground != 0) { return; } playingBackground = app.BeginBackgroundTask(() => { app.EndBackgroundTask(playingBackground); playingBackground = 0; }); }; App.OnStopped = () => { if (playingBackground == 0) { return; } app.EndBackgroundTask(playingBackground); playingBackground = 0; }; App.OnShowSpinner = (title) => { BTProgressHUD.ShowContinuousProgress(title, ProgressHUD.MaskType.Clear); }; App.OnDismissSpinner = BTProgressHUD.Dismiss; App.OnCheckForOffline = (message) => { var tcs = new System.Threading.Tasks.TaskCompletionSource <bool>(); new AlertView(Strings.DoYouWantToContinue, message) { { Strings.Continue, () => tcs.TrySetResult(true) }, { Strings.Nevermind, () => tcs.TrySetResult(false), true }, }.Show(window.RootViewController); return(tcs.Task); }; #pragma warning disable 4014 App.Start(); #pragma warning restore 4014 }
public async Task WinRT_NtpClient_DefaultServer_GetsNonNullResponse() { var ntpClient = new Yort.Ntp.NtpClient(); try { _GotTimeTaskCompletionSource = new TaskCompletionSource<DateTime?>(); ntpClient.TimeReceived += ntpClient_TimeReceived; ntpClient.ErrorOccurred += NtpClient_ErrorOccurred; ntpClient.BeginRequestTime(); var result = await _GotTimeTaskCompletionSource.Task; Assert.AreNotEqual(null, result); } finally { ntpClient.TimeReceived -= ntpClient_TimeReceived; } }
/// <summary> /// Create a new message group. /// </summary> /// <param name="name">The name of the new group, must be unique for the app.</param> /// <param name="openGroup">Optionally whether to make to group open for all user (anyone can join), or closed (only the owner can add users to it).</param> /// <param name="appTag">An optional application tag for this message group.</param> /// <returns>A Task<MessageGroup>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<MessageGroup> CreateAsync(this Buddy.MessageGroups messageGroups, string name, bool openGroup, string appTag = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<MessageGroup>(); messageGroups.CreateInternal(name, openGroup, appTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Delete this message group. /// </summary> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> DeleteAsync(this Buddy.MessageGroup messageGroup) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); messageGroup.DeleteInternal((bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Send a message to the entire message group. /// </summary> /// <param name="message">The message to send to this group. Must be less then 1000 characters.</param> /// <param name="latitude">The optional latitude from where this message was sent.</param> /// <param name="longitude">The optional longitude from where this message was sent.</param> /// <param name="appTag">An optional application tag for this message.</param> /// <returns>A Task<IDictionary<Int32,Boolean> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IDictionary<Int32, Boolean>> SendMessageAsync(this Buddy.MessageGroup messageGroup, string message, double latitude = 0, double longitude = 0, string appTag = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<IDictionary<Int32, Boolean>>(); messageGroup.SendMessageInternal(message, latitude, longitude, appTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Accept a friend request from a user. /// </summary> /// <param name="user">The user to accept as friend. Can't be null and must be on the friend requests list.</param> /// <param name="appTag">Tag this friend accept with a string.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> AcceptAsync(this Buddy.FriendRequests friendRequests, Buddy.User user, string appTag = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); friendRequests.AcceptInternal(user, appTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Get all sent message by the current user. /// </summary> /// <param name="afterDate">Optionally retreive only messages after a certain DateTime.</param> /// <returns>A Task<IEnumerable<Message> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<Message>> GetSentAsync(this Buddy.Messages messages, System.DateTime afterDate = default(DateTime)) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Message>>(); messages.GetSentInternal(afterDate, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Get all GameState keys and values. /// </summary> /// <returns>A Task<IDictionary<String,GameState> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IDictionary<String, GameState>> GetAllAsync(this Buddy.GameStates gameStates) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IDictionary<String, GameState>>(); gameStates.GetAllInternal((bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Get all message groups that this user is part of. /// </summary> /// <returns>A Task<IEnumerable<MessageGroup> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<MessageGroup>> GetMyAsync(this Buddy.MessageGroups messageGroups) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<MessageGroup>>(); messageGroups.GetMyInternal((bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Return all score entries for this user. /// </summary> /// <param name="recordLimit">Limit the number of entries returned.</param> /// <returns>A Task<IEnumerable<GameScore> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<GameScore>> GetAllAsync(this Buddy.GameScores gameScores, int recordLimit = 100) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<GameScore>>(); gameScores.GetAllInternal(recordLimit, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Remove a GameState key. /// </summary> /// <param name="gameStateKey">The key to remove from the GameState.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> RemoveAsync(this Buddy.GameStates gameStates, string gameStateKey) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); gameStates.RemoveInternal(gameStateKey, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Add a new score for this user. /// </summary> /// <param name="score">The numeric value of the score.</param> /// <param name="board">The optional name of the game board.</param> /// <param name="rank">The optional rank for this score. This can be used for adding badges, achievements, etc.</param> /// <param name="latitude">The optional latitude for this score.</param> /// <param name="longitude">The optional longitude for this score.</param> /// <param name="oneScorePerPlayer">The optional one-score-per-player paramter. Setting this to true will always update the score for this user, instead of creating a new one.</param> /// <param name="appTag">An optional application tag for this score.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> AddAsync(this Buddy.GameScores gameScores, double score, string board = null, string rank = null, double latitude = 0, double longitude = 0, bool oneScorePerPlayer = false, string appTag = null) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); gameScores.AddInternal(score, board, rank, latitude, longitude, oneScorePerPlayer, appTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Create a new virtual album. Note that this method internally does two web-service calls, and the IAsyncResult object /// returned is only valid for the first one. /// </summary> /// <param name="name">The name of the new virtual album.</param> /// <param name="appTag">An optional application tag for the album.</param> /// <returns>A Task<VirtualAlbum>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<VirtualAlbum> CreateAsync(this Buddy.VirtualAlbums virtualAlbums, string name, string appTag = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<VirtualAlbum>(); virtualAlbums.CreateInternal(name, appTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Get a virtual album by its globally unique identifier. All the album photos will be retreived as well. Note that this method internally does two web-service calls, and the IAsyncResult object /// returned is only valid for the first one. /// </summary> /// <param name="albumId">The ID of the virtual album to retrieve.</param> /// <returns>A Task<VirtualAlbum>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<VirtualAlbum> GetAsync(this Buddy.VirtualAlbums virtualAlbums, int albumId) { var tcs = new System.Threading.Tasks.TaskCompletionSource<VirtualAlbum>(); virtualAlbums.GetInternal(albumId, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Add a list of pictures to this virtual album. /// </summary> /// <param name="pictures">The list of pictures to add to this photo album. Either PicturePublic or Picture works.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> AddPictureBatchAsync(this Buddy.VirtualAlbum virtualAlbum, System.Collections.Generic.List<Buddy.PicturePublic> pictures) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); virtualAlbum.AddPictureBatchInternal(pictures, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Update virtual album picture comment or app.tag. /// </summary> /// <param name="picture">The picture to be updated, either PicturePublic or Picture works.</param> /// <param name="newComment">The new comment to set for the picture.</param> /// <param name="newAppTag">An optional new application tag for the picture.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> UpdatePictureAsync(this Buddy.VirtualAlbum virtualAlbum, Buddy.PicturePublic picture, string newComment, string newAppTag = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); virtualAlbum.UpdatePictureInternal(picture, newComment, newAppTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Check if a group with this name already exists. /// </summary> /// <param name="name">The name of the group to check for.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> CheckIfExistsAsync(this Buddy.MessageGroups messageGroups, string name) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); messageGroups.CheckIfExistsInternal(name, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Returns all the identity values for this user. /// </summary> /// <returns>A Task<IEnumerable<IdentityItem> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<IdentityItem>> GetAllAsync(this Buddy.Identity identity) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<IdentityItem>>(); identity.GetAllInternal((bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Send a message to a user from the current authenticated user. /// </summary> /// <param name="toUser">The user to send a message to.</param> /// <param name="message">The message to send, must be less then 200 characters.</param> /// <param name="appTag">An optional application tag to set for the message.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> SendAsync(this Buddy.Messages messages, Buddy.User toUser, string message, string appTag = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); messages.SendInternal(toUser, message, appTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Remove an identity value for this user. /// </summary> /// <param name="value">The value to remove.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> RemoveAsync(this Buddy.Identity identity, string value) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); identity.RemoveInternal(value, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Updates the value of this metadata item. /// </summary> /// <param name="value">The new value for this item, can't be null.</param> /// <param name="latitude">The optional latitude for this item.</param> /// <param name="longitude">The optional longitude for this item.</param> /// <param name="appTag">The optional application tag for this item.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> SetAsync(this Buddy.MetadataItem metadataItem, string value, double latitude = 0, double longitude = 0, string appTag = "") { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); metadataItem.SetInternal(value, latitude, longitude, appTag, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Check for the existance of an identity value in the system. The search is perform for the entire app. /// </summary> /// <param name="values">The value to search for. This can either be a single value or a semi-colon separated list of values.</param> /// <returns>A Task<IEnumerable<IdentityItemSearchResult> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<IdentityItemSearchResult>> CheckForValuesAsync(this Buddy.Identity identity, string values) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<IdentityItemSearchResult>>(); identity.CheckForValuesInternal(values, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Remove a user from the current list of friends. /// </summary> /// <param name="user">The user to remove from the friends list. Must be already on the list and can't be null.</param> /// <returns>A Task<Boolean>that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<Boolean> RemoveAsync(this Buddy.Friends friends, Buddy.User user) { var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>(); friends.RemoveInternal(user, (bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }
/// <summary> /// Returns information about all items in the store for the current application which are marked as free. /// </summary> /// <returns>A Task<IEnumerable<StoreItem> >that can be used to monitor progress on this call.</returns> public static System.Threading.Tasks.Task<IEnumerable<StoreItem>> GetFreeStoreItemsAsync(this Buddy.Commerce commerce) { var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<StoreItem>>(); commerce.GetFreeStoreItemsInternal((bcr) => { if (bcr.Error != BuddyServiceClient.BuddyError.None) { tcs.TrySetException(new BuddyServiceException(bcr.Error)); } else { tcs.TrySetResult(bcr.Result); } }); return tcs.Task; }