Beispiel #1
0
        public static List <LogInfo> IniWriteTextLineOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniWriteTextLineOp infoOp = cmd.Info.Cast <CodeInfo_IniWriteTextLineOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");

            bool append = infoOp.Infos[0].Append;

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            List <IniKey> keyList = new List <IniKey>(infoOp.Infos.Count);

            foreach (CodeInfo_IniWriteTextLine info in infoOp.Infos)
            {
                string sectionName = StringEscaper.Preprocess(s, info.Section);
                string line        = StringEscaper.Preprocess(s, info.Line);

                if (append)
                {
                    keyList.Add(new IniKey(sectionName, line));
                }
                else // prepend
                {
                    keyList.Insert(0, new IniKey(sectionName, line));
                }
            }
            IniKey[] keys = keyList.ToArray();

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniWriteTextLineOp");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            bool result = IniReadWriter.WriteRawLines(fileName, keyList, append);

            if (result)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    IniKey kv = keyList[i];
                    logs.Add(new LogInfo(LogState.Success, $"Line [{kv.Key}] written", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Success, $"Wrote [{keys.Length}] lines to [{fileName}]", cmd));
            }
            else
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    IniKey kv = keyList[i];
                    logs.Add(new LogInfo(LogState.Error, $"Could not write line [{kv.Key}]", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Error, $"Could not write [{keys.Length}] lines to [{fileName}]", cmd));
            }

            return(logs);
        }
Beispiel #2
0
 public static String GetCacheMemory()
 {
     return(IniReadWriter.ReadIniKeys("Command", "CacheMemory" + Sort, PathShareTaskPlus));
 }
Beispiel #3
0
 //改变延时
 private void textBox3_TextChanged(object sender, EventArgs e)
 {
     IniReadWriter.WriteIniKeys("Command", "gongxiang", textBox3.Text, ConfigCore.BaseConfig);
     ConfigCore.InitPathShare();
     IniReadWriter.WriteIniKeys("Command", "gongxiang", textBox3.Text, ConfigCore.PathShareConfig);
 }
Beispiel #4
0
 public static String GetComputerRename()
 {
     return(IniReadWriter.ReadIniKeys("Command", "computerRename", PathShareConfig));
 }
Beispiel #5
0
 public static String GetTaskName()
 {
     return(IniReadWriter.ReadIniKeys("Command", "TaskName" + Sort, PathShareTask));
 }
Beispiel #6
0
        public void AddFolder()
        {
            void Template(string folderName, bool overwrite, bool result)
            {
                EngineState s = EngineTests.CreateEngineState();
                string      pbOriginScript = Path.Combine("%TestBench%", "EncodedFile", "Blank.script");
                string      originScript   = StringEscaper.Preprocess(s, pbOriginScript);

                string destDir    = FileHelper.GetTempDir();
                string destScript = Path.Combine(destDir, "AddFolderTest.script");

                try
                {
                    File.Copy(originScript, destScript, true);

                    Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions());
                    try
                    {
                        sc = EncodedFile.AddFolder(sc, folderName, overwrite);
                    }
                    catch (Exception e)
                    {
                        switch (e)
                        {
                        case InvalidOperationException _:
                            Assert.IsFalse(result);
                            return;

                        case ArgumentException _:
                            Assert.IsFalse(result);
                            return;
                        }
                    }

                    Assert.AreEqual(sc.Sections.ContainsKey(folderName), result);
                    Assert.AreEqual(IniReadWriter.ContainsSection(destScript, folderName), result);

                    if (!folderName.Equals(AuthorEncoded, StringComparison.OrdinalIgnoreCase) &&
                        !folderName.Equals(InterfaceEncoded, StringComparison.OrdinalIgnoreCase))
                    {
                        string[] folders = sc.Sections[EncodedFolders].Lines;
                        Assert.AreEqual(folders.Contains(folderName, StringComparer.OrdinalIgnoreCase), result);
                    }
                }
                finally
                {
                    if (Directory.Exists(destDir))
                    {
                        Directory.Delete(destDir, true);
                    }
                }
            }

            Template("UnitTestEncode", false, true);
            Template("DummySection", false, false);
            Template("DummySection", true, true);
            Template("AuthorEncoded", false, false);
            Template("AuthorEncoded", true, true);
            Template("InterfaceEncoded", false, true);
            Template("InterfaceEncoded", true, true);

            Template("Wrong[String]", false, false);
            Template("Tab\tChar", false, false);
            Template("New\r\nLine", false, false);
            Template("Invalid?", false, false);
            Template("Invalid:", false, false);
        }
Beispiel #7
0
 public static int GetOverTime()
 {
     return(int.Parse(IniReadWriter.ReadIniKeys("Command", "cishu", PathShareConfig)));
 }
Beispiel #8
0
        //添加黑名单项目
        public static void AddVoteProjectNameDroped(bool isAllProject)
        {
            string projectName = ConfigCore.GetAutoVote("ProjectName");
            //一机器只允许拉黑投票一次
            string   drop     = IniReadWriter.ReadIniKeys("Command", "drop", "./handler.ini");
            TaskInfo taskInfo = TaskInfos.Get();

            if ((taskInfo != null && taskInfo.ProjectName != projectName) || drop == projectName)
            {
                return;
            }

            IniReadWriter.WriteIniKeys("Command", "drop", projectName, "./handler.ini");
            string voteProjectNameDroped = ConfigCore.GetAutoVote("voteProjectNameDroped");
            int    dropVote = 0;

            try
            {
                dropVote = int.Parse(ConfigCore.GetAutoVote("dropVote"));
            }
            catch (Exception)
            {
            }
            finally
            {
                dropVote++;
            }

            if (isAllProject)
            {
                if (projectName.IndexOf("_") > 0)
                {
                    projectName = projectName.Substring(0, projectName.IndexOf("_"));
                }
            }

            ConfigCore.WriteAutoVote("dropVote", dropVote.ToString());
            if (StringUtil.isEmpty(voteProjectNameDroped) || voteProjectNameDroped.IndexOf(projectName) == -1)
            {
                int    validDrop = 1;
                double blackRate = 1;
                try
                {
                    validDrop = int.Parse(ConfigCore.GetAutoVote("validDrop"));
                }
                catch { }
                try
                {
                    blackRate = int.Parse(ConfigCore.GetAutoVote("blackRate"));
                }
                catch { }
                if (dropVote >= validDrop)
                {
                    IniReadWriter.WriteIniKeys("Command", "drop", "", "./handler.ini");
                    LogCore.Write($"{projectName}拉黑{blackRate * 20}分钟");
                    voteProjectNameDroped +=
                        StringUtil.isEmpty(voteProjectNameDroped) ? projectName : "|" + projectName;
                    ConfigCore.WriteAutoVote("voteProjectNameDroped", voteProjectNameDroped);
                }
            }
        }
