/// <summary>
 /// Handle when the action is clicked in context menu or action pane
 /// </summary>
 /// <param name="action"></param>
 /// <param name="status"></param>
 protected override void OnAction(Action action, AsyncStatus status)
 {
     if ((string)action.Tag == "ShowError")
     {
         // trigger MMC to show the new view
         ((ViewSwitchingScopeNode)this.ScopeNode).SwapView(this, "Simulated Error Message", typeof(ErrorMessageView));
     }
 }
        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);
        }
        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);
                    });
            }
        }
 /// <summary>
 /// Handle triggered action
 /// </summary>
 /// <param name="action">triggered action</param>
 /// <param name="status">asynchronous status to update console</param>
 protected override void OnSelectionAction(Action action, AsyncStatus status)
 {
     switch ((string)action.Tag)
     {
         case "ShowSelection":
             {
                 selectionControl.ShowSelection();
                 break;
             }
     }
 }
 /// <summary>
 /// Handles the view level actions
 /// </summary>
 /// <param name="action">action that was triggered</param>
 /// <param name="status">asynchronous status for updating the console</param>
 protected override void OnAction(Action action, AsyncStatus status)
 {
     switch ((string)action.Tag)
     {
         case "Refresh":
             {
                 this.Refresh();
                 break;
             }
     }
 }
        /// <summary>
        /// Handle any setup necessary
        /// </summary>
        /// <param name="status">asynchronous status for updating the console</param>
        protected override void OnInitialize(AsyncStatus status)
        {
            // handle any basic stuff
            base.OnInitialize(status);

            // get typed reference to the hosted control
            // setup by the FormViewDescription
            selectionControl = (SelectionControl)this.Control;

            //// load data in
            Refresh();
        }
 private async void Completed(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
 {
     if (asyncStatus == AsyncStatus.Canceled)
         return;
     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                         CoreDispatcherPriority.High, () =>
                         {
                             HyperlinkButton.Visibility = _isCompleted
                                 ? Visibility.Visible
                                 : Visibility.Collapsed;
                             greeting.Text = "bitti!";
                         });
 }
Esempio n. 8
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;
         };
     }
 }
Esempio n. 9
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));
     }
 }
        /// <summary>
        /// Define the ListView's structure and actions
        /// </summary>
        /// <param name="status">asynchronous status for updating the console</param>
        protected override void OnInitialize(AsyncStatus status)
        {
            // do default handling
            base.OnInitialize(status);

            // Create a set of columns for use in the list view
            // Define the default column title
            this.Columns[0].Title = "User";
            this.Columns[0].SetWidth(300);

            // Add detail column
            this.Columns.Add(new MmcListViewColumn("Birthday", 200));

            // Set to show all columns
            this.Mode = MmcListViewMode.Report;

            // Load the list with values
            Refresh();
        }
Esempio n. 11
0
        private void OnConnected(IAsyncAction action, AsyncStatus target)
        {
            if (target == AsyncStatus.Completed)
            {
                this.connection.Connected();

                this.writer = new DataWriter(this.socket.OutputStream);
                this.reader = new DataReader(this.socket.InputStream);
                NetworkMessage m = new NetworkMessage();
                m.MessageCategory = SystemMessages.SystemPrefix;
                m.MessageType = SystemMessages.Connect;
                AuthenticationInfo auth = new AuthenticationInfo();
                auth.Username = this.id;
                m.MessageContent = NetworkSerializer.Serialize(auth);
                this.SendMessage(m);
                this.reader.InputStreamOptions = InputStreamOptions.Partial;
                DataReaderLoadOperation operation = this.reader.LoadAsync(256);
                operation.Completed = new AsyncOperationCompletedHandler<uint>(this.ReaderHasData);
            }
        }
Esempio n. 12
0
        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;
            });
        }
