Пример #1
0
        private void ExecuteDeploymentHook()
        {
            // launch the compile process for the current file
            if (File.Exists(Config.FileDeploymentHook))
            {
                _executingHook = true;

                try {
                    var hookExec = new ProExecution {
                        DeploymentStep       = _currentStep,
                        DeploymentSourcePath = _currentProfile.SourceDirectory
                    };
                    if (hookExec.Do(ExecutionType.DeploymentHook))
                    {
                        hookExec.Process.WaitForExit();

                        var fileInfo = new FileInfo(hookExec.LogPath);
                        if (fileInfo.Length > 0)
                        {
                            // the .log is not empty, maybe something went wrong in the runner, display errors
                            UserCommunication.Notify(
                                "Something went wrong while executing the deployment hook procedure:<br>" + Config.FileDeploymentHook.ToHtmlLink() + "<br>The following problems were logged :" +
                                Utils.ReadAndFormatLogToHtml(hookExec.LogPath), MessageImg.MsgError,
                                "Deployment hook procedure", "Execution failed");
                            _hookProcedureErrors.Append("The execution for step " + _currentStep + " returned the following errors :" + Utils.ReadAndFormatLogToHtml(hookExec.LogPath));
                        }
                    }
                } finally {
                    _executingHook = false;
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Should be called to extract the database info from the current environnement
        /// </summary>
        public static void FetchCurrentDbInfo(Action onExtractionDone)
        {
            try {
                // dont extract 2 db at once
                if (_isExtracting)
                {
                    UserCommunication.Notify("Already fetching info for another environment, please wait the end of the previous execution!", MessageImg.MsgWarning, "Database info", "Extracting database structure", 5);
                    return;
                }

                // save the filename of the output database info file for this environment
                UserCommunication.Notify("Now fetching info on all the connected databases for the current environment<br>You will be warned when the process is over", MessageImg.MsgInfo, "Database info", "Extracting database structure", 5);

                var exec = new ProExecution {
                    OnExecutionEnd         = execution => _isExtracting = false,
                    OnExecutionOk          = ExtractionDoneOk,
                    NeedDatabaseConnection = true,
                    ExtractDbOutputPath    = GetOutputName
                };
                _onExtractionDone = onExtractionDone;
                _isExtracting     = exec.Do(ExecutionType.Database);
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "FetchCurrentDbInfo");
            }
        }
Пример #3
0
        /// <summary>
        /// Called on Npp shutdown
        /// </summary>
        internal static void DoNppShutDown()
        {
            try {
                if (OnShutDown != null)
                {
                    OnShutDown();
                }

                // clean up timers
                ReccurentAction.CleanAll();
                DelayedAction.CleanAll();

                // export modified conf
                FileTag.Export();

                // save config (should be done but just in case)
                CodeExplorer.UpdateMenuItemChecked();
                FileExplorer.UpdateMenuItemChecked();
                Config.Save();

                // remember the most used keywords
                Keywords.SaveRanking();

                // close every form
                AutoComplete.ForceClose();
                InfoToolTip.ForceClose();
                Appli.ForceClose();
                FileExplorer.ForceClose();
                CodeExplorer.ForceClose();
                UserCommunication.ForceClose();
                AppliMenu.ForceCloseMenu();
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Stop");
            }
        }
Пример #4
0
        /// <summary>
        /// Read a file in which each line represents a notification to display to the user,
        /// and displays each notification
        /// </summary>
        private void DisplayPostExecutionNotification()
        {
            // no notifications?
            if (string.IsNullOrEmpty(NotificationOutputPath) || !File.Exists(NotificationOutputPath))
            {
                return;
            }

            Utils.ForEachLine(NotificationOutputPath, null, (i, line) => {
                var fields = line.Split('\t').ToList();
                if (fields.Count == 6)
                {
                    MessageImg messageImg;
                    if (!Enum.TryParse(fields[1], true, out messageImg))
                    {
                        messageImg = MessageImg.MsgDebug;
                    }

                    if (string.IsNullOrEmpty(fields[5]))
                    {
                        UserCommunication.Notify(fields[0], messageImg, fields[2], fields[3], (int)fields[4].ConvertFromStr(typeof(int)));
                    }
                    else
                    {
                        UserCommunication.NotifyUnique(fields[5], fields[0], messageImg, fields[2], fields[3], args => {
                            UserCommunication.CloseUniqueNotif(fields[5]);
                        }, (int)fields[4].ConvertFromStr(typeof(int)));
                    }
                }
            });
        }
Пример #5
0
 public void Reload()
 {
     // read npp's stylers.xml file
     try {
         var widgetStyle = new NanoXmlDocument(Utils.ReadAllText(ConfXml.FileNppStylersXml)).RootNode["GlobalStyles"].SubNodes;
         WhiteSpaceFg             = GetColorInStylers(widgetStyle, "White space symbol", "fgColor");
         IndentGuideLineBg        = GetColorInStylers(widgetStyle, "Indent guideline style", "bgColor");
         IndentGuideLineFg        = GetColorInStylers(widgetStyle, "Indent guideline style", "fgColor");
         SelectionBg              = GetColorInStylers(widgetStyle, "Selected text colour", "bgColor");
         CaretLineBg              = GetColorInStylers(widgetStyle, "Current line background colour", "bgColor");
         CaretFg                  = GetColorInStylers(widgetStyle, "Caret colour", "fgColor");
         FoldMarginBg             = GetColorInStylers(widgetStyle, "Fold margin", "bgColor");
         FoldMarginFg             = GetColorInStylers(widgetStyle, "Fold margin", "fgColor");
         FoldMarginMarkerFg       = GetColorInStylers(widgetStyle, "Fold", "fgColor");
         FoldMarginMarkerBg       = GetColorInStylers(widgetStyle, "Fold", "bgColor");
         FoldMarginMarkerActiveFg = GetColorInStylers(widgetStyle, "Fold active", "fgColor");
     } catch (Exception e) {
         ErrorHandler.LogError(e, "Error parsing " + ConfXml.FileNppStylersXml);
         if (!_warnedAboutFailStylers)
         {
             _warnedAboutFailStylers = true;
             UserCommunication.Notify("Error while reading one of Notepad++ file :<div>" + ConfXml.FileNppStylersXml.ToHtmlLink() + "</div><br>The xml isn't correctly formatted, Npp manages to read anyway but you should correct it.", MessageImg.MsgError, "Error reading stylers.xml", "Xml read error");
         }
     }
 }
Пример #6
0
        /// <summary>
        /// Tries to re-indent the code of the whole document
        /// </summary>
        public static void CorrectCodeIndentation()
        {
            var canIndent = ParserHandler.AblParser.ParserErrors.Count == 0;

            UserCommunication.Notify(canIndent ? "This document can be reindented!" : "Oups can't reindent the code...<br>Log : <a href='" + Path.Combine(Config.FolderTemp, "lines.log") + "'>" + Path.Combine(Config.FolderTemp, "lines.log") + "</a>", canIndent ? MessageImg.MsgOk : MessageImg.MsgError, "Parser state", "Can indent?", 20);
            if (!canIndent)
            {
                StringBuilder x   = new StringBuilder();
                var           i   = 0;
                var           dic = ParserHandler.AblParser.LineInfo;
                while (dic.ContainsKey(i))
                {
                    x.AppendLine((i + 1) + " > " + dic[i].BlockDepth + " , " + dic[i].Scope + " , " + dic[i].Scope.Name);
                    //x.AppendLine(item.Key + " > " + item.Value.BlockDepth + " , " + item.Value.Scope);
                    i++;
                }
                Utils.FileWriteAllText(Path.Combine(Config.FolderTemp, "lines.log"), x.ToString());
            }

            // Can we indent? We can't if we didn't parse the code correctly or if there are grammar errors
            if (canIndent)
            {
            }
            else
            {
                UserCommunication.NotifyUnique("FormatDocumentFail", "This action can't be executed right now because it seems that your document contains grammatical errors.<br><br><i>If the code compiles sucessfully then i failed to parse your document correctly, please make sure to create an issue on the project's github and (if possible) include the incriminating code so i can fix this problem : <br><a href='#about'>Open the about window to get the github url</a>", MessageImg.MsgRip, "Format document", "Incorrect grammar", args => {
                    Appli.Appli.GoToPage(PageNames.Welcome);
                    UserCommunication.CloseUniqueNotif("FormatDocumentFail");
                }, 20);
            }
        }
Пример #7
0
 /// <summary>
 /// Move a file, ensures the user gets a feedback is something goes wrong
 /// return true if ok, false otherwise
 /// </summary>
 public static bool MoveFile(string sourceFile, string targetFile, bool silent = false)
 {
     try {
         if (!File.Exists(sourceFile))
         {
             if (!silent)
             {
                 UserCommunication.Notify("There was a problem when trying to move a file, the source doesn't exist :<br>" + sourceFile, MessageImg.MsgError, "Move file", "Couldn't find source file");
             }
             return(false);
         }
         if (sourceFile.Equals(targetFile))
         {
             return(true);
         }
         File.Delete(targetFile);
         File.Move(sourceFile, targetFile);
     } catch (Exception e) {
         if (!silent)
         {
             UserCommunication.Notify("There was a problem when i tried to write the following file:<br>" + targetFile.ToHtmlLink() + "<br><br><i>Please make sure that you have the privileges to write in the targeted directory / file</i>" + "<div class='AlternatBackColor' style='padding: 5px; margin: 5px;'>\"" + e.Message + "\"</div>", MessageImg.MsgError, "Move file", "Couldn't write target file");
         }
         return(false);
     }
     return(true);
 }
Пример #8
0
        /// <summary>
        /// Move a directory, ensures the user gets a feedback is something goes wrong
        /// returns true if ok, false otherwise
        /// </summary>
        public static bool MoveDirectory(string sourceFolder, string targetFolder, bool deleteExistingTarget = false)
        {
            try {
                sourceFolder = Path.GetFullPath(sourceFolder);
                targetFolder = Path.GetFullPath(targetFolder);
                if (!Directory.Exists(sourceFolder))
                {
                    UserCommunication.Notify("There was a problem when trying to move a folder, the source doesn't exist :<br>" + sourceFolder, MessageImg.MsgError, "Copy folder", "Couldn't find source folder");
                    return(false);
                }
                if (deleteExistingTarget)
                {
                    DeleteDirectory(targetFolder, true);
                }

                Directory.CreateDirectory(targetFolder);

                //Copy all the files & Replaces any files with the same name
                foreach (string newPath in Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories).ToList())
                {
                    var target = newPath.Replace(sourceFolder, targetFolder);
                    CreateDirectory(Path.GetDirectoryName(target));
                    File.Move(newPath, target);
                }
            } catch (Exception e) {
                UserCommunication.Notify("There was a problem when i tried to move the following folder:<br>" + targetFolder.ToHtmlLink() + "<br><br><i>Please make sure that you have the privileges to write in the targeted directory</i>" + "<div class='AlternatBackColor' style='padding: 5px; margin: 5px;'>\"" + e.Message + "\"</div>", MessageImg.MsgError, "Move folder", "Couldn't write target folder");
                return(false);
            }
            return(true);
        }
Пример #9
0
        // called when the compilation ended
        private void OnCompilationEnd(DeploymentHandler proDeployment)
        {
            Task.Factory.StartNew(() => {
                this.SafeInvoke(page => {
                    // get rid of the timer
                    if (_progressTimer != null)
                    {
                        _progressTimer.Stop();
                        _progressTimer.Dispose();
                        _progressTimer = null;
                    }
                    ResetScreen();
                    UpdateReport(_proDeployment.FormatDeploymentReport());
                    btReport.Visible = true;

                    // notify the user
                    if (!_proDeployment.HasBeenCancelled)
                    {
                        UserCommunication.NotifyUnique("ReportAvailable", "The requested deployment is over,<br>please check the generated report to see the result :<br><br><a href= '#'>Click here to see the report</a>", MessageImg.MsgInfo, "Deploy your application", "Report available", args => {
                            Appli.GoToPage(PageNames.MassCompiler);
                            UserCommunication.CloseUniqueNotif("ReportAvailable");
                        }, Appli.IsFocused() ? 10 : 0);
                    }
                });
            });
        }
Пример #10
0
        /// <summary>
        /// Should be called to extract the database info from the current environnement
        /// </summary>
        public void FetchCurrentDbInfo(Action onExtractionDone, string outDumpFilePath)
        {
            try {
                // save the filename of the output database info file for this environment
                UserCommunication.Notify("Now fetching info on all the connected databases for the current environment.<br>You will be warned when the process is over.", MessageImg.MsgInfo, "Database info", "Extracting database structure", 5);

                var exec = new ProExecutionDatabase {
                    NeedDatabaseConnection = true
                };
                exec.OnExecutionOk += execution => {
                    // copy the dump to the folder database
                    if (Utils.CopyFile(((ProExecutionDatabase)execution).OutputPath, outDumpFilePath))
                    {
                        // update info
                        UpdateDatabaseInfo();
                        UserCommunication.Notify("A database structure has been extracted successfully.<br>The auto-completion has been updated!", MessageImg.MsgOk, "Database info", "Extraction done", 10);
                        if (onExtractionDone != null)
                        {
                            onExtractionDone();
                        }
                    }
                };
                exec.Start();
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "FetchCurrentDbInfo");
            }
        }
