void OnDownloadPageCompletedForDownloadAllPages(BackgroundTransferRequest request) { uint context = uint.Parse(request.Tag); if (!_downloadAllProgress.ContainsKey(context)) { return; } _downloadAllProgress[context]--; if (null != request.TransferError) { Deployment.Current.Dispatcher.BeginInvoke(new GetAllPagesAsyncCompletedTrigger(TriggerGetAllPagesAsyncCompleted), false); return; } try { IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); store.MoveFile(request.DownloadLocation.OriginalString, Path.GetFileName(request.DownloadLocation.OriginalString)); if (_downloadAllProgress[context] == 0) { Deployment.Current.Dispatcher.BeginInvoke(new GetAllPagesAsyncCompletedTrigger(TriggerGetAllPagesAsyncCompleted), true); } } catch (Exception) { _downloadAllProgress.Remove(context); Deployment.Current.Dispatcher.BeginInvoke(new GetAllPagesAsyncCompletedTrigger(TriggerGetAllPagesAsyncCompleted), false); } }
private void OnSeriesTransferCompleted(BackgroundTransferRequest request) { if (null != request.TransferError) { DeleteFile(request.DownloadLocation.OriginalString); Deployment.Current.Dispatcher.BeginInvoke(new DataLoadedTrigger(TriggerDataLoaded), false); return; } try { string data = Storage.ReadFileToString(request.DownloadLocation.OriginalString); DeleteFile(request.DownloadLocation.OriginalString); List <SeriesModel> series = JsonConvert.DeserializeObject <List <SeriesModel> >(data); // TODO: Is there a more efficient way to empty the entire table? // LINQ on Windows Phone doesn't seem to have ExecuteCommand(). _mangaDB.Series.DeleteAllOnSubmit(_mangaDB.Series); _mangaDB.SubmitChanges(); _mangaDB.Series.InsertAllOnSubmit(series); _mangaDB.SubmitChanges(); Deployment.Current.Dispatcher.BeginInvoke(new UpdateSeriesDelegate(UpdateSeries), series); IsSeriesLoaded = true; Deployment.Current.Dispatcher.BeginInvoke(new DataLoadedTrigger(TriggerDataLoaded), true); } catch (Exception) { Deployment.Current.Dispatcher.BeginInvoke(new DataLoadedTrigger(TriggerDataLoaded), false); } }
/// <summary> /// /// </summary> /// <param name="transfer"></param> /// <exception cref="IsolatedStorageException">If an IO error occurs while processing a successfully transferred file.</exception> protected virtual async Task OnTransferComplete(BackgroundTransferRequest transfer) { // Removes the transfer request in order to make room in the // queue for more transfers. Transfers are not automatically // removed by the system. await RemoveTransfer(transfer.RequestId); var maybeError = transfer.TransferError; if (maybeError == null) { if (transfer.BytesReceived == transfer.TotalBytesToReceive) { var finalDestination = MoveSuccessfullyDownloadedFile(transfer); OnDownloadComplete(transfer, finalDestination); } else { TryToDeleteIfExists(transfer.DownloadLocation.OriginalString); } } else { OnTransferCompletedWithErrors(transfer); } if (initComplete) { //Debug.WriteLine("Download complete"); LoadTransfersFromPersistentStorage(); } }
/// <summary> /// Performs the BackgroundDownloadOperation. /// </summary> public async Task <LiveOperationResult> ExecuteAsync() { Debug.Assert(this.status != OperationStatus.Completed, "Cannot execute on a completed operation."); var builder = new BackgroundDownloadRequestBuilder { AccessToken = this.accessToken, DownloadLocationOnDevice = this.downloadLocationOnDevice, RequestUri = this.requestUri, TransferPreferences = this.transferPreferences }; this.request = builder.Build(); var eventAdapter = new BackgroundDownloadEventAdapter(this.backgroundTransferService, this.tcs); Task <LiveOperationResult> task = this.progress == null? eventAdapter.ConvertTransferStatusChangedToTask(this.request) : eventAdapter.ConvertTransferStatusChangedToTask(this.request, this.progress); Debug.Assert(this.tcs.Task == task, "EventAdapter returned a different task. This could affect cancel."); // if the request has already been cancelled do not add it to the service. if (this.status != OperationStatus.Cancelled) { this.backgroundTransferService.Add(this.request); this.status = OperationStatus.Started; } LiveOperationResult result = await task; this.status = OperationStatus.Completed; return(result); }
public static TransferMonitorViewModel Create(BackgroundTransferRequest request) { var vm = new TransferMonitorViewModel(new TransferMonitor(request)); vm.CreateJobData(request); return vm; }
public void Download(string url, AsyncCallback DownloadCallback) { url = url.Replace("https", "http"); BTR_Download = new BackgroundTransferRequest(new Uri(url)); using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (!iso.DirectoryExists(TRANSFER_FOLDER)) { iso.CreateDirectory(TRANSFER_FOLDER); } } BTR_Download.DownloadLocation = new Uri(DOWNLOAD_LOCATION, UriKind.Relative); BTR_Download.TransferStatusChanged += BTR_Download_TransferStatusChanged; BTR_Download.TransferProgressChanged += BTR_Download_TransferProgressChanged; if (!Downloading) { foreach (BackgroundTransferRequest req in BackgroundTransferService.Requests) { if (req.DownloadLocation == BTR_Download.DownloadLocation) { BackgroundTransferService.Remove(req); } } BackgroundTransferService.Add(BTR_Download); Downloading = true; _downloadProgressChangeCallback = DownloadCallback; } }
private static void Raise(this DownloadStateEventHandler handler, BackgroundTransferRequest request, DownloadRequestState state) { if (request != null && handler != null) { handler(request, new EventArgsState(state)); } }
private void Button_Click_1(object sender, RoutedEventArgs e) { string mp3uri = "http://www.nmgwxc.com/m/yldcj.mp3"; if (BackgroundTransferService.Requests.Count() >= 25) { MessageBox.Show("已经超过最大请求数量,请稍后"); return; } if (BackgroundTransferService.Requests.Any(p => p.RequestUri.AbsoluteUri == mp3uri)) { MessageBox.Show("文件已经在下载的请求中"); return; } BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(new Uri(mp3uri, UriKind.Absolute)); transferRequest.Method = "GET"; transferRequest.TransferPreferences = TransferPreferences.None; transferRequest.TransferStatusChanged += transferRequest_TransferStatusChanged; transferRequest.TransferProgressChanged += transferRequest_TransferProgressChanged; transferRequest.Tag = "yldcj.mp3"; transferRequest.DownloadLocation = new Uri("shared/transfers/yldcj.mp3", UriKind.Relative); try { BackgroundTransferService.Add(transferRequest); } catch (Exception ee) { MessageBox.Show(ee.Message); } }
/// <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; }
/// <summary> /// Keeps the download progress properties of the music items up-to-date /// so that the progress can be displayed under each item in the UI. /// /// The music items in the library and the playlist do not point to the /// same object even if it's the same track so we need to update both places separately. /// </summary> /// <param name="transfer"></param> protected override void OnDownloadStatusUpdate(BackgroundTransferRequest transfer) { base.OnDownloadStatusUpdate(transfer); var path = FileUtilsBase.UnixSeparators(transfer.Tag.Substring(PhoneLocalLibrary.Instance.BaseMusicPath.Length)); var musicItem = MusicProvider.SearchItem(path); var isDownloading = transfer.TransferStatus == TransferStatus.Transferring; var bytesReceived = (ulong)transfer.BytesReceived; // updates track in the library if (musicItem != null) { MusicItem.SetDownloadStatus(musicItem, bytesReceived); musicItem.IsDownloading = isDownloading; } // updates the track in the playlist var playlistTracks = PimpViewModel.Instance.MusicPlayer.Playlist.Songs .Where(item => item.Song.Path == path) .ToList(); // beautiful!!! BasePlaylist.SetDownloadStatus(playlistTracks, bytesReceived); foreach (var item in playlistTracks) { item.Song.IsDownloading = isDownloading; } }
private string MoveSuccessfullyDownloadedFile(BackgroundTransferRequest completedRequest) { string finalDestination = completedRequest.Tag; using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { var tempDownloadPath = completedRequest.DownloadLocation.OriginalString; if (!isoStore.FileExists(tempDownloadPath)) { // this handler has already run previously, ignore return(finalDestination); } if (isoStore.FileExists(finalDestination)) { isoStore.DeleteFile(finalDestination); } else { var dir = Path.GetDirectoryName(finalDestination); if (!isoStore.DirectoryExists(dir)) { isoStore.CreateDirectory(dir); } } isoStore.MoveFile(tempDownloadPath, finalDestination); } return(finalDestination); }
/// <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 PendingDownload chooseDownloadMethod(QueuedDownload queuedDownload) { if (queuedDownload.ForceActiveDownload || queuedDownload.DownloadSize >= 20000000L && queuedDownload.DownloadSize != long.MaxValue) { HttpWebRequest request = WebRequest.CreateHttp(ApplicationSettings.ServerUrl.DownloadPath(queuedDownload)); request.SetCredentials(LoggedUser); request.Headers["Range"] = "bytes=" + queuedDownload.DownloadedBytes.ToString() + "-"; request.AllowReadStreamBuffering = false; return(new PendingActiveDownload(request, Observable.FromAsyncPattern <WebResponse>(request.BeginGetResponse, request.SaneEndGetResponse)() .Select(response => (RunningDownload) new ActiveDownload(response, queuedDownload)))); } else { //first check if there is not tranfer request already added to service foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests) { if (request.RequestUri.Equals(ApplicationSettings.ServerUrl.DownloadPath(queuedDownload))) { return(new PendingBackgroundDownload(request, Observable.Return(new BackgroundDownload(request, queuedDownload) as RunningDownload))); } request.Dispose(); } BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(ApplicationSettings.ServerUrl.DownloadPath(queuedDownload)); return(new PendingBackgroundDownload(transferRequest, Observable.Return(new BackgroundDownload(transferRequest, queuedDownload) as RunningDownload))); } }
/// <summary> /// This function is for demo purposes. It adds three files to the background download queue and displays them in the multi-select list. /// </summary> private void OnAddButtonClick(object sender, EventArgs e) { Dictionary <string, Uri> urlPresets = new Dictionary <string, Uri> { { "21 MB File", new Uri("http://media.ch9.ms/ch9/ecbc/cfcb0ad7-fbdd-47b0-aabf-4da5e3e0ecbc/WP8JumpStart06.mp3", UriKind.Absolute) }, { "34 MB File", new Uri("http://media.ch9.ms/ch9/7e13/ce6ea97c-e233-4e7c-a74d-ee1c81e37e13/WP8JumpStart04.mp3", UriKind.Absolute) }, { "92 MB File", new Uri("http://media.ch9.ms/ch9/7e13/ce6ea97c-e233-4e7c-a74d-ee1c81e37e13/WP8JumpStart04.wmv", UriKind.Absolute) }, }; foreach (var preset in urlPresets) { Uri saveLocation = new Uri("/shared/transfers/" + preset.Key, UriKind.Relative); BackgroundTransferRequest request = new BackgroundTransferRequest(preset.Value, saveLocation) { TransferPreferences = TransferPreferences.AllowBattery // Note: this will not use cellular data to download }; TransferMonitor monitor = new TransferMonitor(request, preset.Key); try { BackgroundTransferService.Add(request); } catch (Exception err) // An exception is thrown if this transfer is already requested. { Debug.WriteLine(err); continue; } monitor.Failed += TransferCanceled; _list.Add(monitor); } }
private void Download_Click(object sender, EventArgs e) { try { // Sichergehen, dass der Download-Ordner existiert using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStore.DirectoryExists(TransfersFolder)) { isoStore.CreateDirectory(TransfersFolder); } } var request = new BackgroundTransferRequest(new Uri("http://ralfe-software.net/Wildlife.wmv", UriKind.Absolute)) { DownloadLocation = new Uri(DownloadLocation, UriKind.Relative), Method = "GET", TransferPreferences = TransferPreferences.AllowBattery }; BackgroundTransferService.Add(request); DownloadButton.IsEnabled = false; DeleteButton.IsEnabled = true; UpdateUI(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Can chu y sua /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ApplicationBarIconButton_DownloadClick(object sender, EventArgs e) { foreach (var track in App.AlbumVM.TrackList) { if (track.IsSelected) { string link; string[] links = await NhacCuaTui.GetSongDownloadLinkAsync(track.Song.Info); if (links[1] != null) { link = links[1]; } else if (links[0] != null) { link = links[0]; } else { link = track.Location; } BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(new Uri(link, UriKind.RelativeOrAbsolute)); transferRequest.Method = "GET"; transferRequest.DownloadLocation = new Uri("shared/transfers/" + track.Title.Replace(' ', '-') + ".mp3", UriKind.RelativeOrAbsolute); try { BackgroundTransferService.Add(transferRequest); } catch (Exception) { } } } }
private static void UpdateTransferStatus(DownloadItem item, BackgroundTransferRequest request) { switch (request.TransferStatus) { case TransferStatus.Transferring: item.Caption = "Cancel"; break; case TransferStatus.Waiting: item.Caption = "Waiting"; break; case TransferStatus.Completed: if (request.TransferStatus == TransferStatus.Completed && request.TransferError == null) { item.Caption = "Show"; } else { item.Caption = "Download"; } break; default: item.Caption = request.TransferStatus.ToString(); break; } }
public StatsPage() { InitializeComponent(); Loaded += new System.Windows.RoutedEventHandler(StatsPage_Loaded); p_reporter = new ProgressReporter(); req = null; }
public void downloadFile(MyChatBubble chatBubble, string msisdn) { Uri downloadUriSource = new Uri(Uri.EscapeUriString(HikeConstants.FILE_TRANSFER_BASE_URL + "/" + chatBubble.FileAttachment.FileKey), UriKind.RelativeOrAbsolute); string relativeFilePath = "/" + msisdn + "/" + Convert.ToString(chatBubble.MessageId); string destinationPath = "shared/transfers" + "/" + Convert.ToString(chatBubble.MessageId); Uri destinationUri = new Uri(destinationPath, UriKind.RelativeOrAbsolute); BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(downloadUriSource); // Set the transfer method. GET and POST are supported. transferRequest.Tag = relativeFilePath; transferRequest.Method = "GET"; transferRequest.TransferStatusChanged += new EventHandler <BackgroundTransferEventArgs>(transfer_TransferStatusChanged); transferRequest.TransferProgressChanged += new EventHandler <BackgroundTransferEventArgs>(transfer_TransferProgressChanged); transferRequest.DownloadLocation = destinationUri; try { transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery; BackgroundTransferService.Add(transferRequest); requestIdChatBubbleMap.Add(transferRequest.RequestId, chatBubble as ReceivedChatBubble); } catch (InvalidOperationException ex) { MessageBox.Show(AppResources.FileTransfer_ErrorMsgBoxText + ex.Message); } catch (Exception e) { MessageBox.Show(AppResources.FileTransfer_ErrorMsgBoxText); } }
public void Upload(AsyncCallback UploadCallback, AsyncCallback uploadProgressCallback) { string upload_uri = FILEPICKER_BASEURL + "/api/store/S3?key=" + FILEPICKER_APIKEY; BTR = new BackgroundTransferRequest(new Uri(upload_uri)); BTR.TransferStatusChanged += BTR_TransferStatusChanged; BTR.TransferProgressChanged += BTR_TransferProgressChanged; BTR.Method = "POST"; using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (!iso.DirectoryExists(TRANSFER_FOLDER)) { iso.CreateDirectory(TRANSFER_FOLDER); } iso.CopyFile("/cars.sdf", TRANSFER_FOLDER + "/cars.sdf", true); } BTR.DownloadLocation = new Uri(SAVE_RESPONSE_LOCATION, UriKind.Relative); BTR.UploadLocation = new Uri(TRANSFER_FOLDER + "/cars.sdf", UriKind.Relative); if (!Uploading) { Uploading = true; foreach (BackgroundTransferRequest req in BackgroundTransferService.Requests) { if (req.UploadLocation == BTR.UploadLocation) { BackgroundTransferService.Remove(req); } } BackgroundTransferService.Add(BTR); _uploadCallback = UploadCallback; _uplaodProgressChangeCallback = uploadProgressCallback; } }
public DownloadItemBackgroundViewModel(BackgroundTransferRequest backgroundTransferRequest) { this.BackgroundTransferRequest = backgroundTransferRequest; this.ProcessTransfer(backgroundTransferRequest); this.WatchTransfer(); this.ProcessTransfer(backgroundTransferRequest); }
private void ProcessTransfer(BackgroundTransferRequest request) { switch (request.TransferStatus) { case TransferStatus.Completed: if (request.StatusCode == 200 || request.StatusCode == 206) { Status.Text = "Abgeschlossen"; // Download fertig - Transfer-Obhjekt entfernen RemoveTransferRequest(request); // AppBar-Buttons aktualisieren DeleteButton.IsEnabled = true; DownloadButton.IsEnabled = false; // Video abspielen string sourcePath = request.DownloadLocation.OriginalString.Substring(1); var player = new MediaPlayerLauncher(); player.Location = MediaLocationType.Data; player.Media = new Uri(sourcePath, UriKind.Relative); player.Orientation = MediaPlayerOrientation.Landscape; player.Show(); } break; default: Status.Text = request.TransferStatus.ToString(); DeleteButton.IsEnabled = true; DownloadButton.IsEnabled = false; break; } }
private void OnBackgroundTransferRequestStateChanged(BackgroundTransferRequest request, EventArgsState e) { BackgroundDownload download = Requests.FirstOrDefault(r => r.Id == request.RequestId); if (download == null) { return; } download.Status = GetStatusText(e.State); if (e.State == DownloadRequestState.Downloading) { download.BytesReceived = request.BytesReceived; if (download.TotalBytesToReceive == -1) { download.TotalBytesToReceive = download.BytesReceived * 2; } } if (e.State == DownloadRequestState.Completed) { Requests.Remove(download); } TxtNothingToDownload.Visibility = Requests.Any() ? Visibility.Collapsed : Visibility.Visible; }
private ITransferRequest DownloadAsyncViaBackgroundTranfer(Uri serverUri, Uri phoneUri) { try { var request = new BackgroundTransferRequest(serverUri, phoneUri); request.Tag = serverUri.ToString(); request.TransferPreferences = TransferPreferences.AllowCellularAndBattery; int count = 0; foreach (var r in BackgroundTransferService.Requests) { count++; if (r.RequestUri == serverUri) return new WindowsTransferRequest(r); if (r.TransferStatus == TransferStatus.Completed) { BackgroundTransferService.Remove(r); count--; } // Max 5 downloads if (count >= 5) return null; } BackgroundTransferService.Add(request); PersistRequestToStorage(request); return new WindowsTransferRequest(request); } catch (InvalidOperationException) { return GetRequest(serverUri.ToString()); } }
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); } }
private void PersistRequestToStorage(BackgroundTransferRequest request) { var requestUri = request.RequestUri; var requestUriHash = CryptoUtils.GetHash(requestUri.ToString()); var trackerDir = FileUtils.GetDowloadTrackerDirectory(false, true); FileUtils.WriteFile(string.Format("{0}\\{1}", trackerDir, requestUriHash), request.RequestId); }
private void ProcessTransfer(BackgroundTransferRequest transfer) { switch (transfer.TransferStatus) { case TransferStatus.Completed: // If the status code of a completed transfer is 200 or 206, the // transfer was successful if (transfer.StatusCode == 200 || transfer.StatusCode == 206) { // Transfers are not automatically removed by the system. // Uncomment the following line to remove completed transfer requests // in order to make room in the queue for more transfers. // RemoveTransferRequest(transfer.RequestId); // In this example, the downloaded file is moved into the root // Isolated Storage directory using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { string filename = transfer.Tag; if (isoStore.FileExists(filename)) { isoStore.DeleteFile(filename); } if (isoStore.FileExists(transfer.DownloadLocation.OriginalString)) { isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename); } } } else { // This is where you can handle whatever error is indicated by the // StatusCode and then remove the transfer from the queue. RemoveTransferRequest(transfer.RequestId); if (transfer.TransferError != null) { // Handle TransferError, if there is one. } } break; case TransferStatus.WaitingForExternalPower: WaitingForExternalPower = true; break; case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode: WaitingForExternalPowerDueToBatterySaverMode = true; break; case TransferStatus.WaitingForNonVoiceBlockingNetwork: WaitingForNonVoiceBlockingNetwork = true; break; case TransferStatus.WaitingForWiFi: WaitingForWiFi = true; break; } }
/// <summary> /// Performs the BackgroundUploadOperation. /// </summary> public async Task <LiveOperationResult> ExecuteAsync() { Debug.Assert(this.status != OperationStatus.Completed, "Cannot execute on a completed operation."); if (this.status == OperationStatus.Cancelled) { return(await this.tcs.Task); } this.status = OperationStatus.Started; string filename = Path.GetFileName(this.uploadLocationOnDevice.OriginalString); Debug.Assert(!string.IsNullOrEmpty(filename)); Uri requestUri = this.client.GetResourceUri(this.path, ApiMethod.Upload); // TODO: Figure out how to mock out GetUploadLinkOperation elegantly so this can be tested. this.getUploadLinkOperation = new GetUploadLinkOperation( this.client, requestUri, filename, this.overwriteOption, null); LiveOperationResult uploadLinkResult = await this.getUploadLinkOperation.ExecuteAsync(); var uploadRequestUri = new Uri(uploadLinkResult.RawResult, UriKind.Absolute); var downloadLocationOnDevice = new Uri(this.uploadLocationOnDevice.OriginalString + ".json", UriKind.RelativeOrAbsolute); var builder = new BackgroundUploadRequestBuilder { RequestUri = uploadRequestUri, AccessToken = this.client.Session.AccessToken, UploadLocationOnDevice = this.uploadLocationOnDevice, DownloadLocationOnDevice = downloadLocationOnDevice, TransferPreferences = this.transferPreferences }; this.request = builder.Build(); var eventAdapter = new BackgroundUploadEventAdapter(this.backgroundTransferService, this.tcs); Task <LiveOperationResult> task = progress == null? eventAdapter.ConvertTransferStatusChangedToTask(this.request) : eventAdapter.ConvertTransferStatusChangedToTask(this.request, progress); Debug.Assert(this.tcs.Task == task, "EventAdapter returned a different task. This could affect cancel."); if (this.status != OperationStatus.Cancelled) { this.backgroundTransferService.Add(this.request); this.requestAddedToService = true; } LiveOperationResult result = await task; this.status = OperationStatus.Completed; return(result); }
public static TransferMonitorViewModel Create(BackgroundTransferRequest request) { var vm = new TransferMonitorViewModel(new TransferMonitor(request)); vm.CreateJobData(request); return(vm); }
protected override async Task OnTransferComplete(BackgroundTransferRequest transfer) { try { await base.OnTransferComplete(transfer); } catch (Exception e) { AddMessage("Error while processing completed transfer. " + e.Message); } }
/// <summary> /// Attaches a BackgroundUploadCompletedEventAdapter to the given BackgroundTransferRequest. /// This is to convert a BackgroundTransferRequest's status changes to a LiveOperationResult. /// </summary> /// <param name="request">Request to attach to.</param> /// <returns>A Task<LiveOperationResult> converted over from a BackgroundTransferEventArgs.</returns> public Task<LiveOperationResult> ConvertTransferStatusChangedToTask(BackgroundTransferRequest request) { var completedEventHandler = new BackgroundUploadCompletedEventAdapter(this.backgroundTransferService, this.tcs); completedEventHandler.BackgroundTransferRequestCompleted += this.OnBackgroundTransferRequestCompleted; return completedEventHandler.ConvertTransferStatusChangedToTask(request); }
/// <summary> /// Callback used when BackgroundTransferRequest's TransferStatus changes to Completed. /// This method performs clean up and detaches the progressEventAdapter event adapter from the request. /// </summary> private void OnBackgroundTransferRequestCompletedEventAdapter(BackgroundTransferRequest request) { // this.completedEventAdapter detaches itself. if (this.progressEventAdapter != null) { this.progressEventAdapter.DetachFromCompletedRequest(request); } }
private void CreateJobData(BackgroundTransferRequest request) { var json = request.Tag; var jobData = JsonConvert.DeserializeObject<JobData>(json); JobData = jobData; Monitor.Name = jobData.Name; }
public WindowsTransferRequest(BackgroundTransferRequest request) { this.request = request; if (this.request != null) { this.request.TransferProgressChanged += request_TransferProgressChanged; this.request.TransferStatusChanged += request_TransferStatusChanged; } }
private void OnBackgroundTransferRequestCompleted(BackgroundTransferRequest request) { Action <BackgroundTransferRequest> handler = BackgroundTransferRequestCompleted; if (handler != null) { handler(request); } }
/// <summary> /// Handles TransferProgressChanged events from a BackgroundTransferRequest. /// </summary> private void HandleTransferProgressChanged(object sender, BackgroundTransferEventArgs e) { BackgroundTransferRequest request = e.Request; long totalBytesToSend = request.TotalBytesToSend; long bytesSent = request.BytesSent; var result = new LiveOperationProgress(bytesSent, totalBytesToSend); this.OnProgressChanged(result); }
private void CreateJobData(BackgroundTransferRequest request) { var json = request.Tag; var jobData = JsonConvert.DeserializeObject <JobData>(json); JobData = jobData; Monitor.Name = jobData.Name; }
/// <summary> /// 开始下载一个新任务,此方法为后台线程调用 /// </summary> /// <param name="info"></param> protected void StartOneDownload(DownloadInfo info) { _isDownloading = true; var destinationPath = string.Format("/shared/transfers/{0}", info.LocalFileName); var destinationFile = new Uri(destinationPath, UriKind.Relative); var transferRequest = new BackgroundTransferRequest(new Uri(info.DownloadUri), destinationFile); info.LocalFileName = transferRequest.DownloadLocation.OriginalString; HandleDownload(transferRequest, info, true); }
public void startAsync(string options) { try { var optStings = JSON.JsonHelper.Deserialize<string[]>(options); var uriString = optStings[0]; var filePath = optStings[1]; if (_activDownloads.ContainsKey(uriString)) { return; } _activDownloads.Add(uriString, new Download(uriString, filePath, optStings[2])); var requestUri = new Uri(uriString); BackgroundTransferRequest transfer = FindTransferByUri(requestUri); if (transfer == null) { // "shared\transfers" is the only working location for BackgroundTransferService download // we use temporary file name to download content and then move downloaded file to the requested location var downloadLocation = new Uri(@"\shared\transfers\" + Guid.NewGuid(), UriKind.Relative); transfer = new BackgroundTransferRequest(requestUri, downloadLocation); // Tag is used to make sure we run single background transfer for this file transfer.Tag = uriString; BackgroundTransferService.Add(transfer); } if (transfer.TransferStatus == TransferStatus.Completed) { // file was already downloaded while we were in background and we didn't report this MoveFile(transfer); BackgroundTransferService.Remove(transfer); DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } else { transfer.TransferProgressChanged += ProgressChanged; transfer.TransferStatusChanged += TransferStatusChanged; } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message)); } }
internal LivePendingDownload( IBackgroundTransferService backgroundTransferService, BackgroundTransferRequest request) { Debug.Assert(backgroundTransferService != null); Debug.Assert(request != null); Debug.Assert(BackgroundTransferHelper.IsDownloadRequest(request)); this.request = request; this.backgroundTransferService = backgroundTransferService; }
/// <summary> /// Attaches a BackgroundDownloadCompletedEventAdapter to the given BackgroundTransferRequest. /// This is to convert a BackgroundTransferRequest's status changes to a LiveOperationResult. /// </summary> /// <param name="request">Request to attach to.</param> /// <returns>A Task<LiveOperationResult> converted over from a BackgroundTransferEventArgs.</returns> public Task<LiveOperationResult> ConvertTransferStatusChangedToTask(BackgroundTransferRequest request) { Debug.Assert(request != null); var completedEventAdapter = new BackgroundDownloadCompletedEventAdapter(this.backgroundTransferService, this.tcs); completedEventAdapter.BackgroundTransferRequestCompleted += this.OnBackgroundTransferRequestCompletedEventAdapter; return completedEventAdapter.ConvertTransferStatusChangedToTask(request); }
public ProgressInfo GetProgressInfo(BackgroundTransferRequest e) { P.FileProgress = (float)e.BytesReceived / (float)e.TotalBytesToReceive; string[] splitted_tag = e.Tag.Split('|'); ts = DateTime.Now - last_time; P.Speed = (float)(e.BytesReceived - BytesTransferredLast) / (float)ts.TotalSeconds/1024; P.Title = splitted_tag[1]; BytesTransferredLast = e.BytesReceived; last_time = DateTime.Now; return P; }
/// <summary> /// Attaches a BackgroundDownloadCompletedEventAdapter and a BackgroundDownloadProgressEventAdapter /// to the given BackgroundTransferRequest. /// This is to convert a BackgroundTransferRequest's status changes to a LiveOperationResult and /// to change it's progress changes to a LiveOperationProgress. /// </summary> /// <param name="request">Request to attach to.</param> /// <param name="progress">The interface to call when there is a progress event.</param> /// <returns>A Task<LiveOperationResult> converted over from a BackgroundTransferEventArgs.</returns> public Task<LiveOperationResult> ConvertTransferStatusChangedToTask( BackgroundTransferRequest request, IProgress<LiveOperationProgress> progress) { if (progress != null) { this.progressEventAdapter = new BackgroundDownloadProgressEventAdapter(progress); this.progressEventAdapter.ConvertTransferProgressChanged(request); } return this.ConvertTransferStatusChangedToTask(request); }
public BackgroundTransferControl() { InitializeComponent(); _request = BackgroundTransferService.Requests.FirstOrDefault(s => s.Tag == "Channel9Download"); if (_request != null) { _monitor = new TransferMonitor(_request); _monitor.Failed += TransferFailed; Control1.DataContext = _monitor; } }
protected BackgroundTransferRequest GetBackTXRequest(string src,string tag) { Uri src_uri = new Uri(src, UriKind.Absolute); Uri dst_uri = new Uri("shared\\transfers\\temp"+src_uri.GetHashCode()+".mp3", UriKind.Relative); BackgroundTransferRequest back_req = new BackgroundTransferRequest(src_uri, dst_uri); back_req.Tag = tag; bool use_cellular = false; IsolatedStorageSettings.ApplicationSettings.TryGetValue("use_cellular", out use_cellular); if (use_cellular) back_req.TransferPreferences = TransferPreferences.AllowCellularAndBattery; else back_req.TransferPreferences = TransferPreferences.AllowBattery; return back_req; }
private PodcastEpisodesDownloadManager() { createEpisodeDownloadDir(); m_applicationSettings = IsolatedStorageSettings.ApplicationSettings; if (BackgroundTransferService.Requests.Count() == 0) { m_applicationSettings.Remove(App.LSKEY_PODCAST_EPISODE_DOWNLOADING_ID); m_currentBackgroundTransfer = null; } processOngoingTransfer(); processStoredQueuedTransfers(); }
/// <summary> /// Attaches to this BackgroundTransferRequest's TransferStatusChanged event. /// </summary> /// <param name="request">request to attach to</param> public Task<LiveOperationResult> ConvertTransferStatusChangedToTask(BackgroundTransferRequest request) { Debug.Assert(BackgroundTransferHelper.IsUploadRequest(request)); if (request.TransferStatus != TransferStatus.Completed) { request.TransferStatusChanged += this.HandleTransferStatusChanged; } else { // If we are working with an already completed request just handle it now. this.OnTransferStatusComplete(request); } return this.tcs.Task; }
private void BeginDownload() { using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (storage.FileExists("/shared/transfers/channel9.mp3")) storage.DeleteFile("/shared/transfers/channel9.mp3"); } _request = new BackgroundTransferRequest( new Uri("http://media.ch9.ms/ch9/7e13/ce6ea97c-e233-4e7c-a74d-ee1c81e37e13/WP8JumpStart04.mp3", UriKind.Absolute), new Uri("/shared/transfers/channel9.mp3", UriKind.Relative)) { Tag = "Channel9Download", TransferPreferences = TransferPreferences.AllowBattery }; _monitor = new TransferMonitor(_request); Control1.DataContext = _monitor; _monitor.RequestStart(); //This adds request to the BackgroundTransferService queue. }
private void RestartDownload() { try { BackgroundTransferService.Remove(_request); } catch (Exception) { //No need to worry. These errors can be surpressed. We are just making sure the download has been completed cancelled. } _request = null; _monitor = null; BeginDownload(); }
void StatsPage_Loaded(object sender, System.Windows.RoutedEventArgs e) { UpdateUsageData(); if (App.GlobalOfflineSync != null) { App.GlobalOfflineSync.Ready += new FileDownloadEvntHandler(GlobalOfflineSync_Ready); App.GlobalOfflineSync.SyncProgressChange += new FileDownloadEvntHandler(GlobalOfflineSync_SyncProgressChange); req = App.GlobalOfflineSync.BACKGROUND_REQUEST;//BackgroundTransferService.Requests.FirstOrDefault(); if(req != null) req.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(StatsPage_TransferProgressChanged); progressbar.Maximum = 1; progressbar.Minimum = 0; progressbar.Value = 0; } else title.Text = "No Syncing in Progress"; }
public void Upload(string username, string password, string filename) { using (System.IO.IsolatedStorage.IsolatedStorageFile iso = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication()) { if (!iso.FileExists(localDBName)) return; iso.CopyFile(localDBName, "/" + TransfersFiles + "/" + localDBName, true); } BackgroundTransferRequest btr = new BackgroundTransferRequest(new Uri(serviceUploadLocationURL + localDBName, UriKind.Absolute)); btr.TransferPreferences = TransferPreferences.AllowBattery; btr.Method = "POST"; btr.UploadLocation = new Uri("/" + TransfersFiles + "/" + localDBName, UriKind.Relative); btr.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(btr_UploadTransferStatusChanged); btr.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(btr_TransferProgressChanged); Microsoft.Phone.BackgroundTransfer.BackgroundTransferService.Add(btr); }
public BackgroundTransferRequest Build() { Debug.Assert(this.requestUri != null); Debug.Assert(this.accessToken != null); Debug.Assert(this.downloadLocationOnDevice != null); var request = new BackgroundTransferRequest(this.requestUri, this.downloadLocationOnDevice); request.Headers.Add( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + this.accessToken); request.Headers.Add(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); request.Tag = BackgroundTransferHelper.Tag; request.TransferPreferences = this.transferPreferences; return request; }
public void QueueDownload(string source, string destination, string tag, OnTransferCompleted callback) { Uri requestUri = new Uri(source, UriKind.Absolute); Uri downloadLocation = new Uri(destination, UriKind.Relative); BackgroundTransferRequest request = new BackgroundTransferRequest(requestUri, downloadLocation); request.TransferPreferences = TransferPreferences.AllowCellularAndBattery; request.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(OnBackgroundTransferStatusChanged); request.Tag = tag; try { _idMapping.Add(request.RequestId, callback); BackgroundTransferService.Add(request); } catch (InvalidOperationException) { _requests.Add(request); } }
private async Task CreateDownload(string source, IApiClient client, LocalItem localItem) { var existingRequest = BackgroundTransferService.Requests.FirstOrDefault(x => x.Tag != null && x.Tag.Contains(localItem.Id)); if (existingRequest != null) { return; } await _storageService.CreateDirectoryIfNotThere("AnyTime"); await _storageService.CreateDirectoryIfNotThere("Shared\\Transfers"); await _storageService.CreateDirectoryIfNotThere("Shared\\Transfers\\Sync"); var stringVersion = ApplicationManifest.Current.App.Version; var downloader = new BackgroundTransferRequest(new Uri(source, UriKind.Absolute)); downloader.Headers.Add("X-MediaBrowser-Token", client.AccessToken); var authorization = string.Format("MediaBrowser UserId=\"{0}\", Client=\"{1}\", Device=\"{2}\", DeviceId=\"{3}\", Version=\"{4}\"", client.CurrentUserId, client.ClientName, client.DeviceName, client.DeviceId, stringVersion); downloader.Headers.Add("Authorization", authorization); downloader.Method = "GET"; downloader.Tag = JsonConvert.SerializeObject(new JobData(localItem.Id, localItem.LocalPath, localItem.Item.Name, localItem.Item.Type)); var downloadLocation = new Uri(string.Format(Constants.AnyTime.DownloadLocation, localItem.Id), UriKind.RelativeOrAbsolute); downloader.DownloadLocation = downloadLocation; downloader.TransferStatusChanged += DownloaderOnTransferStatusChanged; if (BackgroundTransferService.Requests.Count() == 25) { // TODO: error or something var i = 1; } var complete = BackgroundTransferService.Requests.Where(x => x.TransferStatus == TransferStatus.Completed).ToList(); if (!complete.IsNullOrEmpty()) { foreach (var request in complete) { BackgroundTransferService.Remove(request); } } _transferService.Add(downloader); }
private void DownLoad_Click(object sender, RoutedEventArgs e) { // 传输的文件网络路径 Uri requestUri; try { requestUri = new Uri(fileUrl.Text, UriKind.RelativeOrAbsolute); } catch { MessageBox.Show("文件地址不符合格式"); return; } //设置文件下载地址 downloadPath = string.Format("shared/transfers/{0}.mp3", Guid.NewGuid()); //创建一个后台文件传输请求 _request = new BackgroundTransferRequest( requestUri) { Method = "GET",// 设置传输的方法为GET请求 DownloadLocation = new Uri(downloadPath, UriKind.Relative), Tag = "something else", //添加请求的Tag属性,Tag属性不能超过4000个字符 TransferPreferences = TransferPreferences.AllowBattery }; _request.TransferStatusChanged += _request_TransferStatusChanged; _request.TransferProgressChanged += _request_TransferProgressChanged; // 使用BackgroundTransferService添加文件传输请求 try { BackgroundTransferService.Add(_request); } catch (Exception ex) { MessageBox.Show("无法添加请求:" + ex.Message); } }
public AwaitableTransferRequest(BackgroundTransferRequest request, IProgress<ProgressValue> progress) { _request = request; _tcs = new TaskCompletionSource<object>(); Observable.FromEventPattern<BackgroundTransferEventArgs>( h => request.TransferProgressChanged += h, h => request.TransferProgressChanged -= h) .Select(args => args.EventArgs.Request) .Subscribe(r => { //TODO: handle uploading BytesSent (should be handled on higher level in Wrapper.ToUpload()) var progressValue = new ProgressValue((ulong) r.BytesReceived, (ulong) r.TotalBytesToReceive); this.Log().Debug("{0}: current {1}, total {2}", Path.GetFileName(r.RequestUri.OriginalString), progressValue.Current, progressValue.Total); progress?.Report(progressValue); }); Observable.FromEventPattern<BackgroundTransferEventArgs>( h => request.TransferStatusChanged += h, h => request.TransferStatusChanged -= h) .Select(p => p.EventArgs.Request) .StartWith(request) .Distinct(r => r.TransferStatus) .Subscribe(req => { if (req.TransferStatus == TransferStatus.Completed) { if (req.TransferError != null) _tcs.SetException(req.TransferError); else _tcs.SetResult(null); } else if (req.TransferStatus == TransferStatus.Unknown) { _tcs.SetException(new TransferStatusUnknownException()); } }); }