Esempio n. 13
0
        /// <summary>
        /// Load in any saved data
        /// </summary>
        /// <param name="status">asynchronous status for updating the console</param>
        /// <param name="persistenceData">binary data stored in the console file</param>
        protected override void OnLoadCustomData(AsyncStatus status, byte[] persistenceData)
        {
            status.ReportProgress(0, 10, "Loading..");

            // Deserialize the object
            try
            {
                MemoryStream    stream       = new MemoryStream(persistenceData);
                BinaryFormatter deserializer = new BinaryFormatter();
                mgrConfig.SetInitData((InitialisationData)deserializer.Deserialize(stream));

                // Initialise the config object
                mgrConfig.Initialise();

                // Load the CA data into the root node
                ((OSCAroot)RootNode).Load();

                status.Complete("Manager configuration: " + mgrConfig.InitData.configFile, true);
            }
            catch (SerializationException)
            {
                MessageBox.Show("No configuration data defined", "OSCA", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 14
0
        //Successfull network connection handler on hololens
#if !UNITY_EDITOR
        public void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
        {
            // Status completed is successful.
            if (status == AsyncStatus.Completed)
            {
                //Creating the writer that will be repsonsible to send a message through Rosbridge
                dataWriter = new DataWriter(messageWebSocket.OutputStream);

                //Connect to all topics in _subscribers and _publishers
                foreach (Type p in _subscribers)
                {
                    dataWriter.WriteString(ROSBridgeMsg.Subscribe(GetMessageTopic(p), GetMessageType(p)));
                    dataWriter.StoreAsync();
                    Debug.Log("Sending " + ROSBridgeMsg.Subscribe(GetMessageTopic(p), GetMessageType(p)));
                }
                foreach (Type p in _publishers)
                {
                    dataWriter.WriteString(ROSBridgeMsg.Advertise(GetMessageTopic(p), GetMessageType(p)));
                    dataWriter.StoreAsync();
                    Debug.Log("Sending " + ROSBridgeMsg.Advertise(GetMessageTopic(p), GetMessageType(p)));
                }
                _connected = true;
            }
        }
Esempio n. 15
0
 /// <summary>
 /// Called when [expand].
 /// </summary>
 /// <param name="status">The status.</param>
 protected override void OnExpand(AsyncStatus status)
 {
     StandardCollectionExpand(status, new DatabaseModel.Fetch(), (m => new DatabaseNode(m)));
 }
 protected override void OnRefresh(AsyncStatus status)
 {
     base.OnRefresh(status);
     Refresh();
 }
Esempio n. 17
0
 internal override void OnCompleted(AsyncActionWithProgressCompletedHandler <TProgress> userCompletionHandler, AsyncStatus asyncStatus)
 {
     Debug.Assert(userCompletionHandler != null);
     userCompletionHandler(this, asyncStatus);
 }
Esempio n. 18
0
 protected override void OnShutdown(AsyncStatus status)
 {
     _bootstrapper.Shutdown();
 }
 public void CompletedStart(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
 {
     if (asyncStatus == AsyncStatus.Completed)
     {
         _recordingStatus = RecordingStatus.recording;
     }
 }
Esempio n. 20
0
 public abstract void TraceOperationCompletion(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, AsyncStatus status);
        /// <summary>
        /// Called when [expand].
        /// </summary>
        /// <param name="status">The status.</param>
        protected override void OnExpand(AsyncStatus status)
        {
            var databaseModel = ((DatabaseNode)Parent.Parent).DatabaseModel;

            StandardCollectionExpand(status, new DatabaseSecurityLoginModel.Fetch(databaseModel), (m => new DatabaseSecurityLoginNode(m)));
        }
Esempio n. 22
0
 internal virtual void OnCompleted(TCompletedHandler userCompletionHandler, AsyncStatus asyncStatus)
 {
     Debug.Assert(false, "This (sub-)type of IAsyncInfo does not support completion notifications "
                  + " (" + this.GetType().ToString() + ")");
 }
Esempio n. 23
0
 /// <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
 }
Esempio n. 24
0
		public void Cancel()
		{
			Status = AsyncStatus.Canceled;
			Complete();
		}
 public void HandleCompilationCompleted(IAsyncOperation<SpeechRecognitionCompilationResult> opInfo, AsyncStatus status)
 {
     if (status == AsyncStatus.Completed)
     {
         System.Diagnostics.Debug.WriteLine("Compilation Complete");
         var result = opInfo.GetResults();
         System.Diagnostics.Debug.WriteLine(result.Status.ToString());
     }
 }
Esempio n. 26
0
        // Event handler when item recognition is completed
        private void ItemRecognitionCompletedHandler(IAsyncOperation<SpeechRecognitionResult> asyncInfo, AsyncStatus asyncStatus)
        {
            isListening = false;

            var results = asyncInfo.GetResults();
            if (results.Status != SpeechRecognitionResultStatus.Success)
            {
                TextToSpeech.Speak("Sorry, I wasn't able to hear you. Try again later.");
                return;
            }

            if (results.Confidence == SpeechRecognitionConfidence.High | results.Confidence == SpeechRecognitionConfidence.Medium)
            {
                requestedItems.Add(requestor + " wants " + results.Text);
                TextToSpeech.Speak(results.Text + "\n" + "Got it. I have added it your Christmas list" + requestor);
            }
            else
            {
                TextToSpeech.Speak("Sorry, I did not get that.");
            }
        }
Esempio n. 27
0
        // Event handler when name recognition is completed
        private void NameRecognitionCompletedHandler(IAsyncOperation<SpeechRecognitionResult> asyncInfo, AsyncStatus asyncStatus)
        {
            isListening = false;

            var results = asyncInfo.GetResults();
            if (results.Status != SpeechRecognitionResultStatus.Success)
            {
                TextToSpeech.Speak("Sorry, I wasn't able to hear you. Try again later.");
                return;
            }

            if (results.Confidence == SpeechRecognitionConfidence.High | results.Confidence == SpeechRecognitionConfidence.Medium)
            {
                requestor = results.Text;
                if (requestor == listOfNames.First())
                {
                    if (requestedItems.Count == 0)
                    {
                        TextToSpeech.Speak("Hello" + requestor + "\n" + "The list is empty.");
                    }
                    else
                    {
                        TextToSpeech.Speak("Hello" + requestor + "\n" + "Here is the list");
                        foreach (string item in requestedItems)
                        {
                            Task.Delay(4000).Wait();
                            TextToSpeech.Speak(item);
                        }
                    }
                }
                else
                {
                    TextToSpeech.Speak("Hello" + requestor + "\n" + "What would you like for Christmas?");
                    Task.Delay(4000).Wait();
                    RecognizeChristmasListItem();
                }
            }
            else
            {
                TextToSpeech.Speak("Sorry, I do not recognize you.");
            }

        }
        public async void CompletedStop(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
        {
            if (asyncStatus == AsyncStatus.Completed)
            {
                if (_recordingStatus == RecordingStatus.recording)
                {
                    _recordingStatus = RecordingStatus.sucessful;

                    var file = await ApplicationData.Current.LocalFolder.GetFileAsync("recording.mp4");
                    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        mediaElement.SetSource(stream, "");
                        mediaElement.Play();
                    });

                    _recordingStatus = RecordingStatus.stopped;
                }

                if (_recordingStatus == RecordingStatus.failed)
                {
                    // Recording has failed somewhere. Set the recording status to stopped.
                    _recordingStatus = RecordingStatus.stopped;
                }
            }
        }
        /// <summary>
        /// Speech recognition completed.
        /// </summary>
        private async void Recognition_Completed(IAsyncOperation<SpeechRecognitionResult> asyncInfo, AsyncStatus asyncStatus)
        {
            var results = asyncInfo.GetResults();

            if (results.Confidence != SpeechRecognitionConfidence.Rejected)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new DispatchedHandler(
                    () =>
                    {
                        this.txtCortanaMessages.Text = "Je recherche : " + results.Text + "...";

                        CortanaSearchViewModel viewModel = DataContext as CortanaSearchViewModel;
                        viewModel.PropertyChanged += viewModel_PropertyChanged;
                        viewModel.LoadResults(SettingsValues.SiteUrl, results.Text, SettingsValues.LoginName, SettingsValues.Password);

                    }));
            }
            else
            {
                this.txtCortanaMessages.Text = "Désolé, je n'ai pas compris.";
            }
        }
