public BulkEditorViewModel(IWindowFactory windowFactory, MainViewModel mainViewModel) : base(windowFactory) { MainVM = mainViewModel; Logger = MainController.Get().Logger; RunCommand = new RelayCommand(Run, CanRun); Options = new BulkEditOptions(); ProgressReport = new ProgressReport(); }
void ReceiveProgressInfo() { if (ProgressReportInfo != null) { Messenger.Default.Register <MessageCommunicator>(this, (prg) => { this.ProgressReportInfo = prg.ProgressReportFromView; }); } }
static private void reportProgress(ProgressReport pr, Parameters par) { if (pr.IterationStatus == IterationStatus.Initialize) { startProgress(par, dataSetName); } else { Console.WriteLine($"It={pr.Iteration}; Fitness= {pr.BestSolution.Fitness.ToString("F")}, Total={pr.IterationStatistics.IterationSeconds} sec; " /*+ pr.Message*/); } }
private void UpdateProgress(object sender, ElapsedEventArgs e) { lock (timerLock) { if (timer.Enabled) { ProgressReport progress = new ProgressReport(job.Progress); PipeUtilities.SendObjectToPipe(pipeWrite, progress); } } }
private void FindPhotosInDirectory(string directoryPath) { var subDirectories = Directory.GetDirectories(directoryPath); // Recursively process each directory foreach (var subDirectory in subDirectories) { // TODO: Add support for configurable ignore files/dirs if (Path.GetFileName(subDirectory).Equals("@eaDir", StringComparison.InvariantCultureIgnoreCase)) { continue; } FindPhotosInDirectory(subDirectory); } // Get each file path in directory var pathsOfDirectoryFiles = new List <string>(); foreach (var filePath in Directory.GetFiles(directoryPath)) { pathsOfDirectoryFiles.Add(filePath); } // Filter to only include photos (and videos) // TODO: Replace magical strings with crawler recognized extensions settings var photoRegex = new Regex(@".*\.(gif|jpe?g|bmp|png|vmv)$", RegexOptions.IgnoreCase); var videoRegex = new Regex(@".*\.(mov|mpe?g|mp4|avi)$", RegexOptions.IgnoreCase); var pathsOfDirectoryPhotos = pathsOfDirectoryFiles .Where(p => photoRegex.IsMatch(p) || videoRegex.IsMatch(p)) .ToList(); // Process each photo in directory for (var index = 0; index < pathsOfDirectoryPhotos.Count; index++) { var filePath = pathsOfDirectoryPhotos[index]; var(photo, error) = PhotoReader.ReadPhoto(filePath, false, true); if (photo != null) { _list.Add(photo); } if (error != null) { _errorList.Add(error); } var progressReport = new ProgressReport( $"Find photos {directoryPath}", index, pathsOfDirectoryPhotos.Count); _outputPort?.HandleProgress(progressReport); } }
public HttpResponseMessage progressReportCSV(Guid orgId, Guid projId, Guid? locId) { DateTime? startDate = grabStartDate(); DateTime? endDate = grabEndDate(); var response = csvStream("progress.csv", new PushStreamContent((stream, Content, context) => { var writer = new StreamWriter(stream); ProgressReport.buildCSV(writer, orgId, projId, locId, startDate, endDate); })); return response; } // progressReportCSV
/// <summary> /// Converts flags from svg format to bitmap /// </summary> /// <param name="countries"></param> private async Task ConvertFlags(List <Country> countries, IProgress <ProgressReport> progress) { ProgressReport report = new ProgressReport(); int i = 1; await Task.Run(() => { foreach (var country in countries) { try { var svgDocument = SvgDocument.Open($@"Flags\{country.Name}.svg"); using (var smallBitmap = svgDocument.Draw()) { var width = smallBitmap.Width; var height = smallBitmap.Height; using (var bitmap = svgDocument.Draw(width, height)) { bitmap.Save($@"Flags\{country.Name}.bmp", ImageFormat.Bmp); } } } catch (Exception e) { dialogService.ShowMessage("Error", $"An error occurred trying to convert {country.Name}'s flag\n{e.Message}"); } report.CompletePercentage = Convert.ToByte((i * 100) / countries.Count); progress.Report(report); i++; } }); await Task.Run(() => { try { var defaultFlag = SvgDocument.Open($@"Flags\Default.svg"); using (var smallBitmap = defaultFlag.Draw()) { var width = smallBitmap.Width; var height = smallBitmap.Height; using (var bitmap = defaultFlag.Draw(width, height)) { bitmap.Save($@"Flags\Default.bmp", ImageFormat.Bmp); } } } catch (Exception e) { dialogService.ShowMessage("Error", $"An error occurred trying to convert the default flag\n{e.Message}"); } }); }
/// <summary> /// Increments the API progress bar and its respective label based on a received value between 0 and 100, while it's converting all the flags /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ReportProgress(object sender, ProgressReport e) { ProgressBar_api.Value = e.CompletePercentage; if (e.CompletePercentage != 100) { LabelApiProgress.Content = $"Loading... {e.CompletePercentage}%"; } else { LabelApiProgress.Content = $"Countries loaded from the API on {DateTime.UtcNow:dd/MM/yyyy}"; } }
private void ReportProgress(object sender, ProgressReport e) { progressBar.Value = e.Percentage; if (e.Percentage != 100) { lbl_loadingInfo.Content = "Loading countries from API..."; } else { lbl_loadingInfo.Content = "Countries loaded from API"; } }
public void CreateNewProgressReport() { // Arrange ProgressReport progRep = new ProgressReport(); // Act progRep.Name = "First Update"; progRep.Notes = "Testing the progress report object"; progRep.RequestId = 1; // Assert }
private void ReportProgress(object sender, EventArgs e) { ProgressReport d = sender as ProgressReport; if (d != null) { if (progressReport != null) { progressReport(sender, e); } } }
private void Progress_ProgressChanged(object sender, ProgressReport e) { if (e.reportType == ReportType.Percent) { int percent = (int)e.data; if (percent > Progress) { Progress = percent; OnPropertyChanged("Progress"); } } }
/// <summary> /// Receives a C# list of countries and inserts them into the countries sqlite table /// </summary> /// <param name="countries"></param> public async Task SaveData(List <Country> countries, IProgress <ProgressReport> progress) { ProgressReport report = new ProgressReport(); byte i = 1; try { await Task.Run(async() => { foreach (Country country in countries) { command.Parameters.AddWithValue("@name", country.Name); command.Parameters.AddWithValue("@alpha2code", country.Alpha2Code); command.Parameters.AddWithValue("@alpha3code", country.Alpha3Code); command.Parameters.AddWithValue("@capital", country.Capital); command.Parameters.AddWithValue("@region", country.Region); command.Parameters.AddWithValue("@subregion", country.Subregion); command.Parameters.AddWithValue("@population", country.Population); command.Parameters.AddWithValue("@denonym", country.Demonym); command.Parameters.AddWithValue("@area", country.Area); command.Parameters.AddWithValue("@gini", country.Gini); command.Parameters.AddWithValue("@nativeName", country.NativeName); command.Parameters.AddWithValue("@numericCode", country.NumericCode); command.Parameters.AddWithValue("@cioc", country.Cioc); command.CommandText = "insert into countries values(@name, @alpha2code, @alpha3code, @capital, @region, @subregion, @population, @denonym, @area, @gini, @nativeName, @numericCode, @cioc)"; command.Connection = connection; command.ExecuteNonQuery(); await SaveDataToOtherTables(country); report.CompletePercentage = Convert.ToByte((i * 100) / countries.Count); progress.Report(report); i++; } }); string sqlcommand = "update dbState set state = 1"; command = new SQLiteCommand(sqlcommand, connection); command.ExecuteNonQuery(); connection.Close(); } catch (Exception e) { dialogService.ShowMessage("Error", e.Message); } }
private void UpdateProgress(ConcurrentDictionary <string, int> dict, ProgressReport progress) { if (progress == null) { return; } Execute.PostToUIThread(() => { progress.ProgressDict = dict; progress.Value = dict.Values.Last(); }); }
public BulkEditorViewModel( IProjectManager projectManager, ILoggerService loggerService ) : base(ToolTitle) { _projectManager = projectManager; Logger = loggerService; RunCommand = new RelayCommand(Run, CanRun); Options = new BulkEditOptions(); ProgressReport = new ProgressReport(); }
private void ReportProgressDB(object sender, ProgressReport e) { progressBar.Value = e.Percentage; if (e.Percentage != 100) { lbl_loadingInfo.Content = "Saving countries to Database..."; } else { lbl_loadingInfo.Content = "Countries saved to Database"; } }
private void startSyncButton_Click(object sender, EventArgs e) { startSyncButton.Enabled = false; context = DbContextFactory.GetDbContext(); var progressReport = new ProgressReport(); progressReport.ProgressReported += ProgressReport_ProgressReported; source = new CancellationTokenSource(); Task.Run(() => ShowHelper.UpdateShows(context, context.Shows.ToArray(), new TvmazeApi(), source.Token, progressReport)); }
static void ReportProgress(ProgressReport report) { if (report.Message != _reportProgressTitle) { _reportProgressTitle = report.Message; Console.WriteLine(); Console.WriteLine(report.Message); } else { Console.Write("..." + report.featurePos); } }
/// <summary> /// Increments the database progress bar and its respective label based on a received value between 0 and 100, while it's saving all data to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DatabaseReportProgress(object sender, ProgressReport e) { ProgressBar_database.Value = e.CompletePercentage; LabelDatabaseProgress.Content = $"{e.CompletePercentage}%"; if (e.CompletePercentage != 100) { LabelDatabaseProgress.Content = $"Saving... {e.CompletePercentage}%"; } else { LabelDatabaseProgress.Content = "Countries saved to the database"; } }
void BackgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { ItemWorker backgroundWorker = itemWorkers.FirstOrDefault(t => t.BackgroundWorker == (BackgroundWorker)sender); ProgressReport currentProgress = e.UserState as ProgressReport; currentProgress.DesignerItem = backgroundWorker.DesignerItem; currentProgress.State = ItemEvent.ProgressReport; if (progress != null) { progress.Report(currentProgress); } }
public List <TranslationCollection> UpdateSerializedTranslations(ProgressReport report = null) { // Check if we need to report our progress if (report != null) { // Set the number of steps involved in serialization report.SetTotalSteps(AllTranslations.Count); } // Grab a soft-copy of all translations KeyLanguageTextMap translationCopy = AllTranslations; // Clear the translations list (this needs to happen AFTER calling AllTranslations' getter) translations.Clear(); // Go through all the keys TranslationCollection collectionToAdd; LanguageTextPair pairToAdd; foreach (KeyValuePair <string, LanguageTextMap> collection in translationCopy) { // Create a new collection of translations collectionToAdd = new TranslationCollection(collection.Key); // Go through all translations foreach (KeyValuePair <int, string> pair in collection.Value) { // Create a new pair pairToAdd = new LanguageTextPair(pair.Key, pair.Value); // Add the pair to the collection collectionToAdd.AllTranslations.Add(pairToAdd); } // Add new collection to the list translations.Add(collectionToAdd); // Check if we need to report our progress if (report != null) { // Increment report.IncrementCurrentStep(); } } // Indicate the dictionary matches the serialization IsAllTranslationsSerialized = true; // Return the updated translations list return(translations); }
/// <summary> /// Saves Flags images in a Folder inside the Project /// </summary> /// <param name="url"></param> /// <param name="filename"></param> public async Task SaveFlag(List <Country> ListCountry, IProgress <ProgressReport> progress) { ProgressReport report = new ProgressReport(); foreach (var item in ListCountry) { if (!File.Exists(Environment.CurrentDirectory + "/FlagsPNG" + $"/{item.Name}.png")) { await Task.Run(() => { if (!Directory.Exists("Images")) { Directory.CreateDirectory("Images"); } try { using (WebClient webClient = new WebClient()) { webClient.DownloadFile(item.Flag, @"Images\" + item.Name + ".svg"); } } catch (Exception e) { dialogService.ShowMessage("Error While Creating SVG Images Folder", e.Message); } if (!Directory.Exists("FlagsPNG")) { Directory.CreateDirectory("FlagsPNG"); } try { using (MagickImage image = new MagickImage(@"Images\" + item.Name + ".svg")) { image.Write(@"FlagsPNG\" + item.Name + ".png"); } } catch (Exception e) { dialogService.ShowMessage("Error While Creating PNG Images Folder", e.Message); } report.SaveCountries.Add(item); report.Percentagem = (report.SaveCountries.Count * 100) / ListCountry.Count; progress.Report(report); }); } } }
public async Task Run(RunLog runLog) { this.runLog = runLog; this.runLog.StartTime = DateTime.Now; this.runLog.PackageId = this.package.PackageId; this.runLog.PackageDisplayName = this.package.DisplayName; // Create new folder for logs this.logBasePath = this.package.ParentProject.ProjectFolder.Trim('\\') + @"\logs\"; if (Directory.Exists(this.logBasePath) == false) { Directory.CreateDirectory(this.logBasePath); } this.runLog.RunLogPath = this.logBasePath + this.runLog.RunId; Directory.CreateDirectory(this.runLog.RunLogPath); var progress = new Progress <ProgressReport>(); progress.ProgressChanged += (s, e) => { switch (e.State) { case ItemEvent.Started: if (DesignerItemStart != null) { DesignerItemStart.Invoke(e, new EventArgs()); } break; case ItemEvent.ProgressReport: if (ProgressReport != null) { ProgressReport.Invoke(e, new EventArgs()); } break; case ItemEvent.StoppedNotExecuted: case ItemEvent.StoppedWithError: case ItemEvent.StoppedSuccessful: if (DesignerItemStop != null) { DesignerItemStop.Invoke(e, new EventArgs()); } break; } }; await Task.Run(() => RunInternal(progress)); }
public void AddStatusMessage(ProgressReport progressReport) { ProgressReport existingReport = progressReports.Where(t => t.DesignerItem.ID == progressReport.DesignerItem.ID).FirstOrDefault(); if (existingReport == null) { progressReports.Add(progressReport); } else { int existingIndex = progressReports.IndexOf(existingReport); progressReports[existingIndex] = progressReport; } }
private Task ProcessData(List <string> list, IProgress <ProgressReport> progress, CancellationToken m_cancelTokenSource) //private Task ProcessData(List<string> list, IProgress<ProgressReport> progress) { int index = 0; int totalProcess = list.Count; var progressReport = new ProgressReport(); return(Task.Run(() => { if (StepperManager.Instance.GoNearToFar == true) { //Progress_lbl.Content = "Moving to Near Focus..."; MoveToNearFocus2(); Thread.Sleep(2000); Thread.Sleep(StepperManager.Instance.InitStackDelay); for (int i = 0; i < totalProcess; i++) { m_cancelTokenSource.ThrowIfCancellationRequested(); progressReport.PercentComplete = index++ *100 / totalProcess; progress.Report(progressReport); Shot_MoveFar(); } //Progress_lbl.Content = "Moving to Near Focus..."; MoveToNearFocus(); //StepperManager.Instance.IsNotStacking = true; } if (StepperManager.Instance.GoFarToNear == true) { //Progress_lbl.Content = "Moving to Far Focus..."; MoveToFarFocus2(); Thread.Sleep(2000); Thread.Sleep(StepperManager.Instance.InitStackDelay); for (int i = 0; i < totalProcess; i++) { m_cancelTokenSource.ThrowIfCancellationRequested(); progressReport.PercentComplete = index++ *100 / totalProcess; progress.Report(progressReport); Shot_MoveNear(); } //Progress_lbl.Content = "Moving to Far Focus..."; MoveToFarFocus(); //StepperManager.Instance.IsNotStacking = true; } }, m_cancelTokenSource)); //}); }
Task ProcessImport(List <string> data, IProgress <ProgressReport> progress) { int index = 1; int totalProgress = data.Count; var progressReport = new ProgressReport(); return(Task.Run(() => { for (int i = 0; i < totalProgress; i++) { progressReport.percentComplete = index++ *100 / totalProgress; progress.Report(progressReport); Thread.Sleep(15); } })); }
private void OnProgressChanged(ProgressReport progress) { if (progress.reportType == ReportType.Percent) { statusProgressBar.Value = (int)progress.data; } if (progress.reportType == ReportType.Message || progress.reportType == ReportType.MessageInfo) { statusMessage.Text = (string)progress.data; } if (progress.reportType == ReportType.Log) { AppendLog((string)progress.data); } }
public async Task RunDownloadParallelAsync(List <Country> Countries, IProgress <ProgressReport> progress) { List <Task> tasks = new List <Task>(); ProgressReport report = new ProgressReport(); foreach (Country country in Countries) { tasks.Add(Task.Run(() => DownloadSVG(country, progress, report, Countries.Count * 2))); tasks.Add(Task.Run(() => DownloadThumbnail(country, progress, report, Countries.Count * 2))); } await Task.WhenAll(tasks); }
public void ConstructorTest() { var report = new ProgressReport(10, 25); Assert.AreEqual(10, report.Current); Assert.AreEqual(25, report.Total); Assert.AreEqual(40, report.Percentage); Assert.IsTrue(string.IsNullOrWhiteSpace(report.Message)); report = new ProgressReport(15, 25, "Some Message"); Assert.AreEqual(15, report.Current); Assert.AreEqual(25, report.Total); Assert.AreEqual(60, report.Percentage); Assert.AreEqual("Some Message", report.Message); }
/// <summary> /// Loads Country's General Information from Database asynchronously. /// </summary> /// <param name="progress"></param> /// <returns>List</returns> public async Task <List <Country> > LoadCountryDataAsync(IProgress <ProgressReport> progress) { List <Country> Countries = new List <Country>(); ProgressReport report = new ProgressReport(); try { string sql = "SELECT Alpha3Code, Alpha2Code, Country.Name, Capital, Region, SubRegion, Population, Gini FROM Country"; command = new SQLiteCommand(sql, connection); SQLiteDataReader reader = command.ExecuteReader(); while (await Task.Run(() => reader.Read())) { await Task.Run(() => Countries.Add(new Country { Alpha3Code = (string)reader["Alpha3Code"], Alpha2Code = (string)reader["Alpha2Code"], Name = (string)reader["Name"], Capital = (string)reader["Capital"], Region = (string)reader["Region"], SubRegion = (string)reader["SubRegion"], Population = (int)reader["Population"], Gini = (double?)reader["Gini"], })); } foreach (var country in Countries) { country.Currencies = (await LoadCurrencyData(country.Alpha3Code)); } await LoadRatesData(); report.SaveCountries = Countries; report.PercentageComplete = (report.SaveCountries.Count * 100) / Countries.Count; progress.Report(report); connection.Close(); return(Countries); } catch (Exception ex) { dialogService.ShowMessage("Error", ex.Message); return(null); } }
public static void BuildMesh(string name, Stream obj, Stream mtl, ProgressReport progressReporter) { Misc.CheckArchive(ArchivePath); Mesh m = new Mesh(name); m.BuildFromFile(obj, mtl, progressReporter); //m.LoadMTL(fromFile.Folder+fromFile.Name + ".mtl"); //m.BuildOBJ(obj, mtl, fromFile.Folder+fromFile.Name, progressReporter); }
/// <summary> /// This method will update the local xml with sites retrieved from the global webservice. It will also download icons, banner and updated dlls. /// Make sure the local sites are loaded and all paths (<see cref="OnlineVideoSettings.DllsDir"/>, <see cref="OnlineVideoSettings.ConfigDir"/>, <see cref="OnlineVideoSettings.ThumbsDir"/>) are set before calling. /// </summary> /// <param name="progressCallback">pointer to the <see cref="ProgressReport"/> delegate that will receive progress information</param> /// <param name="onlineSitesToUpdate">update the local sites from this list of online sites, if null (default) the complete global list is retrieved</param> /// <param name="onlyUpdateNoAdd">true (default) -> only update already existing local sites, false -> update and add sites from the online list</param> /// <param name="skipCategories">do not update the categories of existing local sites if true (default is false so categories will also be updated)</param> /// <returns> /// <list type="bullet"> /// <item><term>true</term><description>new dlls were downloaded during the update</description></item> /// <item><term>false</term><description>no changes to the local sites or dlls were done</description></item> /// <item><term>null</term><description>update changed only the local xml</description></item> /// </list> /// </returns> public static bool? UpdateSites(ProgressReport progressCallback = null, List<Site> onlineSitesToUpdate = null, bool onlyUpdateNoAdd = true, bool skipCategories = false) { bool newDllsDownloaded = false; bool saveRequired = false; try { if (progressCallback != null) progressCallback.Invoke(Translation.Instance.CheckingForPluginUpdate, 0); if (!VersionCompatible) return false; if (progressCallback != null) progressCallback.Invoke(Translation.Instance.RetrievingRemoteSites, 2); GetRemoteOverviews(); if (onlineSitesToUpdate == null && onlineSites != null) onlineSitesToUpdate = onlineSites.ToList(); if (onlineSitesToUpdate == null || onlineSitesToUpdate.Count == 0) return false; if (progressCallback != null) if (!progressCallback.Invoke(null, 10)) return false; Dictionary<string, bool> requiredDlls = new Dictionary<string, bool>(); for (int i = 0; i < onlineSitesToUpdate.Count; i++) { Site onlineSite = onlineSitesToUpdate[i]; SiteSettings localSite = null; int localSiteIndex = OnlineVideoSettings.Instance.GetSiteByName(onlineSite.Name, out localSite); if (localSiteIndex == -1) { // add if (!onlyUpdateNoAdd) { // remember what dlls are required and check for changed dlls later if (!string.IsNullOrEmpty(onlineSite.RequiredDll)) requiredDlls[onlineSite.RequiredDll] = true; if (progressCallback != null) progressCallback.Invoke(onlineSite.Name, null); localSite = GetRemoteSite(onlineSite.Name); if (localSite != null) { // disable local site if broken if (onlineSite.State == SiteState.Broken) localSite.IsEnabled = false; OnlineVideoSettings.Instance.AddSite(localSite); saveRequired = true; } } } else // update { // remember what dlls are required and check for changed dlls later (regardless of lastUpdated on site) if (!string.IsNullOrEmpty(onlineSite.RequiredDll)) requiredDlls[onlineSite.RequiredDll] = true; // get site if updated on server if ((onlineSite.LastUpdated - localSite.LastUpdated).TotalMinutes > 2) { // don't show the name of that site while updating if it is an adult site and the pin has not been entered yet bool preventMessageDuetoAdult = (localSite.ConfirmAge && OnlineVideoSettings.Instance.UseAgeConfirmation && !OnlineVideoSettings.Instance.AgeConfirmed); if (progressCallback != null && !preventMessageDuetoAdult) progressCallback.Invoke(localSite.Name, null); SiteSettings updatedSite = GetRemoteSite(onlineSite.Name); if (updatedSite != null) { // keep Categories if flag was set if (skipCategories) updatedSite.Categories = localSite.Categories; OnlineVideoSettings.Instance.SetSiteAt(localSiteIndex, updatedSite); localSite = updatedSite; saveRequired = true; } } // disable local site if status of online site is broken if (onlineSite.State == OnlineVideos.OnlineVideosWebservice.SiteState.Broken && localSite.IsEnabled) { localSite.IsEnabled = false; OnlineVideoSettings.Instance.SetSiteAt(localSiteIndex, localSite); saveRequired = true; } } if (progressCallback != null) if (!progressCallback.Invoke(null, (byte)(10 + (70 * (i + 1) / onlineSitesToUpdate.Count)))) return false; } if (progressCallback != null) if (!progressCallback.Invoke(null, null)) return false; if (requiredDlls.Count > 0) { if (progressCallback != null) progressCallback.Invoke(Translation.Instance.RetrievingRemoteDlls, null); // temp target directory for dlls (if exists, delete and recreate) string dllTempDir = Path.Combine(Path.GetTempPath(), "OnlineVideos\\"); if (Directory.Exists(dllTempDir)) Directory.Delete(dllTempDir, true); Directory.CreateDirectory(dllTempDir); int dllsToCopy = 0; for (int i = 0; i < onlineDlls.Length; i++) { Dll anOnlineDll = onlineDlls[i]; if (progressCallback != null) progressCallback.Invoke(anOnlineDll.Name, null); if (requiredDlls.ContainsKey(anOnlineDll.Name)) { // update or download dll if needed string location = Path.Combine(OnlineVideoSettings.Instance.DllsDir, anOnlineDll.Name + ".dll"); bool download = true; if (File.Exists(location)) { byte[] data = null; data = File.ReadAllBytes(location); string md5LocalDll = BitConverter.ToString(md5Service.ComputeHash(data)).Replace("-", "").ToLower(); if (md5LocalDll == anOnlineDll.MD5) { download = false; } else { // MD5 is different - check compile time of local dll vs. LastUpdated of remote dll if (Helpers.FileUtils.RetrieveLinkerTimestamp(location) > anOnlineDll.LastUpdated) { download = false; // local dll is most likely self-compiled - do not download server dll Log.Info("Local '{0}.dll' was compiled later that online version - skipping download", anOnlineDll.Name); } } } if (download) { // download dll to temp dir first if (DownloadDll(anOnlineDll.Name, dllTempDir + anOnlineDll.Name + ".dll")) { newDllsDownloaded = true; // if download was successfull, try to copy to target dir (if not successfull, mark for UAC prompted copy later) try { File.Copy(dllTempDir + anOnlineDll.Name + ".dll", location, true); } catch { dllsToCopy++; } } } } if (progressCallback != null) progressCallback.Invoke(null, (byte)(80 + (15 * (i + 1) / onlineDlls.Length))); } if (dllsToCopy > 0) CopyDlls(dllTempDir, OnlineVideoSettings.Instance.DllsDir); } if (saveRequired) { if (progressCallback != null) progressCallback.Invoke(Translation.Instance.SavingLocalSiteList, 98); OnlineVideoSettings.Instance.SaveSites(); } } catch (Exception ex) { Log.Error(ex); } finally { if (progressCallback != null) progressCallback.Invoke(Translation.Instance.Done, 100); } if (newDllsDownloaded) return true; else if (saveRequired) return null; else return false; }
private static void ReportProgress(LogLevel level, InstallerPhase phase, string message, int percentComplete) { // if we're running in the main thread, just call the function. ProgressReport msg = new ProgressReport(); msg.Phase = phase; msg.Level = level; msg.Message = message; int current_thread_id = Thread.CurrentThread.ManagedThreadId; ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentComplete, msg); if (current_thread_id == m_main_thread_id) { m_worker_ProgressChanged(null, args); } else if (m_init_thread.IsBusy) { m_init_thread.ReportProgress(percentComplete, msg); } else if (m_install_thread.IsBusy) { m_install_thread.ReportProgress(percentComplete, msg); } else { throw new RhinoInstallerException("ReportProgress called with unexpected thread context."); } }
private void bwFetcher_DoWork(object sender, DoWorkEventArgs e) { ProgressReport pr = new ProgressReport(); pr.type = "taskstart"; pr.status = "Connecting to Steam API..."; bwFetcher.ReportProgress(0, pr); List<SteamFriend> friends = new List<SteamFriend>(); List<SteamUserTile> controls = new List<SteamUserTile>(); using (dynamic steamUser = WebAPI.GetInterface("ISteamUser", "D0EEFB98C8993BA3AC91A55879D28D91")) { steamUser.Timeout = (int)TimeSpan.FromSeconds(20).TotalMilliseconds; KeyValue results = steamUser.GetFriendList(steamid: _steamid, method: WebRequestMethods.Http.Get, secure: true); pr.status = "Fetching friends..."; bwFetcher.ReportProgress(0, pr); foreach (var f in results.Children[0].Children) { SteamFriend friend = new SteamFriend(); friend.steamid = f.Children[0].Value; friend.relationship = f.Children[1].Value; friend.friend_since = f.Children[2].Value; friends.Add(friend); } pr.type = "friendscount"; pr.value = friends.Count; bwFetcher.ReportProgress(0, pr); string ssteamids = ""; int count = 0; int handled = 0; int batchdone = 0; do { ssteamids += friends[count].steamid; count++; handled++; if (handled == 100 || count == friends.Count) { //Get user info steamUser.Timeout = (int)TimeSpan.FromSeconds(20).TotalMilliseconds; KeyValue result = steamUser.GetPlayerSummaries(steamids: ssteamids, MethodAccessException: WebRequestMethods.Http.Get, secure: true); for (int k = 0; k < handled; k++) { int index = (100 * batchdone) + k; friends[index].name = FetchKeyValue(result.Children[0].Children[0].Children[k], "personaname"); friends[index].profileurl = FetchKeyValue(result.Children[0].Children[0].Children[k], "profileurl"); friends[index].avatar = FetchKeyValue(result.Children[0].Children[0].Children[k], "avatarmedium"); } handled = 0; ssteamids = ""; batchdone++; } else { ssteamids += ","; } bwFetcher.ReportProgress(count, pr); } while (count < friends.Count); //Creating user tiles int num = 0; pr.type = "taskstart"; pr.status = "Creating tiles...."; bwFetcher.ReportProgress(0, pr); pr.type = "friendscount"; pr.value = friends.Count; bwFetcher.ReportProgress(0, pr); foreach (var friend in friends) { SteamUserTile tile = new SteamUserTile(); tile.SteamName = friend.name; tile.SteamProfile = friend.profileurl; tile.Avatar = friend.avatar; tile.Top = 5 + (85 * num); controls.Add(tile); num++; bwFetcher.ReportProgress(num, pr); } this.Friends = friends; this.Tiles = controls; } }