private void LoadEditors()
        {
            listBoxEditor.Items.Clear();

            foreach (Editor editor in EditorCollection)
            {
                if (editor != null && FileSystem.FileExists(editor.Application))
                {
                    listBoxEditor.Items.Add(editor.Name);
                }
            }

            listBoxEditor.SelectedIndex = 0;
        }
Exemple #2
0
        private void FormEditor_Load(object sender, EventArgs e)
        {
            textBoxName.Focus();

            HelpMessage("This is where to configure an application or script for editing screenshots. The optional %filepath% argument is the filepath of the screenshot");

            _toolTip.SetToolTip(checkBoxMakeDefaultEditor, "When checked it will make this editor the default editor");
            _toolTip.SetToolTip(buttonChooseEditor, "Browse for an application or script");

            checkBoxMakeDefaultEditor.Checked = false;

            if (EditorObject != null)
            {
                Text = "Change Editor";

                if (!string.IsNullOrEmpty(EditorObject.Application) &&
                    FileSystem.FileExists(EditorObject.Application))
                {
                    Icon = Icon.ExtractAssociatedIcon(EditorObject.Application);
                }
                else
                {
                    Icon = (Icon)(resources.GetObject("$this.Icon"));
                }

                textBoxName.Text        = EditorObject.Name;
                textBoxApplication.Text = EditorObject.Application;
                textBoxArguments.Text   = EditorObject.Arguments;

                string defaultEditor = Settings.User.GetByKey("DefaultEditor", DefaultSettings.DefaultEditor).Value.ToString();

                if (EditorObject.Name.Equals(defaultEditor))
                {
                    checkBoxMakeDefaultEditor.Checked = true;
                }

                textBoxNotes.Text = EditorObject.Notes;
            }
            else
            {
                Text = "Add Editor";
                Icon = (Icon)(resources.GetObject("$this.Icon"));

                textBoxName.Text        = "Editor " + (EditorCollection.Count + 1);
                textBoxApplication.Text = string.Empty;
                textBoxArguments.Text   = defaultArguments;
                textBoxNotes.Text       = string.Empty;
            }
        }