Пример #11
0
 /// <summary>
 /// Gets an object with the latest release info
 /// </summary>
 private void CheckForUpdate(bool alwaysShowNotifications)
 {
     if (RestartNeeded && Updater.LatestReleaseInfo != null && (CheckRegularlyAction == null || CheckRegularlyAction.HasBeenDisposed))
     {
         // we already checked and there is a new version, we can't do an update until a restart of n++
         if (alwaysShowNotifications)
         {
             NotifyUpdateAvailable(Updater);
         }
     }
     else
     {
         AlwaysShowNotifications = alwaysShowNotifications;
         Updater.GetPreReleases  = Config.Instance.UserGetsPreReleases;
         Updater.Proxy           = Config.Instance.GetWebClientProxy();
         if (!_updating)
         {
             _updating = true;
             Updater.CheckForUpdates();
         }
         else if (alwaysShowNotifications)
         {
             UserCommunication.NotifyUnique("Update" + UpdatedSoftName, "Please wait, " + UpdatedSoftName + " is being updated.<br>You will be informed when it is done", MessageImg.MsgInfo, UpdatedSoftName + " updater", "Update in progress", null, 5);
         }
     }
 }
Пример #12
0
        private static void NotifyUpdateAvailable()
        {
            if (_latestReleaseInfo != null)
            {
                _updateAvailableOnRestart = true;

                UserCommunication.NotifyUnique("UpdateAvailable", @"Dear user, <br>
                    <br>
                    A new version of 3P has been downloaded!<br>
                    It will be automatically installed the next time you restart Notepad++<br>
                    <br>                   
                    Your version: <b>" + AssemblyInfo.Version + @"</b><br>
                    Distant version: <b>" + _latestReleaseInfo.tag_name + @"</b><br>
                    Release name: <b>" + _latestReleaseInfo.name + @"</b><br>
                    Available since: <b>" + _latestReleaseInfo.published_at + @"</b><br>" +
                                               "Release URL: <b>" + _latestReleaseInfo.html_url.ToHtmlLink() + @"</b><br>" +
                                               (_latestReleaseInfo.prerelease ? "<i>This distant release is a beta version</i><br>" : "") +
                                               (_3PUpdater.Instance.IsAdminRightsNeeded ? "<br><span class='SubTextColor'><i><b>3pUpdater.exe</b> will need administrator rights to replace your current 3P.dll file by the new release,<br>please click yes when you are asked to execute it</i></span>" : "") +
                                               "<br><br><b>" + "Restart".ToHtmlLink("Click here to restart now!") + @"</b>",
                                               MessageImg.MsgUpdate, "Update check", "An update is available",
                                               args => {
                    if (args.Link.Equals("Restart"))
                    {
                        args.Handled = true;
                        Npp.Restart();
                    }
                });

                // stop checking for more updates :)
                _checkEveryHourAction.Dispose();
            }
            _isChecking = false;
        }
