private void ReportProgress(long fsize) { float delta; lock (ProgressLock) { Progress += fsize; } Debug.Assert(Progress <= AllFilesSize, "Fatal, Progress is bigger than size of all files! " + Progress + ":" + AllFilesSize + "\nRoute: " + RoutePath); if (Progress <= AllFilesSize) { if (AllFilesSize > 0) { PercentProgress = Progress * 100f / AllFilesSize; delta = (float)(fsize * 100.0f / AllFilesSize); } else { PercentProgress = 100f; delta = 100f; } // Invoke progress events ProgressUpdated?.Invoke(PercentProgress); DeltaProgress?.Invoke(delta); } }
internal async Task AddToAlbums(IEnumerable <SONG> songs) { await Task.Run(async() => { var albums = from song in songs group song by song.Album into album select album; var opr = SQLOperator.Current(); var count = albums.Count(); if (count == 0) { Completed?.Invoke(this, EventArgs.Empty); return; } int i = 1; await Task.Delay(200); ProgressUpdated?.Invoke(this, new ProgressReport() { Description = $"0 of {count} albums sorted", Current = 0, Total = count }); foreach (var item in albums) { await opr.AddAlbumAsync(item); ProgressUpdated?.Invoke(this, new ProgressReport() { Description = $"{i} of {count} albums sorted", Current = i, Total = count }); i++; } Completed?.Invoke(this, EventArgs.Empty); }); }
public async Task ReadFileandSave(IEnumerable <StorageFile> files) { var opr = SQLOperator.Current(); var total = files.Count(); int i = 1; var newlist = new List <SONG>(); foreach (var file in files) { if (!file.IsAvailable || file.Attributes.HasFlag(FileAttributes.LocallyIncomplete)) { ProgressUpdated?.Invoke(this, new ProgressReport() { Description = $"{i} of {total} files readed", Current = i, Total = total }); i++; continue; } try { using (var tagTemp = File.Create(file.Path)) { var song = await Song.Create(tagTemp.Tag, file.Path, await file.Properties.GetMusicPropertiesAsync()); var t = await opr.InsertSongAsync(song); if (t != null) { newlist.Add(t); } } } catch (Exception e) { Shared.Helpers.Tools.Logging(e); continue; } finally { ProgressUpdated?.Invoke(this, new ProgressReport() { Description = $"{i} of {total} files read", Current = i, Total = total }); i++; } } if (newlist.Count > 0) { await AddToAlbums(newlist); } else { Completed?.Invoke(this, EventArgs.Empty); } }
public MediaPlayerService() { _progressUpdateTimer = new DispatcherTimer(TimeSpan.FromSeconds(0.1), DispatcherPriority.Render, (sender, e) => ProgressUpdated?.Invoke(this, new ProgressUpdatedEventArgs(Progress)), Dispatcher.CurrentDispatcher); }
public async Task <FileSerivceParseResult> OpenAndParseFolder() { var result = new FileSerivceParseResult(); _failedFiles = 0; FolderPicker picker = new FolderPicker(); picker.FileTypeFilter.Add(EventVideoFileExtension); picker.FileTypeFilter.Add(EventMetadataFileExtension); picker.FileTypeFilter.Add(EventThumbnailFileExtension); var folderResult = await picker.PickSingleFolderAsync(); if (folderResult != null) { ProgressUpdated?.Invoke(this, new ProgressEventArgs(0, 0, 0)); // Folder selected, indicate that work is starting var files = await folderResult.GetFilesAsync(CommonFileQuery.OrderByName); result.Result = await ParseFiles(files); result.ParsedPath = folderResult.Path; result.FailedFiles = _failedFiles; } return(result); }
public async Task <List <TeslaEvent> > ParseFiles(IReadOnlyList <StorageFile> files) { var result = new List <TeslaEvent>(); var eventMetadataFiles = files.Where(f => f.FileType.Equals(EventMetadataFileExtension)); var videoFiles = files.Where(f => f.FileType.Equals(EventVideoFileExtension)); var thumbnailFiles = files.Where(f => f.FileType.Equals(EventThumbnailFileExtension)); foreach (var metadataFile in eventMetadataFiles) { var eventText = await FileIO.ReadTextAsync(metadataFile); try { TeslaEvent teslaEvent = ParseEvent(files, metadataFile.Path, eventText); result.Add(teslaEvent); } catch { _failedFiles++; } ProgressUpdated?.Invoke(this, new ProgressEventArgs(result.Count, _failedFiles, eventMetadataFiles.Count())); } return(result.OrderBy(r => r.Timestamp).ToList()); }
private void ReportProgress(long fsize) { float delta; lock (ProgressLock) { Progress += fsize; } Debug.Assert(Progress <= AllFilesSize, string.Format(Localization.Strings.ProgressFail, Progress, AllFilesSize, RoutePath)); if (Progress <= AllFilesSize) { if (AllFilesSize > 0) { PercentProgress = Progress * 100f / AllFilesSize; delta = (float)(fsize * 100.0f / AllFilesSize); } else { PercentProgress = 100f; delta = 100f; } // Invoke progress events ProgressUpdated?.Invoke(PercentProgress); DeltaProgress?.Invoke(delta); } }
public async static Task SortAlbums() { await Task.Run(async() => { var opr = SQLOperator.Current(); var songs = await opr.GetAllAsync <SONG>(); var albums = from song in songs group song by song.Album into album select album; var count = albums.Count(); int i = 1; var scan = Consts.Localizer.GetString("AlbumSortText"); ProgressUpdated?.Invoke(null, new ProgressReport() { Description = SmartFormat.Smart.Format(scan, 0, count), Current = 0, Total = count }); foreach (var item in albums) { await opr.AddAlbumAsync(item); ProgressUpdated?.Invoke(null, new ProgressReport() { Description = SmartFormat.Smart.Format(scan, i, count), Current = i, Total = count }); i++; } Completed?.Invoke(null, EventArgs.Empty); }); }
public void DownloadLatest() { ProgressUpdated?.Invoke(Status.Initializing, 0, 0); string downloadUrl = GetLatestDownloadUrl(); ProgressUpdated?.Invoke(Status.Downloading, 0, 0); StartProgressMonitor(); Download(Filepath + ".temp", downloadUrl); AbortProgressMonitor(); ProgressUpdated?.Invoke(Status.Waiting, 100, 0); while (File.Exists(Filepath) && IsFileInUse(Filepath)) { Thread.Sleep(1000); } ProgressUpdated?.Invoke(Status.Finishing, 100, 0); if (File.Exists(Filepath)) { File.Delete(Filepath); } File.Move(Filepath + ".temp", Filepath); ProgressUpdated?.Invoke(Status.Finished, 100, 0); IsRunning = false; Finished?.Invoke(); }
internal Player() { _progressUpdateTimer = new DispatcherTimer(TimeSpan.FromSeconds(0.1), DispatcherPriority.Render, (sender, e) => ProgressUpdated?.Invoke(this, new ProgressUpdatedEventArgs(Progress)), Dispatcher.CurrentDispatcher); _progressUpdateTimer.Start(); }
public void ErrorOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { ProgressUpdated?.Invoke(outLine.Data); if (Abort) { ((Process)sendingProcess).Kill(); Abort = false; } }
protected override void OnProgressUpdate(params InterfaceViewModel[] values) { base.OnProgressUpdate(values); foreach (InterfaceViewModel interfaceViewModel in values) { ProgressUpdated?.Invoke(this, new ProgressUpdatedEventArgs(interfaceViewModel)); } }
protected virtual void OnProgressUpdated(DownloadProgressChangedEventArgs e) { var dlItem = (DownloadItem)e.UserState; dlItem.BytesRecived = e.BytesReceived; dlItem.TotalBytes = e.TotalBytesToReceive; dlItem.ProgressPrecentage = e.ProgressPercentage; ProgressUpdated?.Invoke(this, e); }
private void DLCompletedCallback(object sender) { // Try to download the next item in the queue, if applicable if (totalDownloads != 0) { completionPercentage = ((totalDownloads - dlQueue.Count) / (double)totalDownloads) * 100; ProgressUpdated.Invoke(this); } DownloadNext(); }
public async Task Start(CancellationToken token) { for (var i = 0; i < 100; i++) { token.ThrowIfCancellationRequested(); await Task.Delay(1000); Progress++; ProgressUpdated?.Invoke(this, EventArgs.Empty); } }
private void ReportProgress(Match match) { long GetBytes(double size, string units) { int GetMultiplier() { switch (units) { case "KiB": return(1024); case "MiB": return(1024 * 1024); case "GiB": return(1024 * 1024 * 1024); default: throw new InvalidOperationException("Invalid units for multiplier."); } } return((long)(size * GetMultiplier())); } long?GetDownloadSpeed() { string downloadSpeed = match.Groups["DownloadSpeed"].Value; if (downloadSpeed == string.Empty) { return(null); } return(GetBytes(double.Parse(downloadSpeed), match.Groups["DownloadSpeedUnits"].Value)); } long totalDownloadSize = GetBytes(double.Parse(match.Groups["TotalDownloadSize"].Value), match.Groups["TotalDownloadSizeUnits"].Value); double progressPercentage = double.Parse(match.Groups["ProgressPercentage"].Value); if (_stage == 0 || progressPercentage >= 100 && _lastProgress < 100) { ++_stage; } _lastProgress = progressPercentage; ProgressUpdated?.Invoke(this, new ProgressUpdatedEventArgs(totalDownloadSize, progressPercentage, GetDownloadSpeed(), _stage)); }
private void ProgressMonitor() { long lastPosition = Position; while (true) { if (Position != 0) { ProgressUpdated?.Invoke(Status.Downloading, (double)Position / Length * 100, Position - lastPosition); } lastPosition = Position; Thread.Sleep(1000); } }
public void StartGettingFilesDescriptors() { var files = GetMp3FilesRecursively(_path).ToList(); for (int i = 0; i < files.Count; i++) { var filePath = files[i]; FileTemplate item = new FileTemplate(filePath); item.Mp3Length = GetMp3Length(filePath); NewFileParsed?.Invoke(this, item); ProgressUpdated?.Invoke(this, GetProgress(i + 1, files.Count)); } }
public override void Handle(string pLine) { if (pLine.StartsWith("Current Frame:", StringComparison.CurrentCulture)) { var arrParts = pLine.Split(','); if (arrParts.Length > 0) { int?intFrame = null; int?intPercentage = null; foreach (string strPart in arrParts) { var arrKvp = strPart.Split(':'); if (arrKvp.Length == 2) { var strKey = arrKvp[0].Trim(); switch (strKey) { case "Current Frame": int intTmpFrame; if (int.TryParse(arrKvp[1].Trim(), out intTmpFrame)) { intFrame = intTmpFrame; } break; case "percentage": int intTmpPercentage; if (int.TryParse(arrKvp[1].Trim(), out intTmpPercentage)) { intPercentage = intTmpPercentage; } break; } } } if (intFrame != null && intPercentage != null && _intPrevPercentage != intPercentage) { _intPrevPercentage = (int)intPercentage; Log.Info("Progress Changed, notify world"); ProgressUpdated?.Invoke(this, new EventArgs.ProgressUpdatedEventArgs((int)intFrame, (int)intPercentage)); } } } }
public void DownloadLatest() { ProgressUpdated?.Invoke(Status.Initializing, 0, 0); File.Move(Filepath, Filepath + ".backup"); IsBackuped = true; string downloadUrl = GetLatestDownloadUrl(); ProgressUpdated?.Invoke(Status.Downloading, 0, 0); StartProgressMonitor(); Download(Filepath, downloadUrl); AbortProgressMonitor(); ProgressUpdated?.Invoke(Status.Finishing, 100, 0); File.Delete(Filepath + ".backup"); ProgressUpdated?.Invoke(Status.Finished, 100, 0); IsRunning = false; Finished?.Invoke(); }
void ProcessFile(string path) { FileInfo info = new FileInfo(path); FolderInfoDictionary[info.Directory.FullName].size += info.Length; FolderInfoDictionary[info.Directory.FullName].FileCount++; SizeOfProcessedFiles += info.Length; double percentCompleted = (SizeOfProcessedFiles / (double)SizeOfDrive) * 100; //Update the UI on the main thread Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { //Every 0.5 percent done raise ProgressUpdated if (percentCompleted > PercentDone + 0.5) { PercentDone = (SizeOfProcessedFiles / (double)SizeOfDrive) * 100; ProgressUpdated?.Invoke(null, new ProgressUpdatedEventArgs(PercentDone)); } })); }
private void UpdateProgress() { if (!UnknownTotalMode && Progress.Total < 1L) { SetUnknownTotalMode(); } if (NumericMode) { BytesProgressValue.Text = Progress.Current.ToString(); BytesTotalValue.Text = Progress.Total.ToString(); } else if (!PercentageMode) { BytesProgressValue.Text = ConvertBytesSep(Progress.Current, out string Unit); BytesProgress.Text = Unit; SpeedValue.Text = Progress.GetSpeed(out Unit); Speed.Text = Unit; } if (!UnknownTotalMode) { double Ratio = Progress.Ratio, Angle = 6.283185307179586D * Ratio; ElementBorder.Fill = new SolidColorBrush(FromRgb((byte)(21D + 139D * Ratio), (byte)(21D + 79D * Ratio), (byte)(21D * (1D - Ratio)))); if (Ratio == 1D) { Angle -= 0.0000001D; } Arc.IsLargeArc = Angle > PI; Arc.Point = new Point(HalfWidth + (HalfWidth - 7D) * Sin(Angle), HalfHeight - (HalfHeight - 7D) * Cos(Angle)); if (!NumericMode) { if (!PercentageMode) { BytesTotalValue.Text = ConvertBytesSep(Progress.Total, out string Unit); BytesTotal.Text = Unit; } Percentage.Text = Progress.Total > 104857600L ? Progress.PrecisePercentage : Progress.Percentage; } } ProgressUpdated?.Invoke(); }
public static async Task SyndDataAsync(IContainerProvider container) { Barrel.Current.EmptyAll(); var interfaces = Assembly.GetExecutingAssembly() .GetTypes() .Where(x => x.IsInterface && typeof(ISyncService).IsAssignableFrom(x) && x != typeof(IService <>) && x != typeof(ISyncService)) .ToArray(); for (int index = 0; index < interfaces.Length; index++) { try { var service = (ISyncService)container.Resolve(interfaces[index]); if (service == null) { continue; } await service.SyncAsync(); if (ProgressUpdated != null) { double progress = (index + 1) / (double)interfaces.Length; ProgressUpdated.Invoke(progress, new EventArgs()); } } catch (Exception) { // TODO - log error } } var settings = new Settings { LastUpdated = DateTime.UtcNow }; Barrel.Current.Add(nameof(Settings), settings, TimeSpan.FromDays(5)); }
public static async Task Read(IList <StorageFolder> folder, IList <string> filterdFolderNames) { var list = new List <StorageFile>(); int i = 1; var scan = Consts.Localizer.GetString("FolderScanText"); foreach (var item in folder) { var files = await GetFilesAsync(item, filterdFolderNames); var opr = SQLOperator.Current(); if (KnownFolders.MusicLibrary.Path == item.Path || item.Path.Contains(ApplicationData.Current.LocalFolder.Path)) { } else { await opr.UpdateFolderAsync(item, files.Count); } list.AddRange(files); ProgressUpdated?.Invoke(null, new ProgressReport() { Description = SmartFormat.Smart.Format(scan, i, folder.Count), Current = i, Total = folder.Count }); i++; } await Task.Delay(200); ProgressUpdated?.Invoke(null, new ProgressReport() { Description = Consts.Localizer.GetString("FolderScanFinishText"), Current = i, Total = folder.Count }); await Task.Delay(200); await ReadFileandSave(from a in list group a by a.Path into b select b.First()); }
public async Task Read(IList <StorageFolder> folder) { var list = new List <StorageFile>(); int i = 1; foreach (var item in folder) { var files = await GetFilesAsync(item); var opr = SQLOperator.Current(); if (KnownFolders.MusicLibrary.Path == item.Path || item.Path == ApplicationData.Current.LocalFolder.Path) { } else { await opr.UpdateFolderAsync(item, files.Count); } list.AddRange(files); ProgressUpdated?.Invoke(this, new ProgressReport() { Description = $"{i} of {folder.Count} folders scanned", Current = i, Total = folder.Count }); i++; } await Task.Delay(200); ProgressUpdated?.Invoke(this, new ProgressReport() { Description = "Folder scanning completed", Current = i, Total = folder.Count }); await Task.Delay(200); await ReadFileandSave(from a in list group a by a.Path into b select b.First()); }
/// <summary> /// Start route crawling /// </summary> /// <returns></returns> public void Start() { Task t = Task.Run(async() => { // If route directory exists if (Directory.Exists(RoutePath)) { try { // Counts size of all files AllFilesSize = CountAllFiles(); // Find all dependencies await GetDependencies(); } catch (Exception e) { if (e.GetType() != typeof(ThreadInterruptedException) && e.GetType() != typeof(ThreadAbortException)) { Trace.Assert(false, string.Format(Localization.Strings.CrawlingRouteFail, RoutePath), e.ToString()); } } // If crawling skipped because cache or inaccuracy, adds to 100 % if (PercentProgress != 100) { DeltaProgress?.Invoke(100f - PercentProgress); PercentProgress = 100; ProgressUpdated?.Invoke(PercentProgress); } } // Crawling complete event Complete?.Invoke(); }); }
private void LogAndUpdate(string msg, int itemsComplete, int totalItems) { Logger?.Write($"[{DateTime.Now}] {msg}"); ProgressUpdated?.Invoke(new ProgressUpdateEventArgs(msg, itemsComplete, totalItems)); }
/// <summary> /// Updates the UI of the solution runner with the current progress, and schedules the next update a couple of /// milliseconds in the future. /// </summary> protected Task UpdateProgressAsync() { _myUpdateTick = Environment.TickCount + MillisecondsBetweenProgressUpdates; ProgressUpdated?.Invoke(this, new SolutionProgressEventArgs(Progress)); return(Task.Delay(1, CancellationToken)); }
/// <summary> /// Invokes all registerd callbacks /// </summary> /// <param name="value"></param> public void Report(Tuple <int, string> value) => ProgressUpdated?.Invoke(this, value);
private void OnAngerUpdated() { progressBar.BarValue = Anger; ProgressUpdated?.Invoke(Anger); }