Exemplo n.º 1
0
        public static IAsyncOperation <T> AsAsyncOperation <T, TProgress>(this IAsyncOperationWithProgress <T, TProgress> operation, IProgress <TProgress> progress)
        {
            if (operation == null)
            {
                throw new ArgumentNullException(nameof(operation));
            }
            if (operation.Status != AsyncStatus.Started)
            {
                try
                {
                    if (operation.Status == AsyncStatus.Canceled)
                    {
                        return(AsyncOperation <T> .CreateCanceled());
                    }
                    else if (operation.Status == AsyncStatus.Error)
                    {
                        return(AsyncOperation <T> .CreateFault(operation.ErrorCode));
                    }
                    else
                    {
                        return(AsyncOperation <T> .CreateCompleted(operation.GetResults()));
                    }
                }
                catch (Exception ex)
                {
                    return(AsyncOperation <T> .CreateFault(ex));
                }
            }
            var op = new AsyncOperation <T>();

            op.RegisterCancellation(operation.Cancel);
            if (progress != null)
            {
                operation.Progress = (s, p) => progress.Report(p);
            }
            operation.Completed = (s, e) =>
            {
                try
                {
                    if (operation.Status == AsyncStatus.Canceled)
                    {
                        op.TrySetCanceled();
                    }
                    else if (operation.Status == AsyncStatus.Error)
                    {
                        op.TrySetException(operation.ErrorCode);
                    }
                    else
                    {
                        op.TrySetResults(operation.GetResults());
                    }
                }
                catch (Exception ex)
                {
                    op.TrySetException(ex);
                }
            };
            return(op);
        }
        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());
            }
        }
Exemplo n.º 3
0
        public static Task <TResult> AsTask <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source, CancellationToken cancellationToken, IProgress <TProgress> progress)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            // TODO: Handle the scenario where the 'IAsyncOperationWithProgress' is actually a task (i.e. originated from native code
            // but projected into an IAsyncOperationWithProgress)

            switch (source.Status)
            {
            case AsyncStatus.Completed:
                return(Task.FromResult(source.GetResults()));

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

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

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

            var bridge = new AsyncInfoToTaskBridge <TResult, TProgress>(cancellationToken);

            source.Completed = new AsyncOperationWithProgressCompletedHandler <TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress);
            bridge.RegisterForCancellation(source);
            return(bridge.Task);
        }
Exemplo n.º 4
0
        /// <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("Escaneo en progreso...", NotifyType.StatusMessage);
                    Utils.UpdateFileListData(fileStorageList, model);

                    ScanerListView.SelectedItem = model.FileList.Last();
                }
                                                          ));
            }
        }
        /// <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);
                }
                                                          ));
            }
        }
        /// <summary>
        /// Submits the http delete request to the specified uri.
        /// </summary>
        /// <param name="uri">The uri to which the delete request will be issued.</param>
        /// <param name="allowRetry">Allow the Post to be retried after issuing a Get call. Currently used for CSRF failures.</param>
        /// <returns>Task tracking HTTP completion</returns>
#pragma warning disable 1998
        private async Task <Stream> Delete(Uri uri, bool allowRetry = true)
        {
            IBuffer dataBuffer = null;

            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.Delete);

                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.DeleteAsync(uri);
                TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter();
                while (!responseAwaiter.IsCompleted)
                {
                }

                using (HttpResponseMessage response = responseOperation.GetResults())
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        // If this isn't a retry and it failed due to a bad CSRF
                        // token, issue a GET to refresh the token and then retry.
                        if (allowRetry && this.IsBadCsrfToken(response))
                        {
                            await this.RefreshCsrfToken();

                            return(await this.Delete(uri, false));
                        }

                        throw new DevicePortalException(response);
                    }

                    this.RetrieveCsrfToken(response);

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

                            dataBuffer = bufferOperation.GetResults();
                        }
                    }
                }
            }

            return((dataBuffer != null) ? dataBuffer.AsStream() : null);
        }
        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());
            }
        }