Esempio n. 30
0
        /// <summary>Completes the task from the completed asynchronous operation.</summary>
        /// <param name="asyncInfo">The asynchronous operation.</param>
        /// <param name="getResultsFunction">A function used to retrieve the TResult from the async operation; may be null.</param>
        /// <param name="asyncStatus">The status of the asynchronous operation.</param>
        private void Complete(IAsyncInfo asyncInfo, Func <IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus)
        {
            if (asyncInfo == null)
            {
                throw new ArgumentNullException(nameof(asyncInfo));
            }

            Contract.EndContractBlock();

            AsyncCausalitySupport.RemoveFromActiveTasks(this.Task);

            try
            {
                Debug.Assert(asyncInfo.Status == asyncStatus,
                             "asyncInfo.Status does not match asyncStatus; are we dealing with a faulty IAsyncInfo implementation?");

                // Assuming a correct underlying implementation, the task should not have been
                // completed yet.  If it is completed, we shouldn't try to do any further work
                // with the operation or the task, as something is horked.
                bool taskAlreadyCompleted = Task.IsCompleted;

                Debug.Assert(!taskAlreadyCompleted, "Expected the task to not yet be completed.");

                if (taskAlreadyCompleted)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
                }

                // Clean up our registration with the cancellation token, noting that we're now in the process of cleaning up.
                CancellationTokenRegistration ctr;
                lock (StateLock)
                {
                    _completing = true;
                    ctr         = _ctr; // under lock to avoid torn reads
                    _ctr        = default(CancellationTokenRegistration);
                }
                ctr.TryDeregister(); // It's ok if we end up unregistering a not-initialized registration; it'll just be a nop.

                try
                {
                    // Find out how the async operation completed.  It must be in a terminal state.
                    bool terminalState = asyncStatus == AsyncStatus.Completed ||
                                         asyncStatus == AsyncStatus.Canceled ||
                                         asyncStatus == AsyncStatus.Error;

                    Debug.Assert(terminalState, "The async operation should be in a terminal state.");

                    if (!terminalState)
                    {
                        throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
                    }

                    // Retrieve the completion data from the IAsyncInfo.
                    TResult   result = default(TResult);
                    Exception error  = null;
                    if (asyncStatus == AsyncStatus.Error)
                    {
                        error = asyncInfo.ErrorCode;

                        // Defend against a faulty IAsyncInfo implementation:
                        if (error == null)
                        {
                            Debug.Assert(false, "IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
                            error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
                        }
                        else
                        {
                            error = asyncInfo.ErrorCode.AttachRestrictedErrorInfo();
                        }
                    }
                    else if (asyncStatus == AsyncStatus.Completed && getResultsFunction != null)
                    {
                        try
                        {
                            result = getResultsFunction(asyncInfo);
                        }
                        catch (Exception resultsEx)
                        {
                            // According to the WinRT team, this can happen in some egde cases, such as marshalling errors in GetResults.
                            error       = resultsEx;
                            asyncStatus = AsyncStatus.Error;
                        }
                    }

                    // Nothing to retrieve for a canceled operation or for a completed operation with no result.

                    // Complete the task based on the previously retrieved results:
                    bool success = false;
                    switch (asyncStatus)
                    {
                    case AsyncStatus.Completed:
                        if (AsyncCausalitySupport.LoggingOn)
                        {
                            AsyncCausalitySupport.TraceOperationCompletedSuccess(this.Task);
                        }
                        success = base.TrySetResult(result);
                        break;

                    case AsyncStatus.Error:
                        Debug.Assert(error != null, "The error should have been retrieved previously.");
                        success = base.TrySetException(error);
                        break;

                    case AsyncStatus.Canceled:
                        success = base.TrySetCanceled(_ct.IsCancellationRequested ? _ct : new CancellationToken(true));
                        break;
                    }

                    Debug.Assert(success, "Expected the outcome to be successfully transfered to the task.");
                }
                catch (Exception exc)
                {
                    // This really shouldn't happen, but could in a variety of misuse cases
                    // such as a faulty underlying IAsyncInfo implementation.
                    Debug.Assert(false, string.Format("Unexpected exception in Complete: {0}", exc.ToString()));

                    if (AsyncCausalitySupport.LoggingOn)
                    {
                        AsyncCausalitySupport.TraceOperationCompletedError(this.Task);
                    }

                    // For these cases, store the exception into the task so that it makes its way
                    // back to the caller.  Only if something went horribly wrong and we can't store the exception
                    // do we allow it to be propagated out to the invoker of the Completed handler.
                    if (!base.TrySetException(exc))
                    {
                        Debug.Assert(false, "The task was already completed and thus the exception couldn't be stored.");
                        throw;
                    }
                }
            }
            finally
            {
                // We may be called on an STA thread which we don't own, so make sure that the RCW is released right
                // away. Otherwise, if we leave it up to the finalizer, the apartment may already be gone.
                if (Marshal.IsComObject(asyncInfo))
                {
                    Marshal.ReleaseComObject(asyncInfo);
                }
            }
        } // private void Complete(..)
