private void UpdateTimeEstimate(DownloadInfoWrapper wrapper, int percent) { if (wrapper == null) return; if (percent <= 0) return; var elapsed = DateTime.UtcNow.Subtract(wrapper.StartTime); var ticksPerPercent = elapsed.Ticks / percent; var totalTicks = ticksPerPercent * 100; var remainingTicks = totalTicks - elapsed.Ticks; var timeRemaining = new TimeSpan(remainingTicks); string message; if (timeRemaining.TotalMinutes <= 60) message = timeRemaining.TotalMinutes <= 1 ? "About 1 minute remains" : string.Format("About {0} minutes remain", timeRemaining.TotalMinutes); else if (timeRemaining.TotalMinutes > 60) message = "Over an hour remains"; else message = "About 1 hour remains"; UpdateTimeEstimate(message); }
protected virtual IResult DownloadFileAsync(FileInfoWrapper info) { try { using (var client = new ConfigurableWebClient { KeepAlive = false }) { var targetPath = PathUtilities.DownloadFolder; if (!Directory.Exists(targetPath)) return new DirectoryNotFound { Target = targetPath }; var uri = GetDownloadUri(info); if (uri == null) return new CouldNotDownloadFile { Issue = "Could not determine host target", Target = info.FileName }; client.Credentials = GetDownloadCredentials(uri); client.DownloadFileCompleted += DownloadCompletedHandler; client.DownloadProgressChanged += DownloadProgressHandler; _completed = false; if (string.IsNullOrWhiteSpace(info.FileName)) return new CouldNotDownloadFile { Issue = "Could not determine local target", Target = info.FileName }; if (string.IsNullOrWhiteSpace(DisplayName)) DisplayName = info.FileName; targetPath = Path.Combine(targetPath, info.FileName); var resultWrapper = new DownloadInfoWrapper { DisplayName = DisplayName, Result = new NextResult(), StartTime = DateTime.UtcNow }; client.Headers.Add(HttpRequestHeader.UserAgent, string.Format("{0} {1}", Application.Current.GetProductName(), Application.Current.GetVersion())); InterveneIfConnectionLost(); client.DownloadFileAsync(uri, targetPath, resultWrapper); do { Thread.Sleep(5); Application.Current.DoEvents(); // check for cancel _cancelRequested = CancelRequested(); if (!_cancelRequested) continue; // handle cancel stuff client.CancelAsync(); _cancelRequested = true; SetCancelMessages(); } while (_completed == false); UserInterfaceUtilities.WaitForMilliseconds(DateTime.UtcNow, 250); UpdateProgressPercent(100); UpdateTimeEstimate(""); UpdateProgressText(resultWrapper.Result.IsOk() ? "Download complete!" : "Download failed!"); return resultWrapper.Result; } } catch (Exception e) { return new ExceptionOccurred(e); } }