Beispiel #9
0
        public static List <LogInfo> ExtractAllFiles(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_ExtractAllFiles info = cmd.Info.Cast <CodeInfo_ExtractAllFiles>();

            string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile);
            string dirName    = StringEscaper.Preprocess(s, info.DirName);
            string destDir    = StringEscaper.Preprocess(s, info.DestDir);

            Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _);

            // Check if encoded file exist
            if (!EncodedFile.ContainsFolder(sc, dirName))
            {
                return(LogInfo.LogErrorMessage(logs, $"Encoded folder [{dirName}] not found in script [{sc.RealPath}]."));
            }

            // Filter dest path
            if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string[] dirs = sc.Sections[ScriptSection.Names.EncodedFolders].Lines;
            if (!dirs.Any(d => d.Equals(dirName, StringComparison.OrdinalIgnoreCase)))
            {
                return(LogInfo.LogErrorMessage(logs, $"Directory [{dirName}] not exists in [{scriptFile}]"));
            }

            if (!Directory.Exists(destDir))
            {
                if (File.Exists(destDir))
                {
                    return(LogInfo.LogErrorMessage(logs, $"File [{destDir}] is not a directory"));
                }
                Directory.CreateDirectory(destDir);
            }

            string[] lines = sc.Sections[dirName].Lines;
            Dictionary <string, string> fileDict = IniReadWriter.ParseIniLinesIniStyle(lines);
            int fileCount = fileDict.Count;

            s.MainViewModel.SetBuildCommandProgress("ExtractAndRun Progress", fileCount);
            try
            {
                int i = 0;
                foreach (string file in fileDict.Keys)
                {
                    object             progressLock = new object();
                    IProgress <double> progress     = new Progress <double>(x =>
                    {
                        lock (progressLock)
                        {
                            s.MainViewModel.BuildCommandProgressText  = $"Decompressing \"{file}\"\r\n({(x + i) * 100 / fileCount:0.0}%)";
                            s.MainViewModel.BuildCommandProgressValue = x + i;
                        }
                    });

                    using (FileStream fs = new FileStream(Path.Combine(destDir, file), FileMode.Create, FileAccess.Write))
                    {
                        EncodedFile.ExtractFile(sc, dirName, file, fs, progress);
                    }

                    i += 1;
                }
            }
            finally
            {
                s.MainViewModel.ResetBuildCommandProgress();
            }

            logs.Add(new LogInfo(LogState.Success, $"Encoded folder [{dirName}] was extracted to [{destDir}]"));

            return(logs);
        }