Esempio n. 31
0
 protected override void OnRefresh(AsyncStatus status)
 {
     PopulateChildren();
 }
 private void BackgroundTaskInitializationCompleted(IAsyncAction action, AsyncStatus status)
 {
     if (status == AsyncStatus.Completed)
     {
         Debug.WriteLine("Background Audio Task initialized");
     }
     else if (status == AsyncStatus.Error)
     {
         Debug.WriteLine("Background Audio Task could not initialized due to an error ::" + action.ErrorCode.ToString());
     }
 }
Esempio n. 33
0
        protected override void OnSelectionAction(Microsoft.ManagementConsole.Action action, AsyncStatus status)

        {
            switch ((int)action.Tag)

            {
            case ACTION_SHOW_PROPERTIES:

                ShowProperties();

                break;
            }
        }
 protected override void OnExpand(AsyncStatus status)
 {
     base.OnExpand(status);
 }
Esempio n. 35
0
 private void OnRecognitionCompleteHandler(IAsyncOperation<SpeechRecognitionResult> asyncInfo, AsyncStatus asyncStatus)
 {
     asyncInfo.Close();
 }
Esempio n. 36
0
        private static void DoTestWrite(Func <Stream> createStreamFunc, bool mustInvokeProgressHandler)
        {
            Stream backingStream = createStreamFunc();

            using (IOutputStream stream = backingStream.AsOutputStream())
            {
                // Create test data
                Random rnd            = new Random(20100720); //  Must be a different seed than used for TestStreamProvider.ModelStreamContents
                byte[] modelWriteData = new byte[0xA000];
                rnd.NextBytes(modelWriteData);

                // Start test

                IBuffer buffer = modelWriteData.AsBuffer();

                // ibuffer.Length for IBuffer created by Array.ToBuffer(void) must equal to array.Length
                Assert.Equal((uint)modelWriteData.Length, buffer.Length);

                // ibuffer.Capacity for IBuffer created by Array.ToBuffer(void) must equal to array.Length
                Assert.Equal((uint)modelWriteData.Length, buffer.Capacity);

                IAsyncOperationWithProgress <uint, uint> writeOp = stream.WriteAsync(buffer);

                // Note the race. By the tie we get here, the status of the op may be started or already completed.
                AsyncStatus writeOpStatus = writeOp.Status;
                Assert.True(writeOpStatus == AsyncStatus.Completed || writeOpStatus == AsyncStatus.Started, "New writeOp must have Status = Started or Completed (race)");

                uint writeOpId = writeOp.Id;
                bool progressCallbackInvoked  = false;
                bool completedCallbackInvoked = false;
                uint resultBytesWritten       = 0;

                EventWaitHandle waitHandle = new ManualResetEvent(false);

                writeOp.Progress = (asyncWriteOp, bytesCompleted) =>
                {
                    progressCallbackInvoked = true;

                    // asyncWriteOp.Id in a progress callback must match the ID of the asyncWriteOp to which the callback was assigned
                    Assert.Equal(writeOpId, asyncWriteOp.Id);

                    // asyncWriteOp.Status must be 'Started' for an asyncWriteOp in progress
                    Assert.Equal(AsyncStatus.Started, asyncWriteOp.Status);

                    // bytesCompleted must be in range [0, maxBytesToWrite] asyncWriteOp in progress
                    Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength);
                };

                writeOp.Completed = (asyncWriteOp, passedStatus) =>
                {
                    try
                    {
                        completedCallbackInvoked = true;

                        // asyncWriteOp.Id in a completion callback must match the ID of the asyncWriteOp to which the callback was assigned
                        Assert.Equal(writeOpId, asyncWriteOp.Id);

                        // asyncWriteOp.Status must match passedStatus for a completed asyncWriteOp
                        Assert.Equal(passedStatus, asyncWriteOp.Status);

                        // asyncWriteOp.Status must be 'Completed' for a completed asyncWriteOp
                        Assert.Equal(AsyncStatus.Completed, asyncWriteOp.Status);

                        uint bytesWritten = asyncWriteOp.GetResults();

                        // asyncWriteOp.GetResults() must return that all required bytes were written for a completed asyncWriteOp
                        Assert.Equal((uint)modelWriteData.Length, bytesWritten);

                        resultBytesWritten = bytesWritten;
                    }
                    finally
                    {
                        waitHandle.Set();
                    }
                };

                // Now, let's block until the write op is complete.
                // We speculate that it will complete within 3500 msec, although under high load it may not be.
                // If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow.
                waitHandle.WaitOne(500);
                waitHandle.WaitOne(1000);
                waitHandle.WaitOne(2000);

                if (mustInvokeProgressHandler)
                {
                    Assert.True(progressCallbackInvoked,
                                "Progress callback specified to WriteAsync callback must be invoked when reading from this kind of stream");
                }

                Assert.True(completedCallbackInvoked, "Completion callback specified to WriteAsync callback must be invoked");

                // writeOp.Status must be 'Completed' for a completed async writeOp
                Assert.Equal(AsyncStatus.Completed, writeOp.Status);

                // writeOp.GetResults() must return that all required bytes were written for a completed async writeOp
                Assert.Equal((uint)modelWriteData.Length, resultBytesWritten);

                // Check contents

                backingStream.Seek(0, SeekOrigin.Begin);
                byte[] verifyBuff = new byte[modelWriteData.Length + 1024];

                int r = backingStream.Read(verifyBuff, 0, verifyBuff.Length);

                for (int i = 0; i < modelWriteData.Length; i++)
                {
                    Assert.Equal(modelWriteData[i], verifyBuff[i]);
                }
            }
        }
