RTC Classes and Getting Started with Revit Macros

I have never dealt with Revit macros in depth before.

Now I am finally forced to, having been asked to take over a hands-on lab on the topic from someone else at the Revit Technology Conference RTC Europe in Budapest later this week.

I am presenting three classes at RTC.

Here they are, plus another important Revit-related news item and pictures from my recent travel preparation – some time out in nature before entering airports, hotels and conference rooms in the big city world:

Autumn walk over Schauenburg

It was suddenly quite cold for a while, but now the weather wormed up again and nature is gifting us with a wonderful autumn.

Here is my pictures from an autumn walk over Schauenburg last Sunday afternoon:

Autumn Walk over Schauenburg

Full Moon Fire

I often celebrate the full moon by spending a couple of hours on a nearby hill overlooking Basel, enjoying nature, space, a big view, the sky, wind, sunset, moonrise and some hours disconnected from all technology.

Here is the full moon fire photo album from my time out yesterday:

Full Moon Fire

Revit 2016 R2 is Available!

The title says it all: Revit 2016 R2 is available.

R2 is a subscription-only release.

For a list of R2 features, check out what's new in Autodesk Revit Sunrise.

I recently installed the standard Revit 2016 service pack 2.

The service pack 2 includes the following API related enhancements:

Here are the service pack 1 API related enhancements:

They are all obviously included in the R2 release as well.

Back to my RTC conference preparation classes.

Connecting the Desktop and the Cloud

I am still actively working on the CompHound component tracker project for this topic and documenting the work on it extensively on The 3D Web Coder.

CompHound is a cloud-based universal component and asset usage analysis, reporting, bill of materials, visualisation and navigation project.

It connects Revit and other CAD models to a cloud database consisting of a node.js web server, mongo database and Autodesk View and Data API viewer.

In this session, I plan to start out by discussing the simpler and long-completed FireRating in the Cloud sample, consisting of the FireRatingCloud C# .NET REST API client Revit add-in and the fireratingdb node.js mongoDB web server.

Here is the class synopsis: We describe the nitty-gritty programming details to implement a cloud-based system to analyse, visualise and report on universal component and asset usage. The components could be Revit family instances used in BIM or any other kind of assets in any other kind of system. The focus is on the cloud-based database used to manage the component occurrences, either in global or project based coordinate systems. Searches can be made based on geographical location or keywords. Models are visualised using the Autodesk View and Data API, providing support for online viewing and model navigation.

The Building Coder Chatroom

Title: All you ever wanted to ask about the Revit API, The Building Coder, and other non-UI Revit topics.

Synopsis: An open discussion with Jeremy Tammik, The Building Coder and heavy-duty Revit API discussion forum supporter, about anything and everything in Revit that lacks a user interface. DIY, your questions, ideas and sharing experience reign supreme.

I don't know what will happen here – it depends completely on the participants   :-)

I'll take notes and share them with you!

Michael's Getting Started with Revit Macros Material

Back to the class on Revit Macros.

The original presenter is Michael Kilkelly of Space Command, who very kindly provided a fantastic set of class materials.

Michael already presented on this topic in the past, e.g. at Autodesk University 2013.

The materials and recording from his AU 2013 class CM2116 – Revit Customization for Mere Mortals: Save Time (and Your Sanity) with Revit Macros provide a very good starting point. They include the handout document, presentation slides and full video recording:

He is presenting a similar class this year as well, IT11135-L – Getting Started with Revit Macros:

We've all been there – it's an hour until your deadline and your project manager wants to make a single little change. The problem is, this change will take hours of tedious work... hours you simply don't have. However, through the power of the Revit software API and some basic knowledge of computer programming, you can write macros to automate Revit software and save a ton of time on your next project. This lab is designed to get you started automating Revit software using macros written in the Microsoft Visual Basic .NET programming language. Over the course of this lab, we'll cover programming basics and dive into the Revit software API. We'll do this by writing useful macros you can take back to your office and put to good use. At the end of the class you'll have a solid foundation from which to start writing your own macros. Take command of your software and learn to program! This class is geared toward intermediate-to-advanced Revit software users with little or no programming experience.

Here are the RTC handout document and slide deck that Michael created for me, providing full instructions on how to easily and efficiently get started with Revit macros:

For the sake of completeness, the pleasure of Internet search engines and above all Revit API students, here is the full handout text direct and live:

Getting Started with Revit Macros

By Michael Kilkelly, Space Command.

What Are Macros?

Macros are one of the easiest ways to Automate Revit and access the inner workings of the software. Macros do not require any additional software other than Revit and are a great way for beginners to learn programming.

So what exactly is a macro? A macro is a user created command that is coded using Revit’s API or Application Programming Interface. Macros are run directly inside of Revit and are saved in the project file. Other applications, like Microsoft Excel and Word, also have the ability to create macros. Revit macros are different from those in Excel and Word because you cannot record actions directly into a macro. Revit macros must be coded by hand.

