private void uploadAdBlank_ItemClick(object sender, ItemClickEventArgs e) { var row = gridView.GetFocusedRow() as MelaveMalkaInfo; string filePath; using (var dialog = new OpenFileDialog { Filter = "PDF Files (*.pdf)|*.pdf|All Files|*.*", Title = "Select " + row.Year + " Ad Blank" }) { if (dialog.ShowDialog(this) == DialogResult.Cancel) { return; } filePath = dialog.FileName; } if (!filePath.Contains(row.Year.ToString(CultureInfo.InvariantCulture))) { if (!Dialog.Warn("Are you sure that " + filePath + " is the " + row.Year + " ad blank?")) { return; } } ProgressWorker.Execute(progress => { progress.Caption = "Uploading " + Path.GetFileName(filePath); FtpClient.Default.UploadFile(row.AdBlankPath, filePath, progress); }, cancellable: false); }
public static void RunCheck() { if (Checker == null) { return; } if (RestartPending) { return; } UpdateInfo update = null; if (Program.UIInvoker != null && Program.UIInvoker.InvokeRequired) { update = Checker.FindUpdate(); } else //If we're running on the UI thread { ProgressWorker.Execute(ui => { ui.Caption = "Searching for updates..."; update = Checker.FindUpdate(); }, false); } if (update == null || !UIInvoke(() => ApplyUpdate(update))) { timer.Start(); //If we didn't find an update, or if the update wasn't applied, check again later } }
/// <summary> /// Upgrades the ini edits log entries. /// </summary> /// <remarks> /// This analyses the mods and determines, as best as possible, who edited which keys, and attempts /// to reconstruct the install order. The resulting information is then put in the new install log. /// </remarks> /// <param name="p_xmlModInstallLog">The current mod install log we are parsing to upgrade.</param> /// <param name="p_strModBaseName">The base name of the mod whose install log is being parsed.</param> private void UpgradeIniEdits(XmlDocument p_xmlModInstallLog, string p_strModBaseName) { var xnlIniEdits = p_xmlModInstallLog.SelectNodes("descendant::iniEdits/*"); foreach (XmlNode xndIniEdit in xnlIniEdits) { var strFile = xndIniEdit.Attributes.GetNamedItem("file").Value; var strSection = xndIniEdit.Attributes.GetNamedItem("section").Value; var strKey = xndIniEdit.Attributes.GetNamedItem("key").Value; string strOldIniEditor; var strOldValue = GetOldIniValue(strFile, strSection, strKey, out strOldIniEditor); if (p_strModBaseName.Equals(strOldIniEditor)) { //this mod owns the ini edit, so append it to the list of editing mods... InstallLog.Current.AddIniEdit(strFile, strSection, strKey, p_strModBaseName, NativeMethods.GetPrivateProfileString(strSection, strKey, "", strFile)); //...and backup the old value as the original value InstallLog.Current.PrependAfterOriginalIniEdit(strFile, strSection, strKey, InstallLog.ORIGINAL_VALUES, strOldValue); } else { //someone else made the ini edit // we don't know what value was overwritten, so we will just use what we have // which is the old value stored in the old install log InstallLog.Current.PrependAfterOriginalIniEdit(strFile, strSection, strKey, p_strModBaseName, strOldValue); } if (ProgressWorker.Cancelled()) { return; } ProgressWorker.StepItemProgress(); } }
public void ExecuteCompactDb(ICommandContext context) { ProgressWorker.Run( context, false, progressVisualizer => { progressVisualizer.SetProgressText(Resources.CompactDbProgressText); var janusDatabaseManager = context.GetRequiredService <IJanusDatabaseManager>(); using (janusDatabaseManager.GetLock().GetWriterLock()) using (var con = new SQLiteConnection(janusDatabaseManager.GetCurrentConnectionString())) using (var cmd = con.CreateCommand()) { con.Open(); // This is a REALLY long operation cmd.CommandTimeout = Int32.MaxValue; // Clean up the backend database file cmd.CommandText = @"pragma page_size=" + SqliteSchemaDriver.PageSize + @"; VACUUM; ANALYZE;"; cmd.ExecuteNonQuery(); } }); }
/// <summary> /// Upgrades the Install Log to the current version from version 0.1.1.0. /// </summary> /// <remarks> /// This method is called by a background worker to perform the actual upgrade. /// </remarks> protected override void DoUpgrade() { InstallLog.Current.SetInstallLogVersion(InstallLog.CURRENT_VERSION); InstallLog.Current.Save(); var xmlInstallLog = new XmlDocument(); xmlInstallLog.Load(InstallLog.Current.InstallLogPath); var xndRoot = xmlInstallLog.SelectSingleNode("installLog"); var xndSdpEdits = xndRoot.SelectSingleNode("sdpEdits"); ProgressWorker.OverallProgressStep = 1; ProgressWorker.OverallProgressMaximum = xndSdpEdits.ChildNodes.Count; ProgressWorker.ShowItemProgress = false; //remove the sdp edit node... xndSdpEdits.ParentNode.RemoveChild(xndSdpEdits); //...and replace it with the game-specific edits node var xndGameSpecificsValueEdits = xndRoot.AppendChild(xmlInstallLog.CreateElement("gameSpecificEdits")); foreach (XmlNode xndSdpEdit in xndSdpEdits.ChildNodes) { ProgressWorker.StepOverallProgress(); var xndGameSpecificsValueEdit = xndGameSpecificsValueEdits.AppendChild(xmlInstallLog.CreateElement("edit")); var strValueKey = String.Format("sdp:{0}/{1}", xndGameSpecificsValueEdits.Attributes["package"].Value, xndGameSpecificsValueEdits.Attributes["shader"].Value); xndGameSpecificsValueEdit.Attributes.Append(xmlInstallLog.CreateAttribute("key")).Value = strValueKey; xndGameSpecificsValueEdit.AppendChild(xndSdpEdit.FirstChild.Clone()); } xmlInstallLog.Save(InstallLog.Current.InstallLogPath); }
private void importSources_ListItemClick(object sender, ListItemClickEventArgs e) { var source = importers[e.Index]; using (var openDialog = new OpenFileDialog { Filter = source.Filter, Title = "Load " + source.Name }) { if (openDialog.ShowDialog(MdiParent) == DialogResult.Cancel) { return; } SynchronizationContext uiThread = SynchronizationContext.Current; try { using (AppFramework.Current.DataContext.BeginLoadData(uiThread)) ProgressWorker.Execute( MdiParent, progress => source.Import(openDialog.FileName, uiThread, progress), cancellable: true ); } catch (Exception ex) { Dialog.ShowError("An error occurred while importing payments.\r\n" + ex.GetBaseException().Message); } peopleView.BestFitColumns(); } }
public bool Publish() { using (var rsa = GetRSA()) { if (rsa == null) { return(false); } bool succeeded = false; ProgressWorker.Execute(ui => { ui.Caption = "Creating directory..."; FtpClient.Default.CreateDirectory(remoteBaseFolder); GatherFiles(ui, rsa); xml.Add(new XElement("Files", allFiles.Select(uf => uf.ToXml()))); DeleteOldFiles(ui); UploadFiles(ui); UploadXml(ui); succeeded = true; }, false); return(succeeded); } }
///<summary>Saves any changes made to the Singularity DataContext.</summary> public void SaveDatabase() { Debug.Assert(SyncContext.Tables.Any(), "There aren't any TableSynchronizers!"); if (!HasDataChanged) { return; } ProgressWorker.Execute(SyncContext.WriteData, cancellable: true); }
public void ExecuteCompactDb(ICommandContext context) { ProgressWorker.Run( context, false, progressVisualizer => { progressVisualizer.SetProgressText(Resources.CompactDbProgressText); var janusDatabaseManager = context.GetRequiredService <IJanusDatabaseManager>(); using (janusDatabaseManager.GetLock().GetWriterLock()) { var connectionString = janusDatabaseManager.GetCurrentConnectionString(); // Ensure there is no cached connections to the DB // SqlConnection.ClearAllPools(); string dbName; using (var con = MssqlSchemaDriver.ConnectToMaster(connectionString, out dbName)) using (var cmd = con.CreateCommand()) { con.Open(); // This is a REALLY long operation // cmd.CommandTimeout = Int32.MaxValue; // Set the database in single user mode. // cmd.CommandText = @"EXEC sp_dboption '" + dbName + @"', 'single user', 'True'"; cmd.ExecuteNonQuery(); // Shrink the database size to the size + 10 percent of free space. // The truncateonly attribute releases the shrunken space to // the operating system. // cmd.CommandText = @"DBCC ShrinkDatabase(" + dbName + @", 10, TRUNCATEONLY)"; cmd.ExecuteNonQuery(); // Checks the integrity of the db, and repairs some issues without // data loss. This will rebuild your indexes. // cmd.CommandText = @"DBCC CheckDB(" + dbName + @", REPAIR_REBUILD)"; cmd.ExecuteNonQuery(); // Sets the db back to full access. // cmd.CommandText = @"EXEC sp_dboption '" + dbName + @"', 'single user', 'False'"; cmd.ExecuteNonQuery(); } } }); }
public void ExecuteCompactDb(ICommandContext context) { ProgressWorker.Run( context, false, progressVisualizer => { progressVisualizer.SetProgressText(Resources.CompactDbProgressText); var janusDatabaseManager = context.GetRequiredService <IJanusDatabaseManager>(); using (janusDatabaseManager.GetLock().GetWriterLock()) { var connectionString = janusDatabaseManager.GetCurrentConnectionString(); var csb = new JetConnectionStringBuilder(connectionString); var dbFile = csb.DataSource; var tmpFile = dbFile + ".temp"; var backupFile = dbFile + ".bak"; csb.DataSource = tmpFile; if (File.Exists(tmpFile)) { File.Delete(tmpFile); } OleDbConnection.ReleaseObjectPool(); var engine = (IJetEngine) new JetEngineClass(); try { engine.CompactDatabase(connectionString, csb.ConnectionString); } finally { Marshal.ReleaseComObject(engine); } if (Environment.OSVersion.Platform == PlatformID.Win32Windows) { // Unsafe replace // File.Move(tmpFile, dbFile); File.Delete(tmpFile); } else { // Safe replace // File.Replace(tmpFile, dbFile, backupFile); File.Delete(backupFile); } } }); }
private void emailTemplateList_ListItemClick(object sender, ListItemClickEventArgs e) { var actualCallers = ConfirmSendEmailTemplate(); if (actualCallers == null) { return; } Program.LoadTables(MelaveMalkaInfo.Schema, MelaveMalkaSeat.Schema, MelaveMalkaInvitation.Schema); //Used by the templates var template = emailTemplateList.Strings[e.Index]; ProgressWorker.Execute(progress => { progress.Maximum = actualCallers.Count * 2; //Two steps per caller foreach (var caller in actualCallers) { if (progress.WasCanceled) { return; } progress.Caption = "Creating spreadsheet for " + caller.Name; string attachmentPath; do { attachmentPath = Path.GetTempFileName(); File.Delete(attachmentPath); attachmentPath = Path.ChangeExtension(attachmentPath, ".xls"); //OleDB cannot write XLS with other extensions } while (File.Exists(attachmentPath)); try { caller.CreateCallList(attachmentPath); if (progress.WasCanceled) { return; } progress.Progress++; progress.Caption = "Emailing " + caller.Name; using (var message = razor.CreateMessage(caller, template)) { message.From = Email.JournalAddress; message.To.Add(caller.EmailAddresses); //Comma-separated string message.Attachments.Add(new Attachment(attachmentPath, new ContentType { MediaType = "application/vnd.ms-excel", Name = "Call List for " + caller.Name + ".xls" })); Email.Default.Send(message); } } finally { File.Delete(attachmentPath); } progress.Progress++; } }, true); }
private void pushData_ItemClick(object sender, ItemClickEventArgs e) { var syncContext = CreateServerContext(); DBManager.PushData(Program.Current.DataContext, syncContext.DataContext); if (syncContext.Tables.Any(t => t.Changes.Any())) { ProgressWorker.Execute(syncContext.WriteData, cancellable: false); } }
/// <summary> /// Upgrades the Install Log to the current version from version 0.1.0.0. /// </summary> /// <remarks> /// This method is called by a background worker to perform the actual upgrade. /// </remarks> protected override void DoUpgrade() { var xmlInstallLog = new XmlDocument(); xmlInstallLog.Load(InstallLog.Current.InstallLogPath); var xndRoot = xmlInstallLog.SelectSingleNode("installLog"); if (xndRoot == null) { return; } var lstMods = InstallLog.Current.GetModList(); var xndSdpEdits = xndRoot.SelectSingleNode("sdpEdits"); if (xndSdpEdits != null) { ProgressWorker.OverallProgressStep = 1; ProgressWorker.OverallProgressMaximum = lstMods.Count + xndSdpEdits.ChildNodes.Count; ProgressWorker.ShowItemProgress = false; //remove the sdp edit node... xndSdpEdits.ParentNode.RemoveChild(xndSdpEdits); //...and replace it with the game-specific edits node var xndGameSpecificsValueEdits = xndRoot.AppendChild(xmlInstallLog.CreateElement("gameSpecificEdits")); foreach (XmlNode xndSdpEdit in xndSdpEdits.ChildNodes) { ProgressWorker.StepOverallProgress(); var xndGameSpecificsValueEdit = xndGameSpecificsValueEdits.AppendChild(xmlInstallLog.CreateElement("edit")); var strValueKey = $"sdp:{xndGameSpecificsValueEdits.Attributes["package"].Value}/{xndGameSpecificsValueEdits.Attributes["shader"].Value}"; xndGameSpecificsValueEdit.Attributes.Append(xmlInstallLog.CreateAttribute("key")).Value = strValueKey; xndGameSpecificsValueEdit.AppendChild(xndSdpEdit.FirstChild.Clone()); } } xmlInstallLog.Save(InstallLog.Current.InstallLogPath); //now update the mod info foreach (var strMod in lstMods) { ProgressWorker.StepOverallProgress(); if (strMod.Equals(InstallLog.ORIGINAL_VALUES) || strMod.Equals(InstallLog.FOMM)) { continue; } var strModPath = Path.Combine(Program.GameMode.ModDirectory, strMod + ".fomod"); var fomodMod = new fomod(strModPath); InstallLog.Current.UpdateMod(fomodMod); } InstallLog.Current.SetInstallLogVersion(InstallLog.CURRENT_VERSION); InstallLog.Current.Save(); }
void HandleNavigating(Object sender, WebBrowserNavigatingEventArgs args) { if (null == myNavWorker) { myNavWorker = new ProgressWorker(); myNavWorker.BlockUserInput = false; myNavWorker.DoWork += this.HandleNavWorkerDoWork; myNavWorker.Dequeued += this.HandleNavWorkerDequeued; myNavEvent.Reset(); myVegas.QueueProgressWorker(myNavWorker); } }
public void RunWorker(TArgument argument) { System.Windows.Forms.Application.DoEvents(); using (var worker = new ProgressWorker <TArgument> { Action = action }) { worker.RunWorkerAsync(); worker.RunWorkerCompleted += worker_RunWorkerCompleted; ShowDialog(); } }
private void doImport_ItemClick(object sender, ItemClickEventArgs e) { using (AppFramework.Current.DataContext.BeginLoadData()) ProgressWorker.Execute(MdiParent, progress => { progress.Maximum = AppFramework.Table <StagedPerson>().Rows.Count; foreach (var source in AppFramework.Table <StagedPerson>().Rows) { Person target; progress.Progress++; if (source.Person != null) { target = source.Person; progress.Caption = $"Importing {source.FullName} to {target.FullName}"; } else { progress.Caption = $"Importing {source.FullName} as new person"; target = new Person { Address = source.Address, City = source.City, FullName = source.FullName, HerName = source.HerName, HisName = source.HisName, LastName = source.LastName, Phone = source.Phone, State = source.State, Zip = source.Zip, Salutation = "", Source = "Migration", }; AppFramework.Table <Person>().Rows.Add(target); } foreach (var payment in source.StagedPayments) { AppFramework.Table <Payment>().Rows.Add(new Payment { Account = payment.Account, Amount = payment.Amount, CheckNumber = payment.CheckNumber, Comments = payment.Comments, Company = payment.Company, Date = payment.Date, Method = payment.Method, Person = target, Modifier = "Migration", // TODO: Change ExternalId to string and always set it. ExternalSource = "Migration", ExternalId = int.TryParse(payment.ExternalId, out var id) ? id : new int?() }); }
public IActionResult Status(String requestPath) { String reqPath = requestPath.Replace('/', Path.DirectorySeparatorChar); String realPath = Path.Combine(Configuration.Get.GalleryPath, reqPath); // The requested path must be a subdir of our configured gallery path, and it must exist if (realPath.Contains(Configuration.Get.GalleryPath) && Directory.Exists(realPath)) { using ProgressWorker progress = new ProgressWorker(new DirectoryInfo(realPath)); return(Ok(progress.GetProgress())); } return(NotFound()); }
void HandleNavWorkerDoWork(ProgressWorker worker, ProgressEventArgs args) { while (!worker.Canceled) { if (myNavEvent.WaitOne(100, false)) { break; } } if (worker.Canceled) { myBrowser.Stop(); } }
///<summary>Reads any changes from the database server.</summary> public void RefreshDatabase() { Debug.Assert(SyncContext.Tables.Any(), "There aren't any TableSynchronizers!"); var threadContext = SynchronizationContext.Current; ProgressWorker.Execute(progress => { if (HasDataChanged) { SyncContext.WriteData(progress); } progress.Caption = "Reading database"; progress.Maximum = -1; SyncContext.ReadData(threadContext); }, cancellable: false); }
void SendBills() { var exceptions = new List <KeyValuePair <Person, SmtpException> >(); var successes = new List <StatementMessage>(people.Length); PageBuilder.Prepare(emailTemplate.Text, startDate.DateTime); ProgressWorker.Execute(ui => { ui.Maximum = people.Length; foreach (var person in people) { ui.Caption = "Emailing " + person.VeryFullName; ui.Progress++; if (ui.WasCanceled) { return; } using (var message = PageBuilder.CreateMessage(person, emailTemplate.Text, startDate.DateTime)) { if (message == null) { continue; } message.To.AddRange(person.EmailAddresses.Select(e => e.MailAddress)); try { Email.Hosted.Send(message); successes.Add(message); } catch (SmtpException ex) { exceptions.Add(new KeyValuePair <Person, SmtpException>(person, ex)); } } } }, true); foreach (var info in successes) //The table can only be modified on the UI thread. { info.LogStatement(); } if (exceptions.Any()) { XtraMessageBox.Show("The following errors occurred while sending the emails:\r\n\r\n • " + exceptions.Join("\r\n\r\n • ", kvp => kvp.Key.FullName + ": " + kvp.Value.Message), "Shomrei Torah Billing", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
DataSyncContext CreateServerContext() { var context = new DataContext(); var syncContext = new DataSyncContext(context, new SqlServerSqlProvider(databases.SelectedConnector)); //Add all of the tables that we actually use. foreach (var ts in Program.Current.SyncContext.Tables.SortDependencies(ts => ts.Table.Schema)) { var table = ts.Table.Schema.CreateTable(); context.Tables.AddTable(table); syncContext.Tables.AddMapping(ts.Mapping); } ProgressWorker.Execute(ui => { ui.Caption = "Reading " + databases.SelectedItem.Caption; syncContext.ReadData(); }, cancellable: false); return(syncContext); }
private void sendSelected_ItemClick(object sender, ItemClickEventArgs args) { bindingSource.EndEdit(); //Commit any changes in the editor. (Very important; otherwise, any changes made since the last time it lost focus will not be sent) #region Validation var recipient = SelectedInvitee; if (recipient == null) { return; } if (recipient.AdAmount > 0) { Dialog.ShowError(recipient.Person.FullName + " already gave an ad."); return; } if (String.IsNullOrWhiteSpace(recipient.EmailSubject) || String.IsNullOrWhiteSpace(recipient.EmailSource)) { Dialog.ShowError("Please enter an email to send."); return; } if (recipient.ReminderEmails.Any(e => e.Date.Date == DateTime.Today)) { if (!Dialog.Warn(recipient.Person.FullName + " have already been emailed today.\r\nAre you sure you want to send another email?")) { return; } } else { if (!Dialog.Confirm("Would you like to email " + recipient.Person.FullName + "?")) { return; } } #endregion ProgressWorker.Execute(progress => { progress.Maximum = -1; progress.Caption = "Emailing " + recipient.Person.FullName; SendEmail(recipient); }, false); }
///<summary>Ensures that a set of tables are loaded in the DataContext.</summary> public static void LoadTables(IEnumerable <TableSchema> schemas) { var allSchemas = new HashSet <TableSchema>(); foreach (var schema in schemas.Where(s => Current.DataContext.Tables[s] == null)) { allSchemas.Add(schema); allSchemas.UnionWith(schema.GetDependencies()); } if (allSchemas.Count == 0) { return; //All of the tables are already loaded } var tables = allSchemas .SortDependencies() .Except(Current.DataContext.Tables.Select(t => t.Schema)) //Must be called after SortDependencies, since sorting requires all dependencies .Select(ts => ts.CreateTable()) .ToList(); //Calculated columns can use child rows. I must add the //tables in reverse order to allow the RowDependencies //to register handlers for the child tables. tables.Reverse(); tables.ForEach(Current.DataContext.Tables.AddTable); var syncers = tables.ConvertAll(t => new TableSynchronizer(t, SchemaMapping.GetPrimaryMapping(t.Schema), Current.SyncContext.SqlProvider)); syncers.ForEach(Current.SyncContext.Tables.Add); var threadContext = SynchronizationContext.Current; ProgressWorker.Execute(ui => { if (Current.HasDataChanged) { Current.SyncContext.WriteData(ui); //I must save before loading in case a parent row was deleted. (The DB is expected to cascade) } ui.Maximum = -1; ui.Caption = "Loading " + tables.Join(", ", t => t.Schema.Name); Current.SyncContext.ReadData(threadContext); //I must refresh everything to pick up potential changes in parent rows }, false); }
/// <summary> /// Upgrades the sdp edits log entries. /// </summary> /// <remarks> /// This analyses the mods and determines, as best as possible, who edited which shaders, and attempts /// to reconstruct the install order. The resulting information is then put in the new install log. /// </remarks> /// <param name="p_xmlModInstallLog">The current mod install log we are parsing to upgrade.</param> /// <param name="p_strModBaseName">The base name of the mod whose install log is being parsed.</param> private void UpgradeSdpEdits(XmlDocument p_xmlModInstallLog, string p_strModBaseName) { var xnlSdpEdits = p_xmlModInstallLog.SelectNodes("descendant::sdpEdits/*"); foreach (XmlNode xndSdpEdit in xnlSdpEdits) { var intPackage = Int32.Parse(xndSdpEdit.Attributes.GetNamedItem("package").Value); var strShader = xndSdpEdit.Attributes.GetNamedItem("shader").Value; var strShaderKey = String.Format("sdp:{0}/{1}", intPackage, strShader); var bteOldValue = GetOldSdpValue(intPackage, strShader); //we have no way of knowing who last edited the shader - that information // was not tracked // so, let's just do first come first serve if (!m_lstSeenShader.Contains(intPackage + "~" + strShader.ToLowerInvariant())) { //this is the first mod we have encountered that edited this shader, // so let's assume it is the lastest mod to have made the edit... InstallLog.Current.AddGameSpecificValueEdit(p_strModBaseName, strShaderKey, SDPArchives.GetShader(intPackage, strShader)); //...and backup the old value as the original value InstallLog.Current.PrependAfterOriginalGameSpecificValueEdit(InstallLog.ORIGINAL_VALUES, strShaderKey, bteOldValue); m_lstSeenShader.Add(intPackage + "~" + strShader.ToLowerInvariant()); } else { //someone else made the shader edit // we don't know what value was overwritten, so we will just use what we have // which is the old value InstallLog.Current.PrependAfterOriginalGameSpecificValueEdit(p_strModBaseName, strShaderKey, bteOldValue); } if (ProgressWorker.Cancelled()) { return; } ProgressWorker.StepItemProgress(); } }
void createDoc_Click(object sender, EventArgs e) { DefaultDuplexMode = duplexMode.Checked; var stmts = SelectedStatements; StatementGenerator.Prepare(stmts); ProgressWorker.Execute(ui => StatementGenerator.CreateBills(stmts, ui, duplexMode.Checked), true); if (DialogResult.Yes == XtraMessageBox.Show("Would you like to log these statements?", "Shomrei Torah Billing", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { foreach (var statement in stmts) { statement.LogStatement(); } } if (cancel.Text != "Close" && mailingDocuments.ItemLinks.Any()) { XtraMessageBox.Show("To create mailing labels or envelopes, click the down arrow next to Create Documents.", "Shomrei Torah Billing", MessageBoxButtons.OK, MessageBoxIcon.Information); } cancel.Text = "Close"; }
private void sendAll_ItemClick(object sender, ItemClickEventArgs args) { bindingSource.EndEdit(); //Commit any changes in the editor. (Very important; otherwise, any changes made since the last time it lost focus will not be sent) var allRecipients = ConfirmSendAll(); if (allRecipients == null) { return; } ProgressWorker.Execute(progress => { progress.Maximum = allRecipients.Count; foreach (var recipient in allRecipients) { progress.Caption = "Emailing " + recipient.Person.FullName; progress.Progress++; SendEmail(recipient); if (progress.WasCanceled) { return; } } }, true); }
public Task <Control> GetToolControl(ProgressWorker worker, SynchronizationContext context, Window window) { return(WPF.Tool.Export.HeroUnlocksView.Get(worker, context, window, NPCs)); }
public static void Export(int hebrewYear, bool includeנקודות) { ProgressWorker.Execute(ui => { MSWord.Visible = true; var document = MSWord.Documents.Add(); ui.Caption = "Creating document"; Range range; try { MSWord.ScreenUpdating = false; document.PageSetup.TopMargin = 13; document.PageSetup.BottomMargin = 10; range = document.Range(); range.Font.Name = "Calibri"; range.Font.NameBi = "David"; range.Font.Size = 12; range.Font.SizeBi = 13; range.ParagraphFormat.Space1(); var bracha = document.Range(); bracha.InsertAfter("\n"); if (includeנקודות) { bracha.Text = "בָּרוּךְ אַתָּה ה' אֱלֹקינוּ מֶלֶךְ הָעוֹלָם אֲשֶׁר קִדְּשָׁנוּ בְּמִצְוֹתָיו וְצִוָּנוּ עַל סְפִירַת הָעוֹמֶר"; } else { bracha.Text = "ברוך אתה ה' אלקינו מלך העולם אשר קדשנו במצותיו וציונו על ספירת העומר"; } bracha.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; bracha.ParagraphFormat.SpaceAfter = 2; range = document.Range(); range.Collapse(WdCollapseDirection.wdCollapseEnd); var table = document.Tables.Add(range, 49, 3); table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; table.Range.ParagraphFormat.SpaceAfter = 0; table.Columns[1].Width = MSWord.InchesToPoints(.32f); table.Columns[2].Width = MSWord.InchesToPoints(2.15f); table.Columns[3].Width = MSWord.InchesToPoints(4.5f); var border = table.Borders[WdBorderType.wdBorderHorizontal]; border.LineStyle = WdLineStyle.wdLineStyleSingle; border.LineWidth = WdLineWidth.wdLineWidth025pt; border.Color = WdColor.wdColorDarkBlue; foreach (var side in new[] { WdBorderType.wdBorderTop, WdBorderType.wdBorderRight, WdBorderType.wdBorderBottom, WdBorderType.wdBorderLeft }) { border = table.Borders[side]; border.LineStyle = WdLineStyle.wdLineStyleThickThinMedGap; border.LineWidth = WdLineWidth.wdLineWidth150pt; border.Color = WdColor.wdColorBlack; } MSWord.ScreenRefresh(); ui.Maximum = 49; ui.Caption = "Writing chart"; for (var date = Program.OmerStart(hebrewYear); date.Info.OmerDay != -1; date++) { var index = date.Info.OmerDay; var text = includeנקודות ? date.Info.OmerTextנקוד : date.Info.OmerText; if (ui.WasCanceled) { return; } ui.Progress = index; table.Rows[index].Range.Font.Color = (WdColor)ColorTranslator.ToOle(Program.GetColor(index)); table.Cell(index, 1).Range.Text = index.ToString(CultureInfo.CurrentCulture); table.Cell(index, 2).Range.Text = date.EnglishDate.AddDays(-1).ToString("dddd \"night\", MMMM d", CultureInfo.CurrentCulture); table.Cell(index, 3).Range.Text = text; } } finally { MSWord.ScreenUpdating = true; } range = document.Range(); range.Collapse(WdCollapseDirection.wdCollapseEnd); //range.Text = String.Format(CultureInfo.CurrentUICulture, // "ספירת העומר for {0} ({1}) | By Schabse S. Laks", // (hebrewYear - 5000).ToHebrewString(HebrewNumberFormat.LetterQuoted), // Program.OmerStart(hebrewYear).EnglishDate.Year); WriteFooter(range, hebrewYear); MSWord.Activate(); }, cancellable: true); }
void Run() { if (_running) { MessageBox.Show( "The neural network is training. Wait until done.", "Already running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } ProgressWorkerParams workerParams = new ProgressWorkerParams { Alignment = System.Drawing.ContentAlignment.BottomLeft, AllowCancel = true, ControlAnchor = frmMain.GInstance.MActiveChart, Modal = true, }; ProgressWorker.Run( workerParams, visualizer => { try { visualizer.SetProgressTitle("Neural Network"); visualizer.SetProgressAction("Initializing..."); AsyncNeuralNetwork worker = new AsyncNeuralNetwork(); bool first = true; worker.ProgressCallback += (object o, int records, int record, ref bool stop) => { if (first) { first = false; visualizer.InitProgress(0, records); } visualizer.ReportProgress(record); stop = visualizer.CancelReqested; }; visualizer.SetProgressAction("Training Neural Network..."); List <string> items = new List <string>(); foreach (NListBoxItem item in lstSelected.Items) { items.Add(item.Text); } // Do the work worker.DoWork(items); // Exit if no report if (worker.ResultCount < 1 || visualizer.CancelReqested) { return; // No work to report } visualizer.SetProgressAction("Completing..."); visualizer.InitProgress(0, worker.ResultCount); for (int n = 0; n < worker.ResultCount; ++n) { visualizer.ReportProgress(n); if (visualizer.CancelReqested) { break; } } } catch (Exception ex) { _asyncOp.Post( () => MessageBox.Show( "An error occured. Error :" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)); } finally { _running = false; } }, () => { }); }
public static Task <Control> Get(ProgressWorker a1, SynchronizationContext context, Window window, bool npc) { var source = new TaskCompletionSource <Control>(); context.Send(obj => { var control = new ImageGridView(); var t = new Thread(() => { if (!(obj is Tuple <ProgressWorker, TaskCompletionSource <Control> > tuple)) { return; } var worker = tuple.Item1; var tcs = tuple.Item2; try { var i = 0; worker.ReportProgress(0, "Loading heroes..."); if (TrackedFiles == null || !TrackedFiles.ContainsKey(0x75)) { throw new DataToolWpfException("Open storage first"); } var max = TrackedFiles[0x75].Count; foreach (var key in TrackedFiles[0x75]) { try { var hero = GetInstance <STUHero>(key); if (hero == null) { continue; } string heroNameActual = GetString(hero.m_0EDCE350) ?? teResourceGUID.Index(key).ToString("X"); heroNameActual = heroNameActual.TrimEnd(' '); ProgressionUnlocks progressionUnlocks = new ProgressionUnlocks(hero); if (progressionUnlocks.LevelUnlocks == null && !npc) { continue; } if (progressionUnlocks.LootBoxesUnlocks != null && npc) { continue; } var tex = hero.m_8203BFE1.FirstOrDefault(x => teResourceGUID.Index(x.m_id) == 0x40C9 || teResourceGUID.Index(x.m_id) == 0x40CA)?.m_texture; if (tex == 0) { tex = hero.m_8203BFE1.FirstOrDefault()?.m_texture; } var image = new byte[] { }; var width = 128; var height = 128; if (tex != 0) { teTexture texture = new teTexture(OpenFile(tex)); if (texture.PayloadRequired) { ulong payload = texture.GetPayloadGUID(tex); Stream payloadStream = OpenFile(payload); if (payloadStream != null) { texture.LoadPayload(payloadStream); } else { continue; } } width = texture.Header.Width; height = texture.Header.Height; Stream ms = texture.SaveToDDS(); image = DDSConverter.ConvertDDS(ms, DXGI_FORMAT.R8G8B8A8_UNORM, DDSConverter.ImageFormat.PNG, 0); } var entry = control.Add(heroNameActual, image, 128, (int)ImagingHelper.CalculateSizeAS(height, width, 128)); entry.Payload = progressionUnlocks; entry.OnClick += (sender, args) => { window.Close(); }; } catch { // ignored } finally { i += 1; worker.ReportProgress((int)(i / (float)max * 100)); } } tcs.SetResult(control); } catch (Exception e) { tcs.SetException(e); } finally { worker.ReportProgress(100); } }); t.SetApartmentState(ApartmentState.STA); t.Start(); }, new Tuple <ProgressWorker, TaskCompletionSource <Control> >(a1, source)); return(source.Task); }