Exemple #3
0
        private void FormEditor_Load(object sender, EventArgs e)
        {
            textBoxName.Focus();

            HelpMessage("This is where to configure an image editor for editing screenshots");

            checkBoxMakeDefaultEditor.Checked = false;

            if (EditorObject != null)
            {
                Text = "Change Editor";

                if (!string.IsNullOrEmpty(EditorObject.Application) &&
                    FileSystem.FileExists(EditorObject.Application))
                {
                    Icon = Icon.ExtractAssociatedIcon(EditorObject.Application);
                }
                else
                {
                    Icon = (Icon)(resources.GetObject("$this.Icon"));
                }

                textBoxName.Text        = EditorObject.Name;
                textBoxApplication.Text = EditorObject.Application;
                textBoxArguments.Text   = EditorObject.Arguments;

                string defaultEditor = Settings.User.GetByKey("StringDefaultEditor", DefaultSettings.StringDefaultEditor).Value.ToString();

                if (EditorObject.Name.Equals(defaultEditor))
                {
                    checkBoxMakeDefaultEditor.Checked = true;
                }

                textBoxNotes.Text = EditorObject.Notes;
            }
            else
            {
                Text = "Add New Editor";
                Icon = (Icon)(resources.GetObject("$this.Icon"));

                textBoxName.Text        = "Editor " + (EditorCollection.Count + 1);
                textBoxApplication.Text = string.Empty;
                textBoxArguments.Text   = defaultArguments;
                textBoxNotes.Text       = string.Empty;
            }
        }
        /// <summary>
        /// Encrypts the screenshots in the specified date range.
        /// </summary>
        private void RunScreenshotsEncryption()
        {
            if (comboBoxFilterType.InvokeRequired || comboBoxFilterValue.InvokeRequired)
            {
                if (comboBoxFilterType.InvokeRequired)
                {
                    comboBoxFilterType.Invoke(new RunScreenshotsEncryptionDelegate(RunScreenshotsEncryption));
                }

                if (comboBoxFilterValue.InvokeRequired)
                {
                    comboBoxFilterValue.Invoke(new RunScreenshotsEncryptionDelegate(RunScreenshotsEncryption));
                }
            }
            else
            {
                foreach (Screenshot screenshot in _screenshotCollection.GetScreenshots(dateTimePickerScreenshotsStartDateRange.Value,
                                                                                       dateTimePickerScreenshotsEndDateRange.Value,
                                                                                       dateTimePickerScreenshotsStartTimeRange.Value,
                                                                                       dateTimePickerScreenshotsEndTimeRange.Value,
                                                                                       comboBoxFilterType.Text,
                                                                                       comboBoxFilterValue.Text))
                {
                    if (!screenshot.Encrypted)
                    {
                        string key = _security.EncryptFile(screenshot.FilePath, screenshot.FilePath + "-encrypted");

                        if (!string.IsNullOrEmpty(key))
                        {
                            if (_fileSystem.FileExists(screenshot.FilePath))
                            {
                                if (_fileSystem.DeleteFile(screenshot.FilePath))
                                {
                                    _fileSystem.MoveFile(screenshot.FilePath + "-encrypted", screenshot.FilePath);

                                    _screenshotCollection.GetScreenshot(screenshot.Id).Encrypted      = true;
                                    _screenshotCollection.GetScreenshot(screenshot.Id).Key            = key;
                                    _screenshotCollection.GetScreenshot(screenshot.Id).ReferenceSaved = false;
                                }
                            }
                        }
                        else
                        {
                            _log.WriteMessage("WARNING: Error with file encryption for \"" + screenshot.FilePath + "\"");
                        }
                    }
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Runs the editor using the specified screenshot.
        /// </summary>
        /// <param name="editor">The editor to use.</param>
        /// <param name="screenshot">The screenshot to use.</param>
        private bool RunEditor(Editor editor, Screenshot screenshot)
        {
            // Execute the chosen image editor. If the %filepath% argument happens to be included
            // then we'll use that argument as the screenshot file path when executing the image editor.
            if (editor != null && (screenshot != null && !string.IsNullOrEmpty(screenshot.Path) &&
                                   FileSystem.FileExists(editor.Application) && FileSystem.FileExists(screenshot.Path)))
            {
                Log.WriteDebugMessage("Starting process for editor \"" + editor.Name + "\" ...");
                Log.WriteDebugMessage("Application: " + editor.Application);
                Log.WriteDebugMessage("Arguments before %filepath% tag replacement: " + editor.Arguments);
                Log.WriteDebugMessage("Arguments after %filepath% tag replacement: " + editor.Arguments.Replace("%filepath%", "\"" + screenshot.Path + "\""));

                _ = Process.Start(editor.Application, editor.Arguments.Replace("%filepath%", "\"" + screenshot.Path + "\""));

                // We successfully opened the editor with the given screenshot path.
                return(true);
            }

            // We failed to open the editor with the given screenshot path.
            return(false);
        }
Exemple #6
0
        /// <summary>
        /// Gets the screenshot image from an image file. This is used when we want to show screenshot images.
        /// </summary>
        /// <param name="path">The path of an image file (such as a JPEG or PNG file).</param>
        /// <returns>The image of the file.</returns>
        public Image GetImageByPath(string path)
        {
            try
            {
                Image image = null;

                if (!string.IsNullOrEmpty(path) && _fileSystem.FileExists(path))
                {
                    image = _fileSystem.GetImage(path);
                }

                CaptureError = false;

                return(image);
            }
            catch (Exception ex)
            {
                _log.WriteExceptionMessage("ScreenCapture::GetImageByPath", ex);

                CaptureError = true;

                return(null);
            }
        }
        /// <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);
            }
        }
        /// <summary>
        /// Loads the triggers.
        /// </summary>
        public void LoadXmlFileAndAddTriggers()
        {
            try
            {
                if (FileSystem.FileExists(FileSystem.TriggersFile))
                {
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(FileSystem.TriggersFile);

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xTriggers = xDoc.SelectNodes(TRIGGER_XPATH);

                    foreach (XmlNode xTrigger in xTriggers)
                    {
                        Trigger       trigger = new Trigger();
                        XmlNodeReader xReader = new XmlNodeReader(xTrigger);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement() && !xReader.IsEmptyElement)
                            {
                                switch (xReader.Name)
                                {
                                case TRIGGER_NAME:
                                    xReader.Read();
                                    trigger.Name = xReader.Value;
                                    break;

                                case TRIGGER_CONDITION:
                                    xReader.Read();
                                    trigger.ConditionType =
                                        (TriggerConditionType)Enum.Parse(typeof(TriggerConditionType), xReader.Value);
                                    break;

                                case TRIGGER_ACTION:
                                    xReader.Read();
                                    trigger.ActionType =
                                        (TriggerActionType)Enum.Parse(typeof(TriggerActionType), xReader.Value);
                                    break;

                                case TRIGGER_EDITOR:
                                    xReader.Read();
                                    trigger.Editor = xReader.Value;
                                    break;

                                case TRIGGER_ACTIVE:
                                    xReader.Read();
                                    trigger.Active = Convert.ToBoolean(xReader.Value);
                                    break;

                                case TRIGGER_DATE:
                                    xReader.Read();
                                    trigger.Date = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TRIGGER_TIME:
                                    xReader.Read();
                                    trigger.Time = Convert.ToDateTime(xReader.Value);
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        // Change the data for each Trigger that's being loaded if we've detected that
                        // the XML document is from an older version of the application.
                        if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                        {
                            Log.WriteDebugMessage("An old version of the triggers.xml file was detected. Attempting upgrade to new schema.");

                            Version v2300         = Settings.VersionManager.Versions.Get("Boombayah", "2.3.0.0");
                            Version configVersion = Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                            if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                            {
                                Log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                // This is a new property for Trigger that was introduced in 2.3.0.0
                                // so any version before 2.3.0.0 needs to have it during an upgrade.
                                trigger.Active = true;
                            }
                        }

                        if (!string.IsNullOrEmpty(trigger.Name))
                        {
                            Add(trigger);
                        }
                    }

                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                    {
                        SaveToXmlFile();
                    }
                }
                else
                {
                    Log.WriteDebugMessage($"WARNING: {FileSystem.TriggersFile} not found. Creating default triggers");

                    Trigger triggerApplicationStartShowInterface = new Trigger()
                    {
                        Active        = true,
                        Name          = "Application Startup -> Show",
                        ConditionType = TriggerConditionType.ApplicationStartup,
                        ActionType    = TriggerActionType.ShowInterface
                    };

                    Trigger triggerScreenCaptureStartedHideInterface = new Trigger()
                    {
                        Active        = true,
                        Name          = "Capture Started -> Hide",
                        ConditionType = TriggerConditionType.ScreenCaptureStarted,
                        ActionType    = TriggerActionType.HideInterface
                    };

                    Trigger triggerScreenCaptureStoppedShowInterface = new Trigger()
                    {
                        Active        = true,
                        Name          = "Capture Stopped -> Show",
                        ConditionType = TriggerConditionType.ScreenCaptureStopped,
                        ActionType    = TriggerActionType.ShowInterface
                    };

                    Trigger triggerInterfaceClosingHideInterface = new Trigger()
                    {
                        Active        = true,
                        Name          = "Interface Closing -> Hide",
                        ConditionType = TriggerConditionType.InterfaceClosing,
                        ActionType    = TriggerActionType.HideInterface
                    };

                    Trigger triggerLimitReachedStopScreenCapture = new Trigger()
                    {
                        Active        = true,
                        Name          = "Limit Reached -> Stop",
                        ConditionType = TriggerConditionType.LimitReached,
                        ActionType    = TriggerActionType.StopScreenCapture
                    };

                    // Setup a few "built in" triggers by default.
                    Add(triggerApplicationStartShowInterface);
                    Add(triggerScreenCaptureStartedHideInterface);
                    Add(triggerScreenCaptureStoppedShowInterface);
                    Add(triggerInterfaceClosingHideInterface);
                    Add(triggerLimitReachedStopScreenCapture);

                    SaveToXmlFile();
                }
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("TriggerCollection::LoadXmlFileAndAddTriggers", ex);
            }
        }
        /// <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);
            }
        }
        /// <summary>
        /// Loads the tags.
        /// </summary>
        public bool LoadXmlFileAndAddTags()
        {
            try
            {
                if (FileSystem.FileExists(FileSystem.TagsFile))
                {
                    Log.WriteDebugMessage("Tags file \"" + FileSystem.TagsFile + "\" found. Attempting to load XML document");

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(FileSystem.TagsFile);

                    Log.WriteDebugMessage("XML document loaded");

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xTags = xDoc.SelectNodes(TAG_XPATH);

                    bool eveningExtendsToNextMorning = false;

                    foreach (XmlNode xTag in xTags)
                    {
                        MacroTag      tag     = new MacroTag();
                        XmlNodeReader xReader = new XmlNodeReader(xTag);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement() && !xReader.IsEmptyElement)
                            {
                                switch (xReader.Name)
                                {
                                case TAG_NAME:
                                    xReader.Read();
                                    tag.Name = xReader.Value;

                                    if (!tag.Name.StartsWith("%"))
                                    {
                                        tag.Name = "%" + tag.Name;
                                    }

                                    if (!tag.Name.EndsWith("%"))
                                    {
                                        tag.Name += "%";
                                    }

                                    break;

                                case TAG_DESCRIPTION:
                                    xReader.Read();
                                    tag.Description = xReader.Value;
                                    break;

                                case TAG_NOTES:
                                    xReader.Read();
                                    tag.Notes = xReader.Value;
                                    break;

                                case TAG_TYPE:
                                    xReader.Read();

                                    string value = xReader.Value;

                                    // Change the data for each Tag that's being loaded if we've detected that
                                    // the XML document is from an older version of the application.
                                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                                    {
                                        Log.WriteDebugMessage("An old version of the tags.xml file was detected. Attempting upgrade to new schema.");

                                        Version v2300         = Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, Settings.CODEVERSION_BOOMBAYAH);
                                        Version v2326         = Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, "2.3.2.6");
                                        Version configVersion = Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                                        if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                                        {
                                            Log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                            // Starting with 2.3.0.0 the DateTimeFormatFunction type became the DateTimeFormatExpression type.
                                            value = value.Replace("DateTimeFormatFunction", "DateTimeFormatExpression");
                                        }

                                        if (v2326 != null && configVersion != null && configVersion.VersionNumber < v2326.VersionNumber)
                                        {
                                            Log.WriteDebugMessage("Boombayah 2.3.2.5 or older detected");

                                            // Starting with 2.3.2.6 the TimeOfDay type became the TimeRange type.
                                            value = value.Replace("TimeOfDay", "TimeRange");
                                        }
                                    }

                                    tag.Type = (MacroTagType)Enum.Parse(typeof(MacroTagType), value);
                                    break;

                                case TAG_DATETIME_FORMAT_VALUE:
                                    xReader.Read();
                                    tag.DateTimeFormatValue = xReader.Value;
                                    break;

                                case TAG_TIMERANGE_MACRO1_START:
                                case TAG_TIME_OF_DAY_MORNING_START:
                                    xReader.Read();
                                    tag.TimeRangeMacro1Start = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO1_END:
                                case TAG_TIME_OF_DAY_MORNING_END:
                                    xReader.Read();
                                    tag.TimeRangeMacro1End = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO2_START:
                                case TAG_TIME_OF_DAY_AFTERNOON_START:
                                    xReader.Read();
                                    tag.TimeRangeMacro2Start = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO2_END:
                                case TAG_TIME_OF_DAY_AFTERNOON_END:
                                    xReader.Read();
                                    tag.TimeRangeMacro2End = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO3_START:
                                case TAG_TIME_OF_DAY_EVENING_START:
                                    xReader.Read();
                                    tag.TimeRangeMacro3Start = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO3_END:
                                case TAG_TIME_OF_DAY_EVENING_END:
                                    xReader.Read();
                                    tag.TimeRangeMacro3End = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO4_START:
                                    xReader.Read();
                                    tag.TimeRangeMacro4Start = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO4_END:
                                    xReader.Read();
                                    tag.TimeRangeMacro4End = Convert.ToDateTime(xReader.Value);
                                    break;

                                case TAG_TIMERANGE_MACRO1_MACRO:
                                case TAG_TIME_OF_DAY_MORNING_VALUE:
                                    xReader.Read();
                                    tag.TimeRangeMacro1Macro = xReader.Value;
                                    break;

                                case TAG_TIMERANGE_MACRO2_MACRO:
                                case TAG_TIME_OF_DAY_AFTERNOON_VALUE:
                                    xReader.Read();
                                    tag.TimeRangeMacro2Macro = xReader.Value;
                                    break;

                                case TAG_TIMERANGE_MACRO3_MACRO:
                                case TAG_TIME_OF_DAY_EVENING_VALUE:
                                    xReader.Read();
                                    tag.TimeRangeMacro3Macro = xReader.Value;
                                    break;

                                case TAG_TIMERANGE_MACRO4_MACRO:
                                    xReader.Read();
                                    tag.TimeRangeMacro4Macro = xReader.Value;
                                    break;

                                case TAG_TIME_OF_DAY_EVENING_EXTENDS_TO_NEXT_MORNING:
                                    xReader.Read();
                                    eveningExtendsToNextMorning = Convert.ToBoolean(xReader.Value);
                                    break;

                                case TAG_ACTIVE:
                                    xReader.Read();
                                    tag.Active = Convert.ToBoolean(xReader.Value);
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        // Change the data for each Tag that's being loaded if we've detected that
                        // the XML document is from an older version of the application.
                        if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                        {
                            Log.WriteDebugMessage("An old version of the tags.xml file was detected. Attempting upgrade to new schema.");

                            Version v2300         = Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, Settings.CODEVERSION_BOOMBAYAH);
                            Version v2326         = Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, "2.3.2.6");
                            Version configVersion = Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                            if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                            {
                                Log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                // This is a new property for Tag that was introduced in 2.3.0.0
                                // so any version before 2.3.0.0 needs to have it during an upgrade.
                                tag.Active = true;

                                // "Description" is a new property for Tag that was introduced in 2.3.0.0
                                switch (tag.Type)
                                {
                                case MacroTagType.ActiveWindowTitle:
                                    tag.Description = "The title of the active window";
                                    break;

                                case MacroTagType.DateTimeFormat:
                                    tag.Description = "A value representing either a date, a time, or a combination of the date and time (" + tag.Name + ")";
                                    break;

                                case MacroTagType.ImageFormat:
                                    tag.Description = "The image format of the screenshot (such as jpeg or png)";
                                    break;

                                case MacroTagType.ScreenCaptureCycleCount:
                                    tag.Description = "The number of capture cycles during a screen capture session";
                                    break;

                                case MacroTagType.ScreenName:
                                    tag.Description = "The name of the screen or region";
                                    break;

                                case MacroTagType.ScreenNumber:
                                    tag.Description = "The screen number. For example, the first display is screen number 1";
                                    break;

                                case MacroTagType.User:
                                    tag.Description = "The name of the user (" + tag.Name + ")";
                                    break;

                                case MacroTagType.Machine:
                                    tag.Description = "The name of the computer (" + tag.Name + ")";
                                    break;

                                case MacroTagType.TimeRange:
                                    tag.Description = "The macro to use for a specific time range";
                                    break;

                                case MacroTagType.DateTimeFormatExpression:
                                    tag.Description = "An expression which represents a time that is either ahead or behind the current time (" + tag.Name + ")";
                                    break;
                                }
                            }

                            if (v2326 != null && configVersion != null && configVersion.VersionNumber < v2326.VersionNumber)
                            {
                                tag.TimeRangeMacro4Start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                                tag.TimeRangeMacro4End   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                                tag.TimeRangeMacro4Macro = string.Empty;

                                // This is an old property from before 2.3.2.6 when TimeOfDay macro tags were used.
                                // Since 2.3.2.6 we now use TimeRange tags so we need to split up the "evening" start and end times
                                // into their own "Macro 4" start and end times when this property is set to true.
                                if (eveningExtendsToNextMorning)
                                {
                                    tag.TimeRangeMacro4Start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                                    tag.TimeRangeMacro4End   = tag.TimeRangeMacro3End;

                                    tag.TimeRangeMacro3End = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);

                                    tag.TimeRangeMacro4Macro = tag.TimeRangeMacro3Macro;
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(tag.Name))
                        {
                            Add(tag);
                        }
                    }

                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                    {
                        Log.WriteDebugMessage("Tags file detected as an old version");
                        SaveToXmlFile();
                    }
                }
                else
                {
                    Log.WriteDebugMessage("WARNING: Unable to load tags");

                    // Setup a few "built in" tags by default.
                    Add(new MacroTag("name", "The name of the screen or region", MacroTagType.ScreenName, active: true));
                    Add(new MacroTag("screen", "The screen number. For example, the first display is screen 1 and the second display is screen 2", MacroTagType.ScreenNumber, active: true));
                    Add(new MacroTag("format", "The image format such as jpeg or png", MacroTagType.ImageFormat, active: true));
                    Add(new MacroTag("date", "The current date (%date%)", MacroTagType.DateTimeFormat, MacroParser.DateFormat, active: true));
                    Add(new MacroTag("time", "The current time (%time%)", MacroTagType.DateTimeFormat, MacroParser.TimeFormatForWindows, active: true));
                    Add(new MacroTag("year", "The current year (%year%)", MacroTagType.DateTimeFormat, MacroParser.YearFormat, active: true));
                    Add(new MacroTag("month", "The current month (%month%)", MacroTagType.DateTimeFormat, MacroParser.MonthFormat, active: true));
                    Add(new MacroTag("day", "The current day (%day%)", MacroTagType.DateTimeFormat, MacroParser.DayFormat, active: true));
                    Add(new MacroTag("hour", "The current hour (%hour%)", MacroTagType.DateTimeFormat, MacroParser.HourFormat, active: true));
                    Add(new MacroTag("minute", "The current minute (%minute%)", MacroTagType.DateTimeFormat, MacroParser.MinuteFormat, active: true));
                    Add(new MacroTag("second", "The current second (%second%)", MacroTagType.DateTimeFormat, MacroParser.SecondFormat, active: true));
                    Add(new MacroTag("millisecond", "The current millisecond (%millisecond%)", MacroTagType.DateTimeFormat, MacroParser.MillisecondFormat, active: true));
                    Add(new MacroTag("lastyear", "The previous year (%lastyear%)", MacroTagType.DateTimeFormatExpression, "{year-1}", active: true));
                    Add(new MacroTag("lastmonth", "The previous month (%lastmonth%)", MacroTagType.DateTimeFormatExpression, "{month-1}", active: true));
                    Add(new MacroTag("yesterday", "The previous day (%yesterday%)", MacroTagType.DateTimeFormatExpression, "{day-1}[yyyy-MM-dd]", active: true));
                    Add(new MacroTag("tomorrow", "The next day (%tomorrow%)", MacroTagType.DateTimeFormatExpression, "{day+1}[yyyy-MM-dd]", active: true));
                    Add(new MacroTag("6hoursbehind", "Six hours behind the current hour (%6hoursbehind%)", MacroTagType.DateTimeFormatExpression, "{hour-6}[yyyy-MM-dd_HH-mm-ss.fff]", active: true));
                    Add(new MacroTag("6hoursahead", "Six hours ahead the current hour (%6hoursahead%)", MacroTagType.DateTimeFormatExpression, "{hour+6}[yyyy-MM-dd_HH-mm-ss.fff]", active: true));
                    Add(new MacroTag("count", "The number of capture cycles during a running screen capture session. For example, the first round of screenshots taken is the first cycle count or count 1", MacroTagType.ScreenCaptureCycleCount, active: true));
                    Add(new MacroTag("user", "The user using this computer (%user%)", MacroTagType.User, active: true));
                    Add(new MacroTag("machine", "The name of the computer (%machine%)", MacroTagType.Machine, active: true));
                    Add(new MacroTag("title", "The title of the active window", MacroTagType.ActiveWindowTitle, active: true));
                    Add(new MacroTag("timerange", "The macro to use during a specific time range. At the moment it is %timerange%", MacroTagType.TimeRange, active: true));
                    Add(new MacroTag("quarteryear", "A number representing the current quarter of the current year (%quarteryear%)", MacroTagType.QuarterYear, active: true));

                    SaveToXmlFile();
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("TagCollection::LoadXmlFileAndAddTags", ex);

                return(false);
            }
        }
