コード例 #1
0
        /// <summary>
        /// Creates an instance of a <see cref="Plugin"/> class to be inserted into the database.
        /// </summary>
        /// <param name="assembly">The assembly of the plug-in.</param>
        /// <param name="plugin">The initialized plug-in.</param>
        /// <param name="fileNameFull">The full file name of the plug-in assembly.</param>
        /// <returns>A <see cref="Plugin"/> class instance based on the given arguments.</returns>
        public static Plugin FromPlugin(Assembly assembly, IScriptNotepadPlugin plugin, string fileNameFull)
        {
            try
            {
                // create a result based on the given parameters..
                var result = new Plugin
                {
                    FileNameFull      = fileNameFull,
                    FileName          = Path.GetFileName(fileNameFull),
                    FilePath          = Path.GetDirectoryName(fileNameFull),
                    PluginName        = plugin.PluginName,
                    PluginDescription = plugin.PluginDescription,
                    IsActive          = true,
                    PluginInstalled   = DateTime.Now,
                    PluginVersion     = VersionStringFromAssembly(assembly),
                };

                // set the version for the plug-in..
                AssemblyVersion.SetPluginUpdated(result, assembly);

                // return the result..
                return(result);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(null);
            }
        }
コード例 #2
0
        /// <summary>
        /// Adds an unique miscellaneous text value to the database.
        /// </summary>
        /// <param name="miscText">The misc text.</param>
        /// <param name="miscellaneousTextType">Type of the miscellaneous text.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns>An instance to a <see cref="MiscellaneousTextEntry"/> if successful, <c>null</c> otherwise.</returns>
        public static MiscellaneousTextEntry AddUniqueMiscellaneousText(string miscText,
                                                                        MiscellaneousTextType miscellaneousTextType, FileSession fileSession)
        {
            try
            {
                var context = ScriptNotepadDbContext.DbContext;

                if (!context.MiscellaneousTextEntries.Any(f =>
                                                          f.TextValue == miscText && f.TextType == miscellaneousTextType && f.Session.SessionName == fileSession.SessionName))
                {
                    var result = new MiscellaneousTextEntry
                    {
                        Session   = fileSession,
                        TextType  = miscellaneousTextType,
                        TextValue = miscText
                    };

                    result = context.MiscellaneousTextEntries.Add(result).Entity;
                    context.SaveChanges();
                    return(result);
                }

                return(context.MiscellaneousTextEntries.FirstOrDefault(f =>
                                                                       f.TextValue == miscText && f.TextType == miscellaneousTextType &&
                                                                       f.Session.SessionName == fileSession.SessionName)); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(null); // failure..
            }
        }