Getting Started With Revit Macros

To get started writing your own macros, you should first install the Revit 2016 Software Development Kit or SDK. The SDK contains help files and sample code that will assist you as you learn to program macros. The Revit 2016 SDK be installed from the main page of the Revit installer or it can be downloaded from the Autodesk Developer Network Revit Developer page at

www.autodesk.com/developrevit.

The SDK will install on your hard drive and create the following subfolders and files. Take some time to review the files. The macro samples are particularly useful as you get started creating your own macros.

Revit SDK

Write Your First Macro

Ready to write your first macro? As you’ll see, the process is very easy. Follow the steps below and you’ll be on your way to macro mastery.

1. Open the Macro Manager

Create a new project file. Click the Manage ribbon then click the Macro Manager icon. This will open the Macro Manager dialog.

Manage tab

Macros can reside in a project file or within the Revit application. Macros saved in the project file can be used by any user who opens that file. Macros saved in the application are saved to the user’s Revit configuration. These macros can be used on any model file but only by the user who created the macro.

Macro manager

2. Create a New Module

Macros are organized in modules. When creating a macro in a new project file, you must first create a module. A module is simply a collection of macros. A single project file can contain several modules with each module having its own macros. Module names cannot contain spaces or special characters.

To create a module, click the “Project 1” tab then click the Module button in the “Create” section. In the “Create a New Module” dialog box, title your module “MyFirstModule”. You can write macros in C#, VB.NET, Python or Ruby. For this exercise, choose C# as the module’s language. Click OK to create the module.

Create new module

Once Revit has created the module, SharpDevelop will launch. SharpDevelop is an open-source development environment that is built into Revit for programming macros.

3. Create a New Macro

Now that you have a module, you can create a macro inside the module. Click the Macro button in the “Create” section of the Macro Manager dialog. In the “Create a New Macro” dialog, title your first macro “MyFirstMacro” and set the language to C#. Click OK to create the macro.

Create new macro

4. Write the Macro

Switch over to SharpDevelop. You’ll see the standard C# code that is automatically generated when you create a new module. Toward the bottom you’ll see the starting code for “MyFirstMacro”.

Your first macro is simply going to popup a message box in Revit. It only takes one line of code. After the “public void MyFirstMacro()”, type the following between the brackets:

Macro source code

  public void MyFirstMacro()
  {
    TaskDialog.Show( "My First Macro", "Hello World!" );
  }

Make sure you add a semicolon at the end of the TaskDialog line. This indicates the end of a line to C#.

5. Build the Macro

Once you’ve typed the code, you’re ready to compile or “build” the macro. All macros must be built before Revit can run them. In the SharpDevelop menu bar, select “Build” then “Build Solution”.

Build the macro

SharpDevelop will compile your C# code into the .NET intermediate code. Any errors or warning will show up in the Errors and Warning window located at the bottom of the SharpDevelop interface.

Error list

If you have an error, double-check your code. The code window will list errors by line number so they are easy to pinpoint.

6. Run the Macro

If your macro compiled correctly, go back to Revit and open the Macro Manager dialog (Manage > Macro Manager). You should see “MyFirstMacro” in the list below “MyFirstModule”.

Run macro

Select “MyFirstMacro” from the list then click the Run button. This will execute your macro. You should see the following on your screen:

Macro message box

You did it! You wrote your first Revit macro. To take this further, you can modify the code to report back something more useful. Change your code to the following:

Code to report project path name

Whitespace and line breaks are ignored in C#, so you can spread the statement over several lines for better readability:

  public void MyFirstMacro()
  {
    TaskDialog.Show( "My First Macro",
      "The current model file is "
      + this.Application.ActiveUIDocument.Document.PathName );
  }

The “this.Application.ActiveUIDocument.” object represents the current model file. The “Document” object contains data pertaining to the current file itself. To see the active view in the current project file, change “Document.PathName” to “ActiveView.Name”.

Next Steps

Congratulations! You’re on your way to Revit macro mastery. The next challenge is learning to write code and utilize the Revit API. While teaching all the details of programming is beyond the scope of this workshop, I will highlight some key areas to guide you on your journey.

Choose a Programming Language

In the example above, we used C# to write the macro. C# is just one of four languages you can use to write macros. Since Revit uses the Microsoft .NET framework 4.0, you can write macros in either Python, Ruby, C# or VB.NET. All these languages compile into the same intermediate language so you have full access to Revit’s API from any of the languages.

Below is additional information about the supported language as well as pros and cons to each.

Converting Code from One Language to Another

SharpDevelop can convert code from one language to another. If you find a good Revit code sample written in VB.NET, you can easily convert it to C#.

To convert code, simply create a module and macro using the language of the code sample then, in SharpDevelop, select Project > Convert and choose the language to convert the code into.

Converting language

Note that the conversion process is not always perfect. Sometimes you may find the code converts into a string of gibberish, unfortunately.

Learning the Revit API