Пример #13
0
        /// <summary>
        /// Called when a new release has been downloaded
        /// </summary>
        protected virtual void OnNewReleaseDownloaded(GitHubUpdater gitHubUpdater, string downloadedFile)
        {
            try {
                // Extract the .zip file
                if (Utils.ExtractAll(downloadedFile, FolderUnzip))
                {
                    // execute extra actions (for the 3P update for instance)
                    if (ExtraActionWhenDownloaded != null)
                    {
                        ExtraActionWhenDownloaded(gitHubUpdater);
                    }

                    NotifyUpdateAvailable(Updater);

                    if (gitHubUpdater.LatestReleaseInfo != null && !RestartNeeded)
                    {
                        Updater.LocalVersion = gitHubUpdater.LatestReleaseInfo.tag_name;
                    }

                    if (OnUpdateDone != null)
                    {
                        OnUpdateDone(this);
                    }
                }
                else
                {
                    UserCommunication.NotifyUnique("Update" + UpdatedSoftName, "Failed to unzip the following file : <br>" + downloadedFile.ToHtmlLink() + "<br>It contains the update for " + UpdatedSoftName + ", you will have to do a manual update." + HowToInstallManually, MessageImg.MsgError, UpdatedSoftName + " updater", "Unzip failed", null);
                }
            } finally {
                _updating = false;
            }
        }