コード例 #3
0
        /// <summary>
        /// Checks if the access to a given file with given permissions requires elevation.
        /// </summary>
        /// <param name="fileName">Name of the file which access permissions to check.</param>
        /// <param name="fileMode">The mode of how to try to open the file.</param>
        /// <param name="fileAccess">The file access mode of how to try to open the file.</param>
        /// <param name="fileShare">The file share mode of how to try to open the file.</param>
        /// <returns>A named tuple containing a value whether a elevation to access the file is required and a flag indicating whether the file is corrupted (I/O error).</returns>
        public static (bool ElevationRequied, bool FileCorrupted) FileRequiresElevation(string fileName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
        {
            try
            {
                using (new FileStream(fileName, fileMode, fileAccess, fileShare))
                {
                    // nothing to  see here..
                }

                return(false, false);
            }
            // catch the exception and determine the result based on the type of the exception.
            catch (Exception ex)
            {
                // log the exception if the action has a value..
                ExceptionLogAction?.Invoke(ex);

                if (ex.GetType() == typeof(UnauthorizedAccessException) ||
                    ex.GetType() == typeof(SecurityException))
                {
                    return(true, false);
                }
                else if (ex.GetType() == typeof(IOException))
                {
                    return(false, true);
                }
                else
                {
                    return(true, false);
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Creates a compiled regular expression from a given list of file extensions.
        /// </summary>
        /// <param name="extensions">The file extensions to be used with the search.</param>
        /// <returns>An instance to a <see cref="Regex"/> class.</returns>
        private static Regex FromExtensions(params string[] extensions)
        {
            // remove the useless '*.' and '.' character combinations from the given parameters..
            for (int i = 0; i < extensions.Length; i++)
            {
                extensions[i] =
                    extensions[i].
                    Replace("*.", "").
                    Replace(".", "");

                // the '*' character requires special handling; otherwise an exception would occur..
                if (extensions[i] == "*")
                {
                    extensions[i] = "." + extensions[i];
                }
            }

            // create a compiled regular expression of the given parameters
            // and return it.. hint: '\.(cs|txt|xml)$'
            try
            {
                return(new Regex(@"\.(" + string.Join("|", extensions) + ")$",
                                 RegexOptions.IgnoreCase | RegexOptions.Compiled));
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);

                // return a regexp matching all file endings..
                return(new Regex(@"\\.*", RegexOptions.IgnoreCase | RegexOptions.Compiled));
            }
        }
コード例 #5
0
 /// <summary>
 /// Determines whether the specified file is a .NET Framework assembly.
 /// </summary>
 /// <param name="fileName">The name of the file to test for.</param>
 /// <returns>True if the file is an assembly; otherwise false.</returns>
 public static bool IsAssembly(string fileName)
 {
     try
     {
         AssemblyName.GetAssemblyName(fileName);
         return(true);
     }
     catch (FileNotFoundException ex)
     {
         // log the exception..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
     catch (BadImageFormatException ex)
     {
         // log the exception..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
     catch (FileLoadException ex)
     {
         // log the exception..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
     catch (Exception ex)
     {
         // log the exception..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
 }
コード例 #6
0
        /// <summary>
        /// Cleans up the closed (history) files from a given session with a given maximum amount to keep.
        /// </summary>
        /// <param name="keepMaximum">The maximum number of file history to keep per session.</param>
        /// <param name="session">The session </param>
        /// <returns><c>true</c> a tuple containing the value whether the clean up was successful and the amount of records deleted.</returns>
        public static (bool success, int count) CleanUpHistoryFiles(int keepMaximum, FileSession session)
        {
            try
            {
                var dbContext      = ScriptNotepadDbContext.DbContext;
                var deleteSavesIds = dbContext.FileSaves
                                     .Where(f => f.Session.SessionName == session.SessionName && f.IsHistory)
                                     .Select(f => new { id = f.Id, modified = f.DatabaseModified });

                var deleteAmount = deleteSavesIds.Count() - keepMaximum;

                if (deleteAmount > 0)
                {
                    deleteSavesIds = deleteSavesIds.Take(deleteAmount);

                    var deleted = dbContext.FileSaves.Count(f => deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id));

                    dbContext.FileSaves.RemoveRange(
                        dbContext.FileSaves.Where(f =>
                                                  deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id)));

                    dbContext.SaveChanges();

                    return(true, deleted);
                }

                return(true, 0);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false, 0);
            }
        }
コード例 #7
0
        /// <summary>
        /// Checks if a compiled regular expression from a given list of file extensions is valid.
        /// </summary>
        /// <param name="extensions">The file extensions to be used with the check.</param>
        /// <returns>True if the created regular expression is valid; otherwise false.</returns>
        public static bool ValidateExtensionRegexp(params string[] extensions)
        {
            // remove the useless '*.' and '.' character combinations from the given parameters..
            for (int i = 0; i < extensions.Length; i++)
            {
                extensions[i] =
                    extensions[i].
                    Replace("*.", "").
                    Replace(".", "");

                // the '*' character requires special handling; otherwise an exception would occur..
                if (extensions[i] == "*")
                {
                    extensions[i] = "." + extensions[i];
                }
            }

            // create a compiled regular expression of the given parameters
            // and return it.. hint: '\.(cs|txt|xml)$'
            try
            {
                // ReSharper disable once ObjectCreationAsStatement
                new Regex(@"\.(" + string.Join("|", extensions) + ")$",
                          RegexOptions.IgnoreCase | RegexOptions.Compiled);
                return(true);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false);
            }
        }
コード例 #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AudioVisualizationPlot"/> class.
        /// </summary>
        public AudioVisualizationPlot()
        {
            InitializeComponent();
            tmVisualize.Tick     += TmVisualize_Tick;
            Disposed             += AudioVisualizationPlot_Disposed;
            ShouldResizeChildren += AudioVisualizationBars_ShouldResizeChildren;

            try
            {
                var propertyInfo = typeof(Panel)
                                   .GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);

                if (propertyInfo != null)
                {
                    propertyInfo.SetValue(pnLeft, true);
                    propertyInfo.SetValue(pnRight, true);
                    propertyInfo.SetValue(pnKHzLabels, true);
                }
            }
            catch (Exception ex)
            {
                // report the exception..
                ExceptionLogAction?.Invoke(ex);
            }

            CalculateHertzLabelHeight(pnKHzLabels.Handle, pnKHzLabels.Font);
        }
コード例 #9
0
        /// <summary>
        /// Deletes the entire session from the database context.
        /// </summary>
        /// <param name="session">The session to delete.</param>
        /// <returns><c>true</c> if the operation was successful, <c>false</c> otherwise.</returns>
        public static bool DeleteEntireSession(FileSession session)
        {
            try
            {
                var context = ScriptNotepadDbContext.DbContext;

                context.FileSaves.RemoveRange(context.FileSaves.Where(f => f.Session.SessionName == session.SessionName));
                context.MiscellaneousTextEntries.RemoveRange(context.MiscellaneousTextEntries.Where(f => f.Session.SessionName == session.SessionName));
                context.RecentFiles.RemoveRange(context.RecentFiles.Where(f => f.Session.SessionName == session.SessionName));

                session = context.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName);

                if (session != null)
                {
                    context.FileSessions.Remove(session);
                }

                context.SaveChanges();
                return(true); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false); // failure..
            }
        }
