示例#1
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(4000);
                _socket.OutputStream.WriteAsync(sendBuffer).AsTask().Wait(4000);
            }
            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(4000);
                    }
                    catch
                    {
                        // if (_socketWriter.Status == AsyncStatus.Started)
                        // {
                        // ConnectionError(ErrorType.WriteStateMismatch, ErrorPolicyType.Reconnect);
                        // return;
                        // }
                    }
                }

                _elevateMutex.WaitOne(4000);

                if (IsConnected)
                {
                    _socketWriter           = _socket.OutputStream.WriteAsync(sendBuffer);
                    _socketWriter.Completed = OnSocketWriterCompleted;
                }
            }
        }
示例#2
0
        //Download input stream async with timeout
        internal async static Task <IInputStream> DownloadInputStreamAsync(Int32 TimeOut, string UserAgent, Uri DownloadUrl)
        {
            try
            {
                using (HttpBaseProtocolFilter ProtocolFilter = new HttpBaseProtocolFilter())
                {
                    ProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
                    using (HttpClient httpClient = new HttpClient(ProtocolFilter))
                    {
                        httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent);
                        httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store");

                        using (CancellationTokenSource CancelToken = new CancellationTokenSource())
                        {
                            CancelToken.CancelAfter(TimeOut);
                            IAsyncOperationWithProgress <IInputStream, HttpProgress> HttpConnectAsync = httpClient.GetInputStreamAsync(DownloadUrl);
                            IInputStream ConnectTask = await HttpConnectAsync.AsTask(CancelToken.Token);

                            Debug.WriteLine("DownloadInputStreamAsync succeeded for url: " + DownloadUrl);
                            return(ConnectTask);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("DownloadInputStreamAsync exception for url: " + DownloadUrl + " / " + ex.Message);
                return(null);
            }
        }
        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);
        }
示例#4
0
        private async Task <Uri> HandleDownload(DownloadOperation download, bool alreadyStarted)
        {
            var bindableDownload = new BindableDownloadOperation(download);

            try {
                ActiveDownloads.Add(bindableDownload);
                var callback = new Progress <DownloadOperation>(OnDownloadStatusUpdate);
                IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> op = null;
                if (alreadyStarted)
                {
                    var d = download.AttachAsync();
                    op = download.AttachAsync();
                }
                else
                {
                    op = download.StartAsync();
                }
                op.Progress = (a, p) => {
                    OnBindableStatusUpdate(bindableDownload);
                };
                // awaits completion of download
                DownloadOperation completedDownload = await op.AsTask(Cts.Token, callback);

                return(FileUtils.UriFor(completedDownload.ResultFile));
            } finally {
                // download complete
                ActiveDownloads.Remove(bindableDownload);
            }
        }
        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;
        }
示例#6
0
        //Send head request with timeout
        internal async static Task <HttpResponseMessage> SendHeadRequestAsync(Int32 TimeOut, string UserAgent, Uri RequestUrl)
        {
            try
            {
                using (HttpBaseProtocolFilter ProtocolFilter = new HttpBaseProtocolFilter())
                {
                    ProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
                    using (HttpClient httpClient = new HttpClient(ProtocolFilter))
                    {
                        httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent);
                        httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store");

                        using (CancellationTokenSource CancelToken = new CancellationTokenSource())
                        {
                            CancelToken.CancelAfter(TimeOut);

                            HttpRequestMessage RequestMsg = new HttpRequestMessage(HttpMethod.Head, RequestUrl);
                            IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> HttpConnectAsync = httpClient.SendRequestAsync(RequestMsg);
                            HttpResponseMessage ConnectTask = await HttpConnectAsync.AsTask(CancelToken.Token);

                            Debug.WriteLine("SendHeadRequestAsync succeeded for url: " + RequestUrl);
                            return(ConnectTask);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("SendHeadRequestAsync exception for url: " + RequestUrl + " HRESULT 0x" + e.HResult.ToString("x"));
                return(null);
            }
        }
        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();
            }
        }
