private void loadSubscriptionsFromRepository() { try { TableauRepository rep = new TableauRepository(Configurator.GetConfig("tableau_server"), Configurator.GetConfig("repository_pw"), "readonly"); rep.logger = this.logger; NpgsqlDataReader dr = rep.query_inactive_subscription_schedules(); Dictionary <string, int> input_box_schedules = new Dictionary <string, int>(); int rowCount = 0; availableSchedulesList.Items.Clear(); if (dr.HasRows == true) { while (dr.Read()) { availableSchedulesList.Items.Add(dr.GetString(1)); input_box_schedules[dr.GetString(1)] = rowCount; rowCount++; } } dr.Close(); // Check the selected schedules from the configs StringCollection checked_schedules = Configurator.GetConfigCollection("selected_schedule_names"); if (checked_schedules != null) { foreach (String sched_name in checked_schedules) { availableSchedulesList.SetItemChecked(input_box_schedules[sched_name], true); } } } catch (NpgsqlException ne) { this.logger.Log("Error with repository while loading the available schedules. Press reload button to try again. Going with existing checked schedules for now"); this.logger.Log(ne.Message); // Fill in the checkbox list based on the existing selected schedules StringCollection checked_schedules = Configurator.GetConfigCollection("selected_schedule_names"); if (checked_schedules != null) { var i = 0; Dictionary <string, int> input_box_schedules = new Dictionary <string, int>(); availableSchedulesList.Items.Clear(); foreach (String sched_name in checked_schedules) { availableSchedulesList.Items.Add(sched_name); input_box_schedules[sched_name] = i; availableSchedulesList.SetItemChecked(input_box_schedules[sched_name], true); i++; } } } catch (ConfigurationException ce) { this.logger.Log("Incorrect credentials for repository readonly user. Cannot connect to repository."); MessageBox.Show("Credentials were not correct for the Repository \"readonly\" user. Please fix"); } }
/* * Main E-mailing methods (used by all) */ public SmtpClient CreateSmtpClientFromConfig() { SmtpClient smtp_client = new SmtpClient(Configurator.GetConfig("smtp_server")); // Set all of the SMTP Server options var port = Configurator.GetConfig("smtp_server_port"); if (port != "") { smtp_client.Port = Int32.Parse(port); } var tls = Configurator.GetConfig("smtp_server_tls"); if (tls == "Yes") { smtp_client.EnableSsl = true; } var smtpServerUsername = Configurator.GetConfig("smtp_server_username"); var smtpServerPassword = Configurator.GetConfig("smtp_server_password"); if (smtpServerUsername != "" && smtpServerPassword != "") { smtp_client.Credentials = new System.Net.NetworkCredential(smtpServerUsername, smtpServerPassword); } return(smtp_client); }
public bool SendEmail() { try { BeholdEmailer tabemailer = this.CreateBeholdEmailerFromConfig(); Watermarker wm = this.CreateWatermarkerFromConfig(); try { bool result; result = tabemailer.GenerateEmailFromView(Configurator.GetConfig("email_sender"), new string[1] { testEmailRecipient.Text }, new string[0] { }, new string[0] { }, testEmailSubject.Text, "Please see attached Tableau file", singleUsernameForImpersonation.Text, singleViewLocation.Text, "fullpdf", new Dictionary <String, String>(), wm); return(result); } catch (ConfigurationException ce) { this.Logger.Log(ce.Message); return(false); } } // From Repository Failing catch (ConfigurationException ce) { this.Logger.Log(ce.Message); return(false); } }
private BeholdEmailer CreateBeholdEmailerFromConfig(string site) { var tabrep = new TableauRepository( Configurator.GetConfig("tableau_server"), Configurator.GetConfig("repository_pw"), "readonly" ) { logger = this.Logger }; var tabcmd = new Tabcmd( Configurator.GetConfig("tabcmd_program_location"), Configurator.GetConfig("tableau_server"), Configurator.GetConfig("server_admin_username"), Configurator.GetConfig("server_admin_password"), site, Configurator.GetConfig("tabcmd_config_location"), tabrep, this.Logger ); BeholdEmailer tabemailer = new BeholdEmailer(tabcmd, this.CreateSmtpClientFromConfig()); tabemailer.Logger = this.Logger; tabemailer.HtmlEmailTemplateFilename = Configurator.GetConfig("html_email_template_filename"); tabemailer.TextEmailTemplateFilename = Configurator.GetConfig("text_email_template_filename"); return(tabemailer); }
public bool SendEmail(string site, string[] emailTo, string[] emailCc, string[] emailBcc, string emailSubject, string usernameForImpersonation, string viewLocation, Dictionary <String, String> viewFiltersMap, string attachmentContentType) { try { BeholdEmailer tabemailer = this.CreateBeholdEmailerFromConfig(site); Watermarker wm = this.CreateWatermarkerFromConfig(); try { bool result; this.Logger.Log("Fixin' to send the e-mail"); result = tabemailer.GenerateEmailFromView(Configurator.GetConfig("email_sender"), emailTo, emailCc, emailBcc, emailSubject, "Please see attached Tableau file", usernameForImpersonation, viewLocation, attachmentContentType.ToLower(), viewFiltersMap, wm); return(result); } catch (ConfigurationException ce) { this.Logger.Log(ce.Message); return(false); } } // From Repository Failing catch (ConfigurationException ce) { this.Logger.Log(ce.Message); return(false); } }
// In this situation you create the tabcmd and smtpClient objects separately public BeholdEmailer(Tabcmd tabcmd, SmtpClient smtpClient) { this.Tabcmd = tabcmd; this.TableauServerUrl = this.Tabcmd.TableauServerUrl; this.SmtpServer = smtpClient; this.HtmlEmailTemplateFilename = ""; this.TextEmailTemplateFilename = ""; this.Logger = null; this.ExportArchiveFolderPath = null; if (Configurator.GetConfigBool("save_emailed_copies_flag")) { SaveEmailsToArchive = Configurator.GetConfigBool("save_emailed_copies_flag"); } if (!String.IsNullOrEmpty(Configurator.GetConfig("export_archive_folder"))) { this.ExportArchiveFolderPath = Configurator.GetConfig("export_archive_folder"); } // Cancel action if no archive folder exists else { MessageBox.Show("Please configure the local save folder", "No Local Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new ConfigurationException("Please configure the local save folder"); } }
// Original constructor created the tabcmd object public BeholdEmailer(string tabcmdDirectory, string tabcmdConfigLocation, string repositoryPassword, string tableauServerUrl, string tableauServerAdminUsername, string tableauServerAdminPassword, string smtpServerName, string smtpServerUsername, string smtpServerPassword) { this.TableauServerUrl = tableauServerUrl; this.RepositoryPassword = repositoryPassword; this.SmtpServer = new SmtpClient(smtpServerName); this.HtmlEmailTemplateFilename = ""; this.TextEmailTemplateFilename = ""; // Add credentials stuff here this.Tabcmd = new Tabcmd(tabcmdDirectory, tableauServerUrl, tableauServerAdminUsername, tableauServerAdminPassword, "default", repositoryPassword, tabcmdConfigLocation); this.Logger = null; if (Configurator.GetConfigBool("save_emailed_copies_flag")) { SaveEmailsToArchive = Configurator.GetConfigBool("save_emailed_copies_flag"); } if (!String.IsNullOrEmpty(Configurator.GetConfig("export_archive_folder"))) { this.ExportArchiveFolderPath = Configurator.GetConfig("export_archive_folder"); } // Cancel action if no archive folder exists else { MessageBox.Show("Please configure the local save folder", "No Local Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new ConfigurationException("Please configure the local save folder"); } }
public MainWindow() { InitializeComponent(); nextActivityId = 1; // Load actions from the queue filename asyncActionQueue = new List <queueAction>(); // Initialize shared logger this.Logger = new SimpleLogger("log.txt"); ExportTypeIndexMap = new string[] { "fullpdf", "pdf", "png", "csv" }; // Fill in some fields singleViewLocation.Text = Configurator.GetConfig("single_export_view_location"); singleExportSite.Text = Configurator.GetConfig("single_export_site"); singleUsernameForImpersonation.Text = Configurator.GetConfig("single_export_impersonate_as_user"); exportTypeDropDown.SelectedIndex = Int32.Parse(Configurator.GetConfig("single_export_type_index")); // Initializing queue system int minutesBetweenTimer = 1; this.scheduleMonitorTimer = new System.Windows.Forms.Timer(); scheduleMonitorTimer.Interval = minutesBetweenTimer * 60 * 1000; this.scheduleMonitorTimer.Tick += queueSchedulesOnTimer; this.ActiveSchedulesQueueFilename = "active_schedules.csv"; string completedSchedulesFilename = "completed_schedules.csv"; this.ActiveSchedules = new List <string[]>(); try { // Read anything in the active_schedules file string[] lastActiveSchedules = File.ReadAllLines(ActiveSchedulesQueueFilename); foreach (string scheduleLine in lastActiveSchedules) { string[] cols = scheduleLine.Split('|'); ActiveSchedules.Add(cols); this.Logger.Log(String.Format("Loaded {0} at {1} to active schedules from disk", cols[0], cols[1])); } // Open up the streams to keep track of what happens even if the program fails this.CompletedSchedulesFile = new StreamWriter(completedSchedulesFilename, true, new UTF8Encoding()); this.CompletedSchedulesFile.AutoFlush = true; } catch (IOException ex) { this.Logger.Log(ex.Message); } // Simple test for first time load with no configs set /*if (Configurator.GetConfig("tableau_server") != "") * { * // Load the Inactive Subscriptions from the Repository * LoadSubscriptionsFromRepository(); * }*/ }
private string GenerateSingleExport(string exportSite, string exportUsername, string exportViewLocation, string exportAttachmentType, string exportFilename, Dictionary <string, string> viewFilterDictionary) { // Generate Single File try { TableauRepository tabrep = new TableauRepository( Configurator.GetConfig("tableau_server"), Configurator.GetConfig("repository_pw"), "readonly" ); tabrep.logger = this.Logger; Tabcmd tabcmd = new Tabcmd( Configurator.GetConfig("tabcmd_program_location"), Configurator.GetConfig("tableau_server"), Configurator.GetConfig("server_admin_username"), Configurator.GetConfig("server_admin_password"), exportSite, Configurator.GetConfig("tabcmd_config_location"), tabrep, this.Logger ); // Emailer here is used because the Watermarking is built in there. Would it make more sense to move it to Tabcmd eventually, or its own class? BeholdEmailer tabemailer = new BeholdEmailer(tabcmd, Configurator.GetConfig("smtp_server")); Watermarker wm = new Watermarker(); string[] pageLocations = { "top_left", "top_center", "top_right", "bottom_left", "bottom_center", "bottom_right" }; foreach (string pageLocation in pageLocations) { string settingsPageLocation = pageLocation.Split('_')[0] + pageLocation.Split('_')[1].First() + pageLocation.Split('_')[1].Substring(1); wm.SetPageLocationWatermarkFromConfig(pageLocation, Configurator.GetConfigSerializableStringDict(settingsPageLocation)); } string filename = tabemailer.GenerateExportAndWatermark(exportUsername, exportViewLocation, exportAttachmentType, viewFilterDictionary, wm); string[] fileEnding = filename.Split('.'); string finalFilename = String.Format("{0}{1}.{2}", Configurator.GetConfig("export_archive_folder"), exportFilename, fileEnding[fileEnding.Length - 1]); this.Logger.Log(String.Format("Finalizing file and putting it here: {0}", finalFilename)); File.Copy(filename, finalFilename, true); this.Logger.Log(String.Format("Removing original file {0}", filename)); File.Delete(filename); return("Finished single export file creation. Saved to: " + finalFilename); } catch (ConfigurationException ce) { //progress.finish_progress_bar(33); // progress.update_status("Export failed for some reason, most likely bad settings.\nCheck logs for more info"); this.Logger.Log(ce.Message); return("Single export failed. Please see logs for more information."); } }
public ConfigureTableauServer() { InitializeComponent(); // Load Settings server_admin_username.Text = Configurator.GetConfig("server_admin_username"); server_password.Text = Configurator.GetConfig("server_admin_password"); tableau_server_url.Text = Configurator.GetConfig("tableau_server"); repositoryPW.Text = Configurator.GetConfig("repository_pw"); tabcmdProgramLocation.Text = Configurator.GetConfig("tabcmd_program_location"); tabcmdConfigLocation.Text = Configurator.GetConfig("tabcmd_config_location"); }
public ConfigureEmailServer() { InitializeComponent(); // Load the configurations emailServer.Text = Configurator.GetConfig("smtp_server"); smtpServerUsername.Text = Configurator.GetConfig("smtp_server_username"); smtpServerPassword.Text = Configurator.GetConfig("smtp_server_password"); smtpServerTLS.Text = Configurator.GetConfig("smtp_server_tls"); smtpServerPort.Text = Configurator.GetConfig("smtp_server_port"); textEmailFilename.Text = Configurator.GetConfig("text_email_template_filename"); htmlEmailFilename.Text = Configurator.GetConfig("html_email_template_filename"); emailSender.Text = Configurator.GetConfig("email_sender"); saveLocalCopyCheckBox.Checked = Configurator.GetConfigBool("save_emailed_copies_flag"); }
public Configure() { InitializeComponent(); this.watermark_page_location_names = new string[] { "topLeft", "topCenter", "topRight", "bottomLeft", "bottomCenter", "bottomRight" }; // Initialize shared logger this.logger = new Logger("log.txt"); // Initializing queue system int minutes_between_timer = 1; this.scheduleMonitorTimer = new System.Windows.Forms.Timer(); scheduleMonitorTimer.Interval = minutes_between_timer * 60 * 1000; this.scheduleMonitorTimer.Tick += runSchedules_TimedEvent; this.active_schedules_queue_filename = "active_schedules.csv"; string completed_schedules_filename = "completed_schedules.csv"; this.active_schedules = new List <string[]>(); try { // Read anything in the active_schedules file string[] last_active_scheds = File.ReadAllLines(active_schedules_queue_filename); foreach (string sched in last_active_scheds) { string[] cols = sched.Split('|'); active_schedules.Add(cols); this.logger.Log(String.Format("Loaded {0} at {1} to active schedules from disk", cols[0], cols[1])); } // Open up the streams to keep track of what happens even if the program fails this.completed_schedules_file = new StreamWriter(completed_schedules_filename, true, new UTF8Encoding()); this.completed_schedules_file.AutoFlush = true; } catch (IOException ex) { this.logger.Log(ex.Message); } // Simple test for first time load with no configs set if (Configurator.GetConfig("tableau_server") != "") { loadAllConfigs(); loadPageLayoutConfigs(); // Load the Inactive Subscriptions from the Repository loadSubscriptionsFromRepository(); } }
private void loadAllConfigs() { server_admin_username.Text = Configurator.GetConfig("server_admin_username"); server_password.Text = Configurator.GetConfig("server_admin_password"); tableau_server_url.Text = Configurator.GetConfig("tableau_server"); repositoryPW.Text = Configurator.GetConfig("repository_pw"); emailServer.Text = Configurator.GetConfig("smtp_server"); smtpServerUsername.Text = Configurator.GetConfig("smtp_server_username"); smtpServerPassword.Text = Configurator.GetConfig("smtp_server_password"); smtpServerTLS.Text = Configurator.GetConfig("smtp_server_tls"); smtpServerPort.Text = Configurator.GetConfig("smtp_server_port"); textEmailFilename.Text = Configurator.GetConfig("text_email_template_filename"); htmlEmailFilename.Text = Configurator.GetConfig("html_email_template_filename"); emailSender.Text = Configurator.GetConfig("email_sender"); tabcmdProgramLocation.Text = Configurator.GetConfig("tabcmd_program_location"); tabcmdConfigLocation.Text = Configurator.GetConfig("tabcmd_config_location"); exportArchiveFolder.Text = Configurator.GetConfig("export_archive_folder"); }
private void QueueSingleEmail(object sender, EventArgs e) { // Valdate the form elements TextBox[] elements_to_validate = { singleExportSite, singleViewLocation, testEmailRecipient, testEmailSubject }; bool validation = this.ValidateSetOfElements(elements_to_validate); if (validation == false) { return; } var activityId = this.nextActivityId; this.nextActivityId++; WriteToActivityGrid(String.Format("Queued an email of {0} to {1}", singleViewLocation.Text, testEmailRecipient.Text), activityId); // Add to the actionQueue asyncActionQueue.Add(() => { var exportSite = singleExportSite.Text; var exportUsername = singleUsernameForImpersonation.Text; var exportViewLocation = singleViewLocation.Text; var exportAttachmentType = ExportTypeIndexMap[Int32.Parse(Configurator.GetConfig("single_export_type_index"))]; // var exportFilename = testFilename.Text; var emailTo = testEmailRecipient.Text; var emailSubject = testEmailSubject.Text; var results = SendSingleEmail(exportSite, emailTo, emailSubject, exportUsername, exportViewLocation, exportAttachmentType); WriteToActivityGrid(results, activityId); return(results); }); // Launch the next action in the queue, if possible try { actionQueueBackgroundWorker.RunWorkerAsync(asyncActionQueue[0]); } // The queue response will launch the next action once it is finished catch (InvalidOperationException) { this.Logger.Log("Action queued but other action currently running"); } }
public bool SendEmail(string scheduleName) { try { BeholdEmailer tabemailer = this.CreateBeholdEmailerFromConfig(); Watermarker wm = this.CreateWatermarkerFromConfig(); try { bool result; if (scheduleName != "") { tabemailer.ExportArchiveFolderPath = Configurator.GetConfig("export_archive_folder"); result = tabemailer.GenerateEmailsFromNamedScheduleInRepository(scheduleName, Configurator.GetConfig("email_sender"), wm); } else { result = tabemailer.GenerateEmailFromView(Configurator.GetConfig("email_sender"), new string[1] { testEmailRecipient.Text }, new string[0] { }, new string[0] { }, testEmailSubject.Text, "Please see attached file", singleUsernameForImpersonation.Text, singleViewLocation.Text, ExportTypeIndexMap[Int32.Parse(Configurator.GetConfig("single_export_type_index"))], new Dictionary <String, String>(), wm); } return(result); } catch (ConfigurationException ce) { this.Logger.Log(ce.Message); return(false); } } // From Repository Failing catch (ConfigurationException ce) { this.Logger.Log(ce.Message); return(false); } }
private void QueueSingleExport(object sender, EventArgs e) { // Needs validation here TextBox[] elementsToValidate = { singleExportSite, singleViewLocation }; bool validation = this.ValidateSetOfElements(elementsToValidate); if (validation == false) { return; } var activityId = this.nextActivityId; this.nextActivityId++; WriteToActivityGrid(String.Format("Queuing export of {0} on site {1}", singleViewLocation.Text, singleExportSite.Text), activityId); // Add to the actionQueue. Throw an anonymous function so you can call whatever params at this time asyncActionQueue.Add(() => { var exportSite = singleExportSite.Text; var exportUsername = singleUsernameForImpersonation.Text; var exportViewLocation = singleViewLocation.Text; var exportAttachmentType = ExportTypeIndexMap[Int32.Parse(Configurator.GetConfig("single_export_type_index"))]; var exportFilename = testFilename.Text; var results = GenerateSingleExport(exportSite, exportUsername, exportViewLocation, exportAttachmentType, exportFilename); WriteToActivityGrid(results, activityId); return(results); }); // Launch the next action in the queue, if possible try { actionQueueBackgroundWorker.RunWorkerAsync(asyncActionQueue[0]); } // The queue response will launch the next action once it is finished catch (InvalidOperationException) { this.Logger.Log("Action queued but other action currently running"); } }
/* * Schedules Tab * */ private void runSchedules_TimedEvent(Object source, EventArgs e) { // Only run on one minute after every 15 if (DateTime.Now.Minute == 1 || DateTime.Now.Minute == 16 || DateTime.Now.Minute == 31 || DateTime.Now.Minute == 46) { this.logger.Log("Schedule checks begin"); this.scheduledEmailsStatus.Text = "Scheduled Emails are running"; try { // Read the schedules that are currently in the repository, to update the active schedule queue TableauRepository rep = new TableauRepository(Configurator.GetConfig("tableau_server"), Configurator.GetConfig("repository_pw"), "readonly"); rep.logger = this.logger; NpgsqlDataReader dr = rep.query_inactive_subscription_schedules_for_next_run_time(); if (dr.HasRows == true) { using (StreamWriter active_schedules_file = new StreamWriter(this.active_schedules_queue_filename, false, new UTF8Encoding())) { while (dr.Read()) { string sched_name = dr.GetString(0); string sched_next_run_time; //Although server time is usually UTC, the time is later compared with current time converted to UTC too. DateTime serverTime = dr.GetDateTime(1); sched_next_run_time = serverTime.ToString(); this.logger.Log(String.Format("Next scheduled run time (UTC) is {0}", sched_next_run_time)); // Only add if the sched_name is in the checked schedules int num_checked_items = availableSchedulesList.CheckedItems.Count; string[] checked_schedule_names = new string[num_checked_items]; var k = 0; foreach (object itemChecked in availableSchedulesList.CheckedItems) { checked_schedule_names[k] = itemChecked.ToString(); k++; } string[] sched = new string[2] { sched_name, sched_next_run_time }; bool schedule_exists_in_queue = false; foreach (string[] queued_sched in this.active_schedules) { if (queued_sched[0] == sched_name && queued_sched[1] == sched_next_run_time) { schedule_exists_in_queue = true; this.logger.Log(String.Format("Schedule {0} at {1} already exists in queue", sched_name, sched_next_run_time)); } } if (schedule_exists_in_queue == false) { // Only add checked schedule names if (checked_schedule_names.Any(sched.Contains) == true) { this.active_schedules.Add(sched); this.logger.Log(String.Format("Schedule {0} at {1} added to the queue", sched_name, sched_next_run_time)); active_schedules_file.WriteLine(String.Format("{0}|{1}", sched_name, sched_next_run_time)); } } } } } dr.Close(); } catch (NpgsqlException ne) { this.logger.Log("Connecting to repository to update the active queue failed. Ignoring for now, will update at next interval"); this.logger.Log(ne.Message); } // Look at the Active Queue and determine if anything is past it's due date foreach (string[] queued_sched in this.active_schedules.Reverse <string[]>()) { if (DateTime.Now.ToUniversalTime() > DateTime.Parse(queued_sched[1])) { this.logger.Log(String.Format("Schedule {0} at {1} is now eligible to be run.", queued_sched[0], queued_sched[1])); bool result = send_email(queued_sched[0]); if (result == true) { this.logger.Log(String.Format("Schedule {0} at {1} has run successfully. Removing from queue", queued_sched[0], queued_sched[1])); } else { //Suppose a schedule contains multiple subscriptions and one of them fails, the original app will send pdf to everyone else every 15 minutes. //This prevents it by removing unsuccessful sessions. this.logger.Log(String.Format("Schedule {0} at {1} failed (maybe partially). Removing from queue", queued_sched[0], queued_sched[1])); } // Write completed schedules into the schedule_run log this.completed_schedules_file.WriteLine(String.Format("{0}|{1}", queued_sched[0], queued_sched[1])); this.active_schedules.Remove(queued_sched); } } // Write the queues to the active_schedules files using (StreamWriter active_schedules_file = new StreamWriter(this.active_schedules_queue_filename, false, new UTF8Encoding())) { foreach (string[] queued_sched in this.active_schedules) { active_schedules_file.WriteLine(String.Format("{0}|{1}", queued_sched[0], queued_sched[1])); } } this.logger.Log("Schedule check completed successfully"); this.scheduledEmailsStatus.Text = "Waiting to Run Next Scheduled Emails"; } }
private string fillInPowerpoint(uint activityId) { // Copy to the new file string ExportArchiveFolderPath = null; if (!String.IsNullOrEmpty(Configurator.GetConfig("export_archive_folder"))) { ExportArchiveFolderPath = Configurator.GetConfig("export_archive_folder"); } // Cancel action if no archive folder exists else { MessageBox.Show("Please configure the local save folder", "No Local Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new ConfigurationException("Please configure the local save folder"); } // Add check for .PPT in the name before final string[] filenameNoExtension = powerPointExportFileName.Text.Split('.'); var finalFilename = ExportArchiveFolderPath + filenameNoExtension[0] + ".pptx"; // Create the new file try { this.Logger.Log(String.Format("Copying template from {1} to filename {0}", finalFilename, powerPointFilename.Text)); File.Copy(powerPointFilename.Text, finalFilename, true); } catch (Exception e) { this.Logger.Log(e.Message); } // Reset the sending messages foreach (DataGridViewRow row in powerPointStatusView.Rows) { row.Cells["Status"].Value = ""; } // Run through and send the e-mails int rowCount = 0; // Catch exception? this.Logger.Log("Opening the PowerPointer object"); var powerpointer = new PowerPointer(finalFilename, this.Logger); this.Logger.Log("Opened the PowerPointer object"); foreach (DataGridViewRow row in powerPointStatusView.Rows) { row.Cells["Status"].Value = "Processing..."; row.Selected = true; string rawSlideNumber = (string)row.Cells["Slide Number"].Value.ToString(); if (rawSlideNumber == null) { row.Cells["Status"].Value = "Invalid"; WriteToActivityGrid(String.Format("Skipped row {0} due to missing Slide Number field", rowCount), activityId); continue; } int slideNumber = Int32.Parse(rawSlideNumber); string viewLocation = (string)row.Cells["View Location"].Value.ToString(); string site = (string)row.Cells["Site"].Value.ToString(); // Skip if there is no view location or site if (viewLocation == "" || site == "") { row.Cells["Status"].Value = "Invalid"; row.Selected = false; WriteToActivityGrid(String.Format("Skipped row {0} due to missing View Location or Site", rowCount), activityId); continue; } Dictionary <string, string> filters_dict = new Dictionary <string, string>(); // Up to 25 filters (no one would realistically go this high) int j = 1; while (j <= 25) { string filterFieldKey = String.Format("Filter Field Name {0}", j.ToString()); string filterValuesKey = String.Format("Filter Values {0}", j.ToString()); if (!powerPointStatusView.Columns.Contains(filterFieldKey) || !powerPointStatusView.Columns.Contains(filterValuesKey)) { break; } if (row.Cells[filterFieldKey].ValueType != typeof(DBNull)) { string filterFieldName = (string)row.Cells[filterFieldKey].Value.ToString(); string filterValuesListRaw = (string)row.Cells[filterValuesKey].Value.ToString(); // Swap the semi-colons for commas as needed in the dict string[] filterValuesList = filterValuesListRaw.Split(';'); // Skip if there's nothing in the first split value if (filterValuesList[0] == "") { j++; continue; } string[] encodedFilters = new string[filterValuesList.Length]; for (int i = 0; i < filterValuesList.Length; i++) { // Gotta double the % sign because batch files use %2 as a replacement token. encodedFilters[i] = Uri.EscapeUriString(filterValuesList[i]).Replace("%", "%%"); } // Figure out how not to add if empty string finalValueParam = String.Join(",", encodedFilters); filters_dict.Add(filterFieldName, finalValueParam); } j++; } // Open PowerPointer object on newly copied file // Save the Presentation try { var slidePart = powerpointer.FindSlidePartBySlideNumber(slideNumber); // Generate the image file this.Logger.Log("Generating the image file to swap in"); var tempImageFileName = String.Format("Image {0}", rowCount); this.GenerateSingleExport(site, powerPointUserToGenerateAs.Text, viewLocation, "png", tempImageFileName, filters_dict); this.Logger.Log("PNG file generated"); var finalImageFileName = ExportArchiveFolderPath + tempImageFileName + ".png"; this.Logger.Log("Replacing the image in the slide"); var replacementSuccess = powerpointer.ReplaceImageInSlide(slidePart, finalImageFileName); this.Logger.Log("Replaced the image in the slide"); File.Delete(finalImageFileName); if (replacementSuccess) { row.Cells["Status"].Value = "Replaced Successfully"; } else { row.Cells["Status"].Value = "No Replacement"; } } catch (NotFoundException) { row.Cells["Status"].Value = "Invalid Slide Number"; } row.Selected = false; rowCount++; } powerpointer.SavePresentation(); powerpointer.ClosePresentation(); EnablePowerpointButtons(); return("Finished filling in PowerPoint template file"); }
private void updateSchedulesQueue() { var activityId = this.nextActivityId; this.nextActivityId++; WriteToActivityGrid("Checking for schedules to run in the repository", activityId); this.Logger.Log("Schedule checks begin"); try { // Read the schedules that are currently in the repository, to update the active schedule queue TableauRepository rep = new TableauRepository(Configurator.GetConfig("tableau_server"), Configurator.GetConfig("repository_pw"), "readonly"); rep.logger = this.Logger; //this.Logger.Log("Starting to read from the repository"); NpgsqlDataReader dr = rep.QueryInactiveSubscriptionSchedulesForNextRunTime(); if (dr.HasRows == true) { //this.Logger.Log("Opening the active schedules queue file"); using (StreamWriter activeSchedulesQueueFileWriter = new StreamWriter(this.ActiveSchedulesQueueFilename, false, new UTF8Encoding())) { //this.Logger.Log("Reading from the result set "); while (dr.Read()) { // this.Logger.Log("Working inside the result set "); string scheduleName = dr.GetString(0); string scheduleNextRunTime = dr.GetDateTime(1).ToString(); //this.Logger.Log(String.Format("Schedule here {0} {1}", scheduleName, scheduleNextRunTime)); // Because the selections are stored instantly, load from the saved collectionr rather than the control // It is possible the control has not been redrawn at the time List <string> selectedScheduleNames = new List <string>() { }; StringCollection savedSchedules = Configurator.GetConfigCollection("selected_schedule_names"); if (savedSchedules != null) { foreach (String savedScheduleName in savedSchedules) { selectedScheduleNames.Add(savedScheduleName); } } string[] scheduleInfo = new string[2] { scheduleName, scheduleNextRunTime }; bool doesScheduleExistInQueue = false; // See if what is in the activeSchedulesQueue file is a checked schedule still foreach (string[] activeSchedule in this.ActiveSchedules) { if (activeSchedule[0] == scheduleName && activeSchedule[1] == scheduleNextRunTime) { this.Logger.Log(String.Format("Schedule {0} at {1} already in the schedules queue", scheduleName, scheduleNextRunTime)); doesScheduleExistInQueue = true; } } if (doesScheduleExistInQueue == false) { // Only add checked schedule names if (selectedScheduleNames.Any(scheduleInfo.Contains) == true) { this.ActiveSchedules.Add(scheduleInfo); WriteToActivityGrid(String.Format("Schedule {0} at {1} added to the schedules queue", scheduleName, scheduleNextRunTime), activityId); this.Logger.Log(String.Format("Schedule {0} at {1} added to the schedules queue", scheduleName, scheduleNextRunTime)); activeSchedulesQueueFileWriter.WriteLine(String.Format("{0}|{1}", scheduleName, scheduleNextRunTime)); } else { this.Logger.Log(String.Format("Schedule {0} at {1} not added to schedules queue because it is not selected", scheduleName, scheduleNextRunTime)); } } } } } else { this.Logger.Log("No rows found in the query for new schedules"); } dr.Close(); } catch (NpgsqlException ne) { this.Logger.Log("Connecting to repository to update the active queue failed. Ignoring for now, will update at next interval"); this.Logger.Log(ne.Message); } WriteToActivityGrid("Completed checking for new schedules", activityId); // Look at the Active Queue and determine if anything is past it's due date foreach (string[] queuedSchedule in this.ActiveSchedules.Reverse <string[]>()) { if (DateTime.Now.ToUniversalTime() > DateTime.Parse(queuedSchedule[1])) { activityId = this.nextActivityId; this.nextActivityId++; this.Logger.Log(String.Format("Schedule {0} at {1} is now eligible to be run.", queuedSchedule[0], queuedSchedule[1])); WriteToActivityGrid(String.Format("Schedule {0} at {1} is now eligible to be run. Queuing to run.", queuedSchedule[0], queuedSchedule[1]), activityId); // Add to the actionQueue at the top asyncActionQueue.Insert(0, () => { var queuedScheduleName = queuedSchedule[0]; var queuedScheduleRunTime = queuedSchedule[1]; WriteToActivityGrid(String.Format("Running Schedule {0} at {1}.", queuedSchedule[0], queuedSchedule[1]), activityId); bool result = SendEmail(queuedScheduleName); // Even if failure, remove from active schedules queue this.Logger.Log(String.Format("Removing {0} at {1} from active schedules queue", queuedSchedule[0], queuedSchedule[1])); this.ActiveSchedules.Remove(queuedSchedule); // Write the remaining queues. using (StreamWriter activeSchedulesQueueFileWriter = new StreamWriter(this.ActiveSchedulesQueueFilename, false, new UTF8Encoding())) { foreach (string[] currentlyQueuedSchedules in this.ActiveSchedules) { activeSchedulesQueueFileWriter.WriteLine(String.Format("{0}|{1}", currentlyQueuedSchedules[0], currentlyQueuedSchedules[1])); } } if (result) { WriteToActivityGrid(String.Format("Completed Schedule {0} at {1}.", queuedScheduleName, queuedScheduleRunTime), activityId); return(String.Format("Completed Schedule {0} at {1}.", queuedScheduleName, queuedScheduleRunTime)); } else { this.ActiveSchedules.Remove(queuedSchedule); WriteToActivityGrid(String.Format("Schedule {0} at {1} failed, see log.", queuedScheduleName, queuedScheduleRunTime), activityId); return(String.Format("Schedule {0} at {1} failed, see log.", queuedScheduleName, queuedScheduleRunTime)); } } ); // Launch the next action in the queue, if possible try { actionQueueBackgroundWorker.RunWorkerAsync(asyncActionQueue[0]); } // The queue response will launch the next action once it is finished catch (InvalidOperationException) { this.Logger.Log("Action queued but other action currently running"); } } } }
public ConfigureLocalSettings() { InitializeComponent(); exportArchiveFolder.Text = Configurator.GetConfig("export_archive_folder"); }
private BeholdEmailer CreateBeholdEmailerFromConfig() { return(this.CreateBeholdEmailerFromConfig(Configurator.GetConfig("single_export_site"))); }