Exemple #1
1
 private void ResetRequest()
 {
     if (sendRequestOperation != null)
     {
         sendRequestOperation.Cancel();
         sendRequestOperation = null;
     }
     if (readAsInputStreamOperation != null)
     {
         readAsInputStreamOperation.Cancel();
         readAsInputStreamOperation = null;
     }
     if (readOperation != null)
     {
         readOperation.Cancel();
         readOperation = null;
     }
     if (inputStream != null)
     {
         inputStream.Dispose();
         inputStream = null;
     }
     if (httpRequest != null)
     {
         httpRequest.Dispose();
         httpRequest = null;
     }
 }
Exemple #2
0
 public UploadFile(StorageFile file, DateTime uploadTime, IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> uploadOperation)
 {
     FileName = file.Name;
     UploadTime = uploadTime;
     Progress = 0;
     UploadOperation = uploadOperation;
     UploadOperation.Progress = (message, progress) =>
     {
         if (progress.TotalBytesToSend == null) return;
         Progress = (100.0 * progress.BytesSent / progress.TotalBytesToSend) ?? 0;
     };
 }
Exemple #3
0
        private void OnAttachedDownloadCompleted(IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> asyncInfo, AsyncStatus asyncStatus)
        {
            string message = String.Empty;
            try
            {
                DownloadOperation download = asyncInfo.GetResults();

                message = String.Format(
                    "Download {0} completed with status {1}.",
                    download.Guid,
                    download.Progress.Status);
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            var runAsyncInfo = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                CurrentBlock.Text += String.Format("{0}\r\n", message);
            });
        }
        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");
        }
Exemple #5
0
 public DownloadFile(string token, IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> operation)
 {
     Token = token;
     Finished = false;
     Saved = false;
     DownloadOperation = operation;
 }
Exemple #6
0
 public HRESULT Invoke([NativeTypeName("IAsyncOperationWithProgress<TResult_logical, TProgress_logical> *")] IAsyncOperationWithProgress <TResult, TProgress> *asyncInfo, [NativeTypeName("TProgress_abi")] TProgress progressInfo)
 {
     return(((delegate * unmanaged <IAsyncOperationProgressHandler <TResult, TProgress> *, IAsyncOperationWithProgress <TResult, TProgress> *, TProgress, int>)(lpVtbl[3]))((IAsyncOperationProgressHandler <TResult, TProgress> *)Unsafe.AsPointer(ref this), asyncInfo, progressInfo));
 }
Exemple #7
0
 /// <summary>Gets a Task to represent the asynchronous operation.</summary>
 /// <param name="source">The asynchronous operation.</param>
 /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
 /// <returns>The Task representing the asynchronous operation.</returns>
 public static Task <TResult> AsTask <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source,
                                                          CancellationToken cancellationToken)
 {
     return(AsTask(source, cancellationToken, null));
 }
Exemple #8
0
 private void OnSocketWriterCompleted(IAsyncOperationWithProgress<uint, uint> asyncInfo, AsyncStatus asyncStatus)
 {
     if (asyncStatus == AsyncStatus.Completed)
     {
     #if DEBUG
         _manager.Events.LogMessage(this, LogType.Debug, "Outgoing Message: {0}", _socketWriteMessage);
     #endif
         _socketWriteMessage = "";
     }
     else if (asyncStatus == AsyncStatus.Error)
     {
         ConnectionError(ErrorType.SocketWriteInterrupted, ErrorPolicyType.Reconnect);
     }
 }
        /// <summary>
        /// Converts a Windows Runtime asynchronous operation to an observable sequence reporting its progress but ignoring its result value.
        /// Each observer subscribed to the resulting observable sequence will be notified about the action's succesful or exceptional completion.
        /// </summary>
        /// <typeparam name="TResult">The type of the asynchronous operation's result, which gets ignored by this conversion.</typeparam>
        /// <typeparam name="TProgress">The type of the reported progress objects.</typeparam>
        /// <param name="source">Asynchronous action to convert.</param>
        /// <returns>An observable sequence that produces progress values from the asynchronous operatin and notifies observers about the operations's completion.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
        public static IObservable <TProgress> ToObservableProgress <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            return(Observable.Create <TProgress>(observer =>
            {
                var progress = observer.ToProgress();
                var src = source.ToObservable_(progress, false);
                return src.Subscribe(_ => { }, observer.OnError, observer.OnCompleted);
            }));
        }
        internal StreamWriteAsyncResult(IAsyncOperationWithProgress<UInt32, UInt32> asyncStreamWriteOperation,
                                        AsyncCallback userCompletionCallback, Object userAsyncStateInfo,
                                        bool processCompletedOperationInCallback)

            : base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
        {
            asyncStreamWriteOperation.Completed = this.StreamOperationCompletedCallback;
        }
        private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<IBuffer, UInt32> completedOperation, out Int64 bytesCompleted)
        {
            IBuffer resultBuffer = completedOperation.GetResults();
            Debug.Assert(resultBuffer != null);

            WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer);
            bytesCompleted = _userBuffer.Length;
        }
        internal StreamReadAsyncResult(IAsyncOperationWithProgress<IBuffer, UInt32> asyncStreamReadOperation, IBuffer buffer,
                                       AsyncCallback userCompletionCallback, Object userAsyncStateInfo,
                                       bool processCompletedOperationInCallback)

            : base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
        {
            if (buffer == null)
                throw new ArgumentNullException(nameof(buffer));

            _userBuffer = buffer;
            asyncStreamReadOperation.Completed = this.StreamOperationCompletedCallback;
        }
Exemple #13
0
 public static int AddEntry(this List<DownloadFile> fileList, string token, IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> operation)
 {
     var newEntry = new DownloadFile(token, operation);
     fileList.Add(newEntry);
     return fileList.Count() - 1;
 }
Exemple #14
0
 public static int AddEntry(this List<UploadFile> fileList, StorageFile file, DateTime uploadTime, IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> operation)
 {
     var newEntry = new UploadFile(file, uploadTime, operation);
     fileList.Add(newEntry);
     return fileList.Count() - 1;
 }
