Execute a script
Execute script code
You can execute a C# script using the ExecuteScriptCode
method of the IApplication
object.
public void ExecuteScriptCode(ICommandContext c, ICommandParams p)
{
var script = @"
var currentProject = CurrentProject;
if ( currentProject == null ) return;
App.Output.WriteLine(""sample"",currentProject.Name);";
//Execute the script
c.App.ExecuteScriptCode(script,"cs");
}
The return value of the script returns the result object of the script's return statement. If the script does not have a return statement, it returns null.
public void ExecuteScriptCode(ICommandContext c, ICommandParams p)
{
var script = @"return CurrentProject.?Name";
//Execute the script
var result = c.App.ExecuteScriptCode(script, "cs");
if (result == null) result = "(null)";
c.App.Output.WriteLine("sample", result.ToString());
}
Execute a script file
Loads and executes the script file specified by the ExecuteScript
method of the IApplication
object.
public void ExecuteScript(ICommandContext c, ICommandParams p)
{
//Absolute path of the script file
var scriptFilePath = "c:/data/myscript.cs";
//Execute the script
c.App.ExecuteScript(scriptFilePath);
}
Pass parameters to the script
You can pass parameters to the script.
public void ExecuteScript(ICommandContext c, ICommandParams p)
{
IScriptParams scriptParams = c.App.CreateScriptParams();
scriptParams.AddParamWithName("modelName", "ABC");
scriptParams.AddParamWithName("close", true);
//Execute the script
c.App.ExecuteScript("c:/data/myscript.cs", scriptParams);
}
You can handle parameters in the script with the Params
object like this:
var modelName = Params["modelName"];
var close = (bool)Params["close"];
//...