public async Task<nuint> DownloadFileAsync (Uri url, string destination) { this.Url = url.AbsoluteUri; if (downloadTask != null) return downloadTask.TaskIdentifier; if (session == null) { Initalize (); } Destination = destination; SessionId = session.Configuration.Identifier; if (!BackgroundDownloadManager.Tasks.TryGetValue (url.AbsoluteUri, out Tcs)) { Tcs = new TaskCompletionSource<bool> (); BackgroundDownloadManager.Tasks.Add (url.AbsoluteUri, Tcs); using (var request = new NSUrlRequest (new NSUrl (url.AbsoluteUri))) { downloadTask = session.CreateDownloadTask (request); downloadTask.Resume (); } } BackgroundDownloadManager.AddController (this.Url, this); await Tcs.Task; return downloadTask.TaskIdentifier; }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { if (!downloadTasks.ContainsKey(downloadTask.TaskIdentifier)) return; var cachedTaskInfo = downloadTasks[downloadTask.TaskIdentifier]; try { OnFileDownloadProgress(cachedTaskInfo.Index, 100f); var tmpLocation = location.Path; var dirName = Path.GetDirectoryName(cachedTaskInfo.DestinationDiskPath); if (!Directory.Exists(dirName)) Directory.CreateDirectory(dirName); if (File.Exists(cachedTaskInfo.DestinationDiskPath)) File.Delete(cachedTaskInfo.DestinationDiskPath); File.Move(tmpLocation, cachedTaskInfo.DestinationDiskPath); OnFileDownloadedSuccessfully(cachedTaskInfo.Index, cachedTaskInfo.DestinationDiskPath); CleanUpCachedTask(cachedTaskInfo); } catch (Exception exception) { OnError(cachedTaskInfo, new NSError(new NSString(exception.Message), 1)); } }
public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { if (downloadTasks.ContainsKey(downloadTask.TaskIdentifier)) { var index = downloadTasks[downloadTask.TaskIdentifier].Index; var progress = totalBytesWritten/(float) totalBytesExpectedToWrite; OnFileDownloadProgress(index, progress); } }
public override void DidWriteData (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { Console.WriteLine ("Set Progress"); if (downloadTask == controller.downloadTask) { float progress = totalBytesWritten / (float)totalBytesExpectedToWrite; Console.WriteLine (string.Format ("DownloadTask: {0} progress: {1}", downloadTask, progress)); InvokeOnMainThread( () => { controller.ProgressView.Progress = progress; }); } }
public override void DidFinishDownloading (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { CopyDownloadedImage (location); var message = new DownloadFinishedMessage () { FilePath = targetFileName, Url = downloadTask.OriginalRequest.Url.AbsoluteString }; MessagingCenter.Send<DownloadFinishedMessage> (message, "DownloadFinishedMessage"); }
void StartDownload() { if (downloadTask != null) return; using (var uri = NSUrl.FromString(_url)) using (var request = NSUrlRequest.FromUrl(uri)) { downloadTask = session.CreateDownloadTask(request); downloadTask.Resume(); } }
public override void DidWriteData (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { float percentage = (float)totalBytesWritten / (float)totalBytesExpectedToWrite; var message = new DownloadProgressMessage () { BytesWritten = bytesWritten, TotalBytesExpectedToWrite = totalBytesExpectedToWrite, TotalBytesWritten = totalBytesWritten, Percentage = percentage }; MessagingCenter.Send<DownloadProgressMessage> (message, "DownloadProgressMessage"); }
void Start(object sender, EventArgs e) { if (downloadTask != null) return; using (var url = NSUrl.FromString (DownloadUrlString)) using (var request = NSUrlRequest.FromUrl (url)) { downloadTask = session.CreateDownloadTask (request); downloadTask.Resume (); } imageView.Hidden = true; progressView.Hidden = false; }
void Start(object sender, EventArgs e) { if (task != null) return; using (var url = NSUrl.FromString (imgurl)) using (var request = NSUrlRequest.FromUrl (url)) { task = session.CreateDownloadTask (request); task.Resume (); } imgView.Hidden = true; prgView.Hidden = false; }
public async Task DownloadFileAsync (Uri url, string destination) { this.url = url.AbsoluteUri; if (downloadTask != null) return; if (session == null) session = InitBackgroundSession (); Destination = destination; if (!BackgroundDownloadManager.Tasks.TryGetValue (url.AbsoluteUri, out Tcs)) { Tcs = new TaskCompletionSource<bool> (); BackgroundDownloadManager.Tasks.Add (url.AbsoluteUri, Tcs); using (var request = new NSUrlRequest (new NSUrl (url.AbsoluteUri))) { downloadTask = session.CreateDownloadTask (request); downloadTask.Resume (); } } BackgroundDownloadManager.AddController (this.url, this); await Tcs.Task; }
/// <summary> /// Gets called if the download has been completed. /// </summary> public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { // The download location will be a file location. var sourceFile = location.Path; // Construct a destination file name. var destFile = downloadTask.OriginalRequest.Url.AbsoluteString.Substring(downloadTask.OriginalRequest.Url.AbsoluteString.LastIndexOf("/") + 1); Console.WriteLine ("DidFinishDownloading - Task: {0}, Source file: {1}", downloadTask.TaskIdentifier, sourceFile); // Copy over to documents folder. Note that we must use NSFileManager here! File.Copy() will not be able to access the source location. NSFileManager fileManager = NSFileManager.DefaultManager; // Create the filename var documentsFolderPath = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); NSUrl destinationURL = NSUrl.FromFilename(Path.Combine(documentsFolderPath, destFile)); // Update download info object. var downloadInfo = AppDelegate.GetDownloadInfoByTaskId (downloadTask.TaskIdentifier); // Remove any existing file in our destination NSError error; fileManager.Remove(destinationURL, out error); bool success = fileManager.Copy(sourceFile, destinationURL.Path, out error); if (success) { location = destinationURL; this.UpdateDownloadInfo (downloadInfo, DownloadInfo.STATUS.Completed, destinationURL); } else { this.UpdateDownloadInfo (downloadInfo, DownloadInfo.STATUS.Cancelled, null); Console.WriteLine ("Error during the copy: {0}", error.LocalizedDescription); } this.InvokeOnMainThread (() => this.controller.TableView.ReloadData()); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine ("Finished"); Console.WriteLine ("File downloaded in : {0}", location); NSFileManager fileManager = NSFileManager.DefaultManager; var URLs = fileManager.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); NSUrl documentsDictionry = URLs [0]; NSUrl originalURL = downloadTask.OriginalRequest.Url; NSUrl destinationURL = documentsDictionry.Append ("image1.png", false); NSError removeCopy; NSError errorCopy; fileManager.Remove (destinationURL, out removeCopy); bool success = fileManager.Copy (location, destinationURL, out errorCopy); if (success) { // we do not need to be on the main/UI thread to load the UIImage UIImage image = UIImage.FromFile (destinationURL.Path); InvokeOnMainThread (() => { controller.ImageView.Image = image; controller.ImageView.Hidden = false; controller.ProgressView.Hidden = true; }); } else { Console.WriteLine ("Error during the copy: {0}", errorCopy.LocalizedDescription); } }
public override void DidResume(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long resumeFileOffset, long expectedTotalBytes) { this.logger.LogDebug("DidResume"); this.onEvent.OnNext(downloadTask.FromNative()); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask task, NSUrl location) { Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading"); Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading Session : {0}", session.Description); Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading Task : {0}", task.Description); Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading Location : {0}", location.Path); _bus.SendAsync <FreeSlot> (new FreeSlot()); var staskdescription = task.TaskDescription; if (staskdescription == null) { Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading NullTaskId"); _bus.SendAsync <DownloadError> (new DownloadError { Error = ErrorEnum.DidFinishDownloading_NullTaskId }); return; } int taskid; if (!int.TryParse(staskdescription, out taskid)) { Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading InvalidTaskId"); _bus.SendAsync <DownloadError> (new DownloadError { Error = ErrorEnum.DidFinishDownloading_InvalidTaskId }); return; } var response = task.Response as NSHttpUrlResponse; if (response == null) { Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading NullResponse"); _bus.SendAsync <DownloadError> (new DownloadError { Error = ErrorEnum.DidFinishDownloading_NullResponse }); return; } int statuscode = (int)response.StatusCode; if (statuscode != 200) { Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading StatusCode"); Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading StatusCode : {0}", statuscode); _bus.SendAsync <TaskError> (new TaskError { Id = taskid, Error = TaskErrorEnum.InvalidResponse, StatusCode = (int)response.StatusCode, }); return; } string path = location == null ? null : location.Path; AutoResetEvent temporaryfilelock = new AutoResetEvent(false); _bus.SendAsync <FinishedDownload> (new FinishedDownload { Id = taskid, Location = path, FileLock = temporaryfilelock }); temporaryfilelock.WaitOne(); }
//public override void DidBecomeInvalid(NSUrlSession session, NSError error) // Console.WriteLine("Session became invalid"); public override void DidResume(NSUrlSession session, NSUrlSessionDownloadTask task, long resumeFileOffset, long expectedTotalBytes) => this.DoAction(task, item => item.SetResumeOffset(resumeFileOffset, expectedTotalBytes));
public override void DidWriteData (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { float progress = totalBytesWritten / (float)totalBytesExpectedToWrite; Console.WriteLine (string.Format ("DownloadTask: {0} progress: {1}", downloadTask.Handle.ToString (), progress)); BackgroundDownloadManager.UpdateProgress (downloadTask, progress); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask task, NSUrl location) => this.DoAction(task, item => { this.tasks.Remove(item.Identifier); item.SetDownloadComplete(location.Path); });
internal static void UpdateProgress(NSUrlSessionDownloadTask downloadTask, float progress) { try{ var url = downloadTask.OriginalRequest.Url.AbsoluteString; DownloadTasks [url] = downloadTask; UpdateProgress (url, progress); Files[url].Percent = progress; } catch(Exception ex) { Console.WriteLine (ex); } }
void ProcessRequest() { try { StringBuilder requestUri = new StringBuilder(); requestUri.AppendFormat("{0}{1}{2}/{3}", base.BaseUri, (base.BaseUri.ToString().EndsWith("/")) ? string.Empty : "/", Uri.EscapeUriString(base.ScopeName), _wrapper.CacheRequest.RequestType.ToString()); string prefix = "?"; // Add the scope params if any foreach (KeyValuePair <string, string> kvp in _scopeParameters) { requestUri.AppendFormat("{0}{1}={2}", prefix, Uri.EscapeUriString(kvp.Key), Uri.EscapeUriString(kvp.Value)); if (prefix.Equals("?")) { prefix = "&"; } } // Create the WebRequest NSMutableUrlRequest webRequest = new NSMutableUrlRequest(new NSUrl(requestUri.ToString())); if (this._credentials != null) { NetworkCredential credential = this._credentials.GetCredential(BaseUri, "Basic"); string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(credential.UserName + ":" + credential.Password)); webRequest ["Authorization"] = "Basic " + svcCredentials; webRequest ["configname"] = _behaviors.ConfigName; webRequest ["configversion"] = _behaviors.ConfigVersion; webRequest ["coreversion"] = _behaviors.CoreVersion.ToString(); } else { throw new Exception("Credentials is null"); } foreach (var item in _behaviors.DeviceInfo) { webRequest [item.Key] = item.Value; } webRequest.HttpMethod = "POST"; webRequest ["Accept"] = (base.SerializationFormat == SerializationFormat.ODataAtom) ? "application/atom+xml" : "application/json"; webRequest ["Content-Type"] = (base.SerializationFormat == SerializationFormat.ODataAtom) ? "application/atom+xml" : "application/json"; webRequest ["Accept-Encoding"] = "gzip, deflate"; webRequest.TimeoutInterval = TIMEOUT; webRequest.Body = CreateRequestBody(); _wrapper.WebRequest = webRequest; if (_wrapper.CacheRequest.RequestType == CacheRequestType.UploadChanges) { lock (_lockObject) { _currentTask = CreateUploadSession().CreateDownloadTask(webRequest); _currentTask.Resume(); } } else { lock (_lockObject) { _currentTask = CreateDownloadSession().CreateDownloadTask(webRequest); _currentTask.Resume(); } } } catch (Exception e) { if (ExceptionUtility.IsFatal(e)) { throw; } _wrapper.Error = e; _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper); } }
public void DidFinishDownloading (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine ($"NSURLSession finished to url: {location}"); UpdateLabel (); ScheduleSnapshot (); }
public static void Errored(NSUrlSessionDownloadTask downloadTask) { BackgroundDownloadFile download; var url = downloadTask.OriginalRequest.Url.AbsoluteString; if (!Files.TryGetValue (url, out download)) return; if (DownloadError != null) DownloadError (download); RemoveUrl (url); }
partial void Start (UIButton sender) { if (downloadTask != null) return; using (var url = NSUrl.FromString (DownloadUrlString)) using (var request = NSUrlRequest.FromUrl (url)) { downloadTask = session.CreateDownloadTask (request); downloadTask.Resume (); } }
void HandleNSUrlSessionPendingTasks(NSUrlSessionDataTask[] dataTasks, NSUrlSessionUploadTask[] uploadTasks, NSUrlSessionDownloadTask[] downloadTasks) { // SAMCTODO foreach (var t in uploadTasks) { } foreach (var t in downloadTasks){ } foreach (var t in dataTasks) { } }
public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { float progress = (totalBytesWritten / (float)totalBytesExpectedToWrite) * 100; Console.WriteLine(string.Format("progress: {0}%", progress)); }
public override void DidResume(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long resumeFileOffset, long expectedTotalBytes) { System.Diagnostics.Debug.WriteLine("DidResume"); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { }
public BackgroundDownload (NSUrlSessionDownloadTask task) { downloadTask = task; Url = task.OriginalRequest.Url.AbsoluteString; }
public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { var percentage = totalBytesWritten / totalBytesExpectedToWrite; }
public override void DidWriteData (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { _progress((int)totalBytesExpectedToWrite, (int)totalBytesWritten); }
/// <summary> /// Gets triggered if one of the buttons of a cell in the table view was touched. /// </summary> /// <param name="cell">Cell.</param> /// <param name="button">Button.</param> /// <param name="action">Action.</param> async void HandleActionRequested(DownloaderCell cell, UIButton button, DownloaderCell.TRANSFER_ACTION action) { // Get the index of the cell in the table view. var path = this.TableView.IndexPathForCell(cell); if (path == null) { return; } int index = path.Row; // Get the related download info object. var downloadInfo = AppDelegate.AvailableDownloads[index]; // Via the task identifier we can get back to the enqueued task. var pendingTasks = await this.Session.GetTasksAsync(); NSUrlSessionDownloadTask downloadTask = pendingTasks.DownloadTasks.FirstOrDefault(t => t.TaskIdentifier == downloadInfo.TaskId); switch (action) { case DownloaderCell.TRANSFER_ACTION.Download: Console.WriteLine("Creating new download task."); // Create a new download task. downloadTask = this.Session.CreateDownloadTask(NSUrl.FromString(downloadInfo.Source)); // The creation can fail. if (downloadTask == null) { new UIAlertView(string.Empty, "Failed to create download task! Please retry.", null, "OK").Show(); return; } // Update the download info object. downloadInfo.TaskId = (int)downloadTask.TaskIdentifier; downloadInfo.Status = DownloadInfo.STATUS.Downloading; // Resume / start the download. downloadTask.Resume(); Console.WriteLine("Starting download of '{0}'. State of task: '{1}'. ID: '{2}'", downloadInfo.Title, downloadTask.State, downloadTask.TaskIdentifier); /* * // If this code is commented in, the app will exit immediately after the downlaod has been initiated. * // When the download completes, iOS will relaunch the app and the UI will reflect the current state. * AppDelegate.SerializeAvailableDownloads (); * Exit (3); */ break; case DownloaderCell.TRANSFER_ACTION.Stop: if (downloadTask != null) { downloadTask.Cancel(); } downloadInfo.Reset(); downloadInfo.Status = DownloadInfo.STATUS.Cancelled; Console.WriteLine("Stopping download of '{0}'.", downloadInfo.Title); break; case DownloaderCell.TRANSFER_ACTION.View: break; } // Update UI. cell.UpdateFromDownloadInfo(downloadInfo); }
public override void DidFinishDownloading (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine ("File downloaded in : {0}", location); BackgroundDownloadManager.Completed (downloadTask, location); }
public override void DidFinishDownloading (NSUrlSession session, NSUrlSessionDownloadTask task, NSUrl location) { Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading"); Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading Session : {0}", session.Description); Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading Task : {0}", task.Description); Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading Location : {0}", location.Path); _bus.SendAsync<FreeSlot> (new FreeSlot()); var staskdescription = task.TaskDescription; if (staskdescription == null) { Console.WriteLine("[NSUrlSessionManager] DidFinishDownloading NullTaskId"); _bus.SendAsync<DownloadError> (new DownloadError { Error = ErrorEnum.DidFinishDownloading_NullTaskId }); return; } int taskid; if (!int.TryParse (staskdescription, out taskid)) { Console.WriteLine ("[NSUrlSessionManager] DidFinishDownloading InvalidTaskId"); _bus.SendAsync<DownloadError> (new DownloadError { Error = ErrorEnum.DidFinishDownloading_InvalidTaskId }); return; } var response = task.Response as NSHttpUrlResponse; if (response == null) { Console.WriteLine ("[NSUrlSessionManager] DidFinishDownloading NullResponse"); _bus.SendAsync<DownloadError> (new DownloadError { Error = ErrorEnum.DidFinishDownloading_NullResponse }); return; } int statuscode = (int)response.StatusCode; if (statuscode != 200) { Console.WriteLine ("[NSUrlSessionManager] DidFinishDownloading StatusCode"); Console.WriteLine ("[NSUrlSessionManager] DidFinishDownloading StatusCode : {0}", statuscode); _bus.SendAsync<TaskError> (new TaskError { Id = taskid, Error = TaskErrorEnum.InvalidResponse, StatusCode = (int)response.StatusCode, }); return; } string path = location == null ? null : location.Path; AutoResetEvent temporaryfilelock = new AutoResetEvent (false); _bus.SendAsync<FinishedDownload> (new FinishedDownload { Id = taskid, Location = path, FileLock = temporaryfilelock }); temporaryfilelock.WaitOne (); }
public void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine($"NSURLSession finished to url: {location}"); UpdateLabel(); ScheduleSnapshot(); }
public override void DidWriteData (NSUrlSession session, NSUrlSessionDownloadTask task, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { Console.WriteLine("[NSUrlSessionManager] DidWriteData"); Console.WriteLine("[NSUrlSessionManager] DidWriteData Task : {0}", task.Description); Console.WriteLine("[NSUrlSessionManager] DidWriteData Session : {0}", session.Description); Console.WriteLine("[NSUrlSessionManager] DidWriteData Written : {0}", bytesWritten); Console.WriteLine("[NSUrlSessionManager] DidWriteData Total : {0}", totalBytesWritten); Console.WriteLine("[NSUrlSessionManager] DidWriteData Expected : {0}", totalBytesExpectedToWrite); var staskdescription = task.TaskDescription; if (staskdescription == null) { Console.WriteLine("[NSUrlSessionManager] DidWriteData NullTaskId"); _bus.SendAsync<DownloadError> (new DownloadError { Error = ErrorEnum.DidWriteData_NullTaskId }); return; } int taskid; if (!int.TryParse (staskdescription, out taskid)) { Console.WriteLine("[NSUrlSessionManager] DidWriteData InvalidTaskId"); _bus.SendAsync<DownloadError> (new DownloadError { Error = ErrorEnum.DidWriteData_InvalidTaskId }); return; } _bus.SendAsync<ProgressDownload> (new ProgressDownload { Id = taskid, Total = Math.Max(totalBytesExpectedToWrite, totalBytesWritten) , Written = totalBytesWritten }); }
public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { this.logger.LogDebug("DidWriteData"); this.onEvent.OnNext(downloadTask.FromNative()); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { OnDownloadCompleted(location.ToString(), downloadTask.TaskDescription ?? ""); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("DidFinishDownloading: {0} {1} {2}", session, downloadTask, location); }
public void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("Downloaded to location " + location); }
// This is for Download public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("Downloading Completed For {0}", downloadTask.TaskIdentifier); }
void ProcessRequest() { try { var requestUri = new StringBuilder(); requestUri.AppendFormat("{0}{1}{2}/{3}", BaseUri, (BaseUri.ToString().EndsWith("/")) ? string.Empty : "/", Uri.EscapeUriString(ScopeName), _wrapper.CacheRequest.RequestType.ToString()); string prefix = "?"; // Add the scope params if any foreach (KeyValuePair<string, string> kvp in _scopeParameters) { requestUri.AppendFormat("{0}{1}={2}", prefix, Uri.EscapeUriString(kvp.Key), Uri.EscapeUriString(kvp.Value)); if (prefix.Equals("?")) { prefix = "&"; } } // Create the WebRequest var webRequest = new NSMutableUrlRequest(new NSUrl(requestUri.ToString())); if (_credentials != null) { NetworkCredential credential = _credentials.GetCredential(BaseUri, "Basic"); string svcCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credential.UserName + ":" + credential.Password)); webRequest["Authorization"] = "Basic " + svcCredentials; webRequest["configname"] = _behaviors.ConfigName; webRequest["configversion"] = _behaviors.ConfigVersion; webRequest["coreversion"] = _behaviors.CoreVersion.ToString(); } else throw new Exception("Credentials is null"); foreach (var item in _behaviors.DeviceInfo) webRequest[item.Key] = item.Value; webRequest.HttpMethod = "POST"; webRequest["Accept"] = ApplicationContext.Current.Settings.BitMobileFormatterDisabled ? "application/atom+xml" : "application/bitmobile"; webRequest["Content-Type"] = ApplicationContext.Current.Settings.BitMobileFormatterDisabled ? "application/atom+xml" : "application/bitmobile"; webRequest["Accept-Encoding"] = "gzip, deflate"; webRequest.TimeoutInterval = Timeout; webRequest.Body = CreateRequestBody(); _wrapper.WebRequest = webRequest; if (_wrapper.CacheRequest.RequestType == CacheRequestType.UploadChanges) { lock (_lockObject) { _currentTask = CreateUploadSession().CreateDownloadTask(webRequest); _currentTask.Resume(); } } else { lock (_lockObject) { _currentTask = CreateDownloadSession().CreateDownloadTask(webRequest); _currentTask.Resume(); } } } catch (Exception e) { if (ExceptionUtility.IsFatal(e)) throw; _wrapper.Error = e; _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper); } }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { try { Logger.Log("INFO: DidFinishDownloading: " + downloadTask.OriginalRequest.Url.ToString()); string itemID = string.Empty; string destinationPath = ItemDownloader.DownloaderPath + Path.DirectorySeparatorChar + downloadTask.OriginalRequest.Url.LastPathComponent; string fileName = downloadTask.Response.SuggestedFilename; string title = downloadTask.Response.SuggestedFilename; var downloadItem = DownloadSessionMetadata.GetDownloadItem(downloadTask.OriginalRequest.Url.ToString()); if ((downloadItem != null) && (downloadItem.FileName != null)) { if (string.IsNullOrEmpty(fileName)) { fileName = downloadItem.FileName; } itemID = downloadItem.Id; if (!string.IsNullOrEmpty(downloadItem.FileName)) { title = downloadItem.FileName.Replace(".mp4", string.Empty); } DownloadSessionMetadata.RemoveDownloadItem(downloadTask.OriginalRequest.Url.ToString()); } string filter = "\\/:*?\"<>|#"; string filteredFileName = new string(fileName.Where(c => filter.IndexOf(c) < 0).ToArray()); destinationPath = ItemDownloader.DownloaderPath + Path.DirectorySeparatorChar + filteredFileName; NSError error = null; Exception exception = null; if (NSFileManager.DefaultManager.FileExists(destinationPath)) { NSFileManager.DefaultManager.Remove(destinationPath, out error); } bool isCustomError = false; var success = NSFileManager.DefaultManager.Move(location, NSUrl.FromFilename(destinationPath), out error); if (!success) { exception = new Exception(error.LocalizedDescription); } else { NSFileManager.SetSkipBackupAttribute(destinationPath, true); if (!LocalLibraryService.Instance.CanReadRecordingMetadata(destinationPath)) { isCustomError = true; Logger.Log("ERROR: DidFinishDownloading: Unable to read the file metadata"); exception = new Exception("We are sorry, but there is a technical issue preventing PlayOn Cloud from downloading or playing your recording. Please report this issue to our support team through this app's Account tab."); } } DownloadProgress progress = new DownloadProgress() { Status = success ? DownloadStatus.Completed : DownloadStatus.Failed, Id = itemID, Title = title, LocalFilePath = destinationPath, Url = downloadTask.OriginalRequest.Url.ToString(), IsCustomError = isCustomError }; Logger.Log("INFO: DidFinishDownloading: ID: " + progress.Id + ". Exception: " + exception); if (itemDownloader != null) { InvokeOnMainThread(() => itemDownloader.Fire_DownloadComplete(new AsyncCompletedEventArgs(exception, false, progress))); } } catch (Exception ex) { Logger.Log("ERROR: DidFinishDownloading: " + ex); } }
public override void DidResume(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long resumeFileOffset, long expectedTotalBytes) { Console.WriteLine("Downloading Resumed For {0}", downloadTask.TaskIdentifier); }
public override void DidResume (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long resumeFileOffset, long expectedTotalBytes) { Console.WriteLine("[NSUrlSessionManager] DidResume"); }
// download public override void DidWriteData(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) { }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine("File downloaded in : {0}", location); BackgroundDownloadManager.Completed(downloadTask, location); }
public override void DidResume(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long resumeFileOffset, long expectedTotalBytes) { }
public override void DidBecomeDownloadTask(NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlSessionDownloadTask downloadTask) { System.Diagnostics.Debug.WriteLine("DidBecomeDownloadTask"); }
public override void DidFinishDownloading (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { _uploadCompleted (this, new NSUrlEventArgs (location.ToString ())); }
public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { _uploadCompleted(this, new NSUrlEventArgs(location.ToString())); }
public void DidResume(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long resumeFileOffset, long expectedTotalBytes) { Console.WriteLine("DidResume"); }
async static void restoreTasks(NSUrlSession ses, NSUrlSessionDataTask[] sessions, NSUrlSessionUploadTask[] uploads, NSUrlSessionDownloadTask[] downloads) { List<BackgroundDownload> restoredDownloads = new List<BackgroundDownload>(); foreach(var d in downloads) { var url = d.OriginalRequest.Url.AbsoluteString; if(d.Error != null) { BackgroundDownloadManager.Errored(d); } BackgroundDownload download; BackgroundDownloadManager.BackgroundDownloadFile downloadFile; download = new BackgroundDownload (d) { SessionId = ses.Configuration.Identifier, }; foreach(var key in BackgroundDownloadManager.Files) { Console.WriteLine(key.Key); } if(BackgroundDownloadManager.Files.TryGetValue(url, out downloadFile)) download.Destination = downloadFile.Destination; BackgroundDownloadManager.AddController (url, download); restoredDownloads.Add(download); } if(RestoredDownloads != null) { RestoredDownloads(restoredDownloads); } }