示例#8
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();
            }
        }
        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);
        }
        async void StartDownload(string filePath, string directory)
        {
            try
            {
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(directory).AsTask(_cancelSource.Token);

                var         fileName   = Path.GetFileName(filePath);
                StorageFile resultFile = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting).AsTask(_cancelSource.Token);

                var downloader = new BackgroundDownloader();
                downloader.TransferGroup = s_BackgroundDownloadGroup;
                if (config.requestHeaders != null)
                {
                    foreach (var header in config.requestHeaders)
                    {
                        if (header.Value != null)
                        {
                            foreach (var value in header.Value)
                            {
                                downloader.SetRequestHeader(header.Key, value);
                            }
                        }
                    }
                }
                switch (config.policy)
                {
                case BackgroundDownloadPolicy.AlwaysAllow:
                    downloader.CostPolicy = BackgroundTransferCostPolicy.Always;
                    break;

                case BackgroundDownloadPolicy.AllowMetered:
                case BackgroundDownloadPolicy.Default:
                    downloader.CostPolicy = BackgroundTransferCostPolicy.Default;
                    break;

                case BackgroundDownloadPolicy.UnrestrictedOnly:
                    downloader.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
                    break;
                }
                _download          = downloader.CreateDownload(config.url, resultFile);
                _downloadOperation = _download.StartAsync();
                var downloadTask = _downloadOperation.AsTask();
                downloadTask.ContinueWith(DownloadTaskFinished, _cancelSource.Token);
            }
            catch (OperationCanceledException)
            {
                _error  = "Download aborted";
                _status = BackgroundDownloadStatus.Failed;
            }
            catch (Exception e)
            {
                _error  = "Download: " + e.Message;
                _status = BackgroundDownloadStatus.Failed;
            }
        }
        private async void GetEasyUpdates()
        {
            StoreContext updateManager = StoreContext.GetDefault();
            IReadOnlyList <StorePackageUpdate> updates = await updateManager.GetAppAndOptionalStorePackageUpdatesAsync();

            if (updates.Count > 0)
            {
                IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> downloadOperation =
                    updateManager.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);
                StorePackageUpdateResult result = await downloadOperation.AsTask();
            }
        }
示例#12
0
 public static async Task <IBuffer> DownloadDataAsync([NotNull] String url, CancellationToken token)
 {
     try
     {
         using (HttpClient client = new HttpClient())
         {
             IAsyncOperationWithProgress <IBuffer, HttpProgress> asyncOperation = client.GetBufferAsync(new Uri(url, UriKind.Absolute));
             return(await asyncOperation.AsTask(token).ContinueWith(t => t.GetAwaiter().GetResult(), token));
         }
     }
     catch
     {
         // Either operation canceled or network error
         return(null);
     }
 }
        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);
        }
        // Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense.
        // Should move this code into the Reading regios once using Dev11 VS becomes the norm.

        private async Task <Int32> ReadAsyncInternal(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
        {
            Debug.Assert(buffer != null);
            Debug.Assert(offset >= 0);
            Debug.Assert(count >= 0);
            Debug.Assert(buffer.Length - offset >= count);
            Debug.Assert(_canRead);

            IInputStream wrtStr = EnsureNotDisposed <IInputStream>();

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

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

                IBuffer resultBuffer = await asyncReadOperation.AsTask(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

                // If cancellationToken was cancelled until now, then we are currently propagating the corresponding cancellation exception.
                // (It will be correctly rethrown by the catch block below and overall we will return a cancelled task.)
                // But if the underlying operation managed to complete before it was cancelled, we want
                // the entire task to complete as well. This is ok as the continuation is very lightweight:

                if (resultBuffer == null)
                {
                    return(0);
                }

                WinRtIOHelper.EnsureResultsInUserBuffer(userBuffer, resultBuffer);

                Debug.Assert(resultBuffer.Length <= unchecked ((UInt32)Int32.MaxValue));
                return((Int32)resultBuffer.Length);
            }
            catch (Exception ex)
            {
                // If the interop layer gave us an Exception, we assume that it hit a general/unknown case and wrap it into
                // an IOException as this is what Stream users expect.
                WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
                return(0);
            }
        }
        public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
        {
            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_InsufficientArrayElementsAfterOffset);
            }

            Contract.EndContractBlock();

            IOutputStream wrtStr = EnsureNotDisposed <IOutputStream>();

            EnsureCanWrite();

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

            // If already cancelled, bail early:
            cancellationToken.ThrowIfCancellationRequested();

            IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);

            IAsyncOperationWithProgress <UInt32, UInt32> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer);
            Task asyncWriteTask = asyncWriteOperation.AsTask(cancellationToken);

            // The underlying IBuffer is the only object to which we expose a direct pointer to native,
            // and that is properly pinned using a mechanism similar to Overlapped.

            return(asyncWriteTask);
        }
