예제 #1
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try {
                //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage);

                // Store the download so we can pause/resume.
                activeDownloads.Add(download);

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                //LogStatus(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
                //    download.Guid, response.StatusCode), NotifyType.StatusMessage);
            } catch (TaskCanceledException) {
                //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
            } catch (Exception ex) {
                if (!IsExceptionHandled("Execution error", ex, download))
                {
                    throw;
                }
            } finally {
                activeDownloads.Remove(download);
            }
        }
예제 #2
0
        async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            cts = new CancellationTokenSource();
            try
            {
                LogStatus("Running: " + upload.Guid);

                Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
                if (start)
                {
                    // Start the upload and attach a progress handler.
                    await upload.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The upload was already running when the application started, re-attach the progress handler.
                    await upload.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = upload.GetResponseInformation();

                LogStatus(string.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));
            }
            catch (TaskCanceledException)
            {
                MainPage.Current?.HideMediaUploadingUc();
                LogStatus("Canceled: " + upload.Guid);
            }
            catch (Exception)
            {
                MainPage.Current?.HideMediaUploadingUc();
                //throw;
            }
        }
예제 #3
0
        private async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            try
            {
                LogStatus("Running: " + upload.Guid, NotifyType.StatusMessage);

                Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
                if (start)
                {
                    // Start the upload and attach a progress handler.
                    await upload.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The upload was already running when the application started, re-attach the progress handler.
                    await upload.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = upload.GetResponseInformation();

                LogStatus(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", upload.Guid,
                                        response.StatusCode), NotifyType.StatusMessage);
            }
            catch (TaskCanceledException)
            {
                LogStatus("Canceled: " + upload.Guid, NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Error", ex, upload))
                {
                    throw;
                }
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                TransferModel transfer = new TransferModel();
                transfer.DownloadOperation   = download;
                transfer.Source              = download.RequestedUri.ToString();
                transfer.Destination         = download.ResultFile.Path;
                transfer.BytesReceived       = download.Progress.BytesReceived;
                transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
                transfer.Progress            = 0;
                transfer.Title    = download.ResultFile.Name.Replace(".mp4", "");
                transfer.PhanTram = "0 %";
                App.ViewModel.transfers.Add(transfer);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await download.AttachAsync().AsTask(cancelToken.Token, progressCallback);

                ResponseInformation response = download.GetResponseInformation();
                Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
                                              download.Guid, response.StatusCode));
            }
            catch (TaskCanceledException)
            {
                Debug.WriteLine("Canceled: " + download.Guid);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                App.ViewModel.transfers.Remove(App.ViewModel.transfers.First(p => p.DownloadOperation == download));
                activeDownloads.Remove(download);
            }
        }
예제 #5
0
        private async Task HandleDownload(DownloadOperation download, bool start)
        {
            try
            {
                activeDownloads.Add(download);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                string statusCode = response != null?response.StatusCode.ToString() : string.Empty;
            }
            catch (Exception ex)
            {
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
예제 #6
0
        //处理正在下载的任务
        private async Task HandleDownloadAsync(DownloadOperation download, bool v)
        {
            try
            {
                TransferModel transfer = new TransferModel();
                transfer.DownloadOperation   = download;
                transfer.Source              = download.RequestedUri.ToString();
                transfer.Destination         = download.ResultFile.Path;
                transfer.BytesReceived       = download.Progress.BytesReceived;
                transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
                transfer.Progress            = 0;
                transfers.Add(transfer);
                //当下载进度发生变化时的回调函数

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(downloadprogressAsync);
                //监听已存在的后台下载任务
                await download.AttachAsync().AsTask(cancelToken.Token, progressCallback);

                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
                await new MessageDialog("任务取消:").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog("处理下载任务失败:" + ex).ShowAsync();
            }
            finally
            {
                transfers.Remove(transfers.First(p => p.DownloadOperation == download));
                DownloadList.Remove(download);
                NoTask.Visibility = Visibility.Visible;
            }
        }
예제 #7
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the upload and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The upload was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
                XmlDocument toastXML = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
                XmlNodeList texts    = toastXML.GetElementsByTagName("text");
                texts[0].AppendChild(toastXML.CreateTextNode("HAP+ - Download Canceled"));
                texts[1].AppendChild(toastXML.CreateTextNode("The download of " + download.ResultFile.Name + " has been Canceled."));
                ((XmlElement)toastXML.SelectSingleNode("/toast")).SetAttribute("launch", "{\"type\":\"toast\"}");
                ToastNotification toast = new ToastNotification(toastXML);
                ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);

                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
        }
        internal object AddNewSurveyForAUser(ResponseInformation responses)
        {
            foreach (var response in responses.Responses)
            {
                DisableOldQuestionsIfExists(response, responses.CustomerId);
                Response newResponse = new Response
                {
                    IdCustomer = responses.CustomerId,
                    IdQuestion = response.IdQuestion
                };
                if (response.AnswerType == "bool")
                {
                    newResponse.ResponseBool = response.ResponseBool;
                }
                else
                {
                    newResponse.ResponseString = response.ResponseString;
                }
                newResponse.CreatedOn = DateConverter.CurrentEasternDateTime();
                newResponse.IsActive  = true;
                Context.Add(newResponse);
            }

            Context.SaveChanges();
            return(1);
        }
