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; } }
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); } }
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()); } }
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); } }
/// <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); }
void BTR_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) { if (e.Request.TransferStatus == TransferStatus.Completed) { Uploading = false; if (e.Request.StatusCode == 200) { using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (iso.FileExists(SAVE_RESPONSE_LOCATION)) { IsolatedStorageFileStream fs = new IsolatedStorageFileStream(SAVE_RESPONSE_LOCATION, System.IO.FileMode.Open, iso); //byte[] buffer = new byte[fs.Length]; //fs.Read(buffer, 0, (int)fs.Length); StreamReader str = new StreamReader(fs); string resp = str.ReadToEnd(); fs.Close(); JsonObject jobj = (JsonObject)SimpleJson.DeserializeObject(resp); string userid; IsolatedStorageSettings.ApplicationSettings.TryGetValue("userid", out userid); if (userid != null) { _heroku.AddBackup(jobj["key"].ToString(), jobj["url"].ToString(), userid); } iso.DeleteFile(SAVE_RESPONSE_LOCATION); _uploadCallback.Invoke(new AsyncCallbackEvent("success")); } } } BackgroundTransferService.Remove(e.Request); } Debug.WriteLine(e.Request.TransferStatus); }
void BTR_Download_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) { if (e.Request.TransferStatus == TransferStatus.Completed) { Downloading = false; if (e.Request.StatusCode == 200) { using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (iso.FileExists(DOWNLOAD_LOCATION)) { iso.CopyFile(DOWNLOAD_LOCATION, "/cars.sdf", true); } } string DBConnectionString = "Data Source=isostore:/cars.sdf"; App.ViewModel.Database.Dispose(); /* * App.ViewModel.Database.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues,App.ViewModel.Database.carInfo); * App.ViewModel.Database.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, App.ViewModel.Database.fuelInfo); * App.ViewModel.Database.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, App.ViewModel.Database.maintInfo); * App.ViewModel.Database.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, App.ViewModel.Database.settingsInfo); */ App.ViewModel = new Data(DBConnectionString); } BackgroundTransferService.Remove(e.Request); } Debug.WriteLine(e.Request.TransferStatus); Debug.WriteLine("downloaded-" + e.Request.BytesReceived); }
//=================================== blob 相关函数定义 private void downloadECG(string filename) { if (_currentRequest != null) { BackgroundTransferService.Remove(_currentRequest); } //解析文件名,赋给SAVE_LOCATION // filename = "634708322772702206"; SAVE_LOCATION = SAVE_LOCATION + filename; Uri saveLocationUri = new Uri(SAVE_LOCATION, UriKind.RelativeOrAbsolute); //向服务器请求sas // string patient var http = new Http(); long A = System.DateTime.Today.Ticks; string uri = "http://echelper.cloudapp.net/Service.svc/doctor/liaomin/downloadrequest?" + A; http.StartRequest(@uri, result => { // A = result; // x = 1; // getfinished = false; Dispatcher.BeginInvoke(() => GetSas(result)); }); }
public void RequestStart() { try { BackgroundTransferService.Add(_request); } catch (ArgumentNullException err) { Debug.WriteLine("The request argument cannot be null."); Debug.WriteLine(err); ErrorMessage = "Invalid request"; State = TransferRequestState.Failed; StatusText = ControlResources.StatusFailed; } catch (InvalidOperationException err) { Debug.WriteLine("The request has already been submitted."); Debug.WriteLine(err); ErrorMessage = "The request has already been submitted."; State = TransferRequestState.Failed; } catch (SystemException err) { Debug.WriteLine("The maximum number of requests on the device has been reached."); Debug.WriteLine(err); ErrorMessage = "The maximum number of requests on the device has been reached."; State = TransferRequestState.Failed; StatusText = ControlResources.StatusFailed; } }
/// <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); }
/// <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); } }
/// <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) { } } } }
public static void RemoveAllRequests() { foreach (var request in BackgroundTransferService.Requests) { BackgroundTransferService.Remove(request); } }
void OnBackgroundTransferStatusChanged(object sender, BackgroundTransferEventArgs e) { if (e.Request.TransferStatus == TransferStatus.Completed) { BackgroundTransferService.Remove(e.Request); if (_idMapping.ContainsKey(e.Request.RequestId)) { _idMapping[e.Request.RequestId].Invoke(e.Request); _idMapping.Remove(e.Request.RequestId); } // Check if there are pending downloads, if there are then queue them up with background transfer service now. if (_requests.Count > 0) { try { BackgroundTransferService.Add(_requests[0]); _requests.RemoveAt(0); } catch (InvalidOperationException) { } } } }
void current_request_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) { switch (e.Request.TransferStatus) { case TransferStatus.Completed: if (e.Request.StatusCode != 0) { string[] filename = e.Request.Tag.Split('|'); ISOHelper.MoveFileOverwrite(e.Request.DownloadLocation.OriginalString, filename[0]); BackgroundTransferService.Remove(e.Request); } long totaldata = 0; long session_data = 0; IsolatedStorageSettings.ApplicationSettings.TryGetValue("total_data", out totaldata); totaldata += e.Request.BytesReceived / 1024 / 1024; IsolatedStorageSettings.ApplicationSettings["total_data"] = totaldata; IsolatedStorageSettings.ApplicationSettings.TryGetValue("session_data", out session_data); session_data += e.Request.BytesReceived / 1024 / 1024; IsolatedStorageSettings.ApplicationSettings["session_data"] = session_data; IsolatedStorageSettings.ApplicationSettings.Save(); if (!Cancelled) { //RaiseCompleted(new FileDownloadEvntArgs("Completed")); Message.SetMessage("Downloading complete"); } if (SOURCES.Count == 0) { //RaiseSyncChange(new FileDownloadEvntArgs("Completed")); Message.SetMessage("Downloading complete"); } break; } }
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; } }
void GlobalOfflineSync_Ready(object sender, FileDownloadEvntArgs e) { OfflineSyncExt sync = (OfflineSyncExt)sender; if (!GlobalOfflineSync.Cancelled) { BackgroundTransferService.Add(sync.BACKGROUND_REQUEST); } }
private void GetSas(string result) { XmlSerializer serializer = new XmlSerializer(typeof(string)); result = "<root>" + result + "</root>"; XDocument document = XDocument.Parse(result); sas = document.Root.Value; // ECGName = "634708322772702206"; string fileDownload = "https://echelperspace.blob.core.windows.net/" + Patientid + "/" + ECGName + "/" + sas; // Uri fileDownloadUri = new Uri("https://echelperspace.blob.core.windows.net/{patientuser}/{filename}+{sas}"); Uri fileDownloadUri = new Uri(fileDownload); using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStore.DirectoryExists("shared/transfers")) { isoStore.CreateDirectory("shared/transfers"); } } //解析文件名,赋给SAVE_LOCATION // SAVE_LOCATION = SAVE_LOCATION + filename; Uri saveLocationUri = new Uri(SAVE_LOCATION, UriKind.RelativeOrAbsolute); using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (userStore.FileExists(SAVE_LOCATION)) { userStore.DeleteFile(SAVE_LOCATION); } } _currentRequest = new BackgroundTransferRequest(fileDownloadUri, saveLocationUri); _currentRequest.Method = "GET"; _currentRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery; // try //{ foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests) { BackgroundTransferService.Remove(request); } BackgroundTransferService.Add(_currentRequest); InitializeTransferRequestEventHandlers(); // } ////catch (InvalidOperationException) //{ // textBlock_Status.Text = "wocao"; //} //sas = (string)serializer.Deserialize(document.CreateReader()); }
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; } }
protected void CancelAll() { var requests = BackgroundTransferService.Requests; foreach (var request in requests) { BackgroundTransferService.Remove(request); request.Dispose(); } }
// 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(); } }
internal void FinalizeRequests() { foreach (var request in BackgroundTransferService.Requests) { if (request.TransferStatus == TransferStatus.Completed) { BackgroundTransferService.Remove(request); } } }
public void CancellAll() { //RaiseSyncChange(new FileDownloadEvntArgs("Syncing Cancelled")); foreach (var t in BackgroundTransferService.Requests) { BackgroundTransferService.Remove(t); } Cancelled = true; Message.SetMessage("Downloading cancelled."); }
public void Dispose() { foreach (var request in BackgroundTransferService.Requests) { if (request.TransferStatus == TransferStatus.Completed) { BackgroundTransferService.Remove(request); } } }
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); } } }
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 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(); } }
public override void Cancel() { try { BackgroundTransferService.Remove(Request); Request.Dispose(); } catch (InvalidOperationException) { // request is alreadty completed/ cancelled } }
public bool Abort() { BackgroundTransferRequest request = BackgroundTransferService.Find(requestId); if (request != null) { isAborted = true; BackgroundTransferService.Remove(request); } return(request != null); }
private static void SafeRemoveRequest(BackgroundTransferRequest request) { try { BackgroundTransferService.Remove(request); } catch { } try { request.Dispose(); } catch { } }