Exemplo n.º 8
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 || readBytes[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;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Submits the http post request to the specified uri.
        /// </summary>
        /// <param name="uri">The uri to which the post request will be issued.</param>
        /// <param name="requestStream">Optional stream containing data for the request body.</param>
        /// <param name="requestStreamContentType">The type of that request body data.</param>
        /// <returns>Task tracking the completion of the POST request</returns>
#pragma warning disable 1998
        private async Task <Stream> PostAsync(
            Uri uri,
            Stream requestStream            = null,
            string requestStreamContentType = null)
        {
            HttpStreamContent requestContent = null;
            IBuffer           dataBuffer     = null;

            if (requestStream != null)
            {
                requestContent = new HttpStreamContent(requestStream.AsInputStream());
                requestContent.Headers.Remove(ContentTypeHeaderName);
                requestContent.Headers.TryAppendWithoutValidation(ContentTypeHeaderName, requestStreamContentType);
            }

            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.Post);

                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.PostAsync(uri, requestContent);
                TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter();
                while (!responseAwaiter.IsCompleted)
                {
                }

                using (HttpResponseMessage response = responseOperation.GetResults())
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new DevicePortalException(response);
                    }

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

                            dataBuffer = bufferOperation.GetResults();
                        }
                    }
                }
            }

            return((dataBuffer != null) ? dataBuffer.AsStream() : null);
        }
Exemplo n.º 10
0
        private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress <IBuffer, uint> completedOperation, out long bytesCompleted)
        {
            IBuffer resultBuffer = completedOperation.GetResults();

            Debug.Assert(resultBuffer != null);

            WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer);
            bytesCompleted = _userBuffer.Length;
        }
Exemplo n.º 11
0
        public static IAsyncOperation <T> Wrap <T, TProgress>(IAsyncOperationWithProgress <T, TProgress> operation, int millisecondsCycle)
        {
            if (operation == null)
            {
                throw new ArgumentNullException(nameof(operation));
            }
            if (millisecondsCycle < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(millisecondsCycle));
            }
            switch (operation.Status)
            {
            case AsyncStatus.Canceled:
                return(AsyncOperation <T> .CreateCanceled());

            case AsyncStatus.Completed:
                return(AsyncOperation <T> .CreateCompleted(operation.GetResults()));

            case AsyncStatus.Error:
                return(AsyncOperation <T> .CreateFault(operation.ErrorCode));
            }
            return(AsyncInfo.Run(async token =>
            {
                token.Register(operation.Cancel);
                while (operation.Status == AsyncStatus.Started)
                {
                    await Task.Delay(millisecondsCycle);
                    token.ThrowIfCancellationRequested();
                }
                switch (operation.Status)
                {
                case AsyncStatus.Error:
                    rethrow(operation);
                    return default;

                case AsyncStatus.Completed:
                    return operation.GetResults();

                default:
                    cancel(token);
                    return default;
                }
            }));
        }
Exemplo n.º 12
0
 private void ReceiveMessageCompleted(IAsyncOperationWithProgress <IBuffer, uint> info, AsyncStatus status)
 {
     if (status == AsyncStatus.Completed)
     {
         Handle(ReceiveAction.Received, info.GetResults());
     }
     else
     {
         Handle(ReceiveAction.ReceiveFailed);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Submits the http put request to the specified uri.
        /// </summary>
        /// <param name="uri">The uri to which the put request will be issued.</param>
        /// <param name="body">The HTTP content comprising the body of the request.</param>
        /// <returns>Task tracking the PUT completion.</returns>
#pragma warning disable 1998
        private async Task <Stream> PutAsync(
            Uri uri,
            IHttpContent body = null)
        {
            IBuffer dataBuffer = null;

            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.Put);

                // Send the request
                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.PutAsync(uri, null);
                TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter();
                while (!responseAwaiter.IsCompleted)
                {
                }

                using (HttpResponseMessage response = responseOperation.GetResults())
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new DevicePortalException(response);
                    }

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

                            dataBuffer = bufferOperation.GetResults();
                        }
                    }
                }
            }

            return((dataBuffer != null) ? dataBuffer.AsStream() : null);
        }
Exemplo n.º 14
0
        public static async Task <TResult> AsAsync <TResult, TProgress>(IAsyncOperationWithProgress <TResult, TProgress> op)
        {
            TResult result = default;

            using (var AsyncMeSemaphore = new SemaphoreSlim(0, 1))
            {
                op.Completed += (o, s) => AsyncMeSemaphore.Release();
                await AsyncMeSemaphore.WaitAsync();

                result = op.GetResults();
            }

            return(result);
        }
Exemplo n.º 15
0
        private TR RunAsyncTask <TR, TP>(IAsyncOperationWithProgress <TR, TP> task)
        {
            AutoResetEvent e = new AutoResetEvent(false);

            task.Completed += (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus != AsyncStatus.Completed)
                {
                    throw new InvalidOperationException("Async operation error: " + asyncStatus);
                }
                e.Set();
            };
            e.WaitOne();
            return(task.GetResults());
        }
        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());
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Gets the root certificate from the device.
        /// </summary>
        /// <param name="acceptUntrustedCerts">Whether or not we should accept untrusted certificates.</param>
        /// <returns>The device certificate.</returns>
