Пример #1
0
            /// <summary>
            /// Applies new options to the config.xml and restart npp to take them into account
            /// </summary>
            /// <param name="options"></param>
            public void ApplyNewOptions(NppConfigXmlOptions options)
            {
                if (options == null)
                {
                    return;
                }

                var encoding    = TextEncodingDetect.GetFileEncoding(FileNppConfigXml);
                var fileContent = Utils.ReadAllText(FileNppConfigXml, encoding);

                fileContent = fileContent.Replace("autoCAction=\"" + AutocompletionMode + "\"", "autoCAction=\"" + (options.DisableDefaultAutocompletion ? 0 : 3) + "\"");
                fileContent = fileContent.Replace("name=\"Backup\" action=\"" + BackupMode + "\"", "name=\"Backup\" action=\"" + (options.EnableBackupOnSave ? 2 : 0) + "\"");
                fileContent = fileContent.Replace("enableMultiSelection=\"" + (MultiSelectionEnabled ? "yes" : "no") + "\"", "enableMultiSelection=\"" + (options.EnableMultiSelection ? "yes" : "no") + "\"");
                if (options.EnableBackupOnSave && (string.IsNullOrEmpty(CustomBackupDirectory) || !BackupUseCustomDir))
                {
                    fileContent = fileContent.Replace("options.EnableBackupOnSave", "enableMultiSelection=\"" + (options.EnableMultiSelection ? "yes" : "no") + "\"");
                    var regex   = new Regex(@"useCustumDir=""\w*?""\s+dir=""[^""]*?""", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                    var matches = regex.Match(fileContent);
                    if (matches.Success)
                    {
                        fileContent = regex.Replace(fileContent, "useCustumDir=\"yes\" dir=\"" + Path.Combine(BackupDirectory, "saved") + "\"");
                    }
                }
                var configCopyPath = Path.Combine(Config.FolderUpdate, "config.xml");

                if (!Utils.FileWriteAllText(configCopyPath, fileContent, encoding))
                {
                    return;
                }

                // replace default config by its copy on npp shutdown
                _3PUpdater.Instance.AddFileToMove(configCopyPath, FileNppConfigXml);

                Restart();
            }
Пример #2
0
        public static Encoding DetectTextFileEncoding(string pFilePath)
        {
            Encoding rtnEnc;

            byte[]             tempByte = null;
            TextEncodingDetect ted      = new TextEncodingDetect();

            TextEncodingDetect.Encoding tedEnc;

            tempByte = File.ReadAllBytes(pFilePath);
            tedEnc   = ted.DetectEncoding(tempByte, tempByte.Length);

            switch (tedEnc)
            {
            case TextEncodingDetect.Encoding.Utf8Bom:
            case TextEncodingDetect.Encoding.Utf8Nobom:
                rtnEnc = Encoding.UTF8;
                break;

            default:
                rtnEnc = Encoding.Default;
                break;
            }

            return(rtnEnc);
        }
Пример #3
0
    public static int Main(string[] args)
    {
        Console.WriteLine();

        if (args.Length != 1)
        {
            Console.WriteLine("Usage: TextEncodingDetect.exe <filename>");
            return(1);
        }

        // Read in the file in binary
        byte[] buffer;

        try
        {
            buffer = File.ReadAllBytes(args[0]);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return(1);
        }

        // Detect encoding
        var textDetect = new TextEncodingDetect();

        TextEncodingDetect.Encoding encoding = textDetect.DetectEncoding(buffer, buffer.Length);

        Console.Write("Encoding: ");
        if (encoding == TextEncodingDetect.Encoding.None)
        {
            Console.WriteLine("Binary");
        }
        else if (encoding == TextEncodingDetect.Encoding.Ascii)
        {
            Console.WriteLine("ASCII (chars in the 0-127 range)");
        }
        else if (encoding == TextEncodingDetect.Encoding.Ansi)
        {
            Console.WriteLine("ANSI (chars in the range 0-255 range)");
        }
        else if (encoding == TextEncodingDetect.Encoding.Utf8Bom || encoding == TextEncodingDetect.Encoding.Utf8Nobom)
        {
            Console.WriteLine("UTF-8");
        }
        else if (encoding == TextEncodingDetect.Encoding.Utf16LeBom || encoding == TextEncodingDetect.Encoding.Utf16LeNoBom)
        {
            Console.WriteLine("UTF-16 Little Endian");
        }
        else if (encoding == TextEncodingDetect.Encoding.Utf16BeBom || encoding == TextEncodingDetect.Encoding.Utf16BeNoBom)
        {
            Console.WriteLine("UTF-16 Big Endian");
        }

        return(0);
    }
Пример #4
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);
        }
        /// <summary>
        /// Reads arguments from a progress parameter file.
        /// </summary>
        /// <param name="pfPath"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public UoeProcessArgs AppendFromPfFilePath(string pfPath, Encoding encoding = null)
        {
            if (!File.Exists(pfPath))
            {
                return(null);
            }
            var tokenizer = UoePfTokenizer.New(File.ReadAllText(pfPath, encoding ?? TextEncodingDetect.GetFileEncoding(pfPath)));

            while (tokenizer.MoveToNextToken())
            {
                var token = tokenizer.PeekAtToken(0);
                if (token is ParameterStringTokenOption || token is ParameterStringTokenValue)
                {
                    Append(token.Value);
                }
            }
            return(this);
        }
