Beispiel #1
0
        /// <summary>
        /// 重新启动一个下载任务
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected bool RestartOneDonwload(DownloadInfo info)
        {
            if (string.IsNullOrEmpty(info.RequestId))
            {
                return(false);
            }

            var transferRequest = BackgroundTransferService.Find(info.RequestId);

            if (transferRequest != null &&
                transferRequest.TransferStatus == TransferStatus.Transferring)
            {
                try
                {
                    _isDownloading     = true;
                    info.DownloadState = DownloadState.Downloading;
                    HandleDownload(transferRequest, info, false);
                    return(true);
                }
                catch (Exception ex)
                {
                    DownloadFailture(info, ex.Message);
                    _isDownloading = false;
                }
            }
            return(false);
        }
        private void DeleteRequest(object o)
        {
            var download = o as BackgroundDownload;

            if (download == null)
            {
                return;
            }

            try
            {
                BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(download.Id);
                if (transferToRemove == null)
                {
                    return;
                }

                // Try to remove the transfer from the background transfer service.
                BackgroundTransferService.Remove(transferToRemove);

                // Remove the request from the UI
                Requests.Remove(download);
                TxtNothingToDownload.Visibility = Requests.Any() ? Visibility.Collapsed : Visibility.Visible;
            }
            catch (Exception ex)
            {
                App.TrackException(ex);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 继续一个下载任务
        /// </summary>
        /// <param name="info"></param>
        protected bool ResumeOneDownload(DownloadInfo info)
        {
            if (string.IsNullOrEmpty(info.RequestId))
            {
                return(false);
            }

            var transferRequest = BackgroundTransferService.Find(info.RequestId);

            if (transferRequest != null &&
                transferRequest.TransferStatus == TransferStatus.Transferring)
            {
                try
                {
                    _isDownloading     = true;
                    info.DownloadState = DownloadState.Downloading;
                    HandleDownload(transferRequest, info, false);
                    return(true);
                }
                catch (Exception ex)
                {
                    DownloadFailture(info, ex.Message);
                    _isDownloading = false;
                }
            }
            else
            {
                _isDownloading     = true;
                info.DownloadState = DownloadState.Downloading;
                transferRequest    = new BackgroundTransferRequest(new Uri(info.DownloadUri), new Uri(info.LocalFileName, UriKind.Relative));
                HandleDownload(transferRequest, info, true);
                return(true);
            }
            return(false);
        }
        private async void DownloadLatestBackupFile()
        {
            //
            //

            try
            {
                bBackup.IsEnabled  = false;
                bRestore.IsEnabled = false;
                pbProgress.Value   = 0;
                var progressHandler = new Progress <LiveOperationProgress>(
                    (e) =>
                {
                    pbProgress.Value = e.ProgressPercentage;

                    pbProgress.Visibility = Visibility.Visible;
                    lblLastBackup.Text    =
                        string.Format(
                            StringResources
                            .BackupAndRestorePage_Messages_DwnlProgress,
                            e.BytesTransferred, e.TotalBytes);
                });
                _ctsDownload = new CancellationTokenSource();
                _client      = new LiveConnectClient(App.LiveSession);
                var reqList = BackgroundTransferService.Requests.ToList();
                foreach (var request in reqList)
                {
                    if (request.DownloadLocation.Equals(new Uri(@"\shared\transfers\restore.zip", UriKind.Relative)))
                    {
                        BackgroundTransferService.Remove(BackgroundTransferService.Find(request.RequestId));
                    }
                }
                var token = await _client.DownloadAsync(_newestFile + "/Content", _ctsDownload.Token, progressHandler);

                lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_Restoring;
                RestoreFromFile(token.Stream);
            }
            catch (TaskCanceledException)
            {
                lblLastBackup.Text = "Download Cancelled.";
            }
            catch (LiveConnectException ee)
            {
                lblLastBackup.Text = string.Format("Error Downloading: {0}", ee.Message);
            }
            catch (Exception e)
            {
                lblLastBackup.Text = e.Message;
            }
            finally
            {
                bBackup.IsEnabled     = true;
                bRestore.IsEnabled    = true;
                pbProgress.Value      = 0;
                pbProgress.Visibility = Visibility.Collapsed;
            }
        }
        // TODO can we use the request instances here instead of the id?
        public virtual async Task RemoveTransfer(string transferID)
        {
            var transfer = BackgroundTransferService.Find(transferID);

            if (transfer != null)
            {
                RemoveTransfer(transfer);
                await UpdateTransfersList();
            }
        }
Beispiel #6
0
        private void HandleDownload(BackgroundTransferRequest transferRequest, DownloadInfo info, bool isAddQueue)
        {
            transferRequest.TransferStatusChanged += (o, e) =>
            {
                switch (e.Request.TransferStatus)
                {
                case TransferStatus.Completed:
                    if (e.Request.StatusCode == 200 || e.Request.StatusCode == 206)
                    {
                        DownloadCompleted(info);
                        BackgroundTransferService.Remove(e.Request);
                        e.Request.Dispose();
                    }
                    break;

                case TransferStatus.WaitingForWiFi:
                case TransferStatus.WaitingForNonVoiceBlockingNetwork:
                    info.DownloadState = DownloadState.WaitingForWiFi;
                    Utils.TileUtils.CreateBasicToast("需要在WiFi环境下才能下载");
                    break;

                case TransferStatus.WaitingForExternalPower:
                case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
                    info.DownloadState = DownloadState.WaitingForExternalPower;
                    Utils.TileUtils.CreateBasicToast("需要外接电源才能下载");
                    break;

                default:
                    break;
                }
            };
            transferRequest.TransferProgressChanged += (o, e) =>
            {
                DownloadProgress(e.Request, info);
            };

            if (isAddQueue)
            {
                transferRequest.Method = "GET";
                info.RequestId         = transferRequest.RequestId;

                try
                {
                    if (BackgroundTransferService.Find(info.RequestId) == null)
                    {
                        BackgroundTransferService.Add(transferRequest);
                    }
                }
                catch (Exception ex)
                {
                    _isDownloading = false;
                    DownloadFailture(info, ex.Message);
                }
            }
        }
 internal void Remove(BackgroundTransferRequest request)
 {
     // Check if the request is in Background service before removing to
     // avoid Object aready disposed exception.
     if (BackgroundTransferService.Find(request.RequestId) != null)
     {
         request.TransferProgressChanged -= onTransferProgressChanged;
         request.TransferStatusChanged   -= onTransferStatusChanged;
         BackgroundTransferService.Remove(request);
         request.Dispose();
     }
 }
Beispiel #8
0
        public bool Abort()
        {
            BackgroundTransferRequest request = BackgroundTransferService.Find(requestId);

            if (request != null)
            {
                isAborted = true;
                BackgroundTransferService.Remove(request);
            }

            return(request != null);
        }
Beispiel #9
0
        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            // try to remove the transfer from the background transfer service.
            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// Uploader notre base de données sur OneDrive
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public async static Task <int> ExportDB(CancellationToken ct, Progress <LiveOperationProgress> uploadProgress)
        {
            int log = 0;

            if (LiveClient == null)
            {
                log = await LogClient();
            }

            // Prepare for download, make sure there are no previous requests
            var reqList = BackgroundTransferService.Requests.ToList();

            foreach (var req in reqList)
            {
                if (req.UploadLocation.Equals(new Uri(@"\shared\transfers\" + AppResources.DBFileName, UriKind.Relative)) ||
                    req.UploadLocation.Equals(new Uri(@"\shared\transfers\" + AppResources.DBFileName + ".json", UriKind.Relative)))
                {
                    BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
                }
            }

            IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

            iso.CopyFile(AppResources.DBFileName, "/shared/transfers/" + AppResources.DBFileName, true);

            //  create a folder
            string folderID = await GetFolderID("checkmapp");

            if (string.IsNullOrEmpty(folderID))
            {
                //  return error
                return(0);
            }

            //  upload local file to OneDrive
            LiveClient.BackgroundTransferPreferences = BackgroundTransferPreferences.AllowCellularAndBattery;
            try
            {
                await LiveClient.BackgroundUploadAsync(folderID, new Uri("/shared/transfers/" + AppResources.DBFileName, UriKind.RelativeOrAbsolute), OverwriteOption.Overwrite, ct, uploadProgress);
            }
            catch (TaskCanceledException exception)
            {
                Console.WriteLine("Exception occured while uploading file to OneDrive : " + exception.Message);
            }
            catch (Exception e)
            {
            }
            return(1);
        }
Beispiel #11
0
        private void RemoveTransferRequest(string transferID)
        {
            requestIdChatBubbleMap.Remove(transferID);
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception e)
            {
                // Handle the exception.
            }
        }
Beispiel #12
0
        private void CleanUp(BackgroundTransferRequest transfer)
        {
            if (transfer != null)
            {
                transfer.TransferProgressChanged -= ProgressChanged;
                transfer.TransferStatusChanged   -= TransferStatusChanged;

                if (BackgroundTransferService.Find(transfer.RequestId) != null)
                {
                    BackgroundTransferService.Remove(transfer);
                }

                transfer = null;
            }
        }
Beispiel #13
0
        protected void CancelDownload(DownloadInfo info)
        {
            if (string.IsNullOrEmpty(info.RequestId))
            {
                return;
            }

            var transferRequest = BackgroundTransferService.Find(info.RequestId);

            if (transferRequest != null)
            {
                BackgroundTransferService.Remove(transferRequest);
                transferRequest.Dispose();
            }
        }
        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            // Try to remove the transfer from the background transfer service.
            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception ex1)
            {
                // Handle the exception.
                MessageBox.Show(ex1.Message);
            }
        }
Beispiel #15
0
 public void FinalizeRequest(ITransferRequest request)
 {
     if (request.RequestId != null)
     {
         if (BackgroundTransferService.Find(request.RequestId) != null)
         {
             BackgroundTransferService.Remove(((WindowsTransferRequest)request).OriginalRequest);
             DeleteRequestFromStorage(((WindowsTransferRequest)request).OriginalRequest);
         }
         if (customTransferRequests.ContainsKey(request.RequestId))
         {
             customTransferRequests[request.RequestId].Cancel();
             customTransferRequests.Remove(request.RequestId);
         }
     }
 }
Beispiel #16
0
        private void RemoveTransferRequest(string requestId)
        {
            var transferToRemove = BackgroundTransferService.Find(requestId);

            if (transferToRemove == null)
            {
                return;
            }

            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception)
            {
            }
        }
Beispiel #17
0
        /// <summary>
        /// 暂停一个下载任务
        /// </summary>
        /// <param name="info"></param>
        protected void PauseOneDownload(DownloadInfo info)
        {
            if (string.IsNullOrEmpty(info.RequestId))
            {
                return;
            }

            var transferRequest = BackgroundTransferService.Find(info.RequestId);

            if (transferRequest != null &&
                transferRequest.TransferStatus == TransferStatus.Transferring)
            {
                BackgroundTransferService.Remove(transferRequest);
                transferRequest.Dispose();
                info.DownloadState = DownloadState.Pause;
            }
        }
Beispiel #18
0
        public void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            // try to remove the transfer from the background transfer service.
            try
            {
                if (transferToRemove != null)
                {
                    BackgroundTransferService.Remove(transferToRemove);
                }
            }
            catch (Exception ex)
            {
                _informerManagerLocator.InformerManager.AddMessage("Error", ex.Message);
            }
        }
        public void ChancelDownload(DownloadItem item)
        {
            var request = BackgroundTransferService.Find(item.Id);

            if (request == null)
            {
                return;
            }
            try {
                BackgroundTransferService.Remove(request);
            } catch (Exception exception) {
                MessageBox.Show("Fehler beim Abbrechen: " + exception.Message);
            }

            item.TotalBytes      = 100;
            item.DownloadedBytes = 0;

            item.Id = null;
        }
        private void BtnReset_OnClick(object sender, RoutedEventArgs e)
        {
            ////alle Dateien entfernen
            //var shared = await ApplicationData.Current.LocalFolder.GetFolderAsync("shared");
            //var folder = await shared.GetFolderAsync("transfers");

            //foreach (var storageFile in await folder.GetFilesAsync()) {
            //  await storageFile.DeleteAsync();
            //}

            // alle BackGroundRequests entfernen
            foreach (var request in BackgroundTransferService.Requests)
            {
                BackgroundTransferService.Remove(BackgroundTransferService.Find(request.RequestId));
            }

            // die Liste mit den Elementen neu laden
            _items = new ObservableCollection <DownloadItem>(GetDownloadItems());
            lsItems.ItemsSource = _items;
        }
Beispiel #21
0
        public ITransferRequest GetRequest(string serverUri)
        {
            var requestUriHash = CryptoUtils.GetHash(serverUri);
            var trackerDir     = FileUtils.GetDowloadTrackerDirectory(false, true);
            var requestId      = FileUtils.ReadFile(string.Format("{0}\\{1}", trackerDir, requestUriHash));

            if (!string.IsNullOrEmpty(requestId))
            {
                var request = BackgroundTransferService.Find(requestId);
                if (request == null)
                {
                    return(null);
                }
                else
                {
                    return(new WindowsTransferRequest(request));
                }
            }
            else
            {
                return(null);
            }
        }
Beispiel #22
0
        void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            ReceivedChatBubble chatBubble;

            requestIdChatBubbleMap.TryGetValue(e.Request.RequestId, out chatBubble);
            if (chatBubble != null)
            {
                if (chatBubble.FileAttachment.FileState != Attachment.AttachmentState.CANCELED)
                {
                    chatBubble.updateProgress(e.Request.BytesReceived * 100 / e.Request.TotalBytesToReceive);
                }
                else
                {
                    try
                    {
                        BackgroundTransferRequest transferRequest = BackgroundTransferService.Find(e.Request.RequestId);
                        BackgroundTransferService.Remove(transferRequest);
                    }
                    catch (InvalidOperationException)
                    { }
                }
            }
        }
Beispiel #23
0
        public void stop(string options)
        {
            var optStings = JSON.JsonHelper.Deserialize <string[]>(options);
            var transfer  = FindTransferByUri(new Uri(optStings[0]));

            try
            {
                if (transfer != null)
                {
                    var request = BackgroundTransferService.Find(transfer.RequestId);
                    if (request != null)
                    {
                        // stops transfer and triggers TransferStatusChanged event
                        BackgroundTransferService.Remove(request);
                    }
                }

                DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message));
            }
        }