#pragma warning disable 1998
        public async Task <Certificate> GetRootDeviceCertificate(bool acceptUntrustedCerts = false)
        {
            Certificate certificate = null;

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

            HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter();

            requestSettings.AllowUI = false;

            if (acceptUntrustedCerts)
            {
                requestSettings.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            }

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

                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri);
                TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter();
                while (!responseAwaiter.IsCompleted)
                {
                }

                using (HttpResponseMessage response = responseOperation.GetResults())
                {
                    this.RetrieveCsrfToken(response);

                    using (IHttpContent messageContent = response.Content)
                    {
                        IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync();
                        TaskAwaiter <IBuffer> readBufferAwaiter = bufferOperation.GetAwaiter();
                        while (!readBufferAwaiter.IsCompleted)
                        {
                        }

                        certificate = new Certificate(bufferOperation.GetResults());
                    }
                }
            }

            return(certificate);
        }
Exemplo n.º 18
0
        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);
        }
Exemplo n.º 19
0
 public void MessageReceived(IAsyncOperationWithProgress <IBuffer, uint> asyncInfo, AsyncStatus status)
 {
     byte[] bytes = WindowsRuntimeBufferExtensions.ToArray(asyncInfo.GetResults());
     for (int i = 0; i < bytes.Length; i++)
     {
         currentReceivedMessage[currentlength++] = bytes[i];
     }
     if (currentlength == currentReceivedMessage.Length)
     {
         messageQueue.Enqueue(currentReceivedMessage);
         currentlength          = 0;
         currentReceivedMessage = null;
         ListenForMessageHeader();
     }
     else
     {
         ListenForMessage();
     }
 }
Exemplo n.º 20
0
        public void MessageHeaderReceived(IAsyncOperationWithProgress <IBuffer, uint> asyncInfo, AsyncStatus status)
        {
            byte[] bytes = WindowsRuntimeBufferExtensions.ToArray(asyncInfo.GetResults());
            if (bytes.Length < 8)
            {
                ListenForMessageHeader();
                return;
            }
            ulong length = System.BitConverter.ToUInt64(bytes, 0);

            if (length == 0)
            {
                ListenForMessageHeader();
                return;
            }
            currentReceivedMessage = new byte[length];
            currentlength          = 0;
            ListenForMessage();
        }
Exemplo n.º 21
0
        private async void OnCompleted(IAsyncOperationWithProgress <TranscodeFailureReason, double> info, AsyncStatus status)
        {
            Analytics.TrackEvent("VideoEditor_ExportFinished");
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    var results = info.GetResults();

                    if (status == AsyncStatus.Canceled)
                    {
                        return;
                    }

                    if (results != TranscodeFailureReason.None || status != AsyncStatus.Completed)
                    {
                        progressText.Visibility  = Visibility.Collapsed;
                        completedText.Text       = "\xE711";
                        completedText.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        progressText.Visibility  = Visibility.Collapsed;
                        completedText.Text       = "\xE8FB";
                        completedText.Visibility = Visibility.Visible;
                        _succeeded = true;
                    }
                }
                catch
                {
                    progressText.Visibility  = Visibility.Collapsed;
                    completedText.Text       = "\xE711";
                    completedText.Visibility = Visibility.Visible;
                }
                finally
                {
                    CloseProcessingOverlay.Begin();
                }
            });

            _renderTask = null;
        }
Exemplo n.º 22
0
        private static void RemovePackage(Package package)
        {
            IAsyncOperationWithProgress<DeploymentResult, DeploymentProgress> deploymentOperation =
                packageManager.RemovePackageAsync(package.Id.FullName);

            ManualResetEvent opCompletedEvent = new ManualResetEvent(false);

            deploymentOperation.Completed = (result, progress) => {
                logger.Log("Removal operation {1}: {0}", package.Id.Name, result.Status);
                if (result.Status == AsyncStatus.Error)
                {
                    DeploymentResult deploymentResult = deploymentOperation.GetResults();
                    logger.Log("Error code: {0}", deploymentOperation.ErrorCode);
                    logger.Log("Error text: {0}", deploymentResult.ErrorText);
                }
                opCompletedEvent.Set();
            };

            opCompletedEvent.WaitOne();
        }
Exemplo n.º 23
0
        private async Task <DeploymentResult> DeploymentProgressWrapper(IAsyncOperationWithProgress <DeploymentResult, DeploymentProgress> t, LaunchStatus status)
        {
            TaskCompletionSource <int> src = new TaskCompletionSource <int>();

            t.Progress += (v, p) =>
            {
                if (LaunchInfo.Status != status)
                {
                    LaunchInfo.Status = status;
                }
                LaunchInfo.LaunchCurrent = p.percentage;
                Trace.WriteLine("Deployment progress: " + p.state + " " + p.percentage + "%");
            };
            t.Completed += (v, p) =>
            {
                Trace.WriteLine("Deployment done: " + p);
                src.SetResult(1);
            };
            await src.Task;

            return(t.GetResults());
        }