示例#16
0
        private async Task InternalStartDmAppStoreUpdateAsync(string jsonParamString)
        {
            Logger.Log("InternalStartDmAppStoreUpdateAsync() invoked.", LoggingLevel.Verbose);

            await Helpers.EnsureErrorsLogged(_deviceManagementClient, PropertySectionName, async() =>
            {
                // Report to the device twin
                StatusSection status = new StatusSection(StatusSection.StateType.Pending);
                await _deviceManagementClient.ReportStatusAsync(PropertySectionName, status);

                StoreContext context = StoreContext.GetDefault();

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

                await ReportResponse(DmAppStoreUpdateDataContract.JSonChecking, lastCheck);

                IReadOnlyList <StorePackageUpdate> updates = await context.GetAppAndOptionalStorePackageUpdatesAsync();
                if (updates.Count == 0)
                {
                    await ReportResponse(DmAppStoreUpdateDataContract.JSonNoUpdates, lastCheck);
                    return;
                }

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

                await ReportResponse(DmAppStoreUpdateDataContract.JsonDownloadingAndInstalling, lastCheck);

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

                string resultString = result.OverallState == StorePackageUpdateState.Completed ?
                                      DmAppStoreUpdateDataContract.JsonInstalled :
                                      DmAppStoreUpdateDataContract.JsonFailed;

                await ReportResponse(resultString, lastCheck);

                // Report to the device twin
                status.State = StatusSection.StateType.Completed;
                await _deviceManagementClient.ReportStatusAsync(PropertySectionName, status);
            });
        }
示例#17
0
        public static async Task <bool> DownloadUpdatesAsync(IEnumerable <StorePackageUpdate> updates)
        {
            App.LogService.Write("Downloading app updates...");

            bool         success = false;
            StoreContext context = GetStoreContext();

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

            downloadOperation.Progress = (asyncInfo, progress) =>
            {
                LogProgress(progress);
                OnUpdateDownloadProgress?.Invoke(null, new StorePackageUpdateStatusEventArgs()
                {
                    Status = progress
                });
            };

            StorePackageUpdateResult result = await downloadOperation.AsTask();

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

            case StorePackageUpdateState.Canceled:
            case StorePackageUpdateState.Deploying:
            case StorePackageUpdateState.Downloading:
            case StorePackageUpdateState.Pending:
                break;

            default:
                OnUpdateOperationError?.Invoke(null, new StorePackageUpdateStateEventArgs()
                {
                    State = result.OverallState
                });
                break;
            }

            OnUpdatesRefresh?.Invoke(null, new UpdateRefreshEventArgs(UpdateStage.Download, success));
            return(success);
        }
示例#18
0
        public static async Task InstallUpdatesAsync(IEnumerable <StorePackageUpdate> updates)
        {
            App.LogService.Write("Installing updates...");

            IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> installOperation = null;
            StoreContext context = GetStoreContext();

            installOperation = context.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);

            installOperation.Progress = (asyncInfo, progress) =>
            {
                LogProgress(progress);
                OnUpdateInstallProgress?.Invoke(null, new StorePackageUpdateStatusEventArgs()
                {
                    Status = progress
                });
            };

            StorePackageUpdateResult result = await installOperation.AsTask();

            switch (result.OverallState)
            {
            case StorePackageUpdateState.Completed:
                // Should never hit this state as the install process will terminate the app
                App.LogService.Write("App should have terminated in order to begin app install...");
                break;

            case StorePackageUpdateState.Canceled:
            case StorePackageUpdateState.Deploying:
            case StorePackageUpdateState.Downloading:
            case StorePackageUpdateState.Pending:
                break;

            default:
                OnUpdateOperationError?.Invoke(null, new StorePackageUpdateStateEventArgs()
                {
                    State = result.OverallState
                });
                break;
            }

            OnUpdatesRefresh?.Invoke(null, new UpdateRefreshEventArgs(UpdateStage.Install, false));
        }