Exemple #15
0
        public async Task DownloadAndInstallAllUpdatesAsync()
        {
            UpdateRing.IsActive   = true;
            CheckUpdate.IsEnabled = false;
            if (context == null)
            {
                context = StoreContext.GetDefault();
            }

            // Get the updates that are available.
            IReadOnlyList <StorePackageUpdate> updates =
                await context.GetAppAndOptionalStorePackageUpdatesAsync();

            if (updates.Count > 0)
            {
                // Alert the user that updates are available and ask for their consent
                // to start the updates.
                MessageDialog dialog = new MessageDialog(
                    "立即下载并安装更新吗? 此过程应用可能会关闭。", "发现新版本的夏日!");
                dialog.Commands.Add(new UICommand("更新"));
                dialog.Commands.Add(new UICommand("取消"));
                IUICommand command = await dialog.ShowAsync();

                if (command.Label.Equals("更新", StringComparison.CurrentCultureIgnoreCase))
                {
                    //downloadProgressBar.Visibility = Visibility.Visible;
                    // Download and install the updates.
                    IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> downloadOperation =
                        context.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);

                    // The Progress async method is called one time for each step in the download
                    // and installation process for each package in this request.

                    downloadOperation.Progress = async(asyncInfo, progress) =>
                    {
                        await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                                       () =>
                                                       { });
                    };
                    //downloadProgressBar.Visibility = Visibility.Collapsed;
                    StorePackageUpdateResult result = await downloadOperation.AsTask();

                    UpdateRing.IsActive   = false;
                    CheckUpdate.IsEnabled = true;
                }
                else
                {
                    UpdateRing.IsActive   = false;
                    CheckUpdate.IsEnabled = true;
                }
            }
            else
            {
                UpdateRing.IsActive   = false;
                CheckUpdate.IsEnabled = true;
                PopupNotice popupNotice = new PopupNotice("已是最新版本!");
                popupNotice.ShowAPopup();
            }
        }
        private IAsyncResult BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state, bool usedByBlockingWrapper)
        {
            // This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult).
            // It would be OK for cases where BeginRead is invoked directly by the public user.
            // However, in cases where it is invoked by Read to achieve a blocking (synchronous) IO operation, the ReadAsync-approach may deadlock:
            //
            // The sync-over-async IO operation will be doing a blocking wait on the completion of the async IO operation assuming that
            // a wait handle would be signalled by the completion handler. Recall that the IAsyncInfo representing the IO operation may
            // not be free-threaded and not "free-marshalled"; it may also belong to an ASTA compartment because the underlying WinRT
            // stream lives in an ASTA compartment. The completion handler is invoked on a pool thread, i.e. in MTA.
            // That handler needs to fetch the results from the async IO operation, which requires a cross-compartment call from MTA into ASTA.
            // But because the ASTA thread is busy waiting this call will deadlock.
            // (Recall that although WaitOne pumps COM, ASTA specifically schedules calls on the outermost ?idle? pump only.)
            //
            // The solution is to make sure that:
            //  - In cases where main thread is waiting for the async IO to complete:
            //    Fetch results on the main thread after it has been signalled by the completion callback.
            //  - In cases where main thread is not waiting for the async IO to complete:
            //    Fetch results in the completion callback.
            //
            // But the Task-plumbing around IAsyncInfo.AsTask *always* fetches results in the completion handler because it has
            // no way of knowing whether or not someone is waiting. So, instead of using ReadAsync here we implement our own IAsyncResult
            // and our own completion handler which can behave differently according to whether it is being used by a blocking IO
            // operation wrapping a BeginRead/EndRead pair, or by an actual async operation based on the old Begin/End pattern.

            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            if (buffer.Length - offset < count)
            {
                throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
            }

            Contract.EndContractBlock();

            IInputStream wrtStr = EnsureNotDisposed <IInputStream>();

            EnsureCanRead();

#if DEBUG
            AssertValidStream(wrtStr);
#endif  // DEBUG

            IBuffer userBuffer = buffer.AsBuffer(offset, count);
            IAsyncOperationWithProgress <IBuffer, UInt32> asyncReadOperation = wrtStr.ReadAsync(userBuffer,
                                                                                                unchecked ((UInt32)count),
                                                                                                InputStreamOptions.Partial);

            StreamReadAsyncResult asyncResult = new StreamReadAsyncResult(asyncReadOperation, userBuffer, callback, state,
                                                                          processCompletedOperationInCallback: !usedByBlockingWrapper);

            // The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation.
            // This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to
            // asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW
            // will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer is the only
            // item to whcih we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped.

            return(asyncResult);
        }
 private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<UInt32, UInt32> completedOperation, out Int64 bytesCompleted)
 {
     UInt32 bytesWritten = completedOperation.GetResults();
     bytesCompleted = bytesWritten;
 }
 /// <summary>Bridge to Completed handler on IAsyncOperationWithProgress{TResult,TProgress}.</summary>
 /// <typeparam name="TProgress">Specifies the type of progress notification data.</typeparam>
 internal void CompleteFromAsyncOperationWithProgress <TProgress>(IAsyncOperationWithProgress <TResult, TProgress> asyncInfo, AsyncStatus asyncStatus)
 {
     // delegate cached by compiler:
     Complete(asyncInfo, ai => ((IAsyncOperationWithProgress <TResult, TProgress>)ai).GetResults(), asyncStatus);
 }
Exemple #19
0
        private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress <UInt32, UInt32> completedOperation, out Int64 bytesCompleted)
        {
            UInt32 bytesWritten = completedOperation.GetResults();

            bytesCompleted = bytesWritten;
        }