Beispiel #24
0
        private static void RemoveTransferRequest(string requestId)
        {
            BackgroundTransferRequest transferToRemove = null;

            try
            {
                // Use Find to retrieve the transfer request with the specified ID.
                transferToRemove = BackgroundTransferService.Find(requestId);
                if (transferToRemove == null)
                {
                    return;
                }

                // Try to remove the transfer from the background transfer service.
                BackgroundTransferService.Remove(transferToRemove);

                BackgroundTransferRequestStateChanged?.Raise(transferToRemove, DownloadRequestState.Completed);
            }
            catch (Exception ex)
            {
                App.TrackException(ex);
                BackgroundTransferRequestStateChanged?.Raise(transferToRemove, DownloadRequestState.Error);
            }
        }
        /// <summary>
        /// Downloader la BD a partir de OneDrive
        /// </summary>
        /// <returns></returns>
        public async static Task <int> ImportBD(CancellationToken ct, Progress <LiveOperationProgress> uploadProgress)
        {
            int log = 0;

            if (LiveClient == null)
            {
                log = await LogClient();
            }

            // Prepare for download, make sure there are no previous requests
            var reqList = BackgroundTransferService.Requests.ToList();

            foreach (var req in reqList)
            {
                if (req.DownloadLocation.Equals(new Uri(@"\shared\transfers\" + AppResources.DBFileName, UriKind.Relative)) ||
                    req.DownloadLocation.Equals(new Uri(@"\shared\transfers\" + AppResources.DBFileName + ".json", UriKind.Relative)))
                {
                    BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
                }
            }

            string fileID = string.Empty;

            //  get folder ID
            string folderID = await GetFolderID("checkmapp");

            if (string.IsNullOrEmpty(folderID))
            {
                return(0); // doesnt exists
            }

            //  get list of files in this folder
            LiveOperationResult loResults = await LiveClient.GetAsync(folderID + "/files");

            List <object> folder = loResults.Result["data"] as List <object>;

            //  search for our file
            foreach (object fileDetails in folder)
            {
                IDictionary <string, object> file = fileDetails as IDictionary <string, object>;
                if (string.Compare(file["name"].ToString(), AppResources.DBFileName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    //  found our file
                    fileID = file["id"].ToString();
                    break;
                }
            }

            if (string.IsNullOrEmpty(fileID))
            {
                //  file doesnt exists
                return(0);
            }

            try
            {
                //  download file from OneDrive
                LiveClient.BackgroundTransferPreferences = BackgroundTransferPreferences.AllowCellularAndBattery;
                await LiveClient.BackgroundDownloadAsync(fileID + @"/content", new Uri(@"\shared\transfers\" + AppResources.DBFileName, UriKind.RelativeOrAbsolute), ct, uploadProgress);
            }
            catch (TaskCanceledException exception)
            {
                Console.WriteLine("Exception occured while downloading file from OneDrive : " + exception.Message);
                return(2);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while downloading file from OneDrive : " + ex.Message);
                return(0);
            }
            return(1);
        }
 internal BackgroundTransferRequest Get(string requestId)
 {
     return(BackgroundTransferService.Find(requestId));
 }