Beispiel #10
0
        public LogInfo SetMacro(string macroName, string macroCommand, ScriptSection section, bool global, bool permanent)
        {
            // Macro Name Validation
            if (!Regex.Match(macroName, MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success)
            {
                return(new LogInfo(LogState.Error, $"Invalid macro name [{macroName}]"));
            }

            if (macroCommand != null)
            { // Insert
                // Try parsing
                CodeParser  parser = new CodeParser(section, Global.Setting, section.Project.Compat);
                CodeCommand cmd    = parser.ParseStatement(macroCommand);
                if (cmd.Type == CodeType.Error)
                {
                    CodeInfo_Error info = cmd.Info.Cast <CodeInfo_Error>();
                    return(new LogInfo(LogState.Error, info.ErrorMessage));
                }

                // Put into dictionary
                if (permanent) // MacroDict
                {
                    GlobalDict[macroName] = cmd;
                    if (IniReadWriter.WriteKey(section.Project.MainScript.RealPath, ScriptSection.Names.Variables, macroName, cmd.RawCode))
                    {
                        return(new LogInfo(LogState.Success, $"Permanent Macro [{macroName}] set to [{cmd.RawCode}]"));
                    }
                    else
                    {
                        return(new LogInfo(LogState.Error, $"Could not write macro into [{section.Project.MainScript.RealPath}]"));
                    }
                }

                if (global) // MacroDict
                {
                    GlobalDict[macroName] = cmd;
                    return(new LogInfo(LogState.Success, $"Global Macro [{macroName}] set to [{cmd.RawCode}]"));
                }

                LocalDict[macroName] = cmd;
                return(new LogInfo(LogState.Success, $"Local Macro [{macroName}] set to [{cmd.RawCode}]"));
            }
            else
            {
                // Delete
                // Put into dictionary
                if (permanent) // MacroDict
                {
                    if (GlobalDict.ContainsKey(macroName))
                    {
                        GlobalDict.Remove(macroName);
                        IniReadWriter.DeleteKey(section.Project.MainScript.RealPath, ScriptSection.Names.Variables, macroName);
                        return(new LogInfo(LogState.Success, $"Permanent Macro [{macroName}] deleted"));
                    }

                    return(new LogInfo(LogState.Error, $"Permanent Macro [{macroName}] not found"));
                }

                if (global) // MacroDict
                {
                    if (GlobalDict.ContainsKey(macroName))
                    {
                        GlobalDict.Remove(macroName);
                        return(new LogInfo(LogState.Success, $"Global Macro [{macroName}] deleted"));
                    }

                    return(new LogInfo(LogState.Error, $"Global Macro [{macroName}] not found"));
                }

                // LocalDict
                if (LocalDict.ContainsKey(macroName))
                {
                    LocalDict.Remove(macroName);
                    return(new LogInfo(LogState.Success, $"Local Macro [{macroName}] deleted"));
                }

                return(new LogInfo(LogState.Error, $"Local Macro [{macroName}] not found"));
            }
        }
Beispiel #11
0
        public Macro(Project project, Variables variables, out List <LogInfo> logs)
        {
            logs = new List <LogInfo>();

            MacroEnabled = true;
            if (!project.MainScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            ScriptSection mainScriptVarSection = project.MainScript.Sections[ScriptSection.Names.Variables];

            Dictionary <string, string> varDict = IniReadWriter.ParseIniLinesVarStyle(mainScriptVarSection.Lines);

            if (!(varDict.ContainsKey(KnownVar.API) && varDict.ContainsKey(KnownVar.APIVAR)))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            // Get macroScript
            string rawScriptPath   = varDict[KnownVar.API];
            string macroScriptPath = variables.Expand(varDict[KnownVar.API]); // Need expansion

            MacroScript = project.AllScripts.Find(x => x.RealPath.Equals(macroScriptPath, StringComparison.OrdinalIgnoreCase));
            if (MacroScript == null)
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro script [{rawScriptPath}"));
                return;
            }

            // Get macroScript
            if (!MacroScript.Sections.ContainsKey(varDict[KnownVar.APIVAR]))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro section [{varDict[KnownVar.APIVAR]}"));
                return;
            }
            MacroSection = MacroScript.Sections[varDict[KnownVar.APIVAR]];
            variables.SetValue(VarsType.Global, KnownVar.API, macroScriptPath);
            if (MacroScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                logs.AddRange(variables.AddVariables(VarsType.Global, MacroScript.Sections[ScriptSection.Names.Variables]));
            }

            // Import Section [APIVAR]'s variables, such as '%Shc_Mode%=0'
            logs.AddRange(variables.AddVariables(VarsType.Global, MacroSection));

            // Parse Section [APIVAR] into MacroDict
            {
                ScriptSection section = MacroSection;
                Dictionary <string, string> rawDict = IniReadWriter.ParseIniLinesIniStyle(MacroSection.Lines);
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success)
                        { // Macro Name Validation
                            CodeParser parser = new CodeParser(section, Global.Setting, section.Project.Compat);
                            GlobalDict[kv.Key] = parser.ParseStatement(kv.Value);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }

            // Parse MainScript's section [Variables] into MacroDict
            // (Written by SetMacro, ... ,PERMANENT
            if (project.MainScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                ScriptSection permaSection          = project.MainScript.Sections[ScriptSection.Names.Variables];
                Dictionary <string, string> rawDict = IniReadWriter.ParseIniLinesIniStyle(permaSection.Lines);
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success)
                        { // Macro Name Validation
                            CodeParser parser = new CodeParser(permaSection, Global.Setting, permaSection.Project.Compat);
                            GlobalDict[kv.Key] = parser.ParseStatement(kv.Value);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }
        }
Beispiel #12
0
        public List <LogInfo> LoadMacroDict(MacroType type, ScriptSection section, IEnumerable <string> lines, bool append)
        {
            Dictionary <string, string> dict = IniReadWriter.ParseIniLinesIniStyle(lines);

            return(LoadMacroDict(type, section, dict, append));
        }
Beispiel #13
0
        public static List <LogInfo> IniWrite(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniWrite info = cmd.Info.Cast <CodeInfo_IniWrite>();

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section);
            string key         = StringEscaper.Preprocess(s, info.Key);
            string value       = StringEscaper.Preprocess(s, info.Value);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");
            Debug.Assert(sectionName != null, $"{nameof(sectionName)} != null");
            Debug.Assert(key != null, $"{nameof(key)} != null");
            Debug.Assert(value != null, $"{nameof(value)} != null");

            if (sectionName.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
            }
            if (key.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty"));
            }

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniWrite");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            // If a dest file does not exist, create an empty file to force ANSI encoding as default in IniReadWriter.
            if (!File.Exists(fileName))
            {
                File.Create(fileName).Dispose();
            }

            bool result;

            if (s.CompatAutoCompactIniWriteCommand)
            {
                result = IniReadWriter.WriteCompactKey(fileName, sectionName, key, value);
            }
            else
            {
                result = IniReadWriter.WriteKey(fileName, sectionName, key, value);
            }

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Key [{key}] and it's value [{value}] written to [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not write key [{key}] and it's value [{value}] to [{fileName}]", cmd));
            }

            return(logs);
        }
Beispiel #14
0
 //改变延时
 private void textBox2_TextChanged(object sender, EventArgs e)
 {
     IniReadWriter.WriteIniKeys("Command", "yanchi", textBox2.Text, ConfigCore.BaseConfig);
 }
Beispiel #15
0
        public static List <LogInfo> IniReadOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniReadOp infoOp = cmd.Info.Cast <CodeInfo_IniReadOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            IniKey[] keys = new IniKey[infoOp.Cmds.Count];
            for (int i = 0; i < keys.Length; i++)
            {
                CodeInfo_IniRead info = infoOp.Infos[i];

                string sectionName = StringEscaper.Preprocess(s, info.Section);
                string key         = StringEscaper.Preprocess(s, info.Key);

                if (sectionName.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
                }
                if (key.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty"));
                }

                keys[i] = new IniKey(sectionName, key);
            }

            keys = IniReadWriter.ReadKeys(fileName, keys);

            int successCount = 0;

            for (int i = 0; i < keys.Length; i++)
            {
                IniKey      kv     = keys[i];
                CodeCommand subCmd = infoOp.Cmds[i];

                if (kv.Value != null)
                {
                    logs.Add(new LogInfo(LogState.Success, $"Key [{kv.Key}] and it's value [{kv.Value}] successfully read", subCmd));

                    string         escapedValue = StringEscaper.Escape(kv.Value, false, true);
                    List <LogInfo> varLogs      = Variables.SetVariable(s, infoOp.Infos[i].DestVar, escapedValue, false, false, false);
                    LogInfo.AddCommand(varLogs, subCmd);
                    logs.AddRange(varLogs);

                    successCount += 1;
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Ignore, $"Key [{kv.Key}] does not exist", subCmd));

                    List <LogInfo> varLogs = Variables.SetVariable(s, infoOp.Infos[i].DestVar, string.Empty, false, false, false);
                    logs.AddRange(varLogs);
                }
            }
            logs.Add(new LogInfo(LogState.Success, $"Read [{successCount}] values from [{fileName}]", cmd));

            return(logs);
        }
