Hi guys,
I try to write an application (in c#) for revit which enqueues and executes multiple dynamo scripts.
My approach enqueues DynamoRevit instances with additional context information given by a DynamoRevitCommandData instance.
I’m using an ExternalEvent and its Raise() method to signify Revit’s command scheduler to execute the command.
The code works fine in a Revit project, so if you enqueue two commands (or more), the event raises twice but only the first script is executed. I hope this introduces you to the scenario.
Here are some line of code to see at yourself:
this method is called in a class implementing the IExternalCommand interface
public void ExecuteQueuedScriptsAndProjects(IEnumerable<ScriptData> queuedScripts, IEnumerable<ProjectData> queuedProjects)
{
Queue<ScriptData> _queuedScripts = new Queue<ScriptData>(queuedScripts);
if (_commandData != null && _doc != null)
{
while (_queuedScripts.Count != 0)
{
ScriptData currentScript = _queuedScripts.Dequeue();
//TODO: what if path to script doesn't exisits anymore?
//could use empty constructor?
DynamoRevitCommandData dynoCommandData = new DynamoRevitCommandData(_commandData);
dynoCommandData.JournalData = new Dictionary<string, string>();
dynoCommandData.JournalData.Add("dynPath", currentScript.Filepath);
dynoCommandData.JournalData.Add("dynShowUI", "false");
dynoCommandData.JournalData.Add("dynAutomation", "true");
dynoCommandData.JournalData.Add("dynPathExecute", "true");
dynoCommandData.JournalData.Add("dynModelShutDown", "true");
(_executeEventHandler as ExecuteScriptEventHandler).SetContext(currentScript, dynoCommandData);
ExternalEventRequest request = _externalEvent.Raise();
//swap foreground to trigger event immediately
IntPtr hBefore = GetForegroundWindow();
SetForegroundWindow(ComponentManager.ApplicationWindow);
SetForegroundWindow(hBefore);
}
}
//TODO: Implement me!
}
and this is the ExternalEvent
public class ExecuteScriptEventHandler : IExternalEventHandler
{
private ScriptData _data;
private DynamoRevitCommandData _commandData;
public ExecuteScriptEventHandler()
{
}
public void SetContext(ScriptData scriptData, DynamoRevitCommandData dynoCommandData)
{
if (scriptData != null && dynoCommandData != null)
{
_data = scriptData;
_commandData = dynoCommandData;
}
}
public void Execute(UIApplication app)
{
Document doc = app.ActiveUIDocument.Document;
DynamoRevit dynoRevit = new DynamoRevit();
using (Transaction t = new Transaction(doc))
{
t.Start("Execute script " + _data.Filename);
dynoRevit.ExecuteCommand(_commandData);
t.Commit();
}
}
public string GetName()
{
return this.GetType().Name;
}
}