Esempio n. 37
0
		public void Start()
		{
			Status = AsyncStatus.Started;
		}
        /// <summary>
        /// Completed Channel creation handler
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="status"></param>
        void OnChannelCreationCompleted(IAsyncOperation<PushNotificationChannel> operation, AsyncStatus status)
        {
            if (operation.Status == AsyncStatus.Completed)
            {
                pushNotificationChannel = operation.GetResults();

                // Send these values together with user data to your server of choice
                var notificationUri = pushNotificationChannel.Uri;
                var expirationTime = pushNotificationChannel.ExpirationTime;
            }
        }
Esempio n. 39
0
 protected override void OnRefresh(AsyncStatus status)
 {
     // TODO: Not implemented yet
 }
Esempio n. 40
0
        private void ReaderHasData(IAsyncOperation<uint> operation, AsyncStatus target)
        {
            uint len = operation.GetResults();
            byte[] buffer = new byte[len];
            this.reader.ReadBytes(buffer);

            this.ProcessBytes(buffer, (int)len);
            DataReaderLoadOperation operation2 = this.reader.LoadAsync(256);
            operation2.Completed = new AsyncOperationCompletedHandler<uint>(this.ReaderHasData);
        }
Esempio n. 41
0
        protected override void OnExpand(AsyncStatus status)
        {
            base.OnExpand(status);

            AddAllServers();
        }
 /// <summary>
 /// Completion callback for the asynchronous call:
 /// it is called whether the drop succeeded, or the user released the pointer on a non-target
 /// or else we cancelled the operation from the timer's callback
 /// </summary>
 /// <param name="asyncInfo"></param>
 /// <param name="asyncStatus"></param>
 private void DragCompleted(IAsyncOperation<DataPackageOperation> asyncInfo, AsyncStatus asyncStatus)
 {
     _dragOperation = null;
     if (_timer != null) _timer.Stop();
     EndRound((asyncStatus == AsyncStatus.Completed) && (asyncInfo.GetResults() == DataPackageOperation.Copy));
 }
Esempio n. 43
0
 /// <summary>Bridge to Completed handler on IAsyncActionWithProgress{TProgress}.</summary>
 internal void CompleteFromAsyncActionWithProgress <TProgress>(IAsyncActionWithProgress <TProgress> asyncInfo, AsyncStatus asyncStatus)
 {
     Complete(asyncInfo, null, asyncStatus);
 }
Esempio n. 44
0
        /// <summary>
        /// The spoken stream is ready.
        /// </summary>
        private async void SpokenStreamCompleted(IAsyncOperation<SpeechSynthesisStream> asyncInfo, AsyncStatus asyncStatus)
        {
            //Debug.WriteLine("SpokenStreamCompleted");

            // Make sure to be on the UI Thread.
            var synthesisStream = asyncInfo.GetResults();
            await media.Dispatcher.RunAsync(
                            Windows.UI.Core.CoreDispatcherPriority.Normal,
                            new DispatchedHandler(() => { media.AutoPlay = true; media.SetSource(synthesisStream, synthesisStream.ContentType); media.Play(); })
            );
        }