Пример #14
0
        /// <summary>
        /// Called when the user saves the current document (just before it saves itself)
        /// </summary>
        public static void OnNppFileBeforeSaved()
        {
            // check for block that are too long and display a warning
            if (Abl.IsCurrentFileFromAppBuilder && !CurrentFileObject.WarnedTooLong)
            {
                var warningMessage    = new StringBuilder();
                var explorerItemsList = ParserHandler.ParserVisitor.ParsedExplorerItemsList;

                if (explorerItemsList != null)
                {
                    foreach (var codeExplorerItem in explorerItemsList.Where(codeExplorerItem => codeExplorerItem.Flag.HasFlag(CodeExplorerFlag.IsTooLong)))
                    {
                        warningMessage.AppendLine("<div><img src='IsTooLong'><img src='" + codeExplorerItem.Branch + "' style='padding-right: 10px'><a href='" + codeExplorerItem.GoToLine + "'>" + codeExplorerItem.DisplayText + "</a></div>");
                    }
                    if (warningMessage.Length > 0)
                    {
                        warningMessage.Insert(0, "<h2>Friendly warning :</h2>It seems that your file can be opened in the appbuilder as a structured procedure, but i detected that one or several procedure/function blocks contains more than " + Config.Instance.GlobalMaxNbCharInBlock + " characters. A direct consequence is that you won't be able to open this file in the appbuilder, it will generate errors and it will be unreadable. Below is a list of incriminated blocks :<br><br>");
                        warningMessage.Append("<br><i>To prevent this, reduce the number of chararacters in the above blocks, deleting dead code and trimming spaces is a good place to start!</i>");
                        var curPath = CurrentFilePath;
                        UserCommunication.NotifyUnique("AppBuilderLimit", warningMessage.ToString(), MessageImg.MsgHighImportance, "File saved", "Appbuilder limitations", args => {
                            Npp.Goto(curPath, Int32.Parse(args.Link));
                            UserCommunication.CloseUniqueNotif("AppBuilderLimit");
                        }, 20);
                        CurrentFileObject.WarnedTooLong = true;
                    }
                }
            }

            // for debug purposes, check if the document can be parsed
            if (Config.IsDevelopper && ParserHandler.AblParser.ParserErrors.Count > 0)
            {
                UserCommunication.Notify("The parser found erros on this file:<br>" + ProCodeFormat.GetParserErrorDescription(), MessageImg.MsgInfo, "Parser message", "Errors found", 3);
            }
        }