示例#19
0
        private async Task CheckForUpdates()
        {
            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(
                    "Download and install updates now? This may cause the application to exit.", "There's an update available!");
                dialog.Commands.Add(new UICommand("Yes"));
                dialog.Commands.Add(new UICommand("No"));
                IUICommand command = await dialog.ShowAsync();

                if (command.Label.Equals("Yes", StringComparison.CurrentCultureIgnoreCase))
                {
                    // 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 Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                    //    () =>
                    //    {
                    //        downloadProgressBar.Value = progress.PackageDownloadProgress;
                    //    });
                    //};

                    StorePackageUpdateResult result = await downloadOperation.AsTask();
                }
            }
        }
示例#20
0
        private async Task <IRandomAccessStream> GetImageStreamAsync(Uri uriSource)
        {
            switch (uriSource.Scheme)
            {
            case "ms-appx":
                var file =
                    await StorageFile.GetFileFromApplicationUriAsync(uriSource).AsTask().ConfigureAwait(false);

                return(await file.OpenReadAsync().AsTask().ConfigureAwait(false));

            case "http":
            case "https":
                var client = new HttpClient();
                IAsyncOperationWithProgress <IBuffer, HttpProgress> getOperation = null;
                try
                {
                    getOperation          = client.GetBufferAsync(uriSource);
                    getOperation.Progress = OnProgress;

                    var buffer = await getOperation.AsTask().ConfigureAwait(false);

                    return(buffer.AsStream().AsRandomAccessStream());
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Failed to get GIF image");
                    Debug.WriteLine(ex);
                    return(null);
                }
                finally
                {
                    client.Dispose();
                    if (getOperation != null)
                    {
                        getOperation.Progress = null;
                    }
                }

            default:
                throw new InvalidOperationException("unsupported uri scheme");
            }
        }
        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            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(global::Windows.Storage.Streams.SR.Argument_InsufficientArrayElementsAfterOffset);
            }

            IOutputStream wrtStr = EnsureNotDisposed <IOutputStream>();

            EnsureCanWrite();

            Debug.Assert(wrtStr != null);

            // If already cancelled, bail early:
            cancellationToken.ThrowIfCancellationRequested();

            IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);

            IAsyncOperationWithProgress <uint, uint> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer);
            Task asyncWriteTask = asyncWriteOperation.AsTask(cancellationToken);

            // The underlying IBuffer is the only object to which we expose a direct pointer to native,
            // and that is properly pinned using a mechanism similar to Overlapped.

            return(asyncWriteTask);
        }
        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();
            }
        }