Exemple #12
0
        /// <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>
        /// 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>
        /// The timer used for checking help tips, monitoring externally-issued commands, running Schedules, and displaying capture information.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerScheduledCapture_Tick(object sender, EventArgs e)
        {
            try
            {
                DateTime dtNow = DateTime.Now;

                // Display help tip message from any class that isn't part of FormMain.
                if (!string.IsNullOrEmpty(HelpTip.Message))
                {
                    RestartHelpTipTimer();

                    HelpMessage(HelpTip.Message);
                    HelpTip.Message = string.Empty;
                }

                // Parse commands issued externally via the command line.
                if (FileSystem.FileExists(FileSystem.CommandFile))
                {
                    string[] args = FileSystem.ReadFromFile(FileSystem.CommandFile);

                    if (args.Length > 0)
                    {
                        ParseCommandLineArguments(args);
                    }
                }
                else
                {
                    FileSystem.CreateFile(FileSystem.CommandFile);
                }

                // Displays the next time screenshots are going to be captured in the system tray icon's tool tip.
                ShowInfo();

                // Process the list of schedules we need to consider.
                foreach (Schedule schedule in _formSchedule.ScheduleCollection)
                {
                    if ((dtNow.DayOfWeek == DayOfWeek.Monday && schedule.Monday) ||
                        (dtNow.DayOfWeek == DayOfWeek.Tuesday && schedule.Tuesday) ||
                        (dtNow.DayOfWeek == DayOfWeek.Wednesday && schedule.Wednesday) ||
                        (dtNow.DayOfWeek == DayOfWeek.Thursday && schedule.Thursday) ||
                        (dtNow.DayOfWeek == DayOfWeek.Friday && schedule.Friday) ||
                        (dtNow.DayOfWeek == DayOfWeek.Saturday && schedule.Saturday) ||
                        (dtNow.DayOfWeek == DayOfWeek.Sunday && schedule.Sunday))
                    {
                        if (schedule.ModeOneTime)
                        {
                            if ((dtNow.Hour == schedule.CaptureAt.Hour) &&
                                (dtNow.Minute == schedule.CaptureAt.Minute) &&
                                (dtNow.Second == schedule.CaptureAt.Second))
                            {
                                TakeScreenshot(captureNow: true);
                            }
                        }

                        if (schedule.ModePeriod)
                        {
                            if ((dtNow.Hour == schedule.StartAt.Hour) &&
                                (dtNow.Minute == schedule.StartAt.Minute) &&
                                (dtNow.Second == schedule.StartAt.Second))
                            {
                                StartScreenCapture();
                            }

                            if ((dtNow.Hour == schedule.StopAt.Hour) &&
                                (dtNow.Minute == schedule.StopAt.Minute) &&
                                (dtNow.Second == schedule.StopAt.Second))
                            {
                                StopScreenCapture();
                            }
                        }
                    }
                }

                // Process the list of triggers of condition type Date/Time and condition type Time.
                foreach (Trigger trigger in _formTrigger.TriggerCollection)
                {
                    if (trigger.ConditionType == TriggerConditionType.DateTime &&
                        trigger.Date.ToString(MacroParser.DateFormat).Equals(dtNow.ToString(MacroParser.DateFormat)) &&
                        trigger.Time.ToString(MacroParser.TimeFormatForTrigger).Equals(dtNow.ToString(MacroParser.TimeFormatForTrigger)))
                    {
                        DoTriggerAction(trigger);
                    }

                    if (trigger.ConditionType == TriggerConditionType.Time &&
                        trigger.Time.ToString(MacroParser.TimeFormatForTrigger).Equals(dtNow.ToString(MacroParser.TimeFormatForTrigger)))
                    {
                        DoTriggerAction(trigger);
                    }
                }
            }
            catch (Exception ex)
            {
                _screenCapture.ApplicationError = true;
                Log.WriteExceptionMessage("FormMain-Schedules::timerScheduledCapture_Tick", ex);
            }
        }
Exemple #15
0
        private void ShowScreenshotBySlideIndex()
        {
            textBoxLabel.Text            = string.Empty;
            textBoxScreenshotTitle.Text  = string.Empty;
            textBoxScreenshotFormat.Text = string.Empty;
            textBoxScreenshotWidth.Text  = string.Empty;
            textBoxScreenshotHeight.Text = string.Empty;
            textBoxScreenshotDate.Text   = string.Empty;
            textBoxScreenshotTime.Text   = string.Empty;

            if (tabControlViews.TabCount > 0 && tabControlViews.SelectedTab != null)
            {
                TabPage selectedTabPage = tabControlViews.SelectedTab;

                ToolStrip toolStrip = (ToolStrip)selectedTabPage.Controls[selectedTabPage.Name + "toolStrip"];

                ToolStripTextBox toolStripTextBox = (ToolStripTextBox)toolStrip.Items[selectedTabPage.Name + "toolStripTextBoxFilename"];

                PictureBox pictureBox = (PictureBox)selectedTabPage.Controls[selectedTabPage.Name + "pictureBox"];

                Screenshot selectedScreenshot = new Screenshot();

                if (Slideshow.Index >= 0 && Slideshow.Index <= (Slideshow.Count - 1))
                {
                    Slideshow.SelectedSlide = (Slide)listBoxScreenshots.Items[Slideshow.Index];

                    if (selectedTabPage.Tag.GetType() == typeof(Screen))
                    {
                        Screen screen = (Screen)selectedTabPage.Tag;
                        selectedScreenshot = _screenshotCollection.GetScreenshot(Slideshow.SelectedSlide.Name, screen.ViewId);
                    }

                    if (selectedTabPage.Tag.GetType() == typeof(Region))
                    {
                        Region region = (Region)selectedTabPage.Tag;
                        selectedScreenshot = _screenshotCollection.GetScreenshot(Slideshow.SelectedSlide.Name, region.ViewId);
                    }
                }

                string path = selectedScreenshot.Path;

                if (!string.IsNullOrEmpty(path))
                {
                    toolStripTextBox.Text        = FileSystem.GetFileName(path);
                    toolStripTextBox.ToolTipText = path;

                    string dirName = FileSystem.GetDirectoryName(path);

                    if (!string.IsNullOrEmpty(dirName))
                    {
                        if (FileSystem.DirectoryExists(dirName) && FileSystem.FileExists(path))
                        {
                            toolStripTextBox.BackColor = Color.PaleGreen;
                        }
                        else
                        {
                            toolStripTextBox.BackColor   = Color.PaleVioletRed;
                            toolStripTextBox.ToolTipText = $"Could not find or access image file at path \"{path}\"";
                        }
                    }

                    pictureBox.Image = _screenCapture.GetImageByPath(path);

                    if (pictureBox.Image != null)
                    {
                        textBoxLabel.Text            = selectedScreenshot.Label;
                        textBoxScreenshotTitle.Text  = selectedScreenshot.WindowTitle;
                        textBoxScreenshotFormat.Text = selectedScreenshot.Format.Name;

                        textBoxScreenshotWidth.Text  = pictureBox.Image.Width.ToString();
                        textBoxScreenshotHeight.Text = pictureBox.Image.Height.ToString();

                        textBoxScreenshotDate.Text = selectedScreenshot.Date;
                        textBoxScreenshotTime.Text = selectedScreenshot.Time;
                    }
                }
                else
                {
                    toolStripTextBox.Text        = string.Empty;
                    toolStripTextBox.BackColor   = Color.LightYellow;
                    toolStripTextBox.ToolTipText = string.Empty;

                    pictureBox.Image = null;
                }
            }
        }