Esempio n. 45
0
 /// <summary>Bridge to Completed handler on IAsyncOperationWithProgress{TResult,TProgress}.</summary>
 internal void CompleteFromAsyncOperationWithProgress <TProgress>(IAsyncOperationWithProgress <TResult, TProgress> asyncInfo, AsyncStatus asyncStatus)
 {
     // delegate cached by compiler:
     Complete(asyncInfo, ai => ((IAsyncOperationWithProgress <TResult, TProgress>)ai).GetResults(), asyncStatus);
 }
        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)
                    {
                        PrintErrorAsync("The Start Time cannot be later than the End Time, or in the future");
                        return;
                    }

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

                    PrintOutputAsync(outputString);
                    PrintStatusAsync("Success");
                }
                catch (Exception ex)
                {
                    PrintErrorAsync("An unexpected error occurred: " + ex.Message);
                }
            }
            else
            {
                PrintErrorAsync("GetConnectivityIntervalsAsync failed with message:\n" + asyncInfo.ErrorCode.Message);
            }
        }
Esempio n. 47
0
 /// <summary>Bridge to Completed handler on IAsyncAction.</summary>
 internal void CompleteFromAsyncAction(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
 {
     Complete(asyncInfo, null, asyncStatus);
 }
Esempio n. 48
0
 public abstract void TraceOperationCompletion(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, AsyncStatus status);
Esempio n. 49
0
        protected override void OnExpand(AsyncStatus status)

        {
            //override and do nothing
        }
 public int Invoke([NativeTypeName("IAsyncOperationWithProgress<TResult_logical, TProgress_logical> *")] IAsyncOperationWithProgress <TResult, TProgress> *asyncInfo, [NativeTypeName("Windows::Foundation::AsyncStatus")] AsyncStatus status)
 {
     return(((delegate * unmanaged <IAsyncOperationWithProgressCompletedHandler <TResult, TProgress> *, IAsyncOperationWithProgress <TResult, TProgress> *, AsyncStatus, int>)(lpVtbl[3]))((IAsyncOperationWithProgressCompletedHandler <TResult, TProgress> *)Unsafe.AsPointer(ref this), asyncInfo, status));
 }
Esempio n. 51
0
        private static void DoTestRead(Func <IInputStream> createStreamFunc, InputStreamOptions inputStreamOptions, bool mustInvokeProgressHandler, bool completesSynchronously)
        {
            IInputStream stream = createStreamFunc();
            IBuffer      buffer = WindowsRuntimeBuffer.Create(TestStreamProvider.ModelStreamLength);

            IAsyncOperationWithProgress <IBuffer, uint> readOp = stream.ReadAsync(buffer, (uint)TestStreamProvider.ModelStreamLength, inputStreamOptions);

            if (completesSynchronously)
            {
                // New readOp for a stream where we know that reading is sycnhronous must have Status = Completed
                Assert.Equal(AsyncStatus.Completed, readOp.Status);
            }
            else
            {
                // Note the race. By the tie we get here, the status of the op may be started or already completed.
                AsyncStatus readOpStatus = readOp.Status;
                Assert.True(readOpStatus == AsyncStatus.Completed || readOpStatus == AsyncStatus.Started, "New readOp must have Status = Started or Completed (race)");
            }

            bool progressCallbackInvoked  = false;
            bool completedCallbackInvoked = false;

            uint            readOpId   = readOp.Id;
            EventWaitHandle waitHandle = new ManualResetEvent(false);

            readOp.Progress = (asyncReadOp, bytesCompleted) =>
            {
                progressCallbackInvoked = true;

                // asyncReadOp.Id in a progress callback must match the ID of the asyncReadOp to which the callback was assigned
                Assert.Equal(readOpId, asyncReadOp.Id);

                // asyncReadOp.Status must be 'Started' for an asyncReadOp in progress
                Assert.Equal(AsyncStatus.Started, asyncReadOp.Status);

                // bytesCompleted must be in range [0, maxBytesToRead] asyncReadOp in progress
                Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength);
            };

            readOp.Completed = (asyncReadOp, passedStatus) =>
            {
                try
                {
                    completedCallbackInvoked = true;

                    // asyncReadOp.Id in a completion callback must match the ID of the asyncReadOp to which the callback was assigned
                    Assert.Equal(readOpId, asyncReadOp.Id);

                    // asyncReadOp.Status must match passedStatus for a completed asyncReadOp
                    Assert.Equal(passedStatus, asyncReadOp.Status);

                    // asyncReadOp.Status must be 'Completed' for a completed asyncReadOp
                    Assert.Equal(AsyncStatus.Completed, asyncReadOp.Status);

                    IBuffer resultBuffer = asyncReadOp.GetResults();

                    // asyncReadOp.GetResults() must not return null for a completed asyncReadOp
                    Assert.NotNull(resultBuffer);

                    AssertExtensions.GreaterThan(resultBuffer.Capacity, 0u, "resultBuffer.Capacity should be more than zero in completed callback");
                    AssertExtensions.GreaterThan(resultBuffer.Length, 0u, "resultBuffer.Length should be more than zero in completed callback");
                    AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, resultBuffer.Capacity, "resultBuffer.Length should be <= Capacity in completed callback");

                    if (inputStreamOptions == InputStreamOptions.None)
                    {
                        // resultBuffer.Length must be equal to requested number of bytes when an asyncReadOp with
                        // InputStreamOptions.None completes successfully
                        Assert.Equal(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength);
                    }

                    if (inputStreamOptions == InputStreamOptions.Partial)
                    {
                        AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength,
                                                           "resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial in completed callback");
                    }
                    buffer = resultBuffer;
                }
                finally
                {
                    waitHandle.Set();
                }
            };

            // Now, let's block until the read op is complete.
            // We speculate that it will complete within 3500 msec, although under high load it may not be.
            // If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow.
            waitHandle.WaitOne(500);
            waitHandle.WaitOne(1000);
            waitHandle.WaitOne(2000);

            if (mustInvokeProgressHandler)
            {
                Assert.True(progressCallbackInvoked,
                            "Progress callback specified to ReadAsync callback must be invoked when reading from this kind of stream");
            }

            Assert.True(completedCallbackInvoked,
                        "Completion callback specified to ReadAsync callback must be invoked");

            // readOp.Status must be 'Completed' for a completed async readOp
            Assert.Equal(AsyncStatus.Completed, readOp.Status);

            AssertExtensions.GreaterThan(buffer.Capacity, 0u, "buffer.Capacity should be greater than zero bytes");
            AssertExtensions.GreaterThan(buffer.Length, 0u, "buffer.Length should be greater than zero bytes");
            AssertExtensions.LessThanOrEqualTo(buffer.Length, buffer.Capacity, "buffer.Length <= buffer.Capacity is required for a completed async readOp");

            if (inputStreamOptions == InputStreamOptions.None)
            {
                // buffer.Length must be equal to requested number of bytes when an async readOp with
                //  InputStreamOptions.None completes successfully
                Assert.Equal((uint)TestStreamProvider.ModelStreamLength, buffer.Length);
            }

            if (inputStreamOptions == InputStreamOptions.Partial)
            {
                AssertExtensions.LessThanOrEqualTo(buffer.Length, (uint)TestStreamProvider.ModelStreamLength,
                                                   "resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial");
            }

            byte[] results = new byte[buffer.Length];
            buffer.CopyTo(0, results, 0, (int)buffer.Length);

            Assert.True(TestStreamProvider.CheckContent(results, 0, (int)buffer.Length),
                        "Result data returned from AsyncRead must be the same as expected from the test data source");
        }