Beispiel #16
0
        private ResultReport <Script> InternalUpdateOneScript(Script sc, ScriptStateBackup stateBackup)
        {
            // Never should be triggered, because Script class constructor check it
            Debug.Assert(sc.ParsedVersion != null, $"Local script [{sc.Title}] does not provide proper version information");

            string updateUrl      = sc.UpdateUrl;
            string metaJsonUrl    = Path.ChangeExtension(updateUrl, ".meta.json");
            string metaJsonFile   = FileHelper.GetTempFile(".meta.json");
            string tempScriptFile = FileHelper.GetTempFile(".script");

            try
            {
                // Download .meta.json
                HttpFileDownloader.Report httpReport = DownloadFile(metaJsonUrl, metaJsonFile);
                if (!httpReport.Result)
                {
                    // Failed to send a request, such as network not available
                    if (httpReport.StatusCode == 0)
                    {
                        return(new ResultReport <Script>(false, null, $"Unable to connect to the server"));
                    }

                    // Try downloading .deleted to check if a script is deleted
                    string errorMsg;
                    string deletedUrl  = Path.ChangeExtension(updateUrl, ".deleted");
                    string deletedFile = Path.ChangeExtension(metaJsonFile, ".deleted");
                    try
                    {
                        httpReport = DownloadFile(deletedUrl, deletedFile);
                        if (httpReport.Result)
                        {                                     // Successfully received response
                            if (httpReport.StatusCode == 200) // .deleted file exists in the server
                            {
                                errorMsg = $"[{sc.Title}] was deleted from the server";
                            }
                            else // There is no .deleted file in the server
                            {
                                errorMsg = $"Update is not available for [{sc.Title}]";
                            }
                        }
                        else
                        {
                            if (httpReport.StatusCode == 0) // Failed to send a request, such as network not available
                            {
                                errorMsg = $"Unable to connect to the server";
                            }
                            else
                            {
                                errorMsg = $"Update is not available for [{sc.Title}]";
                            }
                        }
                    }
                    finally
                    {
                        if (File.Exists(deletedFile))
                        {
                            File.Delete(deletedFile);
                        }
                    }

                    return(new ResultReport <Script>(false, null, errorMsg));
                }

                // Check and read .meta.json
                ResultReport <UpdateJson.Root> jsonReport = UpdateJson.ReadUpdateJson(metaJsonFile);
                if (!jsonReport.Success)
                {
                    return(new ResultReport <Script>(false, null, jsonReport.Message));
                }

                UpdateJson.Root      metaJson = jsonReport.Result;
                UpdateJson.FileIndex index    = metaJson.Index;
                if (index.Kind != UpdateJson.IndexEntryKind.Script)
                {
                    return(new ResultReport <Script>(false, null, "Update json is not of a script file"));
                }
                UpdateJson.ScriptInfo scInfo = index.ScriptInfo;
                if (scInfo.Format != UpdateJson.ScriptFormat.IniBased)
                {
                    return(new ResultReport <Script>(false, null, $"Format [{scInfo.Format}] of remote script [{sc.Title}] is not supported"));
                }
                UpdateJson.IniBasedScript iniScInfo = scInfo.IniBased;
                if (iniScInfo.Version <= sc.ParsedVersion)
                {
                    return(new ResultReport <Script>(false, null, $"You are using the lastest version of script [{sc.Title}]"));
                }

                // Download .script file
                httpReport = DownloadFile(updateUrl, tempScriptFile);
                if (!httpReport.Result)
                {
                    return(new ResultReport <Script>(false, null, httpReport.ErrorMsg));
                }

                // Verify downloaded .script file with FileMetadata
                ResultReport verifyReport = index.FileMetadata.VerifyFile(tempScriptFile);
                if (!verifyReport.Success)
                {
                    return(new ResultReport <Script>(false, null, $"Remote script [{sc.Title}] is corrupted"));
                }

                // Check downloaded script's version and check
                // Must have been checked with the UpdateJson
                string    remoteVerStr = IniReadWriter.ReadKey(tempScriptFile, "Main", "Version");
                VersionEx remoteVer    = VersionEx.Parse(remoteVerStr);
                if (remoteVer == null)
                {
                    return(new ResultReport <Script>(false, null, $"Version of remote script [{sc.Title}] is corrupted"));
                }
                if (!remoteVer.Equals(iniScInfo.Version))
                {
                    return(new ResultReport <Script>(false, null, $"Version of remote script [{sc.Title}] is corrupted"));
                }
                if (remoteVer <= sc.ParsedVersion)
                {
                    return(new ResultReport <Script>(false, null, $"Version of remote script [{sc.Title}] is corrupted"));
                }

                // Check if remote script is valid
                Script remoteScript = _p.LoadScriptRuntime(tempScriptFile, new LoadScriptRuntimeOptions
                {
                    IgnoreMain             = false,
                    AddToProjectTree       = false,
                    OverwriteToProjectTree = false,
                });
                if (remoteScript == null)
                {
                    return(new ResultReport <Script>(false, null, $"Remote script [{sc.Title}] is corrupted"));
                }

                // Overwrite backup state to new script
                if (stateBackup != null)
                {
                    RestoreScriptState(remoteScript, stateBackup);

                    // Let's be extra careful
                    remoteScript = _p.RefreshScript(remoteScript);
                    if (remoteScript == null)
                    {
                        return(new ResultReport <Script>(false, null, $"Internal error at {nameof(FileUpdater)}.{nameof(RestoreScriptState)}"));
                    }
                }

                // Copy downloaded remote script into new script
                File.Copy(tempScriptFile, sc.DirectRealPath, true);
                Script newScript = _p.RefreshScript(sc);

                // Return updated script instance
                return(new ResultReport <Script>(true, newScript, $"Updated script [{sc.Title}] to [v{sc.RawVersion}] from [v{newScript.RawVersion}]"));
            }
            finally
            {
                if (File.Exists(metaJsonFile))
                {
                    File.Delete(metaJsonFile);
                }
                if (File.Exists(tempScriptFile))
                {
                    File.Delete(tempScriptFile);
                }
            }
        }