Exemplo n.º 24
0
        private void DeleteAppsCmd_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            StackPanelBtns.IsEnabled = false;
            for (int index = _appsModelList.Count - 1; index >= 0; index--)
            {
                AppsModel t = _appsModelList[index];
                if (!t.Checked)
                {
                    continue;
                }
                IAsyncOperationWithProgress <DeploymentResult, DeploymentProgress> depOpe =
                    PacManager.RemovePackageAsync(t.ScriptName);
                ManualResetEvent opCompletedEvent = new ManualResetEvent(false);
                depOpe.Completed = (depProgress, status) => { opCompletedEvent.Set(); };
                opCompletedEvent.WaitOne();
                switch (depOpe.Status)
                {
                case AsyncStatus.Error:
                    MessageBox.Show($"Error code: {depOpe.ErrorCode}\n" +
                                    $"Error text: {depOpe.GetResults().ErrorText}");
                    break;

                case AsyncStatus.Canceled:
                    MessageBox.Show(@"Removal canceled");
                    break;

                case AsyncStatus.Completed:
                case AsyncStatus.Started:
                    _appsModelList.Remove(t);
                    break;

                default:
                    MessageBox.Show($"{t.Name} removal failed");
                    break;
                }
            }

            StackPanelBtns.IsEnabled = true;
        }
Exemplo n.º 25
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);
            });
        }
Exemplo n.º 26
0
        private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress <uint, uint> completedOperation, out long bytesCompleted)
        {
            uint bytesWritten = completedOperation.GetResults();

            bytesCompleted = bytesWritten;
        }
Exemplo n.º 27
0
        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;
        }
Exemplo n.º 28
0
 private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<UInt32, UInt32> completedOperation, out Int64 bytesCompleted)
 {
     UInt32 bytesWritten = completedOperation.GetResults();
     bytesCompleted = bytesWritten;
 }
Exemplo n.º 29
0
        /// <summary>
        /// Gets the root certificate from the device.
        /// </summary>
        /// <returns>The device certificate.</returns>
#pragma warning disable 1998
        private async Task <Certificate> GetDeviceCertificate()
        {
            Certificate certificate = null;
            bool        useHttps    = true;

            // try https then http
            while (true)
            {
                Uri uri = null;

                if (useHttps)
                {
                    uri = Utilities.BuildEndpoint(this.deviceConnection.Connection, RootCertificateEndpoint);
                }
                else
                {
                    Uri baseUri = new Uri(string.Format("http://{0}", this.deviceConnection.Connection.Authority));
                    uri = Utilities.BuildEndpoint(baseUri, RootCertificateEndpoint);
                }

                try
                {
                    HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter();
                    requestSettings.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    requestSettings.AllowUI = false;

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

                        IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri);
                        TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter();
                        while (!responseAwaiter.IsCompleted)
                        {
                        }

                        using (HttpResponseMessage response = responseOperation.GetResults())
                        {
                            this.RetrieveCsrfToken(response);

                            using (IHttpContent messageContent = response.Content)
                            {
                                IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync();
                                TaskAwaiter <IBuffer> readBufferAwaiter = bufferOperation.GetAwaiter();
                                while (!readBufferAwaiter.IsCompleted)
                                {
                                }

                                certificate = new Certificate(bufferOperation.GetResults());
                                if (!certificate.Issuer.Contains(DevicePortalCertificateIssuer))
                                {
                                    certificate = null;
                                    throw new DevicePortalException(
                                              (HttpStatusCode)0,
                                              "Invalid certificate issuer",
                                              uri,
                                              "Failed to get the device certificate");
                                }
                            }
                        }
                    }

                    return(certificate);
                }
                catch (Exception e)
                {
                    if (useHttps)
                    {
                        useHttps = false;
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }
Exemplo n.º 30
0
        private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress <UInt32, UInt32> completedOperation, out Int64 bytesCompleted)
        {
            UInt32 bytesWritten = completedOperation.GetResults();

            bytesCompleted = bytesWritten;
        }
Exemplo n.º 31
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);
        }
Exemplo n.º 32
0
        /// <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.
            }
        }
Exemplo n.º 33
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());
            }
        }
Exemplo n.º 34
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());
            }
        }
Exemplo n.º 35
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());
            }
        }
Exemplo n.º 36
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);
            });
        }
Exemplo n.º 37
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;
            }
        }
        /// <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);
                    }
                ));
            }
        }