示例#23
0
        //Send post request with timeout
        internal static async Task <HttpResponseMessage> SendPostRequestAsync(Int32 TimeOut, string UserAgent, string[][] RequestHeader, Uri PostUrl, IHttpContent PostContent)
        {
            try
            {
                using (HttpBaseProtocolFilter ProtocolFilter = new HttpBaseProtocolFilter())
                {
                    ProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
                    using (HttpClient httpClient = new HttpClient(ProtocolFilter))
                    {
                        httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent);
                        httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store");
                        if (RequestHeader != null)
                        {
                            foreach (String[] StringArray in RequestHeader)
                            {
                                httpClient.DefaultRequestHeaders.Add(StringArray[0], StringArray[1]);
                            }
                        }

                        using (CancellationTokenSource CancelToken = new CancellationTokenSource())
                        {
                            CancelToken.CancelAfter(TimeOut);

                            IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> HttpConnectAsync = httpClient.PostAsync(PostUrl, PostContent);
                            HttpResponseMessage ConnectTask = await HttpConnectAsync.AsTask(CancelToken.Token);

                            Debug.WriteLine("SendPostRequestAsync succeeded for url: " + PostUrl);
                            return(ConnectTask);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("SendPostRequestAsync exception for url: " + PostUrl + " HRESULT 0x" + e.HResult.ToString("x"));
                return(null);
            }
        }
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            timeToResponseComplete.Start();
            logView.Log($"{{\"FILTER SendRequestAsync\":{{\"requestUri\":\"{request.RequestUri}\"}}}}", LogViewLoggingLevel.Verbose);

            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, operationProgressReporter) =>
            {
                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> innerOperation = innerFilter.SendRequestAsync(request);

                innerOperation.Progress += new AsyncOperationProgressHandler <HttpResponseMessage, HttpProgress>(
                    (IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> asyncInfo, HttpProgress httpProgressInfo) =>
                {
                    logView.Log($"{{\"FILTER Progress Handler\": {{\"requestUri\":\"{request.RequestUri}\", {httpProgressInfo.ToJsonObject()}}}}}", LogViewLoggingLevel.Verbose);
                });

                HttpResponseMessage response = await innerOperation.AsTask(cancellationToken, operationProgressReporter);
                cancellationToken.ThrowIfCancellationRequested();
                // At this point, SendRequest has completed and we have a response.
                timeToResponseComplete.Stop();

                // We could inspect the content of the response headers:
                var countHeaders = response.Headers.Count();
                logView.Log($"{{\"FILTER Response Complete\": {{\"StatusCode\":\"{response.StatusCode}\",\"timeToResponseComplete\":\"{timeToResponseComplete.ElapsedMilliseconds}\",\"requestUri\":\"{request.RequestUri}\",\"countHeaders\":\"{countHeaders}\"}}}}", LogViewLoggingLevel.Verbose);

                if (!response.IsSuccessStatusCode)
                {
                    logView.Log($"{{\"FILTER Response Failed\": {{\"StatusCode\":\"{response.StatusCode}\",\"timeToResponseComplete\":\"{timeToResponseComplete.ElapsedMilliseconds}\",\"requestUri\":\"{request.RequestUri}\",\"countHeaders\":\"{countHeaders}\"}}}}", LogViewLoggingLevel.Error);
                }

                // Note that we should NOT attempt to access the response.Content in an IHttpFilter such as this,
                // the Content stream is for the base filter and AdaptiveMediaSource to use.
                //
                // If you want to download content in the App and then pass it to the AdaptiveMediaSource,
                // see AppDownloadedKeyRequest in Scenario3, which uses Deferral objects to manage thread timing
                // with the AdaptiveMediaSource.
                return response;
            }));
        }
示例#25
0
        private async Task <LiveDownloadOperationResult> ExecuteAsync(bool start, CancellationToken cancellationToken, IProgress <LiveOperationProgress> progressHandler)
        {
            LiveDownloadOperationResult result = null;
            Exception error = null;

            try
            {
                var progressHandlerWrapper = new Progress <DownloadOperation>(t => {
                    if (progressHandler != null)
                    {
                        progressHandler.Report(
                            new LiveOperationProgress(
                                (long)t.Progress.BytesReceived,
                                (long)t.Progress.TotalBytesToReceive));
                    }
                });

                IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> asyncOperation = start ? this.downloadOperation.StartAsync() : this.downloadOperation.AttachAsync();
                await asyncOperation.AsTask(cancellationToken, progressHandlerWrapper);

                result = this.downloadOperation.ResultFile != null ?
                         new LiveDownloadOperationResult(this.downloadOperation.ResultFile) :
                         new LiveDownloadOperationResult(this.downloadOperation.GetResultStreamAt(0));
                return(result);
            }
            catch (TaskCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                error = ex;
            }

            error = await this.ProcessDownloadErrorResponse(error);

            throw error;
        }