コード例 #10
0
 /// <summary>
 /// Opens the file with associated program.
 /// </summary>
 /// <param name="fileName">The name of the file to open.</param>
 /// <returns>True if the operation was successful; otherwise false.</returns>
 public static bool OpenWithAssociatedProgram(string fileName)
 {
     try
     {
         System.Diagnostics.Process.Start(fileName);
         return(true);
     }
     catch (Exception ex)
     {
         // log the exception if the action has a value..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
 }
コード例 #11
0
 /// <summary>
 /// Set the Clipboard's contents to a given text.
 /// </summary>
 /// <param name="text">The text to set the clipboard's contents to.</param>
 /// <returns>True if the operation was successful; otherwise false.</returns>
 public static bool ClipboardSetText(string text)
 {
     try
     {
         System.Windows.Forms.Clipboard.SetDataObject(text, true, 20, 150);
         return(true);
     }
     catch (Exception ex)
     {
         // clipboard operation may fail..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
 }
コード例 #12
0
 /// <summary>
 /// Opens the folder in explorer.
 /// </summary>
 /// <param name="folder">The folder to show in the Windows explorer.</param>
 /// <returns>True if the operation was successful; otherwise false.</returns>
 public static bool OpenFolderInExplorer(string folder)
 {
     try
     {
         System.Diagnostics.Process.Start("explorer.exe", folder);
         return(true);
     }
     catch (Exception ex)
     {
         // log the exception if the action has a value..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
 }
コード例 #13
0
        /// <summary>
        /// Gets an <see cref="Encoding"/> class instance from string describing the encoding.
        /// </summary>
        /// <param name="encodingString">The string describing the <see cref="Encoding"/>. I.e: utf-32BE;True;True;True.</param>
        /// <returns>Returns the <see cref="Encoding"/> created from the given string instance.</returns>
        public static Encoding EncodingFromString(string encodingString)
        {
            try
            {
                string[] encodingValues = encodingString.Split(';');

                string webName           = encodingValues.Length >= 1 ? encodingValues[0] : Encoding.Default.WebName;
                bool   byteOrderMark     = encodingValues.Length >= 3 && bool.Parse(encodingValues[2]);
                bool   throwInvalidChars = encodingValues.Length >= 5 && bool.Parse(encodingValues[4]);

                if (webName == "utf-8")
                {
                    return(new UTF8Encoding(byteOrderMark, throwInvalidChars));
                }

                if (webName == "utf-16" || webName == "utf-16BE")
                {
                    return(new UnicodeEncoding(webName == "utf-16BE", byteOrderMark, throwInvalidChars));
                }

                if (webName == "utf-32" || webName == "utf-32BE")
                {
                    return(new UTF32Encoding(webName == "utf-32BE", byteOrderMark, throwInvalidChars));
                }

                try
                {
                    return(Encoding.GetEncoding(webName));
                }
                catch (Exception ex)
                {
                    ExceptionLogAction?.Invoke(ex);
                    try
                    {
                        return(CodePagesEncodingProvider.Instance.GetEncoding(webName));
                    }
                    catch (Exception exInner)
                    {
                        ExceptionLogAction?.Invoke(exInner);
                        return(Encoding.Default);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogAction?.Invoke(ex);
                return(Encoding.Default);
            }
        }
コード例 #14
0
 /// <summary>
 /// Shows the file or path in Windows explorer.
 /// </summary>
 /// <param name="fileOrPath">The file or path to show in the Windows explorer.</param>
 /// <returns>True if the operation was successful; otherwise false.</returns>
 public static bool ShowFileOrPathInExplorer(string fileOrPath)
 {
     try
     {
         // (C): https://social.msdn.microsoft.com/Forums/vstudio/en-US/a6e1458a-20d0-48b4-8e3a-0a00c8618d75/opening-folder-in-explorer-by-c-code?forum=netfxbcl
         System.Diagnostics.Process.Start("explorer.exe", $"/e,/select,{fileOrPath}");
         return(true);
     }
     catch (Exception ex)
     {
         // log the exception if the action has a value..
         ExceptionLogAction?.Invoke(ex);
         return(false);
     }
 }
コード例 #15
0
        /// <summary>
        /// Gets a version string from a given <see cref="Assembly"/>.
        /// </summary>
        /// <param name="assembly">The assembly to set the version from.</param>
        internal static string VersionStringFromAssembly(Assembly assembly)
        {
            try
            {
                // return the version from the given assembly..
                return(assembly.GetName().Version.ToString());
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);

                // return a default value..
                return("1.0.0.0");
            }
        }
コード例 #16
0
        /// <summary>
        /// Deletes the older <see cref="MiscellaneousTextEntry"/> entries by a given limit to keep.
        /// </summary>
        /// <param name="miscellaneousTextType">Type of the miscellaneous text.</param>
        /// <param name="limit">The limit of how many to entries to keep.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns><c>true</c> if the operation was successful, <c>false</c> otherwise.</returns>
        public static bool DeleteOlderEntries(MiscellaneousTextType miscellaneousTextType, int limit, FileSession fileSession)
        {
            try
            {
                ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.RemoveRange(
                    ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Where(f => f.Session.SessionName == fileSession.SessionName)
                    .Except(GetEntriesByLimit(miscellaneousTextType, limit, fileSession)));

                return(true); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false); // failure..
            }
        }
コード例 #17
0
        /// <summary>
        /// Cleanups the recent file list by removing older entries from the list by a given number to keep.
        /// </summary>
        /// <param name="keepMaximum">The maximum number of recent files to keep per session.</param>
        /// <param name="session">The session from which to clean the recent file from.</param>
        /// <returns><c>true</c> a tuple containing the value whether the clean up was successful and the amount of records deleted.</returns>
        public static (bool success, int count) CleanupHistoryList(int keepMaximum, FileSession session) // one could probably make this a bit more complicated..
        {
            try
            {
                var dbContext = ScriptNotepadDbContext.DbContext;

                session =
                    dbContext.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName);

                var closedCount =
                    dbContext.FileSaves.Count(f => f.IsHistory && f.Session.SessionName == session.SessionName);

                var removeFiles = dbContext.FileSaves
                                  .Where(f => !f.IsHistory && f.Session.SessionName == session.SessionName)
                                  .Select(f => f.FileNameFull);

                dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles.Where(f =>
                                                                              f.Session.SessionName == session.SessionName && removeFiles.Contains(f.FileNameFull)));

                var historyRemoveCount = closedCount - keepMaximum;

                if (historyRemoveCount > 0)
                {
                    var deleted = dbContext.RecentFiles
                                  .OrderByDescending(f => f.ClosedDateTime)
                                  .Take(historyRemoveCount).Count();

                    dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles
                                                      .OrderByDescending(f => f.ClosedDateTime)
                                                      .Take(historyRemoveCount));

                    dbContext.SaveChanges();

                    return(true, deleted);
                }

                return(true, 0);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false, 0);
            }
        }