Exemple #20
0
        private void SocketSend(string message, bool synchronized = false)
        {
            if (!IsConnected || string.IsNullOrEmpty(message) ) return;

            // Prepare message
            _socketWriteMessage = message;
            byte[] writeBytes = _encoding.GetBytes(message);

            if( _isCompressionEnabled )
                writeBytes = _compression.Deflate(writeBytes);

            IBuffer sendBuffer = CryptographicBuffer.CreateFromByteArray(writeBytes);

            if (synchronized) // Wait for completion
            {
                _elevateMutex.WaitOne(10000);
                _manager.Socket.OutputStream.WriteAsync(sendBuffer).AsTask().Wait(10000);
            }
            else // wait for last task and start new one
            {
                // Wait for other reads to finish
                if (_socketWriter != null && _socketWriter.Status == AsyncStatus.Started)
                {
                    try
                    {
                        _socketWriter.AsTask().Wait(10000);
                    }
                    catch
                    {
                        //if (_socketWriter.Status == AsyncStatus.Started)
                        //{
                        //    ConnectionError(ErrorType.WriteStateMismatch, ErrorPolicyType.Reconnect);
                        //    return;
                        //}
                    }
                }

                _elevateMutex.WaitOne(10000);

                if (IsConnected)
                {
                    _socketWriter = _manager.Socket.OutputStream.WriteAsync(sendBuffer);
                    _socketWriter.Completed = OnSocketWriterCompleted;
                }
            }
        }
Exemple #21
0
        private async void SendSysExFile_Click(object sender, RoutedEventArgs e)
        {
            CloseAllTips();


            // validate the user-entered parameters

            uint transferDelayBetweenBuffers = 0;

            if ((!uint.TryParse(EnteredTransferDelay.Text, out transferDelayBetweenBuffers)) || transferDelayBetweenBuffers < 0)
            {
                var dlg = new MessageDialog("For the send delay, please enter a positive whole number. This is the delay between buffers sent over MIDI.");
                await dlg.ShowAsync();

                return;
            }

            // validate, open the port, and then send the file
            if (_inputFile != null)
            {
                if (_outputPortDeviceInformation != null)
                {
                    // open the MIDI port
                    var outputPort = await MidiOutPort.FromIdAsync(_outputPortDeviceInformation.Id);

                    if (outputPort != null)
                    {
                        // open the file
                        var stream = await _inputFile.OpenReadAsync();

                        if (stream != null && stream.CanRead)
                        {
                            // validate the file

                            var validationStatus = await MidiSysExSender.MeasureAndValidateSysExFile(stream);

                            if (validationStatus.Status != MidiSysExSender.MidiSysExFileValidationStatus.OK)
                            {
                                // TODO: log failure

                                var dlg = new MessageDialog(validationStatus.GetStatusDescription());
                                dlg.Title = "Invalid SysEx file";
                                await dlg.ShowAsync();

                                return;
                            }

                            // Show statistics from the file
                            FileInformationPanel.Visibility  = Visibility.Visible;
                            CalculatedBufferSize.Text        = string.Format("{0:n0}", validationStatus.BufferSize);
                            CalculatedSysExMessageCount.Text = string.Format("{0:n0}", validationStatus.MessageCount);
                            CalculatedFileSize.Text          = string.Format("{0:n0}", validationStatus.FileSize);


                            // send the bytes
                            _transferOperation = MidiSysExSender.SendSysExStreamAsyncWithProgress(
                                stream, outputPort, validationStatus.BufferSize, transferDelayBetweenBuffers);

                            // show progress of the operation. This is updated async
                            ProgressPanel.Visibility = Visibility.Visible;
                            Cancel.IsEnabled         = true;


                            //report progress
                            _transferOperation.Progress = (result, progress) =>
                            {
                                SysExSendProgressBar.Value = (double)progress.BytesRead;
                                ProgressBytes.Text         = string.Format("{0:n0}", progress.BytesRead);
                                PercentComplete.Text       = Math.Round(((double)progress.BytesRead / _fileSizeInBytes) * 100, 0) + "%";

                                TransferOperationInProgress.Text = MidiSysExSender.GetStageDescription(progress.Stage);
                            };

                            // handle completion
                            _transferOperation.Completed = async(result, progress) =>
                            {
                                // no need for cancel anymore
                                Cancel.IsEnabled = false;

                                // nuke the stream
                                stream.Dispose();
                                stream = null;

                                // close the MIDI port
                                outputPort = null;

                                // show completion message, depending on what type of completion we have
                                if (result.Status == AsyncStatus.Canceled)
                                {
                                    TransferOperationInProgress.Text = "Canceled";

                                    Statistics.TotalCancelCount += 1;
                                    Analytics.LogEvent(AnalyticsEvent.TransferCancel);

                                    var dlg = new MessageDialog("Transfer canceled.");
                                    await dlg.ShowAsync();
                                }
                                else if (result.Status == AsyncStatus.Error)
                                {
                                    TransferOperationInProgress.Text = "Error";

                                    Statistics.TotalErrorCount += 1;
                                    Analytics.LogEvent(AnalyticsEvent.TransferError);

                                    var dlg = new MessageDialog("Transfer error. You may need to close and re-open this app, and likely also reboot your device.");
                                    await dlg.ShowAsync();
                                }
                                else
                                {
                                    SysExSendProgressBar.Value       = (double)_fileSizeInBytes;
                                    ProgressBytes.Text               = string.Format("{0:N0}", _fileSizeInBytes);
                                    PercentComplete.Text             = "100%";
                                    TransferOperationInProgress.Text = "Completed";

                                    // save the user-entered settings, since they worked
                                    //Settings.TransferBufferSize = transferBufferSize;
                                    Settings.TransferDelayBetweenBuffers = transferDelayBetweenBuffers;
                                    //Settings.F0Delay = f0Delay;

                                    // update user stats (for local use and display)
                                    Statistics.TotalFilesTransferred += 1;
                                    Statistics.TotalBytesTransferred += _fileSizeInBytes;

                                    Analytics.LogEvent(AnalyticsEvent.TransferSuccess);

                                    NotificationManager.NotifySuccess(_fileSizeInBytes, _inputFile.Name);
                                }
                            };
                        }
                        else
                        {
                            // TODO: log failure

                            // stream is null or CanRead is false
                            var dlg = new MessageDialog("Could not open file '" + _inputFile.Name + "' for reading.");
                            await dlg.ShowAsync();
                        }
                    }
                    else
                    {
                        // TODO: log failure

                        // outputPort is null
                        var dlg = new MessageDialog("Could not open MIDI output port '" + _outputPortDeviceInformation.Name + "'");
                        await dlg.ShowAsync();
                    }
                }
                else
                {
                    // TODO: log failure

                    // _outputPortDeviceInformation is null
                    var dlg = new MessageDialog("No MIDI output port selected'");
                    await dlg.ShowAsync();
                }
            }
            else
            {
                // TODO: log failure

                // _inputFile is null
                var dlg = new MessageDialog("No SysEx input file selected'");
                await dlg.ShowAsync();
            }
        }