As you move beyond your first Revit macro, you’ll need to get familiar with the Revit API. The best way to do that is through the Revit API help file. The help file is your roadmap to learning the API. You can find the help file in the Revit 2016 SDK folder. Open the RevitAPI.chm file and click the “Content” tab. The help file lists all of the namespaces in the Revit API.

A namespace is essentially a hierarchical container for the elements within the API. A good analogy for namespaces is your computer’s folder structure. Each folder at the same level of the directory structure must have a unique name. The folders can contain similarly named files but the path to each file will be unique as the folder names are unique. Namespaces work the same way. There may be elements within the API that are named the same. For example, many elements have a “Geometry” property but namespaces provide a way to accurately identify which geometry you’re specifying. To reference the wall geometry property, you type Autodesk.Revit.DB.Wall.Geometry.

To find more information about a specific element within the API, simply drill down through the namespaces to find the element. For instance, if I want to learn more about the properties of wall objects, I click Autodesk.Revit.DB Namespace > Wall Class > Wall Properties. The help file lists all the properties of wall elements.

Revit API help file RevitAPI.chm

Reading the API help file is not easy. It takes some practice as it is not written in plain English. Rather, it is a description of all the elements within the API. The help file does contain code samples but it not a learning tool. Much like a road map will not teach you to drive a car, the API help file will not teach you to code but it will help you get where you’re going.

Troubleshooting Macros

You will spend a lot of time troubleshooting and debugging your macros. One of the great things about coding is that the feedback is immediate. You write some code, compile it then run it. Your code will either work or it will not. Revit will tell you immediately if it does not work and you will feel a sense of accomplishment when it does work. SharpDevelop provides a number of tools to assist you while troubleshooting your code.

Using Debug.Print and the Output Window

While writing code, it is often useful to have your macro report back information while the macro is running. Writing code is an iterative process and you will need feedback as you develop your macro. SharpDevelop’s output window is useful for understanding what’s going on inside your macro.

To output information to the output window, use the Debug.Print command. Before you can use the command, however, you’ll need to add the Systems.Diagnostics namespace to your macro. You do this by adding “using System.Diagnostics” to the beginning of your macro code.

Systems.Diagnostics namespace

Stepping Through Your Code

When you compile your code and run it, Revit will run through the code sequentially. While writing macros however, it is often useful to step through your code line by line so you can see exactly what is going on. You can step through your code using the Step Into button in the “Macro Manager” dialog.

Step through code

Press the F10 key to step through the next line of code. While you are walking through the code, you can view the Output window to see any output from your Debug.Print lines. You can also view the current values in your variables through the “Local Variables” tab.

Using Break Points

In addition to stepping through your code, you can set specific points where you want the code to stop running so you can check out the Output or Local Variables windows. Clicking on the grey area to the left of the line number row will create a break point. A break point is represented as a red dot. Any line containing a break point will also be highlighted in red. When Revit encounters a break point when running the code, it will stop executing the code. Pressing F10 will step through your code or press F5 to continue running the remainder of the macro.

Break point

Commenting Your Code

One of the most critical practices to follow when writing code is to add comments as you are writing your code. These comments should serve as a reminder for what the code does and why it’s structured in that particular way.

Each language has its own syntax for writing comments. Comments are identified in C# by a double slash (//) at the beginning of the line. SharpDevelop highlights all comments in green.

C# comment

Comments can also be used to block code from running. Say you are testing some alternate approaches to a specific part of the macro. You can “comment out” parts of the code that you do not want to run. If you have three options for the code, comment out two and run the macro with one of the options. Commenting out can also be used to test very specific parts of your macro. If you are getting errors from one section of the macro, comment out everything else, build the macro and step through it. This focused approach will save you a lot of time while troubleshooting.

Exceptions

Face it, your code is not going to be perfect. Even if your code compiles without an error, it can still crash or throw an exception when you run it. This is simply the nature of coding. If you get an error, use the methods listed above to systematically work through your code to identify the problem. This can seem like finding a needle in a haystack when you are first starting out but as you code more and more macros, you will get better at identifying problems in your code.

Macro Sample

Our first macro was useful for illustrating the process for creating a macro but let us take what we just learned and put it to use on a macro that is more useful. The following code deletes unused views in the current model file. If a view is not on a sheet or does not have the “working” prefix, it is deleted. Note this macro does not work with dependent views.

Real-world macro

Next Steps

What else can you do with Revit macros? Pretty much anything you can think of! Good candidates are tasks that are fairly standardized or require lots of user input. Some examples include:

Think about the tasks you do on a regular basis. Which of these do you like the least? Would you like to automate it? Could you write a macro that would do the task for you?

Additional Resources

Want to learn more about writing your own macros? Check out these resources for more information.

Conclusion

Learning to write macros and automate Revit will drastically improve your efficiency. A well-written macro can do more in five minutes than a regular user can accomplish in one hour. Learning to program takes time and patience. Start small and work systematically. You’ll be on your way to macro mastery in no time!