void Load ()
		{
			var monitor = loadMonitor;
			System.Threading.ThreadPool.QueueUserWorkItem (delegate {
				try {
					HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create (url);
					WebResponse resp = req.GetResponse ();
					MemoryStream ms = new MemoryStream ();
					using (var s = resp.GetResponseStream ()) {
						s.CopyTo (ms);
					}
					var data = ms.ToArray ();

					MonoDevelop.Ide.DispatchService.GuiSyncDispatch (delegate {
						Gdk.PixbufLoader l = new Gdk.PixbufLoader (resp.ContentType);
						l.Write (data);
						image = l.Pixbuf;
						l.Close ();
						monitor.Dispose ();
					});
					
					// Replace the async operation to avoid holding references to all
					// objects that subscribed the Completed event.
					loadOperation = NullAsyncOperation.Success;
				} catch (Exception ex) {
					loadMonitor.ReportError (null, ex);
					Gtk.Application.Invoke (delegate {
						monitor.Dispose ();
					});
					loadOperation = NullAsyncOperation.Failure;
				}
				loadMonitor = null;
			});
		}
        public async static Task<bool> showPopup(string message, bool errorServer = false)
        {
            // Close the previous one out
            if (messageDialogCommand != null)
            {
                messageDialogCommand.Cancel();
                messageDialogCommand = null;
            }

            MessageDialog dlg = new MessageDialog(message);

            if (errorServer)
            {
                dlg.Commands.Clear();
                dlg.Commands.Add(new UICommand("Retry"));
                dlg.Commands.Add(new UICommand("Cancel"));
            }

            messageDialogCommand = dlg.ShowAsync();
            var res = await messageDialogCommand;

            if (errorServer && res.Label == "Retry")
                return false;
            return true;
        }
        /// <summary>
        /// Displays a dialog and a toast notification corresponding to the given beacon action.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnBeaconActionResolvedAsync(object sender, BeaconAction e)
		{
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                MessageDialog messageDialog = e.ToMessageDialog();

                switch (e.Type)
                {
                    case BeaconActionType.UrlMessage:
                    case BeaconActionType.VisitWebsite:
                        messageDialog.Commands.Add(new UICommand("Yes",
                            new UICommandInvokedHandler(async (command) =>
                            {
                                await Windows.System.Launcher.LaunchUriAsync(new Uri(e.Url));
                                _beaconActionDialogOperation.Cancel();
                                _beaconActionDialogOperation = null;
                            })));

                        messageDialog.Commands.Add(new UICommand("No"));

                        _beaconActionDialogOperation = messageDialog.ShowAsync();
                        break;

                    case BeaconActionType.InApp:
                        await messageDialog.ShowAsync();
                        break;
                }
            });
        }
        async void OnButtonClick(object sender, RoutedEventArgs e) {
            MessageDialog msgdlg = new MessageDialog("Choose a color", "How to Async #1");
            msgdlg.Commands.Add(new UICommand("Red", null, Colors.Red));
            msgdlg.Commands.Add(new UICommand("Green", null, Colors.Green));
            msgdlg.Commands.Add(new UICommand("Blue", null, Colors.Blue));

            // Start a five-second timer
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(5);
            timer.Tick += OnTimerTick;
            timer.Start();

            // Show the MessageDialog
            asyncOp = msgdlg.ShowAsync();
            IUICommand command = null;

            try {
                command = await asyncOp;
            }
            catch (Exception) {
                // The exception in this case will be TaskCanceledException
            }

            // Stop the timer
            timer.Stop();

            // If the operation was canceled, exit the method
            if (command == null) {
                return;
            }

            // Get the Color value and set the background brush
            Color clr = (Color)command.Id;
            contentGrid.Background = new SolidColorBrush(clr);
        }
 public AsyncOperationBitmapProvider(IAsyncOperation<Bitmap> bitmapAsyncOperation)
 {
     m_bitmapAsyncOperation = bitmapAsyncOperation
         .AsTask()
         .ContinueWith(t => (IReadableBitmap)t.Result, TaskContinuationOptions.OnlyOnRanToCompletion|TaskContinuationOptions.ExecuteSynchronously)
         .AsAsyncOperation();
 }
Example #6
0
        /// <summary>
        /// 语音识别
        /// </summary>
        /// <returns>识别文本</returns>
        public async Task<string> RecognizeAsync()
        {
            if (_initialization == null || _initialization.IsFaulted)
                _initialization = InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);

            await _initialization;

            CancelRecognitionOperation();

            // Start recognition.
            try
            {
                _recognitionOperation = _speechRecognizer.RecognizeWithUIAsync();
                SpeechRecognitionResult speechRecognitionResult = await _recognitionOperation;
                // If successful, return the recognition result.
                if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
                    return speechRecognitionResult.Text;
                else
                    throw new Exception($"Speech recognition failed. Status: {speechRecognitionResult.Status}");
            }
            catch (Exception ex) when ((uint)ex.HResult == HResultPrivacyStatementDeclined)
            {
                // Handle the speech privacy policy error.
                var messageDialog = new MessageDialog("您没有同意语音识别隐私声明,请同意后重试");
                await messageDialog.ShowAsync();
                throw;
            }
        }
        /// <summary>
        /// Shows the dialog. It takes <see cref="SystemDialogViewModel"/> to populate the system dialog. It also sets the first command to be 
        /// the default and last one to be the cancel command.
        /// </summary>
        /// <param name="viewType"> Type of dialog control. </param>
        public async void Show(Type viewType)
        {
            this.Initialize(); 

            var dialog = new MessageDialog(ViewModel.ActivationData.Message, ViewModel.ActivationData.Title);
            foreach (var command in ViewModel.ActivationData.Commands)
            {
                dialog.Commands.Add(new UICommand(command));
            }

            dialog.DefaultCommandIndex = 0;
            dialog.CancelCommandIndex = (uint)ViewModel.ActivationData.Commands.Length - 1;

            try
            {
                this.dialogTask = dialog.ShowAsync();
                var result = await this.dialogTask;

                this.dialogTask = null;
                this.NavigationService.GoBack(result.Label);
            }
            catch (TaskCanceledException ex)
            {
                // Happens when you call nanavigationSerivce.GoBack(...) while the dialog is still open.
            }
        }
        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;
        }
		public ImageLoader (string url)
		{
			loadMonitor = new NullProgressMonitor ();
			loadOperation = loadMonitor.AsyncOperation;
			this.url = url;
			Load ();
		}
 private async void AsyncMethodWithViewModel(IAsyncOperation<bool> asyncOperation, bool result, IViewModel viewModel)
 {
     bool b = await asyncOperation;
     b.ShouldEqual(result);
     ViewModel = viewModel;
     AsyncMethodInvoked = true;
 }