Пример #6
0
        protected override bool SetExecutionInfo()
        {
            var           fileToExecute = "hook_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
            StringBuilder hookProc      = new StringBuilder();

            hookProc.AppendLine("&SCOPED-DEFINE ApplicationName " + ProEnv.Name.PreProcQuoter());
            hookProc.AppendLine("&SCOPED-DEFINE ApplicationSuffix " + ProEnv.Suffix.PreProcQuoter());
            hookProc.AppendLine("&SCOPED-DEFINE StepNumber " + DeploymentStep);
            hookProc.AppendLine("&SCOPED-DEFINE SourceDirectory " + DeploymentSourcePath.PreProcQuoter());
            hookProc.AppendLine("&SCOPED-DEFINE DeploymentDirectory " + ProEnv.BaseCompilationPath.PreProcQuoter());
            var encoding = TextEncodingDetect.GetFileEncoding(Config.FileDeploymentHook);

            Utils.FileWriteAllText(Path.Combine(_localTempDir, fileToExecute), Utils.ReadAllText(Config.FileDeploymentHook, encoding).Replace(@"/*<inserted_3P_values>*/", hookProc.ToString()), encoding);

            SetPreprocessedVar("CurrentFilePath", fileToExecute.PreProcQuoter());

            return(true);
        }
Пример #7
0
        protected override bool SetExecutionInfo()
        {
            if (!base.SetExecutionInfo())
            {
                return(false);
            }

            // prolint, we need to copy the StartProlint program
            var fileToExecute = "prolint_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";

            _prolintOutputPath = Path.Combine(_localTempDir, "prolint.log");

            StringBuilder prolintProgram = new StringBuilder();

            prolintProgram.AppendLine("&SCOPED-DEFINE PathFileToProlint " + Files.First().CompiledSourcePath.ProQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE PathProlintOutputFile " + _prolintOutputPath.ProQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE PathToStartProlintProgram " + Config.FileStartProlint.ProQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE UserName " + Config.Instance.UserName.ProQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE PathActualFilePath " + Files.First().SourcePath.ProQuoter());
            var filename = Npp.CurrentFile.FileName;

            if (FileTag.Contains(filename))
            {
                var fileInfo = FileTag.GetLastFileTag(filename);
                prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationName " + fileInfo.ApplicationName.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationVersion " + fileInfo.ApplicationVersion.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileWorkPackage " + fileInfo.WorkPackage.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileBugID " + fileInfo.BugId.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileCorrectionNumber " + fileInfo.CorrectionNumber.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileDate " + fileInfo.CorrectionDate.ProQuoter());
            }
            var encoding = TextEncodingDetect.GetFileEncoding(Config.FileStartProlint);

            Utils.FileWriteAllText(Path.Combine(_localTempDir, fileToExecute), Utils.ReadAllText(Config.FileStartProlint, encoding).Replace(@"/*<inserted_3P_values>*/", prolintProgram.ToString()), encoding);

            SetPreprocessedVar("CurrentFilePath", fileToExecute.ProQuoter());

            return(true);
        }
Пример #8
0
        public static Encoding GetEncoding(byte[] bytesFile)
        {
            var encoding = new TextEncodingDetect().DetectEncoding(bytesFile, bytesFile.Length);

            switch (encoding)
            {
            case TextEncodingDetect.Encoding.None:
                return(Encoding.Default);

            case TextEncodingDetect.Encoding.Ansi:
                //https://stackoverflow.com/questions/33033514/how-can-i-convert-values-stored-in-ansi-windows-1252-in-a-database-to-utf-8
                return(Encoding.GetEncoding("ISO-8859-1"));

            case TextEncodingDetect.Encoding.Ascii:
                return(Encoding.ASCII);

            case TextEncodingDetect.Encoding.Utf8Bom:
                return(Encoding.UTF8);

            case TextEncodingDetect.Encoding.Utf8Nobom:
                return(new UTF8Encoding(false));

            case TextEncodingDetect.Encoding.Utf16LeBom:
                return(Encoding.Unicode);

            case TextEncodingDetect.Encoding.Utf16LeNoBom:
                return(new UnicodeEncoding(false, false));

            case TextEncodingDetect.Encoding.Utf16BeBom:
                return(Encoding.BigEndianUnicode);

            case TextEncodingDetect.Encoding.Utf16BeNoBom:
                return(new UnicodeEncoding(true, false));

            default:
                return(Encoding.Default);
            }
        }
Пример #9
0
            /// <summary>
            /// Ask the user to disable the default auto completion
            /// </summary>
            public bool AskToDisableAutocompletionAndRestart()
            {
                if (AutocompletionMode == 0 || Config.Instance.AutoCompleteNeverAskToDisableDefault)
                {
                    return(false);
                }

                var answer = UserCommunication.Message("3P (Progress Programmers Pal) <b>fully replaces the default autocompletion</b> offered by Notepad++ by a much better version.<br><br>If the default autocompletion isn't disabled, you will see 2 lists of suggestions!<br><br>I advise you to let 3P disable the default autocompletion now (restart required); otherwise, you can do it manually later", MessageImg.MsgInfo, "Autocompletion", "Deactivate default autocompletion now", new List <string> {
                    "Yes, restart now", "No, never ask again", "I'll do it later myself"
                });

                if (answer == 1)
                {
                    Config.Instance.AutoCompleteNeverAskToDisableDefault = true;
                }
                if (answer != 0)
                {
                    return(false);
                }

                var encoding    = TextEncodingDetect.GetFileEncoding(FileNppConfigXml);
                var fileContent = Utils.ReadAllText(FileNppConfigXml, encoding);

                fileContent = fileContent.Replace("autoCAction=\"3\"", "autoCAction=\"0\"");
                var configCopyPath = Path.Combine(Config.FolderUpdate, "config.xml");

                if (!Utils.FileWriteAllText(configCopyPath, fileContent, encoding))
                {
                    return(false);
                }

                // replace default config by its copy on npp shutdown
                _3PUpdater.Instance.AddFileToMove(configCopyPath, FileNppConfigXml);

                Restart();
                return(true);
            }