Exemple #16
0
        /// <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();
            }
        }
Exemple #17
0
        /// <summary>
        /// Loads screenshot references from the screenshots.xml file into an XmlDocument so it's available in memory.
        /// The old way of loading screenshots also had the application construct each Screenshot object from an XML screenshot node and add it to the collection. This would take a long time to load for a large screenshots.xml file.
        /// The new way (as of version 2.3.0.0) will only load XML screenshot nodes whenever necessary.
        /// </summary>
        public void LoadXmlFile()
        {
            try
            {
                _mutexWriteFile.WaitOne();

                if (_screenshotList != null && !FileSystem.FileExists(FileSystem.ScreenshotsFile))
                {
                    Log.WriteMessage("Could not find \"" + FileSystem.ScreenshotsFile + "\" so creating default version");

                    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
                    };

                    using (XmlWriter xWriter = XmlWriter.Create(FileSystem.ScreenshotsFile, 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_SCREENSHOTS_NODE);

                        xWriter.WriteEndElement();
                        xWriter.WriteEndElement();
                        xWriter.WriteEndDocument();

                        xWriter.Flush();
                        xWriter.Close();
                    }

                    Log.WriteMessage("Created \"" + FileSystem.ScreenshotsFile + "\"");
                }

                if (FileSystem.FileExists(FileSystem.ScreenshotsFile))
                {
                    Log.WriteDebugMessage("Screenshots file \"" + FileSystem.ScreenshotsFile + "\" found. Attempting to load XML document");

                    xDoc = new XmlDocument();

                    lock (xDoc)
                    {
                        xDoc.Load(FileSystem.ScreenshotsFile);

                        Log.WriteDebugMessage("XML document loaded");
                    }
                }
                else
                {
                    Log.WriteDebugMessage("WARNING: Unable to load screenshots");
                }
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("ScreenshotCollection::LoadXmlFile", ex);
            }
            finally
            {
                _mutexWriteFile.ReleaseMutex();
            }
        }
Exemple #18
0
        /// <summary>
        /// Loads the configuration file.
        /// </summary>
        public void Load(FileSystem fileSystem)
        {
            try
            {
                FileSystem = fileSystem;

                Settings    = new Settings();
                MacroParser = new MacroParser(Settings);

                string configDirectory = FileSystem.GetDirectoryName(FileSystem.ConfigFile);

                if (!string.IsNullOrEmpty(configDirectory) && !FileSystem.DirectoryExists(configDirectory))
                {
                    FileSystem.CreateDirectory(configDirectory);
                }

                if (!FileSystem.FileExists(FileSystem.ConfigFile))
                {
                    string[] linesToWrite =
                    {
                        "# Auto Screen Capture Configuration File",
                        "# Use this file to tell the application what folders and files it should utilize.",
                        "# Each key-value pair can be the name of a folder or file or a path to a folder or file.",
                        "# If only the folder name is given then it will be parsed as the sub-folder of the folder",
                        "# where the executed autoscreen.exe binary is located.",                                                   "",
                        "# This is the folder where screenshots will be stored by default.",
                        "ScreenshotsFolder=" + FileSystem.DefaultScreenshotsFolder,                                                 "",
                        "# If any errors are encountered then you will find them in this folder when DebugMode is enabled.",
                        "DebugFolder=" + FileSystem.DefaultDebugFolder,                                                             "",
                        "# Logs are stored in this folder when either Logging or DebugMode is enabled.",
                        "LogsFolder=" + FileSystem.DefaultLogsFolder,                                                               "",
                        "# This file is monitored by the application for commands issued from the command line while it's running.",
                        "CommandFile=" + FileSystem.DefaultCommandFile,                                                             "",
                        "# The application settings (such as DebugMode).",
                        "ApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile,                                     "",
                        "# Your personal settings.",
                        "UserSettingsFile=" + FileSystem.DefaultUserSettingsFile,                                                   "",
                        "# SMTP settings for emailing screenshots using an email server.",
                        "SMTPSettingsFile=" + FileSystem.DefaultSmtpSettingsFile,                                                   "",
                        "# SFTP settings for uploading screenshots to a file server.",
                        "SFTPSettingsFile=" + FileSystem.DefaultSftpSettingsFile,                                                   "",
                        "# References to image editors.",
                        "EditorsFile=" + FileSystem.DefaultEditorsFile,                                                             "",
                        "# References to regions.",
                        "RegionsFile=" + FileSystem.DefaultRegionsFile,                                                             "",
                        "# References to screens.",
                        "ScreensFile=" + FileSystem.DefaultScreensFile,                                                             "",
                        "# References to triggers.",
                        "TriggersFile=" + FileSystem.DefaultTriggersFile,                                                           "",
                        "# References to screenshots.",
                        "ScreenshotsFile=" + FileSystem.DefaultScreenshotsFile,                                                     "",
                        "# References to tags.",
                        "TagsFile=" + FileSystem.DefaultTagsFile,                                                                   "",
                        "# References to schedules.",
                        "SchedulesFile=" + FileSystem.DefaultSchedulesFile,                                                         ""
                    };

                    FileSystem.WriteToFile(FileSystem.ConfigFile, linesToWrite);
                }

                foreach (string line in FileSystem.ReadFromFile(FileSystem.ConfigFile))
                {
                    if (string.IsNullOrEmpty(line) || line.StartsWith("#"))
                    {
                        continue;
                    }

                    string path;

                    if (GetPathAndCreateIfNotFound(line, REGEX_SCREENSHOTS_FOLDER, out path))
                    {
                        FileSystem.ScreenshotsFolder = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_DEBUG_FOLDER, out path))
                    {
                        FileSystem.DebugFolder = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_LOGS_FOLDER, out path))
                    {
                        FileSystem.LogsFolder = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_COMMAND_FILE, out path))
                    {
                        FileSystem.CommandFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_APPLICATION_SETTINGS_FILE, out path))
                    {
                        FileSystem.ApplicationSettingsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_SMTP_SETTINGS_FILE, out path))
                    {
                        FileSystem.SmtpSettingsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_SFTP_SETTINGS_FILE, out path))
                    {
                        FileSystem.SftpSettingsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_USER_SETTINGS_FILE, out path))
                    {
                        FileSystem.UserSettingsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_EDITORS_FILE, out path))
                    {
                        FileSystem.EditorsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_REGIONS_FILE, out path))
                    {
                        FileSystem.RegionsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_SCREENS_FILE, out path))
                    {
                        FileSystem.ScreensFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_TRIGGERS_FILE, out path))
                    {
                        FileSystem.TriggersFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_SCREENSHOTS_FILE, out path))
                    {
                        FileSystem.ScreenshotsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_TAGS_FILE, out path))
                    {
                        FileSystem.TagsFile = path;
                    }

                    if (GetPathAndCreateIfNotFound(line, REGEX_SCHEDULES_FILE, out path))
                    {
                        FileSystem.SchedulesFile = path;
                    }
                }

                CheckAndCreateFolders();

                Settings.Load(FileSystem);
                Log           = new Log(Settings, FileSystem, MacroParser);
                ScreenCapture = new ScreenCapture(this, MacroParser, FileSystem, Log);

                Security security = new Security();
                CheckAndCreateFiles(security, ScreenCapture, Log);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("Config::Load", ex);
            }
        }
Exemple #19
0
        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);
            }
        }