Example #11
0
		protected void ExecuteFile (IAsyncOperation op)
		{
//			if (op.Success)
//				ProfilingOperations.Profile (profiler, doc);

			//if (op.Success)
			//	doc.Run ();
		}
Example #12
0
 private void DisplayException(Exception ex)
 {
     var dialog = new MessageDialog(ex.ToString(), ex.Message);
     if (showOperation != null)
     {
         showOperation.Cancel();
     }
     showOperation = dialog.ShowAsync();
 }
 public void AddOperation(IAsyncOperation operation)
 {
     lock (list) {
         if (monitor.IsCancelRequested)
             operation.Cancel ();
         else
             list.Add (operation);
     }
 }
Example #14
0
        public async Task Navigate(string url)
        {
            manualResetEvent.Reset();

            Browser.Navigate(new Uri(url));
            asyncDialog = ShowAsync();

            await Task.Run(() => manualResetEvent.WaitOne());
        }
        void OnMessageDialogShowAsyncCompleted(IAsyncOperation<IUICommand> asyncInfo, AsyncStatus asyncStatus) {
            // Get the Color value
            IUICommand command = asyncInfo.GetResults();
            clr = (Color)command.Id;

            // Use a Dispatcher to run in the UI thread
            IAsyncAction asyncAction = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                OnDispatcherRunAsyncCallback);
        }
 /// <summary>
 /// Closes the dialog.
 /// </summary>
 /// <param name="viewType"> Type of dialog control. </param>
 public void Hide(Type viewType)
 {
     if (this.dialogTask != null)
     {
         var task = this.dialogTask;
         this.dialogTask = null;
         task.Cancel();
     }
 }
        async private void GetConnectivityIntervalsAsyncHandler(IAsyncOperation<IReadOnlyList<ConnectivityInterval>> asyncInfo, AsyncStatus asyncStatus)
        {
            if (asyncStatus == AsyncStatus.Completed)
            {
                try
                {
                    String outputString = string.Empty;
                    IReadOnlyList<ConnectivityInterval> connectivityIntervals = asyncInfo.GetResults();

                    if (connectivityIntervals == null)
                    {
                        rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                            {
                                rootPage.NotifyUser("The Start Time cannot be later than the End Time, or in the future", NotifyType.StatusMessage);
                            });
                        return;
                    }

                    // Get the NetworkUsage for each ConnectivityInterval
                    foreach (ConnectivityInterval connectivityInterval in connectivityIntervals)
                    {
                        outputString += PrintConnectivityInterval(connectivityInterval);

                        DateTimeOffset startTime = connectivityInterval.StartTime;
                        DateTimeOffset endTime = startTime + connectivityInterval.ConnectionDuration;
                        IReadOnlyList<NetworkUsage> networkUsages = await InternetConnectionProfile.GetNetworkUsageAsync(startTime, endTime, Granularity, NetworkUsageStates);

                        foreach (NetworkUsage networkUsage in networkUsages)
                        {
                            outputString += PrintNetworkUsage(networkUsage, startTime);
                            startTime += networkUsage.ConnectionDuration;
                        }
                    }

                    rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
                        });
                }
                catch (Exception ex)
                {
                    rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            rootPage.NotifyUser("An unexpected error occurred: " + ex.Message, NotifyType.ErrorMessage);
                        });
                }
            }
            else
            {
                rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        rootPage.NotifyUser("GetConnectivityIntervalsAsync failed with message:\n" + asyncInfo.ErrorCode.Message, NotifyType.ErrorMessage);
                    });
            }
        }
Example #18
0
        public static bool CloseDialog()
        {
            if ( DialogCommand != null )
            {
                DialogCommand.Cancel();
                DialogCommand = null;
                return true;
            }

            return false;
        }
		void OperCompleted (IAsyncOperation op)
		{
			bool raiseEvent;
			lock (operations) {
				completed++;
				success = success && op.Success;
				successWithWarnings = success && op.SuccessWithWarnings;
				raiseEvent = (completed == operations.Count);
			}
			if (raiseEvent && Completed != null)
				Completed (this);
		}
Example #20
0
 void AppServiceConnectionCompleted(IAsyncOperation<AppServiceConnectionStatus> operation, AsyncStatus asyncStatus)
 {
     var status = operation.GetResults();
     if (status == AppServiceConnectionStatus.Success)
     {
         var secondOperation = _appServiceConnection.SendMessageAsync(null);
         secondOperation.Completed = (_, __) =>
         {
             _appServiceConnection.Dispose();
             _appServiceConnection = null;
         };
     }
 }
