private static void WriteStartupError(Config config, FileSystem fileSystem, string message) { if (config == null) { fileSystem.AppendToFile(fileSystem.StartupErrorFile, "Cannot start application. Missing configuration."); } else { string appVersion = "[(v" + config.Settings.ApplicationVersion + ") "; fileSystem.AppendToFile(fileSystem.StartupErrorFile, appVersion + DateTime.Now.ToString(config.MacroParser.DateFormat + " " + config.MacroParser.TimeFormat) + "] " + message); } Environment.Exit(1); }
private static void Main(string[] args) { if (args.Length == 1 && !string.IsNullOrEmpty(args[0]) && args[0].Equals("-kill")) { // Find all instances of autoscreen and kill them. foreach (var process in Process.GetProcessesByName("autoscreen")) { process.Kill(); } } else { // Parse any command line arguments before we start a new instance so we can issue commands externally // such as -debug, -log, -capture, -start, -stop, and -exit to the instance which is already running. if (args.Length > 0) { ParseCommandLineArguments(args); } else { // Normally we could use the -config command to specify the configuration file to use, but if we // have no commands to parse then we'll load the settings from the default configuration file. Config.Load(); } // This block of code figures out if we're already running an instance of the application. using (new Mutex(false, ((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute), false)).Value, out bool createdNew)) { if (createdNew) { // If we're not already running then start a new instance of the application. Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; if ((Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 3) || Environment.OSVersion.Version.Major >= 10) { Application.EnableVisualStyles(); Log.WriteMessage("Windows 8.1 or higher detected. Attempting to set DPI awareness"); SetProcessDpiAwareness(ProcessDPIAwareness.ProcessPerMonitorDPIAware); } Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } else { if (args.Length == 0 && Convert.ToBoolean(Settings.Application.GetByKey("ShowStartupError", DefaultSettings.ShowStartupError).Value)) { // We've determined that an existing instance is already running. We should write out an error message informing the user. string appVersion = "[(v" + Settings.ApplicationVersion + ") "; FileSystem.AppendToFile(FileSystem.StartupErrorFile, appVersion + DateTime.Now.ToString(MacroParser.DateFormat + " " + MacroParser.TimeFormat) + "] Cannot start " + Settings.ApplicationName + " because an existing instance of the application is already running. To disable this error message set \"ShowStartupError\" to \"False\" in \"" + FileSystem.ApplicationSettingsFile + "\""); } } } } }
/// <summary> /// Parse the given command line arguments. /// </summary> /// <param name="args">The command line arguments to parse.</param> /// <param name="config">The config file to use.</param> /// <returns>True if parsing command line arguments is successful. False if parsing command line arguments unsuccessful.</returns> private static bool ParseCommandLineArguments(string[] args, Config config) { bool cleanStartup = false; FileSystem fileSystem = new FileSystem(); // Make sure we parse for the most important command line options here. const string REGEX_COMMAND_LINE_CONFIG = "^-config=(?<ConfigFile>.+)$"; const string REGEX_COMMAND_LINE_CLEAN_STARTUP = "^-cleanStartup$"; foreach (string arg in args) { if (Regex.IsMatch(arg, REGEX_COMMAND_LINE_CONFIG)) { string configFile = Regex.Match(arg, REGEX_COMMAND_LINE_CONFIG).Groups["ConfigFile"].Value; if (configFile.Length > 0) { fileSystem.ConfigFile = configFile; if (!config.Load(fileSystem)) { return(false); } } } if (Regex.IsMatch(arg, REGEX_COMMAND_LINE_CLEAN_STARTUP)) { cleanStartup = true; } } // We didn't get a -config or -cleanStartup command line argument so just load the default config // and let the application parse any other command line options that were given to it. if (config.Settings == null) { if (!config.Load(fileSystem, cleanStartup)) { return(false); } } // All of these commands can be externally issued to an already running instance. // The current running instance monitors the command file for the commands in the file. foreach (string arg in args) { fileSystem.AppendToFile(fileSystem.CommandFile, arg); } return(true); }
private static void ParseCommandLineArguments(string[] args) { // Because ordering is important I want to make sure that we pick up the configuration file first. // This will avoid scenarios like "autoscreen.exe -debug -config" creating all the default folders // and files (thanks to -debug being the first argument) before -config is parsed. foreach (string arg in args) { if (Regex.IsMatch(arg, CommandLineRegex.REGEX_COMMAND_LINE_CONFIG)) { string configFile = Regex.Match(arg, CommandLineRegex.REGEX_COMMAND_LINE_CONFIG).Groups["ConfigFile"].Value; if (configFile.Length > 0) { FileSystem.ConfigFile = configFile; Config.Load(); } } } // We didn't get a -config command line argument so just load the default config. if (Settings.Application == null) { Config.Load(); } // Load user settings. if (string.IsNullOrEmpty(FileSystem.UserSettingsFile)) { Config.Load(); } // All of these commands can be externally issued to an already running instance. // The current running instance monitors the command file for the commands in the file. foreach (string arg in args) { FileSystem.AppendToFile(FileSystem.CommandFile, arg); } }
private static void ParseCommandLineArguments(string[] args, Config config) { FileSystem fileSystem = new FileSystem(); // Because ordering is important I want to make sure that we pick up the configuration file first. // This will avoid scenarios like "autoscreen.exe -debug -config" creating all the default folders // and files (thanks to -debug being the first argument) before -config is parsed. const string REGEX_COMMAND_LINE_CONFIG = "^-config=(?<ConfigFile>.+)$"; foreach (string arg in args) { if (Regex.IsMatch(arg, REGEX_COMMAND_LINE_CONFIG)) { string configFile = Regex.Match(arg, REGEX_COMMAND_LINE_CONFIG).Groups["ConfigFile"].Value; if (configFile.Length > 0) { fileSystem.ConfigFile = configFile; config.Load(fileSystem); } } } // We didn't get a -config command line argument so just load the default config // and let the application parse any other command line options. if (config.Settings == null) { config.Load(fileSystem); } // All of these commands can be externally issued to an already running instance. // The current running instance monitors the command file for the commands in the file. foreach (string arg in args) { fileSystem.AppendToFile(fileSystem.CommandFile, arg); } }
// Check the folders to make sure that each folder was included in the config file and the folder exists. private static void CheckAndCreateFolders() { if (string.IsNullOrEmpty(FileSystem.ScreenshotsFolder)) { FileSystem.ScreenshotsFolder = FileSystem.DefaultScreenshotsFolder; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nScreenshotsFolder=" + FileSystem.DefaultScreenshotsFolder); if (!FileSystem.DirectoryExists(FileSystem.DefaultScreenshotsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultScreenshotsFolder); } } if (string.IsNullOrEmpty(FileSystem.DebugFolder)) { FileSystem.DebugFolder = FileSystem.DefaultDebugFolder; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nDebugFolder=" + FileSystem.DefaultDebugFolder); if (!FileSystem.DirectoryExists(FileSystem.DefaultDebugFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultDebugFolder); } } if (string.IsNullOrEmpty(FileSystem.LogsFolder)) { FileSystem.LogsFolder = FileSystem.DefaultLogsFolder; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nLogsFolder=" + FileSystem.DefaultLogsFolder); if (!FileSystem.DirectoryExists(FileSystem.DefaultLogsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultLogsFolder); } } }
private void CheckAndCreateFiles(Security security, ScreenCapture screenCapture, Log log) { if (string.IsNullOrEmpty(FileSystem.CommandFile)) { FileSystem.CommandFile = FileSystem.DefaultCommandFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nCommandFile=" + FileSystem.DefaultCommandFile); if (!FileSystem.FileExists(FileSystem.DefaultCommandFile)) { FileSystem.CreateFile(FileSystem.DefaultCommandFile); } } if (string.IsNullOrEmpty(FileSystem.ApplicationSettingsFile)) { FileSystem.ApplicationSettingsFile = FileSystem.DefaultApplicationSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } } if (string.IsNullOrEmpty(FileSystem.SmtpSettingsFile)) { FileSystem.SmtpSettingsFile = FileSystem.DefaultSmtpSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nSMTPSettingsFile=" + FileSystem.DefaultSmtpSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } } if (string.IsNullOrEmpty(FileSystem.SftpSettingsFile)) { FileSystem.SftpSettingsFile = FileSystem.DefaultSftpSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nSFTPSettingsFile=" + FileSystem.DefaultSftpSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } } if (string.IsNullOrEmpty(FileSystem.UserSettingsFile)) { FileSystem.UserSettingsFile = FileSystem.DefaultUserSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nUserSettingsFile=" + FileSystem.DefaultUserSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } } Settings.User.Load(Settings, FileSystem); Settings.SMTP.Load(Settings, FileSystem); Settings.SFTP.Load(Settings, FileSystem); Settings.VersionManager.OldApplicationSettings = Settings.Application.Clone(); Settings.VersionManager.OldUserSettings = Settings.User.Clone(); Settings.UpgradeApplicationSettings(Settings.Application, FileSystem); Settings.UpgradeUserSettings(Settings.User, screenCapture, security, FileSystem); Settings.UpgradeSmtpSettings(Settings.SMTP, FileSystem); Settings.UpgradeSftpSettings(Settings.SFTP, FileSystem); if (string.IsNullOrEmpty(FileSystem.ScreenshotsFile)) { ImageFormatCollection imageFormatCollection = new ImageFormatCollection(); ScreenCollection screenCollection = new ScreenCollection(); ScreenshotCollection screenshotCollection = new ScreenshotCollection(imageFormatCollection, screenCollection, screenCapture, this, FileSystem, log); screenshotCollection.SaveToXmlFile(this); } if (string.IsNullOrEmpty(FileSystem.EditorsFile)) { // Loading the editor collection will automatically create the default editors and add them to the collection. EditorCollection editorCollection = new EditorCollection(); editorCollection.LoadXmlFileAndAddEditors(this, FileSystem, log); } if (string.IsNullOrEmpty(FileSystem.RegionsFile)) { RegionCollection regionCollection = new RegionCollection(); regionCollection.SaveToXmlFile(Settings, FileSystem, log); } if (string.IsNullOrEmpty(FileSystem.ScreensFile)) { // Loading the screen collection will automatically create the available screens and add them to the collection. ScreenCollection screenCollection = new ScreenCollection(); screenCollection.LoadXmlFileAndAddScreens(new ImageFormatCollection(), this, MacroParser, screenCapture, FileSystem, log); } if (string.IsNullOrEmpty(FileSystem.TriggersFile)) { // Loading triggers will automatically create the default triggers and add them to the collection. TriggerCollection triggerCollection = new TriggerCollection(); triggerCollection.LoadXmlFileAndAddTriggers(this, FileSystem, log); } if (string.IsNullOrEmpty(FileSystem.TagsFile)) { // Loading tags will automatically create the default tags and add them to the collection. MacroTagCollection tagCollection = new MacroTagCollection(); tagCollection.LoadXmlFileAndAddTags(this, MacroParser, FileSystem, log); } if (string.IsNullOrEmpty(FileSystem.SchedulesFile)) { // Loading schedules will automatically create the default schedules and add them to the collection. ScheduleCollection scheduleCollection = new ScheduleCollection(); scheduleCollection.LoadXmlFileAndAddSchedules(this, FileSystem, log); } }
/// <summary> /// Saves the triggers. /// </summary> public void SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.Indent = true; xSettings.CloseOutput = true; xSettings.CheckCharacters = true; xSettings.Encoding = Encoding.UTF8; xSettings.NewLineChars = Environment.NewLine; xSettings.IndentChars = XML_FILE_INDENT_CHARS; xSettings.NewLineHandling = NewLineHandling.Entitize; xSettings.ConformanceLevel = ConformanceLevel.Document; if (string.IsNullOrEmpty(FileSystem.TriggersFile)) { FileSystem.TriggersFile = FileSystem.DefaultTriggersFile; if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nTriggersFile=" + FileSystem.TriggersFile); } } if (FileSystem.FileExists(FileSystem.TriggersFile)) { FileSystem.DeleteFile(FileSystem.TriggersFile); } using (XmlWriter xWriter = XmlWriter.Create(FileSystem.TriggersFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_TRIGGERS_NODE); foreach (Trigger trigger in base.Collection) { xWriter.WriteStartElement(XML_FILE_TRIGGER_NODE); xWriter.WriteElementString(TRIGGER_ACTIVE, trigger.Active.ToString()); xWriter.WriteElementString(TRIGGER_NAME, trigger.Name); xWriter.WriteElementString(TRIGGER_CONDITION, trigger.ConditionType.ToString()); xWriter.WriteElementString(TRIGGER_ACTION, trigger.ActionType.ToString()); xWriter.WriteElementString(TRIGGER_EDITOR, trigger.Editor); xWriter.WriteElementString(TRIGGER_DATE, trigger.Date.ToString()); xWriter.WriteElementString(TRIGGER_TIME, trigger.Time.ToString()); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } } catch (Exception ex) { Log.WriteExceptionMessage("TriggerCollection::SaveToXmlFile", ex); } }
/// <summary> /// Saves the image schedules in the collection to the schedules.xml file. /// </summary> public bool SaveToXmlFile(Settings settings, FileSystem fileSystem, Log log) { try { XmlWriterSettings xSettings = new XmlWriterSettings { Indent = true, CloseOutput = true, CheckCharacters = true, Encoding = Encoding.UTF8, NewLineChars = Environment.NewLine, IndentChars = XML_FILE_INDENT_CHARS, NewLineHandling = NewLineHandling.Entitize, ConformanceLevel = ConformanceLevel.Document }; if (string.IsNullOrEmpty(fileSystem.SchedulesFile)) { fileSystem.SchedulesFile = fileSystem.DefaultSchedulesFile; fileSystem.AppendToFile(fileSystem.ConfigFile, "\nSchedulesFile=" + fileSystem.SchedulesFile); } if (fileSystem.FileExists(fileSystem.SchedulesFile)) { fileSystem.DeleteFile(fileSystem.SchedulesFile); } using (XmlWriter xWriter = XmlWriter.Create(fileSystem.SchedulesFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_SCHEDULES_NODE); foreach (Schedule schedule in base.Collection) { xWriter.WriteStartElement(XML_FILE_SCHEDULE_NODE); xWriter.WriteElementString(SCHEDULE_ENABLE, schedule.Enable.ToString()); xWriter.WriteElementString(SCHEDULE_NAME, schedule.Name); xWriter.WriteElementString(SCHEDULE_MODE_ONETIME, schedule.ModeOneTime.ToString()); xWriter.WriteElementString(SCHEDULE_MODE_PERIOD, schedule.ModePeriod.ToString()); xWriter.WriteElementString(SCHEDULE_CAPTUREAT, schedule.CaptureAt.ToString()); xWriter.WriteElementString(SCHEDULE_STARTAT, schedule.StartAt.ToString()); xWriter.WriteElementString(SCHEDULE_STOPAT, schedule.StopAt.ToString()); xWriter.WriteElementString(SCHEDULE_SCREEN_CAPTURE_INTERVAL, schedule.ScreenCaptureInterval.ToString()); xWriter.WriteElementString(SCHEDULE_MONDAY, schedule.Monday.ToString()); xWriter.WriteElementString(SCHEDULE_TUESDAY, schedule.Tuesday.ToString()); xWriter.WriteElementString(SCHEDULE_WEDNESDAY, schedule.Wednesday.ToString()); xWriter.WriteElementString(SCHEDULE_THURSDAY, schedule.Thursday.ToString()); xWriter.WriteElementString(SCHEDULE_FRIDAY, schedule.Friday.ToString()); xWriter.WriteElementString(SCHEDULE_SATURDAY, schedule.Saturday.ToString()); xWriter.WriteElementString(SCHEDULE_SUNDAY, schedule.Sunday.ToString()); xWriter.WriteElementString(SCHEDULE_NOTES, schedule.Notes); xWriter.WriteElementString(SCHEDULE_LOGIC, schedule.Logic.ToString()); xWriter.WriteElementString(SCHEDULE_SCOPE, schedule.Scope); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } return(true); } catch (Exception ex) { log.WriteExceptionMessage("ScheduleCollection::SaveToXmlFile", ex); return(false); } }
private static void CheckAndCreateFiles() { if (string.IsNullOrEmpty(FileSystem.CommandFile)) { FileSystem.CommandFile = FileSystem.DefaultCommandFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nCommandFile=" + FileSystem.DefaultCommandFile); if (!FileSystem.FileExists(FileSystem.DefaultCommandFile)) { FileSystem.CreateFile(FileSystem.DefaultCommandFile); } } if (string.IsNullOrEmpty(FileSystem.ApplicationSettingsFile)) { FileSystem.ApplicationSettingsFile = FileSystem.DefaultApplicationSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } SettingCollection applicationSettingsCollection = new SettingCollection { Filepath = FileSystem.ApplicationSettingsFile }; applicationSettingsCollection.Save(); } if (string.IsNullOrEmpty(FileSystem.UserSettingsFile)) { FileSystem.UserSettingsFile = FileSystem.DefaultUserSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nUserSettingsFile=" + FileSystem.DefaultUserSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } SettingCollection userSettingsCollection = new SettingCollection { Filepath = FileSystem.ApplicationSettingsFile }; userSettingsCollection.Save(); } if (string.IsNullOrEmpty(FileSystem.ScreenshotsFile)) { ImageFormatCollection imageFormatCollection = new ImageFormatCollection(); ScreenCollection screenCollection = new ScreenCollection(); ScreenshotCollection screenshotCollection = new ScreenshotCollection(imageFormatCollection, screenCollection); screenshotCollection.SaveToXmlFile(0); } if (string.IsNullOrEmpty(FileSystem.EditorsFile)) { // Loading the editor collection will automatically create the default editors and add them to the collection. EditorCollection editorCollection = new EditorCollection(); editorCollection.LoadXmlFileAndAddEditors(); } if (string.IsNullOrEmpty(FileSystem.RegionsFile)) { RegionCollection regionCollection = new RegionCollection(); regionCollection.SaveToXmlFile(); } if (string.IsNullOrEmpty(FileSystem.ScreensFile)) { // Loading the screen collection will automatically create the available screens and add them to the collection. ScreenCollection screenCollection = new ScreenCollection(); screenCollection.LoadXmlFileAndAddScreens(new ImageFormatCollection()); } if (string.IsNullOrEmpty(FileSystem.TriggersFile)) { // Loading triggers will automatically create the default triggers and add them to the collection. TriggerCollection triggerCollection = new TriggerCollection(); triggerCollection.LoadXmlFileAndAddTriggers(); } if (string.IsNullOrEmpty(FileSystem.TagsFile)) { // Loading tags will automatically create the default tags and add them to the collection. TagCollection tagCollection = new TagCollection(); tagCollection.LoadXmlFileAndAddTags(); } if (string.IsNullOrEmpty(FileSystem.SchedulesFile)) { // Loading schedules will automatically create the default schedules and add them to the collection. ScheduleCollection scheduleCollection = new ScheduleCollection(); scheduleCollection.LoadXmlFileAndAddSchedules(); } }
private static void CheckAndCreateFiles() { if (string.IsNullOrEmpty(FileSystem.CommandFile)) { FileSystem.CommandFile = FileSystem.DefaultCommandFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nCommandFile=" + FileSystem.DefaultCommandFile); if (!FileSystem.FileExists(FileSystem.DefaultCommandFile)) { FileSystem.CreateFile(FileSystem.DefaultCommandFile); } } if (string.IsNullOrEmpty(FileSystem.ApplicationSettingsFile)) { FileSystem.ApplicationSettingsFile = FileSystem.DefaultApplicationSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } } if (string.IsNullOrEmpty(FileSystem.UserSettingsFile)) { FileSystem.UserSettingsFile = FileSystem.DefaultUserSettingsFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nUserSettingsFile=" + FileSystem.DefaultUserSettingsFile); if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder)) { FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder); } } Settings.Initialize(); Log.WriteMessage("Loading user settings"); Settings.User.Load(); Log.WriteDebugMessage("User settings loaded"); Log.WriteDebugMessage("Attempting upgrade of application settings from old version of application (if needed)"); Settings.Application.Upgrade(); Log.WriteDebugMessage("Attempting upgrade of user settings from old version of application (if needed)"); Settings.User.Upgrade(); if (string.IsNullOrEmpty(FileSystem.ScreenshotsFile)) { ImageFormatCollection imageFormatCollection = new ImageFormatCollection(); ScreenCollection screenCollection = new ScreenCollection(); ScreenshotCollection screenshotCollection = new ScreenshotCollection(imageFormatCollection, screenCollection); screenshotCollection.SaveToXmlFile(0); } if (string.IsNullOrEmpty(FileSystem.EditorsFile)) { // Loading the editor collection will automatically create the default editors and add them to the collection. EditorCollection editorCollection = new EditorCollection(); editorCollection.LoadXmlFileAndAddEditors(); } if (string.IsNullOrEmpty(FileSystem.RegionsFile)) { RegionCollection regionCollection = new RegionCollection(); regionCollection.SaveToXmlFile(); } if (string.IsNullOrEmpty(FileSystem.ScreensFile)) { // Loading the screen collection will automatically create the available screens and add them to the collection. ScreenCollection screenCollection = new ScreenCollection(); screenCollection.LoadXmlFileAndAddScreens(new ImageFormatCollection()); } if (string.IsNullOrEmpty(FileSystem.TriggersFile)) { // Loading triggers will automatically create the default triggers and add them to the collection. TriggerCollection triggerCollection = new TriggerCollection(); triggerCollection.LoadXmlFileAndAddTriggers(); } if (string.IsNullOrEmpty(FileSystem.TagsFile)) { // Loading tags will automatically create the default tags and add them to the collection. TagCollection tagCollection = new TagCollection(); tagCollection.LoadXmlFileAndAddTags(); } if (string.IsNullOrEmpty(FileSystem.SchedulesFile)) { // Loading schedules will automatically create the default schedules and add them to the collection. ScheduleCollection scheduleCollection = new ScheduleCollection(); scheduleCollection.LoadXmlFileAndAddSchedules(); } }
/// <summary> /// Saves the tags. /// </summary> public void SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.Indent = true; xSettings.CloseOutput = true; xSettings.CheckCharacters = true; xSettings.Encoding = Encoding.UTF8; xSettings.NewLineChars = Environment.NewLine; xSettings.IndentChars = XML_FILE_INDENT_CHARS; xSettings.NewLineHandling = NewLineHandling.Entitize; xSettings.ConformanceLevel = ConformanceLevel.Document; if (string.IsNullOrEmpty(FileSystem.TagsFile)) { FileSystem.TagsFile = FileSystem.DefaultTagsFile; if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nTagsFile=" + FileSystem.TagsFile); } } if (FileSystem.FileExists(FileSystem.TagsFile)) { FileSystem.DeleteFile(FileSystem.TagsFile); } using (XmlWriter xWriter = XmlWriter.Create(FileSystem.TagsFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_TAGS_NODE); foreach (Tag tag in base.Collection) { xWriter.WriteStartElement(XML_FILE_TAG_NODE); xWriter.WriteElementString(TAG_ACTIVE, tag.Active.ToString()); xWriter.WriteElementString(TAG_NAME, tag.Name); xWriter.WriteElementString(TAG_DESCRIPTION, tag.Description); xWriter.WriteElementString(TAG_NOTES, tag.Notes); xWriter.WriteElementString(TAG_TYPE, tag.Type.ToString()); xWriter.WriteElementString(TAG_DATETIME_FORMAT_VALUE, tag.DateTimeFormatValue); xWriter.WriteElementString(TAG_TIME_OF_DAY_MORNING_START, tag.TimeOfDayMorningStart.ToString()); xWriter.WriteElementString(TAG_TIME_OF_DAY_MORNING_END, tag.TimeOfDayMorningEnd.ToString()); xWriter.WriteElementString(TAG_TIME_OF_DAY_AFTERNOON_START, tag.TimeOfDayAfternoonStart.ToString()); xWriter.WriteElementString(TAG_TIME_OF_DAY_AFTERNOON_END, tag.TimeOfDayAfternoonEnd.ToString()); xWriter.WriteElementString(TAG_TIME_OF_DAY_EVENING_START, tag.TimeOfDayEveningStart.ToString()); xWriter.WriteElementString(TAG_TIME_OF_DAY_EVENING_END, tag.TimeOfDayEveningEnd.ToString()); xWriter.WriteElementString(TAG_TIME_OF_DAY_MORNING_VALUE, tag.TimeOfDayMorningValue); xWriter.WriteElementString(TAG_TIME_OF_DAY_AFTERNOON_VALUE, tag.TimeOfDayAfternoonValue); xWriter.WriteElementString(TAG_TIME_OF_DAY_EVENING_VALUE, tag.TimeOfDayEveningValue); xWriter.WriteElementString(TAG_TIME_OF_DAY_EVENING_EXTENDS_TO_NEXT_MORNING, tag.EveningExtendsToNextMorning.ToString()); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } } catch (Exception ex) { Log.WriteExceptionMessage("TagCollection::SaveToXmlFile", ex); } }
/// <summary> /// Saves the image editors in the collection to the editors.xml file. /// </summary> public bool SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings { Indent = true, CloseOutput = true, CheckCharacters = true, Encoding = Encoding.UTF8, NewLineChars = Environment.NewLine, IndentChars = XML_FILE_INDENT_CHARS, NewLineHandling = NewLineHandling.Entitize, ConformanceLevel = ConformanceLevel.Document }; if (string.IsNullOrEmpty(FileSystem.EditorsFile)) { FileSystem.EditorsFile = FileSystem.DefaultEditorsFile; if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nEditorsFile=" + FileSystem.EditorsFile); } } if (FileSystem.FileExists(FileSystem.EditorsFile)) { FileSystem.DeleteFile(FileSystem.EditorsFile); } using (XmlWriter xWriter = XmlWriter.Create(FileSystem.EditorsFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_EDITORS_NODE); foreach (Editor editor in base.Collection) { xWriter.WriteStartElement(XML_FILE_EDITOR_NODE); xWriter.WriteElementString(EDITOR_NAME, editor.Name); xWriter.WriteElementString(EDITOR_APPLICATION, editor.Application); xWriter.WriteElementString(EDITOR_ARGUMENTS, editor.Arguments); xWriter.WriteElementString(EDITOR_NOTES, editor.Notes); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } return(true); } catch (Exception ex) { Log.WriteExceptionMessage("EditorCollection::SaveToXmlFile", ex); return(false); } }
/// <summary> /// Writes a message (whether it be an error or just a general message) and the exception (if any). /// </summary> /// <param name="message">The message to write.</param> /// <param name="writeError">Determines if we write the message to the error file in the debug folder.</param> /// <param name="ex">The exception received from the .NET Framework.</param> private void Write(string message, bool writeError, Exception ex) { try { _mutexWriteFile.WaitOne(); string appVersion = "[(v" + _settings.ApplicationVersion + ") "; if (string.IsNullOrEmpty(_fileSystem.DebugFolder)) { _fileSystem.DebugFolder = AppDomain.CurrentDomain.BaseDirectory + @"!autoscreen" + _fileSystem.PathDelimiter + "debug" + _fileSystem.PathDelimiter; } if (string.IsNullOrEmpty(_fileSystem.LogsFolder)) { _fileSystem.LogsFolder = _fileSystem.DebugFolder + "logs" + _fileSystem.PathDelimiter; } if (!_fileSystem.DirectoryExists(_fileSystem.DebugFolder)) { _fileSystem.CreateDirectory(_fileSystem.DebugFolder); } if (!_fileSystem.DirectoryExists(_fileSystem.LogsFolder)) { _fileSystem.CreateDirectory(_fileSystem.LogsFolder); } // These are just general errors from the application so, if we have one, then write it out to the error file. if (writeError) { _fileSystem.AppendToFile(_fileSystem.DebugFolder + _fileSystem.ErrorFile, appVersion + DateTime.Now.ToString(_macroParser.DateFormat + " " + _macroParser.TimeFormat) + "] ERROR: " + message); } // Log any exception errors we encounter. if (ex != null) { string exceptionError = appVersion + DateTime.Now.ToString(_macroParser.DateFormat + " " + _macroParser.TimeFormat) + "] " + message + " - Exception Message: " + ex.Message + "\nInner Exception: " + (ex.InnerException != null ? ex.InnerException.Message : string.Empty) + "\nSource: " + ex.Source + "\nStack Trace: " + ex.StackTrace; _fileSystem.AppendToFile(_fileSystem.DebugFolder + _fileSystem.ErrorFile, exceptionError); _fileSystem.AppendToFile(_fileSystem.LogsFolder + _fileSystem.LogFile + _extension, exceptionError); // If we encounter an exception error it's probably better to just error out on exit // but we'll let the user decide if that's what they really want to do. if (_settings.Application == null || Convert.ToBoolean(_settings.Application.GetByKey("ExitOnError", _settings.DefaultSettings.ExitOnError).Value)) { Environment.Exit(1); } } else { // Write to the main log file. _fileSystem.AppendToFile(_fileSystem.LogsFolder + _fileSystem.LogFile + _extension, appVersion + DateTime.Now.ToString(_macroParser.DateFormat + " " + _macroParser.TimeFormat) + "] " + message); // Create a date-stamped directory if it does not already exist. if (!_fileSystem.DirectoryExists(_fileSystem.LogsFolder + DateTime.Now.ToString(_macroParser.DateFormat))) { _fileSystem.CreateDirectory(_fileSystem.LogsFolder + DateTime.Now.ToString(_macroParser.DateFormat)); } // Write to a log file within a directory representing the day when the message was logged. _fileSystem.AppendToFile(_fileSystem.LogsFolder + DateTime.Now.ToString(_macroParser.DateFormat) + _fileSystem.PathDelimiter + _fileSystem.LogFile + "_" + DateTime.Now.ToString(_macroParser.DateFormat) + ".txt", appVersion + DateTime.Now.ToString(_macroParser.DateFormat + " " + _macroParser.TimeFormat) + "] " + message); } } finally { _mutexWriteFile.ReleaseMutex(); } }
/// <summary> /// Saves the image schedules in the collection to the schedules.xml file. /// </summary> public void SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings { Indent = true, CloseOutput = true, CheckCharacters = true, Encoding = Encoding.UTF8, NewLineChars = Environment.NewLine, IndentChars = XML_FILE_INDENT_CHARS, NewLineHandling = NewLineHandling.Entitize, ConformanceLevel = ConformanceLevel.Document }; if (string.IsNullOrEmpty(FileSystem.SchedulesFile)) { FileSystem.SchedulesFile = FileSystem.DefaultSchedulesFile; FileSystem.AppendToFile(FileSystem.ConfigFile, "\nSchedulesFile=" + FileSystem.SchedulesFile); } if (FileSystem.FileExists(FileSystem.SchedulesFile)) { FileSystem.DeleteFile(FileSystem.SchedulesFile); } using (XmlWriter xWriter = XmlWriter.Create(FileSystem.SchedulesFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_SCHEDULES_NODE); foreach (Schedule schedule in base.Collection) { xWriter.WriteStartElement(XML_FILE_SCHEDULE_NODE); xWriter.WriteElementString(SCHEDULE_ACTIVE, schedule.Active.ToString()); xWriter.WriteElementString(SCHEDULE_NAME, schedule.Name); xWriter.WriteElementString(SCHEDULE_MODE_ONETIME, schedule.ModeOneTime.ToString()); xWriter.WriteElementString(SCHEDULE_MODE_PERIOD, schedule.ModePeriod.ToString()); xWriter.WriteElementString(SCHEDULE_CAPTUREAT, schedule.CaptureAt.ToString()); xWriter.WriteElementString(SCHEDULE_STARTAT, schedule.StartAt.ToString()); xWriter.WriteElementString(SCHEDULE_STOPAT, schedule.StopAt.ToString()); xWriter.WriteElementString(SCHEDULE_MONDAY, schedule.Monday.ToString()); xWriter.WriteElementString(SCHEDULE_TUESDAY, schedule.Tuesday.ToString()); xWriter.WriteElementString(SCHEDULE_WEDNESDAY, schedule.Wednesday.ToString()); xWriter.WriteElementString(SCHEDULE_THURSDAY, schedule.Thursday.ToString()); xWriter.WriteElementString(SCHEDULE_FRIDAY, schedule.Friday.ToString()); xWriter.WriteElementString(SCHEDULE_SATURDAY, schedule.Saturday.ToString()); xWriter.WriteElementString(SCHEDULE_SUNDAY, schedule.Sunday.ToString()); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } } catch (Exception ex) { Log.WriteExceptionMessage("ScheduleCollection::SaveToXmlFile", ex); } }
/// <summary> /// Saves the triggers. /// </summary> public bool SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.Indent = true; xSettings.CloseOutput = true; xSettings.CheckCharacters = true; xSettings.Encoding = Encoding.UTF8; xSettings.NewLineChars = Environment.NewLine; xSettings.IndentChars = XML_FILE_INDENT_CHARS; xSettings.NewLineHandling = NewLineHandling.Entitize; xSettings.ConformanceLevel = ConformanceLevel.Document; if (string.IsNullOrEmpty(FileSystem.TriggersFile)) { FileSystem.TriggersFile = FileSystem.DefaultTriggersFile; if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nTriggersFile=" + FileSystem.TriggersFile); } } FileSystem.DeleteFile(FileSystem.TriggersFile); using (XmlWriter xWriter = XmlWriter.Create(FileSystem.TriggersFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_TRIGGERS_NODE); foreach (Trigger trigger in base.Collection) { xWriter.WriteStartElement(XML_FILE_TRIGGER_NODE); xWriter.WriteElementString(TRIGGER_ACTIVE, trigger.Active.ToString()); xWriter.WriteElementString(TRIGGER_NAME, trigger.Name); xWriter.WriteElementString(TRIGGER_CONDITION, trigger.ConditionType.ToString()); xWriter.WriteElementString(TRIGGER_ACTION, trigger.ActionType.ToString()); xWriter.WriteElementString(TRIGGER_DATE, trigger.Date.ToString()); xWriter.WriteElementString(TRIGGER_TIME, trigger.Time.ToString()); xWriter.WriteElementString(TRIGGER_DAY, string.IsNullOrEmpty(trigger.Day) ? "Weekday" : trigger.Day.ToString()); xWriter.WriteElementString(TRIGGER_DAYS, trigger.Days.ToString()); xWriter.WriteElementString(TRIGGER_SCREEN_CAPTURE_INTERVAL, trigger.ScreenCaptureInterval.ToString()); xWriter.WriteElementString(TRIGGER_MODULE_ITEM, trigger.ModuleItem); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } return(true); } catch (Exception ex) { Log.WriteExceptionMessage("TriggerCollection::SaveToXmlFile", ex); return(false); } }
/// <summary> /// Saves the screens. /// </summary> public bool SaveToXmlFile(Settings settings, FileSystem fileSystem, Log log) { try { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.Indent = true; xSettings.CloseOutput = true; xSettings.CheckCharacters = true; xSettings.Encoding = Encoding.UTF8; xSettings.NewLineChars = Environment.NewLine; xSettings.IndentChars = XML_FILE_INDENT_CHARS; xSettings.NewLineHandling = NewLineHandling.Entitize; xSettings.ConformanceLevel = ConformanceLevel.Document; if (string.IsNullOrEmpty(fileSystem.ScreensFile)) { fileSystem.ScreensFile = fileSystem.DefaultScreensFile; if (fileSystem.FileExists(fileSystem.ConfigFile)) { fileSystem.AppendToFile(fileSystem.ConfigFile, "\nScreensFile=" + fileSystem.ScreensFile); } } if (fileSystem.FileExists(fileSystem.ScreensFile)) { fileSystem.DeleteFile(fileSystem.ScreensFile); } using (XmlWriter xWriter = XmlWriter.Create(fileSystem.ScreensFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_SCREENS_NODE); foreach (Screen screen in base.Collection) { xWriter.WriteStartElement(XML_FILE_SCREEN_NODE); xWriter.WriteElementString(SCREEN_ENABLE, screen.Enable.ToString()); xWriter.WriteElementString(SCREEN_VIEWID, screen.ViewId.ToString()); xWriter.WriteElementString(SCREEN_NAME, screen.Name); xWriter.WriteElementString(SCREEN_FOLDER, fileSystem.CorrectScreenshotsFolderPath(screen.Folder)); xWriter.WriteElementString(SCREEN_MACRO, screen.Macro); xWriter.WriteElementString(SCREEN_COMPONENT, screen.Component.ToString()); xWriter.WriteElementString(SCREEN_FORMAT, screen.Format.Name); xWriter.WriteElementString(SCREEN_JPEG_QUALITY, screen.JpegQuality.ToString()); xWriter.WriteElementString(SCREEN_MOUSE, screen.Mouse.ToString()); xWriter.WriteElementString(SCREEN_X, screen.X.ToString()); xWriter.WriteElementString(SCREEN_Y, screen.Y.ToString()); xWriter.WriteElementString(SCREEN_WIDTH, screen.Width.ToString()); xWriter.WriteElementString(SCREEN_HEIGHT, screen.Height.ToString()); xWriter.WriteElementString(SCREEN_SOURCE, screen.Source.ToString()); xWriter.WriteElementString(SCREEN_DEVICE_NAME, screen.DeviceName); xWriter.WriteElementString(SCREEN_AUTO_ADAPT, screen.AutoAdapt.ToString()); xWriter.WriteElementString(SCREEN_CAPTURE_METHOD, screen.CaptureMethod.ToString()); xWriter.WriteElementString(SCREEN_ENCRYPT, screen.Encrypt.ToString()); xWriter.WriteElementString(SCREEN_RESOLUTION_RATIO, screen.ResolutionRatio.ToString()); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } return(true); } catch (Exception ex) { log.WriteExceptionMessage("ScreenCollection::SaveToXmlFile", ex); return(false); } }
/// <summary> /// Saves the screens. /// </summary> public bool SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.Indent = true; xSettings.CloseOutput = true; xSettings.CheckCharacters = true; xSettings.Encoding = Encoding.UTF8; xSettings.NewLineChars = Environment.NewLine; xSettings.IndentChars = XML_FILE_INDENT_CHARS; xSettings.NewLineHandling = NewLineHandling.Entitize; xSettings.ConformanceLevel = ConformanceLevel.Document; if (string.IsNullOrEmpty(FileSystem.ScreensFile)) { FileSystem.ScreensFile = FileSystem.DefaultScreensFile; if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nScreensFile=" + FileSystem.ScreensFile); } } if (FileSystem.FileExists(FileSystem.ScreensFile)) { FileSystem.DeleteFile(FileSystem.ScreensFile); } using (XmlWriter xWriter = XmlWriter.Create(FileSystem.ScreensFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_SCREENS_NODE); foreach (Screen screen in base.Collection) { xWriter.WriteStartElement(XML_FILE_SCREEN_NODE); xWriter.WriteElementString(SCREEN_ACTIVE, screen.Active.ToString()); xWriter.WriteElementString(SCREEN_VIEWID, screen.ViewId.ToString()); xWriter.WriteElementString(SCREEN_NAME, screen.Name); xWriter.WriteElementString(SCREEN_FOLDER, FileSystem.CorrectScreenshotsFolderPath(screen.Folder)); xWriter.WriteElementString(SCREEN_MACRO, screen.Macro); xWriter.WriteElementString(SCREEN_COMPONENT, screen.Component.ToString()); xWriter.WriteElementString(SCREEN_FORMAT, screen.Format.Name); xWriter.WriteElementString(SCREEN_JPEG_QUALITY, screen.JpegQuality.ToString()); xWriter.WriteElementString(SCREEN_RESOLUTION_RATIO, screen.ResolutionRatio.ToString()); xWriter.WriteElementString(SCREEN_MOUSE, screen.Mouse.ToString()); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } return(true); } catch (Exception ex) { Log.WriteExceptionMessage("ScreenCollection::SaveToXmlFile", ex); return(false); } }
/// <summary> /// Saves the screenshots in the collection to the screenshots.xml file. /// This method will also delete old screenshot references based on the number of days screenshots should be kept. /// </summary> /// <param name="keepScreenshotsForDays">The number of days screenshots should be kept.</param> public void SaveToXmlFile(int keepScreenshotsForDays) { try { _mutexWriteFile.WaitOne(); if (string.IsNullOrEmpty(FileSystem.ScreenshotsFile)) { FileSystem.ScreenshotsFile = FileSystem.DefaultScreenshotsFile; if (xDoc == null) { xDoc = new XmlDocument(); XmlElement rootElement = xDoc.CreateElement(XML_FILE_ROOT_NODE); XmlElement xScreenshots = xDoc.CreateElement(XML_FILE_SCREENSHOTS_NODE); XmlAttribute attributeVersion = xDoc.CreateAttribute("app", "version", "autoscreen"); XmlAttribute attributeCodename = xDoc.CreateAttribute("app", "codename", "autoscreen"); attributeVersion.Value = Settings.ApplicationVersion; attributeCodename.Value = Settings.ApplicationCodename; rootElement.Attributes.Append(attributeVersion); rootElement.Attributes.Append(attributeCodename); rootElement.AppendChild(xScreenshots); xDoc.AppendChild(rootElement); xDoc.Save(FileSystem.ScreenshotsFile); } if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nScreenshotsFile=" + FileSystem.ScreenshotsFile); } } // Delete old screenshots. if (keepScreenshotsForDays > 0) { lock (_screenshotList) { // Check what we already have in memory and remove the screenshot object from every list. List <Screenshot> screenshotsToDelete = _screenshotList.Where(x => !string.IsNullOrEmpty(x.Date) && Convert.ToDateTime(x.Date) <= DateTime.Now.Date.AddDays(-keepScreenshotsForDays)).ToList(); foreach (Screenshot screenshot in screenshotsToDelete) { _screenshotList.Remove(screenshot); _slideList.Remove(screenshot.Slide); _slideNameList.Remove(screenshot.Slide.Name); } } XmlNode minDateNode = GetMinDateFromXMLDocument(); if (minDateNode != null) { DateTime dtMin = DateTime.Parse(minDateNode.FirstChild.Value).Date; DateTime dtMax = DateTime.Now.Date.AddDays(-keepScreenshotsForDays).Date; for (DateTime date = dtMin; date.Date <= dtMax; date = date.AddDays(1)) { XmlNodeList screenshotNodesToDeleteByDate = xDoc.SelectNodes(SCREENSHOT_XPATH + "[" + SCREENSHOT_DATE + "='" + date.ToString(MacroParser.DateFormat) + "']"); foreach (XmlNode node in screenshotNodesToDeleteByDate) { string path = node.SelectSingleNode("path").FirstChild.Value; if (FileSystem.FileExists(path)) { FileSystem.DeleteFile(path); } node.ParentNode.RemoveChild(node); } } } } // Save screeenshots. lock (_screenshotList) { for (int i = 0; i < _screenshotList.Count; i++) { Screenshot screenshot = _screenshotList[i]; // A new screenshot that needs to be written to the file will have its "Saved" property set to "false" so make sure to check that. if (!screenshot.Saved && xDoc != null && screenshot?.Format != null && !string.IsNullOrEmpty(screenshot.Format.Name)) { XmlElement xScreenshot = xDoc.CreateElement(XML_FILE_SCREENSHOT_NODE); // Starting from version 2.3.0.0 we're going to save the version number of the application // with every screenshot that gets saved so, when looking at the screenshots XML document, // we can determine what version each screenshot originated from. If there is no <version></version> // tag then assume you're looking at a screenshot XML node from before version 2.3.0.0! // // It should also be noted that we don't want to "upgrade" the version of the entire XML document // because the document can become very large and we don't want to lose the ability to know if we're // reading from an old version of the document. We don't read from the entire document either (starting with 2.3) // since the new way is reading individual screenshot XML nodes. XmlElement xVersion = xDoc.CreateElement(SCREENSHOT_VERSION); xVersion.InnerText = screenshot.Version; XmlElement xViedId = xDoc.CreateElement(SCREENSHOT_VIEWID); xViedId.InnerText = screenshot.ViewId.ToString(); XmlElement xDate = xDoc.CreateElement(SCREENSHOT_DATE); xDate.InnerText = screenshot.Date; XmlElement xTime = xDoc.CreateElement(SCREENSHOT_TIME); xTime.InnerText = screenshot.Time; XmlElement xPath = xDoc.CreateElement(SCREENSHOT_PATH); xPath.InnerText = screenshot.Path; XmlElement xFormat = xDoc.CreateElement(SCREENSHOT_FORMAT); xFormat.InnerText = screenshot.Format.Name; XmlElement xComponent = xDoc.CreateElement(SCREENSHOT_COMPONENT); xComponent.InnerText = screenshot.Component.ToString(); XmlElement xSlidename = xDoc.CreateElement(SCREENSHOT_SLIDENAME); xSlidename.InnerText = screenshot.Slide.Name; XmlElement xSlidevalue = xDoc.CreateElement(SCREENSHOT_SLIDEVALUE); xSlidevalue.InnerText = screenshot.Slide.Value; XmlElement xWindowTitle = xDoc.CreateElement(SCREENSHOT_WINDOW_TITLE); xWindowTitle.InnerText = screenshot.WindowTitle; XmlElement xProcessName = xDoc.CreateElement(SCREENSHOT_PROCESS_NAME); xProcessName.InnerText = screenshot.ProcessName; XmlElement xLabel = xDoc.CreateElement(SCREENSHOT_LABEL); xLabel.InnerText = screenshot.Label; xScreenshot.AppendChild(xVersion); xScreenshot.AppendChild(xViedId); xScreenshot.AppendChild(xDate); xScreenshot.AppendChild(xTime); xScreenshot.AppendChild(xPath); xScreenshot.AppendChild(xFormat); xScreenshot.AppendChild(xComponent); xScreenshot.AppendChild(xSlidename); xScreenshot.AppendChild(xSlidevalue); xScreenshot.AppendChild(xWindowTitle); xScreenshot.AppendChild(xProcessName); xScreenshot.AppendChild(xLabel); XmlNode xScreenshots = xDoc.SelectSingleNode(SCREENSHOTS_XPATH); if (xScreenshots != null) { if (xScreenshots.HasChildNodes) { xScreenshots.InsertAfter(xScreenshot, xScreenshots.LastChild); } else { xScreenshots.AppendChild(xScreenshot); } // Make sure to set this property to "true" so we only write out new screenshots (those with "Saved" set to "false"). screenshot.Saved = true; _screenshotList[i] = screenshot; } } } if (xDoc != null) { lock (xDoc) { xDoc.Save(FileSystem.ScreenshotsFile); } } } } finally { _mutexWriteFile.ReleaseMutex(); } }
/// <summary> /// Saves the tags. /// </summary> public bool SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.Indent = true; xSettings.CloseOutput = true; xSettings.CheckCharacters = true; xSettings.Encoding = Encoding.UTF8; xSettings.NewLineChars = Environment.NewLine; xSettings.IndentChars = XML_FILE_INDENT_CHARS; xSettings.NewLineHandling = NewLineHandling.Entitize; xSettings.ConformanceLevel = ConformanceLevel.Document; if (string.IsNullOrEmpty(FileSystem.TagsFile)) { FileSystem.TagsFile = FileSystem.DefaultTagsFile; if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nTagsFile=" + FileSystem.TagsFile); } } FileSystem.DeleteFile(FileSystem.TagsFile); using (XmlWriter xWriter = XmlWriter.Create(FileSystem.TagsFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_TAGS_NODE); foreach (MacroTag tag in base.Collection) { xWriter.WriteStartElement(XML_FILE_TAG_NODE); xWriter.WriteElementString(TAG_ACTIVE, tag.Active.ToString()); xWriter.WriteElementString(TAG_NAME, tag.Name); xWriter.WriteElementString(TAG_DESCRIPTION, tag.Description); xWriter.WriteElementString(TAG_NOTES, tag.Notes); xWriter.WriteElementString(TAG_TYPE, tag.Type.ToString()); xWriter.WriteElementString(TAG_DATETIME_FORMAT_VALUE, tag.DateTimeFormatValue); xWriter.WriteElementString(TAG_TIMERANGE_MACRO1_START, tag.TimeRangeMacro1Start.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO1_END, tag.TimeRangeMacro1End.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO2_START, tag.TimeRangeMacro2Start.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO2_END, tag.TimeRangeMacro2End.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO3_START, tag.TimeRangeMacro3Start.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO3_END, tag.TimeRangeMacro3End.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO4_START, tag.TimeRangeMacro4Start.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO4_END, tag.TimeRangeMacro4End.ToString()); xWriter.WriteElementString(TAG_TIMERANGE_MACRO1_MACRO, tag.TimeRangeMacro1Macro); xWriter.WriteElementString(TAG_TIMERANGE_MACRO2_MACRO, tag.TimeRangeMacro2Macro); xWriter.WriteElementString(TAG_TIMERANGE_MACRO3_MACRO, tag.TimeRangeMacro3Macro); xWriter.WriteElementString(TAG_TIMERANGE_MACRO4_MACRO, tag.TimeRangeMacro4Macro); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } return(true); } catch (Exception ex) { Log.WriteExceptionMessage("TagCollection::SaveToXmlFile", ex); return(false); } }
/// <summary> /// Saves the regions. /// </summary> public void SaveToXmlFile() { try { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.Indent = true; xSettings.CloseOutput = true; xSettings.CheckCharacters = true; xSettings.Encoding = Encoding.UTF8; xSettings.NewLineChars = Environment.NewLine; xSettings.IndentChars = XML_FILE_INDENT_CHARS; xSettings.NewLineHandling = NewLineHandling.Entitize; xSettings.ConformanceLevel = ConformanceLevel.Document; if (string.IsNullOrEmpty(FileSystem.RegionsFile)) { FileSystem.RegionsFile = FileSystem.DefaultRegionsFile; if (FileSystem.FileExists(FileSystem.ConfigFile)) { FileSystem.AppendToFile(FileSystem.ConfigFile, "\nRegionsFile=" + FileSystem.RegionsFile); } } if (FileSystem.FileExists(FileSystem.RegionsFile)) { FileSystem.DeleteFile(FileSystem.RegionsFile); } using (XmlWriter xWriter = XmlWriter.Create(FileSystem.RegionsFile, xSettings)) { xWriter.WriteStartDocument(); xWriter.WriteStartElement(XML_FILE_ROOT_NODE); xWriter.WriteAttributeString("app", "version", XML_FILE_ROOT_NODE, Settings.ApplicationVersion); xWriter.WriteAttributeString("app", "codename", XML_FILE_ROOT_NODE, Settings.ApplicationCodename); xWriter.WriteStartElement(XML_FILE_REGIONS_NODE); foreach (Region region in base.Collection) { xWriter.WriteStartElement(XML_FILE_REGION_NODE); xWriter.WriteElementString(REGION_ACTIVE, region.Active.ToString()); xWriter.WriteElementString(REGION_VIEWID, region.ViewId.ToString()); xWriter.WriteElementString(REGION_NAME, region.Name); xWriter.WriteElementString(REGION_FOLDER, FileSystem.CorrectScreenshotsFolderPath(region.Folder)); xWriter.WriteElementString(REGION_MACRO, region.Macro); xWriter.WriteElementString(REGION_FORMAT, region.Format.Name); xWriter.WriteElementString(REGION_JPEG_QUALITY, region.JpegQuality.ToString()); xWriter.WriteElementString(REGION_RESOLUTION_RATIO, region.ResolutionRatio.ToString()); xWriter.WriteElementString(REGION_MOUSE, region.Mouse.ToString()); xWriter.WriteElementString(REGION_X, region.X.ToString()); xWriter.WriteElementString(REGION_Y, region.Y.ToString()); xWriter.WriteElementString(REGION_WIDTH, region.Width.ToString()); xWriter.WriteElementString(REGION_HEIGHT, region.Height.ToString()); xWriter.WriteElementString(REGION_ACTIVE_WINDOW_TITLE_CAPTURE_CHECK, region.ActiveWindowTitleCaptureCheck.ToString()); xWriter.WriteElementString(REGION_ACTIVE_WINDOW_TITLE_CAPTURE_TEXT, region.ActiveWindowTitleCaptureText); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.WriteEndElement(); xWriter.WriteEndDocument(); xWriter.Flush(); xWriter.Close(); } } catch (Exception ex) { Log.WriteExceptionMessage("RegionCollection::SaveToXmlFile", ex); } }