コード例 #18
0
        /// <summary>
        /// Gets the scintilla lines as string list.
        /// </summary>
        /// <param name="scintilla">The <see cref="Scintilla"/> class instance to get the lines from.</param>
        /// <returns>A collection containing the <see cref="Scintilla"/> control's lines.</returns>
        public static List <string> GetScintillaLinesAsStringList(Scintilla scintilla)
        {
            List <string> result = new List <string>();

            try
            {
                foreach (var line in scintilla.Lines)
                {
                    result.Add(line.Text);
                }
            }
            catch (Exception ex)
            {
                // log the exception if the action has a value..
                ExceptionLogAction?.Invoke(ex);
            }
            return(result);
        }
コード例 #19
0
 /// <summary>
 /// Loads a custom spell checking assembly if defined in the settings file.
 /// </summary>
 public static void Load()
 {
     if (FormSettings.Settings.EditorSpellUseCustomDictionary)
     {
         try
         {
             var data = DictionaryPackage.GetXmlDefinitionDataFromDefinitionFile(FormSettings.Settings
                                                                                 .EditorSpellCustomDictionaryDefinitionFile);
             ExternalSpellChecker.LoadSpellCheck(Path.GetDirectoryName(FormSettings.Settings
                                                                       .EditorSpellCustomDictionaryDefinitionFile), data.lib);
         }
         catch (Exception ex)
         {
             // log the exception..
             ExceptionLogAction?.Invoke(ex);
         }
     }
 }