Пример #15
0
        public static bool GenerateNewCommunications(Guid userId)
        {
            var newComm = false;

            using (var dbContext = new ActivityTrackerDbContext())
            {
                var comms     = dbContext.Communications.ToList();
                var userComms = dbContext.UserCommunications.Where(x => x.UserID == userId).ToList();

                foreach (var comm in comms)
                {
                    if (checkIfUserHasCommunication(userId, comm, userComms))
                    {
                        var userComm = new UserCommunication();
                        userComm.CommunicationID = comm.CommunicationID;
                        userComm.UserID          = userId;
                        userComm.Date            = DateTime.UtcNow;
                        dbContext.UserCommunications.Add(userComm);

                        newComm = true;
                    }
                }
                dbContext.SaveChanges();
            }

            return(newComm);
        }
Пример #16
0
        /// <summary>
        /// Called on Npp shutdown
        /// </summary>
        internal static void DoNppShutDown()
        {
            try {
                if (OnShutDown != null)
                {
                    OnShutDown();
                }

                // clean up timers
                RecurentAction.CleanAll();
                DelayedAction.CleanAll();
                AsapButDelayableAction.CleanAll();

                // Triggered when the resolution of an assembly fails, gives us the opportunity to feed the required assembly
                AppDomain.CurrentDomain.AssemblyResolve -= LibLoader.AssemblyResolver;

                // catch unhandled errors to log them
                AppDomain.CurrentDomain.UnhandledException -= ErrorHandler.UnhandledErrorHandler;
                Application.ThreadException           -= ErrorHandler.ThreadErrorHandler;
                TaskScheduler.UnobservedTaskException -= ErrorHandler.UnobservedErrorHandler;

                // unsubscribe to static events
                ProEnvironment.OnEnvironmentChange -= FileExplorer.Instance.RebuildFileList;
                ProEnvironment.OnEnvironmentChange -= DataBase.Instance.UpdateDatabaseInfo;
                ProEnvironment.OnEnvironmentChange -= ParserHandler.ClearStaticData;

                Keywords.Instance.OnImport         -= AutoCompletion.SetStaticItems;
                DataBase.Instance.OnDatabaseUpdate -= AutoCompletion.SetStaticItems;
                AutoCompletion.OnUpdateStaticItems -= ParserHandler.UpdateKnownStaticItems;

                ParserHandler.OnEndSendCompletionItems -= AutoCompletion.SetDynamicItems;
                ParserHandler.OnStart -= CodeExplorer.Instance.OnStart;
                ParserHandler.OnEndSendParserItems       -= CodeExplorer.Instance.OnParseEndParserItems;
                ParserHandler.OnEndSendCodeExplorerItems -= CodeExplorer.Instance.OnParseEndCodeExplorerItems;
                ParserHandler.OnEnd -= CodeExplorer.Instance.OnParseEnd;

                ProExecutionHandleCompilation.OnEachCompilationOk -= FilesInfo.ProExecutionHandleCompilationOnEachCompilationOk;

                // export modified conf
                FileTag.Export();

                // save config (should be done but just in case)
                Config.Save();

                // remember the most used keywords
                Keywords.Instance.SaveRanking();

                // close every form
                FileExplorer.Instance.ForceClose();
                CodeExplorer.Instance.ForceClose();
                AutoCompletion.ForceClose();
                InfoToolTip.ForceClose();
                Appli.ForceClose();
                UserCommunication.ForceClose();
                AppliMenu.ForceClose();
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Stop");
            }
        }
Пример #17
0
        public static void MeasureIt(Action toMeasure, string id = null)
        {
            var watch = Stopwatch.StartNew();

            toMeasure();
            watch.Stop();
            UserCommunication.Notify((id ?? "") + watch.ElapsedMilliseconds + "ms");
        }
Пример #18
0
 /// <summary>
 /// Deletes the file corresponding to the current database (if it exists)
 /// </summary>
 public static void DeleteCurrentDbInfo()
 {
     if (!Utils.DeleteFile(GetCurrentDumpPath))
     {
         UserCommunication.Notify("Couldn't delete the current database info stored in the file :<br>" + GetCurrentDumpPath.ToHtmlLink(), MessageImg.MsgError, "Delete failed", "Current database info");
     }
     UpdateDatabaseInfo();
 }
