Revit APP Blog

Information on Revit APP.

Browsing Posts in Technical

To develope Revit add-in applications, the capability to debug the code is very important to find problems, solve bugs etc.

In visual studio, select the project you want to debug, right click and select the lowest “Property” item, in the property page, choose “Debug” in the left panel, and in “Start Action”, choose “Start external program:” and then select the Revit.exe in your installation folder like following picture, then you can add break points in your project and debug your application as general executable projects.

And there is another way to debug your program: run revit first, then in visual studio, click the “Attach to Process” under “Debug” menu:

In the pop-up dialog, select Revit in the “Available Processes”, then click “Attach”, the other is same as previous method:

Revit 2011 supports user defined keyboard shortcut for both build-in commands and API addin commands. Here we show you the way to set your own keyboard shortcut for your addin commands. Before the setting, please make sure “Add-ins” tab shows up in your Revit ribbon and your addin commands shows up under the “Add-ins” tab.

Go to “View” tab, click the “User Interface” dropdown menu, and select the “Keyboard Shortcuts” item like following pic.

Then in the pop up dialog, select “Add-ins tab” in the Filter dropdown combobox, like following pic:

After the selection, you can see all your commands under Add-ins tab, choose the command item and input the keyboard shortcuts in the “Press new keys” area, then click “Assign” button:

Click “OK” to close the Keyboard Shortcuts dialog. Then you can use your new defined shortcuts for your own commands now.

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<Element>. 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(m_doc);
// First apply a built-in filter to minimize the number of elements processed by LINQ
collector.WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Levels));

var levelElements = from element in collector
                    where element.Name == “Level 1″
                    select element;  // LINQ query to find level with name == “Level 1″

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.

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 application)
    {
        // OnStartup implementation
    }
  
    public Autodesk.Revit.UI.Result OnShutdown(ControlledApplication  application)
    {
      // 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.

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.

    }

}

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\
  • 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\
  • In a user specific location in “application data”

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:

 Tag  Description
 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.

Many people are wondering what the prospect of Revit API development is. They believe there is some opportunities, however don’t know how big it is and how large the market will be. Even Revit based products still have many limitations, gaps, and are not mature as AutoCAD, I still would say that there is a great opportunity for Revit API development and there would be a great increase market on this with grows of Revit market. There are three reasons.

First, building information modeling (BIM) is the future of building modeling and would be a standard. It proves its value in the complete life cycle of building modeling starting from the very beginning stage – conceptual design.

Second, all Revit based products which are parametric BIM tools are the main BIM tools produced by Autodesk. Autodesk will definitely reinforce these products to make it as the leader role in this area. From the latest 2011 release, we can see many new features / enhancement / problem fix. And I believe Autodesk will improve these products continuously.

Third, as we know, none software can satisfy every user, there always be gaps between the user requirements and the software capabilities. So many smart companies deliver their public API for their software and allow third party developer to develop add-ins based on their API. There are tons of successful cases. Like apple’s iPhone platform and Autodesk’s AutoCAD platform. The third party add-ins will also add value to the platform. From the change in 2011 Revit API, we can see that Autodesk is trying to provide as much API as possible and I am expecting Revit API will be as strong as AutoCAD APIs at the end of day.

Based on these, I have confidence that Revit API development has a bright future. The only concern is how quick Autodesk will make the Revit success and make the Revit API strong enough.

What You Will Need to Get Started

  • A working understanding of Autodesk Revit Architecture, Autodesk Revit Structure or Autodesk Revit MEP 2011
  • An installation of an Autodesk Revit-based product, including the Software Development Kit
  • MS Visual Studio 2008 or MS Visual Studio 2008 Express Edition, or a full installation of Microsoft Visual Studio. If you plan to start with VSTA, you do not need to install any of these.
  • Some experience in a .NET based development language (Autodesk Revit API examples are provided in C# and Visual Basic.NET.)
  • 2 days of free time

Understanding Autodesk Revit

All Autodesk Revit-based products are Parametric Building Information Modeling (BIM) tools. Such a tool can be looked at as a CAD program that is used to build a 3D model rather than a set of individual drawing files. Autodesk Revit modeling is accomplished with real-world elements like columns, walls, doors and windows. The user can create views of the model, including plans, sections and callouts. All these views are directly generated from the 3D physical model so changes made in one view will automatically propagate through all other views. This process virtually eliminates the need to update multiple drawings and details when a change is made in the model.

The Autodesk Revit API is designed to reflect the same user interaction paradigms as the program’s Graphical User Interface. Therefore, the first step to understanding the API is to learn how to use the program. If you are an Autodesk Revit novice, we suggest you first start by going through the Tutorials which you can access through the program’s Help menu. You may also find it helpful to take a Training class from your local Autodesk reseller. This will help you quickly get up to speed with the program

Autodesk Resources:

Select = Autodesk Revit Building

Then Select = Autodesk Revit API

External Resources:

Installation of the Autodesk Revit API

The Autodesk Revit API is automatically installed with the default installation of the Autodesk Revit based product.

The Autodesk Revit API Software Development Kit is installed from the Tools and Utilities section of the Autodesk Revit installation DVD.

Development Requirements

The Autodesk Revit API requires the Microsoft .NET Framework v3.5.  To edit and debug your API applications, you need an interactive development environment such as Microsoft Visual Studio 2008 or one of the MS Visual Studio Express Editions for C# or Visual Basic.NET.  When developing with the Autodesk Revit API, ensure that your project references two DLLs: RevitAPI.dll and RevitAPIUI.dll contained in the Autodesk Revit Program directory.

Some programming skills are required to effectively use the API. If you are a beginner in programming, we strongly advise you to learn Microsoft Visual Studio 2008 and one of the compatible languages like C# or Visual Basic.NET. There are many good books and classes to get you started.

Resources:

Online resources

Books:

  • Code Complete, Second Edition, by Steve McConnell
  • Software Project Survival Guide, by Steve McConnell
Powered by WordPress Web Design by SRS Solutions © 2012 Revit APP Blog Design by SRS Solutions