Пример #10
0
        private void button7_Click(object sender, EventArgs e)
        {
            if (comboBoxEdit1.SelectedIndex <= 0)
            {
                MessageBox.Show("請先選擇模組!");
                return;
            }
            string[] array_path = Directory.GetFiles(s_folderpath + "\\" + comboBoxEdit1.Properties.Items[comboBoxEdit1.SelectedIndex].ToString() + "\\SQL\\");
            for (int j = 0; j < array_path.Length; j++)
            {
                byte[] byteData = File.ReadAllBytes(array_path[j]);

                var textDetect = new TextEncodingDetect();
                TextEncodingDetect.Encoding encoding = textDetect.DetectEncoding(byteData, byteData.Length);

                if (encoding == TextEncodingDetect.Encoding.UTF8_BOM)
                {
                    string s = array_path[j] + " 是UTF8格式,請轉成無BOM格式!";
                    MessageBox.Show(s);
                    return;
                }
            }
            MessageBox.Show("檢查完成,全部都是UTF8無BOM格式");
        }
Пример #11
0
        // 检测文本文件的encoding

        /*
         * UTF-8: EF BB BF
         * UTF-16 big-endian byte order: FE FF
         * UTF-16 little-endian byte order: FF FE
         * UTF-32 big-endian byte order: 00 00 FE FF
         * UTF-32 little-endian byte order: FF FE 00 00
         * */
        public static Encoding DetectTextFileEncoding(string strFilename,
                                                      Encoding default_encoding)
        {
            byte[] buffer = new byte[4];

            try
            {
                using (FileStream file = File.Open(
                           strFilename,
                           FileMode.Open,
                           FileAccess.Read,
                           FileShare.ReadWrite))
                {
                    if (file.Length >= 2)
                    {
                        file.Read(buffer, 0, 2);    // 1, 2 BUG

                        if (buffer[0] == 0xff && buffer[1] == 0xfe)
                        {
                            return(Encoding.Unicode);    // little-endian
                        }

                        if (buffer[0] == 0xfe && buffer[1] == 0xff)
                        {
                            return(Encoding.BigEndianUnicode);
                        }
                    }

                    if (file.Length >= 3)
                    {
                        file.Read(buffer, 2, 1);
                        if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
                        {
                            return(Encoding.UTF8);
                        }
                    }

                    if (file.Length >= 4)
                    {
                        file.Read(buffer, 3, 1);

                        // UTF-32 big-endian byte order: 00 00 FE FF
                        // UTF-32 little-endian byte order: FF FE 00 00

                        if (buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xfe && buffer[3] == 0xff)
                        {
                            return(Encoding.UTF32);    // little-endian
                        }

                        if (buffer[0] == 0xff && buffer[1] == 0xfe && buffer[2] == 0x00 && buffer[3] == 0x00)
                        {
                            return(Encoding.GetEncoding(65006));    // UTF-32 big-endian
                        }
                    }

                    // 2018/11/6
                    // 检测是不是没有 BOM 的 UTF-8
                    {
                        byte[] temp_buffer = new byte[4096];
                        file.Seek(0, SeekOrigin.Begin);
                        int length = file.Read(temp_buffer, 0, temp_buffer.Length);
                        TextEncodingDetect          detector = new TextEncodingDetect();
                        TextEncodingDetect.Encoding encoding = detector.DetectEncoding(temp_buffer, length);
                        switch (encoding)
                        {
                        case TextEncodingDetect.Encoding.Utf8Bom:
                        case TextEncodingDetect.Encoding.Utf8Nobom:
                            return(Encoding.UTF8);
                        }
                    }
                }
            }
            catch
            {
            }

            return(default_encoding);    // default
        }
