private void SetTextForDownloadState(DownloadState state) { switch (state) { case DownloadState.Complete: if (level == null) { level = SongUtils.masterLevelList.FirstOrDefault(x => x.levelID == parameters.Beatmap.LevelId); } songNameText.text = level?.songName; songDetailsText.text = level?.songAuthorName; songDetailsText.richText = true; if (!string.IsNullOrEmpty(level?.levelAuthorName)) { songDetailsText.text += $" <size=80%>[{level?.levelAuthorName}]</size>"; } break; case DownloadState.InProgress: songNameText.text = "Loading..."; break; case DownloadState.Failed: songNameText.text = "Download Error"; break; } }
public async Task Stop() { Task initTask; Task startTask; lock (_monitorState) { initTask = _initTask?.Task; startTask = _startTask?.Task; switch (State) { case DownloadState.Finished: case DownloadState.Stopped: case DownloadState.Error: return; } State = DownloadState.Stopping; _cancellationTokenSource?.Cancel(); } if (initTask != null) { await initTask.ConfigureAwait(false); } if (startTask != null) { await initTask.ConfigureAwait(false); } State = DownloadState.Stopped; }
protected void RaiseDownloadProgress(long bytes, DownloadState state) { if (DownloadProgress != null) { DownloadProgress(this, new DownloadProgressEventArgs(bytes, state)); } }
public AbstractDownload(Uri url, int bufferSize, long?offset, long?maxReadBytes, IWebRequestBuilder requestBuilder, IDownloadChecker downloadChecker) { if (url == null) { throw new ArgumentNullException("url"); } if (bufferSize < 0) { throw new ArgumentException("bufferSize < 0"); } if (offset.HasValue && offset.Value < 0) { throw new ArgumentException("offset < 0"); } if (maxReadBytes.HasValue && maxReadBytes.Value < 0) { throw new ArgumentException("maxReadBytes < 0"); } this.url = url; this.bufferSize = bufferSize; this.offset = offset; this.maxReadBytes = maxReadBytes; this.requestBuilder = requestBuilder; this.downloadChecker = downloadChecker; this.state = DownloadState.Initialized; }
private static void DownloadCompleted(object sender, DownloadDataCompletedEventArgs e) { DownloadState state = e.UserState as DownloadState; state.Stream.Write(e.Result, 0, e.Result.Length); state.Complete = true; }
public void SetDownloadState(DownloadState downloadState) { lock (_downloadStateLockObject) { DownloadState = downloadState; } }
private void UpdateStatus(Feed downloadItems, Feed entry, DownloadState downloadState, double percentage) { try { switch (downloadState) { case DownloadState.AllStart: ProgressBar.Value = 0; break; case DownloadState.AllFinished: Log.Text = "DONE!"; ProgressBar.Value = 0; downloadItems.Entries.Clear(); return; case DownloadState.UpdateCache: _cacheManager.Save(); return; case DownloadState.DownloadProgressChanged: ProgressBar.Value = percentage; break; case DownloadState.TitleChanged: MixpanelTrack("Download", new { entry.Title, Guid = _settings.ApplicationConfiguration.Guid }); break; } Log.Text = (entry != null) ? entry.ToString() : ""; } catch {} }
/// <summary> /// creates the new download /// </summary> public void Create() { State = DownloadState.Create; try { //set the download parameters DwnlSize = FindFileSize(); ChunkCount = FindChunkCount(); //create a temp directory for chunks if (!Directory.Exists(Path.GetDirectoryName(ChunkTarget))) { Directory.CreateDirectory(Path.GetDirectoryName(ChunkTarget)); } //idle when no job is there State = DownloadState.Idle; } catch (Exception e) { //save the error DwnlException = e; State = DownloadState.Error; } }
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e) { if (State == DownloadState.Restart) { State = DownloadState.InQueue; Start(); return; } DownloadFileCompleted?.Invoke(this, e); if (State == DownloadState.InQueue) { return; } _webClient.DownloadFileCompleted -= DownloadCompleted; if (State == DownloadState.Cancelled) { try { File.Delete(DestinationalFile); } catch (Exception fileError) { ErrorMessage = fileError.Message; State = DownloadState.HasError; return; } return; } State = e.Error != null ? DownloadState.HasError : DownloadState.Completed; }
private void OnDownloadStatusChange(Feed downloadList, Feed entry, DownloadState downloadState, double percentage) { if (Entries.Count <= 0 || _onStatusChanged == null) return; if (downloadState == DownloadState.Deleted) { _settings.SaveDownloadLists(this); UpdateStatus(downloadList, entry, DownloadState.AllFinished, 100.0); return; } var finishedCount = 0; var average = 0.0; foreach (var en in Entries) { if (en.DownloadState == DownloadState.AllFinished) finishedCount++; average += en.Percentage; } average = average/Entries.Count; if (downloadState == DownloadState.DownloadProgressChanged) UpdateStatus(downloadList, entry, DownloadState.DownloadProgressChanged, average); else if (finishedCount == Entries.Count) UpdateStatus(downloadList, entry, DownloadState.AllFinished, 100.0); else if (Entries.Count == 1 && downloadState == DownloadState.AllStart) UpdateStatus(downloadList, entry, DownloadState.AllStart, 0.0); else if(_onStatusChanged != null && !(downloadState == DownloadState.AllFinished || downloadState == DownloadState.AllStart || downloadState == DownloadState.DownloadProgressChanged )) _onStatusChanged(downloadList, entry, downloadState, percentage); _settings.SaveDownloadLists(this); }
private void HttpRequest() { try { state = DownloadState.Downloading; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "GET"; request.Timeout = timeout; ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; if (File.Exists(tempSavePath)) { fileStream = File.OpenWrite(tempSavePath); curLength = fileStream.Length; fileStream.Seek(curLength, SeekOrigin.Current); request.AddRange((int)curLength); } else { fileStream = new FileStream(tempSavePath, FileMode.Create, FileAccess.Write); curLength = 0; } request.KeepAlive = false; request.BeginGetResponse(new AsyncCallback(RespCallback), request); } catch (Exception e) { DownloadFailed(fileName); throw e; } }
private void OnErrorMessage(string errorMessage, int operationErrorCode = -1, UIError.Attribute attr = UIError.Attribute.None) { m_State = DownloadState.Error; if ((attr & UIError.Attribute.IsWarning) != 0) { Debug.LogWarning($"{k_ConsoleLogPrefix} {errorMessage}"); } else { Debug.LogError($"{k_ConsoleLogPrefix} {errorMessage}"); } attr |= UIError.Attribute.IsDetailInConsole; if (operationErrorCode == 403) { m_ErrorMessage = k_ForbiddenErrorMessage; } else { attr |= UIError.Attribute.IsClearable; m_ErrorMessage = k_DownloadErrorMessage; } var error = new UIError(UIErrorCode.AssetStoreOperationError, m_ErrorMessage, attr, operationErrorCode); onOperationError?.Invoke(this, error); onOperationFinalized?.Invoke(this); PackageManagerOperationErrorAnalytics.SendEvent(GetType().Name, error); }
public Downloader(string url, string saveDir) { this.url = url; this.saveDir = saveDir; fileName = GetFileNameFromUrl(url); state = DownloadState.None; }
private void ReadCallback(IAsyncResult result) { responseStream = (Stream)result.AsyncState; int read = responseStream.EndRead(result); if (curLength < fileLength) { fileStream.Write(buffer, 0, read); curLength += read; responseStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReadCallback), responseStream); } else { buffer = null; state = DownloadState.Completed; Close(); string savePath = saveDir + "/" + fileName; if (File.Exists(savePath)) { File.Delete(savePath); } File.Move(tempSavePath, savePath); DownloadSuccessed(fileName); } }
private async Task InternalDownloadFileAsync(string Input, Stream Output, CancellationToken Token, long?StartOffset, long?EndOffset, bool DisposeStream) { this._InputURL = Input; this._OutputStream = Output; this._ThreadToken = Token; this._ThreadSingleMode = true; this._Stopwatch = Stopwatch.StartNew(); this._DownloadedSize = 0; this._LastContinuedSize = 0; this._TotalSizeToDownload = 0; this._DownloadState = DownloadState.Starting; this._IsFileAlreadyCompleted = false; this._DisposeStream = DisposeStream; try { EnsureAllThreadsStatus(); await Task.WhenAll(await StartThreads(StartOffset, EndOffset)); this._DownloadState = DownloadState.Completed; UpdateProgress(new _DownloadProgress(_DownloadedSize, _TotalSizeToDownload, 0, _LastContinuedSize, _Stopwatch.Elapsed, _DownloadState)); _Stopwatch.Stop(); } catch (TaskCanceledException ex) { _Stopwatch.Stop(); this._DownloadState = DownloadState.Cancelled; UpdateProgress(new _DownloadProgress(_DownloadedSize, _TotalSizeToDownload, 0, _LastContinuedSize, _Stopwatch.Elapsed, _DownloadState)); throw new TaskCanceledException($"Cancellation for {Input} has been fired!", ex); } }
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { DisposeResources(); progressBar.Style = ProgressBarStyle.Continuous; if (e.Error != null) { DownloadState = DownloadState.Error; textBoxStatus.Text = "Error: " + e.Error.Message; buttonRetry.Enabled = true; } else if (e.Cancelled) { DownloadState = DownloadState.Cancelled; textBoxStatus.Text = "Cancelled"; progressBar.Value = progressBar.Minimum; buttonRetry.Enabled = true; } else { DownloadState = DownloadState.Completed; textBoxStatus.Text = "Completed"; progressBar.Value = progressBar.Maximum; } buttonCancel.Enabled = false; OnStateChanged(); }
public void Abort() { if (downloadInfo?.isValid != true) { return; } if (state == DownloadState.Aborted || state == DownloadState.Completed || state == DownloadState.Error) { return; } // We reset everything if we cancel after pausing a download if (state == DownloadState.Paused) { m_DownloadedBytes = 0; m_State = DownloadState.Aborted; onOperationFinalized?.Invoke(this); return; } // the actual download state change from `downloading` to `aborted` happens in `OnDownloadProgress` callback if (!m_AssetStoreUtils.AbortDownload($"{k_AssetStoreDownloadPrefix}{m_ProductId}", downloadInfo.destination)) { Debug.LogError(L10n.Tr(k_LocalizedAbortErrorMessage)); } }
private void OnDownloadStatusChanged(Feed feed, DownloadState downloadState, double percentage) { var finishedCount = 0; var downloadCount = 0; var average = 0.0; var entry = feed as YoutubeEntry; if (downloadState == DownloadState.Deleted) { if (entry != null) { entry.OnEntryDownloadStatusChange = null; Entries.Remove(entry); } return; } foreach (var en in Entries) { if (en.DownloadState == DownloadState.Ready || en.DownloadState == DownloadState.Error) finishedCount++; if (!(en.DownloadState == DownloadState.Ready || en.DownloadState == DownloadState.Error || en.DownloadState == DownloadState.Initialized)) downloadCount++; average += en.Percentage; } average = average/Entries.Count; if (OnListDownloadStatusChange != null) { DownloadState = downloadState; if (downloadState == DownloadState.DownloadProgressChanged) Percentage = average; if (downloadCount == 0 && finishedCount == Entries.Count) DownloadState = DownloadState.AllFinished; if (Entries.Count == 1 && downloadState == DownloadState.TitleChanged) Title = Entries[0].Title; OnListDownloadStatusChange(this, feed, DownloadState, Percentage); } if (downloadCount < PoolSize) DownloadFirst(); }
private void OnErrorMessage(string errorMessage, int operationErrorCode = -1, UIError.Attribute attr = UIError.Attribute.None) { m_State = DownloadState.Error; if ((attr & UIError.Attribute.IsWarning) != 0) { Debug.LogWarning($"{k_ConsoleLogPrefix} {errorMessage}"); } else { Debug.LogError($"{k_ConsoleLogPrefix} {errorMessage}"); } if (operationErrorCode == 403) { m_ErrorMessage = k_ForbiddenErrorMessage; } else { attr |= UIError.Attribute.IsDetailInConsole | UIError.Attribute.IsClearable; m_ErrorMessage = k_DownloadErrorMessage; } onOperationError?.Invoke(this, new UIError(UIErrorCode.AssetStoreOperationError, m_ErrorMessage, attr, operationErrorCode)); onOperationFinalized?.Invoke(this); }
private void DownloadFile() { WebClient client = new WebClient(); //register download events client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileCompleted += client_DownloadFileCompleted; //start the download client.DownloadFileAsync(address, outFileName); patchDownloadState = DownloadState.InProgress; bool patchDownloadCancelling = false; //wait for the file to be downloaded while (patchDownloadState == DownloadState.InProgress) { if (!patchDownloadCancelling && (Cancelling || Cancelled)) { Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC; client.CancelAsync(); patchDownloadCancelling = true; } Thread.Sleep(SLEEP_TIME); } //deregister download events client.DownloadProgressChanged -= client_DownloadProgressChanged; client.DownloadFileCompleted -= client_DownloadFileCompleted; if (patchDownloadState == DownloadState.Cancelled) throw new CancelledException(); if (patchDownloadState == DownloadState.Error) MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN)); }
public void Abort() { if (!isInProgress && !isInPause) { return; } // We reset everything if we cancel after pausing a download if (state == DownloadState.Paused) { m_DownloadedBytes = 0; m_State = DownloadState.Aborted; onOperationFinalized?.Invoke(this); return; } m_State = DownloadState.AbortRequsted; if (downloadInfo?.isValid != true) { return; } // the actual download state change from `downloading` to `aborted` happens in `OnDownloadProgress` callback if (!m_AssetStoreUtils.AbortDownload(downloadInfo.destination)) { Debug.LogError($"{k_ConsoleLogPrefix} {k_AbortErrorMessage}"); } }
/// <summary> /// Downloads, loads and applies all files required for this mod. /// </summary> public void ApplyTo(int model) { if (this.state == DownloadState.Downloaded) { ApplyFiles(model); return; } else if (this.state == DownloadState.Downloading) { modelsToApply.Add(model); return; } this.state = DownloadState.Downloading; modelsToApply.Add(model); if (this.txd != null) { this.txd.OnDownloadComplete += OnFileDownload; this.txd.Download(); } if (this.dff != null) { this.dff.OnDownloadComplete += OnFileDownload; this.dff.Download(); } if (this.col != null) { this.col.OnDownloadComplete += OnFileDownload; this.col.Download(); } }
private static string GetDownloadStateText1(DownloadState state) { switch (state) { case DownloadState.DownloadCompleted: return("already downloaded"); case DownloadState.DownloadFailed: return("download failed"); case DownloadState.DownloadStarted: return("download already started"); case DownloadState.WaitToDownload: return("download is already waiting for download"); case DownloadState.UnknowEndDownload: return("download end unknow"); case DownloadState.NotDownloaded: return("not downloaded"); default: return(string.Format("download unknow state ???????? {0}", state)); } }
private void updateState(DownloadState state) { switch (state) { case DownloadState.NotDownloaded: background.FadeColour(colours.Gray4, 500, Easing.InOutExpo); icon.MoveToX(0, 500, Easing.InOutExpo); checkmark.ScaleTo(Vector2.Zero, 500, Easing.InOutExpo); break; case DownloadState.Downloading: background.FadeColour(colours.Blue, 500, Easing.InOutExpo); icon.MoveToX(0, 500, Easing.InOutExpo); checkmark.ScaleTo(Vector2.Zero, 500, Easing.InOutExpo); break; case DownloadState.Downloaded: background.FadeColour(colours.Yellow, 500, Easing.InOutExpo); break; case DownloadState.LocallyAvailable: background.FadeColour(colours.Green, 500, Easing.InOutExpo); icon.MoveToX(-8, 500, Easing.InOutExpo); checkmark.ScaleTo(new Vector2(13), 500, Easing.InOutExpo); break; } }
private void OnComplete(string path) { // 下载完成解压资源 m_State = DownloadState.COMPLETE; if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { System.Threading.Thread t = new System.Threading.Thread(() => { string strResPath = GetUnZipPath(); //Engine.ThreadHelper.RunOnMainThread(() => //{ string strLog = string.Format("解压文件{0},到{1}", m_strSaveFile, strResPath); UnityEngine.Debug.Log(strLog); bool bResult = ZipHelper.UnZip(m_strSaveFile, strResPath); if (bResult == true) { // 记录下 SaveUnZipFileSuccess(); // 删除文件 File.Delete(m_strSaveFile); } else { Debug.Log("解压资源文件失败"); } //}); }); t.Start(); } }
public TwitchVideoDownload( string id, DownloadParameters downloadParams, DownloadState downloadState, string log, double progress, string status, bool isIndeterminate) { Id = id; DownloadParams = downloadParams; DownloadState = downloadState; Progress = progress; Status = status; IsIndeterminate = isIndeterminate; _log = new StringBuilder(); _downloadStateLockObject = new object(); _logLockObject = new object(); _progressLockObject = new object(); _statusLockObject = new object(); _isIndeterminateLockObject = new object(); AppendLog(log); }
public DownloadSessionStateChangedEventArgs(DownloadSession session, DownloadState oldState, DownloadState newState) { Session = session; OldState = oldState; NewState = newState; }
private Task Init2() { lock (_monitorState) { if (_initTask != null) { return(_initTask.Task); } switch (State) { case DownloadState.Initializing: case DownloadState.Initialized: case DownloadState.Downloading: case DownloadState.Finished: return(Task.FromResult(0)); } _initTask = new TaskCompletionSource <object>(); _state = DownloadState.Initializing; _cancellationTokenSource = new CancellationTokenSource(); } DownloadStateChanged?.Invoke(this, new EventArgs()); return(Init3()); }
public override void Initialize(DownloadState downloadState, ServerConfiguration serverConfiguration, DownloadPresenter downloadPresenter) { base.Initialize(downloadState, serverConfiguration, downloadPresenter); var port = int.Parse(serverConfiguration.FileDownloadServerPort); //Make payload.json request var uri = DownloadState.GetUri(serverConfiguration.FileDownloadServerUrl, port, "downloads/launcher/payload.json"); var request = UnityWebRequest.Get(uri); request.SendWebRequest().completed += operation => { if (request.isHttpError || request.isNetworkError) { var error = $"Error while making initial request to server: {request.error}"; downloadState.StopAndShowError(error); return; } var payloadDictionary = JToken.Parse(request.downloadHandler.text); var files = payloadDictionary["Files"].Select(x => x["Name"].Value <string>()); //Find the files with the right extension var filesToDownload = files.Where(x => DownloadState.NeededUoFileExtensions.Any(x.Contains)).ToList(); //Get rid of paths with backslash in them now to prevent downloading files from subdirectories filesToDownload.RemoveAll(x => x.Contains("\\")); downloadState.SetFileListAndDownload(filesToDownload, "downloads/launcher/client/"); }; }
/// <summary> /// Downloads, loads and applies all files required for this mod. /// </summary> public void ApplyTo(int model, bool supportsAlpha = false) { if (this.state == DownloadState.Downloaded) { ApplyFiles(model, supportsAlpha); return; } else if (this.state == DownloadState.Downloading) { modelsToApply.Add(new Tuple <int, bool>(model, supportsAlpha)); return; } this.state = DownloadState.Downloading; modelsToApply.Add(new Tuple <int, bool>(model, supportsAlpha)); if (this.txd != null) { this.txd.OnDownloadComplete += OnFileDownload; this.txd.Download(); } if (this.dff != null) { this.dff.OnDownloadComplete += OnFileDownload; this.dff.Download(); } if (this.col != null) { this.col.OnDownloadComplete += OnFileDownload; this.col.Download(); } }
public void Pause() { if (CanPause) { state = DownloadState.Pausing; } }
public void Start() { if (DownloadState == DownloadState.Downloading) { return; } try { InitializeDownload(); } catch (Exception ex) { DisposeResources(); DownloadState = DownloadState.Error; textBoxStatus.Text = "Error: " + ex.Message; buttonRetry.Enabled = true; OnStateChanged(); return; } contentLength = -1; progressBar.Style = ProgressBarStyle.Marquee; textBoxStatus.Text = "Downloading"; DownloadState = DownloadState.Downloading; buttonCancel.Enabled = true; buttonRetry.Enabled = false; OnStateChanged(); backgroundWorker.RunWorkerAsync(); }
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled && patchDownloadState == DownloadState.Error) // cancelled due to network connectivity issue (see NetworkAvailabilityChanged) { return; } if (e.Cancelled) //user cancelled { patchDownloadState = DownloadState.Cancelled; log.DebugFormat("XenServer patch '{0}' download cancelled by the user", updateName); return; } if (e.Error != null) //failure { patchDownloadError = e.Error; log.DebugFormat("XenServer patch '{0}' download failed", updateName); patchDownloadState = DownloadState.Error; return; } //success patchDownloadState = DownloadState.Completed; log.DebugFormat("XenServer patch '{0}' download completed successfully", updateName); }
private void UpdateStatus(DownloadState state, double percentage = 100.0) { DownloadState = state; Percentage = percentage; if (OnEntryDownloadStatusChange != null) OnEntryDownloadStatusChange(this, DownloadState, Percentage); }
public AssetBundleLoader(string path,string fileName,Type type,string assetName=null,bool cache=false,DownloadState state=DownloadState.Init,bool isScene=false,bool isAsyncLoad=false) { this.path = path; this.fileName = fileName; this.assetName = assetName; this.state = state; this.isScene = isScene; this.assetType = type; this.isAsyncLoad = isAsyncLoad; this.isCache = cache; }
private void HandleFinishedDownloading(AllFeed allFeed, DownloadState state) { if (mainControl != null) { GlueCommands.Self.DoOnUiThread(() => { viewModel.UpdateFrom(allFeed); mainControl.AllFeed = allFeed; mainControl.DownloadState = state; }); } }
private static string GetDownloadStateString(DownloadState state) { switch (state) { case DownloadState.MissingParser: return Resources.MissingCompatibleParser; case DownloadState.Cancelled: return Resources.Cancelled; case DownloadState.Completed: return Resources.Completed; case DownloadState.Failed: return Resources.Failed; default: throw new ArgumentOutOfRangeException("state"); } }
private void OnDownloadStatusChange(Feed downloadList, Feed entry, DownloadState downloadState, double percentage) { if (Entries.Count <= 0 || _onStatusChanged == null) return; var finishedCount = Entries.Count(p => p.DownloadState == DownloadState.AllFinished); if (downloadState == DownloadState.DownloadProgressChanged) UpdateStatus(downloadList, entry, DownloadState.DownloadProgressChanged, Entries.Average(en => en.Percentage)); else if (finishedCount == Entries.Count) UpdateStatus(downloadList, entry, DownloadState.AllFinished, 100.0); else if (Entries.Count == 1 && downloadState == DownloadState.AllStart) UpdateStatus(downloadList, entry, DownloadState.AllStart, 0.0); else if(_onStatusChanged != null && !(downloadState == DownloadState.AllFinished || downloadState == DownloadState.AllStart || downloadState == DownloadState.DownloadProgressChanged )) _onStatusChanged(downloadList, entry, downloadState, percentage); }
private void OnDownloadStatusChanged(Feed feed, DownloadState downloadState, double percentage) { var downloadCount = Entries.Count(p => !(p.DownloadState == DownloadState.Ready || p.DownloadState == DownloadState.Error || p.DownloadState == DownloadState.Initialized)); if (OnListDownloadStatusChange != null) { DownloadState = downloadState; var finishedCount = Entries.Count(p => (p.DownloadState == DownloadState.Ready || p.DownloadState == DownloadState.Error)); if (downloadState == DownloadState.DownloadProgressChanged) { var avg = Entries.Average(entry => entry.Percentage); Percentage = avg; } if (downloadCount == 0 && finishedCount == Entries.Count) DownloadState = DownloadState.AllFinished; if (Entries.Count == 1 && downloadState == DownloadState.TitleChanged) { Title = Entries[0].Title; } OnListDownloadStatusChange(this, feed, DownloadState, Percentage); } if (downloadCount != _poolSize) DownloadFirst(); }
internal DownloadInfo(string uri, string path, long length) { if (path.LastIndexOf (System.IO.Path.DirectorySeparatorChar) != (path.Length-1)) { path += System.IO.Path.DirectorySeparatorChar; } directory_path = path; _length = length; remote_uri = new Uri (uri); unique_key = String.Format ( "{0}-{1}", path, remote_uri ); _active = true; local_path = null; _state = DownloadState.New; }
public AbstractDownload(Uri url, int bufferSize, int? offset, int? maxReadBytes, IWebRequestBuilder requestBuilder, IDownloadChecker downloadChecker) { if (url == null) throw new ArgumentNullException("url"); if (bufferSize < 0) throw new ArgumentException("bufferSize < 0"); if (offset.HasValue && offset.Value < 0) throw new ArgumentException("offset < 0"); if (maxReadBytes.HasValue && maxReadBytes.Value < 0) throw new ArgumentException("maxReadBytes < 0"); this.url = url; this.bufferSize = bufferSize; this.offset = offset; this.maxReadBytes = maxReadBytes; this.requestBuilder = requestBuilder; this.downloadChecker = downloadChecker; this.state = DownloadState.Initialized; }
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) //user cancelled { patchDownloadState = DownloadState.Cancelled; log.DebugFormat("XenServer patch '{0}' download cancelled by the user", updateName); return; } if (e.Error != null) //failure { patchDownloadError = e.Error; log.DebugFormat("XenServer patch '{0}' download failed", updateName); patchDownloadState = DownloadState.Error; return; } //success patchDownloadState = DownloadState.Completed; log.DebugFormat("XenServer patch '{0}' download completed successfully", updateName); }
private void QueueAndDownload(WMSLayer layer) { if(layer.dates != null && layer.dates.Length>0) { UpdateProgressBarFrame(0, layer.dates.Length - 1); this.progressBarTotalProgress.Maximum = layer.dates.Length; } else { UpdateProgressBarFrame(0,1); this.progressBarTotalProgress.Maximum = 1; } if(layer.dates == null) this.downloadLayer(layer, null); else { foreach(string curDate in layer.dates) this.downloadLayer(layer, curDate); } this.buttonPlay.Enabled = true; this.downloadState = DownloadState.Pending; // Start Download thread if (downloadThread!=null && downloadThread.IsAlive) return; downloadThread = new Thread( new ThreadStart(Downloader)); downloadThread.Name = "AnimatedEarthManager.Downloader"; downloadThread.IsBackground = true; downloadThread.Start(); }
private void OnDownloadStatusChange(Feed list, Feed feed, DownloadState downloadState, double percentage) { try { Controls.Activity.RunOnUiThread(() => UpdateStatus(list, feed, downloadState, percentage)); } catch { } }
private void UpdateStatus(Feed list, Feed feed, DownloadState downloadState, double percentage) { switch (downloadState) { case DownloadState.AllStart: Controls.ProgressBar.Progress = 0; Controls.DownloadFrame.Visibility = ViewStates.Visible; break; case DownloadState.AllFinished: Log.Debug("STATUS", "DONE!"); Controls.ProgressBar.Progress = 0; Controls.DownloadFrame.Visibility = ViewStates.Gone; list.Entries.Clear(); return; case DownloadState.DownloadProgressChanged: Controls.ProgressBar.Progress = (int)percentage; break; case DownloadState.TitleChanged: //MixpanelTrack("Download", new { feed.Title, _settings.Guid }); break; } if (feed != null) Controls.Title.Text = feed.ToString(); }
private void StartXmlDownloading() { _state = DownloadState.XmlDownloading; AsyncLoadFile(XmlFilePath, GetDownloadedXmlPath()); }
public void StartLoad() { _state = DownloadState.None; DoNextStep(); }
private void FinishDownloading() { try { OnAdsLoadedEvent(this, new AdsLoadedEventArgs() { AdsTabImage = new BitmapImage(new Uri(GetDownloadedImagePath())), AdsPageUrl = _recentDownloadedXmlFormat.AdsPageURL }); } catch (Exception) { } _state = DownloadState.None; }
private void StartImageDownloading() { _state = DownloadState.ImageDownloading; try { _recentDownloadedXmlFormat = _xmlFormatManager.GetXmlFormat(GetDownloadedXmlPath()); if (_recentDownloadedXmlFormat == null) { return; } AsyncLoadFile(_recentDownloadedXmlFormat.DownloadFile, GetDownloadedImagePath()); } catch (Exception ) { } }
private void UpdateStatus(Feed downloadList, Feed entry, DownloadState state, double percentage) { DownloadState = state; Percentage = percentage; if (_onStatusChanged != null) _onStatusChanged(downloadList, entry, DownloadState, Percentage); }
private void Download_CompleteCallback(WMSDownload wdl) { // Not running on UI thread try { updateStatusBar( "Converting: " + wdl.Date ); string srcPath = wdl.SavedFilePath; // Convert to DDS /* // TODO: Investigate whether conversion really improves playback speed. wdl.SavedFilePath = Path.Combine( Path.GetDirectoryName(wdl.SavedFilePath), Path.GetFileNameWithoutExtension(wdl.SavedFilePath)) + ".dds"; Directory.CreateDirectory(Path.GetDirectoryName(wdl.SavedFilePath)); ImageHelper.ConvertToDxt3(srcPath, wdl.SavedFilePath,this.worldWindow.DrawArgs.device, !WorldWindow.World.Settings.KeepOriginalSvsImages); */ AddAnimationFrame(wdl); updateStatusBar( "" ); this.downloadState = DownloadState.Pending; } catch(Exception caught) { this.PauseAnimation(); this.worldWindow.Caption = caught.Message; updateStatusBar( caught.Message ); Thread.Sleep(600); } }
/// <summary> /// 设置任务的下载状态,并触发状态改变事件 /// </summary> /// <param name="value">状态</param> public void SetState(DownloadState value) { this.state = value; OnStateChanged(); }
public bool Setup( IPluginSetupInfo info ) { _versionState = UpdateVersionState.Unknown; _downloadState = DownloadState.None; _webClient = new WebClient(); // Used to read the available version. _webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler( OnDownloadDataCompleted ); // Used to download the new version. _webClient.DownloadFileCompleted += new AsyncCompletedEventHandler( OnDownloadFileCompleted ); return true; }
public PreparedDownload(Download download) { this.Item = download; this.state = DownloadState.Idle; this.Statistics = new DownloadStatistics(); }
/// <summary> /// Download thread runs this function. /// </summary> private void Downloader() { while(true) { if(this.animationState == AnimationState.Pending) { Thread.Sleep(100); continue; } lock(this.downloadQueue) { if(this.downloadQueue.Count <= 0) { Thread.Sleep(100); continue; } this.wmsDownload = (WMSDownload)this.downloadQueue.Dequeue(); } if(File.Exists(wmsDownload.SavedFilePath)) { AddAnimationFrame(wmsDownload); return; } // Download try { this.downloadState = DownloadState.Downloading; updateStatusBar( string.Format( CultureInfo.CurrentCulture, "Downloading {0} ({1}/{2})", wmsDownload.Date, this.animationFrames.Count+1, this.currentlySelectedLayer.AnimationFrameCount ) ); using( WebDownload dl = new WebDownload( wmsDownload.Url) ) { dl.DownloadType = DownloadType.Wms; dl.ProgressCallback += new DownloadProgressHandler(updateCurrentProgressBar); dl.DownloadFile(wmsDownload.SavedFilePath); } Download_CompleteCallback(wmsDownload); } catch(ThreadAbortException) { // Normal shutdown } catch(Exception caught) { updateStatusBar(caught.Message); // Abort download. return; } } }
/// <summary> /// Stops the animation playback. /// </summary> public void StopAnimation() { if(this.animationState==AnimationState.Pending) return; if(this.currentlyAnimatingNode != null) this.currentlyAnimatingNode.ForeColor = this.treeViewLayers.ForeColor; this.currentlyAnimatingNode = null; this.animationState = AnimationState.Pending; this.animationTimer.Enabled = false; StopDownloadThread(); updateCurrentProgressBar(0,1); lock(this.downloadQueue.SyncRoot) this.downloadQueue.Clear(); this.downloadState = DownloadState.Pending; lock(this.animationFrames.SyncRoot) this.animationFrames.Clear(); this.currentAnimationFrame = 0; if(this.imageLayer != null) { this.worldWindow.CurrentWorld.RenderableObjects.Remove(this.imageLayer.Name); this.imageLayer.Dispose(); this.imageLayer = null; } this.worldWindow.Caption = ""; UpdateProgressBarFrame(0,1); this.buttonPlay.ImageIndex = 4; this.CurrentFrameInterval = startFrameInterval; this.buttonColorBar.Enabled = false; if(this.colorbar != null) { this.colorbar.Visible = false; this.colorbar.Dispose(); this.colorbar = null; } SetCaption( "" ); updateStatusBar("Stopped."); }
private void OnAudioConversionStatusChange(Feed feed, DownloadState downloadState, double percentage) { UpdateStatus(downloadState, percentage); }
private void DownloadButtonClickHandler(object sender, RoutedEventArgs eventArgs) { if (ResultListBox.SelectedItem == null) return; if(downloadState != DownloadState.IDLE) return; //Or send some message to user var fileName = ResultListBox.SelectedItem.ToString(); var file = model.GetFileInformation(fileName); if(file.hostIp.Equals(Settings.LOCAL_IP.ToString())) return; //Already have this file ResetDownloadStateDelegate callBack = ResetDownloadState; downloadState = DownloadState.DOWNLOADING; var listenerThread = new Thread(() => { TcpFileReceiver tcpReceiver = new TcpFileReceiver(Settings.LOCAL_IP.ToString(), Settings.DOWNLOAD_PORT, Settings.TCP_TRANSFER_BUFFER); tcpReceiver.ReceiveFile(Settings.DOWNLOAD_DIRECTORY); callBack(); }); listenerThread.IsBackground = true; listenerThread.Start(); var senderThread = new Thread(() => { try { var url = "tcp://" + file.hostIp + ":" + Settings.REMOTING_SERVER_PORT + "/TcpFileSender"; TcpFileSender tcpSender = (TcpFileSender) Activator.GetObject(typeof(TcpFileSender), url); tcpSender.SendFile(Settings.LOCAL_IP.ToString(), Settings.DOWNLOAD_PORT, file.fullName, Settings.TCP_TRANSFER_BUFFER); } catch (SocketException e) { } }); senderThread.IsBackground = true; senderThread.Start(); }
private void OnDownloadStatusChange(Feed downloadItems, Feed entry, DownloadState downloadState, double percentage) { switch (downloadState) { case DownloadState.AllStart: Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Log.Text = "START"; ProgressBar.Value = 0; DownloadProcessRing.IsActive = true; }); break; case DownloadState.AllFinished: Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Log.Text = "DONE!"; DownloadProcessRing.IsActive = false; ProgressBar.Value = 0; }); downloadItems.Entries.Clear(); return; case DownloadState.DownloadProgressChanged: Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ProgressBar.Value = percentage; }); break; } if (entry != null) Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Log.Text = entry.ToString(); }); }
private void ResetDownloadState() { downloadState = DownloadState.IDLE; }