Exemple #22
0
        /// <summary>Gets a Task to represent the asynchronous operation.</summary>
        /// <param name="source">The asynchronous operation.</param>
        /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
        /// <param name="progress">The progress object used to receive progress updates.</param>
        /// <returns>The Task representing the asynchronous operation.</returns>
        public static Task <TResult> AsTask <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source,
                                                                 CancellationToken cancellationToken, IProgress <TProgress> progress)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            Contract.EndContractBlock();

            // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
            var wrapper = source as TaskToAsyncOperationWithProgressAdapter <TResult, TProgress>;

            if (wrapper != null && !wrapper.CompletedSynchronously)
            {
                Task <TResult> innerTask = wrapper.Task as Task <TResult>;
                Debug.Assert(innerTask != null);
                Debug.Assert(innerTask.Status != TaskStatus.Created);  // Is WaitingForActivation a legal state at this moment?

                if (!innerTask.IsCompleted)
                {
                    // The race here is benign: If the task completes here, the concatinations are useless, but not damaging.

                    if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
                    {
                        ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
                    }

                    if (progress != null)
                    {
                        ConcatenateProgress(source, progress);
                    }
                }

                return(innerTask);
            }

            // Fast path to return a completed Task if the operation has already completed
            switch (source.Status)
            {
            case AsyncStatus.Completed:
                return(Task.FromResult(source.GetResults()));

            case AsyncStatus.Error:
                return(Task.FromException <TResult>(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode)));

            case AsyncStatus.Canceled:
                return(Task.FromCancellation <TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)));
            }

            // Benign race: source may complete here. Things still work, just not taking the fast path.

            // Forward progress reports:
            if (progress != null)
            {
                ConcatenateProgress(source, progress);
            }

            // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
            var bridge = new AsyncInfoToTaskBridge <TResult, TProgress>(cancellationToken);

            source.Completed = new AsyncOperationWithProgressCompletedHandler <TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress);
            bridge.RegisterForCancellation(source);

            return(bridge.Task);
        }
Exemple #23
0
        private void SendHttpRequest()
        {
            // Tie the transport method to the ControlChannelTrigger object to push enable it.
            // Note that if the transport's TCP connection is broken at a later point of time,
            // the ControlChannelTrigger object can be reused to plug in a new transport by
            // calling UsingTransport again.
            Diag.DebugPrint("Calling UsingTransport() ...");
            channel.UsingTransport(httpRequest);

            // Call the SendRequestAsync function to kick start the TCP connection establishment
            // process for this HTTP request.
            Diag.DebugPrint("Calling SendRequestAsync() ...");
            sendRequestOperation = httpClient.SendRequestAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
            sendRequestOperation.Completed += OnSendRequestCompleted;

            // Call WaitForPushEnabled API to make sure the TCP connection has been established, 
            // which will mean that the OS will have allocated any hardware or software slot for this TCP connection.

            ControlChannelTriggerStatus status = channel.WaitForPushEnabled();
            Diag.DebugPrint("WaitForPushEnabled() completed with status: " + status);
            if (status != ControlChannelTriggerStatus.HardwareSlotAllocated
                && status != ControlChannelTriggerStatus.SoftwareSlotAllocated)
            {
                throw new Exception("Hardware/Software slot not allocated");
            }

            Diag.DebugPrint("Transport is ready to read response from server.");
        }
Exemple #24
0
 public static Task <TResult> AsTask <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source, CancellationToken cancellationToken, IProgress <TProgress> progress)
 {
     throw new NotImplementedException();
 }
Exemple #25
0
        private void OnSendRequestCompleted(IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> asyncInfo, AsyncStatus asyncStatus)
        {
            try
            {
                if (asyncStatus == AsyncStatus.Canceled)
                {
                    Diag.DebugPrint("HttpRequestMessage.SendRequestAsync was canceled.");
                    return;
                }

                if (asyncStatus == AsyncStatus.Error)
                {
                     
                    Diag.DebugPrint("HttpRequestMessage.SendRequestAsync failed: " + asyncInfo.ErrorCode);
                    return;
                }

                Diag.DebugPrint("HttpRequestMessage.SendRequestAsync succeeded.");

                HttpResponseMessage response = asyncInfo.GetResults();
                readAsInputStreamOperation = response.Content.ReadAsInputStreamAsync();
                readAsInputStreamOperation.Completed = OnReadAsInputStreamCompleted;
            }
            catch (Exception ex)
            {
                Diag.DebugPrint("Error in OnSendRequestCompleted: " + ex.ToString());
            }
        }
        /// <summary>
        /// API for getting installation status.
        /// </summary>
        /// <returns>The status</returns>