Beispiel #17
0
        public void Base64Decode()
        {
            EngineState s = EngineTests.CreateEngineState();

            void Template(string binFileName, string encFileName, string section, bool inMem)
            {
                string workDir = StringEscaper.Preprocess(s, Path.Combine("%TestBench%", "EncodedFile"));

                // Be careful! encFile will be converted to LF from CRLF in git tree!
                string binFile = Path.Combine(workDir, binFileName);
                string encFile = Path.Combine(workDir, encFileName);

                byte[] binDigest;
                byte[] encDigest;
                using (FileStream fs = new FileStream(binFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    binDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, fs);
                }

                if (inMem)
                {
                    List <string> lines = new List <string>();
                    using (StreamReader r = new StreamReader(encFile, Encoding.UTF8))
                    {
                        string rawLine;
                        while ((rawLine = r.ReadLine()) != null)
                        {
                            string line = rawLine.Trim();
                            if (0 < line.Length)
                            {
                                lines.Add(line);
                            }
                        }
                    }

                    byte[] decoded = SplitBase64.DecodeInMem(lines);
#if DEBUG_MIDDLE_FILE
                    using (FileStream fs = new FileStream(binFile + ".inMem.comp", FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(decoded, 0, decoded.Length);
                    }
#endif
                    encDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, decoded);
                }
                else
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (StreamReader tr = new StreamReader(encFile, Encoding.UTF8))
                        {
                            if (section.Length != 0)
                            {
                                IniReadWriter.FastForwardTextReader(tr, section);
                            }
                            SplitBase64.Decode(tr, ms);
                        }
                        ms.Position = 0;
#if DEBUG_MIDDLE_FILE
                        using (FileStream fs = new FileStream(binFile + ".noMem.comp", FileMode.Create, FileAccess.Write))
                        {
                            ms.CopyTo(fs);
                        }
                        ms.Position = 0;
#endif
                        encDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, ms);
                    }
                }

                Assert.IsTrue(binDigest.SequenceEqual(encDigest));
            }

            Template("BigData.bin", "BigDataEnc4090.txt", string.Empty, true);
            Template("BigData.bin", "BigDataEnc4090.txt", string.Empty, false);
            Template("BigData.bin", "BigDataEnc4090S.txt", "Base64", false);
            Template("Type3.pdf", "Type3Enc4090.txt", string.Empty, true);
            Template("Type3.pdf", "Type3Enc4090.txt", string.Empty, false);
            Template("Type3.pdf", "Type3Enc4090S.txt", "Base64", false);
            Template("Type3.pdf", "Type3Enc1024.txt", string.Empty, true);
            Template("Type3.pdf", "Type3Enc1024.txt", string.Empty, false);
            Template("Type3.pdf", "Type3Enc1024S.txt", "Base64", false);
            // https://github.com/pebakery/pebakery/issues/90
            Template("Type5.bin", "Type5Enc4090.txt", string.Empty, true);
            Template("Type5.bin", "Type5Enc4090.txt", string.Empty, false);
        }