Пример #12
0
        /// <summary>
        /// allows to prepare the execution environnement by creating a unique temp folder
        /// and copying every critical files into it
        /// Then execute the progress program
        /// </summary>
        /// <returns></returns>
        public bool Do(ExecutionType executionType)
        {
            if (ListToCompile == null)
            {
                ListToCompile = new List <FileToCompile>();
            }

            ExecutionType = executionType;

            // check prowin32.exe
            if (!File.Exists(ProEnv.ProwinPath))
            {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The file path to Prowin.exe is incorrect : <div class='ToolTipcodeSnippet'>" + ProEnv.ProwinPath + "</div>You must provide a valid path before executing this action<br><i>You can change this path in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return(false);
            }

            // check compilation dir
            if (executionType == ExecutionType.Compile && !ProEnv.CompileLocally && (!Path.IsPathRooted(ProEnv.BaseCompilationPath)))
            {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The path for the compilation base directory is incorrect : <div class='ToolTipcodeSnippet'>" + (string.IsNullOrEmpty(ProEnv.BaseCompilationPath) ? "it's empty!" : ProEnv.BaseCompilationPath) + "</div>You must provide a valid path before executing this action :<br><br><i>1. Either change the compilation directory<br>2. Or toggle the option to compile next to the source file!<br><br>The options are configurable in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return(false);
            }

            // create a unique temporary folder
            LocalTempDir = Path.Combine(Config.FolderTemp, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
            if (!Utils.CreateDirectory(LocalTempDir))
            {
                return(false);
            }

            // for each file of the list
            var           filesListPath    = Path.Combine(LocalTempDir, "files.list");
            StringBuilder filesListcontent = new StringBuilder();
            var           count            = 1;

            foreach (var fileToCompile in ListToCompile)
            {
                if (!File.Exists(fileToCompile.InputPath))
                {
                    UserCommunication.Notify("Couldn't find the following file :<br>" + fileToCompile.InputPath, MessageImg.MsgError, "Execution error", "File not found", 10);
                    return(false);
                }

                // if current file and the file has unsaved modif, we copy the content to a temp file, otherwise we just use the input path (also use the input path for .cls files!)
                if (fileToCompile.InputPath.Equals(Plug.CurrentFilePath) &&
                    (Npp.GetModify || (fileToCompile.BaseFileName ?? "").StartsWith("_")) &&
                    !Path.GetExtension(fileToCompile.InputPath).Equals(".cls"))
                {
                    fileToCompile.CompInputPath = Path.Combine(LocalTempDir, "tmp_" + DateTime.Now.ToString("yyMMdd_HHmmssfff_") + count + Path.GetExtension(fileToCompile.InputPath));
                    Utils.FileWriteAllText(fileToCompile.CompInputPath, Npp.Text, Encoding.Default);
                }
                else
                {
                    fileToCompile.CompInputPath = fileToCompile.InputPath;
                }

                if (executionType != ExecutionType.Compile)
                {
                    continue;
                }

                // we set where the *.lst and *.r files will be generated by the COMPILE command
                var baseFileName   = Path.GetFileNameWithoutExtension(fileToCompile.CompInputPath);
                var lastDeployment = ProEnv.Deployer.GetTargetDirsNeededForFile(fileToCompile.InputPath, 0).Last();

                // for *.cls files, as many *.r files are generated, we need to compile in a temp directory
                // we need to know which *.r files were generated for each input file
                // so each file gets his own sub tempDir
                if ((lastDeployment.DeployType != DeployType.Move) ||
                    Config.Instance.CompileForceUseOfTemp ||
                    Path.GetExtension(fileToCompile.InputPath).Equals(".cls")
                    )
                {
                    var subTempDir = Path.Combine(LocalTempDir, count.ToString());

                    // if the deployment dir is not on the same disk as the temp folder, we create a temp dir
                    // as close to the final deployment as possible (= in the deployment base dir!)
                    if (lastDeployment.DeployType != DeployType.Ftp && !string.IsNullOrEmpty(DistantRootTempDir) && DistantRootTempDir.Length > 2 && !DistantRootTempDir.Substring(0, 2).EqualsCi(LocalTempDir.Substring(0, 2)))
                    {
                        if (Utils.CreateDirectory(DistantRootTempDir, FileAttributes.Hidden))
                        {
                            DistantTempDir = Path.Combine(DistantRootTempDir, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
                        }
                        else
                        {
                            DistantTempDir = LocalTempDir;
                        }

                        subTempDir = Path.Combine(DistantTempDir, count.ToString());
                    }

                    if (!Utils.CreateDirectory(subTempDir))
                    {
                        return(false);
                    }

                    fileToCompile.CompOutputDir = subTempDir;
                    fileToCompile.CompOutputLst = Path.Combine(subTempDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR   = Path.Combine(subTempDir, baseFileName + ".r");
                }
                else
                {
                    // if we want to move the r-code somewhere during the deployment, then we will compile the r-code
                    // directly there, because it's faster than generating it in a temp folder and moving it afterward
                    fileToCompile.CompOutputDir = lastDeployment.TargetDir;
                    if (!Utils.CreateDirectory(fileToCompile.CompOutputDir))
                    {
                        return(false);
                    }

                    fileToCompile.CompOutputLst = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR   = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".r");
                }

                // feed files list
                filesListcontent.AppendLine(fileToCompile.CompInputPath.ProQuoter() + " " + fileToCompile.CompOutputDir.ProQuoter() + " " + fileToCompile.CompOutputLst.ProQuoter());

                count++;
            }
            Utils.FileWriteAllText(filesListPath, filesListcontent.ToString(), Encoding.Default);

            // when running a procedure, check that a .r is not hiding the program, if that's the case we warn the user
            if (executionType == ExecutionType.Run && !_dontWarnAboutRCode && ListToCompile.Count >= 1)
            {
                if (File.Exists(Path.ChangeExtension(ListToCompile.First().InputPath, ".r")))
                {
                    UserCommunication.NotifyUnique("rcodehide", "Friendly warning, an <b>r-code</b> <i>(i.e. *.r file)</i> is hiding the current program<br>If you modified it since the last compilation you might not have the expected behavior...<br><br><i>" + "stop".ToHtmlLink("Click here to not show this message again for this session") + "</i>", MessageImg.MsgWarning, "Execution warning", "An Rcode hides the program", args => {
                        _dontWarnAboutRCode = true;
                        UserCommunication.CloseUniqueNotif("rcodehide");
                    }, 5);
                }
            }

            // Move ini file into the execution dir
            var baseIniPath = "";

            if (File.Exists(ProEnv.IniPath))
            {
                baseIniPath = Path.Combine(LocalTempDir, "base.ini");
                // we need to copy the .ini but we must delete the PROPATH= part, as stupid as it sounds, if we leave a huge PROPATH
                // in this file, it increases the compilation time by a stupid amount... unbelievable i know, but trust me, it does...
                var encoding    = TextEncodingDetect.GetFileEncoding(ProEnv.IniPath);
                var fileContent = Utils.ReadAllText(ProEnv.IniPath, encoding);
                var regex       = new Regex("^PROPATH=.*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                var matches     = regex.Match(fileContent);
                if (matches.Success)
                {
                    fileContent = regex.Replace(fileContent, @"PROPATH=");
                }
                Utils.FileWriteAllText(baseIniPath, fileContent, encoding);
            }

            // Move pf file into the execution dir
            var basePfPath = "";

            if (File.Exists(ProEnv.GetPfPath()))
            {
                basePfPath = Path.Combine(LocalTempDir, "base.pf");
                File.Copy(ProEnv.GetPfPath(), basePfPath);
            }

            // set common info on the execution
            LogPath         = Path.Combine(LocalTempDir, "run.log");
            ProcessStartDir = executionType == ExecutionType.Run ? Path.GetDirectoryName(ListToCompile.First().InputPath) ?? LocalTempDir : LocalTempDir;
            ProgressWin32   = ProEnv.ProwinPath;
            if (executionType == ExecutionType.Database)
            {
                ExtractDbOutputPath = Path.Combine(LocalTempDir, ExtractDbOutputPath);
            }
            ProgressionFilePath    = Path.Combine(LocalTempDir, "compile.progression");
            DatabaseConnectionLog  = Path.Combine(LocalTempDir, "db.ko");
            NotificationOutputPath = Path.Combine(LocalTempDir, "postExecution.notif");
            var    propathToUse  = string.Join(",", ProEnv.GetProPathDirList);
            string fileToExecute = "";


            if (executionType == ExecutionType.Appbuilder)
            {
                fileToExecute = ListToCompile.First().InputPath;
            }
            else if (executionType == ExecutionType.Database)
            {
                // for database extraction, we need to copy the DumpDatabase program
                fileToExecute = "db_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                if (!Utils.FileWriteAllBytes(Path.Combine(LocalTempDir, fileToExecute), DataResources.DumpDatabase))
                {
                    return(false);
                }
            }
            else if (executionType == ExecutionType.Prolint)
            {
                // prolint, we need to copy the StartProlint program
                fileToExecute     = "prolint_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                ProlintOutputPath = Path.Combine(LocalTempDir, "prolint.log");
                StringBuilder prolintProgram = new StringBuilder();
                prolintProgram.AppendLine("&SCOPED-DEFINE PathFileToProlint " + ListToCompile.First().CompInputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathProlintOutputFile " + ProlintOutputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathToStartProlintProgram " + Config.FileStartProlint.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE UserName " + Config.Instance.UserName.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathActualFilePath " + ListToCompile.First().InputPath.ProQuoter());
                var filename = Path.GetFileName(Plug.CurrentFilePath);
                if (FileTag.Contains(filename))
                {
                    var fileInfo = FileTag.GetLastFileTag(filename);
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationName " + fileInfo.ApplicationName.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationVersion " + fileInfo.ApplicationVersion.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileWorkPackage " + fileInfo.WorkPackage.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileBugID " + fileInfo.BugId.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileCorrectionNumber " + fileInfo.CorrectionNumber.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileDate " + fileInfo.CorrectionDate.ProQuoter());
                }
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileStartProlint);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileStartProlint, encoding).Replace(@"/*<inserted_3P_values>*/", prolintProgram.ToString()), encoding);
            }
            else if (executionType == ExecutionType.DeploymentHook)
            {
                fileToExecute = "hook_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                StringBuilder hookProc = new StringBuilder();
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationName " + ProEnv.Name.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationSuffix " + ProEnv.Suffix.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE StepNumber " + DeploymentStep);
                hookProc.AppendLine("&SCOPED-DEFINE SourceDirectory " + DeploymentSourcePath.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE DeploymentDirectory " + ProEnv.BaseCompilationPath.ProQuoter());
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileDeploymentHook);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileDeploymentHook, encoding).Replace(@"/*<inserted_3P_values>*/", hookProc.ToString()), encoding);
            }
            else if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader)
            {
                // need to init datadigger?
                if (!File.Exists(Path.Combine(Config.FolderDataDigger, "DataDigger.p")))
                {
                    if (!Utils.FileWriteAllBytes(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), DataResources.DataDigger))
                    {
                        return(false);
                    }
                    if (!Utils.ExtractAll(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), Config.FolderDataDigger))
                    {
                        return(false);
                    }
                }
                // add the datadigger folder to the propath
                propathToUse = Config.FolderDataDigger + "," + propathToUse;
            }
            else
            {
                if (ListToCompile.Count == 1)
                {
                    fileToExecute = ListToCompile.First().CompInputPath;
                }
            }

            // prepare the .p runner
            var           runnerPath    = Path.Combine(LocalTempDir, "run_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p");
            StringBuilder runnerProgram = new StringBuilder();

            runnerProgram.AppendLine("&SCOPED-DEFINE ExecutionType " + executionType.ToString().ToUpper().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ToExecute " + fileToExecute.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE LogFile " + LogPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtractDbOutputPath " + ExtractDbOutputPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE propathToUse " + (LocalTempDir + "," + propathToUse).ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtraPf " + ProEnv.ExtraPf.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE BasePfPath " + basePfPath.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileWithLst " + ProEnv.CompileWithListing);
            runnerProgram.AppendLine("&SCOPED-DEFINE ToCompileListFile " + filesListPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CreateFileIfConnectFails " + DatabaseConnectionLog.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileProgressionFile " + ProgressionFilePath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE DbConnectionMandatory " + NeedDatabaseConnection);
            runnerProgram.AppendLine("&SCOPED-DEFINE NotificationOutputPath " + NotificationOutputPath.ProQuoter());
            runnerProgram.Append(Encoding.Default.GetString(DataResources.ProgressRun));
            Utils.FileWriteAllText(runnerPath, runnerProgram.ToString(), Encoding.Default);

            // preferably, we use the batch mode because it's faster than the client mode
            var batchMode = (executionType == ExecutionType.CheckSyntax || executionType == ExecutionType.Compile || executionType == ExecutionType.Database);

            // no batch mode option?
            batchMode = batchMode && !Config.Instance.NeverUseProwinInBatchMode;

            // multiple compilation, we don't want to show all those Prowin in the task bar...
            batchMode = batchMode && !NoBatch;

            // Parameters
            StringBuilder Params = new StringBuilder();

            if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader)
            {
                Params.Append(" -s 10000 -d dmy -E -rereadnolock -h 255 -Bt 4000 -tmpbsize 8");
            }
            if (executionType != ExecutionType.Run)
            {
                Params.Append(" -T " + LocalTempDir.Trim('\\').ProQuoter());
            }
            if (!string.IsNullOrEmpty(baseIniPath))
            {
                Params.Append(" -ini " + baseIniPath.ProQuoter());
            }
            if (batchMode)
            {
                Params.Append(" -b");
            }
            Params.Append(" -p " + runnerPath.ProQuoter());
            if (!string.IsNullOrWhiteSpace(ProEnv.CmdLineParameters))
            {
                Params.Append(" " + ProEnv.CmdLineParameters.Trim());
            }
            ExeParameters = Params.ToString();

            // we supress the splashscreen
            if (!batchMode)
            {
                MoveSplashScreenNoError(Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen.bmp"), Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen-3p-disabled.bmp"));
            }

            // Start a process
            var pInfo = new ProcessStartInfo {
                FileName         = ProEnv.ProwinPath,
                Arguments        = ExeParameters,
                WorkingDirectory = ProcessStartDir
            };

            if (batchMode)
            {
                pInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                pInfo.CreateNoWindow = true;
            }
            Process = new Process {
                StartInfo           = pInfo,
                EnableRaisingEvents = true
            };
            Process.Exited += ProcessOnExited;
            try {
                Process.Start();
            } catch (Exception e) {
                UserCommunication.NotifyUnique("ProwinFailed", "Couldn't start a new prowin process!<br>Please check that the file path to prowin32.exe is correct in the <a href='go'>set environment page</a>.<br><br>Below is the technical error that occured :<br><div class='ToolTipcodeSnippet'>" + e.Message + "</div>", MessageImg.MsgError, "Execution error", "Can't start a prowin process", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProwinFailed");
                    args.Handled = true;
                }, 10);
            }

            //UserCommunication.Notify("New process starting...<br><br><b>FileName :</b><br>" + ProEnv.ProwinPath + "<br><br><b>Parameters :</b><br>" + ExeParameters + "<br><br><b>Temporary directory :</b><br><a href='" + TempDir + "'>" + TempDir + "</a>");

            return(true);
        }
