Revit .NET API has provided the UIApplication.OpenAndActivateDocument method since version 2012 for programmers to open a valid Revit file and activate it right away.
However, it has pretty strict limitations. One is that it cannot be invoked from any event handlers; another is that it cannot be called from inside of any transactions even including those automatic ones that are specified by the Transaction API attribute with the TransactionMode.Automatic argument and are maintained by Revit itself.
If we really try to do so, however,
using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using RvtApplication = Autodesk.Revit.ApplicationServices.Application;
using RvtDocument = Autodesk.Revit.DB.Document;
namespace Revit2012Api
{
[Transaction(TransactionMode.Automatic)]
[Regeneration(RegenerationOption.Manual)]
public class ExtCmd1 : IExternalCommand
{
private static ExternalCommandData _cachedCmdData;
public static UIApplication CachedUiApp
{
get
{
return _cachedCmdData.Application;
}
}
#region IExternalCommand Members
public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elemSet)
{
_cachedCmdData = cmdData;
try
{
//TODO: add your code below.
CachedUiApp.OpenAndActivateDocument(@"c:\temp\project1.rvt");
return Result.Succeeded;
}
catch (Exception ex)
{
msg = ex.ToString();
return Result.Failed;
}
}
#endregion
}
}
the following exception will come up.
“Autodesk.Revit.Exceptions.InvalidOperationException: The active document is curently modifiable.
at Autodesk.Revit.UI.UIApplication.OpenAndActivateDocument(String fileName)
at Revit2012Api.ExtCmd1.Execute(ExternalCommandData cmdData, String& msg, ElementSet elemSet) in …”
If we use the same code but change the TransactionMode from Automatic to Manual, everything will be just fine.
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class ExtCmd1 : IExternalCommand
{
private static ExternalCommandData _cachedCmdData;
public static UIApplication CachedUiApp
{
get
{
return _cachedCmdData.Application;
}
}
#region IExternalCommand Members
public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elemSet)
{
_cachedCmdData = cmdData;
try
{
//TODO: add your code below.
CachedUiApp.OpenAndActivateDocument(@"c:\temp\project1.rvt");
return Result.Succeeded;
}
catch (Exception ex)
{
msg = ex.ToString();
return Result.Failed;
}
}
#endregion
}
So a single method call will force the whole command to be migrated from the automatic transaction mode to manual.
Revit Addin Wizard (RevitAddinWizard) provides various wizards, coders and widgets to help program Revit addins. It can be downloaded from the Download link at the bottom of the blog index page.
Recent Comments