예제 #10
0
        public static ResponseInformation GetUserLanguageInformation()
        {
            var user = User.Instance.GetLoggedUser();
            if (HttpContext.Current.Session == null)
            {
                return new ResponseInformation
                {
                    Language = (int)ELanguage.PtBr
                };

            }
            var lang = HttpContext.Current.Session["Language"];
            var respInfo = new ResponseInformation();

            if (lang != null)
            {
                respInfo.Language = (int)lang;
            }
            else
            {
                respInfo.Language = (int)ELanguage.PtBr;
            }
            if (user != null)
            {
                respInfo.UserId = user.Id;
                respInfo.UserName = user.Name;
            }

            return respInfo;
        }
예제 #11
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
                string statusCode            = response != null?response.StatusCode.ToString() : String.Empty;
            }
            catch (TaskCanceledException)
            {
                //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                /*
                 * if (!IsExceptionHandled("Execution error", ex, download))
                 * {
                 *  throw;
                 * }
                 */
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download)
        {
            try
            {
                // For more advanced Background Transfer features, please take a look at the
                // BackgroundTransfer sample.
                if (download.Progress.Status == BackgroundTransferStatus.Idle)
                {
                    await download.StartAsync();
                }
                else
                {
                    await download.AttachAsync();
                }

                ResponseInformation response = download.GetResponseInformation();

                // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                string statusCode = response != null?response.StatusCode.ToString() : String.Empty;

                rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture,
                                                  "Successfully completed background download: {0}, Status Code: {1}",
                                                  download.Guid,
                                                  statusCode),
                                    NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
        private async static Task <string> GetResponseMessage(UploadOperation uploadOperation)
        {
            ResponseInformation responseInformation = uploadOperation.GetResponseInformation();

            //uint contentLength = Convert.ToUInt32(responseInformation.Headers["Content-Length"]);

            uint contentLength = (uint)uploadOperation.Progress.BytesReceived;

            uint statusCode = responseInformation.StatusCode;

            IInputStream resultStreamAt = uploadOperation.GetResultStreamAt(0);

            IBuffer result = await resultStreamAt.ReadAsync(
                new Windows.Storage.Streams.Buffer(contentLength),
                contentLength,
                InputStreamOptions.None);

            Stream responseStream = result.AsStream();

            XDocument xDocument = XDocument.Load(responseStream);

            foreach (XElement xe in xDocument.Root.Descendants())
            {
                if (xe.Name.LocalName.Equals("Ok"))
                {
                    return("SUCCESS");
                }
                if (xe.Name.LocalName.Equals("Error"))
                {
                    return(xe.Value);
                }
            }
            return("Unspecified error submiting video");
        }
예제 #14
0
        async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            cts = new CancellationTokenSource();
            try
            {
                LogStatus("Running: " + upload.Guid);

                Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
                if (start)
                {
                    await upload.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    await upload.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = upload.GetResponseInformation();

                LogStatus(string.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));
            }
            catch (TaskCanceledException)
            {
                OnFailed?.Invoke(this);
                MainPage.Current?.HideMediaUploadingUc();
                LogStatus("Canceled: " + upload.Guid);
            }
            catch (Exception ex)
            {
                OnFailed?.Invoke(this);
                ex.PrintException("HandleUploadAsync");
                MainPage.Current?.HideMediaUploadingUc();
            }
        }