Exemple #20
0
        private ToolStrip BuildViewTabPageToolStripItems(ToolStrip toolStrip, string name)
        {
            ToolStripSplitButton toolStripSplitButtonEdit = new ToolStripSplitButton
            {
                Text        = "Edit",
                Alignment   = ToolStripItemAlignment.Left,
                AutoToolTip = false,
                Image       = Resources.edit
            };

            ToolStripButton toolStripButtonEmail = new ToolStripButton
            {
                Text        = "Email",
                Alignment   = ToolStripItemAlignment.Left,
                AutoToolTip = false,
                Image       = Resources.email
            };

            toolStripButtonEmail.Click += new EventHandler(emailScreenshot_Click);

            // Check to see if Email (SMTP) is configured.
            string host = Settings.Application.GetByKey("EmailServerHost", DefaultSettings.EmailServerHost).Value.ToString();

            string username = Settings.Application.GetByKey("EmailClientUsername", DefaultSettings.EmailClientUsername).Value.ToString();
            string password = Settings.Application.GetByKey("EmailClientPassword", DefaultSettings.EmailClientPassword).Value.ToString();

            string from = Settings.Application.GetByKey("EmailMessageFrom", DefaultSettings.EmailMessageFrom).Value.ToString();
            string to   = Settings.Application.GetByKey("EmailMessageTo", DefaultSettings.EmailMessageTo).Value.ToString();

            if (string.IsNullOrEmpty(host) ||
                string.IsNullOrEmpty(username) ||
                string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(@from) ||
                string.IsNullOrEmpty(to))
            {
                toolStripButtonEmail.ToolTipText = "SMTP settings have not been configured for " + Settings.ApplicationName + " to email screenshots";
                toolStripButtonEmail.Enabled     = false;
            }
            else
            {
                toolStripButtonEmail.ToolTipText = "Email this screenshot using the configured SMTP settings";
                toolStripButtonEmail.Enabled     = true;
            }

            toolStripSplitButtonEdit.DropDown.Items.Add("Add New Editor ...", null, addEditor_Click);

            foreach (Editor editor in _formEditor.EditorCollection)
            {
                if (editor != null && FileSystem.FileExists(editor.Application))
                {
                    toolStripSplitButtonEdit.DropDown.Items.Add(editor.Name, Icon.ExtractAssociatedIcon(editor.Application).ToBitmap(), runEditor_Click);
                }
            }

            ToolStripSplitButton toolStripSplitButtonConfigure = new ToolStripSplitButton
            {
                Text        = "Configure",
                Alignment   = ToolStripItemAlignment.Right,
                AutoToolTip = false,
                Image       = Resources.configure
            };

            toolStripSplitButtonConfigure.DropDown.Items.Add("Add New Screen", null, addScreen_Click);
            toolStripSplitButtonConfigure.DropDown.Items.Add("Add New Region", null, addRegion_Click);

            toolStripSplitButtonConfigure.DropDown.Items.Add(new ToolStripSeparator());

            if (toolStrip.Tag is Screen)
            {
                ToolStripMenuItem toolStripMenuItemChangeScreen = new ToolStripMenuItem
                {
                    Text = "Change Screen",
                    Tag  = toolStrip.Tag
                };

                toolStripMenuItemChangeScreen.Click += new EventHandler(changeScreen_Click);

                toolStripSplitButtonConfigure.DropDown.Items.Add(toolStripMenuItemChangeScreen);

                ToolStripMenuItem toolStripMenuItemRemoveScreen = new ToolStripMenuItem
                {
                    Text = "Remove Screen",
                    Tag  = toolStrip.Tag
                };

                toolStripMenuItemRemoveScreen.Click += new EventHandler(removeScreen_Click);

                toolStripSplitButtonConfigure.DropDown.Items.Add(toolStripMenuItemRemoveScreen);
            }

            if (toolStrip.Tag is Region)
            {
                ToolStripMenuItem toolStripMenuItemRegion = new ToolStripMenuItem
                {
                    Text = "Change Region",
                    Tag  = toolStrip.Tag
                };

                toolStripMenuItemRegion.Click += new EventHandler(changeRegion_Click);

                toolStripSplitButtonConfigure.DropDown.Items.Add(toolStripMenuItemRegion);

                ToolStripMenuItem toolStripMenuItemRemoveRegion = new ToolStripMenuItem
                {
                    Text = "Remove Region",
                    Tag  = toolStrip.Tag
                };

                toolStripMenuItemRemoveRegion.Click += new EventHandler(removeRegion_Click);

                toolStripSplitButtonConfigure.DropDown.Items.Add(toolStripMenuItemRemoveRegion);
            }

            ToolStripItem toolStripLabelFilename = new ToolStripLabel
            {
                Text      = "Filename:",
                Alignment = ToolStripItemAlignment.Right,
                Anchor    = AnchorStyles.Top | AnchorStyles.Left
            };

            ToolStripItem toolstripTextBoxFilename = new ToolStripTextBox
            {
                Name      = name + "toolStripTextBoxFilename",
                Alignment = ToolStripItemAlignment.Right,
                AutoSize  = false,
                ReadOnly  = true,
                Width     = 200,
                BackColor = Color.LightYellow,
                Text      = string.Empty
            };

            ToolStripItem toolstripButtonOpenFolder = new ToolStripButton
            {
                Image        = Resources.openfolder,
                Alignment    = ToolStripItemAlignment.Right,
                AutoToolTip  = false,
                ToolTipText  = "Show Screenshot Location",
                DisplayStyle = ToolStripItemDisplayStyle.Image
            };

            toolstripButtonOpenFolder.Click += new EventHandler(showScreenshotLocation_Click);

            toolStrip.Items.Add(toolStripSplitButtonEdit);
            toolStrip.Items.Add(toolStripButtonEmail);
            toolStrip.Items.Add(toolStripSplitButtonConfigure);
            toolStrip.Items.Add(new ToolStripSeparator {
                Alignment = ToolStripItemAlignment.Right
            });
            toolStrip.Items.Add(toolstripButtonOpenFolder);
            toolStrip.Items.Add(toolstripTextBoxFilename);
            toolStrip.Items.Add(toolStripLabelFilename);
            toolStrip.Items.Add(new ToolStripSeparator {
                Alignment = ToolStripItemAlignment.Right
            });

            return(toolStrip);
        }
