What's New in the Revit 2011 API

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 repsonses to any comments for a while.

    My first cappuccino in Domodossola was slightly disappointing.

First Italian coffee

    It improved later, though.

I love cappuccino

Searching for sun and warmth, we found cold and snow, and started heading southward to flee it.

Poirone clock tower with snow

Instead of getting better, it got worse, causing huge trees to crash down or lose their branches under loads of snow never previously experienced.

Cesenatico branch broken by snow

We did what we could to improve the situation.

Rolling a snowball on the beach

The result is anti-art.

Snowman and woman

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:

Within these main namespaces there are subdivisions based on discipline, e.g.:

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.:

As a result of the rearrangement of the namespaces, a few classes have been modified more drastically than simply being moved to new namespaces:

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:

In order to facilitate access to application and document level interfaces from both DLLs, the Application and Document classes have also split into two:

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:

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:

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:

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:

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:

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:

The new Transaction interfaces replace the old APIs:

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:

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.

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:

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:

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

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:

  1. 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.
  2. 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.
  3. 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:

  1. 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.
  2. 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

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.

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.

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:

The new element iteration interfaces offer several enhanced capabilities from their predecessors:

  FilteredElementCollector collector
    = new FilteredElementCollector( document );
 
  // Finds all walls in a certain design option
 
  ICollection<ElementId> walls = collector
    .OfClass( typeof( Wall ) )
    .ContainedInDesignOption( myDesignOptionId )
    .ToElementIds();
  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:

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

have been replaced with new enums:

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:

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:

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:

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 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:

Revit exceptions

All Revit API methods have been changed to throw subclasses of Autodesk.Revit.Exceptions.ApplicationException. Some Revit exceptions, such as

closely mirror the corresponding .NET System exception types. However, some of them have subclasses which are unique to Revit, e.g.

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:

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:

  1. 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.
  2. 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).
  3. 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.
  4. 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

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:

  1. The ability to define and post failures from within API code when a user-visible problem has occurred.
  2. 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:

  1. 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).
  2. Find the failure definition id, either from the BuiltInFailures classes or from your pre-registered custom failure using the class related to FailureDefinition.
  3. 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:

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)

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:

Pick point on the view active workplane

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:

For ComboBox and TextBox, events are included; these events call your API code when the component is changed by the user.

The new property:

provides control over whether a particular item is visible.

The new properties:

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:

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:

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:

Task dialogue

Construct an instance of the class:

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

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

has been replaced with a new property

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

was replaced by

The method

has been replaced by

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:

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:

The previously existing API classes

have been renamed to

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

rehost a form to a new edge, face, curve, or sketch plane.

Obtain the location of point placement references from a family

The methods

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

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

can be set to null to dissociate a dimension from a label parameter.

Rename and replace a family parameter

The method

allows you to rename a Family parameter.

The overloaded methods

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

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

change a family parameter to be reporting or non-reporting.

Place 2D family types on views

A new overload

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

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

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

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

will now return the host element of face-hosted family instances. Previously it returned null.

Convert family to be face host based

The method

converts a family to be face host based.

Extract id of a family parameter

The new property

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

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:

View API changes

NewViewPlan input change

The method

now accepts a ViewPlanType enum, which contains only those view types which can be created by the method.

Refresh active view

The method

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

saves the graphics shown in the current view to a rendering view in the document.

API for placeholder sheets

The method

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

identifies if a sheet is a placeholder sheet or not.

Import, export and print changes

Import DWG as link

The method

imports a DWG into the document as a link.

Identify if import instance is linked

The property

identifies if an import instance element is a link to an external file.

Print API changes

The property

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

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

The event arguments for the event

has been changed to return an IPrintSetting object as well.

The property

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

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

Export option for colour mode

The new property

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

exports the document to the Industry Standard Classes (IFC) format.

Export model to DXF

The new method

exports the document or set of selected views to the DXF format.

Export model to SAT

The new method

exports the document or set of selected views to the SAT format.

Export image

The new method

exports the graphics shown in one or more views to image file(s).

Extract image of an ElementType

The new method

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:

Both methods can export both 2D views as well as 3D views in one call.

Export id

The static method

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:

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:

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

identify if a given parameter is a shared parameter, and if it is, extract its GUID.

Extract id of a parameter

The new property

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

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

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

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:

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.

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

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:

  1. The RoomTag, SpaceTag, AreaTag property Leader has been renamed to HasLeader.
  2. 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

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

indicate whether an element is monitoring any elements in the local document or in linked files.

Design Options

The new static function

returns the id of the active design option within the document.

The new property

identifies if the design option is the primary option within its owning design option set.

Family template path

The property

provides the default path for family template files.

Write comments to the Revit Journal File

The method

allows the API application to write comments to the Revit Journal file for diagnostic, testing, and other purposes.

Window extents

The properties

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

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:

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

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

have been replaced by methods

supporting both top and bottom chords as inputs.

Drop truss and beam systems

The new methods

delete the parent collection elements after disassociating their constituent members.

Rebar API changes

The new methods

allow creation of new instances of these elements.

The RebarBarType class has a new interface. (Formerly some properties were available through parameters only.)

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.)

The method SetLayoutRuleWithoutExaminingHost() has been removed in favour of the new setLayoutRuleAs...() methods.

The methods:

control the visibility of the Rebar in the indicated view.

New Rebar properties and methods have been introduced to work with spiral rebar:

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:

To obtain the StructuralSettings for a given document, use the static method:

Some items in the Revit Structural Settings dialog box are not accessed through StructuralSettings in the API:

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.