Esempio n. 52
0
        private void ConnectionCompletedHandler(IAsyncOperation <ConnectionSession> asyncInfo, AsyncStatus asyncStatus)
        {
            if (asyncInfo.Status == AsyncStatus.Completed)
            {
                rootPage.g_ConnectionSession = asyncInfo.GetResults();

                UpdateOutputText("Connected to " + rootPage.g_ConnectionSession.ConnectionProfile.ProfileName + "\n" +
                                 "Connectivity Level: " + rootPage.g_ConnectionSession.ConnectionProfile.GetNetworkConnectivityLevel());

                // Transition button to Disconnect state
                UpdateButtonText("Disconnect");

                connectionResult.Close();
                connectionResult = null;
            }
            else
            {
                UpdateOutputText(asyncStatus.ToString() + ": " + asyncInfo.ErrorCode.Message);

                UpdateButtonText("Connect");

                connectionResult = null;
            }
        }
Esempio n. 53
0
 public void Invoke(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
 {
     _parent.Tick?.Invoke(_st.Elapsed);
     using var act = _parent._compositor5.RequestCommitAsync();
     act.SetCompleted(this);
 }
Esempio n. 54
0
        /// <summary>
        /// 获取用户位置后,触发本函数
        /// </summary>
        /// <param name="asyncInfo"></param>
        /// <param name="asyncStatus"></param>
        private void GetCurrentPosition(IAsyncOperation<Geoposition> asyncInfo, AsyncStatus asyncStatus)
        {
            Debug.WriteLine("获取到位置信息");
            Geoposition currentGeoposition =asyncInfo.GetResults();
            Geocoordinate coordinate= currentGeoposition.Coordinate;
            //获取的数据有偏差
            
            LatLng currentLatLng = new LatLng(coordinate.Latitude + 0.000423, coordinate.Longitude + 0.006090);
            _daBeiJing = currentLatLng;
            Debug.WriteLine(currentLatLng);
            
                if(_amap!=null)
                {
                    _amap.Dispatcher.BeginInvoke(() =>
                    {
                        _amap.AnimateCamera(CameraUpdateFactory.NewCameraPosition(currentLatLng, 17, _bearing, _tile), 2);//移动视角(动画效果)
                        _cameraIsNew = false;
                        if (_locationMarker == null)
                        {
                            //添加圆
                            _circle = _amap.AddCircle(new AMapCircleOptions
                            {
                                Center = currentLatLng, //圆点位置
                                Radius = (float)20, //半径
                                FillColor = Color.FromArgb(80, 100, 150, 255),//圆的填充颜色
                                StrokeWidth = 1, //边框粗细
                                StrokeColor = Color.FromArgb(80, 100, 150, 255) //圆的边框颜色
                            });


                            //添加点标注,用于标注地图上的点
                            _locationMarker = _amap.AddMarker(new AMapMarkerOptions
                            {
                                Position = currentLatLng, //图标的位置
                                //待修改,更换IconUri的图标//
                                IconUri = new Uri("Images/myLocationIcon.png", UriKind.RelativeOrAbsolute), //图标的URL
                                Anchor = new Point(0.5, 0.5) //图标中心点
                            });
                        }
                        else
                        {
                            //点标注和圆的位置在当前经纬度
                            _locationMarker.Position = currentLatLng;
                            _circle.Center = currentLatLng;
                            _circle.Radius = (float)20; //圆半径
                        }
                    });
                    
                    
                }
            
            


        }
        internal void StreamOperationCompletedCallback(IAsyncInfo completedOperation, AsyncStatus unusedCompletionStatus)
        {
            try
            {
                if (_callbackInvoked)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_MultipleIOCompletionCallbackInvocation);
                }

                _callbackInvoked = true;

                // This happens in rare stress cases in Console mode and the WinRT folks said they are unlikely to fix this in Dev11.
                // Moreover, this can happen if the underlying WinRT stream has a faulty user implementation.
                // If we did not do this check, we would either get the same exception without the explaining message when dereferencing
                // completedOperation later, or we will get an InvalidOperation when processing the Op. With the check, they will be
                // aggregated and the user will know what went wrong.
                if (completedOperation == null)
                {
                    throw new NullReferenceException(SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo);
                }

                _completedOperation = completedOperation;

                // processCompletedOperationInCallback == false indicates that the stream is doing a blocking wait on the waitHandle of this IAsyncResult.
                // In that case calls on completedOperation may deadlock if completedOperation is not free threaded.
                // By setting processCompletedOperationInCallback to false the stream that created this IAsyncResult indicated that it
                // will call ProcessCompletedOperation after the waitHandle is signalled to fetch the results.

                if (_processCompletedOperationInCallback)
                {
                    ProcessCompletedOperation();
                }
            }
            catch (Exception ex)
            {
                _bytesCompleted = 0;
                _errorInfo      = ExceptionDispatchInfo.Capture(ex);
            }
            finally
            {
                _completed = true;
                Interlocked.MemoryBarrier();
                // From this point on, AsyncWaitHandle would create a handle that is readily set,
                // so we do not need to check if it is being produced asynchronously.
                if (_waitHandle != null)
                {
                    _waitHandle.Set();
                }
            }

            if (_userCompletionCallback != null)
            {
                _userCompletionCallback(this);
            }
        }
