private static void ExecuteManagedScript <T>(ref ScriptRuntime runtime) where T : ScriptEngine, new() { // 1: ---------------------------------------------------------------------------------------------------- // get new engine manager (EngineManager manages document-specific engines) // and ask for an engine (EngineManager return either new engine or an already active one) T engine = ScriptEngineManager.GetEngine <T>(ref runtime); // init the engine engine.Start(ref runtime); // execute var result = engine.Execute(ref runtime); // stop and cleanup the engine engine.Stop(ref runtime); // set result runtime.ExecutionResult = result; }
public static void LogScriptTelemetryRecord(ref ScriptRuntime runtime) { var env = new EnvDictionary(); var record = MakeTelemetryRecord(ref runtime); if (env.TelemetryServerUrl != null && !string.IsNullOrEmpty(env.TelemetryServerUrl)) { new Task(() => Telemetry.PostTelemetryRecord(env.TelemetryServerUrl, record)).Start(); } if (env.TelemetryFilePath != null && !string.IsNullOrEmpty(env.TelemetryFilePath)) { new Task(() => Telemetry.WriteTelemetryRecord(env.TelemetryFilePath, record)).Start(); } }
public override void Start(ref ScriptRuntime runtime) { if (!RecoveredFromCache) { using (Py.GIL()) { // initialize if (!PythonEngine.IsInitialized) { PythonEngine.Initialize(); } } } SetupBuiltins(ref runtime); SetupStreams(ref runtime); SetupCaching(ref runtime); SetupSearchPaths(ref runtime); SetupArguments(ref runtime); }
public override void Init(ref ScriptRuntime runtime) { base.Init(ref runtime); // extract engine configuration from runtime data try { ExecEngineConfigs = new JavaScriptSerializer().Deserialize <IronPythonEngineConfigs>(runtime.ScriptRuntimeConfigs.EngineConfigs); } catch { // if any errors switch to defaults ExecEngineConfigs.clean = false; ExecEngineConfigs.full_frame = false; ExecEngineConfigs.persistent = false; } // If the command required a fullframe engine // or if the command required a clean engine // of if the user is asking to refresh the cached engine for the command, UseNewEngine = ExecEngineConfigs.clean || runtime.ScriptRuntimeConfigs.RefreshEngine; }
public override void Start(ref ScriptRuntime runtime) { if (!RecoveredFromCache) { var flags = new Dictionary <string, object>(); // default flags flags["LightweightScopes"] = true; if (ExecEngineConfigs.full_frame) { flags["Frames"] = true; flags["FullFrames"] = true; flags["Tracing"] = true; } Engine = IronPython.Hosting.Python.CreateEngine(flags); // also, allow access to the PyRevitLoader internals Engine.Runtime.LoadAssembly(typeof(PyRevitLoader.ScriptExecutor).Assembly); // also, allow access to the PyRevitRuntime internals Engine.Runtime.LoadAssembly(typeof(ScriptExecutor).Assembly); // reference RevitAPI and RevitAPIUI Engine.Runtime.LoadAssembly(typeof(Autodesk.Revit.DB.Document).Assembly); Engine.Runtime.LoadAssembly(typeof(Autodesk.Revit.UI.TaskDialog).Assembly); // save the default stream for later resetting the streams DefaultOutputStreamConfig = new Tuple <Stream, System.Text.Encoding>(Engine.Runtime.IO.OutputStream, Engine.Runtime.IO.OutputEncoding); DefaultInputStreamConfig = new Tuple <Stream, System.Text.Encoding>(Engine.Runtime.IO.InputStream, Engine.Runtime.IO.InputEncoding); // setup stdlib SetupStdlib(Engine); } SetupStreams(ref runtime); SetupBuiltins(ref runtime); SetupSearchPaths(ref runtime); SetupArguments(ref runtime); }
private void SetupSearchPaths(ref ScriptRuntime runtime) { // set sys paths PyList sysPaths = RestoreSearchPaths(); // manually add PYTHONPATH since we are overwriting the sys paths var pythonPath = Environment.GetEnvironmentVariable("PYTHONPATH"); if (pythonPath != null && pythonPath != string.Empty) { var searthPathStr = new PyString(pythonPath); sysPaths.Insert(0, searthPathStr); } // now add the search paths for the script bundle foreach (string searchPath in runtime.ScriptRuntimeConfigs.SearchPaths.Reverse <string>()) { var searthPathStr = new PyString(searchPath); sysPaths.Insert(0, searthPathStr); } }
private void SetupArguments(ref ScriptRuntime runtime) { // setup arguments (sets sys.argv) PyObject sys = PythonEngine.ImportModule("sys"); PyObject sysArgv = sys.GetAttr("argv"); var pythonArgv = new PyList(); // for python make sure the first argument is the script var scriptSourceStr = new PyString(runtime.ScriptSourceFile); pyRevitLabs.PythonNet.Runtime.PyList_Append(pythonArgv.Handle, scriptSourceStr.Handle); // add the rest of the args foreach (string arg in runtime.ScriptRuntimeConfigs.Arguments) { var argStr = new PyString(arg); pyRevitLabs.PythonNet.Runtime.PyList_Append(pythonArgv.Handle, argStr.Handle); } sys.SetAttr("argv", pythonArgv); }
public override void Start(ref ScriptRuntime runtime) { // if this is the first run if (!RecoveredFromCache) { // initialize using (Py.GIL()) { if (!PythonEngine.IsInitialized) { PythonEngine.Initialize(); } } // if this is a new engine, save the syspaths StoreSearchPaths(); } SetupBuiltins(ref runtime); SetupStreams(ref runtime); SetupCaching(ref runtime); SetupSearchPaths(ref runtime); SetupArguments(ref runtime); }
private void SetupSearchPaths(ref ScriptRuntime runtime) { // set sys paths PyObject sys = PythonEngine.ImportModule("sys"); PyObject sysPaths = sys.GetAttr("path"); // if this is a new engine, save the syspaths if (!RecoveredFromCache) { SaveSearchPaths(sysPaths.Handle); } // otherwise reset to default before changing else { sysPaths = RestoreSearchPaths(); sys.SetAttr("path", sysPaths); } foreach (string searchPath in runtime.ScriptRuntimeConfigs.SearchPaths.Reverse <string>()) { var searthPathStr = new PyString(searchPath); pyRevitLabs.PythonNet.Runtime.PyList_Insert(sysPaths.Handle, 0, searthPathStr.Handle); } }
private static ScriptTelemetryRecord MakeTelemetryRecord(ref ScriptRuntime runtime) { // setup a new telemetry record return(new ScriptTelemetryRecord { host_user = UserEnv.GetLoggedInUserName(), username = Telemetry.GetRevitUser(runtime.App), revit = Telemetry.GetRevitVersion(runtime.App), revitbuild = Telemetry.GetRevitBuild(runtime.App), sessionid = runtime.SessionUUID, pyrevit = runtime.PyRevitVersion, clone = runtime.CloneName, debug = runtime.ScriptRuntimeConfigs.DebugMode, config = runtime.ScriptRuntimeConfigs.ConfigMode, from_gui = runtime.ScriptRuntimeConfigs.ExecutedFromUI, exec_id = runtime.ExecId, exec_timestamp = runtime.ExecTimestamp, commandname = runtime.ScriptData.CommandName, commandbundle = runtime.ScriptData.CommandBundle, commandextension = runtime.ScriptData.CommandExtension, commanduniquename = runtime.ScriptData.CommandUniqueId, scriptpath = runtime.ScriptSourceFile, docname = runtime.DocumentName, docpath = runtime.DocumentPath, resultcode = runtime.ExecutionResult, commandresults = runtime.GetResultsDictionary(), trace = new ScriptTelemetryRecordTraceInfo { engine = new ScriptTelemetryRecordEngineInfo { type = runtime.EngineType.ToString().ToLower(), version = runtime.EngineVersion, syspath = runtime.ScriptRuntimeConfigs.SearchPaths, configs = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(runtime.ScriptRuntimeConfigs.EngineConfigs), }, message = runtime.TraceMessage } }); }
private void SetupBuiltins(ref ScriptRuntime runtime) { // BUILTINS ----------------------------------------------------------------------------------------------- // Get builtin to add custom variables var builtin = IronPython.Hosting.Python.GetBuiltinModule(Engine); // Add timestamp and executuin uuid builtin.SetVariable("__execid__", runtime.ExecId); builtin.SetVariable("__timestamp__", runtime.ExecTimestamp); // Let commands know if they're being run in a cached engine builtin.SetVariable("__cachedengine__", RecoveredFromCache); // Add current engine id to builtins builtin.SetVariable("__cachedengineid__", TypeId); // Add this script executor to the the builtin to be globally visible everywhere // This support pyrevit functionality to ask information about the current executing command builtin.SetVariable("__scriptruntime__", runtime); // Add host application handle to the builtin to be globally visible everywhere if (runtime.UIApp != null) { builtin.SetVariable("__revit__", runtime.UIApp); } else if (runtime.UIControlledApp != null) { builtin.SetVariable("__revit__", runtime.UIControlledApp); } else if (runtime.App != null) { builtin.SetVariable("__revit__", runtime.App); } else { builtin.SetVariable("__revit__", (object)null); } // Adding data provided by IExternalCommand.Execute builtin.SetVariable("__commanddata__", runtime.ScriptRuntimeConfigs.CommandData); builtin.SetVariable("__elements__", runtime.ScriptRuntimeConfigs.SelectedElements); // Add ui button handle builtin.SetVariable("__uibutton__", runtime.UIControl); // Adding information on the command being executed builtin.SetVariable("__commandpath__", Path.GetDirectoryName(runtime.ScriptData.ScriptPath)); builtin.SetVariable("__configcommandpath__", Path.GetDirectoryName(runtime.ScriptData.ConfigScriptPath)); builtin.SetVariable("__commandname__", runtime.ScriptData.CommandName); builtin.SetVariable("__commandbundle__", runtime.ScriptData.CommandBundle); builtin.SetVariable("__commandextension__", runtime.ScriptData.CommandExtension); builtin.SetVariable("__commanduniqueid__", runtime.ScriptData.CommandUniqueId); builtin.SetVariable("__commandcontrolid__", runtime.ScriptData.CommandControlId); builtin.SetVariable("__forceddebugmode__", runtime.ScriptRuntimeConfigs.DebugMode); builtin.SetVariable("__shiftclick__", runtime.ScriptRuntimeConfigs.ConfigMode); // Add reference to the results dictionary // so the command can add custom values for logging builtin.SetVariable("__result__", runtime.GetResultsDictionary()); // EVENT HOOKS BUILTINS ---------------------------------------------------------------------------------- // set event arguments for engine builtin.SetVariable("__eventsender__", runtime.ScriptRuntimeConfigs.EventSender); builtin.SetVariable("__eventargs__", runtime.ScriptRuntimeConfigs.EventArgs); }
private void SetupStreams(ref ScriptRuntime runtime) { Engine.Runtime.IO.SetOutput(runtime.OutputStream, System.Text.Encoding.UTF8); }
public override void Stop(ref ScriptRuntime runtime) { }
public override int Execute(ref ScriptRuntime runtime) { #if (REVIT2013 || REVIT2014) TaskDialog.Show(PyRevitLabsConsts.ProductName, NotSupportedFeatureException.NotSupportedMessage); return(ScriptExecutorResultCodes.NotSupportedFeatureException); #else if (runtime.UIApp != null && runtime.UIApp.ActiveUIDocument != null) { string familySourceFile = runtime.ScriptSourceFile; UIDocument uidoc = runtime.UIApp.ActiveUIDocument; Document doc = uidoc.Document; // find or load family first Family contentFamily = null; // attempt to find previously loaded family Element existingFamily = null; string familyName = Path.GetFileNameWithoutExtension(familySourceFile); var currentFamilies = new FilteredElementCollector(doc).OfClass(typeof(Family)).Where(q => q.Name == familyName); if (currentFamilies.Count() > 0) { existingFamily = currentFamilies.First(); } if (existingFamily != null) { contentFamily = (Family)existingFamily; } // if not found, attemt to load if (contentFamily == null) { try { var txn = new Transaction(doc, "Load pyRevit Content"); txn.Start(); doc.LoadFamily( familySourceFile, new ContentLoaderOptions(), out contentFamily ); txn.Commit(); } catch (Exception loadEx) { var dialog = new TaskDialog(PyRevitLabsConsts.ProductName); dialog.MainInstruction = "Failed loading content."; dialog.ExpandedContent = string.Format("{0}\n{1}", loadEx.Message, loadEx.StackTrace); dialog.Show(); return(ScriptExecutorResultCodes.FailedLoadingContent); } } if (contentFamily == null) { TaskDialog.Show(PyRevitLabsConsts.ProductName, string.Format("Failed finding or loading bundle content at:\n{0}", familySourceFile)); return(ScriptExecutorResultCodes.FailedLoadingContent); } // now ask ui to place an instance ElementId firstSymbolId = contentFamily.GetFamilySymbolIds().First(); if (firstSymbolId != null && firstSymbolId != ElementId.InvalidElementId) { FamilySymbol firstSymbol = (FamilySymbol)doc.GetElement(firstSymbolId); if (firstSymbol != null) { try { var placeOps = new PromptForFamilyInstancePlacementOptions(); uidoc.PromptForFamilyInstancePlacement(firstSymbol, placeOps); return(ScriptExecutorResultCodes.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { // user cancelled placement return(ScriptExecutorResultCodes.Succeeded); } }
public override void Init(ref ScriptRuntime runtime) { base.Init(ref runtime); // this is not a cachable engine; always use new engines UseNewEngine = true; }
public static int ExecuteExternalCommandType(Type extCommandType, ref ScriptRuntime runtime) { // create instance object extCommandInstance = Activator.CreateInstance(extCommandType); // set properties if available // set ExecParams var execParams = new ExecParams { ExecId = runtime.ExecId, ExecTimeStamp = runtime.ExecTimestamp, ScriptPath = runtime.ScriptData.ScriptPath, ConfigScriptPath = runtime.ScriptData.ConfigScriptPath, CommandUniqueId = runtime.ScriptData.CommandUniqueId, CommandControlId = runtime.ScriptData.CommandControlId, CommandName = runtime.ScriptData.CommandName, CommandBundle = runtime.ScriptData.CommandBundle, CommandExtension = runtime.ScriptData.CommandExtension, HelpSource = runtime.ScriptData.HelpSource, RefreshEngine = runtime.ScriptRuntimeConfigs.RefreshEngine, ConfigMode = runtime.ScriptRuntimeConfigs.ConfigMode, DebugMode = runtime.ScriptRuntimeConfigs.DebugMode, ExecutedFromUI = runtime.ScriptRuntimeConfigs.ExecutedFromUI, UIButton = runtime.UIControl }; FieldInfo execParamField = null; foreach (var fieldInfo in extCommandType.GetFields()) { if (fieldInfo.FieldType == typeof(ExecParams)) { execParamField = fieldInfo; } } if (execParamField != null) { execParamField.SetValue(extCommandInstance, execParams); } // reroute console output to runtime stream var existingOutStream = Console.Out; StreamWriter runtimeOutputStream = new StreamWriter(runtime.OutputStream); StreamReader runtimeInputStream = new StreamReader(runtime.OutputStream); runtimeOutputStream.AutoFlush = true; Console.SetOut(runtimeOutputStream); Console.SetIn(runtimeInputStream); // setup logger var prevLoggerCfg = LogManager.Configuration; var newLoggerCfg = new LoggingConfiguration(); var target = new CLREngineOutputTarget(); target.CurrentExecParams = execParams; target.Name = logger.Name; target.Layout = "${level:uppercase=true}: [${logger}] ${message}"; newLoggerCfg.AddTarget(target.Name, target); newLoggerCfg.AddRuleForAllLevels(target); LogManager.Configuration = newLoggerCfg; // execute string commandMessage = string.Empty; extCommandType.InvokeMember( "Execute", BindingFlags.Default | BindingFlags.InvokeMethod, null, extCommandInstance, new object[] { runtime.ScriptRuntimeConfigs.CommandData, commandMessage, runtime.ScriptRuntimeConfigs.SelectedElements } ); // revert logger back to previous LogManager.Configuration = prevLoggerCfg; // cleanup reference to exec params target.CurrentExecParams = null; if (execParamField != null) { execParamField.SetValue(extCommandInstance, null); } // reroute console output back to original Console.SetOut(existingOutStream); runtimeOutputStream = null; return(ScriptExecutorResultCodes.Succeeded); }
public override int Execute(ref ScriptRuntime runtime) { try { // find RhinoInside.Revit.dll ObjectHandle ghObjHandle = Activator.CreateInstance("RhinoInside.Revit", "RhinoInside.Revit.UI.CommandGrasshopperPlayer"); object ghPlayer = ghObjHandle.Unwrap(); foreach (MethodInfo methodInfo in ghPlayer.GetType().GetMethods()) { var methodParams = methodInfo.GetParameters(); if (methodInfo.Name == "Execute" && methodParams.Count() == 5) { View activeView = null; #if !(REVIT2013 || REVIT2014) if (runtime.UIApp != null && runtime.UIApp.ActiveUIDocument != null) { activeView = runtime.UIApp.ActiveUIDocument.ActiveGraphicalView; } #else if (runtime.UIApp != null && runtime.UIApp.ActiveUIDocument != null) { activeView = runtime.UIApp.ActiveUIDocument.ActiveView; } #endif // run the script if (runtime.UIApp != null) { string message = string.Empty; methodInfo.Invoke( ghPlayer, new object[] { runtime.UIApp, activeView, new Dictionary <string, string>(), runtime.ScriptSourceFile, message }); return(ScriptExecutorResultCodes.Succeeded); } else { TaskDialog.Show(PyRevitLabsConsts.ProductName, "Can not access the UIApplication instance"); return(ScriptExecutorResultCodes.ExecutionException); } } } TaskDialog.Show(PyRevitLabsConsts.ProductName, "Can not find appropriate Grasshopper Execute method"); return(ScriptExecutorResultCodes.ExecutionException); } catch (FileNotFoundException) { // if failed in finding DynamoRevitDS.dll, assume no dynamo TaskDialog.Show(PyRevitLabsConsts.ProductName, "Can not find Rhino.Inside installation or it is not loaded yet.\n\n" + "Install/Load Rhino.Inside first."); return(ScriptExecutorResultCodes.ExecutionException); } catch (Exception ghEx) { // if failed in finding RhinoInside.Revit.dll, assume no rhino var dialog = new TaskDialog(PyRevitLabsConsts.ProductName); dialog.MainInstruction = "Error executing Grasshopper script."; dialog.ExpandedContent = string.Format("{0}\n{1}", ghEx.Message, ghEx.StackTrace); dialog.Show(); return(ScriptExecutorResultCodes.ExecutionException); } }
private void SetupSearchPaths(ref ScriptRuntime runtime) { // process search paths provided to executor Engine.SetSearchPaths(runtime.ScriptRuntimeConfigs.SearchPaths); }
public static Assembly CompileCLRScript(ref ScriptRuntime runtime) { // https://stackoverflow.com/a/3188953 // read the script var scriptContents = File.ReadAllText(runtime.ScriptSourceFile); // read the referenced dlls from env vars // pyrevit sets this when loading string[] refFiles; var envDic = new EnvDictionary(); if (envDic.ReferencedAssemblies.Length == 0) { var refs = AppDomain.CurrentDomain.GetAssemblies(); refFiles = refs.Select(a => a.Location).ToArray(); } else { refFiles = envDic.ReferencedAssemblies; } // create compiler parameters var compileParams = new CompilerParameters(refFiles); compileParams.OutputAssembly = Path.Combine( UserEnv.UserTemp, string.Format("{0}_{1}.dll", runtime.ScriptData.CommandName, runtime.ScriptSourceFileSignature) ); compileParams.CompilerOptions = string.Format("/optimize /define:REVIT{0}", runtime.App.VersionNumber); compileParams.GenerateInMemory = true; compileParams.GenerateExecutable = false; compileParams.ReferencedAssemblies.Add(typeof(ScriptExecutor).Assembly.Location); // determine which code provider to use CodeDomProvider compiler; var compConfig = new Dictionary <string, string>() { { "CompilerVersion", "v4.0" } }; switch (runtime.EngineType) { case ScriptEngineType.CSharp: compiler = new CSharpCodeProvider(compConfig); break; case ScriptEngineType.VisualBasic: compiler = new VBCodeProvider(compConfig); break; default: throw new PyRevitException("Specified language does not have a compiler."); } // compile code first var res = compiler.CompileAssemblyFromSource( options: compileParams, sources: new string[] { scriptContents } ); return(res.CompiledAssembly); }
public override int Execute(ref ScriptRuntime runtime) { // compile first // only if the signature doesn't match if (scriptSig == null || runtime.ScriptSourceFileSignature != scriptSig) { try { scriptSig = runtime.ScriptSourceFileSignature; scriptAssm = CompileCLRScript(ref runtime); } catch (Exception compileEx) { string traceMessage = compileEx.ToString(); traceMessage = traceMessage.NormalizeNewLine(); runtime.TraceMessage = traceMessage; if (runtime.RuntimeType == ScriptRuntimeType.ExternalCommand) { var dialog = new TaskDialog(PyRevitLabsConsts.ProductName); dialog.MainInstruction = "Error compiling .NET script."; dialog.ExpandedContent = string.Format("{0}\n{1}", compileEx.Message, traceMessage); dialog.Show(); } return(ScriptExecutorResultCodes.CompileException); } } // scriptAssm must have value switch (runtime.RuntimeType) { // if is an external command case ScriptRuntimeType.ExternalCommand: try { // execute now var resultCode = ExecuteExternalCommand(scriptAssm, null, ref runtime); if (resultCode == ScriptExecutorResultCodes.ExternalInterfaceNotImplementedException) { TaskDialog.Show(PyRevitLabsConsts.ProductName, string.Format( "Can not find any type implementing IExternalCommand in assembly \"{0}\"", scriptAssm.Location )); } return(resultCode); } catch (Exception execEx) { string traceMessage = execEx.ToString(); traceMessage = traceMessage.NormalizeNewLine(); runtime.TraceMessage = traceMessage; var dialog = new TaskDialog(PyRevitLabsConsts.ProductName); dialog.MainInstruction = "Error executing .NET script."; dialog.ExpandedContent = string.Format("{0}\n{1}", traceMessage, execEx.StackTrace); dialog.Show(); return(ScriptExecutorResultCodes.ExecutionException); } // if is an event hook case ScriptRuntimeType.EventHandler: try { return(ExecuteEventHandler(scriptAssm, ref runtime)); } catch (Exception execEx) { string traceMessage = execEx.ToString(); traceMessage = traceMessage.NormalizeNewLine(); runtime.TraceMessage = traceMessage; runtime.OutputStream.WriteError(traceMessage, runtime.EngineType); return(ScriptExecutorResultCodes.ExecutionException); } default: return(ScriptExecutorResultCodes.ExternalInterfaceNotImplementedException); } }
public ScriptIO(ScriptRuntime runtime) { _outputBuffer = string.Empty; _runtime = new WeakReference <ScriptRuntime>(runtime); _gui = new WeakReference <ScriptConsole>(null); }
public override int Execute(ref ScriptRuntime runtime) { int result = ScriptExecutorResultCodes.Succeeded; using (Py.GIL()) { // read script var scriptContents = File.ReadAllText(runtime.ScriptSourceFile, encoding: System.Text.Encoding.UTF8); // create new scope and set globals var scope = Py.CreateScope("__main__"); scope.Set("__file__", runtime.ScriptSourceFile); // execute try { scope.ExecUTF8(scriptContents); } catch (PythonException cpyex) { var traceBackParts = cpyex.StackTrace.Split(']'); string pyTraceback = traceBackParts[0].Trim() + "]"; string cleanedPyTraceback = string.Empty; foreach (string tbLine in pyTraceback.ConvertFromTomlListString()) { if (tbLine.Contains("File \"<string>\"")) { var fixedTbLine = tbLine.Replace("File \"<string>\"", string.Format("File \"{0}\"", runtime.ScriptSourceFile)); cleanedPyTraceback += fixedTbLine; var lineNo = new Regex(@"\,\sline\s(?<lineno>\d+)\,").Match(tbLine).Groups["lineno"].Value; cleanedPyTraceback += scriptContents.Split('\n')[int.Parse(lineNo.Trim()) - 1] + "\n"; } else { cleanedPyTraceback += tbLine; } } string pyNetTraceback = traceBackParts[1].Trim(); string traceMessage = string.Join( "\n", cpyex.Message, cleanedPyTraceback, cpyex.Source, pyNetTraceback ); // Print all errors to stdout and return cancelled to Revit. // This is to avoid getting window prompts from Revit. // Those pop ups are small and errors are hard to read. traceMessage = traceMessage.NormalizeNewLine(); runtime.TraceMessage = traceMessage; runtime.OutputStream.WriteError(traceMessage, ScriptEngineType.CPython); result = ScriptExecutorResultCodes.ExecutionException; } finally { // remove scope scope.Dispose(); } } return(result); }
public override int Execute(ref ScriptRuntime runtime) { // Setup the command scope in this engine with proper builtin and scope parameters var scope = Engine.CreateScope(); // Create the script from source file var script = Engine.CreateScriptSourceFromFile( runtime.ScriptSourceFile, System.Text.Encoding.UTF8, SourceCodeKind.File ); // Setting up error reporter and compile the script // setting module to be the main module so __name__ == __main__ is True var compiler_options = (PythonCompilerOptions)Engine.GetCompilerOptions(scope); compiler_options.ModuleName = "__main__"; compiler_options.Module |= IronPython.Runtime.ModuleOptions.Initialize; var errors = new IronPythonErrorReporter(); var command = script.Compile(compiler_options, errors); // Process compile errors if any if (command == null) { // compilation failed, print errors and return runtime.OutputStream.WriteError(string.Join(Environment.NewLine, errors.Errors.ToArray()), ScriptEngineType.IronPython); return(ScriptExecutorResultCodes.CompileException); } // Finally let's execute try { command.Execute(scope); return(ScriptExecutorResultCodes.Succeeded); } catch (SystemExitException) { // ok, so the system exited. That was bound to happen... return(ScriptExecutorResultCodes.SysExited); } catch (Exception exception) { // show (power) user everything! string clrTraceMessage = exception.ToString(); string ipyTraceMessage = Engine.GetService <ExceptionOperations>().FormatException(exception); // Print all errors to stdout and return cancelled to Revit. // This is to avoid getting window prompts from Revit. // Those pop ups are small and errors are hard to read. ipyTraceMessage = ipyTraceMessage.NormalizeNewLine(); clrTraceMessage = clrTraceMessage.NormalizeNewLine(); // set the trace messages on runtime for later usage (e.g. logging) runtime.TraceMessage = string.Join("\n", ipyTraceMessage, clrTraceMessage); // manually add the CLR traceback since this is a two part error message clrTraceMessage = string.Join("\n", ScriptConsoleConfigs.ToCustomHtmlTags(ScriptConsoleConfigs.CLRErrorHeader), clrTraceMessage); runtime.OutputStream.WriteError(ipyTraceMessage + "\n\n" + clrTraceMessage, ScriptEngineType.IronPython); return(ScriptExecutorResultCodes.ExecutionException); } finally { if (!ExecEngineConfigs.persistent) { // cleaning removes all references to revit content that's been casualy stored in global-level // variables and prohibit the GC from cleaning them up and releasing memory var scopeClearScript = Engine.CreateScriptSourceFromString( "for __deref in dir():\n" + " if not __deref.startswith('__'):\n" + " del globals()[__deref]"); scopeClearScript.Compile(); scopeClearScript.Execute(scope); } } }
public virtual void Stop(ref ScriptRuntime runtime) { }
public override int Execute(ref ScriptRuntime runtime) { var journalData = new Dictionary <string, string>() { // Specifies the path to the Dynamo workspace to execute. { "dynPath", runtime.ScriptSourceFile }, // Specifies whether the Dynamo UI should be visible (set to false - Dynamo will run headless). { "dynShowUI", runtime.ScriptRuntimeConfigs.DebugMode.ToString() }, // If the journal file specifies automation mode // Dynamo will run on the main thread without the idle loop. { "dynAutomation", ExecEngineConfigs.automate ? "True" : "False" }, // The journal file can specify if the Dynamo workspace opened // from DynPathKey will be executed or not. // If we are in automation mode the workspace will be executed regardless of this key. { "dynPathExecute", ExecEngineConfigs.dynamo_path_exec ? "True" : "False" }, // The journal file can specify if the existing UIless RevitDynamoModel // needs to be shutdown before performing any action. // per comments on https://github.com/eirannejad/pyRevit/issues/570 // Setting this to True slows down Dynamo by a factor of 3 { "dynModelShutDown", ExecEngineConfigs.clean ? "True" : "False" }, }; if (ExecEngineConfigs.dynamo_path != null && ExecEngineConfigs.dynamo_path != string.Empty) { // The journal file can specify a Dynamo workspace to be opened // (and executed if we are in automation mode) at run time. journalData["dynPath"] = ExecEngineConfigs.dynamo_path; // The journal file can specify if a check should be performed to see if the // current workspaceModel already points to the Dynamo file we want to // run (or perform other tasks). If that's the case, we want to use the // current workspaceModel. journalData["dynPathCheckExisting "] = ExecEngineConfigs.dynamo_path_check_existing ? "True" : "False"; // The journal file can specify if the Dynamo workspace opened // from DynPathKey will be forced in manual mode. journalData["dynForceManualRun "] = ExecEngineConfigs.dynamo_force_manual_run ? "True" : "False"; } if (ExecEngineConfigs.dynamo_model_nodes_info != null && ExecEngineConfigs.dynamo_model_nodes_info != string.Empty) { // The journal file can specify the values of Dynamo nodes. journalData["dynModelNodesInfo"] = ExecEngineConfigs.dynamo_model_nodes_info; } //return new DynamoRevit().ExecuteCommand(new DynamoRevitCommandData() { // JournalData = journalData, // Application = commandData.Application //}); try { // find the DynamoRevitApp from DynamoRevitDS.dll // this should be already loaded since Dynamo loads before pyRevit ObjectHandle dynRevitAppObjHandle = Activator.CreateInstance("DynamoRevitDS", "Dynamo.Applications.DynamoRevitApp"); object dynRevitApp = dynRevitAppObjHandle.Unwrap(); MethodInfo execDynamo = dynRevitApp.GetType().GetMethod("ExecuteDynamoCommand"); // run the script execDynamo.Invoke(dynRevitApp, new object[] { journalData, runtime.UIApp }); return(ScriptExecutorResultCodes.Succeeded); } catch (FileNotFoundException) { // if failed in finding DynamoRevitDS.dll, assume no dynamo TaskDialog.Show(PyRevitLabsConsts.ProductName, "Can not find Dynamo installation or determine which Dynamo version to Run.\n\n" + "Run Dynamo once to select the active version."); return(ScriptExecutorResultCodes.ExecutionException); } catch (Exception dynEx) { // on any other errors var dialog = new TaskDialog(PyRevitLabsConsts.ProductName); dialog.MainInstruction = "Error executing Dynamo script."; dialog.ExpandedContent = string.Format("{0}\n{1}", dynEx.Message, dynEx.StackTrace); dialog.Show(); return(ScriptExecutorResultCodes.ExecutionException); } }
public override int Execute(ref ScriptRuntime runtime) { // compile first // only if the signature doesn't match var errors = new List <string>(); if (scriptSig == null || runtime.ScriptSourceFileSignature != scriptSig || scriptDbg != runtime.ScriptRuntimeConfigs.DebugMode) { try { scriptSig = runtime.ScriptSourceFileSignature; scriptDbg = runtime.ScriptRuntimeConfigs.DebugMode; scriptAssm = CompileCLRScript(ref runtime, out errors); if (scriptAssm == null) { if (runtime.RuntimeType == ScriptRuntimeType.ExternalCommand) { var errorReport = string.Join(Environment.NewLine, errors.ToArray()); runtime.OutputStream.WriteError( errorReport != string.Empty ? errorReport : "Failed to compile assembly for unknown reason", runtime.EngineType ); } // clear script signature scriptSig = null; return(ScriptExecutorResultCodes.CompileException); } } catch (Exception compileEx) { // make sure a bad compile is not cached scriptAssm = null; string traceMessage = compileEx.ToString(); traceMessage = traceMessage.NormalizeNewLine(); runtime.TraceMessage = traceMessage; if (runtime.RuntimeType == ScriptRuntimeType.ExternalCommand) { var dialog = new TaskDialog(PyRevitLabsConsts.ProductName); dialog.MainInstruction = "Error compiling .NET script."; string errorReport = string.Empty; foreach (var errline in errors) { errorReport += $"{errline}\n"; } errorReport += string.Format("\nTrace:\n{0}\n{1}", compileEx.Message, traceMessage); dialog.ExpandedContent = errorReport; dialog.Show(); } return(ScriptExecutorResultCodes.CompileException); } } // scriptAssm must have value switch (runtime.RuntimeType) { // if is an external command case ScriptRuntimeType.ExternalCommand: try { // execute now var resultCode = ExecuteExternalCommand(scriptAssm, null, ref runtime); if (resultCode == ScriptExecutorResultCodes.ExternalInterfaceNotImplementedException) { TaskDialog.Show(PyRevitLabsConsts.ProductName, string.Format( "Can not find any type implementing IExternalCommand in assembly \"{0}\"", scriptAssm.Location )); } return(resultCode); } catch (Exception execEx) { string traceMessage = execEx.ToString(); traceMessage = traceMessage.NormalizeNewLine(); runtime.TraceMessage = traceMessage; var dialog = new TaskDialog(PyRevitLabsConsts.ProductName); dialog.MainInstruction = "Error executing .NET script."; dialog.ExpandedContent = string.Format("{0}\n{1}", traceMessage, execEx.StackTrace); dialog.Show(); return(ScriptExecutorResultCodes.ExecutionException); } // if is an event hook case ScriptRuntimeType.EventHandler: try { return(ExecuteEventHandler(scriptAssm, ref runtime)); } catch (Exception execEx) { string traceMessage = execEx.ToString(); traceMessage = traceMessage.NormalizeNewLine(); runtime.TraceMessage = traceMessage; runtime.OutputStream.WriteError(traceMessage, runtime.EngineType); return(ScriptExecutorResultCodes.ExecutionException); } default: return(ScriptExecutorResultCodes.ExternalInterfaceNotImplementedException); } }
private static int ExecuteScriptNow(ScriptData scriptData, ScriptRuntimeConfigs scriptRuntimeCfg, ScriptExecutorConfigs scriptExecConfigs) { // create runtime var runtime = new ScriptRuntime(scriptData, scriptRuntimeCfg); // determine which engine to use, and execute if (EnsureTargetScript(ref runtime)) { switch (runtime.EngineType) { case ScriptEngineType.IronPython: ExecuteManagedScript <IronPythonEngine>(ref runtime); break; case ScriptEngineType.CPython: ExecuteManagedScript <CPythonEngine>(ref runtime); break; case ScriptEngineType.CSharp: ExecuteManagedScript <CLREngine>(ref runtime); break; case ScriptEngineType.Invoke: ExecuteManagedScript <InvokableDLLEngine>(ref runtime); break; case ScriptEngineType.VisualBasic: ExecuteManagedScript <CLREngine>(ref runtime); break; case ScriptEngineType.IronRuby: ExecuteManagedScript <IronRubyEngine>(ref runtime); break; case ScriptEngineType.DynamoBIM: ExecuteManagedScript <DynamoBIMEngine>(ref runtime); break; case ScriptEngineType.Grasshopper: ExecuteManagedScript <GrasshoppertEngine>(ref runtime); break; case ScriptEngineType.Content: ExecuteManagedScript <ContentEngine>(ref runtime); break; case ScriptEngineType.HyperLink: ExecuteManagedScript <HyperlinkEngine>(ref runtime); break; default: // should not get here throw new PyRevitException("Unknown engine type."); } } else { runtime.ExecutionResult = ScriptExecutorResultCodes.MissingTargetScript; } // Log results int result = runtime.ExecutionResult; if (scriptExecConfigs.SendTelemetry) { ScriptTelemetry.LogScriptTelemetryRecord(ref runtime); } // GC cleanups var re = runtime.ExecutionResult; runtime.Dispose(); runtime = null; // return the result return(result); }
public virtual int Execute(ref ScriptRuntime runtime) { return(ScriptExecutorResultCodes.Succeeded); }