Пример #19
0
 /// <summary>
 /// To call when the user click on an update button
 /// </summary>
 public static void CheckForUpdate()
 {
     if (!Utils.IsSpamming("updates", 1000))
     {
         UserCommunication.Notify("Now checking for updates, you will be notified when it's done", MessageImg.MsgInfo, "Update", "Update check", 5);
         Task.Factory.StartNew(() => { CheckForUpdate(false); });
     }
 }
Пример #20
0
 /// <summary>
 /// Allows to kill the process of the currently running Progress.exe (if any, for the current file)
 /// </summary>
 public static void KillCurrentProcess()
 {
     if (Plug.CurrentFileObject.ProgressExecution != null)
     {
         Plug.CurrentFileObject.ProgressExecution.KillProcess();
         UserCommunication.CloseUniqueNotif("KillExistingProcess");
         OnSingleExecutionEnd(Plug.CurrentFileObject.ProgressExecution);
     }
 }
Пример #21
0
 /// <summary>
 /// Allows to kill the process of the currently running Progress.exe (if any, for the current file)
 /// </summary>
 public static void KillCurrentProcess()
 {
     if (OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution != null)
     {
         OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution.KillProcess();
         UserCommunication.CloseUniqueNotif("KillExistingProcess");
         OnSingleExecutionEnd(OpenedFilesInfo.CurrentOpenedFileInfo.ProgressExecution);
     }
 }
Пример #22
0
        /// <summary>
        /// Called by the process's thread when it is over, execute the ProcessOnExited event
        /// </summary>
        private void ProcessOnExited(object sender, EventArgs eventArgs)
        {
            // end of execution action
            if (OnExecutionEnd != null)
            {
                OnExecutionEnd(this);
            }

            // if log not found then something is messed up!
            if (string.IsNullOrEmpty(LogPath) || !File.Exists(LogPath))
            {
                UserCommunication.NotifyUnique("ExecutionFailed", "Something went terribly wrong while using progress!<br><div>Below is the <b>command line</b> that was executed:</div><div class='ToolTipcodeSnippet'>" + ProgressWin32 + " " + ExeParameters + "</div><b>Temporary directory :</b><br>" + LocalTempDir.ToHtmlLink() + "<br><br><i>Did you messed up the prowin32.exe command line parameters in the <a href='go'>set environment page</a> page?</i>", MessageImg.MsgError, "Critical error", "Action failed", args => {
                    if (args.Link.Equals("go"))
                    {
                        Appli.Appli.GoToPage(PageNames.SetEnvironment);
                        UserCommunication.CloseUniqueNotif("ExecutionFailed");
                        args.Handled = true;
                    }
                }, 0, 600);

                ExecutionFailed = true;
            }

            // if this file exists, then the connect statement failed, warn the user
            if (File.Exists(DatabaseConnectionLog) && new FileInfo(DatabaseConnectionLog).Length > 0)
            {
                UserCommunication.NotifyUnique("ConnectFailed", "Failed to connect to the progress database!<br>Verify / correct the connection info <a href='go'>in the environment page</a> and try again<br><br><i>Also, make sure that the database for the current environment is connected!</i><br><br>Below is the error returned while trying to connect to the database : " + Utils.ReadAndFormatLogToHtml(DatabaseConnectionLog), MessageImg.MsgRip, "Database connection", "Connection failed", args => {
                    if (args.Link.Equals("go"))
                    {
                        Appli.Appli.GoToPage(PageNames.SetEnvironment);
                        UserCommunication.CloseUniqueNotif("ConnectFailed");
                        args.Handled = true;
                    }
                }, NeedDatabaseConnection ? 0 : 10, 600);

                ConnectionFailed = true;
            }

            // end of successful/unsuccessful execution action
            if (ExecutionFailed || (ConnectionFailed && NeedDatabaseConnection))
            {
                if (OnExecutionFailed != null)
                {
                    OnExecutionFailed(this);
                }
            }
            else
            {
                if (OnExecutionOk != null)
                {
                    OnExecutionOk(this);
                }

                // display a custom post execution notification if needed
                DisplayPostExecutionNotification();
            }
        }
