Esempio n. 1
0
        public bool Update()
        {
            // Update ScriptSection.Lines
            Section.UpdateIniKey(Key, ForgeRawLine(false));

            // Update actual file
            return(IniReadWriter.WriteKey(Section.Script.RealPath, Section.Name, Key, ForgeRawLine(false)));
        }
Esempio n. 2
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);
            }

            bool 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);
        }
Esempio n. 3
0
        /// <summary>
        /// To the best-effort to restore script state
        /// </summary>
        /// <remarks>
        /// This method does not refresh the Script instance, it is the responsibility of a callee
        /// </remarks>
        private static void RestoreScriptState(Script sc, ScriptStateBackup backup)
        {
            List <string> ifaceSectionNames = sc.GetInterfaceSectionNames(false);

            // Restore selected state
            IniReadWriter.WriteKey(sc.RealPath, ScriptSection.Names.Main, Script.Const.Selected, backup.Selected.ToString());

            // Restore interfaces
            List <UIControl> newCtrls = new List <UIControl>();

            foreach (var kv in backup.IfaceSectionDict)
            {
                string           ifaceSectionName = kv.Key;
                List <UIControl> bakCtrls         = kv.Value;

                if (!ifaceSectionNames.Contains(ifaceSectionName))
                {
                    continue;
                }

                (List <UIControl> uiCtrls, _) = sc.GetInterfaceControls(ifaceSectionName);
                foreach (UIControl uiCtrl in uiCtrls)
                {
                    // Get old uiCtrl, equality identified by Type and Key.
                    UIControl bakCtrl = bakCtrls.FirstOrDefault(bak => bak.Type == uiCtrl.Type && bak.Key.Equals(uiCtrl.Key, StringComparison.OrdinalIgnoreCase));
                    if (bakCtrl == null)
                    {
                        continue;
                    }

                    // Get old value
                    string bakValue = bakCtrl.GetValue(false);
                    Debug.Assert(bakValue != null, "Internal Logic Error at FileUpdater.RestoreInterface");

                    // Add to newCtrls only if apply was successful
                    if (uiCtrl.SetValue(bakValue, false, out _))
                    {
                        newCtrls.Add(uiCtrl);
                    }
                }
            }

            // Write to file
            UIControl.Update(newCtrls);
        }
Esempio n. 4
0
        public async Task DeletedScript()
        {
            string destDir = FileHelper.GetTempDir();

            try
            {
                // Prepare running FileUpdater
                string workbench          = EngineTests.Project.Variables["TestBench"];
                string srcScriptFile      = Path.Combine(workbench, "FileUpdater", "Removed.script");
                string workScriptFile     = Path.Combine(destDir, "Removed.script");
                string workScriptTreePath = Path.Combine("TestSuite", "Updater", "Removed.script");
                File.Copy(srcScriptFile, workScriptFile);
                IniReadWriter.WriteKey(workScriptFile, "ScriptUpdate", "Url", @$ "http://localhost:{TestSetup.ServerPort}/Updater/Standalone/Removed.script");

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

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

                Console.WriteLine(log.ToString());
                Assert.IsTrue(log.Message.Equals($"[{sc.Title}] was deleted from the server", StringComparison.Ordinal));
                Assert.IsNull(newScript);
            }
            finally
            {
                if (Directory.Exists(destDir))
                {
                    Directory.Delete(destDir, true);
                }
            }
        }
Esempio n. 5
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"));
            }
        }
Esempio n. 6
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);
                }
            }
        }