This is the second instalment of a series publishing the information provided in the 'What's New' sections of the past few Revit API releases help file RevitAPI.chm.
The first instalment covering What's New in the Revit 2010 API explains my motivation for this and provides an overview of the other releases.
We now move on to Revit 2011, looking at:
First, however, an update on my vacation so far.
Snowstorm in Italy
I am still on holiday in Italy, so please do not expect any immediate responses to any comments for a while.
My first cappuccino in Domodossola was slightly disappointing.
It improved later, though.
Searching for sun and warmth, we found cold and snow, and started heading southward to flee it.
Instead of getting better, it got worse, causing huge trees to crash down or lose their branches under loads of snow never previously experienced.
We did what we could to improve the situation.
The result is anti-art.
Still hoping for better weather further south...
Now, to continue the promised series of 'What's New' documentation from the past few Revit API releases.
Major renovations to the Revit 2011 API
Autodesk is using the 2011 Release to position the Revit API for significant future growth. In order to ensure that as the API grows, the interfaces created during this expansion can remain stable for a significant period of time, there are some quite significant up-front changes being made to the existing API.
Changes to the Revit API namespaces
The Revit API namespaces have been changed to be more consistent and more suitable to expansion. In previous releases, API classes were split along the lines of functionality and Revit vertical product, which led to confusion about where classes which were Elements or Symbols belonged if they were specific to one vertical. In the new namespace structure, there is a primary division into three sets of namespaces:
- Autodesk.Revit.ApplicationServices – contains classes accessing settings and options for the main Revit application
- Autodesk.Revit.DB – contains classes accessing data from the Revit file
- Autodesk.Revit.UI – contains classes accessing or customizing the Revit user interface
Within these main namespaces there are subdivisions based on discipline, e.g.:
- Autodesk.Revit.DB.Architecture
- Autodesk.Revit.DB.Structure
- Autodesk.Revit.DB.Mechanical
- Autodesk.Revit.DB.Electrical
- Autodesk.Revit.DB.Plumbing
Classes which are useful in more than one discipline are placed in the Autodesk.Revit.DB main namespace.
Less commonly used classes, like event arguments, are also placed in subordinate namespaces, e.g.:
- Autodesk.Revit.DB.Events
- Autodesk.Revit.UI.Events
As a result of the rearrangement of the namespaces, a few classes have been modified more drastically than simply being moved to new namespaces:
- Autodesk.Revit.Geometry.Element has been renamed to Autodesk.Revit.DB.GeometryElement to avoid a naming conflict.
- Autodesk.Revit.Geometry.Instance has been renamed to Autodesk.Revit.DB.GeometryInstance to avoid a naming conflict.
- Autodesk.Revit.Structural.Enums.Material has been renamed to Autodesk.Revit.DB.MaterialType to avoid a naming conflict.
- Autodesk.Revit.Options.Application has been removed. The properties accessible from this class have been moved into Autodesk.Revit.ApplicationServices.Application.
To obtain a full list mapping the changes from the Revit 2010 API, see the document Revit 2011 API Namespace Remapping.xlsx in the Software Development Kit install.
Split of Revit API DLL
The Revit API has been split into two DLLs. The new DLLs are:
- RevitAPI.dll – which now contains only methods used to access Revit's application, documents, elements, and parameters at the database level.
- RevitAPIUI.dll – which contains all API interfaces related to manipulation and customization of the Revit user interface, including:
- IExternalCommand and External Command related interfaces
- IExternalApplication and related interfaces
- Selection
- RibbonPanel, RibbonItem and subclasses
- TaskDialogs
In order to facilitate access to application and document level interfaces from both DLLs, the Application and Document classes have also split into two:
- Autodesk.Revit.UI.UIApplication – provides access to UI-level interfaces for the application, including the ability to add RibbonPanels to the user interface, and the ability to obtain the active document in the user interface.
- Autodesk.Revit.ApplicationServices.Application – provides access to all other application level properties.
- Autodesk.Revit.UI.UIDocument – provides access to UI-level interfaces for the document, such as the contents of the selection and the ability to prompt the user to make selections and pick points
- Autodesk.Revit.DB.Document – provides access to all other document level properties
The ExternalCommandData interface now provides access to the UIApplication object as well as the active view. From the active UIApplication object you can obtain the active UI document. You can also construct the UIApplication from the Application object, and the UIDocument from the DB level document at any time.
New classes for XYZ, UV, and ElementId
New classes have been introduced for the basic XYZ, UV and ElementId classes used in the API. These classes are:
- Autodesk.Revit.DB.XYZ
- Autodesk.Revit.DB.UV
- Autodesk.Revit.DB.ElementId
These new classes provide a more consistent and complete interface, operate more quickly by having their implementation be entirely in managed code, and are immutable thus making them more suitable for use as properties. The following table summarizes the old and new methods for the XYZ and UV classes listing the old XYZ/UV member, the new member, and optional notes:
- AlmostEqual() – IsAlmostEqualTo()
- Angle() – AngleTo()
- AngleAround() – AngleOnPlaneTo()
- Cross() – CrossProduct()
- Distance() – DistanceTo()
- Dot() – DotProduct()
- Basis – N/A: Use BasisX, BasisY, BasisZ as required
- IsNormalized – IsUnitLength()
- IsZero – IsZeroLength()
- Item – Item: Property is now read-only
- Length – GetLength()
- Normalized – Normalize()
- X – X: Property is now read-only
- Y – Y: Property is now read-only
- Z – Z: Property is now read-only
All Revit API methods accepting or returning these types have been converted to the new classes.
In addition, the collections for these types have been removed.
Methods which used to take dedicated Revit collections now take equivalent .NET collection interfaces containing these types:
- Autodesk.Revit.ElementIdSet – ICollection<Autodesk.Revit.DB.ElementId>
- Autodesk.Revit.Geometry.XYZArray – IList<Autodesk.Revit.DB.XYZ>
- Autodesk.Revit.Geometry.UVArray – IList<Autodesk.Revit.DB.UV>
The major impact to existing code is the replacement of the collections, and the changes to the classes designed to make them immutable. Code which previously change the coordinates of an XYZ via setting XYZ.X, XYZ.Y, and/or XYZ.Z, now should construct a new XYZ with the desired coordinates.
One further impact is the fact that ElementId is now a class, instead of a struct, and should not be passed with "ref" in C# or "ByRef" in VB.NET.
Replacement for Symbol and properties that access types
The Symbol class has been renamed to ElementType.
The Element ObjectType and SimilarObjectTypes properties that access types from elements have been replaced:
- ObjectType – Element.GetTypeId(), Element.ChangeTypeId(): ChangeTypeId() returns the id of a new element; in rare cases, changing the element type will result in deletion of the current element. Static versions which operate on sets of elements are also supplied.
- Element.SimilarObjectTypes – Element.GetValidTypes()
New transaction interfaces
New interfaces have been added to the API related to Transactions. These interfaces will provide a more comprehensive set of options for managing changes being made to the Revit document.
At this time, the new transaction interfaces are not compatible with the automatically-opened transactions created around ExternalCommand callbacks and VSTA macros. So, Autodesk recommends that you not use these interfaces until compatible changes have been made to those frameworks. In order to experiment with the new interfaces, a document needs to be opened or created while in an external command. In the new document, either the old transaction interfaces or the new ones can be used, as long as they are not used together in the same document.
There are three main classes among the new interfaces plus a few supporting classes. The main classes represent three different (but related) transaction contexts.
Transaction – a context required in order to make any changes to a Revit model. Only one transaction can be open at a time; nesting is not allowed. Each transaction must have a name, which will be listed on the Undo menu in Revit once a transaction is successfully submitted.
SubTransaction – can be used to enclose a set of model modifying commands. Sub-transactions are optional. They are not required in order to modify the model. They are a convenience tool to allow logical splitting of larger tasks into smaller ones. Sub-transaction can only be created within an already opened transaction and must be closed (either committed or rolled back) before the transaction is closed (committed or rolled back). Unlike transactions, sub-transaction may be nested, but any nested sub-transaction must be closed before the enclosing sub-transaction is closed. Sub-transactions do not have name, for they do not appear on the Undo menu in Revit.
Transaction group – allows grouping together several independent transactions, which gives the owner of a group an opportunity to treat many transactions at once. When a transaction group is to be closed, it can be rolled back, which means that all already submitted transactions will be rolled back at once. If not rolled back, a group can be either submitted or assimilated. In the former case, all submitted transactions (within the group) will be left as they were. In the later case, transactions within the group will be merged together into one single transaction that will bear the group's name. A transaction group can only be started when there is no transaction open yet, and must be closed only after all enclosed transactions are closed (rolled back or committed). Transaction groups can be nested, but any nested group must be closed before the enclosing group is closed. Transaction groups are optional. They are not required in order to make modifications to a model.
All three transaction objects share some common methods:
- Start – Will start the context.
- Commit – Ends the context and commits all changes to the document.
- RollBack – Ends the context and discards all changes to the document.
- GetStatus – Returns the current status of a transaction object
Besides having the GetStatus returning the current status, both Commit and RollBack methods also return a status indicating whether or not the method was successful. Available status values include:
- Uninitialized – The initial value after object is instantiated; the context has not started yet
- Started – Set after a transaction object successfully started (Start method was called)
- Committed – Set after a transaction object successfully committed (Commit method was called)
- RolledBack – Set after a transaction object successfully rolled back (RollBack method was called)
- Pending – Set after transaction object was attempted to be either submitted or rolled back, but due to failures that process could not be finished yet and is waiting for the end-user's response (in a modeless dialog). Once the failure processing is finished, the status will be automatically updated (to either Committed or RolledBack status).
The new Transaction interfaces replace the old APIs:
- Document.BeginTransaction()
- Document.EndTransaction()
- Document.AbortTransaction()
which have been removed from the API.
Refactored Document properties related to transactions
Two existing properties have been re-implemented to better complement the changes in the transaction framework:
- Document.IsReadOny
Indicates that a document is – either temporarily or permanently – in read-only state. If it is read-only, it would mean that new transactions may not be started in that document, thus no modification could be made to the model.
- Document.IsModifiabe
Indicates whether a document is or is not currently modifiable. A document is not modifiable if either there is no transaction currently open or when some temporary state lock modification for a certain operation. Taken from another perspective, a transaction may be started only when document is not yet modifiable, but is also not read-only.
Transactions in events
All events have been changed to no longer automatically open transactions like they originally did in earlier releases. As a result of this new policy, the document will not be modified during an event unless one of the event’s handlers modifies it by making changes inside a transaction. A transaction may be opened by either the event handler if there is no transaction already opened (sometimes when the event is invoked, there is already a trasnaction open). If an event handler opens a transaction it is required that it will also close it (commit it or roll it back), otherwise all eventual changes will be discarded.
Please be aware that modifying the active document is not permitted during some events (e.g. the DocumentClosing event). If an event handler attempts to make modifications during such an event, an exception will be thrown. The event documentation indicates whether or not the event is read-only.
New ExternalCommand and ExternalApplication registration mechanism
The Revit API now offers the ability to register API applications via a .addin manifest file.
Manifest files will be read automatically by Revit when they are places in one of two locations on a user's system:
- In a non-user specific location in "application data"
- For Windows XP – C:\Documents and Settings\All Users\Application Data\Autodesk\Revit\Addins\2011\
- For Vista/Windows 7 – C:\ProgramData\Autodesk\Revit\Addins\2011\
- In a user specific location in "application data"
- For Windows XP – C:\Documents and Settings\[user]\Application Data\Autodesk\Revit\Addins\2011\
- For Vista/Windows 7 – C:\Users\[user]\AppData\Roaming\Autodesk\Revit\Addins\2011\
All files named .addin in these locations will be read and processed by Revit during startup.
A basic file adding one ExternalCommand looks like this:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <RevitAddIns> <AddIn Type="Command"> <Assembly>c:\MyProgram\MyProgram.dll</Assembly> <AddInId>76eb700a-2c85-4888-a78d-31429ecae9ed</AddInId> <FullClassName>Revit.Samples.SampleCommand</FullClassName> <Text>Sample command</Text> <VisibilityMode>NotVisibleInFamily</VisibilityMode> <VisibilityMode>NotVisibleInMEP</VisibilityMode> <AvailabilityClassName>Revit.Samples.SampleAccessibilityCheck</AvailabilityClassName> <LongDescription> <p>This is the long description for my command.</p> </p/> <p>This is another descriptive paragraph, with notes about how to use the command properly.</p> </LongDescription> <TooltipImage>c:\MyProgram\Autodesk.jpg</TooltipImage> <LargeImage>c:\MyProgram\MyProgramIcon.png</LargeImage> </AddIn> </RevitAddIns>
A basic file adding one ExternalApplication looks like this:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <RevitAddIns> <AddIn Type="Application"> <Name>SampleApplication</Name> <Assembly>c:\MyProgram\MyProgram.dll</Assembly> <AddInId>604B1052-F742-4951-8576-C261D1993107</AddInId> <FullClassName>Revit.Samples.SampleApplication</FullClassName> </AddIn> </RevitAddIns>
Multiple AddIn elements may be provided in a single manifest file.
The new mechanism currently offers the following XML tags:
- Assembly – The full path to the add-in assembly file. Required for all ExternalCommands and ExternalApplications.
- FullClassName – The full name of the class in the assembly file which implements IExternalCommand or IExternalApplication. Required for all ExternalCommands and ExternalApplications.
- ClientId – A GUID which represents the id of this particular application. ClientIds must be unique for a given session of Revit. Autodesk recommends you generate a unique GUID for each registered application or command. Required for all ExternalCommands and ExternalApplications. The property UIApplication.ActiveAddInId provides programmatic access to this value, if required.
- Name – The name of application. Required; for ExternalApplications only.
- Text – The name of the button. Optional; use this tag for ExternalCommands only. The default is "External Tool".
- Description – Short description of the command, will be used as the button tooltip. Optional; use this tag for ExternalCommands only. The default is a tooltip with just the command text.
- VisibilityMode – Provides the ability to specify if the command is visible in project documents, family documents, or no document at all. Also provides the ability to specify the discipline(s) where the command should be visible. Multiple values may be set for this option. Optional; use this tag for ExternalCommands only. The default is to display the command in all modes and disciplines, including when there is no active document. Previously written external commands which need to run against the active document should either be modified to ensure that the code deals with invocation of the command when there is no active document, or apply the NotVisibleWhenNoActiveDocument mode.
- AvailabilityClassName – The full name of the class in the assembly file which implemented IExternalCommandAvailability. This class allows the command button to be selectively grayed out depending on context. Optional; use this tag for ExternalCommands only. The default is a command that is available whenever it is visible.
- LargeImage – The path to the icon to use for the button in the External Tools pulldown menu. The icon should be 32 x 32 pixels for best results. Optional; use this tag for ExternalCommands only. The default is to show a button without an icon.
- LongDescription – Long description of the command, will be used as part of the button's extended tooltip. This tooltip is shown when the mouse hovers over the command for a long amount of time. You can split the text of this option into multiple paragraphs by placing <p> tags around each paragraph. Optional; use this tag for ExternalCommands only. If neither of this property and TooltipImage are supplied, the button will not have an extended tooltip.
- TooltipImage – The path to an image file to show as a part of the button extended tooltip, shown when the mouse hovers over the command for a longer amount of time. Optional; use this tag for ExternalCommands only. If neither of this property and TooltipImage are supplied, the button will not have an extended tooltip.
- LanguageType – Localization setting for Text, Description, LargeImage, LongDescription, and TooltipImage of external tools buttons. Revit will load the resource values from the specified language resource dll. The value can be one of the eleven languages supported by Revit. If no LanguageType is specified, the language resource which the current session of Revit is using will be automatically loaded. For more details see the section on Localization.
The Revit.ini registration mechanism remains in place for the 2011 release but will be removed in the future. The Revit.ini mechanism does not offer any of the new capabilities listed above. In addition, because Dynamic Model Update registration requires a valid AddInId, updaters may not be registered from applications declared in Revit.ini.
Localization
You can let Revit localize the user-visible resources of an external command button (including Text, large icon image, long and short descriptions and tooltip image). You will need to create a .NET Satellite DLL which contains the strings, images, and icons for the button. Then change the values of the tags in the .addin file to correspond to the names of resources in the Satellite dll, but prepended with the 'at' character '@'. So the tag:
<Text>Extension Manager</Text>
Becomes
<Text>@ExtensionText</Text>
where ExtensionText is the name of the resource found in the Satellite DLL.
The Satellite DLLs are expected to be in a directory with the name of the language of the language-culture, such as en or en-US. The directory should be located in the directory that contains the add-in assembly. Please refer to how to create managed Satellite DLLs.
You can force Revit to use a particular language resource DLL, regardless of the language of the Revit session, by specifying the language and culture explicitly with a LanguageType tag. For example:
<LanguageType>English_USA</LanguageType>
would force Revit to always load the values from the en-US Satellite DLL and to ignore the current Revit language and culture settings when considering the localizable members of the external command manifest file.
Revit supports the 11 languages defined in the Autodesk.Revit.ApplicationServices.LanguageType enumerated type: English_USA, German, Spanish, French, Italian, Dutch, Chinese_Simplified, Chinese_Traditional, Japanese, Korean, and Russian.
External Command Accessibility
The interface
- IExternalCommandAvailability
allows you control over whether or not an external command button may be pressed. The IsCommandAvailable interface method passes the application and a set of categories matching the categories of selected items in Revit to your implementation. The typical use would be to check the selected categories to see if they meet the criteria for your command to be run.
In this example accessibility check allows a button to be clicked when there is no active selection, or when at least one wall is selected:
public class SampleAccessibilityCheck : IExternalCommandAvailability { public bool IsCommandAvailable( Autodesk.Revit.ApplicationServices.Application data, CategorySet selectedCategories ) { // Allow button click if there is no active selection if( selectedCategories.IsEmpty ) return true; // Allow button click if there is at least one wall selected foreach( Category c in selectedCategories ) { if( c.Id.IntegerValue == (int)BuiltInCategory.OST_Walls ) return true; } return false; } }
External Command and External Application registration utility
The .NET utility DLL RevitAddInUtility.dll offers a dedicated API capable of reading, writing and modifying Revit Add-In manifest files. It is intended for use from product installers and scripts. Consult the API documentation in the RevitAddInUtility.chm help file in the SDK installation folder.
Here are some code snippets showing use of the RevitAddInUtility API.
First, creating a new .addin manifest file which contains one external command and one external application:
//create a new addin manifest RevitAddInManifest Manifest = new RevitAddInManifest(); //create an external command RevitAddInCommand command1 = new RevitAddInCommand( "full path\\assemblyName.dll", Guid.NewGuid(), "namespace.className" ); command1.Description = "description"; command1.Text = "display text"; //this command only visible in Revit MEP, Structure, // and only visible in Project document or when no // document at all command1.VisibilityMode = VisibilityMode.NotVisibleInArchitecture | VisibilityMode.NotVisibleInFamily; //create an external application RevitAddInApplication application1 = new RevitAddInApplication( "appName", "full path\\assemblyName.dll", Guid.NewGuid(), "namespace.className" ); //add both command(s) and application(s) into manifest Manifest.AddInCommands.Add( command1 ); Manifest.AddInApplications.Add( application1 ); //save manifest to a file RevitProduct revitProduct1 = RevitProductUtility .GetAllInstalledRevitProducts()[0]; Manifest.SaveAs( revitProduct1.AllUsersAddInFolder + "\\RevitAddInUtilitySample.addin" );
Second, reading from an existing addin file:
RevitProduct revitProduct1 = RevitProductUtility
.GetAllInstalledRevitProducts()[0];
RevitAddInManifest revitAddInManifest
= Autodesk.RevitAddIns.AddInManifestUtility
.GetRevitAddInManifest(
revitProduct1.AllUsersAddInFolder
+ "\\RevitAddInUtilitySample.addin" );
Attributes for configuring ExternalCommand and ExternalApplication behavior
Transaction mode
The custom attribute Autodesk.Revit.Attributes.TransactionMode should be applied to your implementation class of the IExternalCommand interface to control transaction behavior for external command. There is no default for this option. You must apply it to legacy application classes to allow your application to function in Revit 2011.
This mode controls how the API framework expects transactions to be used when the command is invoked. There are three supported values:
- TransactionMode.Automatic – The API framework will create a transaction on the active document before the external command is executed and the transaction will be committed or rolled back after the command is completed (based upon the return value of the ExternalCommand callback). This means that command code cannot create and start its own Transactions, but it can create SubTransactions as required during the implementation of the command. The command must report its success or failure status via the Result return value.
- TransactionMode.Manual – The API framework will not create a transaction (but it will create an outer group to roll back all changes if the external command returns a failure status). Instead, you may use combinations of Transactions, SubTransactions, and TransactionGroups as you please. You will have to follow all rules regarding use of transactions and related classes. You will have to give your transaction(s) names, which will then appear in the Undo menu. Revit will check that all transactions (also groups and sub-transactions) are properly closed upon return from an external command. If not, it will discard all changes made to the model.
- TransactionMode.ReadOnly – No transaction (nor group) will be created, and no transaction may be created for the lifetime of the command. The External command may use methods that only read from the model, but not methods that write anything to it. Exceptions will be thrown if the command either tries to start a transaction (or group) or attempts to write to the model.
In all three modes, the TransactionMode applies only to the active document. You may open other documents during the course of the command, and you may have complete control over the creation and use of Transactions, SubTransactions, and TransactionGroups on those other documents (even in ReadOnly mode).
For example, to set an external command to use automatic transaction mode:
[Regeneration( RegenerationOption.Manual )] [Transaction( TransactionMode.Automatic )] public class Command : IExternalCommand { public Autodesk.Revit.IExternalCommand.Result Execute( Autodesk.Revit.ExternalCommandData commandData, ref string message, Autodesk.Revit.ElementSet elements ) { // Command implementation, which modifies the // active document directly and no need to // start/commit any transactions. } }
Regeneration option
The custom attribute Autodesk.Revit.Attributes.RegenerationAttribute should be applied to your implementation class of the IExternalCommand interface and IExternalApplication interface to control the regeneration behavior for the external command and external application. There is no default for this option. You must apply it to legacy application classes to allow your application to function in Revit 2011.
This mode controls whether or not the API framework automatically regenerates after every model modification. There are two supported values:
- RegenerationOption.Automatic – The API framework will regenerate after every model level change (equivalent behavior with Revit 2010 and earlier). Regeneration and update can be suspended using SuspendUpdating for some operations, but in general the performance of multiple modifications within the same file will be slower than RegenerationOption.Manual. This mode is provided for behavioral equivalence with Revit 2010 and earlier; it is obsolete and will be removed in a future release.
- RegenerationOption.Manual – The API framework will not regenerate after every model level change. Instead, you may use the regeneration APIs to force update of the document after a group of changes. SuspendUpdating blocks are unnecessary and should not be used. Performance of multiple modifications of the Revit document should be faster than RegenerationOption.Automatic. Because this mode suspends all updates to the document, your application should not read data from the document after it has been modified until the document has been regenerated, or it runs the risk of accessing stale data. This mode will be only option in a future release.
For example, to set an external command to use manual regeneration mode:
[Regeneration( RegenerationOption.Manual )] [Transaction( TransactionMode.Automatic )] public class Command : IExternalCommand { public Autodesk.Revit.IExternalCommand.Result Execute( Autodesk.Revit.ExternalCommandData commandData, ref string message, Autodesk.Revit.ElementSet elements ) { // Command implementation, which modifies the // document and calls regeneration APIs when // needed. } }
To set an external application to use automatic mode
[Regeneration( RegenerationOption.Automatic )] public class Application : IExternalApplication { public Autodesk.Revit.UI.Result OnStartup( ControlledApplication a ) { // OnStartup implementation } public Autodesk.Revit.UI.Result OnShutdown( ControlledApplication a ) { // OnShutdown implementation } }
The regeneration mode used for code executed during events and updater callbacks will be the same mode applied to the ExternalApplication or ExternalCommand during which the event or updater was registered.
Manual regeneration and update
- Document.Regenerate
- Document.AutoJoinElements
These new methods have been added to allow an application running in manual regeneration mode to update the elements in the Revit document at any time.
Journaling mode
The custom attribute Autodesk.Revit.Attributes.JournalingAttribute can optionally be applied to your implementation class of the IExternalCommand interface to control the journaling behavior during the external command execution session.
- JournalMode.UsingCommandData
Uses the “StringStringMap” supplied in the command data. Hides all Revit journal entries in between the external command invocation and the StringStringMap entry. Commands which invoke the Revit UI for selection or for responses to task dialogs may not replay correctly.
- JournalMode.NoCommandData
Does not write contents of the ExternalCommandData.Data map to the Revit journal. But does allow Revit API calls to write to the journal as needed. This option should allow commands which invoke the Revit UI for selection or for responses to task dialogs to replay correctly.
New element iteration interfaces
New interfaces have been added to the API to permit iteration of elements and element ids. These new interfaces have been designed to provide a more flexible and usable interface for a variety of applications, while being completely implemented in native Revit code to provide the best possible performance.
Existing element iteration routines have been replaced, including:
- Document.Elements (all versions of this property)
- ElementIterator
- Filter and all subclasses of it
- Application.Create.Filter
- Classes and properties related to the ParameterFilter:
- CriteriaFilterType
- Document.FilterTypeSupported
- FilterCriterion
- ParameterStorage
The new element iteration interfaces offer several enhanced capabilities from their predecessors:
- The ability to iterate and filter elements from a document, or only elements from an arbitrary list of element ids, or elements visible in a view (replacing View.Elements)
- The ability to clearly identify filters which are designed for best performance ("Quick Filters"), which do not expand the element in memory when evaluating whether the element passes the filter
- The ability to use chained shortcuts which automatically apply commonly used filters, e.g.
FilteredElementCollector collector = new FilteredElementCollector( document ); // Finds all walls in a certain design option ICollection<ElementId> walls = collector .OfClass( typeof( Wall ) ) .ContainedInDesignOption( myDesignOptionId ) .ToElementIds();
- The ability to logically group more than two filters.
- The ability to match derived types automatically when using the type filter and type filter shortcut.
- The ability to iterate elements from all design options or from any specific design option.
- The ability to use foreach on the collector element, and to use the class with LINQ queries. This is due to the connection between the collector class and System.Collections.Generic.IEnumerable
. Note that because the ElementFilters and the shortcut methods offered by this class process elements in native code before their managed wrappers are generated, better performance will be obtained by using as many native filters as possible on the collector before attempting to process the results using LINQ queries.
FilteredElementCollector collector = new FilteredElementCollector( doc ); // First apply a built-in filter to minimize // the number of elements processed by LINQ collector.WherePasses( new ElementCategoryFilter( BuiltInCategory.OST_Levels ) ); // LINQ query to find level with name == "Level 1" var levelElements = from element in collector where element.Name == "Level 1" select element; Level level1 = levelElements.Cast<Level>() .ElementAt<Level>( 0 );
Detailed information on the new element iteration interfaces can be found in the document "Element iteration APIs" in the SDK.
Note that there are a few behavioral changes in the new iteration mechanism when compared to the old:
- View templates were previously returned as Element. They are now returned as the correct View subclass (ViewPlan, View3d, etc). You can identify these using the new View.IsTemplate property.
- Previous element iteration methods only returned elements of the main model, the active design option, and primary design options of each option set. Elements of design options which were not active and not primary were excluded. In the new iteration API, by default, design option membership is no longer considered when iterating elements. In order to find the same elements which were iterated in the 2010 API, you should use the following filters combined using 'OR':
- An ElementDesignOptionFilter with id = InvalidElementId, to match all elements not associated to a design option.
- An ElementDesignOptionFilter with id = DesignOption.GetActiveDesignOptionId(), to match elements in the active design option.
- A PrimaryDesignOptionMemberFilter, to match all elements in primary design options.
Replacement for View.Elements
The property View.Elements has been removed and replaced with a constructor for FilteredElementCollector taking a document and view id. This allows you to use filtering and LINQ queries against the elements visible in a given view.
Replacement for 3 structural enums
The enumerated types
- Autodesk.Revit.Structural.Enums.InstanceUsage
- Autodesk.Revit.Structural.Enums.Material
- Autodesk.Revit.Structural.Enums.WallUsage
have been replaced with new enums:
- Autodesk.Revit.DB.Structure.StructuralInstanceUsage
- Autodesk.Revit.DB.Structure.StructuralMaterialType
- Autodesk.Revit.DB.Structure.StructuralWallUsage
Some of the names of the members have changed.
Replacement for AnalyticalModel
The class hierarchy for accessing the structural analytical model has been replaced. The new class hierarchy offers a more streamlined interface and more capabilities to read data and modify analytical model settings.
The following AnalyticalModel subclasses have been removed:
- AnalyticalModel3D
- AnalyticalModelFloor
- AnalyticalModelFrame
- AnalyticalModelLocation
- AnalyticalModelWall
Access the data you used to find on those subclasses on the base AnalyticalModel class, as indicated by the following list of classes, old properties, and new methods:
- AnalyticalModelFrame – Curve – GetCurves(): If analytical model was approximated, .Curve would have previously returned non-approximated analytical model. Now GetCurves() will return approximated analytical model when analytical model is approximated. GetCurve() is a shortcut method returning the single curve.
- AnalyticalModel3D, AnalyticalModelFloor, AnalyticalModelFrame, AnalyticalModelLocation, AnalyticalModelWall – Curves – GetCurves(): AnalyticalCurveType.ActiveCurves will return the analytical model displayed by Revit. Most of the time, this is what is desired.
- AnalyticalModelLocation – Point – GetPoint(): GetCurves() can also be called, the return will be a single curve of almost 0-length containing the point.
- AnalyticalModelFrame – Profile – GetSweptProfile()
- AnalyticalModelFrame – RigidLink – GetCurves(AnalyticalCurveType.RigidLinkHead) or GetCurves(AnalyticalCurveType.RigidLinkTail): AnalyticalCurveType.RigidLinkHead retrieves the Rigid Link at the end, and AnalyticalCurveType.RigidLinkTail retrieves the Rigid Link at the start.
- AnalyticalModel3D, AnalyticalModelFloor,: AnalyticalModelFrame, AnalyticalModelLocation, AnalyticalModelWall – SupportData – GetAnalyticalModelSupports()
Note that the curves returned from these new methods will not have their Reference properties set, and cannot be used for the properties like Curve.EndPointReference. Instead, you can obtain References to the curves and their endpoints through construction of an AnalyticalModelSelector object containing the necessary information.
The AnalyticalModel class offers new methods to access other Analytical Model properties, such as:
- Adjustment information, both manual and automatic
- Parameter information, including projection, hard points, approximation, and rigid links
- Analytical offset
The AnalyticalModelProfile class has been replaced by the AnalyticalModelSweptProfile class, which offers similar contents to the original class.
The AnalyticalSupportData and AnalyticalSupportInfo classes have been replaced by collections of AnalyticalModelSupport objects. This new class offers the same information offered by AnalyticalSupportInfo, plus:
- The support priority
- The curve, point, and face providing support
The new AnalyticalSupportChecking interface offers the ability to run the check for unsupported structural elements. The new AnalyticalConsistencyChecking interface offers the ability to run a consistency check for the Analytical Model.
The results of both checks are added to the document as warnings.
Access the AnalyticalModel through the method GetAnalyticalModel() on Element. This replaces the AnalyticalModel property of Wall, Floor, ContFooting and FamilyInstance.
The integer values of the enumerated type AnalyticalSupportType have changed. They no longer match the values returned for the built-in parameter BOUNDARY_CONDITIONS_TYPE, use the members of the enum BoundaryConditionsType instead.
Replacement for gbXMLParamElem
The new class EnergyDataSettings replaces the gbXMLParamElem class. The members of the old class, the gbXMLParamElem properties, can be accessed via the new EnergyDataSettings properties as follows:
- BuildingConstruction – ConstructionSetElementId
- BuildingService – ServiceType
- BuildingType – BuildingType
- ExportComplexity – ExportComplexity
- GroundPlane – GroundPlane
- PostalCode – This is not supported in the new interface as the property has been removed from the element stored within Revit. It was removed because the data often conflicted with other settings provided during gbXML export.
- ProjectLocation – This data is not supplied; it was always the same as Document.ActiveProjectLocation.
- ProjectPhase – ProjectPhase
Revit exceptions
All Revit API methods have been changed to throw subclasses of Autodesk.Revit.Exceptions.ApplicationException. Some Revit exceptions, such as
- ArgumentException
- InvalidOperationException
- FileNotFoundException
closely mirror the corresponding .NET System exception types. However, some of them have subclasses which are unique to Revit, e.g.
- AutoJoinFailedException
- RegenerationFailedException
- ModificationOutsideTransactionException
In addition, there is a special exception type called InternalException, which represents a failure path which was not anticipated. Exceptions of this type carry extra diagnostic information which can be passed back to Autodesk for diagnosis.
Removed deprecated events
The pre-Revit 2010 events:
- Application.OnDocumentSaved
- Application.OnDocumentSavedAs
- Application.OnDocumentOpened
- Application.OnDocumentClosed
- Application.OnDocumentNewed
- Application.OnDialogBox
- Document.OnSaveAs
- Document.OnSave
- Document.OnClose
have been removed from the API. To replace these, use the replacement events in both Revit External Applications and VSTA macros.
Changes to VSTA
There are many changes to the VSTA framework:
- Revit VSTA no longer depends on the proxy DLL. Macros are now written referencing RevitAPI.dll and RevitAPIUI.dll directly. This allows macros access to the full features of the Revit API, including generic methods, all events and other methods missing from the proxy previously. Module templates have been updated accordingly, and the references will be added automatically when upgrading macros from previous releases.
- The entry point classes ThisApplication and ThisDocument have been adjusted to the direct reference of the API classes. They also now represent UIApplication and UIDocument (instead of Application and Document).
- The Transaction and Regeneration attributes must be applied to the ThisApplication and ThisDocument class. Their meanings for VSTA are same as for external commands. Module templates have been updated with default assignments, but upgraded modules must have these added manually.
- A special AddInId attribute can be added to modules. This allows VSTA macros to work with updaters. When new modules are created this attribute is automatically generated with a random Guid.
- The Module_Startup methods are now executed at the time when the module is first loaded (as the Revit application starts for Application-level macros, and as the document is loaded for document-level macros).
- No transactions may be opended in the Module_Startup and Module_Shutdown methods.
New modules created in Revit 2011 should be "ready to code" – all framework changes have been incorporated into the templates.
Upgraded macros and modules will need to be adjusted to the framework changes mentioned above, as well as all of the API changes (namespace changes, modified APIs).
Major enhancements to the Revit API
Dynamic Model Update
Dynamic model update offers the ability for a Revit API application to modify the Revit model as a reaction to changes happening in the model. This facility is offered through implementation of updaters. The updater interface offers the ability to implement a method that is informed of the scope of changes that triggered the update.
In order to "subscribe" an updater to the right set of changes, the updater should be assigned one or more update triggers. Update triggers are combinations of "Change Scope" and "Change Type". Change Scope may be either an explicit list of element ids in a document, or an implicit list of elements communicated via an ElementFilter. Change Type represents one of an available list of possible changes, including element addition, deletion, and modification of geometry, parameters, or any property of the element.
For a more detailed introduction to the Dynamic Model Update capabilities, consult the "Introduction to Dynamic Model Update" document in the SDK.
Elements changed event
The new event
- Application.DocumentChanged
is raised after every transaction gets committed, undone, or redone. This is a read-only event, designed to allow you to keep external data in synch with the state of the Revit database. To update the Revit database in response to changes in elements, use the Dynamic Model Update framework.
Failure API
There are two capabilities offered by the new failure API:
- The ability to define and post failures from within API code when a user-visible problem has occurred.
- The ability to respond to failures posted by Revit and by API code through code in your application.
This section offers a high level overview of both capabilities; more detail about the failures API is provided in the "Failure API" document in the Revit API help file.
As a part of exposing these new capabilities, all overloads accepting "PostedErrors" have been removed from the API.
Failure posting
If you are using the failure posting mechanism to report your problem, all you need to do is:
- If you are creating a new failure not already existing in Revit, define the new failure and register it in the FailureDefinitionRegistry during the OnStartup() call of your ExternalApplication (new failures must be registered at Revit startup).
- Find the failure definition id, either from the BuiltInFailures classes or from your pre-registered custom failure using the class related to FailureDefinition.
- Post a failure to a document that has a problem – using the classes related to FailureMessage to set options and details related to the failure.
Failure handling
Normally posted failures are processed by Revit's standard failure resolution UI at the end of transaction. The user is presented information and options in the UI to deal with the failures.
However, if your operation (or set of operations) on the document requires some special treatment for certain errors (or even all possible errors), you can customize failure resolution. Custom failure resolution can be supplied:
- For a given transaction using the interface IFailuresPreprocessor.
- For all possible errors using the FailuresProcessing event.
Finally, the API offers the ability to completely replace the standard failure processing user interface using the interface IFailuresProcessor.
Select element(s), point(s) on element(s), face(s) or edge(s)
- Selection.PickObject
- Selection.PickObjects
New methods have been added to prompt the user to select items from the Revit model. When using the new selection methods from your application you can:
- Allow users to make one or multiple selections
- Allow users to make multiple selections via box select
- Provide a custom status prompt to direct the user what to select
- Provide a custom selection filter (Autodesk.Revit.UI.ISelectionFilter) to accept only those items which your application supports
- Provide a list of preselected items which will be selected and highlighted when the selection activity starts
- Reference(Element) – This new constructor allows you to obtain a Reference for an Element; it can be useful when adding preselected elements to the PickObjects() call.
Pick point on the view active workplane
- Selection.PickPoint()
New methods have been added to prompt the user to pick a point on the view active workplane. When using these methods you have the option of overriding the user's default snap settings and providing a custom status prompt to direct the user what to pick. The method returns an XYZ location corresponding to the user's pick.
For 2D and 3D views, you can set the active workplane via the new setter property for View.SketchPlane. This allows you to control the plane used for calls to the PickPoint() method.
For 2D views where the active workplane cannot be changed, such as drafting and sheet views, the method picks a point in the default coordinate system of the view.
Additional options for Ribbon customization
There are new Ribbon components supported via the Ribbon API:
- SplitButton – a pulldown button with a default pushbutton attached
- RadioGroup – a set of ToggleButtons, where only one of the set can be active at a time
- ComboBox – a pulldown containing a set of selectable items, which can be grouped optionally
- TextBox – an input field for users to enter text
- SlideOut panel – an extra panel can optionally slide down from a Ribbon panel; this panel can contain any of the standard Ribbon components
For ComboBox and TextBox, events are included; these events call your API code when the component is changed by the user.
The new property:
- RibbonItem.Visible
provides control over whether a particular item is visible.
The new properties:
- RibbonItem.LongDescription
- RibbonItem.ToolTipImage
allow you to set up an extended tooltip for the Ribbon item. This tooltip can display a longer set of text, and/or a single image.
The new property:
- PushButton.AvailabilityClassName
allows assignment of an availability class to controlled whether or not the button is available, similar to the option provided for ExternalCommands registered by manifest.
There is also a new option supported for PulldownButton – a separator can now be added between buttons this component.
There is also a new option to add custom panels to the Analyze tab in Revit as well as the Add-Ins tab, via a new overload of Application.CreateRibbonPanel().
As a result of these enhancements, some pre-existing APIs have changed:
- RibbonPanel.AddButton() has been replaced with RibbonPanel.AddItem()
- RibbonPanel.AddStackedButtons() overloads have been replaced with RibbonPanel.AddStackedItems() overloads
- Property RibbonPanel.Items has been replaced with method RibbonPanel.GetItems()
- Property PulldownButton.Items has been replaced with method PulldownButton.GetItems()
- Methods RibbonPanel.AddPushButton() and RibbonPanel.AddPulldownButton() have been removed. Use RibbonPanel.AddItem() for this operation.
- RibbonPanel.AddToPulldown() has been removed. Use PulldownButton.AddItem() for this operation.
- PulldownButton.AddPushButton() has been removed. Use PulldownButton.AddItem() for this operation.
Create and display Revit-style Task Dialogs
The API now offers the ability to create and display Revit-style Task Dialogs. It is intended to provide capabilities similar to System.Windows.Forms.MessageBox with a Revit look-and-feel such as:
Construct an instance of the class:
- Autodesk.Revit.UI.TaskDialog
and use the members of that class to set the instructions, detailed text, icons, buttons and command links to be displayed in the task dialog. Then display the dialog using the Show() method. After the user responds to the dialog by clicking one of the buttons or links, the Show() method returns an identifier indicating the user's preferred choice.
There are also shortcut static Show() methods on this class providing a quick way to show simple task dialogs.
Idling event
The new event
- UIApplication.Idling
is raised when it is safe for the API application to access the active document between user interactions. The event is raised only when the Revit UI is in a state where the user could successfully click on an API command button. The event allows changes to a document if a new transaction is opened.
Because this event is invoked between user actions in the Revit UI, if the handler for this event requires a significant amount of processing time, users will perceive a slowdown in the responsiveness of Revit. If the execution for updates can be safely split across multiple calls to this event, the user perception of Revit responsiveness will be improved.
Sun and shadows settings element
The SunAndShadowSettings class represents the settings applied to a project or view regarding the position, dates, time intervals and other options for the sun control and solar studies. Obtain the SunAndShadowSettings for a particular view from the View.SunAndShadowSettings property. Obtain the SunAndShadowSettings for the project from SunAndShadowSettings.GetActiveSunAndShadowSettingsId().
MEP Electrical API
Demand factor and load classifications
The property
- ElectricalSystem.LoadClassification
has been replaced with a new property
- ElectricalSystem.LoadClassifications
The new property returns a semicolon-delimited string listing the load classifications assigned to the system. Load classifications are now an element and can be found through regular element iteration.
The class
- DemandFactor
was replaced by
- ElectricalDemandFactorDefinition.
The method
- ElectricalSetting.GetDemandFactor()
has been replaced by
- ElectricalLoadClassification.DemandFactorId
which returns the id of the ElectricalDemandFactorDefinition element assigned to the load classification.
Panel schedules
A new comprehensive API has been introduced to support access to Panel Schedules and their contents. The major classes exposed by this API are:
- TableView – represents a view that shows a table.
- TableData – holds most of the data that describe the style of the rows, columns, and cells in a table.
- TableSectionData – holds row, column and cell data for a TableData instance.
- PanelScheduleView – represents a view that shows a panel schedule.
- PanelScheduleData – holds most of the data that describe the layout, appearance, and style of the rows, columns, and cells of a panel schedule.
- PanelScheduleTemplate – represents a branch panel, a switchboard or a data panel template.
- PanelScheduleSheetInstance – represents an instance of a panel schedule placed on sheet.
Cable tray and conduit
New classes and elements have been added to the API related to Cable Tray and Conduit elements. The major classes introduced by this API are:
- CableTrayConduitBase – the base class for cable trays and conduits.
- CableTrayConduitRunBase – the base class for cable tray and conduit runs.
- CableTray – a cable tray instance.
- CableTrayType – a cable tray type.
- CableTrayRun – a cable tray run.
- Conduit – a conduit instance.
- ConduitType – a conduit type.
- ConduitRun – a conduit run.
The previously existing API classes
- ConduitType
- ConduitTypeSet
have been renamed to
- WireConduitType
- WireConduitTypeSet
as a result of the introduction of the new conduit elements.
Analysis Visualization Framework
This new functionality creates a mechanism for external analysis applications to easily display the results of their computation as 3D data in the Revit model. Note that the results data is transient; it is stored only in the model for the duration of the current Revit session.
The SpatialFieldManager class is used to create, delete, and modify the "containers" in which the analysis results are stored.
The FieldDomainPoints sub-classes indicate the points where analysis results are computed.
The FieldValues class contains the values for each domain point. Each domain point can have multiple values, each for a separate "measurement" at this point. For example, if a solar calculation is being done for every day of the year, each point would have 365 corresponding values.
The code below assigns results for two data points on a surface:
SpatialFieldManager sfm = SpatialFieldManager .CreateSpatialFieldManager( view, 1 ); Reference reference = doc.Selection.PickObject( ObjectType.Face, "Select a face" ); int idx = sfm.AddSpatialFieldPrimitive( reference ); Face face = reference.GeometryObject as Face; IList<UV> uvPts = new List<UV>(); uvPts.Add( new UV( 0, 0 ) ); uvPts.Add( new UV( 0.1, 0.1 ) ); FieldDomainPointsByUV pnts = new FieldDomainPointsByUV( uvPts ); List<double> doubleList = new List<double>(); IList<ValueAtPoint> valList = new List<ValueAtPoint>(); doubleList.Add( 0 ); valList.Add( new ValueAtPoint( doubleList ) ); doubleList.Clear(); doubleList.Add( 10 ); valList.Add( new ValueAtPoint( doubleList ) ); FieldValues vals = new FieldValues( valList ); sfm.UpdateSpatialFieldPrimitive( idx, pnts, vals );
Small enhancements & API interface changes
Family & massing API enhancements
Rehost a form
The overloaded methods
- Form.Rehost()
rehost a form to a new edge, face, curve, or sketch plane.
Obtain the location of point placement references from a family
The methods
- FamilySymbol.GetFamilyPointPlacementReferences()
- FamilyInstance.GetFamilyPointPlacementReferences()
provide information about the location and geometry of point placement references in the loaded family symbol or placed family instance. These points are found in Panel families and flexible components.
Associate array dimension to label in families
The property
- BaseArray.Label
associates the number of members of the array with a family parameter.
A BaseArray only can be labelled in a family document and only can be labelled to an integer FamilyParameter. The property can also unbind a labelled family parameter.
Dissociate label from dimension in families
The property
- Dimension.Label
can be set to null to dissociate a dimension from a label parameter.
Rename and replace a family parameter
The method
- FamilyManager.RenameParameter()
allows you to rename a Family parameter.
The overloaded methods
- FamilyManager.ReplaceParameter()
allow you to replace a Family parameter with a new shared parameter, or a shared parameter with a new Family parameter.
Reporting parameters
The property
- FamilyParameter.IsReporting
identifies if the parameter is a reporting parameter. If true, the parameter is associated to a dimension value and cannot be modified. If false, the parameter is a driving parameter and if associated to a dimension, can modify the dimension it labels.
The methods
- FamilyManager.MakeReporting()
- FamilyManager.MakeNonReporting()
change a family parameter to be reporting or non-reporting.
Place 2D family types on views
A new overload
- ItemFactoryBase.NewFamilyInstance(XYZ, FamilySymbol, View)
has been added to support placement of 2D families in target views. This can be used for placement of detail components, annotation symbols, and titleblocks into their target views.
Prompt user to interactively place a family type
The method
- UIDocument.PromptForFamilyInstancePlacement()
prompts the user to place one or more instances of a particular FamilySymbol.
Use IFamilyLoadOptions to override behavior when loading family or family symbol from disk
New overloads for
- Document.LoadFamily()
- Document.LoadFamilySymbol()
have been added. These overloads accept IFamilyLoadOptions as an argument, allowing your application to automatically respond to the prompts Revit typically shows the user when reloading a family which already exists in a document. These new overloads apply when loading a family or a family symbol from a file on disk.
Extract PartAtom from loaded family
The method
- Family.ExtractPartAtom()
writes a PartAtom file describing the loaded family to a specified file on disk.
FamilyHostingBehavior
The enum FamilyHostingBehavior represents the type of host a family expects. The value for a particular family can be obtained from the family's BuiltInParameter.FAMILY_HOSTING_BEHAVIOR parameter.
FamilyInstance.Host property improved
The property
- FamilyInstance.Host
will now return the host element of face-hosted family instances. Previously it returned null.
Convert family to be face host based
The method
- FamilyUtils.ConvertFamilyToFaceHostBased()
converts a family to be face host based.
Extract id of a family parameter
The new property
- FamilyParameter.Id
extracts the id of a FamilyParameter as an ElementId. When you have a shared or family parameter, this Id is needed in order to use the parameter from an ElementParameterFilter during element iteration and as a ParameterChange for an updater. When you have a built-in parameter, the integer value of the id is the same as the integer value of the BuiltInParameter enumeration.
API for solid/solid cut
The static methods in the class
- SolidSolidCutUtils
expose the ability to add and remove new solid/solid cuts, and to inquire if an element is used in solid/solid cut in a family.
Additional DividedSurface API
Some additional methods have been added to the DividedSurface class and provide access to intersection references:
- DividedSurface.GetAllIntersectionElements()
- DividedSurface.AddIntersectionElement()
- DividedSurface.RemoveIntersectionElement()
- DividedSurface.RemoveAllIntersectionElements()
- DividedSurface.CanBeIntersectionElement()
View API changes
NewViewPlan input change
The method
- Autodesk.Revit.Creation.Document.NewViewPlan()
now accepts a ViewPlanType enum, which contains only those view types which can be created by the method.
Refresh active view
The method
- Document.RefreshActiveView()
refreshes the display of the active view during the execution of your command so users can see incremental updates to their model. As in the past, Revit will automatically redraw the view after the command completes.
View.IsTemplate
This property identifies if an instance of the View class represents an instance view (which users see in the project browser and graphics window) or a template view.
Save image to new view
The new method
- Document.SaveToProjectAsImage()
saves the graphics shown in the current view to a rendering view in the document.
API for placeholder sheets
The method
- ViewSheet.CreatePlaceholder()
creates a placeholder sheet in the document. Placeholder sheets represent sheets stored outside of the Revit model, but which should be organized along with the Revit sheets.
The property
- ViewSheet.IsPlaceholder
identifies if a sheet is a placeholder sheet or not.
Import, export and print changes
Import DWG as link
The method
- Document.Link()
imports a DWG into the document as a link.
Identify if import instance is linked
The property
- ImportInstance.IsLinked
identifies if an import instance element is a link to an external file.
Print API changes
The property
- PrintSetup.CurrentPrintSetting
has been changed to an IPrintSetting. This interface may represent a PrintSetting element, or an InSessionPrintSetting object representing the In-session print settings for Revit printing.
The property
- PrintSetup.InSessionPrintSetting
has been added to return the In-session print settings object. The in-session print settings will no longer returned in the collection of elements from the property
- Document.PrintSettings
The event arguments for the event
- Document.DocumentPrinting
has been changed to return an IPrintSetting object as well.
The property
- ViewSheetSetting.CurrentViewSheetSet
has been changed to an IViewSheetSet. This interface may represent a ViewSheetSet element, or an InSessionViewSheetSet object representing the In-session view sheet set for Revit printing.
The property
- ViewSheetSetting.InSessionViewSheetSet
has been added to return the In-session view sheet set object. The in-session view sheet set will no longer returned in the collection of elements from the property
- Document.ViewSheetSets
Export option for colour mode
The new property
- ACADExportOptions.Colors
allows the option of exporting colours matching the AutoCAD Color Index colours, or as 24-bit true colour RGB values.
Export model to IFC
The new method
- Document.Export(string, string, IFCExportOptions)
exports the document to the Industry Standard Classes (IFC) format.
Export model to DXF
The new method
- Document.Export(string, string, ViewSet, DXFExportOptions)
exports the document or set of selected views to the DXF format.
Export model to SAT
The new method
- Document.Export(string, string, ViewSet, DXFExportOptions)
exports the document or set of selected views to the SAT format.
Export image
The new method
- Document.ExportImage()
exports the graphics shown in one or more views to image file(s).
Extract image of an ElementType
The new method
- ElementType.GetPreviewImage()
extracts the preview image of an Element Type. This image is similar to what is seen in the Revit UI when selecting the type of an element. You can specify the size of the image in pixels.
Updated DWF and DWFX export methods
The four 2010 Document.Export methods for exporting of DWF-2D, DWF-3D, DWFX-2D and DWFX-3D files were consolidated into just two methods, one for exporting to DWF format, another to DWFX format. The corresponding export options classes are:
- DWFExportOptions
- DWFXExportOptions
Both methods can export both 2D views as well as 3D views in one call.
Export id
The static method
- ExportUtils.GetExportId()
retrieves the GUID representing an element in DWF and IFC export. This id is used in the contents of DWF export and IFC export and it should be used only when cross-referencing to the contents of these export formats. When storing Ids that will need to be mapped back to elements in future sessions, UniqueId must be used instead.
Parameter API changes
ParameterFilterElement
Provides access to filter elements associated to views. You can access and modify the categories associated to a filter and the rules associated to a filter. You can also create new filters using an input list of categories and rules.
Rules are organized in a hierarchy based on parameter value type:
- FilterIntegerRule – applies to integer and enumerated type parameters.
- FilterDoubleRule – applies to double type parameters.
- FilterElementIdRule – applies to ElementId type parameters.
- FilterStringRule – applies to String type parameters.
Rules are associated to evaluators and value providers.
Evaluators are classes which determine how to evaluate the rule based on the value of the parameter and the value set in the rule. There are two hierarchies of evaluators:
- FilterStringRuleEvaluator – applies to FilterStringRule rules, offers options for equality, begins with, ends with, contains, greater than, and less than evaluations.
- FilterNumericRuleEvaluator – applies to other rule types, offers options for equality, greater than, and less than.
At this time, the hierarchy of evaluators is not extendable in the API.
Value providers determine how the value is obtained for the evaluation. In this release, there is only one value provider available: ParameterValueProvider.
Extract GUID from a Parameter
The new properties
- Parameter.IsShared
- Parameter.GUID
identify if a given parameter is a shared parameter, and if it is, extract its GUID.
Extract id of a parameter
The new property
- Parameter.Id
extracts the id of a parameter as an ElementId. When you have a shared or family parameter, this Id is needed in order to use the parameter from an ElementParameterFilter during element iteration and as a ParameterChange for an updater. When you have a built-in parameter, the integer value of the id is the same as the integer value of the BuiltInParameter enumeration.
SuspendUpdating applies to Parameter.Set
SuspendUpdating performance improvements now apply to Parameter.Set by default. By using the new constructor for SuspendUpdating which takes a boolean suspendForParameterSet, you can turn off this option.
The performance benefits of this can be extremely significant (95-99% improvement in speed) if you are setting instance parameters on family instances (where the instance parameters are defined in the family itself, and not added to the instances via shared parameters). For most other applications of Parameter.Set this will likely have no visible performance benefit.
Note that SuspendUpdating applies only to RegenerationMode.Manual.
Alignment and ItemFactoryBase.NewAlignment() method
The Alignment element subclass has been removed. NewAlignment() and element iteration will now return alignments as Dimension elements.
DimensionType – access to the dimension style
The property
- DimensionType.StyleType
identifies the style to which the dimension type can be applied, e.g. linear, angular, radial, etc.
Create sloped wall on mass face
The method
- FaceWall.Create()
creates a new instance of a face wall on the sloped face of a mass.
Face.GetBoundingBox() method
This new method returns a BoundingBoxUV with the extents of the parameterization of the face.
NewFootPrintRoof() input
The method
- Autodesk.Revit.Creation.Document.NewFootPrintRoof()
has been changed. It now outputs an array of Model Curves corresponding to the set of Curves input in the footPrint. By knowing which Model Curve was created by each footPrint curve, you can set properties like SlopeAngle for each curve.
Floor slope and elevation
The slope and elevation at a point on floor's surface can be found using the methods:
- Floor.GetVerticalProjectionPoint()
- Floor.GetNormalAtVerticalProjectionPoint()
Converting between Model Curves and Detail/Symbolic Curves
The Revit API offers new utilities to convert model curves to and from detail curves or symbolic curves.
- Document.ConvertModelToDetailCurves()
- Document.ConvertDetailToModelCurves()
- Document.ConvertModelToSymbolicCurves()
- Document.ConvertSymbolicToModelCurves()
In all these methods, the original curves are deleted. If the curves do not lie in the appropriate plane for their target curve type, they will be projected to the target plane.
CurveElement type
The new property
- CurveElement.CurveElementType
identifies if a particular curve is a model curve, detail curve, symbolic curve, reference line, room, area or space separation line, insulation detail curve, repeating detail profile line, or revision cloud line.
Shared base classes for Room, Space, Area and their tags
The new classes Enclosure and EnclosureTag act as shared base classes for rooms, spaces, and areas, and room tags, space tags, and area tags, respectively. Some shared functionality from the derived classes has been moved into the base classes. There are some minor impacts to the previous API interfaces:
- The RoomTag, SpaceTag, AreaTag property Leader has been renamed to HasLeader.
- The Room and Space properties Area and Perimeter have been moved to the base class, thus granting access to these properties for the Area class as well.
View-specific elements
The new properties
- Element.ViewSpecific
- Element.OwnerViewId
identify if the element is owned by a particular view (for example, a Detail Curve is owned by the drafting view in which it is drawn), and which view is the owner. These properties align with the ElementOwnerViewFilter which can be used in Element iteration.
Monitoring elements
The new functions
- Element.IsMonitoringLinkElement()
- Element.IsMonitoringLocalElement()
- Element.GetMonitoredLinkElementIds()
- Element.GetMonitoredLocalElementIds()
indicate whether an element is monitoring any elements in the local document or in linked files.
Design Options
The new static function
- DesignOption.GetActiveDesignOptionId()
returns the id of the active design option within the document.
The new property
- DesignOption.IsPrimary
identifies if the design option is the primary option within its owning design option set.
Family template path
The property
- Application.FamilyTemplatePath
provides the default path for family template files.
Write comments to the Revit Journal File
The method
- Application.WriteJournalComment()
allows the API application to write comments to the Revit Journal file for diagnostic, testing, and other purposes.
Window extents
The properties
- UIApplication.MainWindowExtents
- UIApplication.DrawingAreaExtents
provide access to the outer coordinates of the Revit window and drawing area, in pixels. An application can use these value to correctly locate its own UI relative to the Revit UI.
City.WeatherStation
The new property
- City.WeatherStation
provides an identifier for the nearest weather station.
Labels matching commonly used enumerated type values
The new class LabelUtils provides methods to obtain the user-visible label corresponding to certain enum values. These routines obtain the label corresponding to the name in the current Revit language. Support is offered for:
- BuiltInParameter
- BuiltInParameterGroup
- ParameterType
- UnitType
- DisplayUnitType
- gbXMLBuildingType
Keyboard shortcut support for API buttons
API buttons found on the Ribbon can be assigned a keyboard shortcut. Buttons created by applications registered using manifest files now use an id based on their application id and button name to provide a unique identifier for the button. The keyboard shortcut will be maintained even if the order of registration of API applications changes.
MEP API
Validation in ElectricalSystem properties
The properties
- ElectricalSystem.Length
- ElectricalSystem.VoltageDrop
now throw an InvalidOperationException when the value cannot be computed (instead of returning 0).
WireMaterialType, InsulationType, TemperatureRatingType
These methods now inherit from ElementType.
DuctConnector, PipeConnector, ElectricalConnector
The methods now inherit from a new common base class, ConnectorElement.
Structural API
NewTruss() in Revit Architecture
The Autodesk.Revit.Creation.Document.NewTruss method, which was previously only enabled in Revit Structure, is now also enabled in Revit Architecture.
Truss – attach and detach chord
The methods
- Truss.AttachTopChord
- Truss.DetachTopChord
have been replaced by methods
- Truss.AttachChord
- Truss.DetachChord
supporting both top and bottom chords as inputs.
Drop truss and beam systems
The new methods
- Truss.DropTruss()
- BeamSystem.DropBeamSystem()
delete the parent collection elements after disassociating their constituent members.
Rebar API changes
The new methods
- Autodesk.Revit.Creation.Document.NewRebarBarType()
- Autodesk.Revit.Creation.Document.NewRebarHookType()
- Autodesk.Revit.Creation.Document.NewRebarCoverType()
allow creation of new instances of these elements.
The RebarBarType class has a new interface. (Formerly some properties were available through parameters only.)
- BarDiameter
- StandardBendDiameter
- StandardHookBendDiameter (new property for 2011)
- StirrupTieBendDiameter
- MaximumBendRadius
- GetHookPermission() / SetHookPermission()
- GetAutoCalcHookLengths() / SetAutoCalcHookLengths()
- GetHookLength() / SetHookLength()
- GetHookOffsetLength() / SetHookOffsetLength()
The Rebar class has two new properties, includeFirstBar and includeLastBar, which allow suppression of the end bars in a rebar array.
Rebar also has a new interface to its Array functionality. (Formerly these properties were available through parameters only.)
- LayoutRule: (read-only) Array layout rule.
- SetLayoutAsSingle() / SetLayoutAsFixedNumber() / SetLayoutAsMaximumSpacing() / SetLayoutAsNumberWithSpacing() / SetLayoutAsMinimumClearSpacing(): Change the array layout rule. Note that the layout rule interacts with several other properties; to avoid confusion, the SetLayout methods require you to specify values for these other properties.
- ArrayLength: Array length.
- NumberOfBarPositions: Number of bar positions in the array. The actual number may be 1 or 2 fewer and is given by getQuantity().
- MaxSpacing: maxium spacing.
- Quantity: (read-only) Number of bars in the array, equal to getNumberOfBarPositions() minus the number of end bars suppressed with includeFirstBar / includeLastBar.
- BarsOnNormalSide: flip the array with respect to the start plane.
The method SetLayoutRuleWithoutExaminingHost() has been removed in favour of the new setLayoutRuleAs...() methods.
The methods:
- Rebar.IsUnobscuredInView()
- Rebar.SetUnobscuredInView()
- Rebar.IsSolidInView()
- Rebar.SetSolidInView()
control the visibility of the Rebar in the indicated view.
New Rebar properties and methods have been introduced to work with spiral rebar:
- Rebar.Height
- Rebar.Pitch
- Rebar.BaseFinishingTurns
- Rebar.TopFinishingTurns
- Rebar.ScaleToBoxForSpiral()
- RebarShapeDefinitionByArc.SetArcTypeSpiral()
Finally, HostedSweep elements are now valid for the Rebar.Host property.
Structural Settings
The class StructuralSettings provides access to many of the values shown in the Revit Structural Settings dialog box:
- Symbolic Cutback distances
- Brace symbols
- Analytical model settings
- Boundary conditions settings
To obtain the StructuralSettings for a given document, use the static method:
- StructuralSettings.GetStructuralSettings(Document)
Some items in the Revit Structural Settings dialog box are not accessed through StructuralSettings in the API:
- Connection Types are individual elements of type StructuralConnectionType that are part of the document.
- Load cases are individual elements of type LoadCase that are part of the document.
Rigid link built-in parameter change
The built-in parameter id STRUCTURAL_ANALYTICAL_RIGID_LINK has been replaced with STRUCTURAL_ANALYTICAL_COLUMN_RIGID_LINK and STRUCTURAL_ANALYTICAL_BEAM_RIGID_LINK.
You can also access the value of this parameter for a given element via the AnalyticalModel.RigidLinksOption property.
BoundaryConditions type
A new enum BoundaryConditionsType has been introduced. The values of this enum match the values of the built-in parameter id BOUNDARY_CONDITIONS_TYPE.
End of document
So that was the news in the Revit 2011 API way back in the year 2010.
Please be aware that some of the changes listed above obviously have changed yet again since.
Stay tuned for the next installment, coming soon, leading up towards the current day.