#pragma warning disable 1998
        public async Task <ApplicationInstallStatus> GetInstallStatusAsync()
        {
            ApplicationInstallStatus status = ApplicationInstallStatus.None;

            Uri uri = Utilities.BuildEndpoint(
                this.deviceConnection.Connection,
                InstallStateApi);

            HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter();

            httpFilter.AllowUI = false;

            if (this.deviceConnection.Credentials != null)
            {
                httpFilter.ServerCredential          = new PasswordCredential();
                httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName;
                httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password;
            }

            using (HttpClient client = new HttpClient(httpFilter))
            {
                this.ApplyHttpHeaders(client, HttpMethods.Get);

                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri);
                while (responseOperation.Status != AsyncStatus.Completed)
                {
                }

                using (HttpResponseMessage response = responseOperation.GetResults())
                {
                    if (response.IsSuccessStatusCode)
                    {
                        if (response.StatusCode == HttpStatusCode.Ok)
                        {
                            // Status code: 200
                            if (response.Content != null)
                            {
                                Stream dataStream = null;

                                IBuffer dataBuffer = null;
                                using (IHttpContent messageContent = response.Content)
                                {
                                    IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync();
                                    while (bufferOperation.Status != AsyncStatus.Completed)
                                    {
                                    }

                                    dataBuffer = bufferOperation.GetResults();

                                    if (dataBuffer != null)
                                    {
                                        dataStream = dataBuffer.AsStream();
                                    }
                                }

                                if (dataStream != null)
                                {
                                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HttpErrorResponse));

                                    HttpErrorResponse errorResponse = (HttpErrorResponse)serializer.ReadObject(dataStream);

                                    if (errorResponse.Success)
                                    {
                                        status = ApplicationInstallStatus.Completed;
                                    }
                                    else
                                    {
                                        throw new DevicePortalException(response.StatusCode, errorResponse, uri);
                                    }
                                }
                                else
                                {
                                    throw new DevicePortalException(HttpStatusCode.Conflict, "Failed to deserialize GetInstallStatus response.");
                                }
                            }
                        }
                        else if (response.StatusCode == HttpStatusCode.NoContent)
                        {
                            // Status code: 204
                            status = ApplicationInstallStatus.InProgress;
                        }
                    }
                    else
                    {
                        throw new DevicePortalException(response);
                    }
                }
            }

            return(status);
        }
Exemple #27
0
        private void OnReadAsInputStreamCompleted(IAsyncOperationWithProgress<IInputStream, ulong> asyncInfo, AsyncStatus asyncStatus)
        {
            try
            {
                if (asyncStatus == AsyncStatus.Canceled)
                {
                    Diag.DebugPrint("IHttpContent.ReadAsInputStreamAsync was canceled.");
                    return;
                }

                if (asyncStatus == AsyncStatus.Error)
                {
                    Diag.DebugPrint("IHttpContent.ReadAsInputStreamAsync failed: " + asyncInfo.ErrorCode);
                    return;
                }

                Diag.DebugPrint("IHttpContent.ReadAsInputStreamAsync succeeded.");

                inputStream = asyncInfo.GetResults();
                ReadMore();
            }
            catch (Exception ex)
            {
                Diag.DebugPrint("Error in OnReadAsInputStreamCompleted: " + ex.ToString());
            }
        }
        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]);
                }
            }
        }
Exemple #29
0
 private void ReadMore()
 {
     IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);
     readOperation = inputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);
     readOperation.Completed = OnReadCompleted;
 }
        private async Task StartAppSelfUpdate()
        {
            Debug.WriteLine("Check for updates...");
            StoreContext context = StoreContext.GetDefault();

            // Check for updates...
            string lastCheck = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");

            ReportSelfUpdateStatus(lastCheck, "checkStarting");

            IReadOnlyList <StorePackageUpdate> updates = await context.GetAppAndOptionalStorePackageUpdatesAsync();

            if (updates.Count == 0)
            {
                ReportSelfUpdateStatus(lastCheck, "noUpdates");
                return;
            }

            // Download and install the updates...
            IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> downloadOperation =
                context.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);

            ReportSelfUpdateStatus(lastCheck, "updatesDownloadingAndInstalling");

            // Wait for completion...
            StorePackageUpdateResult result = await downloadOperation.AsTask();

            ReportSelfUpdateStatus(lastCheck, result.OverallState == StorePackageUpdateState.Completed ? "installed" : "failed");

            return;
        }
Exemple #31
0
        private void OnReadCompleted(IAsyncOperationWithProgress<IBuffer, uint> asyncInfo, AsyncStatus asyncStatus)
        {
            try
            {
                if (asyncStatus == AsyncStatus.Canceled)
                {
                    Diag.DebugPrint("IInputStream.ReadAsync was canceled.");
                    return;
                }

                if (asyncStatus == AsyncStatus.Error)
                {
                    Diag.DebugPrint("IInputStream.ReadAsync failed: " + asyncInfo.ErrorCode);
                    return;
                }

                IBuffer buffer = asyncInfo.GetResults();

                Diag.DebugPrint("IInputStream.ReadAsync succeeded. " + buffer.Length + " bytes read.");

                if (buffer.Length == 0)
                {
                    // The response is complete
                    lock (this)
                    {
                        ResetRequest();
                    }
                    return;
                }

                byte[] rawBuffer = buffer.ToArray();
                Debug.Assert(buffer.Length <= Int32.MaxValue);

                // The test server content response is UTF-8 encoded. If another encoding is used,
                // change the encoding class in the following line.
                string responseString = Encoding.UTF8.GetString(rawBuffer, 0, (int)buffer.Length);

                // Add the message into a queue that the push notify task will pick up
                AppContext.messageQueue.Enqueue(responseString);

                ReadMore();
            }
            catch (Exception ex)
            {
                Diag.DebugPrint("Error in OnReadCompleted: " + ex.ToString());
            }
        }
 internal void CompleteFromAsyncOperationWithProgress(IAsyncOperationWithProgress <TResult, TProgress> asyncInfo, AsyncStatus asyncStatus)
 {
     Complete(asyncInfo, ai => ((IAsyncOperationWithProgress <TResult, TProgress>)ai).GetResults(), asyncStatus);
 }