Beispiel #18
0
        //切换任务
        private void ChangeTask()
        {
            if (TaskChange.Equals("1"))
            {
                overTimeCount = 0;
                ConfigCore.InitWorker("");
                CustomPath = ConfigCore.GetCustomPath();
                if (CustomPath != "")
                {
                    LogCore.Write($"切换任务:{CustomPath}");
                }

                if (IsVoteTask() && IsAutoVote)
                {
                    string projectName = ConfigCore.GetAutoVote("ProjectName");
                    string drop        = "";
                    try
                    {
                        drop = IniReadWriter.ReadIniKeys("Command", "drop", "./handler.ini");
                    }
                    catch (Exception)
                    {
                    }

                    if (drop != projectName)
                    {
                        IniReadWriter.WriteIniKeys("Command", "drop", "", "./handler.ini");
                    }
                }
            }

            if (TaskName.Equals(TASK_SYS_WAIT_ORDER)) //待命
            {
                NetCore.DisConnect();
                TaskName = ConfigCore.GetTaskName();
                if (TaskName.Equals(TASK_SYS_WAIT_ORDER))
                {
                    WaitOrder();
                }
            }
            else if (TaskName.Equals(TASK_SYS_NET_TEST)) //网络TEST
            {
                NetCore.NetCheck();
                if (Net.IsOnline())
                {
                    NetCore.DisConnect();
                    WaitOrder();
                }
            }
            else if (TaskName.Equals(TASK_SYS_SHUTDOWN)) //关机
            {
                WaitOrder();
                Process.Start("shutdown.exe", "-s -t 0");
                Form1.MainClose();
            }
            else if (TaskName.Equals(TASK_SYS_RESTART)) //重启
            {
                string computerRename = ConfigCore.GetComputerRename();
                if (!StringUtil.isEmpty(computerRename))
                {
                    Computer.apiSetComputerNameEx(5, computerRename + "-" + ConfigCore.Sort);
                }

                WaitOrder();
                Process.Start("shutdown.exe", "-r -t 0");
                Form1.MainClose();
            }
            else if (TaskName.Equals(TASK_SYS_UPDATE)) //升级
            {
                WaitOrder();
                Upgrade.Update();
                Form1.MainClose();
            }
            else if (TaskName.Equals(TASK_SYS_CLEAN)) //清理
            {
                WaitOrder();
                FileUtil.DeleteFolder(PathCore.WorkingPath + "\\投票项目");
            }
            else if (IsVoteTask()) //投票
            {
                NetCore.NetCheck();
                if (CustomPath.Equals(""))
                {
                    WaitOrder();
                    TaskChangeProcess();
                    return;
                }

                if (TaskChange.Equals("1"))
                {
                    if (CustomPath.LastIndexOf("\\") + 1 <= CustomPath.Length && CustomPath.Substring(CustomPath.LastIndexOf("\\") + 1) == "vote.exe")
                    {
                        ProgressCore.StartProcess(CustomPath.Substring(0, CustomPath.Length - 9) + @"\启动九天.bat");
                        TaskName = TASK_VOTE_JIUTIAN;
                    }
                    else
                    {
                        IniReadWriter.WriteIniKeys("setsoft", "ghid", ConfigCore.Id, "c:\\gonghao.ini");
                        ProgressCore.StartProcess(CustomPath);
                        TaskName = TASK_VOTE_PROJECT;
                        IntPtr hwnd0, hwnd1, hwnd2, hwnd3, hwnd4;
                        do
                        {
                            hwnd0 = HwndUtil.FindWindow("WTWindow", null);
                            hwnd1 = HwndUtil.FindWindow("TForm1", null);
                            hwnd2 = HwndUtil.FindWindow("ThunderRT6FormDC", null);
                            hwnd3 = HwndUtil.FindWindow("obj_Form", null);
                            hwnd4 = HwndUtil.FindWindow("TMainForm", null);
                            if (hwnd0 != IntPtr.Zero)
                            {
                                string title = HwndUtil.GetControlText(hwnd0);
                                if (title.Length >= 6 && title.Substring(0, 6) == "自动投票工具")
                                {
                                    TaskName = TASK_VOTE_MM;
                                }
                                else if (title.Length >= 8 && title.Substring(0, 8) == "VOTE2016")
                                {
                                    TaskName = TASK_VOTE_ML;
                                }
                                else if (title.IndexOf("自动投票软件") != -1)
                                {
                                    TaskName = TASK_VOTE_HY;
                                }
                            }
                            else if (hwnd1 != IntPtr.Zero)
                            {
                                TaskName = TASK_VOTE_YUANQIU;
                            }
                            else if (hwnd2 != IntPtr.Zero)
                            {
                                TaskName = TASK_VOTE_JT;
                            }
                            else if (hwnd3 != IntPtr.Zero)
                            {
                                TaskName = TASK_VOTE_DM;
                            }
                            else if (hwnd4 != IntPtr.Zero)
                            {
                                TaskName = TASK_VOTE_JZ;
                            }

                            Thread.Sleep(500);
                        } while (TaskName.Trim().Equals(TASK_VOTE_PROJECT));
                    }

                    bool safeWrite = false;
                    Thread.Sleep(ConfigCore.Sort % 10 * 50);
                    do
                    {
                        try
                        {
                            ConfigCore.WriteTaskName(TaskName);
                            Thread.Sleep(200);
                            string taskNameCheck = ConfigCore.GetTaskName();
                            if (StringUtil.isEmpty(taskNameCheck) || !taskNameCheck.Equals(TaskName))
                            {
                                LogCore.Write("TaskName Write Error!");
                                ConfigCore.WriteTaskName(TaskName);
                                throw new Exception();
                            }

                            safeWrite = true;
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(ConfigCore.Sort % 10 * 50);
                        }
                    } while (!safeWrite);
                }

                if (TaskName.Equals(TASK_VOTE_JIUTIAN))
                {
                    if (!TaskChange.Equals("1"))
                    {
                        ProgressCore.StartProcess(CustomPath.Substring(0, CustomPath.Length - 9) + @"\启动九天.bat");
                        Thread.Sleep(500);
                    }

                    JiuTian.Start();
                }
                else
                {
                    if (!TaskChange.Equals("1"))
                    {
                        ProgressCore.StartProcess(CustomPath);
                        Thread.Sleep(500);
                    }

                    if (TaskName.Equals(TASK_VOTE_MM))
                    {
                        MM.Start();
                    }
                    else if (TaskName.Equals(TASK_VOTE_ML))
                    {
                        //ML开始程序
                    }
                    else if (TaskName.Equals(TASK_VOTE_YUANQIU))
                    {
                        YuanQiu.Start();
                    }
                    else if (TaskName.Equals(TASK_VOTE_JT))
                    {
                        JT.start();
                    }
                    else if (TaskName.Equals(TASK_VOTE_DM))
                    {
                        //DM开始程序
                    }
                    else if (TaskName.Equals(TASK_VOTE_JZ))
                    {
                        JZ.start();
                    }
                    else if (TaskName.Equals(TASK_VOTE_HY))
                    {
                        HY.Start();
                    }
                }

                TaskPath = CustomPath;
            }
            else
            {
                TaskName = TASK_SYS_WAIT_ORDER;
            }
        }
Beispiel #19
0
        public void RenameFolder()
        {
            EngineState s = EngineTests.CreateEngineState();
            string      originScriptPath = Path.Combine(StringEscaper.Preprocess(s, "%TestBench%"), "EncodedFile", "ExtractFileTests.script");

            // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
            void Template(string oldFolderName, string newFolderName, bool result)
            {
                string destDir    = FileHelper.GetTempDir();
                string destScript = Path.Combine(destDir, "RenameFolderTest.script");

                try
                {
                    File.Copy(originScriptPath, destScript, true);

                    Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions());

                    Dictionary <string, string> fileDict = null;
                    if (result)
                    {
                        fileDict = sc.Sections[oldFolderName].IniDict;
                    }

                    string errMsg;
                    (sc, errMsg) = EncodedFile.RenameFolder(sc, oldFolderName, newFolderName);

                    if (errMsg != null)
                    {
                        Assert.IsFalse(result);
                        return;
                    }
                    Assert.IsTrue(result);

                    Assert.IsFalse(sc.Sections.ContainsKey(oldFolderName));
                    Assert.IsTrue(sc.Sections.ContainsKey(newFolderName));
                    Assert.IsFalse(IniReadWriter.ContainsSection(destScript, oldFolderName));
                    Assert.IsTrue(IniReadWriter.ContainsSection(destScript, newFolderName));

                    string[] folders = sc.Sections[EncodedFolders].Lines;
                    Assert.IsFalse(folders.Contains(oldFolderName, StringComparer.OrdinalIgnoreCase));
                    Assert.IsTrue(folders.Contains(newFolderName, StringComparer.OrdinalIgnoreCase));

                    foreach (string fileName in fileDict.Keys)
                    {
                        Assert.IsFalse(sc.Sections.ContainsKey(GetSectionName(oldFolderName, fileName)));
                        Assert.IsTrue(sc.Sections.ContainsKey(GetSectionName(newFolderName, fileName)));
                    }
                }
                finally
                {
                    if (Directory.Exists(destDir))
                    {
                        Directory.Delete(destDir, true);
                    }
                }
            }

            Template("FolderExample", "RenamedExample", true);
            Template("BannerImage", "BannerRenamed", true);
            Template(AuthorEncoded, "Hello", false);
            Template(InterfaceEncoded, "World", false);
            Template("FolderExample", AuthorEncoded, false);
            Template("BannerImage", InterfaceEncoded, false);
            Template("ShouldFail", "ShouldNotRename", false);
        }