Example #21
0
        private void complete_failed_request(Exception ex, HttpContext http, IAsyncOperation aop)
        {
            var errMsg = "ProcessRequest() failed ({0}); {1}".Fmt(http.Request.Path, ex.Message);

            if (ex is BadRequestException)
                _log.Error(errMsg);
            else
                _log.Error(ex, errMsg);

            http.set_error_response(ex.Message);

            aop.MarkAsSynchronous();
            aop.NotifyCompletion();
        }
Example #22
0
 private void GeoLocationCompleted(IAsyncOperation<Geoposition> asyncInfo, AsyncStatus asyncStatus)
 {
     if (asyncStatus == AsyncStatus.Completed)
     {
         var deviceLocation = (Geoposition)asyncInfo.GetResults();
         try
         {
             DeviceLocation = GeoLocationAdapter.GetLocationFromDeviceGeoPositionObject(deviceLocation);
         }
         catch (Exception ex)
         {
             DeviceLocation = GeoLocationAdapter.GetDefaultLocaiton();
         }
         OnLocationLoadSuccess(new LocationEventArgs(DeviceLocation));
     }
 }
        private void OnFileOpened(IAsyncOperation op)
        {
            if (!op.Success) return;

            IMember member = CurrentNode.DataItem as IMember;
            int line = member.Region.BeginLine;
            string file = GetFileName ();

            IWorkbenchWindow window = Runtime.FileService.GetOpenFile (file);
            if (window == null) {
                return;
            }

            IViewContent content = window.ViewContent;
            if (content is IPositionable) {
                ((IPositionable)content).JumpTo (Math.Max (1, line), 1);
            }
        }
Example #24
0
        public async static Task<bool> ShowDialog( ContentDialog dlg )
        {
            // Close the previous one out
            CloseDialog();

            dlg.Closed += Dlg_Closed;
            DialogCommand = dlg.ShowAsync();
            try
            {
                await DialogCommand;
            }
            catch ( OperationCanceledException )
            {

            }

            return true;
        }
        public  async static Task< string> RecognizeVoiceCommand()
        {
            try
            {             
                speechRecognizer = await ResourceHelper.InitRecognizer() ;
                if(null == speechRecognizer)
                {
                    _command = ResourceHelper.GetString("Sys Err");//"系统异常";
                    return _command;
                }
                
                recognitionOperation = speechRecognizer.RecognizeAsync();

                SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;

                // If successful, display the recognition result. A cancelled task should do nothing.

                if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
                {
                    if (speechRecognitionResult.Confidence == SpeechRecognitionConfidence.Rejected)
                    {
                        _command = ResourceHelper.GetString("invalid");//"对不起,无法识别您的命令";
                    }
                    else
                    {
                        string tag = "unknown";
                        if (speechRecognitionResult.Constraint != null)
                        {
                            // Only attempt to retreive the tag if we didn't hit the garbage rule.
                            tag = speechRecognitionResult.Constraint.Tag;
                        }

                        _command = speechRecognitionResult.Text;
                    }
                }
                return _command;
            }
            catch (Exception e)
            {
                return e.Message;
            }                     
        }
Example #26
0
        public async static Task<bool> ShowDialog( MessageDialog dlg )
        {
            // Close the previous one out
            if ( MsgDialogCommand != null )
            {
                MsgDialogCommand.Cancel();
                MsgDialogCommand = null;
            }

            MsgDialogCommand = dlg.ShowAsync();
            try
            {
                await MsgDialogCommand;
            }
            catch( OperationCanceledException )
            {

            }

            return true;
        }
        async private void GeocodingCompleted(IAsyncOperation<MapLocationFinderResult> asyncInfo, AsyncStatus asyncStatus)
        {
            // Get the result
            MapLocationFinderResult result = asyncInfo.GetResults();

            // 
            // Update the UI thread by using the UI core dispatcher.
            // 
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                // Update the status
                Status = result.Status;

                // Update th Address
                Address = result.Locations[0].Address.FormattedAddress;

                // If there are Name and/or description provided and they are not set yet, set them!
                if (Name == NameDefault && result.Locations[0].DisplayName != null && result.Locations[0].DisplayName != "") Name = result.Locations[0].DisplayName;
                if (Description == DescriptionDefault && result.Locations[0].Description != null && result.Locations[0].Description != "") Description = result.Locations[0].Description;

                // If the Name is still empty, use the Address
                if (Name == NameDefault || Name == "") Name = Address;
            });
        }