예제 #15
0
        public void when_building_from_a_write_response_all_target_fields_are_mapped()
        {
            var result = ResponseInformation.FromWriteResponse(new FakeStoredProcedureResponse <dynamic>());

            Assert.That(result.CurrentResourceQuotaUsage, Is.EqualTo(Expected.CurrentResourceQuotaUsage));
            Assert.That(result.MaxResourceQuota, Is.EqualTo(Expected.MaxResourceQuota));
            Assert.That(result.RequestCharge, Is.EqualTo(Expected.RequestCharge));
            Assert.That(result.ResponseHeaders, Is.EqualTo(Expected.ResponseHeaders));
        }
예제 #16
0
        public void when_building_from_a_subscription_read_response_all_target_fields_are_mapped()
        {
            var result = ResponseInformation.FromSubscriptionReadResponse(new FakeFeedResponse <Document>());

            Assert.That(result.CurrentResourceQuotaUsage, Is.EqualTo(Expected.CurrentResourceQuotaUsage));
            Assert.That(result.MaxResourceQuota, Is.EqualTo(Expected.MaxResourceQuota));
            Assert.That(result.RequestCharge, Is.EqualTo(Expected.RequestCharge));
            Assert.That(result.ResponseHeaders, Is.EqualTo(Expected.ResponseHeaders));
        }
예제 #17
0
        public static ResponseInformation GetUserLanguageInformation(int id)
        {
            var user = User.Instance.GetById(id);
            var respInfo = new ResponseInformation
            {
                Language = (int) ELanguage.PtBr,
                UserId = user.Id,
                UserName = user.Name
            };

            return respInfo;
        }
예제 #18
0
        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Console.WriteLine("BarnardTech Web Server is now running at:");
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Cyan;
                foreach (string uri in _listener.Prefixes)
                {
                    Console.WriteLine("        " + uri);
                }
                Console.WriteLine();
                Console.ResetColor();

                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                //string rstr = _responderMethod(ctx.Request);
                                //byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.AddHeader("Content-Type", MIME.GetMimeType(System.IO.Path.GetExtension(ctx.Request.Url.AbsolutePath)));
                                ResponseInformation r = _responderMethod(ctx.Request);
                                byte[] buf            = r.Content;
                                if (r.ContentType != "")
                                {
                                    ctx.Response.AddHeader("Content-Type", r.ContentType);
                                }
                                else
                                {
                                    ctx.Response.AddHeader("Content-Type", MIME.GetMimeType(System.IO.Path.GetExtension(ctx.Request.Url.AbsolutePath)));
                                }

                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                            }
                            catch { } // suppress any exceptions
                            finally
                            {
                                // always close the stream
                                ctx.Response.OutputStream.Close();
                            }
                        }, _listener.GetContext());
                    }
                }
                catch { } // suppress any exceptions
            });
        }
예제 #19
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            DownloadViewModel Selected = Downloads.FirstOrDefault(p => p.Address == download.RequestedUri.ToString());

            try {
                // LogStatus("Running: " + download.Guid, NotifyType.StatusMessage);

                // Store the download so we can pause/resume.
                // activeDownloads.Add(download);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                string statusCode = response != null?response.StatusCode.ToString() : String.Empty;

                // download completed
                Selected.Status            = "decompressing...";
                Selected.IsDownloadVisible = false;

                // Unzip
                var zipFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Selected.FullFileName);

                var unzipFolder = await FileHelper.GetFolderNotNullAsync(
                    ApplicationData.Current.LocalFolder, "cards");

                await ZipHelper.UnZipFileAsync(zipFile, unzipFolder);

                // end
                Selected.Complete();
            } catch (TaskCanceledException) {
                // LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
            } catch (Exception) {
                if (Selected != null)
                {
                    await Selected.Delete();
                }
            } finally {
                // activeDownloads.Remove(download);
            }
        }