Пример #23
0
        /// <summary>
        /// Called after the execution of run/compile/check/prolint
        /// </summary>
        public static void OnSingleExecutionOk(ProExecutionHandleCompilation lastExec, List <FileToCompile> filesToCompile, List <FileToDeploy> filesToDeploy)
        {
            try {
                var treatedFile = lastExec.Files.First();
                CurrentOperation currentOperation;
                if (!Enum.TryParse(lastExec.ExecutionType.ToString(), true, out currentOperation))
                {
                    currentOperation = CurrentOperation.Run;
                }

                var isCurrentFile     = treatedFile.SourcePath.EqualsCi(Npp.CurrentFileInfo.Path);
                var otherFilesInError = false;
                int nbWarnings        = 0;
                int nbErrors          = 0;

                // count number of warnings/errors, loop through files > loop through errors in each file
                foreach (var fileInError in filesToCompile.Where(file => file.Errors != null))
                {
                    foreach (var error in fileInError.Errors)
                    {
                        if (error.Level <= ErrorLevel.StrongWarning)
                        {
                            nbWarnings++;
                        }
                        else
                        {
                            nbErrors++;
                        }
                    }
                    otherFilesInError = otherFilesInError || !treatedFile.SourcePath.EqualsCi(fileInError.SourcePath);
                }

                // Prepare the notification content
                var notifTitle    = currentOperation.GetAttribute <CurrentOperationAttr>().Name;
                var notifImg      = (nbErrors > 0) ? MessageImg.MsgError : ((nbWarnings > 0) ? MessageImg.MsgWarning : MessageImg.MsgOk);
                var notifTimeOut  = (nbErrors > 0) ? 0 : ((nbWarnings > 0) ? 10 : 5);
                var notifSubtitle = lastExec.ExecutionType == ExecutionType.Prolint ? (nbErrors + nbWarnings) + " problem" + ((nbErrors + nbWarnings) > 1 ? "s" : "") + " detected" :
                                    (nbErrors > 0) ? nbErrors + " error" + (nbErrors > 1 ? "s" : "") + " found" :
                                    ((nbWarnings > 0) ? nbWarnings + " warning" + (nbWarnings > 1 ? "s" : "") + " found" :
                                     "Syntax correct");

                // when compiling, transferring .r/.lst to compilation dir
                if (filesToDeploy != null)
                {
                    filesToDeploy = lastExec.ProEnv.Deployer.DeployFiles(filesToDeploy, null, null);
                }

                // Notify the user, or not
                if (Config.Instance.CompileAlwaysShowNotification || !isCurrentFile || !Sci.GetFocus() || otherFilesInError)
                {
                    UserCommunication.NotifyUnique(treatedFile.SourcePath, "<div style='padding-bottom: 5px;'>Was " + currentOperation.GetAttribute <CurrentOperationAttr>().ActionText + " :</div>" + ProExecutionCompile.FormatCompilationResultForSingleFile(treatedFile.SourcePath, treatedFile, filesToDeploy), notifImg, notifTitle, notifSubtitle, null, notifTimeOut);
                }
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e, "Error in OnExecutionOk");
            }
        }
Пример #24
0
 private void BtDeleteOnButtonPressed(object sender, EventArgs buttonPressedEventArgs) {
     var answ = _unsafeDelete ? 0 : UserCommunication.Message("Do you really want to delete the current environment?", MessageImg.MsgQuestion, "Delete", "Confirmation", new List<string> {"Yes I do", "Yes don't ask again", "No, Cancel"});
     if (answ == 0 || answ == 1) {
         if (answ == 1)
             _unsafeDelete = true;
         _currentMode = ViewMode.Delete;
         if (Save())
             ToggleMode(ViewMode.Select);
     }
 }
Пример #25
0
 /// <summary>
 /// To call when the user click on an update button
 /// </summary>
 public void CheckForUpdate()
 {
     if (!Utils.IsSpamming(UpdatedSoftName + "update", 3000))
     {
         UserCommunication.NotifyUnique("Update" + UpdatedSoftName, "Checking for a new release from " + Updater.GitHubReleaseApi.ToHtmlLink("github.com", true) + ".<br>You will be notified when it's done.", MessageImg.MsgInfo, UpdatedSoftName + " updater", "Checking for updates...", null, 5);
         Task.Factory.StartNew(() => {
             CheckForUpdate(true);
         });
     }
 }
Пример #26
0
 /// <summary>
 /// File write all bytes
 /// </summary>
 public static bool FileWriteAllBytes(string path, byte[] bytes)
 {
     try {
         File.WriteAllBytes(path, bytes);
         return(true);
     } catch (Exception e) {
         UserCommunication.Notify("Unable to write the following file :<br>" + path + "<br>Please check that you have the appropriate rights on this folder" + "<div class='AlternatBackColor' style='padding: 5px; margin: 5px;'>\"" + e.Message + "\"</div>", MessageImg.MsgError, "Write file", "Failed");
     }
     return(false);
 }