Example #28
0
        /// <inheritdoc/>
        public bool GetNextOperation(IAsyncOperation current, IEnumerable <IAsyncOperation> ops, out IAsyncOperation next)
        {
            if (this.IsReplaying)
            {
                var enabledOperations = ops.Where(op => op.Status is AsyncOperationStatus.Enabled).ToList();
                if (enabledOperations.Count == 0)
                {
                    next = null;
                    return(false);
                }

                try
                {
                    if (this.ScheduledSteps >= this.ScheduleTrace.Count)
                    {
                        this.ErrorText = "Trace is not reproducible: execution is longer than trace.";
                        throw new InvalidOperationException(this.ErrorText);
                    }

                    ScheduleStep nextStep = this.ScheduleTrace[this.ScheduledSteps];
                    if (nextStep.Type != ScheduleStepType.SchedulingChoice)
                    {
                        this.ErrorText = "Trace is not reproducible: next step is not a scheduling choice.";
                        throw new InvalidOperationException(this.ErrorText);
                    }

                    next = enabledOperations.FirstOrDefault(op => op.Id == nextStep.ScheduledOperationId);
                    if (next is null)
                    {
                        this.ErrorText = $"Trace is not reproducible: cannot detect id '{nextStep.ScheduledOperationId}'.";
                        throw new InvalidOperationException(this.ErrorText);
                    }
                }
                catch (InvalidOperationException ex)
                {
                    if (this.SuffixStrategy is null)
                    {
                        if (!this.Configuration.DisableEnvironmentExit)
                        {
                            Error.ReportAndExit(ex.Message);
                        }

                        next = null;
                        return(false);
                    }
                    else
                    {
                        this.IsReplaying = false;
                        return(this.SuffixStrategy.GetNextOperation(current, ops, out next));
                    }
                }

                this.ScheduledSteps++;
                return(true);
            }

            return(this.SuffixStrategy.GetNextOperation(current, ops, out next));
        }
Example #29
0
        async Task <BitmapImage> LoadImageAsync(IRandomAccessStreamReference thumbStreamReference)
        {
            m_profilePictureReadAsync = null;

            // Contact is not yet supported.
            throw new NotSupportedException("Contact is not yet supported");

            //var operation = thumbStreamReference.OpenReadAsync();

            //operation.Completed(
            //	AsyncOperationCompletedHandler<IRandomAccessStreamWithContentType>(
            //		[strongThis, completedFunction](
            //			IAsyncOperation<IRandomAccessStreamWithContentType> operation,
            //			AsyncStatus asyncStatus)
            //{
            //	strongThis.m_dispatcherHelper.RunAsync(
            //		[strongThis, asyncStatus, completedFunction, operation]()
            //	{
            //		BitmapImage bitmap;

            //		// Handle the failure case here to ensure we are on the UI thread.
            //		if (asyncStatus != AsyncStatus.Completed)
            //		{
            //			strongThis.m_profilePictureReadAsync = null);
            //			return;
            //		}

            //		try
            //		{
            //			bitmap.SetSourceAsync(operation.GetResults()).Completed(
            //				AsyncActionCompletedHandler(
            //					[strongThis, completedFunction, bitmap](IAsyncAction, AsyncStatus asyncStatus)
            //			{
            //				if (asyncStatus != AsyncStatus.Completed)
            //				{
            //					strongThis.m_profilePictureReadAsync = null);
            //					return;
            //				}

            //				completedFunction(bitmap);
            //				strongThis.m_profilePictureReadAsync = null);
            //			}));
            //		}
            //		catch (hresult_error &e)
            //		{
            //			strongThis.m_profilePictureReadAsync = null);

            //			// Ignore the exception if the image is invalid
            //			if (e.to_abi() == E_INVALIDARG)
            //			{
            //				return;
            //			}
            //			else
            //			{
            //				throw;
            //			}
            //		}
            //	});
            //}));

            //m_profilePictureReadAsync = operation;
        }
Example #30
0
 private void TextBlock_Tapped_1(object sender, TappedRoutedEventArgs e)
 {
     var uri = new Uri("https://www.facebook.com/EGAppFactory");
     IAsyncOperation <bool> x = Windows.System.Launcher.LaunchUriAsync(uri);
 }
        private void ProcessConcreteCompletedOperation(IAsyncOperation <bool> completedOperation, out long bytesCompleted)
        {
            bool success = completedOperation.GetResults();

            bytesCompleted = (success ? 0 : -1);
        }
Example #32
0
        private async void StartRecognizeEvent()
        {
            IAsyncOperation <SpeechRecognitionCompilationResult> op = reco.CompileConstraintsAsync();

            op.Completed += HandleCompilationCompleted;
        }
Example #33
0
        public override void Invoke(IAsyncOperation asyncOp)
        {
            if (IsCompleted)
            {
                return;
            }

            if (Interlocked.Decrement(ref _count) == 0)
            {
                List <Exception> exceptions = null;
                IAsyncOperation  canceledOp = null;

                foreach (var op in _ops)
                {
                    if (op.IsFaulted)
                    {
                        if (exceptions == null)
                        {
                            exceptions = new List <Exception>()
                            {
                                op.Exception
                            };
                        }
                    }
                    else if (op.IsCanceled)
                    {
                        canceledOp = op;
                    }
                }

                if (exceptions != null)
                {
                    TrySetExceptions(exceptions);
                }
                else if (canceledOp != null)
                {
                    TrySetCanceled();
                }
                else if (typeof(T) == typeof(VoidResult))
                {
                    TrySetCompleted();
                }
                else
                {
                    var results = new List <T>(_ops.Length);

                    foreach (var op in _ops)
                    {
                        if (op is IAsyncOperation <T> rop)
                        {
                            results.Add(rop.Result);
                        }
                    }

                    TrySetResult(results.ToArray());
                }
            }
            else
            {
                ReportProgress();
            }
        }
Example #34
0
 public static ConfiguredTaskAwaitable <T> DontSync <T>(this IAsyncOperation <T> self)
 {
     return(self.AsTask().ConfigureAwait(false));
 }
Example #35
0
        public async void HandleCompilationCompleted(IAsyncOperation <SpeechRecognitionCompilationResult> opInfo, AsyncStatus status)
        {
            if (status == AsyncStatus.Completed)
            {
                System.Diagnostics.Debug.WriteLine("CompilationCompleted");
                var result = opInfo.GetResults();

                System.Diagnostics.Debug.WriteLine(result.ToString());

                IAsyncOperation <Windows.Media.SpeechRecognition.SpeechRecognitionResult> speechRecognitionResult = reco.RecognizeAsync();
                speechRecognitionResult.Completed += RecogComplated;
            }
        }