Exemple #21
0
        /// <summary>
        /// Populates the list of editors, screens, regions, schedules, macro tags, or triggers (depending on what type of module has been selected).
        /// </summary>
        private void LoadModuleItems()
        {
            listBoxModuleItemList.Items.Clear();

            if (listBoxAction.SelectedIndex == (int)TriggerActionType.RunEditor)
            {
                foreach (Editor editor in EditorCollection)
                {
                    if (editor != null && _fileSystem.FileExists(editor.Application))
                    {
                        listBoxModuleItemList.Items.Add(editor.Name);
                    }
                }
            }

            if (listBoxAction.SelectedIndex == (int)TriggerActionType.EnableScreen ||
                listBoxAction.SelectedIndex == (int)TriggerActionType.DisableScreen)
            {
                foreach (Screen screen in ScreenCollection)
                {
                    if (screen != null)
                    {
                        listBoxModuleItemList.Items.Add(screen.Name);
                    }
                }
            }

            if (listBoxAction.SelectedIndex == (int)TriggerActionType.EnableRegion ||
                listBoxAction.SelectedIndex == (int)TriggerActionType.DisableRegion)
            {
                foreach (Region region in RegionCollection)
                {
                    if (region != null)
                    {
                        listBoxModuleItemList.Items.Add(region.Name);
                    }
                }
            }

            if (listBoxAction.SelectedIndex == (int)TriggerActionType.EnableSchedule ||
                listBoxAction.SelectedIndex == (int)TriggerActionType.DisableSchedule)
            {
                foreach (Schedule schedule in ScheduleCollection)
                {
                    if (schedule != null)
                    {
                        listBoxModuleItemList.Items.Add(schedule.Name);
                    }
                }
            }

            if (listBoxAction.SelectedIndex == (int)TriggerActionType.EnableMacroTag ||
                listBoxAction.SelectedIndex == (int)TriggerActionType.DisableMacroTag)
            {
                foreach (MacroTag tag in MacroTagCollection)
                {
                    if (tag != null)
                    {
                        listBoxModuleItemList.Items.Add(tag.Name);
                    }
                }
            }

            if (listBoxAction.SelectedIndex == (int)TriggerActionType.EnableTrigger ||
                listBoxAction.SelectedIndex == (int)TriggerActionType.DisableTrigger)
            {
                foreach (Trigger trigger in TriggerCollection)
                {
                    if (trigger != null)
                    {
                        listBoxModuleItemList.Items.Add(trigger.Name);
                    }
                }
            }

            if (listBoxModuleItemList.Items.Count > 0)
            {
                listBoxModuleItemList.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// Loads the regions.
        /// </summary>
        public void LoadXmlFileAndAddRegions(ImageFormatCollection imageFormatCollection)
        {
            try
            {
                Log.WriteDebugMessage(":: LoadXmlFileAndAddRegions Start ::");

                if (FileSystem.FileExists(FileSystem.RegionsFile))
                {
                    Log.WriteDebugMessage("Regions file \"" + FileSystem.RegionsFile + "\" found. Attempting to load XML document");

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(FileSystem.RegionsFile);

                    Log.WriteDebugMessage("XML document loaded");

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xRegions = xDoc.SelectNodes(REGION_XPATH);

                    foreach (XmlNode xRegion in xRegions)
                    {
                        Region        region  = new Region();
                        XmlNodeReader xReader = new XmlNodeReader(xRegion);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement() && !xReader.IsEmptyElement)
                            {
                                switch (xReader.Name)
                                {
                                case REGION_VIEWID:
                                    xReader.Read();
                                    region.ViewId = Guid.Parse(xReader.Value);
                                    break;

                                case REGION_NAME:
                                    xReader.Read();
                                    region.Name = xReader.Value;
                                    break;

                                case REGION_FOLDER:
                                    xReader.Read();
                                    region.Folder = xReader.Value;
                                    break;

                                case REGION_MACRO:
                                    xReader.Read();
                                    region.Macro = xReader.Value;
                                    break;

                                case REGION_FORMAT:
                                    xReader.Read();
                                    region.Format = imageFormatCollection.GetByName(xReader.Value);
                                    break;

                                case REGION_JPEG_QUALITY:
                                    xReader.Read();
                                    region.JpegQuality = Convert.ToInt32(xReader.Value);
                                    break;

                                case REGION_RESOLUTION_RATIO:
                                    xReader.Read();
                                    region.ResolutionRatio = Convert.ToInt32(xReader.Value);
                                    break;

                                case REGION_MOUSE:
                                    xReader.Read();
                                    region.Mouse = Convert.ToBoolean(xReader.Value);
                                    break;

                                case REGION_X:
                                    xReader.Read();
                                    region.X = Convert.ToInt32(xReader.Value);
                                    break;

                                case REGION_Y:
                                    xReader.Read();
                                    region.Y = Convert.ToInt32(xReader.Value);
                                    break;

                                case REGION_WIDTH:
                                    xReader.Read();
                                    region.Width = Convert.ToInt32(xReader.Value);
                                    break;

                                case REGION_HEIGHT:
                                    xReader.Read();
                                    region.Height = Convert.ToInt32(xReader.Value);
                                    break;

                                case REGION_ACTIVE:
                                    xReader.Read();
                                    region.Active = Convert.ToBoolean(xReader.Value);
                                    break;

                                case REGION_ACTIVE_WINDOW_TITLE_CAPTURE_CHECK:
                                    xReader.Read();
                                    region.ActiveWindowTitleCaptureCheck = Convert.ToBoolean(xReader.Value);
                                    break;

                                case REGION_ACTIVE_WINDOW_TITLE_CAPTURE_TEXT:
                                    xReader.Read();
                                    region.ActiveWindowTitleCaptureText = xReader.Value;
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        // Change the data for each region that's being loaded if we've detected that
                        // the XML document is from an older version of the application.
                        if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                        {
                            Log.WriteDebugMessage("An old version of the regions file was detected. Attempting upgrade to new region schema");

                            Version v2182         = Settings.VersionManager.Versions.Get("Clara", "2.1.8.2");
                            Version v2300         = Settings.VersionManager.Versions.Get("Boombayah", "2.3.0.0");
                            Version configVersion = Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                            if (v2182 != null && string.IsNullOrEmpty(AppCodename) && string.IsNullOrEmpty(AppVersion))
                            {
                                Log.WriteDebugMessage("Clara 2.1.8.2 or older detected");

                                region.ViewId = Guid.NewGuid();

                                // Get the screenshots folder path from the old user settings to be used for the region's folder property.
                                region.Folder = Settings.VersionManager.OldUserSettings.GetByKey("ScreenshotsDirectory", FileSystem.ScreenshotsFolder).Value.ToString();

                                region.Folder = FileSystem.CorrectScreenshotsFolderPath(region.Folder);

                                // 2.1 used "%region%", but 2.2 uses "%name%" for a region's Macro value.
                                region.Macro = region.Macro.Replace("%region%", "%name%");

                                region.Format          = imageFormatCollection.GetByName(ImageFormatSpec.NAME_JPEG);
                                region.JpegQuality     = 100;
                                region.ResolutionRatio = 100;
                                region.Mouse           = true;
                                region.Active          = true;
                            }

                            if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                            {
                                Log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                // This is a new property for Screen that was introduced in 2.3.0.0
                                // so any version before 2.3.0.0 needs to have it during an upgrade.
                                region.Active = true;
                            }
                        }

                        if (!string.IsNullOrEmpty(region.Name))
                        {
                            Add(region);
                        }
                    }

                    // Write out the regions to the XML document now that we've updated the region objects
                    // with their appropriate property values if it was an old version of the application.
                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                    {
                        Log.WriteDebugMessage("Regions file detected as an old version");
                        SaveToXmlFile();
                    }
                }
                else
                {
                    Log.WriteDebugMessage($"WARNING: {FileSystem.RegionsFile} not found. Unable to load regions");

                    SaveToXmlFile();
                }

                Log.WriteDebugMessage(":: LoadXmlFileAndAddRegions End ::");
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("RegionCollection::Load", ex);
            }
        }
        /// <summary>
        /// Loads the settings.
        /// </summary>
        public void Load()
        {
            try
            {
                if (string.IsNullOrEmpty(Filepath))
                {
                    return;
                }

                if (FileSystem.FileExists(Filepath))
                {
                    // Check the size of the settings file.
                    // Delete the file if it's too big so we don't hang.
                    if (FileSystem.FileContentLength(Filepath) > MAX_FILE_SIZE)
                    {
                        FileSystem.DeleteFile(Filepath);

                        Log.WriteDebugMessage("WARNING: User settings file was too big and needed to be deleted");

                        return;
                    }

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(Filepath);

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xSettings = xDoc.SelectNodes(SETTING_XPATH);

                    foreach (XmlNode xSetting in xSettings)
                    {
                        Setting       setting = new Setting();
                        XmlNodeReader xReader = new XmlNodeReader(xSetting);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement())
                            {
                                switch (xReader.Name)
                                {
                                case SETTING_KEY:
                                    xReader.Read();
                                    setting.Key = xReader.Value;
                                    break;

                                case SETTING_VALUE:
                                    xReader.Read();
                                    setting.Value = xReader.Value;
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        if (!string.IsNullOrEmpty(setting.Key))
                        {
                            Add(setting);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("SettingCollection::Load", ex);
            }
        }
        /// <summary>
        /// Loads the image schedules from the schedules.xml file.
        /// </summary>
        public bool LoadXmlFileAndAddSchedules()
        {
            try
            {
                if (FileSystem.FileExists(FileSystem.SchedulesFile))
                {
                    Log.WriteDebugMessage("Schedules file \"" + FileSystem.SchedulesFile + "\" found. Attempting to load XML document");

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(FileSystem.SchedulesFile);

                    Log.WriteDebugMessage("XML document loaded");

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xSchedules = xDoc.SelectNodes(SCHEDULE_XPATH);

                    foreach (XmlNode xSchedule in xSchedules)
                    {
                        Schedule      schedule = new Schedule();
                        XmlNodeReader xReader  = new XmlNodeReader(xSchedule);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement() && !xReader.IsEmptyElement)
                            {
                                switch (xReader.Name)
                                {
                                case SCHEDULE_NAME:
                                    xReader.Read();
                                    schedule.Name = xReader.Value;
                                    break;

                                case SCHEDULE_ACTIVE:
                                    xReader.Read();
                                    schedule.Active = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_MODE_ONETIME:
                                    xReader.Read();
                                    schedule.ModeOneTime = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_MODE_PERIOD:
                                    xReader.Read();
                                    schedule.ModePeriod = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_CAPTUREAT:
                                    xReader.Read();
                                    schedule.CaptureAt = Convert.ToDateTime(xReader.Value);
                                    break;

                                case SCHEDULE_STARTAT:
                                    xReader.Read();
                                    schedule.StartAt = Convert.ToDateTime(xReader.Value);
                                    break;

                                case SCHEDULE_STOPAT:
                                    xReader.Read();
                                    schedule.StopAt = Convert.ToDateTime(xReader.Value);
                                    break;

                                case SCHEDULE_SCREEN_CAPTURE_INTERVAL:
                                    xReader.Read();
                                    schedule.ScreenCaptureInterval = Convert.ToInt32(xReader.Value);
                                    break;

                                case SCHEDULE_MONDAY:
                                    xReader.Read();
                                    schedule.Monday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_TUESDAY:
                                    xReader.Read();
                                    schedule.Tuesday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_WEDNESDAY:
                                    xReader.Read();
                                    schedule.Wednesday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_THURSDAY:
                                    xReader.Read();
                                    schedule.Thursday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_FRIDAY:
                                    xReader.Read();
                                    schedule.Friday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_SATURDAY:
                                    xReader.Read();
                                    schedule.Saturday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_SUNDAY:
                                    xReader.Read();
                                    schedule.Sunday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_NOTES:
                                    xReader.Read();
                                    schedule.Notes = xReader.Value;
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        // Change the data for each Schedule that's being loaded if we've detected that
                        // the XML document is from an older version of the application.
                        if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                        {
                            Log.WriteDebugMessage("An old version of the schedules.xml file was detected. Attempting upgrade to new schema.");

                            Version v2300         = Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, Settings.CODEVERSION_BOOMBAYAH);
                            Version v2319         = Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, "2.3.1.9");
                            Version configVersion = Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                            if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                            {
                                Log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                // This is a new property for Schedule that was introduced in 2.3.0.0
                                // so any version before 2.3.0.0 needs to have it during an upgrade.
                                schedule.Active = true;
                            }

                            if (v2319 != null && configVersion != null && configVersion.VersionNumber < v2319.VersionNumber)
                            {
                                Log.WriteDebugMessage("Boombayah 2.3.1.8 or older detected");

                                // A new property for Schedule introduced in 2.3.1.9
                                schedule.ScreenCaptureInterval = Convert.ToInt32(Settings.User.GetByKey("ScreenCaptureInterval", DefaultSettings.ScreenCaptureInterval).Value);
                            }
                        }

                        if (!string.IsNullOrEmpty(schedule.Name))
                        {
                            Add(schedule);
                        }
                    }

                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                    {
                        Log.WriteDebugMessage("Schedules file detected as an old version");
                        SaveToXmlFile();
                    }
                }
                else
                {
                    Log.WriteDebugMessage("WARNING: Unable to load schedules");

                    // If we can't find the schedules.xml file we'll need to have a "Special Schedule" schedule created to be compatible with old commands like -startat and -stopat.
                    Log.WriteDebugMessage("Creating default Special Schedule for use with command line arguments such as -startat and -stopat");

                    DateTime dtNow = DateTime.Now;

                    Schedule specialSchedule = new Schedule()
                    {
                        Name                  = SpecialScheduleName,
                        Active                = false,
                        ModeOneTime           = true,
                        ModePeriod            = false,
                        CaptureAt             = dtNow,
                        StartAt               = dtNow,
                        StopAt                = dtNow,
                        ScreenCaptureInterval = DefaultSettings.ScreenCaptureInterval,
                        Notes                 = "This schedule is used for the command line arguments -captureat, -startat, and -stopat."
                    };

                    if (Settings.VersionManager != null && Settings.VersionManager.OldUserSettings != null)
                    {
                        // If we're importing the schedule settings from a previous version of Auto Screen Capture we'll need to update the "Special Schedule" and enable it.
                        SettingCollection oldUserSettings = Settings.VersionManager.OldUserSettings;

                        bool captureStartAt = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureStartAt", DefaultSettings.BoolCaptureStartAt).Value);
                        bool captureStopAt  = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureStopAt", DefaultSettings.BoolCaptureStopAt).Value);

                        DateTime dtStartAt = Convert.ToDateTime(oldUserSettings.GetByKey("DateTimeCaptureStartAt", DefaultSettings.DateTimeCaptureStartAt).Value);
                        DateTime dtStopAt  = Convert.ToDateTime(oldUserSettings.GetByKey("DateTimeCaptureStopAt", DefaultSettings.DateTimeCaptureStopAt).Value);

                        // Days
                        bool captureOnTheseDays = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnTheseDays", DefaultSettings.BoolCaptureOnTheseDays).Value);
                        bool sunday             = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnSunday", DefaultSettings.BoolCaptureOnSunday).Value);
                        bool monday             = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnMonday", DefaultSettings.BoolCaptureOnMonday).Value);
                        bool tuesday            = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnTuesday", DefaultSettings.BoolCaptureOnTuesday).Value);
                        bool wednesday          = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnWednesday", DefaultSettings.BoolCaptureOnWednesday).Value);
                        bool thursday           = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnThursday", DefaultSettings.BoolCaptureOnThursday).Value);
                        bool friday             = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnFriday", DefaultSettings.BoolCaptureOnFriday).Value);
                        bool saturday           = Convert.ToBoolean(oldUserSettings.GetByKey("BoolCaptureOnSaturday", DefaultSettings.BoolCaptureOnSaturday).Value);

                        specialSchedule.ModeOneTime = false;
                        specialSchedule.ModePeriod  = true;

                        if (captureStartAt)
                        {
                            specialSchedule.Active  = true;
                            specialSchedule.StartAt = dtStartAt;
                        }

                        if (captureStopAt)
                        {
                            specialSchedule.Active = true;
                            specialSchedule.StopAt = dtStopAt;
                        }

                        if (captureOnTheseDays)
                        {
                            specialSchedule.Sunday    = sunday;
                            specialSchedule.Monday    = monday;
                            specialSchedule.Tuesday   = tuesday;
                            specialSchedule.Wednesday = wednesday;
                            specialSchedule.Thursday  = thursday;
                            specialSchedule.Friday    = friday;
                            specialSchedule.Saturday  = saturday;
                        }
                    }

                    Add(specialSchedule);

                    SaveToXmlFile();
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("ScheduleCollection::LoadXmlFileAndAddSchedules", ex);

                return(false);
            }
        }
        /// <summary>
        /// Loads the screens.
        /// </summary>
        public bool LoadXmlFileAndAddScreens(ImageFormatCollection imageFormatCollection)
        {
            try
            {
                if (FileSystem.FileExists(FileSystem.ScreensFile))
                {
                    Log.WriteDebugMessage("Screens file \"" + FileSystem.ScreensFile + "\" found. Attempting to load XML document");

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(FileSystem.ScreensFile);

                    Log.WriteDebugMessage("XML document loaded");

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xScreens = xDoc.SelectNodes(SCREEN_XPATH);

                    foreach (XmlNode xScreen in xScreens)
                    {
                        Screen        screen  = new Screen();
                        XmlNodeReader xReader = new XmlNodeReader(xScreen);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement() && !xReader.IsEmptyElement)
                            {
                                switch (xReader.Name)
                                {
                                case SCREEN_VIEWID:
                                    xReader.Read();
                                    screen.ViewId = Guid.Parse(xReader.Value);
                                    break;

                                case SCREEN_NAME:
                                    xReader.Read();
                                    screen.Name = xReader.Value;
                                    break;

                                case SCREEN_FOLDER:
                                    xReader.Read();
                                    screen.Folder = xReader.Value;
                                    break;

                                case SCREEN_MACRO:
                                    xReader.Read();
                                    screen.Macro = xReader.Value;
                                    break;

                                case SCREEN_COMPONENT:
                                    xReader.Read();
                                    screen.Component = Convert.ToInt32(xReader.Value);
                                    break;

                                case SCREEN_FORMAT:
                                    xReader.Read();
                                    screen.Format = imageFormatCollection.GetByName(xReader.Value);
                                    break;

                                case SCREEN_JPEG_QUALITY:
                                    xReader.Read();
                                    screen.JpegQuality = Convert.ToInt32(xReader.Value);
                                    break;

                                case SCREEN_RESOLUTION_RATIO:
                                    xReader.Read();
                                    screen.ResolutionRatio = Convert.ToInt32(xReader.Value);
                                    break;

                                case SCREEN_MOUSE:
                                    xReader.Read();
                                    screen.Mouse = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCREEN_ACTIVE:
                                    xReader.Read();
                                    screen.Active = Convert.ToBoolean(xReader.Value);
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        // Change the data for each Screen that's being loaded if we've detected that
                        // the XML document is from an older version of the application.
                        if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                        {
                            Log.WriteDebugMessage("An old version of the screens.xml file was detected. Attempting upgrade to new schema.");

                            Version v2300         = Settings.VersionManager.Versions.Get("Boombayah", "2.3.0.0");
                            Version configVersion = Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                            if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                            {
                                Log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                // This is a new property for Screen that was introduced in 2.3.0.0
                                // so any version before 2.3.0.0 needs to have it during an upgrade.
                                screen.Active = true;
                            }
                        }

                        if (!string.IsNullOrEmpty(screen.Name))
                        {
                            Add(screen);
                        }
                    }

                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                    {
                        Log.WriteDebugMessage("Screens file detected as an old version");
                        SaveToXmlFile();
                    }
                }
                else
                {
                    Log.WriteDebugMessage("WARNING: Unable to load screens");

                    // Setup some screens based on what we can find.
                    for (int screenNumber = 1; screenNumber <= System.Windows.Forms.Screen.AllScreens.Length; screenNumber++)
                    {
                        Screen screen = new Screen()
                        {
                            Name            = $"Screen {screenNumber}",
                            Folder          = FileSystem.ScreenshotsFolder,
                            Macro           = MacroParser.DefaultMacro,
                            Component       = screenNumber,
                            Format          = imageFormatCollection.GetByName(ScreenCapture.DefaultImageFormat),
                            JpegQuality     = 100,
                            ResolutionRatio = 100,
                            Mouse           = true,
                            Active          = true
                        };

                        Add(screen);

                        Log.WriteDebugMessage($"Screen {screenNumber} created using \"{FileSystem.ScreenshotsFolder}\" for folder path and \"{MacroParser.DefaultMacro}\" for macro.");
                    }

                    SaveToXmlFile();
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("ScreenCollection::LoadXmlFileAndAddScreens", ex);

                return(false);
            }
        }
Exemple #26
0
        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();
            }
        }
Exemple #27
0
        /// <summary>
        /// Loads the image editors from the editors.xml file.
        /// </summary>
        public bool LoadXmlFileAndAddEditors()
        {
            try
            {
                if (FileSystem.FileExists(FileSystem.EditorsFile))
                {
                    Log.WriteDebugMessage("Editors file \"" + FileSystem.EditorsFile + "\" found. Attempting to load XML document");

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(FileSystem.EditorsFile);

                    Log.WriteDebugMessage("XML document loaded");

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xEditors = xDoc.SelectNodes(EDITOR_XPATH);

                    foreach (XmlNode xEditor in xEditors)
                    {
                        Editor        editor  = new Editor();
                        XmlNodeReader xReader = new XmlNodeReader(xEditor);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement() && !xReader.IsEmptyElement)
                            {
                                switch (xReader.Name)
                                {
                                case EDITOR_NAME:
                                    xReader.Read();
                                    editor.Name = xReader.Value;
                                    break;

                                case EDITOR_APPLICATION:
                                    xReader.Read();
                                    editor.Application = xReader.Value;
                                    break;

                                case EDITOR_ARGUMENTS:
                                    xReader.Read();

                                    string value = xReader.Value;

                                    // Change the data for each Tag that's being loaded if we've detected that
                                    // the XML document is from an older version of the application.
                                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                                    {
                                        Log.WriteDebugMessage("An old version of the editors.xml file was detected. Attempting upgrade to new schema.");

                                        Version v2300         = Settings.VersionManager.Versions.Get("Boombayah", "2.3.0.0");
                                        Version configVersion = Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                                        if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                                        {
                                            Log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                            // Starting with 2.3.0.0 the %screenshot% argument tag became the %filepath% argument tag.
                                            value = value.Replace("%screenshot%", "%filepath%");

                                            // Set this editor as the default editor. Version 2.3 requires at least one editor to be the default editor.
                                            Settings.User.SetValueByKey("StringDefaultEditor", editor.Name);
                                        }
                                    }

                                    editor.Arguments = value;
                                    break;

                                case EDITOR_NOTES:
                                    xReader.Read();
                                    editor.Notes = xReader.Value;
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        if (!string.IsNullOrEmpty(editor.Name) &&
                            !string.IsNullOrEmpty(editor.Application))
                        {
                            Add(editor);
                        }
                    }

                    if (Settings.VersionManager.IsOldAppVersion(AppCodename, AppVersion))
                    {
                        Log.WriteDebugMessage("Editors file detected as an old version");
                        SaveToXmlFile();
                    }
                }
                else
                {
                    Log.WriteDebugMessage("WARNING: Unable to load editors");

                    // Setup default image editors.
                    // This is going to get maintenance heavy. I just know it.

                    // Microsoft Paint
                    if (FileSystem.FileExists(@"C:\Windows\System32\mspaint.exe"))
                    {
                        Add(new Editor("Microsoft Paint", @"C:\Windows\System32\mspaint.exe", "%filepath%"));

                        // We'll make Microsoft Paint the default image editor because usually everyone has it already.
                        Settings.User.SetValueByKey("StringDefaultEditor", "Microsoft Paint");
                    }

                    // Snagit Editor
                    if (FileSystem.FileExists(@"C:\Program Files\TechSmith\Snagit 2020\SnagitEditor.exe"))
                    {
                        Add(new Editor("Snagit Editor", @"C:\Program Files\TechSmith\Snagit 2020\SnagitEditor.exe", "%filepath%"));

                        // If the user has Snagit installed then make the Snagit Editor the default editor.
                        Settings.User.SetValueByKey("StringDefaultEditor", "Snagit Editor");
                    }

                    // Microsoft Outlook
                    if (FileSystem.FileExists(@"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE"))
                    {
                        Add(new Editor("Microsoft Outlook", @"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE", "/c ipm.note /a %filepath%"));
                    }

                    // Chrome
                    if (FileSystem.FileExists(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"))
                    {
                        Add(new Editor("Chrome", @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "%filepath%"));
                    }

                    // Firefox
                    if (FileSystem.FileExists(@"C:\Program Files\Mozilla Firefox\firefox.exe"))
                    {
                        Add(new Editor("Firefox", @"C:\Program Files\Mozilla Firefox\firefox.exe", "%filepath%"));
                    }

                    // GIMP
                    // We assume GIMP will be in the default location available for all users on 64-bit systems.
                    if (FileSystem.FileExists(@"C:\Program Files\GIMP 2\bin\gimp-2.10.exe"))
                    {
                        Add(new Editor("GIMP", @"C:\Program Files\GIMP 2\bin\gimp-2.10.exe", "%filepath%"));
                    }

                    // Glimpse
                    if (FileSystem.FileExists(@"C:\Program Files (x86)\Glimpse Image Editor\Glimpse 0.1.2\bin\Glimpse.exe"))
                    {
                        Add(new Editor("Glimpse", @"C:\Program Files (x86)\Glimpse Image Editor\Glimpse 0.1.2\bin\Glimpse.exe", "%filepath%"));
                    }

                    // Clip Studio Paint
                    if (FileSystem.FileExists(@"C:\Program Files\CELSYS\CLIP STUDIO 1.5\CLIP STUDIO PAINT\CLIPStudioPaint.exe"))
                    {
                        Add(new Editor("Clip Studio Paint", @"C:\Program Files\CELSYS\CLIP STUDIO 1.5\CLIP STUDIO PAINT\CLIPStudioPaint.exe", "%filepath%"));
                    }

                    SaveToXmlFile();
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("EditorCollection::LoadXmlFileAndAddEditors", ex);

                return(false);
            }
        }
Exemple #28
0
        /// <summary>
        /// Loads the configuration file.
        /// </summary>
        public static void Load()
        {
            try
            {
                if (!FileSystem.DirectoryExists(FileSystem.GetDirectoryName(FileSystem.ConfigFile)))
                {
                    FileSystem.CreateDirectory(FileSystem.GetDirectoryName(FileSystem.ConfigFile));
                }

                if (!FileSystem.FileExists(FileSystem.ConfigFile))
                {
                    string[] linesToWrite =
                    {
                        "# Auto Screen Capture Configuration File",
                        "# Use this file to tell the application what folders and files it should utilize.",
                        "# Each key-value pair can be the name of a folder or file or a path to a folder or file.",
                        "# If only the folder name is given then it will be parsed as the sub-folder of the folder",
                        "# where the executed autoscreen.exe binary is located.",                                                   "",
                        "# This is the folder where screenshots will be stored by default.",
                        "ScreenshotsFolder=" + FileSystem.DefaultScreenshotsFolder,                                                 "",
                        "# If any errors are encountered then you will find them in this folder when DebugMode is enabled.",
                        "DebugFolder=" + FileSystem.DefaultDebugFolder,                                                             "",
                        "# Logs are stored in this folder when either Logging or DebugMode is enabled.",
                        "LogsFolder=" + FileSystem.DefaultLogsFolder,                                                               "",
                        "# This file is monitored by the application for commands issued from the command line while it's running.",
                        "CommandFile=" + FileSystem.DefaultCommandFile,                                                             "",
                        "# The application settings (such as DebugMode).",
                        "ApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile,                                     "",
                        "# Your personal settings.",
                        "UserSettingsFile=" + FileSystem.DefaultUserSettingsFile,                                                   "",
                        "# References to image editors.",
                        "EditorsFile=" + FileSystem.DefaultEditorsFile,                                                             "",
                        "# References to regions.",
                        "RegionsFile=" + FileSystem.DefaultRegionsFile,                                                             "",
                        "# References to screens.",
                        "ScreensFile=" + FileSystem.DefaultScreensFile,                                                             "",
                        "# References to triggers.",
                        "TriggersFile=" + FileSystem.DefaultTriggersFile,                                                           "",
                        "# References to screenshots.",
                        "ScreenshotsFile=" + FileSystem.DefaultScreenshotsFile,                                                     "",
                        "# References to tags.",
                        "TagsFile=" + FileSystem.DefaultTagsFile,                                                                   "",
                        "# References to schedules.",
                        "SchedulesFile=" + FileSystem.DefaultSchedulesFile,                                                         ""
                    };

                    FileSystem.WriteToFile(FileSystem.ConfigFile, linesToWrite);
                }

                foreach (string line in FileSystem.ReadFromFile(FileSystem.ConfigFile))
                {
                    string path;

                    if (GetPath(line, REGEX_SCREENSHOTS_FOLDER, out path))
                    {
                        FileSystem.ScreenshotsFolder = path;
                    }

                    if (GetPath(line, REGEX_DEBUG_FOLDER, out path))
                    {
                        FileSystem.DebugFolder = path;
                    }

                    if (GetPath(line, REGEX_LOGS_FOLDER, out path))
                    {
                        FileSystem.LogsFolder = path;
                    }

                    if (GetPath(line, REGEX_COMMAND_FILE, out path))
                    {
                        FileSystem.CommandFile = path;
                    }

                    if (GetPath(line, REGEX_APPLICATION_SETTINGS_FILE, out path))
                    {
                        FileSystem.ApplicationSettingsFile = path;
                    }

                    if (GetPath(line, REGEX_USER_SETTINGS_FILE, out path))
                    {
                        FileSystem.UserSettingsFile = path;
                    }

                    if (GetPath(line, REGEX_EDITORS_FILE, out path))
                    {
                        FileSystem.EditorsFile = path;
                    }

                    if (GetPath(line, REGEX_REGIONS_FILE, out path))
                    {
                        FileSystem.RegionsFile = path;
                    }

                    if (GetPath(line, REGEX_SCREENS_FILE, out path))
                    {
                        FileSystem.ScreensFile = path;
                    }

                    if (GetPath(line, REGEX_TRIGGERS_FILE, out path))
                    {
                        FileSystem.TriggersFile = path;
                    }

                    if (GetPath(line, REGEX_SCREENSHOTS_FILE, out path))
                    {
                        FileSystem.ScreenshotsFile = path;
                    }

                    if (GetPath(line, REGEX_TAGS_FILE, out path))
                    {
                        FileSystem.TagsFile = path;
                    }

                    if (GetPath(line, REGEX_SCHEDULES_FILE, out path))
                    {
                        FileSystem.SchedulesFile = path;
                    }
                }

                CheckAndCreateFolders();

                CheckAndCreateFiles();
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("Config::Load", ex);
            }
        }
        /// <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>
        /// Loads the image schedules from the schedules.xml file.
        /// </summary>
        public bool LoadXmlFileAndAddSchedules(Config config, FileSystem fileSystem, Log log)
        {
            try
            {
                if (fileSystem.FileExists(fileSystem.SchedulesFile))
                {
                    log.WriteDebugMessage("Schedules file \"" + fileSystem.SchedulesFile + "\" found. Attempting to load XML document");

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(fileSystem.SchedulesFile);

                    log.WriteDebugMessage("XML document loaded");

                    AppVersion  = xDoc.SelectSingleNode("/autoscreen").Attributes["app:version"]?.Value;
                    AppCodename = xDoc.SelectSingleNode("/autoscreen").Attributes["app:codename"]?.Value;

                    XmlNodeList xSchedules = xDoc.SelectNodes(SCHEDULE_XPATH);

                    foreach (XmlNode xSchedule in xSchedules)
                    {
                        Schedule      schedule = new Schedule();
                        XmlNodeReader xReader  = new XmlNodeReader(xSchedule);

                        while (xReader.Read())
                        {
                            if (xReader.IsStartElement() && !xReader.IsEmptyElement)
                            {
                                switch (xReader.Name)
                                {
                                case SCHEDULE_NAME:
                                    xReader.Read();
                                    schedule.Name = xReader.Value;
                                    break;

                                case SCHEDULE_ENABLE:
                                case "active":     // Any version older than 2.4.0.0 used "active" instead of "enable".
                                    xReader.Read();
                                    schedule.Enable = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_MODE_ONETIME:
                                    xReader.Read();
                                    schedule.ModeOneTime = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_MODE_PERIOD:
                                    xReader.Read();
                                    schedule.ModePeriod = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_CAPTUREAT:
                                    xReader.Read();
                                    schedule.CaptureAt = Convert.ToDateTime(xReader.Value);
                                    break;

                                case SCHEDULE_STARTAT:
                                    xReader.Read();
                                    schedule.StartAt = Convert.ToDateTime(xReader.Value);
                                    break;

                                case SCHEDULE_STOPAT:
                                    xReader.Read();
                                    schedule.StopAt = Convert.ToDateTime(xReader.Value);
                                    break;

                                case SCHEDULE_SCREEN_CAPTURE_INTERVAL:
                                    xReader.Read();
                                    schedule.ScreenCaptureInterval = Convert.ToInt32(xReader.Value);
                                    break;

                                case SCHEDULE_MONDAY:
                                    xReader.Read();
                                    schedule.Monday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_TUESDAY:
                                    xReader.Read();
                                    schedule.Tuesday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_WEDNESDAY:
                                    xReader.Read();
                                    schedule.Wednesday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_THURSDAY:
                                    xReader.Read();
                                    schedule.Thursday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_FRIDAY:
                                    xReader.Read();
                                    schedule.Friday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_SATURDAY:
                                    xReader.Read();
                                    schedule.Saturday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_SUNDAY:
                                    xReader.Read();
                                    schedule.Sunday = Convert.ToBoolean(xReader.Value);
                                    break;

                                case SCHEDULE_NOTES:
                                    xReader.Read();
                                    schedule.Notes = xReader.Value;
                                    break;

                                case SCHEDULE_LOGIC:
                                    xReader.Read();
                                    schedule.Logic = Convert.ToInt32(xReader.Value);
                                    break;

                                case SCHEDULE_SCOPE:
                                    xReader.Read();
                                    schedule.Scope = xReader.Value;
                                    break;
                                }
                            }
                        }

                        xReader.Close();

                        // Change the data for each Schedule that's being loaded if we've detected that
                        // the XML document is from an older version of the application.
                        if (config.Settings.VersionManager.IsOldAppVersion(config.Settings, AppCodename, AppVersion))
                        {
                            log.WriteDebugMessage("An old version of the schedules.xml file was detected. Attempting upgrade to new schema.");

                            Version v2300         = config.Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, Settings.CODEVERSION_BOOMBAYAH);
                            Version v2319         = config.Settings.VersionManager.Versions.Get(Settings.CODENAME_BOOMBAYAH, "2.3.1.9");
                            Version configVersion = config.Settings.VersionManager.Versions.Get(AppCodename, AppVersion);

                            if (v2300 != null && configVersion != null && configVersion.VersionNumber < v2300.VersionNumber)
                            {
                                log.WriteDebugMessage("Dalek 2.2.4.6 or older detected");

                                // This is a new property for Schedule that was introduced in 2.3.0.0
                                // so any version before 2.3.0.0 needs to have it during an upgrade.
                                schedule.Enable = true;
                            }

                            if (v2319 != null && configVersion != null && configVersion.VersionNumber < v2319.VersionNumber)
                            {
                                log.WriteDebugMessage("Boombayah 2.3.1.8 or older detected");

                                // A new property for Schedule introduced in 2.3.1.9
                                schedule.ScreenCaptureInterval = Convert.ToInt32(config.Settings.User.GetByKey("ScreenCaptureInterval", config.Settings.DefaultSettings.ScreenCaptureInterval).Value);
                            }

                            // 2.4 removes "Special Schedule" that was used in previous versions because 2.4 uses an internal special schedule going forward.
                            if (schedule.Name.Equals("Special Schedule"))
                            {
                                schedule.Name = string.Empty;
                            }
                        }

                        if (!string.IsNullOrEmpty(schedule.Name))
                        {
                            Add(schedule);
                        }
                    }

                    if (config.Settings.VersionManager.IsOldAppVersion(config.Settings, AppCodename, AppVersion))
                    {
                        log.WriteDebugMessage("Schedules file detected as an old version");
                        SaveToXmlFile(config.Settings, fileSystem, log);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (fileSystem.FileExists(fileSystem.SchedulesFile))
                {
                    fileSystem.DeleteFile(fileSystem.SchedulesFile);

                    log.WriteErrorMessage("The file \"" + fileSystem.SchedulesFile + "\" had to be deleted because an error was encountered. You may need to force quit the application and run it again.");
                }

                log.WriteExceptionMessage("ScheduleCollection::LoadXmlFileAndAddSchedules", ex);

                return(false);
            }
        }