Beispiel #20
0
        public static List <LogInfo> IniWriteOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniWriteOp infoOp = cmd.Info.Cast <CodeInfo_IniWriteOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            IniKey[] keys = new IniKey[infoOp.Cmds.Count];
            for (int i = 0; i < keys.Length; i++)
            {
                CodeInfo_IniWrite info = infoOp.Infos[i];

                string sectionName = StringEscaper.Preprocess(s, info.Section);
                string key         = StringEscaper.Preprocess(s, info.Key);
                string value       = StringEscaper.Preprocess(s, info.Value);

                if (sectionName.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
                }
                if (key.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty"));
                }

                keys[i] = new IniKey(sectionName, key, value);
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniWriteOp");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            bool result = IniReadWriter.WriteKeys(fileName, keys);

            if (result)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    IniKey kv = keys[i];
                    logs.Add(new LogInfo(LogState.Success, $"Key [{kv.Key}] and it's value [{kv.Value}] written", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Success, $"Wrote [{keys.Length}] values to [{fileName}]", cmd));
            }
            else
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    IniKey kv = keys[i];
                    logs.Add(new LogInfo(LogState.Error, $"Could not write key [{kv.Key}] and it's value [{kv.Value}]", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Error, $"Could not write [{keys.Length}] values to [{fileName}]", cmd));
            }

            return(logs);
        }
Beispiel #21
0
 public static int GetMaxKb()
 {
     return(int.Parse(IniReadWriter.ReadIniKeys("Command", "maxKb", PathShareConfig)));
 }
Beispiel #22
0
        public static List <LogInfo> IniDeleteOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniDeleteOp infoOp = cmd.Info.Cast <CodeInfo_IniDeleteOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            IniKey[] keys = new IniKey[infoOp.Cmds.Count];
            for (int i = 0; i < keys.Length; i++)
            {
                CodeInfo_IniDelete info = infoOp.Infos[i];

                string sectionName = StringEscaper.Preprocess(s, info.Section);
                string key         = StringEscaper.Preprocess(s, info.Key);

                if (sectionName.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
                }
                if (key.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty"));
                }

                keys[i] = new IniKey(sectionName, key);
            }

            bool[] result = IniReadWriter.DeleteKeys(fileName, keys);

            int successCount = 0;

            for (int i = 0; i < keys.Length; i++)
            {
                IniKey kv = keys[i];
                if (result[i])
                {
                    successCount += 1;
                    logs.Add(new LogInfo(LogState.Success, $"Key [{kv.Key}] deleted", infoOp.Cmds[i]));
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Ignore, $"Could not delete key [{kv.Key}]", infoOp.Cmds[i]));
                }
            }

            if (0 < successCount)
            {
                logs.Add(new LogInfo(LogState.Success, $"Deleted [{keys.Length}] values from [{fileName}]", cmd));
            }
            if (0 < keys.Length - successCount)
            {
                logs.Add(new LogInfo(LogState.Ignore, $"Could not delete [{keys.Length}] values from [{fileName}]", cmd));
            }

            return(logs);
        }
Beispiel #23
0
 public static void SetTaskChange(String taskChange)
 {
     IniReadWriter.WriteIniKeys("Command", "TaskChange" + Sort, taskChange, PathShareTask);
 }
Beispiel #24
0
        public static List <LogInfo> IniReadSectionOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniReadSectionOp infoOp = cmd.Info.Cast <CodeInfo_IniReadSectionOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");

            string[] sections = new string[infoOp.Cmds.Count];
            string[] destVars = new string[infoOp.Cmds.Count];
            string[] delims   = new string[infoOp.Cmds.Count];
            for (int i = 0; i < sections.Length; i++)
            {
                CodeInfo_IniReadSection info = infoOp.Infos[i];

                string section = StringEscaper.Preprocess(s, info.Section);
                if (section.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
                }

                sections[i] = section;
                destVars[i] = info.DestVar;
                delims[i]   = "|";
                if (info.Delim != null)
                {
                    delims[i] = StringEscaper.Preprocess(s, info.Delim);
                }
            }

            Dictionary <string, IniKey[]> keyDict = IniReadWriter.ReadSections(fileName, sections);

            int successCount = 0;

            for (int i = 0; i < sections.Length; i++)
            {
                string      section = sections[i];
                string      delim   = delims[i];
                IniKey[]    keys    = keyDict[section];
                CodeCommand subCmd  = infoOp.Cmds[i];

                if (keys != null)
                {
                    List <string> kvList = new List <string>(keys.Length * 2);
                    foreach (IniKey k in keys)
                    {
                        kvList.Add(k.Key);
                        kvList.Add(k.Value);
                    }
                    string destStr = StringEscaper.PackListStr(kvList, delim);
                    logs.Add(new LogInfo(LogState.Success, $"Section [{section}] read", subCmd));

                    string         escapedValue = StringEscaper.Escape(destStr, false, true);
                    List <LogInfo> varLogs      = Variables.SetVariable(s, destVars[i], escapedValue, false, false, false);
                    LogInfo.AddCommand(varLogs, subCmd);
                    logs.AddRange(varLogs);
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Ignore, $"Section [{section}] does not exist", subCmd));

                    List <LogInfo> varLogs = Variables.SetVariable(s, destVars[i], string.Empty, false, false, false);
                    LogInfo.AddCommand(varLogs, subCmd);
                    logs.AddRange(varLogs);
                }
            }
            logs.Add(new LogInfo(LogState.Success, $"Read [{successCount}] sections from [{fileName}]", cmd));

            return(logs);
        }