Exemple #33
0
 private void DownloadCompleted(IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> asyncInfo, AsyncStatus asyncStatus)
 {
     MainPage.Current.PopMessage(Consts.Localizer.GetString("DownloadCompletedText"));
     MainPage.Current.ProgressUpdate(Consts.Localizer.GetString("CompletedText"), Consts.Localizer.GetString("DownloadCompletedText"));
 }
        private bool UpdateProgressForDeploymentTask(Presenter.Progress.ProgressPresenter progressPresenter, IAsyncOperationWithProgress <Windows.Management.Deployment.DeploymentResult, Windows.Management.Deployment.DeploymentProgress> deploymentTask)
        {
            bool success           = false;
            var  addCompletedEvent = new ManualResetEvent(false);

            deploymentTask.Completed = (result, progress) =>
            {
                progressPresenter.OverallProgress = 100;
                addCompletedEvent.Set();
            };

            deploymentTask.Progress = (result, progress) =>
            {
                progressPresenter.OverallProgress = progress.percentage;
            };

            progressPresenter.SetDetailsText(true, "Waiting for task to complete...");
            addCompletedEvent.WaitOne();

            if (deploymentTask.Status == Windows.Foundation.AsyncStatus.Error)
            {
                var result = deploymentTask.GetResults();
                progressPresenter.SetDetailsText(true, "Error: {0}", result.ExtendedErrorCode);
                progressPresenter.SetDetailsText(true, "Detailed Error Text: {0}", result.ErrorText);
                success = false;
            }
            else if (deploymentTask.Status == Windows.Foundation.AsyncStatus.Canceled)
            {
                success = false;
                progressPresenter.SetDetailsText(true, "Task Canceled");
            }
            else if (deploymentTask.Status == Windows.Foundation.AsyncStatus.Completed)
            {
                progressPresenter.SetDetailsText(true, "Task succeeded!");
                success = true;
            }
            else
            {
                success = false;
                progressPresenter.SetDetailsText(true, "Task status unknown");
            }
            return(success);
        }
        private async Task <bool> DownloadPackageUpdatesAsync(IEnumerable <StorePackageUpdate> updates)
        {
            bool downloadedSuccessfully = false;

            // If automatic updates are on, the download will begin, otherwise it may prompt
            IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> downloadOperation =
                updateManager.RequestDownloadStorePackageUpdatesAsync(updates);

            downloadOperation.Progress = async(asyncInfo, progress) =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    // Progress gets called once for each progress step of each package.
                    // If you are downloading 10 packages, and each gets 10 notifications...
                    // You will receive 100 progress updates.
                    ShowProgress(
                        updates.SingleOrDefault(update => update.Package.Id.FamilyName == progress.PackageFamilyName),
                        progress);
                });
            };

            // Wait for the download operation to complete
            StorePackageUpdateResult result = await downloadOperation.AsTask();

            switch (result.OverallState)
            {
            case StorePackageUpdateState.Completed:
                // Everything worked, now ready to install the updates.
                downloadedSuccessfully = true;
                break;

            default:
                // The overall progress didn't complete
                // Find failed updates
                var failedUpdates = result.StorePackageUpdateStatuses.Where(status => status.PackageUpdateState != StorePackageUpdateState.Completed);

                // See if any failed updates were mandatory
                if (updates.Any(u => u.Mandatory && failedUpdates.Any(failed => failed.PackageFamilyName == u.Package.Id.FamilyName)))
                {
                    // At least one of the updates is mandatory, so tell the user.
                    ShowMandatoryMessage();
                }
                break;
            }

            return(downloadedSuccessfully);
        }
        /// <summary>
        /// Converts a Windows Runtime asynchronous operation to an observable sequence by retrieving the operation's results whenever progress is reported and when the operation completes. The operation's progress is reported through the supplied progress object.
        /// Each observer subscribed to the resulting observable sequence will be notified about the action's succesful or exceptional completion.
        /// </summary>
        /// <typeparam name="TResult">The type of the asynchronous operation's result.</typeparam>
        /// <typeparam name="TProgress">The type of the reported progress objects.</typeparam>
        /// <param name="source">Asynchronous operation to convert.</param>
        /// <param name="progress">Progress object to receive progress notifications on.</param>
        /// <returns>An observable sequence that notifies observers about the asynchronous operation's (incremental) result value(s) and completion.</returns>
        /// <remarks>This conversion can be used with Windows Runtime APIs that support incremental retrieval of results during an asynchronous operation's execution.</remarks>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="progress"/> is null.</exception>
        public static IObservable <TResult> ToObservableMultiple <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source, IProgress <TProgress> progress)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (progress == null)
            {
                throw new ArgumentNullException(nameof(progress));
            }

            return(source.ToObservable_(progress, true));
        }
        private async Task InstallPackageUpdatesAsync(IEnumerable <StorePackageUpdate> updates)
        {
            // This will prompt the user with a dialog depending on the state:
            //      Download and Install these updates? (size, etc)
            //      Install these updates?
            IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> installOperation =
                updateManager.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);

            // Note: This has "progress" as it can download if necessary
            // Since we separated our download and install into two steps, we won't have anything to download
            // and the download part will complete immediately.  If we hadn't done that, then we would get progress
            // notifications as the package was downloaded.
            StorePackageUpdateResult result = await installOperation.AsTask();

            await new MessageDialog("Installing...").ShowAsync();

            switch (result.OverallState)
            {
            case StorePackageUpdateState.Completed:
                // Should never hit for this sample. The install kills the app.
                break;

            default:

                // The install failed for some reason
                // Find failed updates
                var failedUpdates = result.StorePackageUpdateStatuses.Where(status => status.PackageUpdateState != StorePackageUpdateState.Completed);

                // See if any failed updates were mandatory
                if (updates.Any(u => u.Mandatory && failedUpdates.Any(failed => failed.PackageFamilyName == u.Package.Id.FamilyName)))
                {
                    // At least one of the updates is mandatory, so tell the user.
                    ShowMandatoryMessage();
                }
                break;

                //await new MessageDialog("Here 3").ShowAsync();
            }
        }