예제 #20
0
        public async Task when_a_write_operation_is_successful_the_log_callback_is_called()
        {
            ResponseInformation response = null;
            var sut      = new EventStore(await CreateStorageEngine(t => response = t));
            var streamId = Guid.NewGuid().ToString();

            await sut.AppendToStream(streamId, 0, new EventData(Guid.NewGuid(), new OrderCreated("TEST-ORDER")));

            Assert.NotNull(response);
            TestContext.Out.WriteLine($"Charge: {response.RequestCharge}");
            TestContext.Out.WriteLine($"Quota Usage: {response.CurrentResourceQuotaUsage}");
            TestContext.Out.WriteLine($"Max Resource Quote: {response.MaxResourceQuota}");
            TestContext.Out.WriteLine($"Response headers: {response.ResponseHeaders}");
        }
예제 #21
0
        private async Task <string> HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage);

                // Store the download so we can pause/resume.
                activeDownloads.Add(download);

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                string statusCode = response != null?response.StatusCode.ToString() : String.Empty;

                return(statusCode);
                //LogStatus(
                //    String.Format(
                //        CultureInfo.CurrentCulture,
                //        "Completed: {0}, Status Code: {1}",
                //        download.Guid,
                //        statusCode),
                //    NotifyType.StatusMessage);
            }
            catch (TaskCanceledException et)
            {
                //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
                return(et.Message);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
 /// <summary>
 /// This is the upload handler.
 /// </summary>
 /// <param name="upload"></param>
 /// <param name="start"></param>
 private static async void HandleUploadAsync(UploadOperation upload, bool start)
 {
     try
     {
         Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
         if (start)
         {
             await upload.StartAsync().AsTask(cancellationToken.Token, progressCallback);
         }
         ResponseInformation response = upload.GetResponseInformation();
     }
     catch (Exception ex)
     {
     }
 }
예제 #23
0
        private static async Task StartDownload(Uri target, BackgroundTransferPriority priority, string localFilename)
        {
            var result = await BackgroundExecutionManager.RequestAccessAsync();

            StorageFile destinationFile;

            destinationFile = await GetLocalFileFromName(localFilename);

            var group = BackgroundTransferGroup.CreateGroup(Guid.NewGuid().ToString());

            group.TransferBehavior = BackgroundTransferBehavior.Serialized;

            BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup();

            // this will cause the app to be activated when the download completes and
            // CheckCompletionResult will be called for the final download state
            RegisterBackgroundTask(completionGroup.Trigger);

            BackgroundDownloader downloader = new BackgroundDownloader(completionGroup);

            downloader.TransferGroup = group;
            group.TransferBehavior   = BackgroundTransferBehavior.Serialized;
            CreateNotifications(downloader);
            DownloadOperation download = downloader.CreateDownload(target, destinationFile);

            download.Priority = priority;

            completionGroup.Enable();

            Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
            var downloadTask = download.StartAsync().AsTask(progressCallback);

            string tag = GetFileNameFromUri(target);

            CreateToast(tag, localFilename);

            try
            {
                await downloadTask;

                // Will occur after download completes
                ResponseInformation response = download.GetResponseInformation();
            }
            catch (Exception)
            {
                Debug.WriteLine("Download exception");
            }
        }
예제 #24
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            if (_cts is null)
            {
                _cts = new CancellationTokenSource();
            }

            if (_activeDownloads is null)
            {
                _activeDownloads = new Dictionary <string, DownloadOperation>();
            }

            try
            {
                // Store the download so we can pause/resume.
                _activeDownloads.TryAdd(download.ResultFile.Path, download);

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(_cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(_cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled(ex))
                {
                    throw;
                }
            }
            finally
            {
                _activeDownloads.Remove(download.ResultFile.Path);
                _activeProgress.Remove(download.ResultFile.Path);
            }
        }
예제 #25
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                // Store the download so we can pause/resume.
                activeDownloads.Add(download);

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                string statusCode = response != null?response.StatusCode.ToString() : String.Empty;

                LogHelper.WriteLine(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        "Completed: {0}, Status Code: {1}",
                        download.Guid,
                        statusCode));
            }
            catch (TaskCanceledException)
            {
                LogHelper.WriteLine("Canceled: " + download.Guid);
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Execution error", ex, download))
                {
                    throw;
                }
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
예제 #26
0
        private static void DownloadProgress(DownloadOperation download)
        {
            BackgroundDownloadProgress currentProgress = download.Progress;

            double percent = 100;

            if (currentProgress.TotalBytesToReceive > 0)
            {
                percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
            }

            if (currentProgress.HasResponseChanged)
            {
                ResponseInformation response = download.GetResponseInformation();
                int headersCount             = response != null ? response.Headers.Count : 0;
            }
        }
예제 #27
0
        /// <summary>
        /// 处理并监视指定的后台上传任务
        /// </summary>
        /// <param name="upload">后台上传任务</param>
        /// <param name="isNew">是否是新增的任务</param>
        private async Task HandleUploadAsync(UploadOperation upload, bool isNew)
        {
            try
            {
                // 将 UploadOperation 附加到 TransferModel,以便上传进度可通知
                TransferModel transfer = new TransferModel();
                transfer.UploadOperation = upload;
                transfer.Source          = "多个文件";
                transfer.Destination     = upload.RequestedUri.ToString();
                transfer.Progress        = upload.Progress.Status.ToString() + "0 / 0";

                _transfers.Add(transfer);

                WriteLine("Task Count: " + _transfers.Count.ToString());

                // 当上传进度发生变化时的回调函数
                Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);

                if (isNew)
                {
                    await upload.StartAsync().AsTask(_cancelToken.Token, progressCallback); // 启动一个后台上传任务
                }
                else
                {
                    await upload.AttachAsync().AsTask(_cancelToken.Token, progressCallback); // 监视已存在的后台上传任务
                }
                // 上传完成后获取服务端的响应信息
                ResponseInformation response = upload.GetResponseInformation();
                WriteLine("Completed: " + response.ActualUri + ", HttpStatusCode: " + response.StatusCode.ToString());
            }
            catch (TaskCanceledException) // 调用 CancellationTokenSource.Cancel() 后会抛出此异常
            {
                WriteLine("Canceled: " + upload.Guid);
            }
            catch (Exception ex)
            {
                // 将异常转换为 WebErrorStatus 枚举,如果获取到的是 WebErrorStatus.Unknown 则说明此次异常不是涉及 web 的异常
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

                WriteLine(ex.ToString());
            }
            finally
            {
                _transfers.Remove(_transfers.First(p => p.UploadOperation == upload));
            }
        }