コード例 #20
0
        /// <summary>
        /// Adds or updates a <see cref="SearchAndReplaceHistory"/> entity.
        /// </summary>
        /// <param name="text">The text used for searching or replacing.</param>
        /// <param name="searchAndReplaceSearchType">Type of the search and replace search.</param>
        /// <param name="searchAndReplaceType">Type of the search and replace.</param>
        /// <param name="caseSensitive">if set to <c>true</c> the search or replace is case sensitive.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns>SearchAndReplaceHistory.</returns>
        public static SearchAndReplaceHistory AddOrUpdateAndReplaceHistory(string text,
                                                                           SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType,
                                                                           bool caseSensitive, FileSession fileSession)
        {
            try
            {
                var context = ScriptNotepadDbContext.DbContext;

                if (!context.SearchAndReplaceHistories.Any(f =>
                                                           f.SearchOrReplaceText == text &&
                                                           f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) &&
                                                           f.SearchAndReplaceType == searchAndReplaceType &&
                                                           f.CaseSensitive == caseSensitive &&
                                                           f.Session.SessionName == fileSession.SessionName))
                {
                    var result = new SearchAndReplaceHistory
                    {
                        SearchOrReplaceText        = text,
                        SearchAndReplaceSearchType = searchAndReplaceSearchType,
                        SearchAndReplaceType       = searchAndReplaceType,
                        CaseSensitive = caseSensitive,
                        Session       = fileSession,
                    };

                    result = context.SearchAndReplaceHistories.Add(result).Entity;
                    context.SaveChanges();
                    return(result);
                }

                return(context.SearchAndReplaceHistories.FirstOrDefault(f =>
                                                                        f.SearchOrReplaceText == text &&
                                                                        f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) &&
                                                                        f.SearchAndReplaceType == searchAndReplaceType &&
                                                                        f.CaseSensitive == caseSensitive &&
                                                                        f.Session.SessionName == fileSession.SessionName)); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(null); // failure..
            }
        }
コード例 #21
0
        /// <summary>
        /// Loads a spell checker library from a given path with a given file name.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="fileName">Name of the file.</param>
        public static void LoadSpellCheck(string path, string fileName)
        {
            try
            {
                fileName = Path.Combine(path, fileName);

                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

                var assemblyName = Path.Combine(path, fileName);

                // the location of the assembly must be defined..
                Assembly spellCheck = Assembly.LoadFile(assemblyName);

                SetSpellChecker(spellCheck);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
            }
        }