Exemple #38
0
        private void OnSocketReaderCompleted(IAsyncOperationWithProgress<IBuffer, uint> asyncInfo, AsyncStatus asyncStatus)
        {
            if (asyncStatus == AsyncStatus.Completed)
            {
                _manager.ProcessComplete.Reset();

                IBuffer readBuffer = asyncInfo.GetResults();

                if (readBuffer.Length == 0)
                {
                    // This is not neccessarily an error, it can be just fine
                    //ConnectionError(ErrorType.ServerDisconnected, "Server sent empty package");
                    return;
                }

                // Get data
                byte[] readBytes = new byte[readBuffer.Length];
                DataReader dataReader = DataReader.FromBuffer(readBuffer);
                dataReader.ReadBytes(readBytes);
                dataReader.DetachBuffer();

                // Check if it is a keepalive
                if (readBytes.Length != 1 && readBytes[0] != 0)
                {
                    // Trim
                    readBytes = readBytes.TrimNull();

                    if (readBytes == null || readBytes.Length == 0)
                    {
                        ConnectionError(ErrorType.ServerDisconnected, ErrorPolicyType.Reconnect, "Server sent empty package");
                        return;
                    }

                    // Decompress
                    if (_isCompressionEnabled)
                        readBytes = _compression.Inflate(readBytes, readBytes.Length);

                    // Encode to string
                    string data = _encoding.GetString(readBytes, 0, readBytes.Length);

                    // Add to parser
            #if DEBUG
                    _manager.Events.LogMessage(this, LogType.Debug, "Incoming data: {0}", data);
            #endif

                    _manager.Parser.Parse(data);
                }

                _manager.ProcessComplete.Set();

                SocketRead();
            }
            else if (asyncStatus == AsyncStatus.Error)
            {
                ConnectionError(ErrorType.SocketReadInterrupted, ErrorPolicyType.Reconnect);
                return;
            }
        }
        private async void Button_Click_Update_Blocking(object sender, RoutedEventArgs e)
        {
            try
            {
                // Block trying to get all updates
                updates = await updateManager.GetAppAndOptionalStorePackageUpdatesAsync();

                if (updates.Count > 0)
                {
                    TotalProgressBar.Visibility = Visibility.Visible;

                    // Trigger download and monitor progress
                    IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> downloadOperation = updateManager.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);
                    downloadOperation.Progress = async(asyncInfo, progress) =>
                    {
                        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            TotalProgressBar.Value = progress.TotalDownloadProgress * 100;
                        });
                    };

                    // Wait for download and install to complete
                    StorePackageUpdateResult result = await downloadOperation.AsTask();
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog("Unable to perform simple blocking update. {" + err(ex) + "}").ShowAsync();
            }
        }
Exemple #40
0
        private void SocketRead()
        {
            try
            {

                if (!IsConnected) return;
                _elevateMutex.WaitOne(10000);

                _socketReader = _manager.Socket.InputStream.ReadAsync(_socketReadBuffer, _bufferSize, InputStreamOptions.Partial);
                _socketReader.Completed = OnSocketReaderCompleted;
            }
            catch
            {
                ConnectionError(ErrorType.ConnectToServerFailed, ErrorPolicyType.Reconnect);
            }
        }
        private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress <uint, uint> completedOperation, out long bytesCompleted)
        {
            uint bytesWritten = completedOperation.GetResults();

            bytesCompleted = bytesWritten;
        }
Exemple #42
0
 public static TaskAwaiter <TResult> GetAwaiter <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source)
 {
     return(AsTask(source).GetAwaiter());
 }
        public static async Task <Boolean> DownloadPackageUpdatesAsync(IEnumerable <StorePackageUpdate> updates)
        {
            InitStoreContext();

            bool success = false;

            IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> downloadOperation = shared._storeContext.RequestDownloadStorePackageUpdatesAsync(updates);

            downloadOperation.Progress = (asyncInfo, progress) =>
            {
                LogProgress(progress);
                UpdateManager.OnDownloadProgress(progress);
            };

            StorePackageUpdateResult result = await downloadOperation.AsTask();

            switch (result.OverallState)
            {
            case StorePackageUpdateState.Completed:
                success = true;
                break;

            case StorePackageUpdateState.OtherError:
                System.Diagnostics.Debug.WriteLine("Error code: " + downloadOperation.ErrorCode);
                break;

            default:
                break;
            }

            return(success);
        }
Exemple #44
0
 /// <summary>Gets a Task to represent the asynchronous operation.</summary>
 /// <param name="source">The asynchronous operation.</param>
 /// <param name="progress">The progress object used to receive progress updates.</param>
 /// <returns>The Task representing the asynchronous operation.</returns>
 public static Task <TResult> AsTask <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source,
                                                          IProgress <TProgress> progress)
 {
     return(AsTask(source, CancellationToken.None, progress));
 }
        public static async Task <StorePackageUpdateState> InstallPackageUpdatesAsync(IEnumerable <StorePackageUpdate> updates)
        {
            IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> installOperation = shared._storeContext.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);

            StorePackageUpdateResult result = await installOperation.AsTask();

            return(result.OverallState);
        }
Exemple #46
0
 private static void ConcatenateProgress <TResult, TProgress>(IAsyncOperationWithProgress <TResult, TProgress> source, IProgress <TProgress> sink)
 {
     // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null.
     source.Progress += new AsyncOperationProgressHandler <TResult, TProgress>((_, info) => sink.Report(info));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DevicePortalException"/> class.
        /// </summary>
        /// <param name="responseMessage">Http response message.</param>
        /// <param name="message">Optional exception message.</param>
        /// <param name="innerException">Optional inner exception.</param>
        public DevicePortalException(
            HttpResponseMessage responseMessage,
            string message           = "",
            Exception innerException = null) : this(
                responseMessage.StatusCode,
                responseMessage.ReasonPhrase,
                responseMessage.RequestMessage != null ? responseMessage.RequestMessage.RequestUri : null,
                message,
                innerException)
        {
            try
            {
                if (responseMessage.Content != null)
                {
                    Stream dataStream = null;
#if !WINDOWS_UWP
                    using (HttpContent content = responseMessage.Content)
                    {
                        dataStream = new MemoryStream();

                        Task copyTask = content.CopyToAsync(dataStream);
                        copyTask.ConfigureAwait(false);
                        copyTask.Wait();

                        // Ensure we point the stream at the origin.
                        dataStream.Position = 0;
                    }
#else // WINDOWS_UWP
                    IBuffer dataBuffer = null;
                    using (IHttpContent messageContent = responseMessage.Content)
                    {
                        IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync();
                        while (bufferOperation.Status != AsyncStatus.Completed)
                        {
                        }

                        dataBuffer = bufferOperation.GetResults();

                        if (dataBuffer != null)
                        {
                            dataStream = dataBuffer.AsStream();
                        }
                    }
#endif  // WINDOWS_UWP

                    if (dataStream != null)
                    {
                        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HttpErrorResponse));

                        HttpErrorResponse errorResponse = (HttpErrorResponse)serializer.ReadObject(dataStream);

                        this.HResult = errorResponse.ErrorCode;
                        this.Reason  = errorResponse.ErrorMessage;

                        // If we didn't get the Hresult and reason from these properties, try the other ones.
                        if (this.HResult == 0)
                        {
                            this.HResult = errorResponse.Code;
                        }

                        if (string.IsNullOrEmpty(this.Reason))
                        {
                            this.Reason = errorResponse.Reason;
                        }
                    }
                }
            }
            catch (Exception)
            {
                // Do nothing if we fail to get additional error details from the response body.
            }
        }