예제 #28
0
        // Note that this event is invoked on a background thread, so we cannot access the UI directly.
        private void DownloadProgress(DownloadOperation download)
        {
            var Selected = Downloads.First(p => p.guid == download.Guid);

            // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
            // we must make a local copy at the beginning of the progress handler, so that we can have a consistent
            // view of that ever-changing state throughout the handler's lifetime.
            BackgroundDownloadProgress currentProgress = download.Progress;

            // MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", download.Guid,
            //     currentProgress.Status));

            double percent = 0;

            if (currentProgress.TotalBytesToReceive > 0)
            {
                percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
            }
            Selected.Progress = percent;

            // MarshalLog(String.Format(
            //     CultureInfo.CurrentCulture,
            //     " - Transfered bytes: {0} of {1}, {2}%",
            //     currentProgress.BytesReceived,
            //     currentProgress.TotalBytesToReceive,
            //     percent));
            Selected.Size = currentProgress.TotalBytesToReceive / 1024 / 1024;

            if (currentProgress.HasRestarted)
            {
                // MarshalLog(" - Download restarted");
            }

            if (currentProgress.HasResponseChanged)
            {
                // We have received new response headers from the server.
                // Be aware that GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                ResponseInformation response = download.GetResponseInformation();
                int headersCount             = response != null ? response.Headers.Count : 0;

                // MarshalLog(" - Response updated; Header count: " + headersCount);

                // If you want to stream the response data this is a good time to start.
                // download.GetResultStreamAt(0);
            }
        }