Example #36
0
 public static Task <TResult> AsTask <TResult>(this IAsyncOperation <TResult> source, CancellationToken cancellationToken)
 => source.AsTaskCore(cancellationToken);
Example #37
0
        private IEnumerator LoadSourceControllerModel(InteractionSource source)
        {
            byte[]     fileBytes;
            GameObject controllerModelGameObject;

            if (GLTFMaterial == null)
            {
                Debug.Log("If using glTF, please specify a material on " + name + ".");
                yield break;
            }

#if !UNITY_EDITOR
            // This API returns the appropriate glTF file according to the motion controller you're currently using, if supported.
            IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.TryGetRenderableModelAsync();

            if (modelTask == null)
            {
                Debug.Log("Model task is null; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            while (modelTask.Status == AsyncStatus.Started)
            {
                yield return(null);
            }

            IRandomAccessStreamWithContentType modelStream = modelTask.GetResults();

            if (modelStream == null)
            {
                Debug.Log("Model stream is null; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            if (modelStream.Size == 0)
            {
                Debug.Log("Model stream is empty; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            fileBytes = new byte[modelStream.Size];

            using (DataReader reader = new DataReader(modelStream))
            {
                DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size);

                while (loadModelOp.Status == AsyncStatus.Started)
                {
                    yield return(null);
                }

                reader.ReadBytes(fileBytes);
            }
#else
            IntPtr controllerModel = new IntPtr();
            uint   outputSize      = 0;

            if (TryGetMotionControllerModel(source.id, out outputSize, out controllerModel))
            {
                fileBytes = new byte[Convert.ToInt32(outputSize)];

                Marshal.Copy(controllerModel, fileBytes, 0, Convert.ToInt32(outputSize));
            }
            else
            {
                Debug.Log("Unable to load controller models; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }
#endif

            controllerModelGameObject = new GameObject {
                name = "glTFController"
            };
            GLTFComponent gltfScript = controllerModelGameObject.AddComponent <GLTFComponent>();
            gltfScript.GLTFConstant = gltfScript.GLTFStandard = gltfScript.GLTFStandardSpecular = GLTFMaterial.shader;
            gltfScript.UseStream    = true;
            gltfScript.GLTFStream   = new MemoryStream(fileBytes);

            yield return(gltfScript.WaitForModelLoad());

            FinishControllerSetup(controllerModelGameObject, source.handedness, GenerateKey(source));
        }
Example #38
0
 public static Task <TResult> AsTask <TResult>(this IAsyncOperation <TResult> source)
 => source.AsTaskCore(CancellationToken.None);
Example #39
0
        /// <inheritdoc/>
        public bool GetNextOperation(IAsyncOperation current, IEnumerable <IAsyncOperation> ops, out IAsyncOperation next)
        {
            next = null;
            var enabledOperations = ops.Where(op => op.Status is AsyncOperationStatus.Enabled).ToList();

            if (enabledOperations.Count == 0)
            {
                return(false);
            }

            IAsyncOperation highestEnabledOp = this.GetPrioritizedOperation(enabledOperations, current);

            if (next is null)
            {
                next = highestEnabledOp;
            }

            this.ScheduledSteps++;

            return(true);
        }
Example #40
0
		public IAsyncOperation Execute (IBuildTarget entry, ExecutionContext context)
		{
			if (currentRunOperation != null && !currentRunOperation.IsCompleted) return currentRunOperation;

			NullProgressMonitor monitor = new NullProgressMonitor ();

			DispatchService.ThreadDispatch (delegate {
				ExecuteSolutionItemAsync (monitor, entry, context);
			});
			currentRunOperation = monitor.AsyncOperation;
			currentRunOperationOwner = entry;
			currentRunOperation.Completed += delegate {
			 	DispatchService.GuiDispatch (() => {
					var error = monitor.Errors.FirstOrDefault ();
					if (error != null)
						IdeApp.Workbench.StatusBar.ShowError (error.Message);
					currentRunOperationOwner = null;
				});
			};
			return currentRunOperation;
		}
Example #41
0
 private void OnAssetInstantiated(IAsyncOperation <GameObject> asyncOp)
 {
     Debug.Log(asyncOp.Result.name + " loaded.");
 }
Example #42
0
        // Instead of using the async and await keywords, actual Tasks will be returned.
        // That way, components consuming these APIs can await the returned tasks
        public IAsyncOperation <ChannelAndWebResponse> OpenChannelAndUploadAsync(String url)
        {
            IAsyncOperation <PushNotificationChannel> channelOperation = PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

            return(ExecuteChannelOperation(channelOperation, url, MAIN_APP_TILE_KEY, true));
        }
        internal StreamFlushAsyncResult(IAsyncOperation <bool> asyncStreamFlushOperation, bool processCompletedOperationInCallback)

            : base(asyncStreamFlushOperation, null, null, processCompletedOperationInCallback)
        {
            asyncStreamFlushOperation.Completed = this.StreamOperationCompletedCallback;
        }
Example #44
0
 internal static void WatchForError <T>(this IAsyncOperation <T> self) =>
 self.AsTask().WatchForError();
Example #45
0
        private void RecogComplated(IAsyncOperation <SpeechRecognitionResult> asyncInfo, AsyncStatus asyncStatus)
        {
            var result = asyncInfo.GetResults(); //result of speech
            var status = asyncStatus.ToString(); //succes or failed

            ReadCommands(result.Text, status.ToString());
            IAsyncOperation <Windows.Media.SpeechRecognition.SpeechRecognitionResult> speechRecognitionResult = reco.RecognizeAsync();

            speechRecognitionResult.Completed += RecogComplated;//restarts recognation
        }
Example #46
0
        public static async Task <T> WithTimeout <T>(this IAsyncOperation <T> task, double timeout)
        {
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeout));

            return(await task.AsTask(cts.Token));
        }
Example #47
0
        private void LaunchCmdProcess(string commandLineText)
        {
            var args           = String.Format("/C \"{0}\"", commandLineText);;
            var standardOutput = new InMemoryRandomAccessStream();
            var standardError  = new InMemoryRandomAccessStream();
            var options        = new ProcessLauncherOptions
            {
                StandardOutput   = standardOutput,
                StandardError    = standardError,
                WorkingDirectory = GetWorkingDirectory()
            };
            string       stdErrRunText = string.Empty;
            CommandError commandError  = CommandError.None;

            isProcessRunning                   = true;
            isProcessTimedOut                  = false;
            lastOutputTime                     = DateTime.Now;
            processLauncherOperation           = ProcessLauncher.RunToCompletionAsync(CommandLineProcesserExe, args, options);
            processLauncherOperation.Completed = (operation, status) =>
            {
                isProcessRunning = false;

                if (status == AsyncStatus.Canceled)
                {
                    if (isProcessTimedOut)
                    {
                        commandError  = CommandError.TimedOut;
                        stdErrRunText = "\n" + String.Format(resourceLoader.GetString("CommandTimeoutText"), TimeOutAfterNoOutput.Seconds);
                    }
                    else
                    {
                        commandError  = CommandError.Cancelled;
                        stdErrRunText = "\n" + resourceLoader.GetString("CommandCancelled");
                    }
                }
                else if (status == AsyncStatus.Error)
                {
                    if (operation.ErrorCode.HResult == HRESULT_AccessDenied)
                    {
                        commandError  = CommandError.NotAuthorized;
                        stdErrRunText = String.Format(resourceLoader.GetString("CmdNotEnabled"), EnableCommandLineProcesserRegCommand);
                    }
                    else
                    if (operation.ErrorCode.HResult == HRESULT_InvalidDirectory)
                    {
                        commandError  = CommandError.InvalidDirectory;
                        stdErrRunText = String.Format(resourceLoader.GetString("WorkingDirectoryInvalid"), options.WorkingDirectory);
                    }
                    else
                    {
                        commandError  = CommandError.GenericError;
                        stdErrRunText = String.Format(resourceLoader.GetString("CommandLineError"), operation.ErrorCode.Message);
                    }
                }

                if (commandError != CommandError.None)
                {
                    ShowError(stdErrRunText);

                    if (commandError == CommandError.NotAuthorized)
                    {
                        ShowAuthorizationUI();
                    }
                }

                if (commandError == CommandError.InvalidDirectory)
                {
                    EnableCommandLineTextBox(true, WorkingDirectory);
                }
                else
                {
                    EnableCommandLineTextBox(true, CommandLine);
                }
            };

            var stdOutTask = ThreadPool.RunAsync(async(t) =>
            {
                using (var outStreamRedirect = standardOutput.GetInputStreamAt(0))
                {
                    using (var streamReader = new StreamReader(outStreamRedirect.AsStreamForRead()))
                    {
                        await ReadText(streamReader);
                    }
                }
            }).AsTask();

            var stdErrTask = ThreadPool.RunAsync(async(t) =>
            {
                using (var errStreamRedirect = standardError.GetInputStreamAt(0))
                {
                    using (var streamReader = new StreamReader(errStreamRedirect.AsStreamForRead()))
                    {
                        await ReadText(streamReader, isErrorRun: true);
                    }
                }
            }).AsTask();

            Task[] tasks = new Task[2]
            {
                stdOutTask,
                stdErrTask
            };

            Task.WaitAll(tasks);
        }
Example #48
0
 public static TickResultDelayed Delayed(IAsyncOperation asyncOperation)
 => new TickResultDelayed()
 {
     DelayOperation = asyncOperation
 };
 /// <summary>Bridge to Completed handler on IAsyncOperation{TResult}.</summary>
 internal void CompleteFromAsyncOperation(IAsyncOperation <TResult> asyncInfo, AsyncStatus asyncStatus)
 {
     Complete(asyncInfo, ai => ((IAsyncOperation <TResult>)ai).GetResults(), asyncStatus); // delegate cached by compiler
 }
Example #50
0
        public static DirectoryInfo CreateDirectory(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException();
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("Path is empty");
            }
            StorageFolder folder = (StorageFolder)null;

            path = path.Replace('/', '\\');
            string         path1 = path;
            Stack <string> stack = new Stack <string>();

            do
            {
                try
                {
                    folder = Directory.GetDirectoryForPath(path1);
                    break;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Directory.CreateDirectory: " + ex.Message + "\n" + ex.StackTrace);
                    int length = path1.LastIndexOf('\\');
                    if (length < 0)
                    {
                        path1 = (string)null;
                    }
                    else
                    {
                        stack.Push(path1.Substring(length + 1));
                        path1 = path1.Substring(0, length);
                    }
                }
            }while (path1 != null);
            if (path1 == null)
            {
                System.Diagnostics.Debug.WriteLine("Directory.CreateDirectory: Could not find any part of the path: " + path);
                throw new IOException("Could not find any part of the path: " + path);
            }
            try
            {
                while (stack.Count > 0)
                {
                    string desiredName = stack.Pop();
                    if (string.IsNullOrWhiteSpace(desiredName) && stack.Count > 0)
                    {
                        throw new ArgumentNullException("Empty directory name in the path");
                    }
                    IAsyncOperation <StorageFolder> folderAsync = folder.CreateFolderAsync(desiredName);
                    WindowsRuntimeSystemExtensions.AsTask <StorageFolder>(folderAsync).Wait();
                    folder = folderAsync.GetResults();
                }
                return(new DirectoryInfo(path, folder));
            }
            catch (IOException ex)
            {
                System.Diagnostics.Debug.WriteLine("Directory.CreateDirectory: " + ex.Message + "\n" + ex.StackTrace);
                throw;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Directory.CreateDirectory: " + ex.Message + "\n" + ex.StackTrace);
                throw new IOException(ex.Message, ex);
            }
        }
Example #51
0
 public static TaskAwaiter <TResult> GetAwaiter <TResult>(this IAsyncOperation <TResult> source)
 {
     return(AsTask(source).GetAwaiter());
 }
        private IEnumerator LoadSourceControllerModel(InteractionSource source)
        {
            byte[]     fileBytes;
            GameObject controllerModelGameObject;

            if (GLTFMaterial == null)
            {
                Debug.Log("If using glTF, please specify a material on " + name + ".");
                yield break;
            }

#if !UNITY_EDITOR
            // This API returns the appropriate glTF file according to the motion controller you're currently using, if supported.
            IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.TryGetRenderableModelAsync();

            if (modelTask == null)
            {
                Debug.Log("Model task is null; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            while (modelTask.Status == AsyncStatus.Started)
            {
                yield return(null);
            }

            IRandomAccessStreamWithContentType modelStream = modelTask.GetResults();

            if (modelStream == null)
            {
                Debug.Log("Model stream is null; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            if (modelStream.Size == 0)
            {
                Debug.Log("Model stream is empty; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            fileBytes = new byte[modelStream.Size];

            using (DataReader reader = new DataReader(modelStream))
            {
                DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size);

                while (loadModelOp.Status == AsyncStatus.Started)
                {
                    yield return(null);
                }

                reader.ReadBytes(fileBytes);
            }
#else
            IntPtr controllerModel = new IntPtr();
            uint   outputSize      = 0;

            if (TryGetMotionControllerModel(source.id, out outputSize, out controllerModel))
            {
                fileBytes = new byte[Convert.ToInt32(outputSize)];

                Marshal.Copy(controllerModel, fileBytes, 0, Convert.ToInt32(outputSize));
            }
            else
            {
                Debug.Log("Unable to load controller models; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }
#endif

            controllerModelGameObject = new GameObject {
                name = "glTFController"
            };
            controllerModelGameObject.transform.Rotate(0, 180, 0);

            var sceneImporter = new GLTFSceneImporter(
                "",
                new MemoryStream(fileBytes, 0, fileBytes.Length, false, true),
                controllerModelGameObject.transform
                );

            sceneImporter.SetShaderForMaterialType(GLTFSceneImporter.MaterialType.PbrMetallicRoughness, GLTFMaterial.shader);
            sceneImporter.SetShaderForMaterialType(GLTFSceneImporter.MaterialType.KHR_materials_pbrSpecularGlossiness, GLTFMaterial.shader);
            sceneImporter.SetShaderForMaterialType(GLTFSceneImporter.MaterialType.CommonConstant, GLTFMaterial.shader);

            yield return(sceneImporter.Load());

            FinishControllerSetup(controllerModelGameObject, source.handedness, GenerateKey(source));
        }
Example #53
0
 /// <summary>Gets a Task to represent the asynchronous operation.</summary>
 /// <param name="source">The asynchronous operation.</param>
 /// <returns>The Task representing the asynchronous operation.</returns>
 public static Task <TResult> AsTask <TResult>(this IAsyncOperation <TResult> source)
 {
     return(AsTask(source, CancellationToken.None));
 }
Example #54
0
 /// <inheritdoc/>
 public bool GetNextIntegerChoice(IAsyncOperation current, int maxValue, out int next)
 {
     next = this.RandomValueGenerator.Next(maxValue);
     this.ScheduledSteps++;
     return(true);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AsyncAwaitable{TResult}"/> struct.
 /// </summary>
 public AsyncAwaitable(IAsyncOperation <TResult> op, SynchronizationContext syncContext)
 {
     _awaiter = new AsyncAwaiter <TResult>(op, syncContext);
 }
Example #56
0
        public async void PicturePicker()
        {
            //打开文件选择器
            FolderPicker pick = new FolderPicker();

            pick.FileTypeFilter.Add(".png");
            pick.FileTypeFilter.Add(".jpg");
            pick.FileTypeFilter.Add(".bmp");
            IAsyncOperation <StorageFolder> folderTask = pick.PickSingleFolderAsync();

            StorageFolder folder = await folderTask;

            //var folder = await pick.PickSingleFolderAsync();
            StorageFolder Folder = null;
            string        Address;
            string        Token = "";

            if (folder != null)
            {
                Folder  = folder;
                Address = folder.Path;
                Token   = StorageApplicationPermissions.FutureAccessList.Add(folder);
            }
            await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(Token);

            //获取本地文件夹
            StorageFolder folderLocal = ApplicationData.Current.LocalFolder;

            //创建一个文件夹account
            string folderStr = string.Empty;

            try
            {
                folderLocal = await folderLocal.GetFolderAsync(folderStr);
            }
            catch (FileNotFoundException)
            {
                folderLocal = await folderLocal.CreateFolderAsync(folderStr);
            }

            StorageFile file = await folderLocal.CreateFileAsync(
                folderStr + ".json", CreationCollisionOption.ReplaceExisting);

            //保存选择的文件夹Token
            //var json = JsonSerializer.Create();
            ImagePath imagePath = new ImagePath {
                Id = DateTime.Now.ToString("yyMMddHHmmss"), Path = Token
            };
            string imageJson = imagePath.Stringify();

            if (file != null)
            {
                try
                {
                    using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
                    {
                        using (DataWriter dataWriter = new DataWriter(transaction.Stream))
                        {
                            dataWriter.WriteInt32(Encoding.UTF8.GetByteCount(imageJson));
                            dataWriter.WriteString(imageJson);
                            transaction.Stream.Size = await dataWriter.StoreAsync();

                            await transaction.CommitAsync();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Example #57
0
//		bool errorPadInitialized = false;
		public IAsyncOperation Build (IBuildTarget entry)
		{
			if (currentBuildOperation != null && !currentBuildOperation.IsCompleted) return currentBuildOperation;
			/*
			if (!errorPadInitialized) {
				try {
					Pad errorsPad = IdeApp.Workbench.GetPad<MonoDevelop.Ide.Gui.Pads.ErrorListPad> ();
					errorsPad.Window.PadHidden += delegate {
						content.IsOpenedAutomatically = false;
					};
					
					Pad monitorPad = IdeApp.Workbench.Pads.FirstOrDefault (pad => pad.Content == ((OutputProgressMonitor)((AggregatedProgressMonitor)monitor).MasterMonitor).OutputPad);
					monitorPad.Window.PadHidden += delegate {
						monitorPad.IsOpenedAutomatically = false;
					};
				} finally {
					errorPadInitialized = true;
				}
			}
			*/
			
			ITimeTracker tt = Counters.BuildItemTimer.BeginTiming ("Building " + entry.Name);
			try {
				IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor ();
				BeginBuild (monitor, tt, false);
				DispatchService.ThreadDispatch (() => BuildSolutionItemAsync (entry, monitor, tt));
				currentBuildOperation = monitor.AsyncOperation;
				currentBuildOperationOwner = entry;
				currentBuildOperation.Completed += delegate { currentBuildOperationOwner = null; };
			} catch {
				tt.End ();
				throw;
			}
			return currentBuildOperation;
		}
Example #58
0
 //twitter tap
 private void Image_Tapped_1(object sender, TappedRoutedEventArgs e)
 {
     var uri = new Uri("https://twitter.com/EGAppFactory");
     IAsyncOperation <bool> x = Windows.System.Launcher.LaunchUriAsync(uri);
 }
Example #59
0
		public IAsyncOperation Clean (IBuildTarget entry)
		{
			if (currentBuildOperation != null && !currentBuildOperation.IsCompleted) return currentBuildOperation;
			
			ITimeTracker tt = Counters.BuildItemTimer.BeginTiming ("Cleaning " + entry.Name);
			try {
				IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetCleanProgressMonitor ();
				OnStartClean (monitor, tt);
				DispatchService.ThreadDispatch (() => CleanAsync (entry, monitor, tt, false));
				
				currentBuildOperation = monitor.AsyncOperation;
				currentBuildOperationOwner = entry;
				currentBuildOperation.Completed += delegate {
					currentBuildOperationOwner = null;
				};
			}
			catch {
				tt.End ();
				throw;
			}
			
			return currentBuildOperation;
		}
Example #60
0
        /// <summary>
        /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
        /// it back on the screen. Uses developer-provided UI for user feedback.
        /// </summary>
        /// <param name="sender">Button that triggered this event</param>
        /// <param name="e">State information about the routed event</param>
        private async void RecognizeWithoutUIListConstraint_Click(object sender, RoutedEventArgs e)
        {
            heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;

            // Disable the UI while recognition is occurring, and provide feedback to the user about current state.
            btnRecognizeWithUI.IsEnabled    = false;
            btnRecognizeWithoutUI.IsEnabled = false;
            cbLanguageSelection.IsEnabled   = false;
            listenWithoutUIButtonText.Text  = " listening for speech...";

            // Start recognition.
            try
            {
                // Save the recognition operation so we can cancel it (as it does not provide a blocking
                // UI, unlike RecognizeWithAsync()
                recognitionOperation = speechRecognizer.RecognizeAsync();

                SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;

                // If successful, display the recognition result. A cancelled task should do nothing.
                if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
                {
                    string tag = "unknown";
                    if (speechRecognitionResult.Constraint != null)
                    {
                        // Only attempt to retreive the tag if we didn't hit the garbage rule.
                        tag = speechRecognitionResult.Constraint.Tag;
                    }

                    heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text            = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString());
                }
                else
                {
                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
                }
            }
            catch (TaskCanceledException exception)
            {
                // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
                // processing speech. Since this happens here when we navigate out of the scenario, don't try to
                // show a message dialog for this exception.
                System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
                System.Diagnostics.Debug.WriteLine(exception.ToString());
            }
            catch (Exception exception)
            {
                // Handle the speech privacy policy error.
                if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
                {
                    resultTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Text       = "The privacy statement was declined.";
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
                    await messageDialog.ShowAsync();
                }
            }

            // Reset UI state.
            listenWithoutUIButtonText.Text  = " without UI";
            cbLanguageSelection.IsEnabled   = true;
            btnRecognizeWithUI.IsEnabled    = true;
            btnRecognizeWithoutUI.IsEnabled = true;
        }