Beispiel #25
0
 public static String GetCustomPath()
 {
     return(IniReadWriter.ReadIniKeys("Command", "customPath" + Sort, PathShareTaskPlus));
 }
Beispiel #26
0
        public static List <LogInfo> IniAddSectionOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniAddSectionOp infoOp = cmd.Info.Cast <CodeInfo_IniAddSectionOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string[] sections = new string[infoOp.Cmds.Count];
            for (int i = 0; i < sections.Length; i++)
            {
                CodeInfo_IniAddSection info = infoOp.Infos[i];

                string sectionName = StringEscaper.Preprocess(s, info.Section);
                if (sectionName.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
                }

                sections[i] = sectionName;
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniAddSectionOp");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            bool result = IniReadWriter.AddSections(fileName, sections);

            if (result)
            {
                for (int i = 0; i < sections.Length; i++)
                {
                    logs.Add(new LogInfo(LogState.Success, $"Section [{sections[i]}] added", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Success, $"Added [{sections.Length}] sections to [{fileName}]", cmd));
            }
            else
            {
                for (int i = 0; i < sections.Length; i++)
                {
                    logs.Add(new LogInfo(LogState.Error, $"Could not add section [{sections[i]}]", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Error, $"Could not add [{sections.Length}] sections to [{fileName}]", cmd));
            }

            return(logs);
        }
Beispiel #27
0
 public static void ClearCacheMemory()
 {
     IniReadWriter.WriteIniKeys("Command", "CacheMemory" + Sort, "", PathShareTaskPlus);
 }
Beispiel #28
0
        public async Task UpdateScript()
        {
            string destDir = FileHelper.GetTempDir();

            try
            {
                // Prepare running FileUpdater
                string srcScriptFile      = Path.Combine(TestSetup.WebRoot, "Updater", "Standalone", "PreserveInterface_r1.script");
                string workScriptFile     = Path.Combine(destDir, "PreserveInterface.script");
                string workScriptTreePath = Path.Combine("TestSuite", "Updater", "PreserveInterface.script");
                File.Copy(srcScriptFile, workScriptFile);
                IniReadWriter.WriteKey(workScriptFile, "ScriptUpdate", "Url", @$ "http://localhost:{TestSetup.ServerPort}/Updater/Standalone/PreserveInterface_r2.script");

                Project p  = EngineTests.Project;
                Script  sc = p.LoadScriptRuntime(workScriptFile, workScriptTreePath, new LoadScriptRuntimeOptions
                {
                    AddToProjectTree       = true,
                    IgnoreMain             = false,
                    OverwriteToProjectTree = true,
                });

                // Run an update
                FileUpdater updater = new FileUpdater(EngineTests.Project, null, null);
                (Script newScript, LogInfo log) = await updater.UpdateScriptAsync(sc, true);

                // Validate updated script
                Console.WriteLine(log);
                Assert.IsNotNull(newScript);
                Assert.IsTrue(newScript.TidyVersion.Equals("1.2", StringComparison.Ordinal));
                Assert.AreEqual(SelectedState.True, newScript.Selected);
                IniKey[] keys =
                {
                    new IniKey("Interface",       "checkbox02"),
                    new IniKey("Interface",       "ComboBox02"),
                    new IniKey("Interface",       "bvl_Top"),
                    new IniKey("Interface",       "ComboBox01"),
                    new IniKey("Interface",       "CheckBox01"),
                    new IniKey("Interface",       "Button01"),
                    new IniKey("Interface",       "CheckBox03"),
                    new IniKey("ThirdInterface",  "RadioGroup01"),
                    new IniKey("FourthInterface", "RadioButton01"),
                    new IniKey("FourthInterface", "RadioButton02"),
                    new IniKey("FourthInterface", "RadioButton03"),
                };

                keys = IniReadWriter.ReadKeys(newScript.RealPath, keys);
                Dictionary <string, string> ifaceDict = keys.Where(x => x.Section.Equals("Interface"))
                                                        .ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);
                Assert.IsTrue(ifaceDict["checkbox02"].Equals("checkbox02,1,3,10,10,200,18,False", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["ComboBox02"].Equals("C,1,4,262,120,150,22,A,B,C", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["bvl_Top"].Equals("\"Updated\",1,12,254,101,228,70,8,Normal", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["ComboBox01"].Equals("A,1,4,42,66,150,21,A,B,C", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["CheckBox01"].Equals("CheckBox01,1,3,42,98,173,18,False", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["Button01"].Equals("Button01,1,8,262,46,80,25,TestSection,0,False", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["CheckBox03"].Equals("CheckBox03,1,3,100,400,200,18,True", StringComparison.Ordinal));

                ifaceDict = keys.Where(x => x.Section.Equals("ThirdInterface"))
                            .ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);
                Assert.IsTrue(ifaceDict["RadioGroup01"].Equals("RadioGroup01,1,14,10,30,150,60,A,B,C,1", StringComparison.Ordinal));

                ifaceDict = keys.Where(x => x.Section.Equals("FourthInterface"))
                            .ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);
                Assert.IsTrue(ifaceDict["RadioButton01"].Equals("A,1,11,10,30,120,20,False", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["RadioButton02"].Equals("B,1,11,10,50,120,20,False", StringComparison.Ordinal));
                Assert.IsTrue(ifaceDict["RadioButton03"].Equals("C,1,11,10,70,120,20,True", StringComparison.Ordinal));

                Assert.IsFalse(IniReadWriter.ContainsSection(newScript.RealPath, "SecondInterface"));
            }
            finally
            {
                if (Directory.Exists(destDir))
                {
                    Directory.Delete(destDir, true);
                }
            }
        }