ShowErrors() public static method

Shows an error to the user
public static ShowErrors ( Exception e, string message = null ) : void
e System.Exception
message string
return void
Exemplo n.º 1
0
        /// <summary>
        /// Gets an object with the latest release info
        /// </summary>
        public static void CheckForUpdate(bool alwaysGetFeedBack)
        {
            if (_latestReleaseInfo != null)
            {
                // we already checked and there is a new version
                if (!_warnedUserAboutUpdateAvail || alwaysGetFeedBack)
                {
                    NotifyUpdateAvailable();
                }
                return;
            }

            if (_checking)
            {
                return;
            }

            try {
                var wb = new WebServiceJson(WebServiceJson.WebRequestMethod.Get, Config.ReleasesApi);
                wb.TimeOut         = 3000;
                wb.OnRequestEnded += json => WbOnOnRequestEnded(json, alwaysGetFeedBack);
                wb.Execute();
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Error when checking for updates");
            }
        }
Exemplo n.º 2
0
        public MenuItem(AppliMenu menuToRegisterTo, string name, Image img, Action action, string itemId, string defaultKey, List <MenuItem> children)
        {
            ItemName  = name;
            ItemImage = img;

            // children?
            if (children != null)
            {
                ChildrenList = children;
                Children     = children.Select(item => (YamuiMenuItem)item).ToList();
            }

            // shortcut?
            if (!string.IsNullOrEmpty(itemId))
            {
                ItemId   = itemId;
                ItemSpec = defaultKey;

                if (Config.Instance.ShortCuts.ContainsKey(ItemId))
                {
                    ItemSpec = Config.Instance.ShortCuts[ItemId];
                    Config.Instance.ShortCuts.Remove(ItemId);
                }

                if (!string.IsNullOrEmpty(ItemSpec))
                {
                    Config.Instance.ShortCuts.Add(ItemId, ItemSpec);
                    Shortcut = new ShortcutKey(ItemSpec);
                    SubText  = ItemSpec;
                }

                // we set up a list of items to use in the shortcut page
                if (menuToRegisterTo != null)
                {
                    menuToRegisterTo.ShortcutableItemList.Add(this);
                }
            }

            // action?
            if (action != null)
            {
                OnClic = action;
                // We set the Do() action, which is the "go through" action when the OnClic action is activated
                Do = () => {
                    if (OnClic != null)
                    {
                        try {
                            OnClic();
                        } catch (Exception e) {
                            ErrorHandler.ShowErrors(e, "Error in : " + ItemName);
                        }
                    }
                };
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Call this method to save the content of the config.instance into an .xml file
 /// </summary>
 public static void Save()
 {
     try {
         if (!String.IsNullOrWhiteSpace(FileSettings))
         {
             Object2Xml <ConfigObject> .SaveToFile(_instance, FileSettings);
         }
     } catch (Exception e) {
         ErrorHandler.ShowErrors(e, "Error when saving settings");
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// init the instance by either reading the values from an existing file or
 /// creating one with the default values of the object
 /// </summary>
 /// <returns></returns>
 private static ConfigObject Init()
 {
     _instance = new ConfigObject();
     if (File.Exists(FileSettings))
     {
         try {
             Object2Xml <ConfigObject> .LoadFromFile(_instance, FileSettings);
         } catch (Exception e) {
             ErrorHandler.ShowErrors(e, "Error when loading settings", FileSettings);
             _instance = new ConfigObject();
         }
     }
     return(_instance);
 }
Exemplo n.º 5
0
        /// <summary>
        /// check if the User Defined Language for "OpenEdgeABL" exists in the
        /// userDefineLang.xml file, if it does it updates it, if it doesn't exists it creates it and asks the user
        /// to restart Notepad++
        /// Can also only check and not install it by setting onlyCheckInstall to true
        /// </summary>
        public static bool InstallUdl(bool onlyCheckInstall = false)
        {
            var encoding    = TextEncodingDetect.GetFileEncoding(Config.FileNppUdlXml);
            var fileContent = File.Exists(Config.FileNppUdlXml) ? Utils.ReadAllText(Config.FileNppUdlXml, encoding) : @"<NotepadPlus />";
            var regex       = new Regex("<UserLang name=\"OpenEdgeABL\".*?</UserLang>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            var matches     = regex.Match(fileContent);

            if (matches.Success)
            {
                if (onlyCheckInstall)
                {
                    return(true);
                }
                // if it already exists in the file, delete the existing one
                fileContent = regex.Replace(fileContent, @"");
            }
            else
            {
                if (onlyCheckInstall)
                {
                    return(false);
                }
                // if it doesn't exist in the file
                UserCommunication.Notify("It seems to be the first time that you use this plugin.<br>In order to activate the syntax highlighting, you must restart notepad++.<br><br><i>Please note that if a document is opened at the next start, you will have to manually close/reopen it to see the changes.</i><br><br><b>Sorry for the inconvenience</b>!", MessageImg.MsgInfo, "Information", "Installing syntax highlighting");
            }
            if (fileContent.ContainsFast(@"<NotepadPlus />"))
            {
                fileContent = fileContent.Replace(@"<NotepadPlus />", "<NotepadPlus>\r\n" + DataResources.UDL + "\r\n</NotepadPlus>");
            }
            else
            {
                fileContent = fileContent.Replace(@"<NotepadPlus>", "<NotepadPlus>\r\n" + DataResources.UDL);
            }
            // write to userDefinedLang.xml
            try {
                Utils.FileWriteAllText(Config.FileNppUdlXml, fileContent, encoding);
            } catch (Exception e) {
                if (e is UnauthorizedAccessException)
                {
                    UserCommunication.Notify("<b>Couldn't access the file :</b><br>" + Config.FileNppUdlXml + "<br><br>This means i couldn't correctly applied the syntax highlighting feature!<br><br><i>Please make sure to allow write access to this file (Right click on file > Security > Check what's needed to allow total control to current user)</i>", MessageImg.MsgError, "Syntax highlighting", "Can't access userDefineLang.xml");
                }
                else
                {
                    ErrorHandler.ShowErrors(e, "Error while accessing userDefineLang.xml");
                }
                return(false);
            }
            return(true);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Show a given menu
        /// </summary>
        public static void ShowMenuAtCursor(List <YamuiMenuItem> menuList, string menuTitle, string menuLogo = "logo16x16", int minSize = 180)
        {
            try {
                // Close any already opened menu
                ForceCloseMenu();

                // open requested menu
                var copyMenuList = menuList.ToList();
                copyMenuList.Insert(0, new YamuiMenuItem {
                    IsSeparator = true
                });

                var menu = new YamuiMenu(Cursor.Position, copyMenuList, "<div class='contextMenuTitle'><img src='" + menuLogo + "' width='16' Height='16' style='padding-right: 5px; padding-top: 1px;'>" + menuTitle + "</span>", minSize);
                menu.Show();
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Error in ShowMenuAtCursor");
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Show a given menu
        /// </summary>
        public static void ShowMenu(List <YamuiMenuItem> menuList, string menuTitle, string menuLogo, bool showAtCursor = false, int minWidth = 250)
        {
            try {
                // Close any already opened menu
                ForceClose();

                if (menuLogo == null)
                {
                    menuLogo = Utils.GetNameOf(() => ImageResources.Logo16x16);
                }

                // open requested menu
                _popup = new YamuiMenu {
                    HtmlTitle        = "<div class='contextMenuTitle'><img src='" + menuLogo + "' width='16' Height='16' style='padding-right: 5px; padding-top: 1px;'>" + menuTitle + "</span>",
                    SpawnLocation    = Cursor.Position,
                    MenuList         = menuList,
                    DisplayNbItems   = true,
                    DisplayFilterBox = true,
                    FormMinSize      = new Size(minWidth, 0)
                };
                if (!showAtCursor)
                {
                    _popup.ParentWindowRectangle = WinApi.GetWindowRect(Npp.CurrentSci.Handle);
                }
                _popup.YamuiList.ShowTreeBranches = Config.Instance.ShowTreeBranches;
                _popup.ClicItemWrapper            = item => {
                    if (item.OnClic != null)
                    {
                        try {
                            item.OnClic(item);
                        } catch (Exception e) {
                            ErrorHandler.ShowErrors(e, "Error in : " + item.DisplayText);
                        }
                    }
                };
                _popup.Show(Npp.Win32Handle);
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Error in ShowMenuAtCursor");
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Called when the latest release download is done
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="asyncCompletedEventArgs"></param>
        private static void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
        {
            try {
                // Extract the .zip file
                if (Utils.ExtractAll(Config.FileLatestReleaseZip, Config.FolderUpdate))
                {
                    // check the presence of the plugin file
                    if (File.Exists(Config.FileDownloadedPlugin))
                    {
                        // set up the update so the .dll file downloaded replaces the current .dll
                        _3PUpdater.Instance.AddFileToMove(Config.FileDownloadedPlugin, AssemblyInfo.Location);

                        // if the release was containing a .pdb file, we want to copied it as well
                        if (File.Exists(Config.FileDownloadedPdb))
                        {
                            _3PUpdater.Instance.AddFileToMove(Config.FileDownloadedPdb, Path.Combine(Path.GetDirectoryName(AssemblyInfo.Location) ?? "", Path.GetFileName(Config.FileDownloadedPdb) ?? ""));
                        }

                        // write the version log
                        Utils.FileWriteAllText(Config.FileVersionLog, _latestReleaseInfo.body, Encoding.Default);

                        NotifyUpdateAvailable();
                    }
                    else
                    {
                        Utils.DeleteDirectory(Config.FolderUpdate, true);
                    }
                }
                else
                {
                    UserCommunication.Notify("I failed to unzip the following file : <br>" + Config.FileLatestReleaseZip + "<br>It contains the update for 3P, you will have to do a manual update.", MessageImg.MsgError, "Unzip", "Failed");
                }
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "On Download File Completed");
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Update the information of the conf list, using the given share directory
        /// </summary>
        public static void UpdateList(string distantShareDirectory)
        {
            try {
                // We get the latest info for each line
                bool sharedDirOk = false;
                if (!string.IsNullOrEmpty(distantShareDirectory) && Directory.Exists(distantShareDirectory))
                {
                    sharedDirOk = true;
                    Config.Instance.SharedConfFolder = distantShareDirectory;
                }

                StringBuilder updateMessage = new StringBuilder();

                // update each line of the list
                foreach (var confLine in List)
                {
                    // read the autoupdate status from the config
                    confLine.AutoUpdate = Config.Instance.AutoUpdateConfList.ContainsFast(confLine.Label);

                    confLine.LocalPath   = confLine.HandledItem;
                    confLine.DistantPath = sharedDirOk ? Path.Combine(distantShareDirectory, (confLine.IsDir ? Path.GetFileName(confLine.HandledItem.TrimEnd('\\')) : Path.GetFileName(confLine.HandledItem)) ?? "") : "";

                    confLine.LocalTime   = DateTime.Now;
                    confLine.DistantTime = DateTime.Now;

                    if (confLine.IsDir)
                    {
                        confLine.LocalExists   = Directory.Exists(confLine.LocalPath);
                        confLine.DistantExists = !string.IsNullOrEmpty(confLine.DistantPath) && Directory.Exists(confLine.DistantPath);

                        if (confLine.LocalExists)
                        {
                            confLine.LocalNbFiles = 0;
                            foreach (var file in Directory.GetFiles(confLine.LocalPath))
                            {
                                if (confLine.LocalNbFiles == 0)
                                {
                                    confLine.LocalTime = File.GetLastWriteTime(file);
                                }
                                else if (File.GetLastWriteTime(file).CompareTo(confLine.LocalTime) > 0)
                                {
                                    confLine.LocalTime = File.GetLastWriteTime(file);
                                }
                                confLine.LocalNbFiles++;
                            }
                        }

                        if (!string.IsNullOrEmpty(confLine.DistantPath) && confLine.DistantExists)
                        {
                            confLine.DistantNbFiles = 0;
                            foreach (var file in Directory.GetFiles(confLine.DistantPath))
                            {
                                if (confLine.DistantNbFiles == 0)
                                {
                                    confLine.DistantTime = File.GetLastWriteTime(file);
                                }
                                else if (File.GetLastWriteTime(file).CompareTo(confLine.DistantTime) > 0)
                                {
                                    confLine.DistantTime = File.GetLastWriteTime(file);
                                }
                                confLine.DistantNbFiles++;
                            }
                        }
                    }
                    else
                    {
                        confLine.LocalExists   = !string.IsNullOrEmpty(confLine.LocalPath) && File.Exists(confLine.LocalPath);
                        confLine.DistantExists = !string.IsNullOrEmpty(confLine.DistantPath) && File.Exists(confLine.DistantPath);

                        if (confLine.LocalExists)
                        {
                            confLine.LocalTime = File.GetLastWriteTime(confLine.LocalPath);
                        }

                        if (!string.IsNullOrEmpty(confLine.DistantPath) && confLine.DistantExists)
                        {
                            confLine.DistantTime = File.GetLastWriteTime(confLine.DistantPath);
                        }
                    }

                    // if the difference between the two dates are small, correct it (it sometimes happen, even when the files are strictly identical)
                    if (Math.Abs(confLine.LocalTime.Subtract(confLine.DistantTime).TotalSeconds) < 2)
                    {
                        confLine.LocalTime = confLine.DistantTime;
                    }

                    confLine.NeedUpdate = confLine.OnFetch != null && ((confLine.DistantExists && !confLine.LocalExists) || (confLine.LocalExists && confLine.DistantExists && confLine.DistantTime.CompareTo(confLine.LocalTime) > 0));

                    // the line needs to be autoupdated
                    if (confLine.AutoUpdate && confLine.NeedUpdate && confLine.OnFetch != null)
                    {
                        _silentUpdate = true;
                        confLine.OnFetch(confLine);
                        confLine.LocalExists  = true;
                        confLine.LocalTime    = confLine.DistantTime;
                        confLine.LocalNbFiles = confLine.DistantNbFiles;
                        confLine.NeedUpdate   = false;
                        _silentUpdate         = false;

                        if (updateMessage.Length == 0)
                        {
                            updateMessage.Append("The following configuration files have been updated from the shared folder:<br><br>");
                        }
                        updateMessage.Append("<div><b>" + confLine.Label + "</b></div>");
                    }
                }

                if (updateMessage.Length > 0)
                {
                    updateMessage.Append("<br><br><i>You can set which config file gets auto-updated in <a href='go'>the option page</a></i>");
                    UserCommunication.NotifyUnique("ExportConfUpdate", updateMessage.ToString(), MessageImg.MsgInfo, "Update notification", "Configuration auto-update", args => {
                        Appli.Appli.GoToPage(PageNames.ExportShareConf);
                        UserCommunication.CloseUniqueNotif("ExportConfUpdate");
                        args.Handled = true;
                    }, 10);
                }
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Error while fetching info on the distant files");
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Called when the gitub api for releases responses
        /// </summary>
        private static void WbOnOnRequestEnded(WebServiceJson webServiceJson, bool alwaysGetFeedBack)
        {
            try {
                if (webServiceJson.StatusCodeResponse == HttpStatusCode.OK && webServiceJson.ResponseException == null)
                {
                    Config.Instance.LastCheckUpdateOk = true;

                    // get the releases
                    var releases = webServiceJson.DeserializeArray <ReleaseInfo>();
                    if (releases != null && releases.Count > 0)
                    {
                        // sort by descring order
                        releases.Sort((o, o2) => o.tag_name.IsHigherVersionThan(o2.tag_name) ? -1 : 1);

                        var localVersion = AssemblyInfo.Version;
                        var outputBody   = new StringBuilder();
                        foreach (var release in releases)
                        {
                            if (string.IsNullOrEmpty(release.tag_name))
                            {
                                continue;
                            }

                            // For each version higher than the local one, append to the release body
                            // Will be used to display the version log to the user
                            if (release.tag_name.IsHigherVersionThan(localVersion) &&
                                (Config.Instance.UserGetsPreReleases || !release.prerelease) &&
                                release.assets != null && release.assets.Count > 0 && release.assets.Exists(asset => asset.name.EqualsCi(Config.FileGitHubAssetName)))
                            {
                                // in case something is undefined (but shouldn't happen)
                                if (string.IsNullOrEmpty(release.tag_name))
                                {
                                    release.tag_name = "vX.X.X.X";
                                }
                                if (string.IsNullOrEmpty(release.name))
                                {
                                    release.name = "unknown";
                                }
                                if (string.IsNullOrEmpty(release.body))
                                {
                                    release.body = "...";
                                }
                                if (string.IsNullOrEmpty(release.published_at))
                                {
                                    release.published_at = DateTime.Now.ToString(CultureInfo.CurrentCulture);
                                }

                                // h1
                                outputBody.AppendLine("## " + release.tag_name + " : " + release.name + " ##\n\n");
                                // body
                                outputBody.AppendLine(release.body + "\n\n");

                                // the first higher release encountered is the latest
                                if (_latestReleaseInfo == null)
                                {
                                    _latestReleaseInfo = release;
                                }
                            }
                        }

                        // There is a distant version higher than the local one
                        if (_latestReleaseInfo != null)
                        {
                            // to display all the release notes
                            _latestReleaseInfo.body = outputBody.ToString();

                            // delete existing dir
                            Utils.DeleteDirectory(Config.FolderUpdate, true);

                            Utils.DownloadFile(_latestReleaseInfo.assets.First(asset => asset.name.EqualsCi(Config.FileGitHubAssetName)).browser_download_url, Config.FileLatestReleaseZip, OnDownloadFileCompleted);
                        }
                        else if (alwaysGetFeedBack)
                        {
                            UserCommunication.NotifyUnique("UpdateChecked", "Congratulations! You already possess the latest <b>" + (!Config.Instance.UserGetsPreReleases && !AssemblyInfo.IsPreRelease ? "stable" : "beta") + "</b> version of 3P!", MessageImg.MsgOk, "Update check", "You own the version " + AssemblyInfo.Version, null);
                        }
                    }
                }
                else
                {
                    // failed to retrieve the list
                    if (alwaysGetFeedBack || Config.Instance.LastCheckUpdateOk)
                    {
                        UserCommunication.NotifyUnique("ReleaseListDown", "For your information, I couldn't manage to retrieve the latest published version on github.<br><br>A request has been sent to :<br>" + Config.ReleasesApi.ToHtmlLink() + "<br>but was unsuccessul, you might have to check for a new version manually if this happens again.", MessageImg.MsgHighImportance, "Couldn't reach github", "Connection failed", null);
                    }
                    Config.Instance.LastCheckUpdateOk = false;

                    // check if there is an update available in the Shared config folder
                    if (!string.IsNullOrEmpty(Config.Instance.SharedConfFolder) && Directory.Exists(Config.Instance.SharedConfFolder))
                    {
                        var potentialUpdate = Path.Combine(Config.Instance.SharedConfFolder, AssemblyInfo.AssemblyName);

                        // if the .dll exists, is higher version and (the user get beta releases or it's a stable release)
                        if (File.Exists(potentialUpdate) &&
                            Utils.GetDllVersion(potentialUpdate).IsHigherVersionThan(AssemblyInfo.Version) &&
                            (Config.Instance.UserGetsPreReleases || Utils.GetDllVersion(potentialUpdate).EndsWith(".0")))
                        {
                            // copy to local update folder and warn the user
                            if (Utils.CopyFile(potentialUpdate, Config.FileDownloadedPlugin))
                            {
                                _latestReleaseInfo = new ReleaseInfo {
                                    name         = "Updated from shared directory",
                                    tag_name     = Utils.GetDllVersion(Config.FileDownloadedPlugin),
                                    prerelease   = Utils.GetDllVersion(Config.FileDownloadedPlugin).EndsWith(".1"),
                                    published_at = "???",
                                    html_url     = Config.UrlCheckReleases
                                };

                                // write the version log
                                Utils.FileWriteAllText(Config.FileVersionLog, @"This version has been updated from the shared directory" + Environment.NewLine + Environment.NewLine + @"Find more information on this release [here](" + Config.UrlCheckReleases + @")", Encoding.Default);

                                // set up the update so the .dll file downloaded replaces the current .dll
                                _3PUpdater.Instance.AddFileToMove(Config.FileDownloadedPlugin, AssemblyInfo.Location);

                                NotifyUpdateAvailable();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Error when checking the latest release ");
            }

            _checking = false;
        }