Exemple #48
0
 public static Task <TResult> AsTask <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source)
 {
     throw new NotImplementedException();
 }
        private async Task StartDownloadAndReadContentsAsync()
        {
            try
            {
                // Retrieve a random access stream from the download operation. Every OpenReadAsync() operation returns
                // a new stream instance that is independent of previous ones (i.e., the seek position of one stream
                // isn't affected by calls on another stream).
                //
                // This sample demonstrates the direct usage of a DownloadOperation's random access stream and its
                // effects on the ongoing transfer. However, bear in mind that there are a variety of operations
                // that can manage the stream on the app's behalf for specific scenarios. For instance, a
                // DownloadOperation pointing to a video URL can be consumed by the MediaPlayer class in four easy
                // steps:
                //
                // var randomAccessStreamReference = download.GetResultRandomAccessStreamReference();
                // stream = await randomAccessStreamReference.OpenReadAsync();
                // var mediaPlayer = new Windows.Media.Playback.MediaPlayer();
                // mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromStream(stream, stream.ContentType);

                var randomAccessStreamReference = download.GetResultRandomAccessStreamReference();
                randomAccessStream = await randomAccessStreamReference.OpenReadAsync();

                // Start the download. If the server doesn't support random access, the download will fail
                // with WebErrorStatus.InsufficientRangeSupport or WebErrorStatus.MissingContentLengthSupport.
                IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> downloadOperation = download.StartAsync();
                downloadOperation.Progress += OnDownloadProgress;
                Task downloadTask = downloadOperation.AsTask();

                startDownloadButton.IsEnabled = false;
                pauseDownloadButton.IsEnabled = true;

                // Read data while the download is still ongoing. Use a 1 MB read buffer for that purpose.
                var readBuffer = new Windows.Storage.Streams.Buffer(BytesPerMegaByte);
                while (!downloadTask.IsCompleted)
                {
                    ulong readOffsetInBytes = randomAccessStream.Position;

                    PreviousReadText.Text = CurrentReadText.Text;
                    CurrentReadText.Text  = $"Reading from offset {readOffsetInBytes:n0}";

                    readOperation = randomAccessStream.ReadAsync(
                        readBuffer,
                        readBuffer.Capacity,
                        InputStreamOptions.None).
                                    AsTask(readCancellationTokenSource.Token);

                    // Update the UI to show the current read's position.
                    currentPositionSlider.Value = readOffsetInBytes / BytesPerMegaByte;

                    try
                    {
                        // Wait for the read to complete.
                        IBuffer bytesRead = await readOperation;
                        CurrentReadText.Text += $", completed with {bytesRead.Length:n0} bytes";

                        // At this point, a real app would process the 'bytesRead' data to do something interesting
                        // with it (e.g., display video and/or play audio).

                        if (randomAccessStream.Position >= randomAccessStream.Size)
                        {
                            // We have reached EOF. Wrap around to the beginning while we wait for the download to complete.
                            randomAccessStream.Seek(0);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // The ongoing read was canceled by SeekDownload_Click(...) in order for a new download
                        // position to take effect immediately.
                        CurrentReadText.Text += ", cancelled.";
                    }
                }

                // Wait for the download to complete.
                await downloadTask;

                rootPage.NotifyUser("Download completed successfully", NotifyType.StatusMessage);
            }
            catch (Exception ex) when(IsWebException("Execution error", ex))
            {
                // Abandon the operation if a web exception occurs.
            }
            finally
            {
                download           = null;
                randomAccessStream = null;
                readOperation      = null;

                startDownloadButton.IsEnabled  = true;
                pauseDownloadButton.IsEnabled  = false;
                resumeDownloadButton.IsEnabled = false;
            }
        }
        /// <summary>
        /// Event Handler for progress of scanning 
        /// </summary>
        /// <param name="operation">async operation for scanning</param>
        /// <param name="numberOfFiles">The Number of files scanned so far</param>
        private async void ScanProgress(IAsyncOperationWithProgress<ImageScannerScanResult, UInt32> operation, UInt32 numberOfScannedFiles) 
        {
            
            ImageScannerScanResult result = null;
            try
            {
                result = operation.GetResults();
            }
            catch (OperationCanceledException)
            {
                // The try catch is placed here for scenarios in which operation has already been cancelled when progress call is made
                Utils.DisplayScanCancelationMessage();
            }

            if (result != null && result.ScannedFiles.Count > 0)
            {
                IReadOnlyList<StorageFile> fileStorageList = result.ScannedFiles;
                await MainPage.Current.Dispatcher.RunAsync(
                    Windows.UI.Core.CoreDispatcherPriority.Normal,
                    new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        StorageFile file = fileStorageList[0];
                        Utils.SetImageSourceFromFile(file, DisplayImage);

                        rootPage.NotifyUser("Scanning is in progress. The Number of files scanned so far: " + numberOfScannedFiles + ". Below is the latest scanned image. \n" +
                        "All the files that have been scanned are saved to local My Pictures folder.", NotifyType.StatusMessage);
                        Utils.UpdateFileListData(fileStorageList, ModelDataContext);
                    }
                ));
            }
        }
 private async void TaskComplete(IAsyncOperationWithProgress<TrainingResult, TrainingProgress> asyncinfo, AsyncStatus asyncstatus)
 {
     if (Dispatcher != null)
         await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
          {
              ProgressRing.IsActive = false;
              TrainButton.Visibility = Visibility.Visible;
              CancelButton.Visibility = Visibility.Collapsed;
              _training = false;
          });
 }