static void Main() { CSScript.GlobalSettings.UseAlternativeCompiler = Path.GetFullPath("CSSCodeProvider.dll"); //compiler that understands JS/VB.NET/C++ and classless-C# var script = new AsmHelper(CSScript.Load("Hello.js")); script.Invoke("*.Main"); }
void ExecuteAndUnloadScript(string script) { using (CSScriptLibrary.AsmHelper helper = new CSScriptLibrary.AsmHelper(CSScriptLibrary.CSScript.Compile(Path.GetFullPath(script), null, true), null, true)) { helper.Invoke("*.Execute", this); } }
void ExecuteAndUnloadScript(string script) { using (AsmHelper helper = new AsmHelper(CSScript.Compile(script, Path.GetFullPath("ExternalAsm.dll")), null, true)) { helper.Invoke("*.Execute"); } }
static void ExecuteAndUnloadScript(string script) { using (AsmHelper helper = new AsmHelper(CSScript.Compile(script), null, true)) { helper.Invoke("*.Execute"); } }
/// <summary> /// Executes the script and adds it to the current app domain /// NOTE: This locks the assembly script file /// </summary> public void ExecuteScriptInternal(String script, Boolean random) { if (!File.Exists(script)) throw new FileNotFoundException(); String file = random ? Path.GetTempFileName() : null; AsmHelper helper = new AsmHelper(CSScript.Load(script, file, false, null)); helper.Invoke("*.Execute"); }
void Start() { CreateDocument(); var script = new AsmHelper(CSScript.Load("script.cs", null, true)); script.Invoke("*.Execute", this); }
static void CallStaticMethodOfTheOnlyClassAvailableInClasslessScript() { CSScript.GlobalSettings.UseAlternativeCompiler = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\Lib\CSSCodeProvider.dll"); var helper = new AsmHelper(CSScript.Load("script1.ccs", null, true)); helper.Invoke("*.SayHello", "Hello World!"); }
static void CallStaticMethodOfSpecifiedClassWithNamespaceInClasslessScript() { CSScript.GlobalSettings.UseAlternativeCompiler = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\Lib\CSSCodeProvider.dll"); var helper = new AsmHelper(CSScript.Load("script2.ccs", null, true)); helper.Invoke("MyNamespace.MyClass.SayHello", "Hello World!"); }
/// <summary> /// Executes the script in a seperate appdomain and then unloads it /// NOTE: This is more suitable for one pass processes /// </summary> public void ExecuteScriptExternal(String script) { if (!File.Exists(script)) throw new FileNotFoundException(); using (AsmHelper helper = new AsmHelper(CSScript.Compile(script, null, true), null, true)) { helper.Invoke("*.Execute"); } }
static void CallStaticMethod1() { //AsmHelper allows accessing scripts methods with wild card Assembly assembly = CSScript.LoadMethod( @"public static void SayHello(string greeting) { Console.WriteLine(greeting); }"); AsmHelper script = new AsmHelper(assembly); script.Invoke("*.SayHello", "Hello World!"); }
static void Main() { string code = @"using System; public class Script { public static string Main() { return ""Main0""; } public static string Main(string args) { return ""Main1""; } public static string Main(string[] args) { return ""MainN""; } public static string Main(string[] args, int count) { return ""MainN1""; } }"; string asmFile = CSScript.CompileCode(code); using (AsmHelper helper = new AsmHelper(asmFile, "", true)) { string[] args = new string[0]; Console.WriteLine(helper.Invoke("Script.Main")); //Main0 Console.WriteLine(helper.Invoke("Script.Main", "test arg")); //Main1 Console.WriteLine(helper.Invoke("Script.Main", new object[] { args })); //MainN Console.WriteLine(helper.Invoke("Script.Main", new object[] { new string[0] })); //MainN Console.WriteLine(helper.Invoke("Script.Main", args, 7)); //MainN1 } }
static void CallStaticMethodOfDefaultClassInClasslessScript() { //There is a script file to execute. //The script consist of the only method definition. //Autoclass is injected by CS-Script engine and user has no control //on class name, which is always Scripting.DynamicClass CSScript.GlobalSettings.UseAlternativeCompiler = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\Lib\CSSCodeProvider.dll"); var helper = new AsmHelper(CSScript.Load("script1.ccs", null, true)); helper.Invoke("script1.Script.SayHello", "Hello World!"); }
void Initialise() { InitializeComponent(); upBtn.Text = downBtn.Text = ""; if (Environment.Version.Major >= 2) { // the following code must be generated dynamically as ShellEx is guaranteed to be run //under CLR 1.1 as part of the installation sequence (config.cs) and 1.1 cannot handle //"this.treeView1.DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(this.treeView1_DrawNode);" treeViewExtension = new AsmHelper(CSScript.LoadCode(treeViewExtensionCode, null, false, this.GetType().Assembly.Location)); treeViewExtension.Invoke("*.Extend", treeView1); } }
static void Run1() { var code = @"public static void Hello(string greeting) { SayHello(greeting); } static void SayHello(string greeting) { Console.WriteLine(greeting); }"; var script = new AsmHelper(CSScript.LoadMethod(code)); // /call first Hello method found with Reflection based MethodInvoker script.Invoke("*.Hello", "Hello World!"); }
public static void Main(string[] args) { try { // Create a new, empty permission set so we don't mistakenly grant some permission we don't want PermissionSet permissionSet = new PermissionSet(PermissionState.None); // Set the permissions that you will allow, in this case we only want to allow execution of code permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); // Make sure we have the permissions currently permissionSet.Demand(); // Create the security policy level for this application domain PolicyLevel policyLevel = PolicyLevel.CreateAppDomainLevel(); // Give the policy level's root code group a new policy statement based on the new permission set. policyLevel.RootCodeGroup.PolicyStatement = new PolicyStatement(permissionSet); CSScript.GlobalSettings.AddSearchDir(Environment.CurrentDirectory); File.Copy("Danger.cs", "Danger1.cs", true); var script = new AsmHelper(CSScript.Load("Danger.cs")); // Update the application domain's policy now AppDomain.CurrentDomain.SetAppDomainPolicy(policyLevel); var script1 = new AsmHelper(CSScript.Load("Danger1.cs")); Console.WriteLine(); Console.WriteLine("Access local file from host application assembly..."); using (FileStream f = File.Open("somefile.txt", FileMode.OpenOrCreate)) //OK because executing assembly was loaded before the new policy set Console.WriteLine(" Ok"); Console.WriteLine(); Console.WriteLine("Access local file from Script assembly (before security policy set)..."); script.Invoke("*.SayHello"); //OK because executing assembly was loaded before the new policy set Console.WriteLine(); Console.WriteLine("Access local file from Script assembly (after security policy set)...\n"); script1.Invoke("*.SayHello"); //ERROR because executing assembly was loaded after the new policy set Console.WriteLine("The end..."); } catch (Exception e) { Console.WriteLine(); Console.WriteLine(e.Message); Console.WriteLine(); } }
/// <summary> /// Previews the section form, but no change made. /// </summary> /// <param name="packageClass">The package class.</param> /// <param name="sectionItem">The param collection.</param> public void Preview(PackageClass packageClass, SectionItem sectionItem) { MessageBox.Show("This is a non visual Section. Nothing to show"); bool state = false; try { Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; AsmHelper script = new AsmHelper(CSScript.LoadCode(sectionItem.Params[Const_script].Value, Path.GetTempFileName(), true)); state = (bool)script.Invoke("Script.GetState", packageClass, sectionItem); MessageBox.Show("Result of script : " + state.ToString()); } catch (Exception ex) { MessageBox.Show("Eror in script : " + ex.Message); } }
static void Main() { string code = @"using System; public class Script { public static void SayHello(string greeting) { Console.WriteLine(""Static: "" + greeting); } public void Say(string greeting) { Console.WriteLine(""Instance: "" + greeting); } }"; var script = new AsmHelper(CSScript.LoadCode(code, null, true)); //call static method script.Invoke("*.SayHello", "Hello World! (invoke)"); //call static method via emitted FastMethodInvoker var SayHello = script.GetStaticMethod("*.SayHello", ""); SayHello("Hello World! (emitted method)"); object obj = script.CreateObject("Script"); //call instance method script.InvokeInst(obj, "*.Say", "Hello World! (invoke)"); //call instance method via emitted FastMethodInvoker var Say = script.GetMethod(obj, "*.Say", ""); Say("Hello World! (emitted method)"); //call using C# 4.0 Dynamics dynamic script1 = CSScript.LoadCode(code) .CreateObject("*"); script1.Say("Hello World! (dynamic object)"); //call using CS-Scrit Interface Alignment IScript script2 = obj.AlignToInterface<IScript>(); script2.Say("Hello World! (aligned interface)"); }
static void CallStaticMethodOfFreeStandingClasslessCode() { //There is no script. //The code consist of the only method definition. //Autoclass is injected by CS-Script engine and user has no control //on class name, which is always Scripting.DynamicClass var assembly = CSScript.LoadMethod( @"public static void SayHello(string greeting) { Console.WriteLine(greeting); }"); AsmHelper script = new AsmHelper(assembly); script.Invoke("*.SayHello", "Hello World!"); //or var SayHello = script.GetStaticMethod(); SayHello("Hello World!"); }
public static void RunCode(string name, string code) { if (string.IsNullOrEmpty(code)) { return; } try { code = GetCode(code); var script = new AsmHelper(CSScript.LoadMethod(code)); script.Invoke("*.Run"); } catch (ThreadAbortException) { } catch (Exception e) { Logging.Write(LogType.Error, "Error running script: {0}:{1} ", name, e.Message); } }
public override bool Action(string action) { bool result = base.Action(action); if (result && action == ACTION_SETTINGS) { using (System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog()) { if (dlg.ShowDialog()== System.Windows.Forms.DialogResult.OK) { ClearActions(); PluginSettings.Instance.UserScriptsFolder = dlg.SelectedPath; Core.CSScriptsPath = PluginSettings.Instance.UserScriptsFolder; LoadFolder(PluginSettings.Instance.UserScriptsFolder); InitFileSystemWatcher(); } } } else if (result && action == ACTION_REFRESH) { ClearActions(); LoadFolder(PluginSettings.Instance.UserScriptsFolder); } else { try { if (!_allAssembliesLoaded) { using (Utils.API.GeocachingLiveV6 client = new Utils.API.GeocachingLiveV6(Core)) { //to load assembly } string s = System.Web.HttpUtility.HtmlEncode("hallo"); s = ""; _allAssembliesLoaded = true; } AsmHelper scriptAsm = new AsmHelper(CSScript.Load(_availableScripts[action].ToString())); result = (bool)scriptAsm.Invoke("Script.Run", new object[] { this, Core }); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message, "Error"); } } return result; }
public SectionResponseEnum Execute(PackageClass packageClass, SectionItem sectionItem) { Base.ActionExecute(packageClass, sectionItem, ActionExecuteLocationEnum.BeforPanelShow); Base.ActionExecute(packageClass, sectionItem, ActionExecuteLocationEnum.AfterPanelShow); Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; bool state = false; try { AsmHelper script = new AsmHelper(CSScript.LoadCode(sectionItem.Params[Const_script].Value, Path.GetTempFileName(), true)); state = (bool)script.Invoke("Script.GetState", packageClass, sectionItem); } catch (Exception ex) { if (!packageClass.Silent) MessageBox.Show("Eror in script : " + ex.Message); state = false; } foreach (string includedGroup in sectionItem.IncludedGroups) { packageClass.Groups[includedGroup].Checked = state; } Base.ActionExecute(packageClass, sectionItem, ActionExecuteLocationEnum.AfterPanelHide); return SectionResponseEnum.Ok; }
private void SetValues(SectionItem sectionItem) { Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; try { AsmHelper script = new AsmHelper(CSScript.LoadCode(sectionItem.Params[CONST_SHOW_SCRIPT].Value, Path.GetTempFileName(), true)); script.Invoke("Script.Main", _packageClass, sectionItem, this); } catch (Exception ex) { if (!_packageClass.Silent) MessageBox.Show("Eror in script : " + ex.Message); } }
void ExecuteScript(string script) { AsmHelper helper = new AsmHelper(CSScript.Load(script, Path.GetFullPath("ExternalAsm.dll"))); helper.Invoke("*.Execute"); }
void ExecuteScript(string script) { var helper = new AsmHelper(CSScript.Load(script, null, true)); helper.Invoke("*.Execute", this); }
void ExecuteScript(string script) { CSScriptLibrary.AsmHelper helper = new CSScriptLibrary.AsmHelper(CSScriptLibrary.CSScript.Load(script, null, true)); helper.Invoke("*.Execute", this); }
public void GetRawSheetData(RawSheetConfig sheetConfig, DataTable rawSheetData, DataTable rawFormulaTable, DataTable rawTitleData, AsmHelper filterScript) { try { Worksheet sheet = workbook.Worksheets[sheetConfig.RawSheetIndex]; if (sheet == null) return; #region Read Data int rowIndex = sheetConfig.GetStartRow; var columns = sheetConfig.DataColumns; var nullSkipColumnName = sheetConfig.NullSkipColumn; string checkEndCellName; string checkEndValue; RawSheetDataColumn nullSkipColumn; string nullSkipCellName; string nullSkipCellValue; string cellName; object cellValue; while (true) { checkEndCellName = string.Concat(sheetConfig.CheckEndCell, rowIndex); checkEndValue = GetCellStringValue(sheet, checkEndCellName); if (checkEndValue.Trim().ToUpper() == sheetConfig.CheckEndValue.Trim().ToUpper()) break; if (!string.IsNullOrEmpty(nullSkipColumnName)) { nullSkipColumn = columns.Single(c => c.Name == nullSkipColumnName); if (nullSkipColumn != null) { nullSkipCellName = string.Concat(nullSkipColumn.GetCell, rowIndex); nullSkipCellValue = GetCellStringValue(sheet, nullSkipCellName); if (string.IsNullOrEmpty(nullSkipCellValue.Trim())) { rowIndex++; continue; } } } DataRow dr = rawSheetData.NewRow(); DataRow formulaDR = null; if (rawFormulaTable != null) { formulaDR = rawFormulaTable.NewRow(); } foreach (var column in columns) { cellName = string.Concat(column.GetCell, rowIndex); cellValue = GetCellValue(sheet, column, cellName); dr[column.Name] = cellValue; if (column.ContainFormula && formulaDR != null) { formulaDR[column.Name] = GetCellFormula(sheet, cellName); } } if (filterScript != null) { var filterResult = (bool)filterScript.Invoke(sheetConfig.FilterMethod, new object[] { dr }); if (true == filterResult) { rawSheetData.Rows.Add(dr); if (rawFormulaTable != null && formulaDR != null) { rawFormulaTable.Rows.Add(formulaDR); } } } else { rawSheetData.Rows.Add(dr); if (rawFormulaTable != null && formulaDR != null) { rawFormulaTable.Rows.Add(formulaDR); } } rowIndex++; } #endregion #region Read Title Data if (rawTitleData != null) { var titleColumns = sheetConfig.TitleDataColumns; DataRow dr = rawTitleData.NewRow(); foreach (var column in titleColumns) { dr[column.Name] = GetCellValue(sheet, column, column.GetCell); } rawTitleData.Rows.Add(dr); } #endregion } catch (System.Exception ex) { FinaChanLogger.Info("Occured error when load raw data of {0} worksheet, caused by: {1}, details: {2}", sheetConfig.Name, ex.Message, ex.StackTrace); throw ex; } }
/// <summary> /// Evaluates an expression in Cs-Script /// </summary> /// <param name="input"></param> private void Evaluate( string input ) { string boilerplate = @" using Sept1983Client; private static CssInterpreter hostEnvironment; private static void log(string message) {{ hostEnvironment.WriteLine(message); }} private static void run(string fileName, string className) {{ hostEnvironment.LoadScript(fileName, className); }} public static void Evaluate(CssInterpreter callee) {{ hostEnvironment = callee; {0}; // here goes the code that is to be evaluated. }}"; var script = new AsmHelper(CSScript.LoadMethod(string.Format(boilerplate, input))); script.Invoke("*.Evaluate", this); }
private void buttonGenerate_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { GenerateScript(); //todo: background! File.WriteAllText(_scriptFile.Path, textBoxGeneratedScript.Text); AsmHelper scriptAsm = new AsmHelper(CSScript.Load(_scriptFile.Path)); string result = (string)scriptAsm.Invoke("StatisticsTemplate.Run", new object[] { this.OwnerPlugin, Core }); textBoxHtml.Text = result; DisplayHtml(string.Format("<html><head></head><body>{0}</body></html>", result)); tabControl1.SelectedIndex = 3; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, "Error"); } this.Cursor = Cursors.Default; }
static void CallStaticMethod5() { //With LoadMethod() you can load code containing multiple methods and you can also //specify namespaces var script = new AsmHelper(CSScript.LoadMethod( @"using System.Windows.Forms; public static void SayHello(string greeting) { MessageBoxSayHello(greeting); ConsoleSayHello(greeting); } public static void MessageBoxSayHello(string greeting) { MessageBox.Show(greeting); } public static void ConsoleSayHello(string greeting) { Console.WriteLine(greeting); }")); script.Invoke("*.SayHello", "Hello World!"); }
protected override bool Execute() { if (Values[0] != "") { try { AsmHelper scriptAsm = new AsmHelper(CSScript.Load(Path.Combine(Core.CSScriptsPath, string.Format("{0}.cs", Values[0])))); scriptAsm.Invoke("Script.Run", new object[] { Utils.PluginSupport.PluginByName(Core, "GlobalcachingApplication.Plugins.ActBuilder.ActionBuilder"), Core }); } catch { } } return true; }