Пример #27
0
        public static void ParseAllFiles()
        {
            // create unique temporary folder
            var    testDir  = Path.Combine(Npp.ConfigDirectory, "Tests", "ParseAllFiles_" + DateTime.Now.ToString("yy.MM.dd_HH-mm-ss-fff"));
            string outNotif = "";
            var    outFile  = Path.Combine(testDir, "out.txt");

            if (!Utils.CreateDirectory(testDir))
            {
                return;
            }

            var parserErrors = "";
            var watch2       = Stopwatch.StartNew();

            foreach (var file in Directory.EnumerateFiles(ProEnvironment.Current.BaseLocalPath, "*", SearchOption.AllDirectories))
            {
                if (file.TestAgainstListOfPatterns(Config.Instance.FilesPatternCompilable))
                {
                    string outStr = file + " >>> ";

                    var watch = Stopwatch.StartNew();

                    ProTokenizer proTokenizer = new ProTokenizer(Utils.ReadAllText(file));
                    outStr += "ProLexer (" + watch.ElapsedMilliseconds + " ms), ";

                    Parser parser = new Parser(proTokenizer, file, null, true, null);
                    outStr += "Parser (" + watch.ElapsedMilliseconds + " ms), ";

                    if (parser.ParserErrors != null && parser.ParserErrors.Count > 0)
                    {
                        outNotif     += file.ToHtmlLink() + "<br>";
                        parserErrors += file + "<br>" + parser.ParseErrorsInHtml + "<br>";
                    }

                    /*
                     * var parserVisitor = new ParserVisitor(true);
                     * parser.Accept(parserVisitor);
                     * outStr += "Visitor (" + watch.ElapsedMilliseconds + " ms)\r\n";
                     */

                    watch.Stop();

                    Utils.FileAppendAllText(outFile, outStr + "\r\n");
                }
            }

            Utils.FileAppendAllText(outFile, "\r\n\r\n" + parserErrors);

            watch2.Stop();

            Utils.FileAppendAllText(outFile, "\r\n\r\nTotal time : " + watch2.ElapsedMilliseconds);

            UserCommunication.Notify(outNotif + "<br>Done :<br>" + outFile.ToHtmlLink(), 0);
        }
Пример #28
0
        /// <summary>
        /// Called before the download starts
        /// </summary>
        protected virtual void MainUpdaterOnStartingUpdate(GitHubUpdater gitHubUpdater, GitHubUpdater.ReleaseInfo releaseInfo, GitHubUpdater.StartingDownloadEvent e)
        {
            Config.Instance.TechnicalLastWebserviceCallOk = true;

            DelayedAction.StartNew(2000, () => {
                if (_updating && !UserCommunication.IsUniqueNotifShown("Update" + UpdatedSoftName))
                {
                    UserCommunication.NotifyUnique("Update" + UpdatedSoftName, "A newer version of " + UpdatedSoftName + " (" + releaseInfo.tag_name + ") has been found online.<br>It is being downloaded, you will be notified when the update is available.", MessageImg.MsgUpdate, UpdatedSoftName + " updater", "New version found", null, 5);
                }
            });
        }
Пример #29
0
        private bool ChooseName()
        {
            object name = string.Empty;

            if (UserCommunication.Input(ref name, "", MessageImg.MsgQuestion, "Save profile as...", "Enter a name for this profile") == 1 ||
                string.IsNullOrEmpty((string)name))
            {
                return(false);
            }
            DeploymentProfile.Current.Name = (string)name;
            return(true);
        }
Пример #30
0
        /// <summary>
        /// Tries to re-indent the code of the whole document
        /// </summary>
        public static void CorrectCodeIndentation()
        {
            // handle spam (1s min between 2 indent)
            if (Utils.IsSpamming("CorrectCodeIndentation", 1000))
            {
                return;
            }

            var parser = new Parser.Parser(Sci.Text, Npp.CurrentFile.Path, null, false);

            // in case of an incorrect document, warn the user
            var parserErrors = parser.ParseErrorsInHtml;

            if (!string.IsNullOrEmpty(parserErrors))
            {
                if (UserCommunication.Message("The internal parser of 3P has found inconsistencies in your document :<br>" + parserErrors + "<br>You can still try to format your code but the result is not guaranteed (worst case scenario you can press CTRL+Z).<br>Please confirm that you want to proceed", MessageImg.MsgQuestion, "Correct indentation", "Problems spotted", new List <string> {
                    "Continue", "Abort"
                }) != 0)
                {
                    return;
                }
            }

            var linesLogFile    = Path.Combine(Config.FolderTemp, "lines.log");
            var canIndentSafely = string.IsNullOrEmpty(parserErrors);

            // start indenting
            Sci.BeginUndoAction();

            StringBuilder x           = new StringBuilder();
            var           indentWidth = Sci.TabWidth;
            var           i           = 0;
            var           dic         = parser.LineInfo;

            while (dic.ContainsKey(i))
            {
                Sci.GetLine(i).Indentation = dic[i].BlockDepth * indentWidth;
                if (!canIndentSafely)
                {
                    x.AppendLine(i + 1 + " > " + dic[i].BlockDepth + " , " + dic[i].Scope.ScopeType + " , " + dic[i].Scope.Name);
                }
                i++;
            }
            Sci.EndUndoAction();

            // if we didn't parse the code correctly or if there are grammar errors
            if (!canIndentSafely)
            {
                Utils.FileWriteAllText(linesLogFile, x.ToString());
                UserCommunication.Notify("If the code compiles successfully and the document is incorrectly formatted, please make sure to create an issue on the project's github and (if possible) include the incriminating code so i can fix this problem : <br>" + Config.IssueUrl.ToHtmlLink() + (Config.IsDevelopper ? "<br><br>Lines report log :<br>" + linesLogFile.ToHtmlLink() : ""), MessageImg.MsgRip, "Correct indentation", "Incorrect grammar", null, 10);
            }
        }