예제 #29
0
        /// <summary>
        /// Start uplaod and create handler.
        /// </summary>
        /// <param name="upload">UploadOperation handled.</param>
        /// <param name="start">Whether uplaod is started.</param>
        /// <returns>
        /// Represent the asynchronous operation.
        /// </returns>
        private async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            try
            {
                try
                {
                    Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
                    if (start)
                    {
                        // Start the upload and attach a progress handler.
                        await upload.StartAsync().AsTask(cts.Token, progressCallback);
                    }
                    else
                    {
                        // The upload was already running when the application started, re-attach the progress handler.
                        await upload.AttachAsync().AsTask(cts.Token, progressCallback);
                    }
                }
                catch
                {
                    ShowMessageDialog("Error90! Upload canceled.");
                }

                ResponseInformation response = upload.GetResponseInformation();
                foreach (var c in response.Headers)
                {
                    System.Diagnostics.Debug.WriteLine("{0}, {1}. markkkkkkkk", c.Key, c.Value);
                }

                if (images != null && images.Count != 0 && hasImage == false)
                {
                    toBeUploadCourse.ImageUri = response.Headers[images.FirstOrDefault().Name];
                    hasImage = true;
                }
                SaveUploadLessonToListAsync(response);
            }
            catch (TaskCanceledException)
            {
                ShowMessageDialog("Error9! Upload canceled.");
            }
            catch
            {
                ShowMessageDialog("Error10! Upload canceled.");
                //throw;
            }
        }
예제 #30
0
        /// <summary>
        /// Handles the download asynchronous.
        /// </summary>
        /// <param name="download">The download.</param>
        /// <param name="start">if set to <c>true</c> [start].</param>
        /// <returns></returns>
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage);

                // Store the download so we can pause/resume.
                //activeDownloads.Add(download);

                cts = new CancellationTokenSource();

                //Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, null);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, null);
                }
                ShowMessageDialog("Download Complete!");
                ResponseInformation response = download.GetResponseInformation();

                //LogStatus(String.Format("Completed: {0}, Status Code: {1}", download.Guid, response.StatusCode),
                //NotifyType.StatusMessage);
            }
            catch (TaskCanceledException)
            {
                //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
            }
            catch (Exception)
            {
                ShowMessageDialog("Execution error!12");
                //if (!IsExceptionHandled("Execution error", ex, download))
                //{
                // throw;
                //}
            }
            finally
            {
                //activeDownloads.Remove(download);
            }
        }
예제 #31
0
        private bool IsFailed(DownloadOperation download)
        {
            BackgroundTransferStatus status = download.Progress.Status;

            if (status == BackgroundTransferStatus.Error || status == BackgroundTransferStatus.Canceled)
            {
                return(true);
            }

            ResponseInformation response = download.GetResponseInformation();

            if (response == null || response.StatusCode != 200)
            {
                return(true);
            }

            return(false);
        }
예제 #32
0
        private static void DownloadProgress(DownloadOperation download)
        {
            // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
            // we must make a local copy so that we can have a consistent view of that ever-changing state
            // throughout this method's lifetime.
            BackgroundDownloadProgress currentProgress = download.Progress;

            (string.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", download.Guid,
                           currentProgress.Status)).PrintDebug();

            double percent = 100;

            if (currentProgress.TotalBytesToReceive > 0)
            {
                percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
            }

            (string.Format(
                 CultureInfo.CurrentCulture,
                 " - Transferred bytes: {0} of {1}, {2}%",
                 currentProgress.BytesReceived,
                 currentProgress.TotalBytesToReceive,
                 percent)).PrintDebug();

            if (currentProgress.HasRestarted)
            {
                (" - Download restarted").PrintDebug();
            }

            if (currentProgress.HasResponseChanged)
            {
                // We have received new response headers from the server.
                // Be aware that GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                ResponseInformation response = download.GetResponseInformation();
                int headersCount             = response != null ? response.Headers.Count : 0;

                (" - Response updated; Header count: " + headersCount).PrintDebug();

                // If you want to stream the response data this is a good time to start.
                // download.GetResultStreamAt(0);
            }
        }