コード例 #22
0
        /// <summary>
        /// Crawls the directory containing Hunspell dictionary and affix files.
        /// </summary>
        /// <param name="path">The path to search the dictionaries from.</param>
        /// <returns>List&lt;HunspellData&gt;.</returns>
        public static List <HunspellData> CrawlDirectory(string path)
        {
            // create a new instance of the DirectoryCrawler class by user given "arguments"..
            DirectoryCrawler crawler = new DirectoryCrawler(path, DirectoryCrawler.SearchTypeMatch.Regex,
                                                            "*.dic", true);

            // search for the Hunspell dictionary files (*.dic)..
            var files = crawler.GetCrawlResult();

            // initialize a return value..
            List <HunspellData> result = new List <HunspellData>();

            // loop through the found dictionary files (*.dic)..
            foreach (var file in files)
            {
                try
                {
                    // create a new HunspellData class instance..
                    var data = HunspellData.FromDictionaryFile(file);

                    // validate that there is a affix (*.aff) pair for the found dictionary file (*.dic)..
                    if (!File.Exists(data.DictionaryFile) || !File.Exists(data.AffixFile))
                    {
                        // ..if not, do continue..
                        continue;
                    }

                    // the validation was successful, so add the data to the result..
                    result.Add(data);
                }
                catch (Exception ex)
                {
                    // log the exception..
                    ExceptionLogAction?.Invoke(ex);
                }
            }

            // return the result..
            return(result);
        }
コード例 #23
0
        /// <summary>
        /// Updates the plug-in entry data.
        /// </summary>
        /// <param name="pluginEntry">The plug-in entry <see cref="Plugin"/>.</param>
        /// <param name="assembly">The assembly of the plug-in.</param>
        /// <param name="plugin">The initialized plug-in.</param>
        /// <param name="fileNameFull">The full file name of the plug-in assembly.</param>
        /// <returns>An updated <see cref="Plugin"/> class instance based on the given arguments.</returns>
        public static Plugin UpdateFromPlugin(Plugin pluginEntry, Assembly assembly, IScriptNotepadPlugin plugin, string fileNameFull)
        {
            try
            {
                pluginEntry.FileNameFull      = fileNameFull;
                pluginEntry.FileName          = Path.GetFileName(fileNameFull);
                pluginEntry.FilePath          = Path.GetDirectoryName(fileNameFull);
                pluginEntry.PluginName        = plugin.PluginName;
                pluginEntry.PluginDescription = plugin.PluginDescription;

                // set the version for the plug-in..
                AssemblyVersion.SetPluginUpdated(pluginEntry, assembly);

                return(pluginEntry);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(pluginEntry);
            }
        }
コード例 #24
0
        /// <summary>
        /// Deletes the older entities with a given limit.
        /// </summary>
        /// <param name="searchAndReplaceSearchType">Type of the search and replace search.</param>
        /// <param name="searchAndReplaceType">Type of the search and replace.</param>
        /// <param name="limit">The limit of how many to entities to keep.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns><c>true</c> if the operation was successful, <c>false</c> otherwise.</returns>
        public static bool DeleteOlderEntries(SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, int limit,
                                              FileSession fileSession)
        {
            try
            {
                ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.RemoveRange(
                    ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.Where(f =>
                                                                                     f.Session.SessionName == fileSession.SessionName &&
                                                                                     f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) &&
                                                                                     f.SearchAndReplaceType == searchAndReplaceType)
                    .Except(GetEntriesByLimit(searchAndReplaceSearchType, searchAndReplaceType, limit,
                                              fileSession)));

                return(true); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false); // failure..
            }
        }
コード例 #25
0
        /// <summary>
        /// Gets a collection the <see cref="Encoding"/> class instances corresponding to the given character set enumeration.
        /// </summary>
        /// <param name="characterSets">An enumeration value indicating which character set's encodings to get.</param>
        /// <returns>A collection of <see cref="Encoding"/> class instances for the given character set enumeration.</returns>
        public IEnumerable <Encoding> this[CharacterSets characterSets]
        {
            get
            {
                var result = new List <Encoding>();
                int idx    = internalList.FindIndex(f => f.Value == characterSets);
                if (idx != -1)
                {
                    foreach (int encodingNum in internalList[idx].Key)
                    {
                        try
                        {
                            var encoding = Encoding.GetEncoding(encodingNum);
                            result.Add(encoding);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogAction?.Invoke(ex);
                            try
                            {
                                var encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingNum);

                                if (encoding != null)
                                {
                                    result.Add(encoding);
                                }
                            }
                            catch (Exception exInner)
                            {
                                ExceptionLogAction?.Invoke(exInner);
                            }
                        }
                    }
                }

                return(result);
            }
        }