示例#26
0
        //Download string async with timeout
        internal static async Task <string> DownloadStringAsync(Int32 TimeOut, string UserAgent, string[][] RequestHeader, Uri DownloadUrl)
        {
            try
            {
                using (HttpBaseProtocolFilter ProtocolFilter = new HttpBaseProtocolFilter())
                {
                    ProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
                    using (HttpClient httpClient = new HttpClient(ProtocolFilter))
                    {
                        httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent);
                        httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store");
                        if (RequestHeader != null)
                        {
                            foreach (String[] StringArray in RequestHeader)
                            {
                                httpClient.DefaultRequestHeaders.Add(StringArray[0], StringArray[1]);
                            }
                        }

                        using (CancellationTokenSource CancelToken = new CancellationTokenSource())
                        {
                            CancelToken.CancelAfter(TimeOut);
                            IAsyncOperationWithProgress <string, HttpProgress> HttpConnectAsync = httpClient.GetStringAsync(DownloadUrl);
                            string ConnectTask = await HttpConnectAsync.AsTask(CancelToken.Token);

                            Debug.WriteLine("DownloadStringAsync succeeded for url: " + DownloadUrl + " / " + ConnectTask.Length + "bytes");
                            return(ConnectTask);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("DownloadStringAsync exception for url: " + DownloadUrl + " / " + ex.Message);
                return(String.Empty);
            }
        }
        private async Task HandleDownloadAsync()
        {
            try
            {
                startDownloadButton.IsEnabled = false;
                IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> downloadOperation = download.StartAsync();
                downloadOperation.Progress += OnDownloadProgress;
                await downloadOperation.AsTask(downloadCancellationTokenSource.Token);

                rootPage.NotifyUser("Download completed successfully", NotifyType.StatusMessage);
            }
            catch (Exception ex) when(IsWebException("Execution error", ex))
            {
            }
            catch (TaskCanceledException)
            {
                // Download was canceled.
            }
            finally
            {
                download = null;
                startDownloadButton.IsEnabled = true;
            }
        }
        public void progresschange(IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> a, AsyncStatus b)
        {
            var task = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                switch (b)
                {
                default:
                case AsyncStatus.Started:
                case AsyncStatus.Canceled:
                case AsyncStatus.Completed:
                    break;

                case AsyncStatus.Error:
                    new Controls.MyToast(dic2[a.Id].ResultFile.Name + "下载失败").Show();
                    break;
                }
                try
                {
                    tasks.Remove(dic[a.AsTask().Result.Guid]);
                }
                catch (OperationCanceledException)
                {
                }
                catch
                {
                    try
                    {
                        tasks.Remove(dic[dic2[a.Id].Guid]);
                    }
                    catch
                    {
                        new Controls.MyToast("出现未知错误" + a.Id).Show();
                    }
                }
            });
        }
示例#29
0
        private async Task <LiveOperationResult> ExecuteAsync(bool start, CancellationToken cancellationToken, IProgress <LiveOperationProgress> progressHandler)
        {
            LiveOperationResult opResult;
            Exception           error = null;

            try
            {
                var progressHandlerWrapper = new Progress <UploadOperation>(t =>
                {
                    if (progressHandler != null)
                    {
                        progressHandler.Report(
                            new LiveOperationProgress(
                                (long)t.Progress.BytesSent,       //uploading, not downloading
                                (long)t.Progress.TotalBytesToSend //uploading, not downloading
                                ));
                    }
                });

                IAsyncOperationWithProgress <UploadOperation, UploadOperation> asyncOperation = start ? this.uploadOperation.StartAsync() : this.uploadOperation.AttachAsync();
                await asyncOperation.AsTask(cancellationToken, progressHandlerWrapper);
            }
            catch (TaskCanceledException)
            {
                throw;
            }
            catch (Exception exp)
            {
                // This might be an server error. We will read the response to determine the error message.
                error = exp;
            }

            IInputStream responseStream = this.uploadOperation.GetResultStreamAt(0);

            if (responseStream == null)
            {
                throw new LiveConnectException(
                          ApiOperation.ApiClientErrorCode,
                          ResourceHelper.GetString("ConnectionError"));
            }
            else
            {
                var  reader = new DataReader(responseStream);
                uint length = await reader.LoadAsync(MaxUploadResponseLength);

                opResult = ApiOperation.CreateOperationResultFrom(reader.ReadString(length), ApiMethod.Upload);

                if (opResult.Error != null)
                {
                    if (opResult.Error is LiveConnectException)
                    {
                        throw opResult.Error;
                    }
                    else if (error != null)
                    {
                        // If the error did not come from the api service,
                        // we'll just return the error thrown by the uploader.
                        throw error;
                    }
                }

                return(opResult);
            }
        }
示例#30
0
        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;
            }
        }