Esempio n. 56
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="status"></param>
 protected override void OnRefresh(AsyncStatus status)
 {
     Refresh();
 }
Esempio n. 57
0
 protected override void OnShutdown(AsyncStatus status)
 {
     VMCASnapInEnvironment.Instance.SaveLocalData();
 }
Esempio n. 58
0
        /// <summary>
        /// Handle short cut style menu actions for selection
        /// </summary>
        /// <param name="action">triggered action</param>
        /// <param name="status">asynchronous status used to update the console</param>
        protected override void OnSelectionAction(Microsoft.ManagementConsole.Action action, AsyncStatus status)
        {
            X509Certificate cert = (X509Certificate)this.SelectedNodes[0].Tag;

            switch ((string)action.Tag)
            {
            case "ViewCert":
                SystemX509.X509Certificate2UI.DisplayCertificate(new SystemX509.X509Certificate2(cert.GetEncoded()));
                break;

            case "ExportCert":
                CertSave certSave = new CertSave(context.caInfo);
                certSave.cert = cert;
                this.SnapIn.Console.ShowDialog(certSave);
                break;

            case "RevokeCert":
                revokeCert revoke = new revokeCert(cert);
                if (this.SnapIn.Console.ShowDialog(revoke) == DialogResult.OK)
                {
                    context.caInfo.RevokeCertificate(cert, (CRLReason)revoke.cbReason.SelectedIndex);
                    Refresh();
                }
                break;

            case "RenewCert":

                break;

            case "RekeyCert":
                RekeyCert rekey = new RekeyCert(context.caInfo, cert);
                if (this.SnapIn.Console.ShowDialog(rekey) == DialogResult.OK)
                {
                    certSave      = new CertSave(context.caInfo);
                    certSave.cert = rekey.cert;
                    this.SnapIn.Console.ShowDialog(certSave);
                    Refresh();
                }
                break;

            case "UnRevokeCert":
                context.caInfo.UnRevokeCertificate(cert);
                Refresh();
                break;
            }
        }
Esempio n. 59
0
 public void Cancel()
 {
     this.current.Cancel();
     this.Status = AsyncStatus.Canceled;
 }
Esempio n. 60
0
 public AsyncStatusTransition(AsyncStatus oldStatus, AsyncStatus newStatus)
 {
     this.oldStatus = oldStatus;
     this.newStatus = newStatus;
 }