コード例 #26
0
        /// <summary>
        /// Opens the Windows PowerShell (powershell.exe) with a given specific path.
        /// </summary>
        /// <param name="path">The path to start the Windows PowerShell with.</param>
        /// <returns>True if the operation was successful; otherwise false.</returns>
        public static bool OpenPowerShellWithPath(string path)
        {
            try
            {
                var processStartInfo = new ProcessStartInfo()
                {
                    FileName         = "powershell.exe",
                    WorkingDirectory = path,
                    UseShellExecute  = false,
                    LoadUserProfile  = true,
                };

                System.Diagnostics.Process.Start(processStartInfo);

                return(true);
            }
            catch (Exception ex)
            {
                // log the exception if the action has a value..
                ExceptionLogAction?.Invoke(ex);
                return(false);
            }
        }
コード例 #27
0
        /// <summary>
        /// Initializes an external spell checker from a specified <see cref="Assembly"/>
        /// </summary>
        /// <param name="assembly">The assembly to load the spell checker from.</param>
        public static void SetSpellChecker(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                // again keep on trying..
                try
                {
                    // check the validity of the found type..
                    if (typeof(IExternalDictionarySource).IsAssignableFrom(type))
                    {
                        ScintillaSpellCheck.ExternalDictionary = (IExternalDictionarySource)Activator.CreateInstance(type);
                        ScintillaSpellCheck.ExternalDictionary.Initialize();

                        return;
                    }
                }
                catch (Exception ex)
                {
                    // log the exception..
                    ExceptionLogAction?.Invoke(ex);
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Return data acquired from an assembly in case a plug-in failed to initialize.
        /// </summary>
        /// <param name="assembly">The assembly of the plug-in.</param>
        /// <param name="fileNameFull">The full file name of the plug-in assembly.</param>
        /// <returns>A <see cref="Plugin"/> class instance based on the given arguments.</returns>
        public static Plugin InvalidPlugin(Assembly assembly, string fileNameFull)
        {
            try
            {
                string description = string.Empty;
                if (assembly != null)
                {
                    description = assembly.FullName;
                }

                // create a result based on the given parameters..
                var result = new Plugin
                {
                    FileNameFull      = fileNameFull,
                    FileName          = Path.GetFileName(fileNameFull),
                    FilePath          = Path.GetDirectoryName(fileNameFull),
                    PluginName        = "Unknown",
                    PluginDescription = description,
                    IsActive          = false,
                    PluginInstalled   = DateTime.Now,
                    LoadFailures      = 1,
                    PluginVersion     = VersionStringFromAssembly(assembly),
                };

                // set the version for the plug-in..
                AssemblyVersion.SetPluginUpdated(result, assembly);

                // return the result..
                return(result);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(null);
            }
        }
コード例 #29
0
        /// <summary>
        /// Creates a new instance of "this" class from a Notepad++ style definition XML file.
        /// </summary>
        /// <param name="fileName">Name of the XML file.</param>
        /// <returns>MarkColorsHelper.</returns>
        public static MarkColorsHelper FromFile(string fileName)
        {
            try
            {
                var markColors = MarkColors.FromFile(fileName);

                return(new MarkColorsHelper
                {
                    SmartHighlight = markColors.SmartHighLightingBackground,
                    Mark1Color = markColors.MarkOneBackground,
                    Mark2Color = markColors.MarkTwoBackground,
                    Mark3Color = markColors.MarkThreeBackground,
                    Mark4Color = markColors.MarkFourBackground,
                    Mark5Color = markColors.MarkFiveBackground,
                    CurrentLineBackground = markColors.CurrentLineBackground
                });
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);

                // ..and return default..
                return(default);
コード例 #30
0
        /// <summary>
        /// Executes a new instance of the current application with possible elevated permissions.
        /// </summary>
        /// <param name="elevated">If set to true try to run the process as administrator.</param>
        /// <param name="arguments">The arguments to be passed to the process.</param>
        /// <returns></returns>
        public static bool RunApplicationProcess(bool elevated, string arguments)
        {
            try
            {
                var processStartInfo = new ProcessStartInfo()
                {
                    FileName        = Application.ExecutablePath,
                    LoadUserProfile = true,
                    Verb            = elevated ? "runas" : null, // process elevation..
                    Arguments       = arguments
                };

                System.Diagnostics.Process.Start(processStartInfo);

                return(true);
            }
            catch (Exception ex)
            {
                // log the exception if the action has a value..
                ExceptionLogAction?.Invoke(ex);

                return(false);
            }
        }