Пример #13
0
        /// <summary>
        /// allows to prepare the execution environment by creating a unique temp folder
        /// and copying every critical files into it
        /// Then execute the progress program
        /// </summary>
        /// <returns></returns>
        public bool Start()
        {
            // check parameters
            var errorString = CheckParameters();

            if (!string.IsNullOrEmpty(errorString))
            {
                UserCommunication.NotifyUnique("ProExecutionChecks", errorString, MessageImg.MsgHighImportance, "Progress execution", "Couldn't start execution", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return(false);
            }

            // create a unique temporary folder
            _localTempDir = Path.Combine(Config.FolderTemp, "exec_" + DateTime.Now.ToString("HHmmssfff") + "_" + Path.GetRandomFileName());
            if (!Utils.CreateDirectory(_localTempDir))
            {
                return(false);
            }

            // move .ini file into the execution directory
            if (File.Exists(ProEnv.IniPath))
            {
                _tempInifilePath = Path.Combine(_localTempDir, "base.ini");

                // we need to copy the .ini but we must delete the PROPATH= part, as stupid as it sounds, if we leave a huge PROPATH
                // in this file, it increases the compilation time by a stupid amount... unbelievable i know, but trust me, it does...
                var encoding    = TextEncodingDetect.GetFileEncoding(ProEnv.IniPath);
                var fileContent = Utils.ReadAllText(ProEnv.IniPath, encoding);
                var regex       = new Regex("^PROPATH=.*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                var matches     = regex.Match(fileContent);
                if (matches.Success)
                {
                    fileContent = regex.Replace(fileContent, @"PROPATH=");
                }
                Utils.FileWriteAllText(_tempInifilePath, fileContent, encoding);
            }

            // set common info on the execution
            _processStartDir = _localTempDir;
            _logPath         = Path.Combine(_localTempDir, "run.log");
            _dbLogPath       = Path.Combine(_localTempDir, "db.ko");
            _notifPath       = Path.Combine(_localTempDir, "postExecution.notif");
            _propath         = (_localTempDir + "," + string.Join(",", ProEnv.GetProPathDirList)).Trim().Trim(',') + "\r\n";
            _propathFilePath = Path.Combine(_localTempDir, "progress.propath");
            Utils.FileWriteAllText(_propathFilePath, _propath, Encoding.Default);

            // Set info
            if (!SetExecutionInfo())
            {
                return(false);
            }

            SetPreprocessedVar("ExecutionType", ExecutionType.ToString().ToUpper().PreProcQuoter());
            SetPreprocessedVar("LogPath", _logPath.PreProcQuoter());
            SetPreprocessedVar("PropathFilePath", _propathFilePath.PreProcQuoter());
            SetPreprocessedVar("DbConnectString", ProEnv.ConnectionString.PreProcQuoter());
            SetPreprocessedVar("DbLogPath", _dbLogPath.PreProcQuoter());
            SetPreprocessedVar("DbConnectionMandatory", NeedDatabaseConnection.ToString());
            SetPreprocessedVar("NotificationOutputPath", _notifPath.PreProcQuoter());
            SetPreprocessedVar("PreExecutionProgram", ProEnv.PreExecutionProgram.Trim().PreProcQuoter());
            SetPreprocessedVar("PostExecutionProgram", ProEnv.PostExecutionProgram.Trim().PreProcQuoter());
            SetPreprocessedVar("DatabaseExtractCandoTblType", ProEnv.DatabaseExtractCandoTblType.Trim().PreProcQuoter());
            SetPreprocessedVar("DatabaseExtractCandoTblName", ProEnv.DatabaseExtractCandoTblName.Trim().PreProcQuoter());
            SetPreprocessedVar("DatabaseAliasList", ProEnv.DatabaseAliasList.Trim().Trim(';').PreProcQuoter());

            // prepare the .p runner
            _runnerPath = Path.Combine(_localTempDir, "run_" + DateTime.Now.ToString("HHmmssfff") + ".p");
            StringBuilder runnerProgram = new StringBuilder();

            foreach (var @var in _preprocessedVars)
            {
                runnerProgram.AppendLine("&SCOPED-DEFINE " + @var.Key + " " + @var.Value);
            }
            runnerProgram.Append(Encoding.Default.GetString(DataResources.ProgressRun));
            Utils.FileWriteAllText(_runnerPath, runnerProgram.ToString(), Encoding.Default);

            // no batch mode option?
            _useBatchMode = !Config.Instance.NeverUseProwinInBatchMode && !NoBatch && CanUseBatchMode();

            // Parameters
            _exeParameters = new StringBuilder();
            if (_useBatchMode)
            {
                _exeParameters.Append(" -b");
            }
            else
            {
                // we suppress the splashscreen
                if (ProEnv.CanProwinUseNoSplash)
                {
                    _exeParameters.Append(" -nosplash");
                }
                else
                {
                    MoveSplashScreenNoError(Path.Combine(Path.GetDirectoryName(ProEnv.ProwinExePath) ?? "", "splashscreen.bmp"), Path.Combine(Path.GetDirectoryName(ProEnv.ProwinExePath) ?? "", "splashscreen-3p-disabled.bmp"));
                }
            }
            _exeParameters.Append(" -p " + _runnerPath.Quoter());
            if (!string.IsNullOrWhiteSpace(ProEnv.CmdLineParameters))
            {
                _exeParameters.Append(" " + ProEnv.CmdLineParameters.Trim());
            }
            AppendProgressParameters(_exeParameters);

            // start the process
            try {
                StartProcess();
            } catch (Exception e) {
                ErrorHandler.ShowErrors(e);
                UserCommunication.NotifyUnique("ProwinFailed", "Couldn't start a new Prowin process!<br>Please check that the file path to prowin32.exe is correct in the <a href='go'>set environment page</a>.<br><br>Below is the technical error that occurred :<br><div class='ToolTipcodeSnippet'>" + e.Message + "</div>", MessageImg.MsgError, "Progress execution", "Can't start a Prowin process", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProwinFailed");
                    args.Handled = true;
                }, 10);
            }

            //UserCommunication.Notify("New process starting...<br><br><b>FileName :</b><br>" + ProEnv.ProwinPath + "<br><br><b>Parameters :</b><br>" + _exeParameters + "<br><br><b>Temporary directory :</b><br><a href='" + _localTempDir + "'>" + _localTempDir + "</a>");

            return(true);
        }
Пример #14
0
    public static FileStateModel GetFileState(string filename)
    {
        // Read in the file in binary
        byte[] buffer;

        try
        {
            buffer = File.ReadAllBytes(filename);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw ex;
        }

        // Detect encoding
        var textDetect = new TextEncodingDetect();

        TextEncodingDetect.Encoding encoding = textDetect.DetectEncoding(buffer, buffer.Length);

        string str = "";

        StringBuilder sb = new StringBuilder();

        //sb.AppendLine("File: " + filename);

        //sb.Append("Encoding: ");
        if (encoding == TextEncodingDetect.Encoding.None)
        {
            //sb.AppendLine("Binary");
        }
        else if (encoding == TextEncodingDetect.Encoding.Ascii)
        {
            str = Encoding.ASCII.GetString(buffer);
            //sb.AppendLine("ASCII (chars in the 0-127 range)");
        }
        else if (encoding == TextEncodingDetect.Encoding.Ansi)
        {
            str = Encoding.Default.GetString(buffer);
            //sb.AppendLine("ANSI (chars in the range 0-255 range)");
        }
        else if (encoding == TextEncodingDetect.Encoding.Utf8Bom || encoding == TextEncodingDetect.Encoding.Utf8Nobom)
        {
            str = Encoding.UTF8.GetString(buffer);
            //sb.AppendLine("UTF-8");
        }
        else if (encoding == TextEncodingDetect.Encoding.Utf16LeBom || encoding == TextEncodingDetect.Encoding.Utf16LeNoBom)
        {
            str = Encoding.Unicode.GetString(buffer);
            //sb.AppendLine("UTF-16 Little Endian");
        }
        else if (encoding == TextEncodingDetect.Encoding.Utf16BeBom || encoding == TextEncodingDetect.Encoding.Utf16BeNoBom)
        {
            str = Encoding.BigEndianUnicode.GetString(buffer);
            //sb.AppendLine("UTF-16 Big Endian");
        }

        int All_Lines  = 0;
        int CRLF_Count = 0;
        int LF_Count   = 0;

        if (encoding != TextEncodingDetect.Encoding.None)
        {
            All_Lines  = LineBreakCount(str);
            CRLF_Count = LineBreakCount(str, new[] { "\r\n" });
            LF_Count   = All_Lines - CRLF_Count;

            //sb.AppendLine(
            //    "Length: " + str.Length + "\t" +
            //    "Lines: " + All_Lines + "\t" +
            //    "CRLF: " + CRLF_Count + "\t" +
            //    "  LF: " + (LF_Count));
        }

        return(new FileStateModel()
        {
            Encoding = encoding,
            Lines = All_Lines,
            CRLFs = CRLF_Count,
            LFs = LF_Count
        });
    }
Пример #15
0
        public static bool IsText(byte[] buffer, int offset, int count)
        {
            if (buffer.Length < offset + count)
            {
                throw new ArgumentOutOfRangeException(nameof(buffer));
            }

            // [Stage 1] Contains unicode BOM -> text
            if (3 <= offset + count &&
                buffer[offset] == Utf8Bom[0] && buffer[offset + 1] == Utf8Bom[1] && buffer[offset + 2] == Utf8Bom[2])
            {
                return(true);
            }
            if (2 <= offset + count)
            {
                if (buffer[offset] == Utf16LeBom[0] && buffer[offset + 1] == Utf16LeBom[1])
                {
                    return(true);
                }
                if (buffer[offset] == Utf16BeBom[0] && buffer[offset + 1] == Utf16BeBom[1])
                {
                    return(true);
                }
            }

            // [Stage 2] Check if a chunk can be decoded as system default ANSI locale.
            // Many multibyte encodings have 'unused area'. If a file contains one of these area, treat it as a binary.
            // Ex) EUC-KR's layout : https://en.wikipedia.org/wiki/CP949#/media/File:Unified_Hangul_Code.svg
            bool     isText  = true;
            Encoding ansiEnc = Encoding.GetEncoding(DefaultAnsi.CodePage, new EncoderExceptionFallback(), new DecoderExceptionFallback());

            try
            {
                // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
                ansiEnc.GetChars(buffer, offset, count);
            }
            catch (DecoderFallbackException)
            { // Failure
                isText = false;
            }

            // [Stage 3]
            // Problem: Some encodings make use of 128-255 area, so every byte is valid. (e.g. Windows-1252 / CP437)
            // To counter these issue, if file is seems to be text, check again with AutoIt.Common.TextEncodingDetect
            if (isText)
            {
                TextEncodingDetect detect = new TextEncodingDetect();
                byte[]             idxZeroBuffer;
                if (offset == 0)
                {
                    idxZeroBuffer = buffer;
                }
                else
                {
                    idxZeroBuffer = new byte[count];
                    Array.Copy(buffer, offset, idxZeroBuffer, 0, count);
                }

                switch (detect.DetectEncoding(idxZeroBuffer, idxZeroBuffer.Length))
                {
                // Binary
                case TextEncodingDetect.Encoding.None:
                // PEBakery mandates unicode text to have BOM.
                // They must have been filtered out in stage 1.
                case TextEncodingDetect.Encoding.Utf16LeBom:
                case TextEncodingDetect.Encoding.Utf16BeBom:
                case TextEncodingDetect.Encoding.Utf8Bom:
                // Treat unicode text file without a BOM as a binary.
                case TextEncodingDetect.Encoding.Utf16LeNoBom:
                case TextEncodingDetect.Encoding.Utf16BeNoBom:
                case TextEncodingDetect.Encoding.Utf8NoBom:
                    isText = false;
                    break;
                }
            }

            return(isText);
        }
Пример #16
0
        protected override bool SetExecutionInfo()
        {
            if (!base.SetExecutionInfo())
            {
                return(false);
            }

            if (!Config.Instance.GlobalDontCheckProlintUpdates && (!Updater <ProlintUpdaterWrapper> .Instance.LocalVersion.IsHigherVersionThan("v0") || !Updater <ProparseUpdaterWrapper> .Instance.LocalVersion.IsHigherVersionThan("v0")))
            {
                UserCommunication.NotifyUnique("NeedProlint",
                                               "The Prolint installation folder could not be found in 3P.<br>This is normal if it is the first time that you are using this feature.<br><br>" + "download".ToHtmlLink("Please click here to download the latest release of Prolint automatically") + "<br><br><i>You will be informed when it is installed and you will be able to use this feature immediately after.<br><br>If you do not wish to download it and see this message again :<br> toggle off automatic updates for Prolint in the " + "options".ToHtmlLink("update options page") + ".<br>Please note that in that case, you will need to configure Prolint yourself</i>",
                                               MessageImg.MsgQuestion, "Prolint execution", "Prolint installation not found", args => {
                    if (args.Link.Equals("options"))
                    {
                        args.Handled = true;
                        Appli.Appli.GoToPage(PageNames.OptionsUpdate);
                    }
                    else if (args.Link.Equals("download"))
                    {
                        args.Handled = true;
                        Updater <ProlintUpdaterWrapper> .Instance.CheckForUpdate();
                        Updater <ProparseUpdaterWrapper> .Instance.CheckForUpdate();
                    }
                    if (args.Handled)
                    {
                        UserCommunication.CloseUniqueNotif("NeedProlint");
                    }
                });
                return(false);
            }

            // prolint, we need to copy the StartProlint program
            var fileToExecute = "prolint_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";

            _prolintOutputPath = Path.Combine(_localTempDir, "prolint.log");

            StringBuilder prolintProgram = new StringBuilder();

            prolintProgram.AppendLine("&SCOPED-DEFINE PathFileToProlint " + Files.First().CompiledSourcePath.PreProcQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE PathProlintOutputFile " + _prolintOutputPath.PreProcQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE PathToStartProlintProgram " + Config.ProlintStartProcedure.PreProcQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE UserName " + Config.Instance.UserName.PreProcQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE PathActualFilePath " + Files.First().SourcePath.PreProcQuoter());
            var filename = Npp.CurrentFileInfo.FileName;

            if (FileCustomInfo.Contains(filename))
            {
                var fileInfo = FileCustomInfo.GetLastFileTag(filename);
                prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationName " + fileInfo.ApplicationName.PreProcQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationVersion " + fileInfo.ApplicationVersion.PreProcQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileWorkPackage " + fileInfo.WorkPackage.PreProcQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileBugID " + fileInfo.BugId.PreProcQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileCorrectionNumber " + fileInfo.CorrectionNumber.PreProcQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE FileDate " + fileInfo.CorrectionDate.PreProcQuoter());

                prolintProgram.AppendLine("&SCOPED-DEFINE ModificationTagOpening " + ModificationTag.ReplaceTokens(fileInfo, ModificationTagTemplate.Instance.TagOpener).PreProcQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE ModificationTagEnding " + ModificationTag.ReplaceTokens(fileInfo, ModificationTagTemplate.Instance.TagCloser).PreProcQuoter());
            }
            prolintProgram.AppendLine("&SCOPED-DEFINE PathDirectoryToProlint " + Updater <ProlintUpdaterWrapper> .Instance.ApplicationFolder.PreProcQuoter());
            prolintProgram.AppendLine("&SCOPED-DEFINE PathDirectoryToProparseAssemblies " + Updater <ProparseUpdaterWrapper> .Instance.ApplicationFolder.PreProcQuoter());
            var encoding = TextEncodingDetect.GetFileEncoding(Config.ProlintStartProcedure);

            Utils.FileWriteAllText(Path.Combine(_localTempDir, fileToExecute), Utils.ReadAllText(Config.ProlintStartProcedure, encoding).Replace(@"/*<inserted_3P_values>*/", prolintProgram.ToString()), encoding);

            SetPreprocessedVar("CurrentFilePath", fileToExecute.PreProcQuoter());

            return(true);
        }