Home
Revit 2013 API Developer Guide - The Building Coder
Contents
1. Look in X Bifold 2 Panel rfa 11 8 2009 10 2 History Bifold 4 Panel rfa 11 8 2009 10 2 E 2 Curtain Wall Db Glass rfa 11 8 2009 10 2 Curtain Wall Sg Glass rfa 11 8 2009 10 2 E E Curtain Wall Store Front Dbl rfa 11 8 2009 10 2 y Double Flush rfa y i ie Bla e Flem Pu B ita ALELA X ed d Ld Pa La E uble Glass 2 rfa donis d di 11 8 2009 102 1 0 gy Double Panel 2 rfa 11 8 2009 10 2 Ea uble Uneven rfa 11 8 2009 10 2 Opening Cased rfa 11 8 2009 10 2 Revit Main y Opening Elliptical Arch rfa 11 8 2009 10 2 hb Overhead Rollina rfa 11 8 2009 10 2 i t Do Double Panel 1 rfa 11 8 2009 10 2 Do Do File name Double Glass 1 rfa Files of type Family rta adsk Worksharing Tools v 71 Audit Detach from Central Create New Local ka Figure 200 Revit Filters dialog In this example Revit Filters the three primary tasks are grouped into columns delineated by the group boxes Filters Categories and Filter Rules Each of these columns contains a top down flow that involves selecting from a collection of items or modifying a control Spacing and Margins The following table taken from the Layout Section of the Microsoft Windows User Experience Guidelines lists the recommended spacing between common Ul elements for 9 pt Segoe UI at 96 dpi For a definition of the difference between dialog units DLU and relative pixels see the Layout Me
2. ee insert T lin Array Ize sme Roues use the Clear method to remove all elements in lineArray lineArray Clear TaskDialt og Show Revit M NITE genou zc panca cav Editing Elements In Revit you can move rotate align delete mirror group and array one element or a set of elements with the Revit Platform API Using the editing functionality in the API is Similar to the commands in the Revit UI Topics tn this section e Moving Elements e Rotating Elements e Aligning Elements e Mirror e Group e Array e Delete Moving Elements The ElementTransformUtils class provides two static methods to move one or more elements from one place to another Table 19 Move Methods Member Description MoveElement Document Elementld XYZ Move an element in the document by a specified vector MoveElements Document ICollection lt Elementid gt XYZ Move several elements by a set of IDs in the document by a specified vector Note When you use the MoveElement or MoveElements methods the following rules apply e The methods cannot move a level based element up or down from the level When the element is level based you cannot change the Z coordinate value However you can place the element at any location in the same level As well some level based elements have an offset instance parameter you can use to move them in the Z direction e For example if you create a new column at the original location 0 O 0
3. appears Additionally if any elements are added to the elements parameter these elements will be highlighted on screen It is a good practice to set the message Whenever Autodesk Revit UI Result Failed or Autodesk Revit UI Result Canceled is returned and the parameter message is not empty A v 00 un u Q O 00 D E Al un c 5 WV a 4 Uv Q c o z k on o E 2 3 c c u 0 H Uv D c o E E Ms oO D O pw pou bei O un 4 mc E c o ayu o0 C 5 EES HE S E Q Oo r3 c EO c fe o Sy 4 ENSE S nv i OP CHPU x S v M Mt Ack 2 S ce pady E 2 E JB EM sa E E 5 Y PU o Ed c po Duo c o T E ij Q X c O Q WY T 5 T a A oR ale E Ma 3 Ns e o S O A A rH OH M vow m H D E y l O 40 nU E u Q a n o 0 T J gt gt cH UE c LL a siu E U c UO U P P oce wo H Y D gt o gt c Q M M YH Uug e oe Hol z m O in c Uy B x ERE y a v r4 N T O Pp E c ucc oca P 5 gt aE D uU LC cm ES OC rd O LL u i amp V Q O o0 Y O Hess I wwe Qu Q 5 el a Uu v Ss 0 axx DY cc gt EJE es 9 rf c T en Ea SHH ocodcuoc DO Es A E 2 so E Bo noc oc oO VU 4 c 5 a n A Ec vou 0 Qr cc 9 c E d l 9 D T eb cc coo u4rn9 5 Q EN 5 m i Z U P P WoO amp q 2 E u 4 e z D OY T mU UE 2 U UO U n al Z EM T i U O a X AH LA SEL HE c O f 9 l oui L oa
4. Keynote DE ns 7557777 aum mE O ERR al N gt i d cdi go Ooo ns SE A A E A A ree 5m OK Cancel Apply Help Figure 178 Concrete Regangular Beam Parameters e Figure 179 Concrete Rectangular Beam Cross Section Length 5 0 O 0 1 2 O 0 1 2 4 T 1 Figure 180 Concrete Rectangular Beam Precast Rectangular Beam m Family Types NE x Name fi 2RB24 O Parameter Vue Formula Construction Start Extension default 0 0 1 2 namas Rename End Extension default Q0 01 2 n Materials and Finishes Beam Material default Structural Angle default Dimensions Length default 10 0 1 2 Start Ext End Extension Calculation default 10 0 Q 1 2 End Exte Figure 182 Precast Rectangular Beam Cross Section length 5 0 Y JS Start Extension Calculation 10 0 End Extension Calculation 10 0 Figure 183 Precast Rectangular Beam Precast L Shaped Beam m Family Types Name i 8LB24 Construction Start Extension default 0 0 1 2 Materials and Finishes Beam Material default Concrete Precast Concrete Normal W Structural Angle default Family Types New Reneme Delete Identity Data Keynote coi rs Type Comments Start Extension Calculation default 10 0 10 0
5. Alternatively the filter results can be returned as an element id iterator Code Region 6 14 Getting the results as an element id iterator view plaincopy to clipboardprint Use a RoomFilter to find all room elements in the document RoomFilter filter new RoomFilter Apply the filter to the elements in the active document FilteredElementCollector collector new FilteredElementCollector document collector WherePasses filter Get results as ElementId iterator FilteredElementIdIterator roomIdItr collector GetElementIdIterator roomIdItr Reset while roomIdItr MoveNext d ET 13 ElementId roomId roomIdItr Current 14 Warn rooms smaller than 50 SF 15 Room room document GetElement roomId as Room 16 if room Area lt 50 0 17 18 String prompt Room is too small id roomId ToString 19 TaskDialog Show Revit prompt 20 break WON aU E YN EA a B bo In some cases it may be useful to test a single element against a given filter rather than getting all elements that pass the filter There are two overloads for ElementFilter PassesFilter that test a given Element or Elementld against the filter returning true if the element passes the filter LINQ Queries In NET the FilteredElementCollector class supports the IEnumerable interface for Elements You can use this class with LINQ queries and operations to process lists of elements Note that because the ElementFilt
6. Elevation 0 0 Angle From Project Morlli Lo True Murlli 30 00 00 East v Figure 125 Point coordinates Note East indicates that the Location is rotated counterclockwise West indicates that the location is rotated clockwise If the Angle value is between 180 and 360 degrees Revit transforms it automatically For example if you select East and type 200 degrees for Angle Revit transforms it to West 160 degrees d x Z Te Angle 0 O 0 A i e Elevation 0 O B X North South East West Y Figure 126 Geographical offset and rotation sketch map The following sample code illustrates how to retrieve the ProjectLocation object Code Region 21 1 Retrieving the ProjectLocation object public void ShowActiveProjectLocationUsage Autodesk Revit DB Document document Get the project location handle Proyect LoOcarion proyecrLlocarlon cecunene Actlverro jocuLoecaraon JF SSO See cdi quis ON SEU IE OIL OUE etico pio eee XS LE EON XYZ Origin new XYZ 0 0 0 Pic eco Eo Sos tor pio Jet llosa Cer Ee Sono Sion Lowe we alin AUS secs b Ore EALO iate EA PETON ENOT Pr e E PO OO Aoi CEStmat Ene prompt Skiing to Show the message Siege joecujoce Cunas joo Jaco ol Aroa tao a Sacco p Va VIEW MO e e ua joo alme DOS eo e SENSE Ao te O sao Ao e Pron Nes os uM E Suse SS AMI M M upon E ces tied met eI promo ous Ve EU x UNIONE ee Sui GirSsecs s TOYX I5 dE T 01
7. Get the Id of the first view ElementId viewId collector FirstElementId CON AU i UN A O Test if the view is valid for element filtering 10 if FilteredElementCollector IsViewValidForElementIteration document viewId 11 T2 FilteredElementCollector viewCollector new FilteredElementCollector document viewId 13 14 Get all FamilyInstance items in the view 15 viewCollector OfClass typeof FamilyInstance 16 ICollection ElementId familyInstanceIds viewCollector ToElementIds 17 18 document Delete familyInstanceIds 19 The GetElementlterator method is used in the following example that iterates through the filtered elements to check the flow state of some pipes Code Region 6 13 Getting the results as an element iterator view plaincopy to clipboardprint FilteredElementCollector collector new FilteredElementCollector document Apply a filter to get all pipes in the document collector OfClass typeof Autodesk Revit DB Plumbing Pipe Get results as an element iterator and look for a pipe with a specific flow state JN NN UN E UN EA 8 FilteredElementIterator elemItr collector GetElementIterator 9 elemItr Reset 10 while elemItr MoveNext 11 12 Pipe pipe elemItr Current as Pipe 13 if pipe FlowState PipeFlowState LaminarState 14 15 TaskDialog Show Revit Model has at least one pipe with Laminar flow state 16 break 17 18
8. Skylight instance if skylight null message Please select one skylight return Result Cancelled J Calculate the height Line line CalculateLineAboveFloor doc skylight Create a model curve to show the distance Plane plane revit Application Application Create NewPlane new XYZ 1 0 0 line get EndPoint 0 SketchPlane sketchPlane doc Create NewSketchPlane plane ModelCurve curve doc Create NewModelCurve line sketchPlane Show a message with the length value TaskDialog Show Distance Distance to floor String Format 0 f2 line Length return Result Succeeded j summary Determines the line segment that connects the skylight to the nearest floor summary returns The line segment lt returns gt private Line CalculateLineAboveFloor Document doc FamilyInstance skylight Find a 3D view to use for the ReferenceIntersector constructor FilteredElementCollector collector new FilteredElementCollector doc Func lt View3D bool gt isNotTemplate v3 gt v3 IsTemplate View3D view3D collector OfClass typeof View3D Cast lt View3D gt First lt View3D gt isNotTemplate Use the center of the skylight bounding box as the start point BoundingBoxXYZ box skylight get BoundingBox view3D XYZ center box Min Add box Max Multiply 0 5 Project in the negative Z direction down to the floor XYZ rayDirection new XYZ 0 0
9. The ElementTransformUtils class provides two additional methods that can be used to determine if one or more elements can be mirrored CanMirrorElement and CanMirrorElements Group The Revit Platform API uses the Creation Document NewGroup method to select an element or multiple elements or groups and then combines them With each instance of a group that you place there is associatively among them For example you create a group with a bed walls and window and then place multiple instances of the group in your project If you modify a wall in one group it changes for all instances of that group This makes modifying your building model much easier because you can change several instances of a group in one operation Code Region 10 9 Creating a Group view plaincopy to clipboardprint Group group null UIDocument uidoc new UIDocument document ElementSet selection uidoc Selection Elements if selection Size gt 0 Group all selected elements group document Create NewGroup uidoc Selection GetElementIds CON dl UE UNE Initially the group has a generic name such as Group 1 It can be modified by changing the name of the group type as follows Code Region 10 10 Naming a Group view plaincopy to clipboardprint 1 Change the default group name to a new name MyGroup 2 group GroupType Name MyGroup There are three types of groups in Revit Model Group Detail Group and Attached Detail Group A
10. 9 10 run BeginsWithRiser true 11 run EndsWithRiser true 12 13 14 The StairsRun class provides access to run properties such as the StairsRunStyle straight winder etc BaseElevation TopElevation and properties about the risers There are also methods in the StairsRun class to access the supports hosted by the run either all or just those on the left or right side of the run boundaries The GetStairsPath method will return the curves representing the stairs path on the run which are projected onto the base level of the stairs The GetFootprintBoundary method returns the run s boundary curves which are also projected onto the stairs base level There are three static methods of the StairsRun class for creating new runs These are covered in the Creating and Editing Stairs section The StairsRunType class represents the type of a StairsRun It contains many properties about the treads and risers of the run as well as other information about the run The following example gets the StairsRunType for the first run in a Stairs element and displays the riser and tread thicknesses along with the type s name Code Region Getting StairsRunType Info view plaincopy to clipboardprint 1 private void GetRunType Stairs stairs 2 NET 3 ICollection lt ElementId gt runIds stairs GetStairsRuns 4 5 ElementId firstRunId runIds First 6 7 StairsRun firstRun stairs Document GetElement firstRunId as StairsRun
11. 9 for int i 0 i mesh NumTriangles i 10 1i 1 123 13 MeshTriangle triangle mesh get Triangle i 14 15 XYZ vertex1 triangle get Vertex 16 17 XYZ vertex2 triangle get Vertex 1 18 19 XYZ vertex3 triangle get Vertex 2 20 21 22 23 y Note that the approximation tolerance used for Revit display purposes is used by the parameterless overload of the Triangulate method used above when constructing the Mesh The overload of Triangulate that takes a double allows a level of detail to be set between 0 coarser and 1 finer Points A point represents a visible coordinate in 3D space These are typically encountered in mass family elements like ReferencePoint The Point class provides read access to its coordinates and an ability to obtain a reference to the point for use as input to other functions PolyLines A polyline is a collection of line segments defined by a set of coordinate points These are typically encountered in imported geometry The PolyLine class offers the ability to read the coordinates e PolyLine NumberOfCoordinates the number of points in the polyline e PolyLine GetCoordinate gets a coordinate by index e PolyLine GetCoordinates gets a collection of all coordinates in the polyline e PolyLine Evaluate given a normalized parameter from O to 1 evaluates an XYZ point along the extents of the entire polyline Solids Faces and Edges A Soli
12. Caten fy ei NE Ee a laa as e denne Tels als E AO cio OCT PEE o jte ct OLD eos ero ILO 6 exo IAE le COOL E bAssimilate false if both transactions are successful assimilate the group if bAssimilate true status trans Croup Assimilate j else SLE CUS wee eue ones lod Ies JE pet gr mnostetus Transactions in Events Modifying the document during an event Events do not automatically open transactions Therefore the document will not be modified during an event unless one of the event s handlers modifies it by making changes inside a transaction If an event handler opens a transaction it is required that it will also close it commit it or roll it back otherwise all 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 DocumentChanged Event The DocumentChanged 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 Handling Options Failure handling options are options for how failures if any
13. Cut Pattern MH m Black EN Black The example above shows Collection Viewer represented as a List Table View and Tree View are also options for displaying the collection items Supported Behaviors Action Description Required 1 Filter This provides options for filtering the list view This can be represented as a No Drop down default criteria must be selected and should include All as an option Check boxes check box ON would refine the list Default set by designer Radio buttons choosing between radio buttons refines the list Default set by designer Once a choice is selected the collection will automatically update based on the selected criteria Controls must follow the MICROSOFT WINDOWS USER EXPERIENCE GUIDELINES 2 Search Box A search box allows users to perform a keyword search on a collection The search box must follow Microsoft Windows User No Experience Guidelines 3 Change viewing Ifthe collection is viewed as list the items can be optionally displayed with small or large icons instead of text No mode 4 Collection A separate UI will be provided to edit rename delete or add items to the collection See Collection Editor No Manager This is only displayed if managing the collection is user editable 5 View the The collection itself can be viewed in the following ways List View Table View Tree View or as a Tree Table Yes collection 6 Show More This button hides shows the additional data associated wi
14. Lines Modal Lines Lines Model Lines Figure 93 ModelEllipse and ModelNurbSpline Creating a ModelCurve The key to creating a ModelCurve is to create the Geometry Curve and SketchPlane where the Curve is located Based on the Geometry Curve type you input the corresponding ModelCurve returned can be downcast to its correct type The following sample illustrates how to create a new model curve ModelLine and ModelArc Code Region 17 2 Creating a new model curve gee aer e ico a ea oa icin ee Autodesk Revit ApplicationServices Application application document Application Create a geometry line in Revit application XOU start E obe mer 200 10 0 0 2405 cnd A men CICA ILO 159 O Line geomLine application Create NewLine startPoint endPoint true Pi Gierexsub e El Geoncery vane db gi nevi ESO bete E lem XYZ endO mew oM XYZ endl mew KALO TO TOI KY pOlLnEeOnCunrve mew LAO UP Arc geomArc application Create NewArc end0 endl pointOnCurve Create a geometry plane in Revit application YOO origin New XA O 10 0 XYZ normal new com ll jee Plane geomPlane application Create NewPlane normal origin Create a sketch plane in current document SketchPlane sketch document Create NewSketchPlane geomPlane Create a ModelLine element using the created geometry line and sketch plane ModelLine line document Create NewModelCurve geomLine sketch as ModelLine Creat
15. The following sample shows how to determine the owner of a connector and what if anything it attaches to along with the connection type Code Region 30 5 Determine what is attached to a connector public void GetElementAtConnector Connector connector Me ovr eie dg mejo Site Xon cetus Milo Ss Sic Sill if null mepSystem string message Connector is owned by connector Owner Name if connector IsConnected true Conn e eror Selene oir eones MISC ConnectoroetItLerator CSi Connector Se s Eos weuselbie eese OS t 5 while csi MoveNext onmes cisci Cel a mec e om reso Ic null l connecied a olny ue ce GRISE GS if connected ConnectorType ConnectorType EndConn connected ConnectorType ConnectorType CurveConn connected ConnectorType ConnectorType PhysicalConn Message AE ie os e ome re c a sCOnMeecred Omer Name message t mme ommecl tony pelis connected Conmecior er else Message Micol SI eee Cece e sua Laia e MessageBox Show message Revit The following dialog box is the result of running this code example on the connector from a piece of mechanical equipment Connector is owned by Size 4 10 inch Inlet Connector is connected to Radius Elbows Tees Connection type is End Conn Figure 168 Connector Information Family Creation When creating mechanical equipment in a Revit family document you will need to add connectors to allow the equip
16. e Binding Definition File The DefinitionFile object represents a shared parameter file The definition file is a common text file Do not edit the definition file directly instead edit it using the UI or the API Definition File Format The shared parameter definition file is a text file txt with two blocks GROUP and PARAM Code Region 22 1 Parameter definition file example This is a Revit shared parameter file Do not edit manually MERO ALD NAME GROUP i MyGroup GROUP 2 AnotherGroup PARAM GUID NAME DATATYPE DATACATEGORY GROUE VISITE EE PARAM 4p mand MOSS Oe T Eoaea TM Par an E L 1 PARAM Sls eos qom ao OL Gacseceoorao Price INTEGER m PARAM 05569bb2 9488 4be4 ae21 b065f93f dde areaTags FAMILII e d SAO e The GROUP block contains group entries that associate every parameter definition with a group The following fields appear in the GROUP block o ID Uniquely identifies the group and associates the parameter definition with a group o Name The group name displayed in the UI Edit Shared Parameters Shared 3arameter file D SEivil amp pishdyParameters Est Parameler group MyGroup v Paramelers MyParameter M Parameters E E Properties Move Delete Groups iT Rename Delete Cencel Hels Figure 130 Edit Shared Parameters Group and Parameter e The PARAM block contains parameter definitions The following fields appear in the PARAM bloc
17. ref ar ar Append ref ar loftForm document FamilyCreate NewLoftForm true ref ar ar CA O Figure 57 Resulting loft form Form modification Once created forms can be modified by changing a sub element i e a face edge curve or vertex of the form or an entire profile The methods to modify a form include e AddEdge e AddProfile e DeleteProfile e DeleteSubElement e MoveProfile e MoveSubElement e RotateProfile e RotateSubElement e ScaleSubElement Additionally you can modify a form by adding an edge or a profile which can then be modified using the methods listed above The following example moves the first profile curve of the given form by a specified offset The corresponding figure shows the result of applying this code to the loft form from the previous example Code Region 14 5 Moving a profile public void Meoverorn Hern term Die Prot MCC esum Eee qe cote aie Ode PEO E ai c 0 ions pror iloTade 0 mos tale Geese oia Sly if form CanManipulateProfile profilelndex IS NOA AS 0 s form MoveProfile profilelndex offset Figure 58 Modified loft form The next sample demonstrates how to move a single vertex of a given form The corresponding figure demonstrate the effect of this code on the previous extrusion form example Code Region 14 6 Moving a sub element public void MoveSubElement Form form abd rome Prori le ount gt 10 mt prorilelndex 0 get first p
18. 1 68 ElementClassFilter filter new ElementClassFilter typeof Floor 69 70 Referencelntersector reflntersector new ReferenceIntersector filter FindReferenceTarget Face view3D 71 ReferenceWithContext referenceWithContext refIntersector FindNearest center rayDirection 727 734 Reference reference referenceWithContext GetReference 74 XYZ intersection reference GlobalPoint 754 76 Create line segment from the start point and intersection point Jd Line result doc Application Create NewLineBound center intersection 78 return result 79 80 Ray bouncing analysis The references returned by Referencelntersector Find include the intersection point on the geometry Knowing the intersection point on the face the face s material and the ray direction allows an application to analyze reflection and refraction within the building The following image demonstrates the use of the intersection point to reflect rays intersected by model elements model curves were added to represent the path of each ray ES Ray TraceBounce This sample shows how to find intersection between ray and face and create connecting lines by Revit API method FindHeferencesByDirectian Start Paint Direction im Le Level 2 Views rations Buildin East North South West nds dules Quantitie ts all lies Ips t Links Example Rays bouncing off intersected faces Find intersections collisio
19. 1 Phase Demolished 1 Comment Baca Extension Distance 0 0 Dase Constraint Level 1 Tigi is AL ariel False Location Line U Top Extension Diskance 0 0 Relaled Lu Mass False marl Base is Attached False Volume 650 00 CF Room Bounding True Structural Usage 0 Top offset 0 0 Unconnected Helght 20 O Figure 26 Get wall parameters result Noteln Revit some parameters have values in the drop down list in the Element Properties dialog box You can get the numeric values corresponding to the enumerated type for the Parameter using the Revit Platform API but you cannot get the string representation for the values using the Parameter AsValueString method Definition The Definition object describes the data type name and other Parameter details There are two kinds of definition objects derived from this object e InternalDefinition represents all kinds of definitions existing entirely in the Revit database e ExternalDefinition represents definitions stored on disk in a shared parameter file You should write the code to use the Definition base class so that the code is applicable to both internal and external parameter Definitions The following code sample shows how to find a specific parameter using the definition type Code Region 8 2 Finding a parameter based on definition type Find parameter using the Parameter s definition type public Parameter FindParameter Element
20. Code Region Reading point cloud points by pointer V IOWAI N AImm nmm T nm nHhnarnanrin t VIEW piaincopy to ciipboaraprint Filter will match 1 8 of the overall point cloud Use the bounding box filter coordinates are in the coordinates of the model BoundingBoxXYZ boundingBox pointCloudInstance get BoundingBox null List Plane planes new List Plane XYZ midpoint boundingBox Min boundingBox Max 2 0 X boundaries planes Add app Create NewPlane XYZ BasisX boundingBox Min 9 planes Add app Create NewPlane XYZ BasisX midpoint CON AU I Uu PN A 11 Y boundaries 12 planes Add app Create NewPlane XYZ BasisY boundingBox Min 13 planes Add app Create NewPlane XYZ BasisY midpoint 15 Z boundaries 16 planes Add app Create NewPlane XYZ BasisZ boundingBox Min 17 planes Add app Create NewPlane XYZ BasisZ midpoint 19 Create filter 20 PointCloudFilter filter PointCloudFilterFactory CreateMultiPlaneFilter planes 21 pointCloudInstance FilterAction SelectionFilterAction Highlight This is the result when the sample above is run on the point cloud from the previous example Figure Point cloud with selection filter The Selection PickBox method which invokes a general purpose two click editor that lets the user to specify a rectagular area on the screen can be used in conjuction with a PointCloudFilter by using the resulting PickedBox to generate the planar
21. E 23 019 32 Figure 72 SpotCoordinates and SpotElevations The SpotDimension Location can be downcast to LocationPoint so that the point coordinate that the spot dimension points to is available from the LocationPoint Point property e SpotDimensions have no dimension curve so their Curve property always returns null e The SpotDimension References property returns one Reference representing the point or the edge referenced by the spot dimension e To control the text and tag display style modify the SpotDimension and SpotDimensionType Parameters Comparison The following table compares different kinds of dimensions and constraints in the API Table 36 Dimension Category Comparison Dimension or Constraint API Class BuiltInCategory Curve Reference View Location Permanent Dimension linear dimension Dimension OST Dimensions A Line gt 2 Specific view null radial dimension Null 1 diameter dimension Null 1 angular dimension AnArc 2 arc length dimension AnArc 2 Dimension Constraint linear dimension constraint OST Constraints An Arc 2 angular dimension AnArc 2 Equality Constraint A Line 2 3 Create and Delete The NewDimension method is available in the Creation Document class This method can create a linear dimension only Code Region 16 2 NewDimension view plaincopy to clipboardprint i public Dimension NewDimension View view Line line ReferenceArray references view plaincopy to clipboardprint 1 public Dim
22. End Extension Calculation 10 0 Figure 190 Precast Single Tee Precast Inverted Tee Family Types x Name Construction Start Extension default 0 0 1 2 Rename a RS 0 01 2 ANNA DE NES AVEO ERVIN ESE LEN ES EURO RECA ER E ALIEN ALOE ENEE LC EOE EO RTA ET Delete Materials and Finishes Beam Material default Structural Angle default Remove Identity Data Assembly Code B10 Start Extension Calculation default 10 O 10 0 1 2 Start Ext End Extension Calculation default 10 O 10 01 2 End Exte Y e ne x een mm re Figure 191 Precast I nverted Tee Properties b z o Figure 192 Precast I nverted Tee Cross Section Length 5 0 Start Extension Calculation 10 0 End Extension Calculation 10 0 Figure 193 Precast I nverted Tee Precast Double Tee Family Types E x Name FEET Construction 0 0 1 2 Rename Start Extension default End Extension default Materials and Finishes Beam Material default Structural Angle default Dimensions Concrete Precast Concrete Normal W Parameters Add A Modify DOT O GA pneu oct TI ee es es iu Wigs 334 E Identity Data Assembly
23. Material found 20 Note To run the sample code make sure the material name exists in your document All material names for the current document are located under the Manage tab Project Settings panel Materials Creating Materials There are two ways to create a new Material object in the API e Duplicate an existing Material e Add a new Material When using the Duplicate method the returned Material object is the same type as the original Code Region 19 6 Duplicating a material view plaincopy to clipboardprint 1 private bool DuplicateMaterial Material material 2 1 3 bool duplicated false 4 try to duplicate a new instance of Material class using duplicate method 5 make sure the name of new material is unique in MaterailSet 6 string newName new material Name 7 Material myMaterial material Duplicate newName 8 if null myMaterial 9 10 TaskDialog Show Revit Failed to duplicate a material 11 12 else 13 1 14 duplicated true 15 16 17 return duplicated 18 Use the static method Material Create to add a new Material directly No matter how it is applied it is necessary to specify a unique name for the material and any assets belonging to the material The unique name is the Material object key Code Region 19 7 Adding a new Material view plaincopy to clipboardprint Create the material ElementId materialld Material Create document M
24. The API also offers an interface to subdivide parts PartUtils DivideParts accepts as input a collection of part ids a collection of intersecting element ids which can be layers and grids and a collection of curves The routine uses the intersecting elements and curves as boundaries from which to divide and generate new parts The GetAssociatedParts method can be called to find some or all of the parts associated with an element or use HasAssociatedParts to determine if an element has parts You can delete parts through the API either by deleting the individual part elements or by deleting the PartMaker associated to the parts which will delete all parts generated by this PartMaker after the next regeneration Parts can be manipulated in the Revit API much the same as they can in the Revit user interface For example the outer boundaries of parts may be offset with PartUtils SetFaceOffset The following example offsets all the faces of a part that can be offset Code Region Offset Faces of a Part Part part doc GetElement uidoc Selection PickObject ObjectType Element as Part Autodesk Revit DB GeometryElement geomElem part get Geometry newOptions foreach GeometryObject geomObject in geomElem if geomObjectisSolid Solidsolid geomObject as Solid FaceArray faceArray solid Faces foreach FacefaceinfaceArray if part CanOffsetFace face part SetFaceOffset face 1 Before and Afte
25. The Document class contains the LoadFamily and LoadFamilySymbol methods e LoadFamily loads an entire family and all of its types or symbols into the project e LoadFamilySymbol loads only the specified family symbol from a family file into the project NoteTo improve the performance of your application and reduce memory usage if possible load specific FamilySymbols instead of entire Family objects e The family file path is retrieved using the Options Application object GetLibraryPaths method e The Options Application object is retrieved using the Application object Options property e n LoadFamilySymbol the input argument Name is the same string value returned by the FamilySymbol object Name property For more information refer to Code Samples Categories The FamilyBase FamilyCategory property indicates the category of the Family such as Columns Furniture Structural Framing or Windows Familyl nstances Examples of categories of FamilyInstance objects in Revit are Beams Braces Columns Furniture Massing and so on The FamilyInstance object provides more detailed properties so that the family instance type and appearance in the project can be changed Location Related Properties Location related properties show the physical and geometric characteristics of FamilyInstance objects such as orientation rotation and location Orientation The face orientation or hand orientation can be changed for some FamilyInstance obje
26. but you may use sub transactions as required Although it can be used to also update data outside of the document such changes will not become part of the original transaction and will not be subject to undo or redo when the original transaction is undone or redone If you do use this method to modify data outside of the document you should also subscribe to the DocumentChanged event to update your data when the original transaction is undone or redone Scope of Changes The Execute method has an UpdaterData parameter that provides all necessary data needed to perform the update including the document and information about the changes that triggered the update Three basic methods GetAddedElementlds GetDeletedElementids and GetModifiedElementlds identify the elements that triggered the update The Updater can also check specifically if a particular change triggered the update by using the IsChangeTriggered method Forbidden and Cautionary Changes The following methods may not be called while executing an Updater because they introduce cross references between elements This can result in document corruption when these changes are combined with workset operations A ForbiddenForDynamicUpdateException will be thrown when an updater attempts to call any of these methods e Autodesk Revit DB ViewSheet AddView e Autodesk Revit DB Document LoadFamily Autodesk Revit DB Document Autodesk Revit DB IFamilyLoadOptions e Autodesk Rev
27. e Hello HelloB e Hello HelloC e Hello HelloRed e Hello HelloBlue e Hello HelloGreen Code Region Ribbon panel and controls view plaincopy to clipboardprint 1 public Result OnStartup Autodesk Revit UI UIControlledApplication app 2 3 RibbonPanel panel app CreateRibbonPanel New Ribbon Panel 4 D AddRadioGroup panel 6 panel AddSeparator Za AddPushButton panel 8 AddSplitButton panel 9 AddStackedButtons panel 10 AddSlideOut panel 1i 12 return Result Succeeded 13 Ribbon Panel Custom ribbon panels can be added to the Add Ins tab the default or the Analyze tab or they can be added to a new custom ribbon tab There are various types of ribbon controls that can be added to ribbon panels which are discussed in more detail in the next section All ribbon controls have some common properties and functionality Ribbon Control Classes Each ribbon control has two classes associated with it one derived from RibbonltemData that is used to create the control i e SplitButtonData and add it to a ribbon panel and one derived from Ribbonltem i e SplitButton which represents the item after it is added to a panel The properties available from RibbonltemData and the derived classes are also available from Ribbonltem and the corresponding derived classes These properties can be set prior to adding the control to the panel or can be set using the Ribbonltem class after it has been added to t
28. e The user defined size should be remembered within and between application sessions e Elements in the dialog should maintain alignment during resizing based on the quadrant they are described in the following table Home Quadrant Alignment 1 Left and Top 2 Right and Top 3 Left and Bottom 4 Right and Bottom Multiple If control is located in multiple quadrants it should anchor to quadrant 1 and or 3 to the left and expand contract to the right to maintain alignments View Templates 4 ues Properties all x View Scale 178 1 0 f Tem Display Model Normal Ed Detail Level Coarse El V G Overrides Model s Edit E V G Overrides Annotati Edit vi V G Overrices Import Edit 4 Architectural Plan Architectural Presentation 3D Architectural Presentation Elevation Architectural Reflected Ceiling Plan Architectural Section pe ie cad ete ee 3 Export to Civil Engineering V G Overrices Filters Edit e Site Plan Visual Style Hidden Lire te Site Section mr lt Structural Framing Elevation Graphic Display Option Edit Structural Framing Plan Far Clipping F Siir Section Phase Filter Show All i Discipline Architectural v Figure 204 Four square grid applied to Revit View Templates dialog to demonstrate how it should be resized In this example the list box is located in all four quadrants So it is anchored to the
29. method to create new floor and ceiling plan views Use the static ViewPlan CreateAreaPlan method to create a new area plan view Code Region Creating Plan Views view plaincopy to clipboardprint 1 public static ViewPlan ViewPlan Create Document document ElementId viewFamilyTypeId ElementId levelld 2 3 public static ViewPlan ViewPlan CreateAreaPlan Document document ElementId areaSchemeld ElementId levelld The viewFamilyTypeld parameter in ViewPlan Create needs to be a FloorPlan CeilingPlan AreaPlan or StructuralPlan ViewType The levelld parameter represents the Id of the level element in the project to which the plan view is associated The following code creates a floor plan and a ceiling plan based on a certain level Code Region Creating a floor plan and ceiling plan view plaincopy to clipboardprint Find a floor plan view type IEnumerable ViewFamilyType viewFamilyTypes from elem in new FilteredElementCollector document OfClass typeof ViewFamilyType let type elem as ViewFamilyType where type ViewFamily ViewFamily FloorPlan select type Create a Level and a Floor Plan based on it double elevation 10 0 9 Level level1 document Create NewLevel elevation 10 ViewPlan floorView ViewPlan Create document viewFamilyTypes First Id level1 Id CON dl UE unn A 12 Create another Level and a Ceiling Plan based on it 13 Find a ceiling plan view type 14 viewFamilyTypes fro
30. thebuildingcoder typepad com http discussion autodesk com Select Autodesk Revit Architecture Then Select Autodesk Revit API http forums augi com forumdisplay php f 93 http discussion autodesk com index2 jspa categorylD 27 http discussion autodesk com index2 jspa categoryID 104 http discussion autodesk com index2 jspa categoryID 114 Installation The Revit Platform API is installed with Revit Architecture Revit Structure and Revit MEP Any NET based application will reference the RevitAPI dll and the RevitAPIUI dll located in the Revit Program directory The RevitAPI dll contains methods used to access Revit s application documents elements and parameters at the database level The RevitAPlUl dll contains the interfaces related to manipulation and customization of the Revit user interface Supported Programming Languages The Revit Platform API is fully accessible by any language compatible with the Microsoft NET Framework 4 0 such as Visual Basic NET or Visual CH User Manual This document is part of the Revit SDK It provides an introduction to implementing Revit add in applications using the Revit Platform API Before creating a Revit Platform API add in application read through the manual and try the sample code If you already have some experience with the Revit Platform API you may just want to review the Notes and Troubleshooting sections Introduction to the Revit Platform API The first two chapters pre
31. view GetWorksetVisibility worksetId 5 6 and set it to Hidden if it is not hidden yet 7 if visibility WorksetVisibility Hidden 8 9 view SetWorksetVisibility worksetId WorksetVisibility Hidden 10 1l 12 Get the workset s default visibility 13 WorksetDefaultVisibilitySettings defaultVisibility WorksetDefaultVisibilitySettings GetWorksetDefaultVisibilitySettings doc 14 15 and making sure it is set to false 16 if true defaultVisibility IsWorksetVisible worksetId 175 18 defaultVisibility SetWorksetVisibility worksetId false 19 20 In addition to getting and setting information about the workset visibility the View class also provides methods to access information on the worksharing display mode and settings The WorksharingDisplayMode enumeration indicates which mode a view is in if any Member Name Description Off No active worksharing display mode CheckoutStatus The view is displaying the checkout status of elements Owners The view is displaying the specific owners of elements ModelUpdates The view is displaying model updates Worksets The view is displaying which workset each element is assigned to Code Region Worksharing Display Mode view plaincopy to clipboardprint 1 public void GetWorksharingDisplayMode View view 2 3 Get and Set worksharingDisplayMode of a given view 4 WorksharingDisplayMode displayMode view GetWorksharingDisplayMode 5
32. 1 9 C NExternalCommands dll Revit Test Command1 10 PushButtonData button2 newPushButtonData Button2 My Button 2 11 C ExternalCommands dll Revit Test Command2 12 13 Create a ribbon panel 14 RibbonPanel m_projectPanel application CreateRibbonPanel tabName This Panel Name 15 Add the buttons to the panel 16 List RibbonItem projectButtons newList RibbonItem 17 projectButtons AddRange m_projectPanel AddStackedItems button1 button2 AMET 19 returnResult Succeeded 20 Create a New Ribbon Panel and Controls The following image shows a ribbon panel on the Add Ins tab using various ribbon panel controls The following sections describe these controls in more detail and provide code samples for creating each portion of the ribbon Enter a comment Track HelloWorld Option One A Option A Tools Changes N External Tools New Ribbon Panel Figure 14 New ribbon panel and controls The following code outlines the steps taken to create the ribbon panel pictured above Each of the functions called in this sample is provided in subsequent samples later in this section Those samples assume that there is an assembly located at D Sample HelloWorld bin Debug Hello dll which contains the External Command Types e Hello HelloButton e Hello HelloOne e Hello HelloTwo e Hello HelloThree e Hello HelloA
33. 2 IList lt Curve gt pathCurves new List Curve 13 XYZ pnt1 new XYZ 0 0 0 14 XYZ pnt2 new XYZ 15 0 0 15 XYZ pnt3 new XYZ 0 10 0 16 XYZ pnt4 new XYZ 15 10 0 175 18 boundaries 19 bdryCurves Add Line get Bound pnt1 pnt2 20 bdryCurves Add Line get Bound pnt3 pnt4 21 25 riser curves 23 const int riserNum 20 24 for int ii 0 ii lt riserNum ii 25 26 XYZ endo pnt1 pnt2 ii double riserNum 27 XYZ endi pnt3 pnt4 ii double riserNum 28 XYZ end2 new XYZ end1 X 10 0 29 riserCurves Add Line get Bound end0 end2 30 3L 525 stairs path curves 33 XYZ pathEndO pnt1 pnt3 2 0 34 XYZ pathEnd1 pnt2 pnt4 2 0 35 pathCurves Add Line get Bound pathEnd0 pathEnd1 36 37 StairsRun newRun1 StairsRun CreateSketchedRun document newStairsId levelBottom Elevation bdryCurves riserCurves pathCurves 38 39 Add a straight run 40 Line locationLine Line get_Bound new XYZ 20 5 newRun1 TopElevation new XYZ 35 5 newRun1 TopElevation 41 StairsRun newRun2 StairsRun CreateStraightRun document newStairsId locationLine StairsRunJustification Center 42 newRun2 ActualRunWidth 10 43 44 Add a landing between the runs 45 CurveLoop landingLoop new CurveLoop 46 XYZ p1 new XYZ 15 10 0 47 XYZ p2 new XYZ 20 10 0 48 XYZ p3 new XYZ 20 10 0 49 XYZ p4
34. 29 0905 9 lt FullClassName gt HelloWorld Classl lt FullClassName gt lex d lb onieussdiels I ede Nendor ADS emcorie lt VendorDescription gt Autodesk www autodesk com lt VendorDescription gt eras RevitAddIns 3 Savethe file as HelloWorld addin and put it in the following location o For Windows XP C Documents and Settings All Users Application Data Autodesk Revit Addins 2012 o For Vista Windows 7 C ProgramData Autodesk Revit Addins 2012 o If your application assembly dll is on a network share instead of your local hard drive you must modify Revit exe config to allow NET assemblies outside your local machine to be loaded In the runtime node in Revit exe config add the element lt loadFromRemoteSources enabled true gt as shown below o lt runtime gt lt generatePublisherEvidence enabled false gt O loade NE MOto Sour a en bl ed eru S Une Refer to Add in Integration for more details using manifest files Debug the Add in Running a program in Debug mode uses breakpoints to pause the program so that you can examine the state of variables and objects If there is an error you can check the variables as the program runs to deduce why the value is not what you might expect 1 Inthe Solution Explorer window right click the HelloWorld project to display a context menu 2 From the context menu click Properties The Properties window appears 3 Click the Debug tab 4 Under the Start Action
35. 48 ComboBoxMemberData cboxMemData new ComboBoxMemberData One Option 1 49 cboxMemData Image 50 new BitmapImage new Uri D Sample HelloWorld bin Debug One bmp 51 cboxMemData GroupName Numbers 52 cBox AddItem cboxMemData 53 ComboBoxMemberData cboxMemData2 new ComboBoxMemberData Two Option 2 54 cboxMemData2 Image 55 new BitmapImage new Uri Q D NSampleNMHelloWorldNbinNDebugNTwo bmp 56 cboxMemData2 GroupName Numbers 57 cBox AddItem cboxMemData2 58 ComboBoxMemberData cboxMemData3 new ComboBoxMemberData Three Option 3 59 cboxMemData3 Image 60 new BitmapImage new Uri Q D NSampleMHelloWorldNbinNDebugNThree bmp 61 cboxMemData3 GroupName Numbers 62 cBox AddItem cboxMemData3 63 64 les y Slide out panel Use the RibbonPanel AddSlideOut method to add a slide out to the bottom of the ribbon panel When a slide out is added an arrow is shown on the bottom of the panel which when clicked will display the slide out After calling AddSlideOut subsequent calls to add new items to the panel will be added to the slide out so the slide out must be added after all other controls have been added to the ribbon panel P on E r a S Enter a comment L HelloWorld Option Two A Option A Button 1 Button 2 New Ribbon Panel Figure 18 Slide out The following example produces the slide out shown above Code Region TextBox EnterPressed
36. 7 XYZ xVec 8 XYZ yVec 9 view plaincopy to clipboardprint Creates a new instance of a Rebar element within the project The instance will have the default is publee statie kebar Rebar Crea terroncurvesmnashapar shape parameters from the RebarShape All curves must belong to the plane defined by the normal DE Document doc and origin 35 RebarShape rebarShape 4 RebarBarType rebarType 5 RebarHookType startHook 6 RebarHookType endHook 75 Element host 8 XYZ norm 9 IList lt Curve gt curves 10 RebarHookOrientation startHookOrient 11 RebarHookOrientation endHookOrient DE The first version creates rebar from an array of curves describing the rebar while the second creates a Rebar object based on a RebarShape and position The third version creates rebar from an array of curves and based on a RebarShape When using the CreateFromCurves or CreateFromCurvesAndShape method the parameters RebarBarType and RebarHookType are available in the RebarBarTypes and RebarHookTypes properties of the Document The following code illustrates how to create Rebar with a specific layout Code Region 29 8 Creating rebar with a specific layout view plaincopy to clipboardprint Rebar CreateRebar Autodesk Revit DB Document document FamilyInstance column RebarBarType barType RebarHookType hookType Define the rebar geometry information Line rebar LocationPoint location column Location as LocationPoint XYZ origin locat
37. 8 if null firstRun 9 10 StairsRunType runType stairs Document GetElement firstRun GetTypeld as StairsRunType 11 Format landing type info for display 12 string info Stairs Run Type runType Name 13 info nRiser Thickness runType RiserThickness 14 info nTread Thickness runType TreadThickness 15 16 TaskDialog Show Revit info 17 18 Landings Landings are represented by the StairsLanding class The following example finds the thickness for each landing of a Stairs object Code Region Working with StairsLanding view plaincopy to clipboardprint 1 private void GetStairLandings Stairs stairs 2 3 ICollection lt ElementId gt landingIds stairs GetStairsLandings 4 string info Number of landings landingIds Count 5 6 int landingIndex 0 7 foreach ElementId landingId in landinglds 8 1 J landingIndex To StairsLanding landing stairs Document GetElement landingId as StairsLanding 11 if null landing 12 13 info nThickness of Landing landingIndex landing Thickness 14 15 16 17 TaskDialog Show Revit info 18 Similar to StairsRun StairsLanding has a GetStairsPath method which returns the curves representing the stairs path on the landing projected onto the base level of the stairs and a GetFootprintBoundary method which returns the landing s boundary curves also projected onto the stairs base level Also simil
38. Add annotation symbol m ct Figure 76 Annotation Symbol with two leaders Create and Delete The annotation symbol creation method is available in the Creation Document class Code Region 16 6 NewAnnotationSymbol public AnnotationSymbol NewAnnotationSymbol XYZ location AnnotationSymbolType annotationSymbolType View specView The annotation symbol can be deleted using the Document Delete method Add and Remove Leader Add and remove leaders using the addLeader and removeLeader methods Code Region 16 7 Using addLeader and removeLeader public void AddAndRemoveLeaders AnnotationSymbol symbol int leaderSize symbol Leaders Size string message Number of leaders in Annotation Symbol before add leaderSize symbol addLeader leaderSize symbol Leaders Size Message 1 9 mNumber ot leaders sateen add esdesssze symbol removeLeader leaderSize symbol Leaders Size message nNumber of leaders after remove leaderSize TaskDialog Show Revit message Geometry The Autodesk Revit DB namespace contains many classes related to geometry and graphic related types used to describe the graphical representation in the API The geometry related classes include GeometryObject class Includes classes derived from the GeometryObject class Geometry Helper classes Includes classes derived from the APIObject class and value types Geometry Utility classes Includes classes to create
39. Adding fields to a schedule view plaincopy to clipboardprint 1 lt summary gt 2 Add fields to view schedule 3 lt summary gt 4 lt param name schedules gt List of view schedule lt param gt 5 public void AddFieldToSchedule List lt ViewSchedule gt schedules 6 rf IList SchedulableField schedulableFields null 8 9 foreach ViewSchedule vs in schedules 10 11 Get all schedulable fields from view schedule definition 12 schedulableFields vs Definition GetSchedulableFields 13 14 foreach SchedulableField sf in schedulableFields 15 16 bool fieldAlreadyAdded false 17 Get all schedule field ids 18 IList ScheduleFieldId ids vs Definition GetFieldOrder 19 foreach ScheduleFieldId id in ids 20 Za If the GetSchedulableField method of gotten schedule field returns same schedulable field 2 it means the field is already added to the view schedule 234 if vs Definition GetField id GetSchedulableField sf 24 25 fieldAlreadyAdded true 26 break 27 28 294 30 If schedulable field doesn t exist in view schedule add it 31 if fieldAlreadyAdded false 32 1 33 vs Definition AddField sf 34 25 36 37 The ScheduleField class represents a single field in a ScheduleDefinition s list of fields Each non hidden field becomes a column in the schedule Most commonly a field represents an instance o
40. Form form EE Bu cover surface with OctagonRotate tile pattern 4 TilePatterns patterns document Settings TilePatterns 5 DividedSurfaceData dsData form GetDividedSurfaceData 6 if dsData null Ta 8 foreach Reference r in dsData GetReferencesWithDividedSurfaces 9 10 DividedSurface ds dsData GetDividedSurfaceForReference r 11 ds ChangeTypeId patterns GetTilePattern TilePatternsBuiltIn OctagonRotate Id T2 13 14 Figure 61 Tile pattern applied to divided surface In addition to applying built in tile patterns to a divided surface you can create your own massing panel families using the Curtain Panel Pattern Based rft template These panel families can then be loaded into massing families and applied to divided surfaces using the DividedSurface ChangeTypeld method The following properties of Family are specific to curtain panel families e IsCurtainPanelFamily e CurtainPanelHorizontalSpacing horizontal spacing of driving mesh e CurtainPanelVerticalSpacing vertical spacing of driving mesh e CurtainPanelTilePattern choice of tile pattern The following example demonstrates how to edit a massing panel family which can then be applied to a form in a conceptual mass document To run this example first create a new family document using the Curtain Panel Pattern Based rft template Code Region 14 9 Editing a curtain panel family view plaincopy to clipboardprint 1 Fam
41. In the example below the resulting family document will display the text Hello World with a line under it When the family is loaded into a Revit project document and an instance is placed in plan view only the line will be visible In 3D view both the line and text will be displayed unless the Detail Level is set to Course in which case the line GenericForm which is the base class for form classes such as Sweep and Extrusion SymbolicCurve ModelText CurveByPoints ModelCurve ReferencePoint Importinstance will disappear Code Region 13 10 Setting family element visibility public void CreateAndSetVisibility Autodesk Revit DB Document familyDocument create a new ModelCurve in the family document KV a pO j New xi Ll 1 30 AYA pl new xl 1 0 Line linel familyDocument Application Create NewLineBound pO pl ModelCurve modelCurvel familyDocument FamilyCreate NewModelCurve linel create a new ModelText along ModelCurve line SketchPlane sketchPlane SketchPlane ModelText text familyDocument FamilyCreate NewModelText Hello World null Sket onr lane PO Aut cis Revit Iesu cm us ect enis c lee 1 See wa Silom ley ir Oi edo FamilyElementVisibility textVisibility new FamilyElementVisibility FamilyElementVisibilityType Model lex bes sre Tien Ls Suo RE ODIETUID OTO EXOXENE OMIT C CE ELS eS Peres el Vals o era sia oa halen 0 Sex absolu For Lime FamilyElementVisibility cu
42. In this case the Host property returns a wall Element in which the window or the door is located See the following picture Figure 46 Doors and windows hosted in a wall HostFace The HostFace property gets the reference to the host face of the family instance or if the instance is placed on a work plane the reference to the geometry face underlying the work plane This property will return a null reference if the work plane is not referencing other geometry or if the instance is not hosted on a face or work plane Subcomponent and Supercomponent The FamilyInstance SubComponents property returns the set of family instances loaded into that family When an instance of Table Dining Round w Chairs rfa is placed in a project the set of chairs are returned by the SubComponent property The SuperComponent property returns the family instance s parent component In Table Dining Round w Chairs rfa the family instance supercomponent for each nested chair is the instance of Table Dining Round w Chairs rfa Code Region 12 1 Getting SubComponents and SuperComponent from FamilyInstance view plaincopy to clipboardprint 1 public void GetSubAndSuperComponents FamilyInstance familyInstance 2 3 ICollection ElementId subElemSet familyInstance GetSubComponentIds Alc if subElemSet null 5 6 string subElems 7 foreach Autodesk Revit DB ElementId ee in subElemSet 8 9 FamilyInstance f familyInstance Do
43. MakeLine document ptA ptB INE elie NEO MO Ie LS Une ve y Come Cig C ue we a y 1 iene eS ion Torm direction ME OCEAN gt TO Xe 0 rs SO eod quus ombesm Gecumenk bamilyCreare Newtext us Lonrorm ecue mE ctecr Gdirecrien PETC UNE SOE IOUS db Ona le ONE ML public ModelCurve MakeLine Document doc XYZ ptA XYZ ptB Autodesk Revit ApplicationServices Application app doc Application Esc ccu cese Me spol mrs Line line app Create NewLine ptA ptB true ASE one JA Cassis OTIS if norm Length 0 morm XMZ Basisz kilene UMS elo o Cres Te Net Lemme iver TN SketchPlane skplane doc FamilyCreate NewSketchPlane plane eere las lem ModelCurve modelcurve doc FamilyCreate NewModelCurve line skplane return model Urve Figure 56 Resulting extrusion form The following example shows how to create loft form using a series of CurveByPoints objects Code Region 14 4 Creating a loft form private Form CreateLoftForm Autodesk Revit Document document Romo eros bills ReferencePointArray rpa new ReferencePointArray ReferenceArrayArray ref ar ar new ReferenceArrayArray ReferenceArray ref ar new ReferenceArray ReferencePoint rp null XY ZZ cmi JL redde m mikes aint le wet i E NS IE OS SIE xyz document Application Create NewXYZ 0 O 0 rp document FamilyCreate NewReferencePoint xyz rpa Append rp nur COCUMehE applet Create New Az bU rp document Fam
44. Point4 true Cite ate El Oeo TEE Jolie au Ie eyes Lancer ein ATA NOG ICG E PZN D ON XYZ normal TWh eee I ler Ones Plane geomPlane application Create NewPlane normal origin um gosse mmc Goa esas Coon SketchPlane sketch document Create NewSketchPlane geomPlane WOM eral hetmereleonentc som key mes cedit dine ae iron SM ecd UNS Tocem JU cem ceo mni tes dci Lon ewe sms cei o document TCio6bpramsaetron start Creadte new curves TransactionStatus Started ARS ARS SK SEC once cu eT peo ueste SketchPlane sketch document Create NewSketchPlane geomPlane Create a ModelLine element using the created geometry line and sketch plane ModelLine linell document Create NewModelCurve geomLinel sketch as ModelLine ModelLine line2 document Create NewModelCurve geomLine2 sketch as ModelLine ModelLine line3 document Create NewModelCurve geomLine3 sketch as ModelLine TaskDialog taskDialog new TaskDialog Revit taskDialog MainContent HO bed Che cer ced Ices sommes one as eras aiei1r Te ud cod A 5 4 Pao kDa oa Cormon eUT TONS herons gt laskDkalloqCommonbumrons Ok Das kDa loo common Burros Cancela Ss kDa icono stos Duis IE Or nU esr TaskDialogResult result taskDialog Show if TaskDialogResult Ok result ias Ae bem OU Dd Ib e Lee else ECU E OXQEn O BE ROI SubTransaction A SubTransaction can be used to enclose a set of model modifying operations Sub transa
45. Revit DB View class is the base class for all view types in the Revit document The Autodesk Revit UI UI View class represents the window view in the Revit user interface In this section you learn how views are generated the types of views supported by Revit the features for each view as well as the functionality available for view windows in the user interface Topics tn this section e Overview e The View3D Class e ViewPlan e ViewDrafting e ViewSection e ViewSheet e ViewSchedule e UlView Overview This section is a high level overview discussing the following e How views are generated e View types e Display settings e Temporary view modes e Element visibility e Creating and deleting views View Process The following figure illustrates how a view is generated 3D world coordinate Clipped 2D device output primitives world coordinates coordinates Transform into Project onto viewport in projection 2D device plane coordinates for display Clip against crop box Figure 94 Create view process Each view is generated by projecting a three dimensional object onto a two dimensional projection plane Projections are divided into two basic classes e Perspective e Parallel After the projection type is determined you must specify the conditions under which the 3D model is needed and the scene is to be rendered For more information about projection refer to the View3D section World coordinates
46. 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 Code Region 3 11 Creating and editing a manifest file Marea ven ne eee DUI aire st RevitAddInManifest Manifest new RevitAddInManifest create an external command RevitAddInCommand commandi new RevitAddInCommand full pathNNassemblyName dll Guid NewGuid namespace className Comman IR DSc Cri prion OCs cuido e commandl Text display text ANS command only io le MEP ye Ue ire same enables c stehe etes in Project document or when no document at all commanesepsscuoiinecc5pscdolbtumecMechasnseo Discipline Bleckureal Diccipline Piping I Da ciplirne ETE eI er commandl VisibilityMode VisibilityMode NotVisibleInFamily create an external application RevitAddInApplication applicationl new RevitAddInApplication appName full pathNNassemblyName dll Guid NewGuid namespace className j acad both commana sy and apeolicarion s inte mentes Manifest AddInCommands Add command1 Mentes Addinappli c E Om Adda pplication j SEVe mena test o a Elle RevitProduct revitProductl RevitProductUtility GetAllinstalledRevitProducts 0 Manifest SaveAss revitProduct gt AlilUsersAddink older t Resto isis samples a
47. The viewFamilyTypeld parameter needs to be a three dimensional ViewType The following code sample illustrates how to create a perspective 3D view Code Region Creating a Perspective 3D view view plaincopy to clipboardprint 1 Find a 3D view type 2 IEnumerable ViewFamilyType viewFamilyTypes from elem in new FilteredElementCollector document OfClass typeof ViewFamilyType 35 let type elem as ViewFamilyType 4 where type ViewFamily ViewFamily ThreeDimensional 5 select type 6 7 Create a new Perspective View3D 8 View3D view3D View3D CreatePerspective document viewFamilyTypes First Id 9 if null view3D 10 11 By default the 3D view uses a default orientation 12 Change the orientation by creating and setting a ViewOrientation3D 13 XYZ eye new XYZ 0 100 10 14 XYZ up new XYZ 0 0 1 15 XYZ forward new XYZ 0 1 0 16 view3D SetOrientation newViewOrientation3D eye up forward i7 18 19 20 21 turn off the far clip plane with standard parameter API 22 234 Parameter farClip view3D get Parameter Far Clip Active gni farClip Set 0 25 The perspective view crop box is part of a pyramid with the apex at the viewer position It is the geometry between the two parallel clip planes The crop box bounds the portion of the model that is clipped out and projected onto the view plane The crop box is represented by the View CropBox property which
48. WhereElementIsNotElementType ToElements Sims gno erence loe well DS o ele XUUG ne COLO CTDUCSIOUE EUER IRR foreach Element e in walls oom cm cM E Resi eoa loo simo deese OO MSIE Topics in this section e Create a FilteredElementCollector e Applying Filters e Getting filtered elements or element ids e LINQ Queries Create a FilteredElementCollector The main class used for element iteration and filtering is called FilteredElementCollector It is constructed in one of three ways 1 From a document will search and filter the set of elements in a document 2 From a document and set of Elementlds will search and filter a specified set of elements 3 From a document and a view will search and filter the visible elements in a view NoteAlways check that a view is valid for element iteration when filtering elements in a specified view by using the static FilteredElementCollector IsViewValidForElementlteration When the object is first created there are no filters applied This class requires that at least one condition be set before making at attempt to access the elements otherwise an exception will be thrown Applying Filters Filters can be applied to a FilteredElementCollector using ElementFilters An ElementFilter is a class that examines an element to see if it meets a certain criteria The ElementFilter base class has three derived classes that divide element filters into three categories e ElementQuickF
49. XYZ Array a set of elements in the project by a specified number The resulting ArrayAnchorMember elements are not associated with a linear array Table 23 RadialArray Methods Member Description Create Document View Elementld int Line double ArrayAnchorMember Array one element in the project based on an input rotation axis Create Document View ICollection Elementld int Line double Array a set of elements in the project based on an input rotation axis ArrayAnchorMember ArrayElementWithoutAssociation Document View Elementld int Line double Array one element in the project based on an input rotation axis The resulting ArrayAnchorMember elements are not associated with a linear array ArrayElementsWithoutAssociation Document View ICollection lt Elementld gt int Line Array a set of elements in the project based on an input rotation axis The double ArrayAnchorMember resulting elements are not associated with a linear array The methods for arraying elements are useful if you need to create several instances of a component and manipulate them simultaneously Every instance in an array can be amember of a group Note When using the methods for arraying elements the following rules apply e When performing Linear and Radial Array operations elements dependent on the arrayed elements are also arrayed e Some elements cannot be arrayed because they cannot be grouped See the Revit User s Guide for more information abo
50. fa GetFailureMessages Inside event handler get all warnings foreach FailureMessageAccessor failure in failList check FailureDefinitionIds against ones that you want to dismiss FailureDefinitionId failID CA wee e Ce E eu Ore Derne Lome 8 prevent Revit from showing Unenclosed room warnings Ii cail D SS Puil dbase a lice soot e La ces oOo mince Te osad fa DeleteWarning failure FailuresProcessor The IFailuresProcessor interface gets control last after the FailuresProcessing event is processed There is only one active IFailuresProcessor in a Revit session To register a failures processor derive a class from IFailuresProcessor and register it using the Application RegisterFailuresProcessor method If there is previously registered failures processor it is discarded If a Revit add in opts to register a failures processor for Revit that processor will become the default error handler for all Revit errors for the session and the standard Revit error dialog will not appear If no failures processors are set there is a default one in the Revit Ul that invokes all regular Revit error dialogs FailuresProcessor should only be overridden to replace the existing Revit failure UI with a custom failure resolution handler which can be interactive or have no user interface If the RegisterFailuresProcessor method is passed NULL any transaction that has any failures is silently aborted unless failures are resolved by fi
51. should be handled at the end of a transaction Failure handling options may be set at any time before calling either Transaction Commit or Transaction RollBack using the Transaction SetFailureHandlingOptions method However after a transaction is committed or rolled back the options return to their respective default settings The SetFailureHandlingOptions method takes a FailureHandlingOptions object as a parameter This object cannot be created it must be obtained from the transaction using the GetFailureHandlingOptions method Options are set by calling the corresponding Set method such as SetClearAfterRollback The following sections discuss the failure handling options in more detail ClearAfterRollback This option controls whether all warnings should be cleared after a transaction is rolled back The default value is False DelayedMiniWarnings This options controls whether mini warnings if any are displayed at the end of the transaction currently being ended or if they should be postponed until the end of next transaction This is typically used within a chain of transactions when it is not desirable to show intermediate warnings at the end of each step but rather to wait until the completion of the entire chain Warnings may be delayed for more than one transaction The first transaction that does not have this option set to True will display all of its own warnings if any as well as all warnings that might have accumulate
52. there are two Arcs in the Curve Figure 164 ContFooting and Wall Support I nformation Isolated Foundation and StructuralColumn Support Information Structural columns can have an isolated footing as a PointSupport In this condition the footing can move with the supported structural column The Elementld of the FamilyInstance with the OST StructuralFoundation category is available from the AnalyticalModelSupport GetSupportingElement method Generally the support point is the bottom point of the curve retrieved from the AnalyticalModel GetCurve method It is also available after you get the isolated footing FamilyInstance and the AnalyticalModel Point available from the GetPoint method Figure 165 Isolated Foundation Familyl nstance and Structural Column Support I nformation Loads The following sections identify load settings and discuss load limitation guidelines Load Settings All functionality on the Setting dialog box Load Cases and Load Combinations tabs can be accessed by the API The following properties are available from the corresponding LoadCase BuiltInParameter Table 60 Load Case Properties and Parameters Property BuiltinParameter Case Number LOAD CASE NUMBER Nature LOAD_CASE_NATURE Category LOAD CASE CATEGORY The LOAD CASE CATEGORY parameter returns an Elementld The following table identifies the mapping between Category and Elementld Value Table 61 Load Case Category Load Case Category BuiltInCateg
53. which only appears when at least one add in is installed is available for third party developers to add a panel Ribbon Panel A ribbon tab is separated into horizontal groupings of commands An Add In panel represents the commands available for a third party developer s application The Add In panel is equivalent to the toolbar in Revit 2009 Ribbon Button The button is the mechanism for launching a command They can either be large medium or small Both large and small buttons can either be a simple push button or a drop down button The default first panel on the Add Ins tab is the External Tools panel that contains one button titled External Tools The External Tools menu button is equivalent to the Tools gt External Tools menu in Revit 2009 Any External Commands registered in a addin manifest file will appear in this menu button Batch Print Figure 240 External Tools menu button on Add Ins tab Drop down button A drop down button expands to show two or more commands in a drop down menu Each sub command can have its own large icon Vertical Separator A vertical separator is a thin vertical line that can be added between controls on a panel Tooltip A tooltip is a small panel that appears when the user hovers the mouse pointer over a ribbon button Tooltips provide a brief explanation of the commands expected behavior Terminology Definitions Several words are used to signify the requirem
54. 0 numberOfPoints lt totalCount numberOfPoints 7 8 CloudPoint point pointBuffer numberOfPoints 9 Process each point 10 System Drawing Color color System Drawing ColorTranslator FromWin32 point Color 11 String pointDescription String Format 1 2 3 12 point X point Y point Z color ToString 13 14 Filters Filters are used both to limit the volume which is searched when reading points and also to govern the display of point clouds A PointCloudFilter can be created based upon a collection of planar boundaries The filter will check whether a point is located on the positive side of each input plane as indicated by the positive direction of the plane normal Therefore such filter implicitly defines a volume which is the intersection of the positive half spaces corresponding to all the planes This volume does not have to be closed but it will always be convex The display of point clouds can be controlled by assigning a filter to e PointCloudInstance SetSelectionFilter Display of the filtered points will be based on the value of the property e PointCloudInstance FilterAction If it is set to None the selection filter is ignored If it is set to Highlight points that pass the filter are highlighted If it is set to Isolate only points that pass the filter will be visible The following example will highlight a subset of the points in a point cloud based on its bounding box
55. 10 0 10 0 0 0 37 newTag TagHeadPosition headerPnt 38 39 return newTag 40 Hello Figure 74 Create I ndependentTag using sample code Text In the API the TextNote class represents Text Its general features are as follows Table 38 General Features of TextNote Function API Method or Property Add text to the application Document Create NewTextNote Method Get and set string from the text component TextNote Text Property Get and set text component position TextNote Coord Property Get and set text component width TextNote Width Property Get all text component leaders TextNote Leaders Property Add a leader to the text component TextNote AddLeader Method Remove all leaders from the text component TextNote RemoveLeaders Method Revit supports two kinds of Leaders straight leaders and arc leaders Control the TextNote leader type using the TextNoteLeaderType enumerated type Table 39 Leader Types Function Member Name al TNLT_ARC_R Add a right arc leader TNLT ARC L Add a left arc leader TNLT STRAIGHT R Add a right leader yr TNLT_STRAIGHT_L i Add a left leader Note Straight leaders and arc leaders cannot be added to a Text type at the same time Annotation Symbol An annotation symbol is a symbol applied to a family to uniquely identify that family in a project mr Tag All Mat Tagged re et Symbol as Legen Symbol nent a Color Scheme Legend Figure 75
56. 20 if curve null 21 22 The curve is already transformed into the project coordinate system 23 DA y 25 26 In this sample the solids are obtained from an instance using GetSymbolGeometry The constituent points are then transformed into the project coordinate system using the Geometrylnstance Transform Code Region Getting solid information from an instance 1 private void GetAndTransformSolidInfo Application application Element element Options geoOptions 2 1 35 Get geometry element of the selected element 4 Autodesk Revit DB GeometryElement geoElement element get Geometry geoOptions 5 6 Get geometry object 7 foreach GeometryObject geoObject in geoElement 8 9 Get the geometry instance which contains the geometry information 10 Autodesk Revit DB GeometryInstance instance 11 geoObject as Autodesk Revit DB GeometryInstance 12 if null instance 13 14 GeometryElement instanceGeometryElement instance GetSymbolGeometry 15 foreach GeometryObject instObj in instanceGeometryElement 16 17 Solid solid instObj as Solid 18 if null solid solid Faces Size 0 solid Edges Size 19 20 continue 21 22 23 Transform instTransform instance Transform 24 Get the faces and edges from solid and transform the formed points 253 foreach Face face in solid Faces 26 27e Mesh mesh face Triangulate 28 foreach XYZ ii in mesh Vertices 29
57. 32 Options for creating instance with NewFamilyInstance below Some FamilyInstance objects require more than one location to be created In these cases it is more appropriate to use the more detailed creation method provided by this object see Table 33 Options for creating instances with other methods below If the instance is not created an exception is thrown The type symbol used must be loaded into the project before the method is called Table 32 Options for creating instance with NewFamilyl nstance Category Air Terminals Boundary Conditions Casework Communication Devices Data Devices Electrical Equipment Electrical Fixtures Entourage Fire Alarm Devices Furniture Furniture Systems Generic Models Lighting Devices Lighting Fixtures Mass Mechanical Equipment Nurse Call Devices Parking Planting Plumbing Fixtures Security Devices Site Specialty Equipment Sprinklers Structural Connections Structural Foundations Structural Stiffeners Telephone Devices Columns Structural Columns Doors Windows Structural Framing Beams Braces NewFamilyInstance parameters XYZ FamilySymbol StructuralType XYZ FamilySymbol Element StructuralType XYZ FamilySymbol XYZ Element StructuralType XYZ FamilySymbol Element Level StructuralType XYZ FamilySymbol Level StructuralType Face XYZ XYZ FamilySymbol Reference XYZ XYZ FamilySymbol Face Line FamilySymbol Referenc
58. 40 else 41 42 throw new Exception Please open a Family document before invoking this command 43 44 return rectExtrusion 45 The following sample shows how to create a new Sweep from a solid ovoid profile in a Family Document Code Region 13 6 Creating a new Sweep view plaincopy to clipboardprint 1 private Sweep CreateSweep Autodesk Revit DB Document document SketchPlane sketchPlane 2 353 4 Sweep sweep null 5 make sure we have a family document 6 if true document IsFamilyDocument y 8 Define a profile for the sweep 9 CurveArrArray arrarr new CurveArrArray 10 CurveArray arr new CurveArray 11 Create an ovoid profile 12 XYZ pnt1 new XYZ 0 0 13 XYZ pnt2 new XYZ 2 0 0 14 XYZ pnt3 new XYZ 1 1 0 15 arr Append document Application Create NewArc pnt2 1 0d 0 0d 180 0d XYZ BasisX XYZ BasisY 16 arr Append document Application Create NewArc pnt1 pnt3 pnt2 17 arrarr Append arr 18 SweepProfile profile document Application Create NewCurveLoopsProfile arrarr 19 Create a path for the sweep 20 XYZ pnt4 new XYZ 10 0 0 21 XYZ pnt5 new XYZ 0 10 0 255 Curve curve document Application Create NewLineBound pnt4 pnt5 23 CurveArray curves new CurveArray 24 curves Append curve 25 create a solid ovoid sweep 26 sweep document FamilyCreate NewSweep true curves sketchPlane profile 0 ProfilePlane
59. A property is 160 The value of StartAngle Graphics Cannot be accessed visible Materials and Finishes Material Identity Data Subcategory Figure 82 Corresponding parameter Revolution Profile Figure 83 Revolution sketch Figure 84 Revolution result Note e The Start Angle is not accessible using the Revit Platform API e Ifthe End Angle is positive the Rotation direction is clockwise If it is negative the Rotation direction is counterclockwise Blend The Blend command blends two profiles together For example if you sketch a large rectangle and a smaller rectangle on top of it Revit Architecture blends the two shapes together Query the Blend Form object for a generic form to use in family modeling and massing The Blend class has the following properties Table 42 Blend Properties Property Description BottomSketch Returns the Bottom Sketch It is a Sketch object TopSketch Returns the Top Sketch Blend It is a Sketch object FirstEnd Returns the First End It is a Double type SecondEnd Returns the Second End It is a Double type The FirstEnd and SecondEnd property values are consistent with the same parameters in the Revit UI The following pictures illustrate the Blend corresponding parameters the sketches and the result Element Properties Family Load Type Edit Mew Type Parameters Control all elements of this type Parameter Value Instance Parameters Contro
60. Architecture This chapter covers API functionality that is specific to Revit Architecture namely e Functionality related to rooms Element Room RoomTag etc Topics tn this section e Rooms Rooms The following sections cover information about the room class its parameters and how to use the room class in the API Room Area and Tags The Room class is used to represent rooms and elements such as room schedule and area plans The properties and create function for different rooms areas and their corresponding tags in the API are listed in the following table Table 55 Room Area and Tags relationship Element Class Category Boundary Location Can Create Room in Plan View Room OST Rooms Has if in an enclosed region LocationPoint NewRoom except for NewRoom Phase Room in Schedule View Room OST Rooms Null Null NewRoom Phase Area Room OST Areas Always has LocationPoint No Room Tag RoomTag OST RoomTags LocationPoint X Creation Document NewRoomTag Area Tag FamilySymbol OST AreaTags LocationPoint No Note Room Name is the combination of the room name and room number Use the ROOM NAME BuiltinParameter to get the room name In the following picture the Room Name returns Master Bedroom 2 Dimensions ij hi r ies i Heig h A coro E i consents M Cd E ARA ONT Hc A Volume Not Computed Master Bedroom iD frre mesero Figure 137 Room name and number Note As
61. Autodesk Revit UI TaskDialog Show GetWorksharingDisplayMode WorksharingDisplayMode displayMode 6 7 view SetWorksharingDisplayMode WorksharingDisplayMode CheckoutStatus 8 Autodesk Revit UI TaskDialog Show SetWorksharingDisplayMode CheckoutStatus was set for View view Name 9 The WorksharingDisplaySettings class controls how elements will appear when they are displayed in any of the worksharing display modes The colors stored in these settings are a common setting and are shared by all users in the model Whether a given color is applied is specific to the current user and will not be shared by other users Note that these settings are available even in models that are not workshared This is to allow pre configuring the display settings before enabling worksets so that they can be stored in template files Code Region Worksharing Diplay Graphic Settings view plaincopy to clipboardprint 1 public WorksharingDisplayGraphicSettings GetWorksharingDisplaySettings Document doc String userName WorksetId worksetId bool ownedbyCurrentUser 2 1 3 WorksharingDisplayGraphicSettings graphicSettings 4 P get or create a WorksharingDisplaySettings current active document 6 WorksharingDisplaySettings displaySettings WorksharingDisplaySettings GetOrCreateWorksharingDisplaySettings doc 7 8 get graphic settings for a user if specified 9 if String IsNullOrEmpty userName 10 graphicSettings displayS
62. BasisY property of the Transform returned by Face ComputeDerivatives e The normal vector of the given face This is the BasisZ property of the Transform returned by Face ComputeDerivatives All of the vectors returned are non normalized Face analysis There are several Face members which are tools suitable for use in geometric analysis Intersect The Intersect method computes the intersection between the face and a curve It can be used in to identify e The intersection point s between the two objects e The edge nearest the intersection point if there is an edge close to this location e Curves totally coincident with a face e Curves and faces which do not intersect Project The Project method projects a point on the input face and returns information on the projection point the distance to the face and the nearest edge to the projection point Triangulate The Triangulate method obtains a triangular mesh approximating the face There are two overloads to this method The parameterless method is similar to Curve Tessellate in that the mesh s points are accurate within the input tolerance used by Revit slightly larger than 1 16 The second Triangulate method accepts a level of detail as an argument ranging from O coarse to 1 fine Face Splitting A face may be split into regions by the Split Face command The Face HasRegions property will report if the face contains regions created with the Split Face command
63. Code C NNNM Silene E NENNEN aaa mmm Y mese mmus Start Extension Calculation default 10 O 10 01 2 Start Ext End Extension Calculation default 10 0 10 0 1 2 End Exte Figure 194 Precast Double Tee Depth 1 6 EQ EQ Width 8 Q EB E Figure 195 Precast Double Tee Cross Section Width 8 0 Ref Level Q 7 D Figure 196 Precast Double Tee Cross Section 2 Length 5 0 1 7 10 0 10 0 7 Stat Extension Calculation 10 0 End Extension Calculation 10 0 Figure 197 Precast Double Tee Slab Depth 0 2 API User Interface Guidelines Topics in this section e Introduction e Consistency e Speak the Users Language e Good Layout e Good Defaults e Progressive Disclosure e Localization of the User Interface e Dialog Guidelines e Ribbon Guidelines e Common Definitions e Terminology Definitions Introduction This section is intended to provide guidance and best practices for designing user interfaces for applications based on the Revit API The following principles are followed by the Autodesk design and development staff when developing Revit and will provide a good starting point to the rest of this document Consistency It is important for applications based on the API to provide a user experience that is consistent with Revit This will allow the users of your application to leverag
64. Connector refConnector in refConnectors 33 34 if refConnector Owner Id hostId 35 36 return hub Id 37 38 39 40 41 return ElementId InvalidElementId Revit MEP The Revit MEP portion of the Revit API provides read and write access to HVAC and Piping data in a Revit model including e Traversing ducts pipes fittings and connectors in a system e Adding removing and changing ducts pipes and other equipment e Getting and setting system properties e Determining if the system is well connected e Access to Mechanical Settings e Managing Routing Preferences Topics in this section e MEP Element Creation e Connectors e Family Creation e Mechanical Settings e Routing Preferences MEP Element Creation Elements related to duct and pipe systems can be created using the following methods available in the Autodesk Revit Creation Document class e NewDuct e NewFlexDuct e NewPipe e NewFlexPipe e NewMechanicalSystem e NewPipingSystem e NewCrossFitting e NewElbowFitting e NewTakeoffFitting e NewTeeFitting e NewTransitionFitting e NewUnionFitting Topics in this Section e Creating Pipes and Ducts e Systems e Placeholders Create Pipes and Ducts There are 3 ways to create new ducts flex ducts pipes and flex pipes They can be created between two points between two connectors or between a point and a connector The following code creates a new pipe between two points New flex pipes duct
65. ElementQuickFilter which should minimize the number of Elements that are expanded in order to evaluate against the criteria set by this filter The following table summarizes the built in slow filters while a few examples follow to provide an in depth look at some of the filters Table 14 Built in Slow Filters Built in Filter What it passes Shortcut Method s AreaFilter Areas None AreaTagFilter Area tags None CurveElementFilter CurveElements None ElementLevelFilter Elements associated with a given level id None ElementParameterFilter Elements passing one or more parameter filter rules None ElementPhaseStatusFilter Elements with a given phase status on a given phase None FamilyInstanceFilter Instances of a particular family instance None FamilyStructuralMaterialTypeFilter Family elements of given structural material type None PrimaryDesignOptionMemberFilter Elements owned by any primary design option None RoomFilter Rooms None RoomTagFilter Room tags None SpaceFilter Spaces None SpaceTagFilter Space tags None StructurallnstanceUsageFilter FamilyInstances of given structural usage None StructuralMaterialTypeFilter FamilyInstances of given structural material type None StructuralWallUsageFilter Walls of given structural wall usage None ElementintersectsElementFilter Elements that intersect the solid geometry of a given element None ElementintersectsSolidFilter Elements that intersect the given solid geometry None The following slow filters ca
66. Elements are introduced based on element classification Make sure that you read the Elements Essentials and Parameter chapters before reading about the individual elements Editing Elements Learn how to move rotate delete mirror group and array elements Wall Floors Roofs and Openings Discusses Elements their corresponding ElementTypes representing built in place construction and different types of Openings in the API Family Instances Learn about the relationship between family and family instance family and family instance features and how to load or create them Family Creation Learn about creation and modification of Revit Family documents Conceptual Design Discusses how to create complex geometry and forms in a Revit Conceptual Mass document Datum and Information Elements Learn how to set up grids add levels use design options and more Annotation Elements Discusses document annotation including adding dimensions detail curves tags and annotation symbols Sketching Sketch functions include 2D and 3D sketch classes such as SketchPlane ModelCurve GenericForm and more Views Learn about the different ways to view models and components and how to manipulate the view in the API Material Material data is an Element that identifies the physical materials used in the project as well as texture color and more Advanced Topics Geometry Discusses graphics related types in the API used to describe the gra
67. Family documents e Access family types and parameters Topics in this section e Family Documents e Family Item Factory e Family Element Visibility e Family Manager Family Documents Family The Family object represents an entire Revit family A Family Document is a Document that represents a Family rather than a Revit project Using the Family Creation functionality of the Revit API you can create and edit families and their types This functionality is particularly useful when you have pre existing data available from an external system that you want to convert to a Revit family library API access to system family editing is not available Categories As noted in the previous chapter the FamilyBase FamilyCategory property indicates the category of the Family such as Columns Furniture Structural Framing or Windows The following code can be used to determine the category of the family in an open Revit Family document Code Region 13 1 Category of open Revit Family Document string categoryName familyDoc OwnerFamily FamilyCategory Name Parameters Family parameters can be accessed from the OwnerFamily property of a Family Document as the following example shows Code Region 13 2 Category of open Revit Family Document get the owner family of the family document Family family familyDoc OwnerFamily Parameter param family get Parameter BuiltInParameter FAMILY WORK PLANE BASED this param is a Yes No paramet
68. Home Inset Annotate Modi fy EE Arc mm Collaborate View mem Je Add Ins External Tools External MultiSelect Activate Dimension Duct between connectors rvt Project bro 8 E C Views Discipline Ej Mechanical B HVAC Ee Floor Plans e 2 a 1 Mech j j 2 Meck o Ele Ceiling Plans ben 1 Ceiling Mech 2 Ceiling Mech j a e 3D Views l 2 e 30H E Elevations Building Elevation 2 m East Mech North Mech South Mech 2 West Mech IE Ej Plumbing T Floor Plans IE 5 1 Plumoing 2 Plumbing S eT 3D Views oo 3D Plumaing D Legends I E schedules Quantities Figure 166 New duct added between selected elements Lining and Insulation Pipe and duct insulation and lining can be added as separate objects associated with ducts and pipes The ids of insulation elements associated with a duct or pipe can be retrieved using the static method InsulationLiningBase GetInsulationlds while the ids of lining elements can be retreived using the static method InsulationLiningBase GetLininglds To create new insulations associated with a given duct pipe fitting accessory or content use the corresponding static method DuctInsulation Create or Pipelnsulation Create DuctLining Create can be used to create a new instance of a lining applied to the inside of a given duct fitting or accessory Placeholders The Revit API provides the ability to p
69. Min new XYZ 10 0 0 29 sectionBox Max new XYZ 10 12 5 30 Min Max X values 10 10 define the section line length on each side of the wall 31 Max Y 12 is the height of the section box Max Z 5 is the far clip offset Dad 33 Create a new view section 34 ViewSection viewSection ViewSection CreateSection document viewFamilyTypes First Id sectionBox Reference sections are sections that reference an existing view Revit does not add a new view when you create a new reference section Code Region ViewSection CreateReferenceSection view plaincopy to clipboardprint 1 public ViewSection ViewSection CreateReferenceSection Document document 2 ElementId parentViewId 35 ElementId viewIdToReference 4 5 XYZ headPoint XYZ tailPoint The parentViewld parameter is the Id of the view in which the new reference section marker will appear Reference sections can be created in FloorPlan CeilingPlan StructuralPlan Section Elevation Drafting and Detail views The viewldToReference can be the Id of a Detail Drafting or Section view The ViewFamilyType of the referenced view will be used by the new reference section The two XYZ points will determine the location of the section marker s head in the parent view Detail Views A detail view is a view of the model that appears as a callout or section in other views This type of view typically represents the model at finer scales of detail than in the p
70. Revit task dialog to communicate with the user The command links below open additional task dialogs with more information Add commmandLink options to task dialog mainDialog AddCommandLink TaskDialogCommandLinkId CommandLinkl view Ini ormation about the kevit NES mcm Nene aot mainDialog AddCommandLink TaskDialogCommandLinkId CommandLink2 view Intormation about Che active document ser Sonna ouere ono anc erae oe eoa DIS Me Coa EE e SIDE ob e onie a oaa e adeee task dialog will show a Close button by default marniDialog CommonButtCons stg oc eno omes lose mainDialog DefaultButton TaskDialogResult Close 1 Se Moores wee oia exc esi sue iy Ms co co deste wo cle dela ocu mainDialog FooterText Ua hrer neip Us auleodesk com adcsk Servlet messem i 2s sc dome ei cic ide Rev ANGI Da loe Cen fco TaskDialogResult tResult mainDialog Show Jy Mie Ea uee elliveles Malas ce dide ede come als ee sao lle Weel Dile llos iaa cin 2 Close louliciccin slows aro eno hom elo oa lie Sy a above ei eco JO if TaskDialogResult CommandLinkl tResult TaskDialog daa loge Command ink new WasikPaalog Revie Build Inteormatrom cla how Commie ine Iba ic di Me aio IL IUS e WWE LOG MVA usd Oi Meis Ges Lees emblem en a Sale Ver eso INUiMeeic iiss 4 a elo Were Sioa Nilo sia ae SR t CC ye Vers one Build isr Ease some Chia lle IC Crimean ode ll Sao C E ZEE che cercle ci be secon
71. Tee vr Care oia e leo oi o le ee ue meno re Oia BuiltInCategory enumCategory BuiltInCategory category Id Value NoteTo avoid Globalization problems when using Category Name BuiltInCategory is a better choice Category Name can be different in different languages Families are classes of Elements within a category Families can group Elements by the following e Acommon set of parameters properties e Identical use e Similar graphical representation Most families are component Family files meaning that you can load them into your project or create them from Family templates You determine the property set and the Family graphical representation Another family type is the system Family System Families are not available for loading or creating Revit predefines the system Family properties and graphical representation they include walls dimensions roofs floors or slabs and levels Families System Families Component Families Figure 22 Families In addition to functioning as an Element class Family is also a template used to generate new items that belong to the Family Family in the Revit Platform API In the Revit Platform API both the Family class and Familylnstance belong to the Component Family Other Elements include System Family Families in the Revit Platform API are represented by three objects e Family e FamilySymbol e FamilyInstance Each object plays a significant role in the Family structure The Fa
72. ThermalAsset associated with the material Other Properties The material object properties identify a specific type of material including color fill pattern and more Properties and Parameter Some Material properties are only available as a Parameter A few such as Color are available as a property or as a Parameter using the BuiltInParameter MATERIAL_PARAM_COLOR Rendering Information Collections of rendering data are organized into objects called Assets which are read only You can obtain all available Appearance related assets from the Application Assets property An appearance asset can be accessed from a material via the Material RenderAppearance property The following figure shows the Appearance Library section of the Asset Browser dialog box which shows how some rendering assets are displayed in the Ul Asset Browser OAhearahnre hPrPAF FR amp EIF F IE z E LARA al 4 PEIES 1 laus Y Jedi dn lie EHZT ut E e A A a e e a ti ctrl El ee Document Assets m Asset Name a Aspect Type Category Favorites gt Autodesk Physical Assets American Cherry Appearance Wood Flooring Wood Appearance Library E l Lo l gt Ceramic ig Andiroba Natural Appearance Wood Flooring Wood t Concrete E a Bamboo Appearance Generic Flooring Wood Default Edo La Beech Plank Appearance Generic Flooring Wood Finish _ Flooring i E Beechwood Amaretto Appearance Wood Flooring Wood Glass Liquid E
73. and RadialArray to array one or more elements in the project These classes provide static methods to create a linear or radial array of one or more selected components Linear arrays represent an array created along a line from one point while radial arrays represent an array created along an arc As an example of using an array you can select a door and windows located in the same wall and then create multiple instances of the door wall and window configuration Both LinearArray and RadialArray also provide methods to array one or several elements without being grouped and associated Although similar to the Create methods for arraying elements each resulting element is independent of the others and can be manipulated without affecting the other elements See the tables below for more information on the methods available to create linear or radial arrays Table 22 LinearArray Methods Member Description Create Document View Elementld int XYZ ArrayAnchorMember Array one element in the project by a specified number Create Document View ICollection Elementld int XYZ ArrayAnchorMember Array a set of elements in the project by a specified number ArrayElementWithoutAssociation Document View Elementld int XYZ Array one element in the project by a specified number The resulting elements ArrayAnchorMember are not associated with a linear array ArrayElementsWithoutAssociation Document View ICollection lt Elementld gt int
74. and Wall Support I nformation Structural Column Beam and Brace Support Information In the following picture the horizontal beam has three PointSupports two structural columns and one structural brace The brace has three PointSupports two structural columns and one structural beam Neither column has a support Element Figure 162 StructuralElements Support Information BeamSystem and Wall Support Information Though you can pick walls as supports when you draw a BeamSystem its support information is not directly available because the BeamSystem does not have the AnalyticalModel property The solution is to call the GetAllBeams method to retrieve the AnalyticalModelSupport collection for the Beams ARAN inset Meet ear dei aT TET rendu Fa DEED PL CER FR p ae RE aer SR pe A erf sriain LF Biases Sighs ed bed ao uel aoa NS NR r EEPL yp PNA L er a LJ LJ YS ur i Ty Modify Create Floor Boundary Debug i Set Show Ref Plane Pick Supports Adds sketch lines Eased on existing structural walls or beams Use this tool to pick beams to define split lines and create constant bearing lines for the structural floor Figure 163 BeamSystem and Wall Support Information ContFooting and Wall Support Information For a Wall with a continuous Foundation the Wall has a CurveSupport with ContFooting available The support curves are available using the AnalyticalModel GetCurves method In the following sample
75. arc Radius message nArc s center ASS Ena ce cm ems else fy Tae eis etiews is ch Wiese cfs deii aio O10 Autodesk Revit Geometry Line line curve as Autodesk Revit DB Line message nLine s Length line Length Get curve start point messages M iniSiceiat Xe c Ya Xe We Sicieiling COUNT EIS Oeste e ane oat 0 Get curve end point message o End polar XV Tos eran curve ese Ebo TaskDialog Show Revit message Il Oi taa pointi Ss ames SOOO ESSE Serna A 230186611 a Te Svea Mog e ME EDO c area QE EU Creating a Grid Two overloaded Document methods are available to create a new grid in the Revit Platform API Using the following method with different parameters you can create a curved or straight grid Code Region 15 4 NewGrid AMO de Gieicl Nets Base sue r sulle uero Mere id iine lime NoteThe arc or the line used to create a grid must be in a horizontal plane The following code sample illustrates how to create a new grid with a line or an arc Code Region 15 5 Creating a grid with a line or an arc void CreateGrid Autodesk Revit Document document M Create the comet line mhich chie weasel dioere tes LESS aati E Mew AO O XYZ end new XYZ 30 30 0 Line online Line etu Domo Suite An M Create a grid using ene geometry line Grid lineGrid document Create NewGrid geomLine if null lineGrid throw new Exception Create a new straight
76. be provided in a single manifest file The following table describes the available XML tags Tag Description Assembly The full path to the add in assembly file Required for all ExternalCommands and ExternalApplications FullClassName Addinld Name Text Vendorld VendorDescription Description VisibilityMode Discipline AvailabilityClassName Largelmage Smalllmage LongDescription Tooltiplmage LanguageType The full name of the class in the assembly file which implements IExternalCommand or IExternalApplication Required for all ExternalCommands and ExternalApplications A GUID which represents the id of this particular application AddlInlds 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 name of application Required for ExternalApplications only The name of the button Optional use this tag for ExternalCommands only The default is External Tool A string conforming to the Autodesk vendor ID standard Required for all ExternalCommands and ExternalApplications Register your vendor id string with Autodesk at http www autodesk com symbreg Description containing vendor s legal name and or other pertinent information Optional Short description of the command will be used as the button tooltip Optional use this tag for ExternalCommands only The d
77. boundaries of the filter Point Cloud Engine A custom point cloud engine can be implemented to supply cloud points to Revit A point cloud engine can be file based or non file based A file based implementation requires that each point cloud be mapped to a single file on disk Revit will allow users to create new point cloud instances in a document directly by selecting point cloud files whose extension matches the engine identifier These files are treated as external links in Revit and may be reloaded and remapped when necessary from the Manage Links dialog A non file based engine implementation may obtain point clouds from anywhere e g from a database from a server or from one part of a larger aggregate file Because there is no file that the user may select Revit s user interface will not allow a user to create a point cloud of this type Instead the engine provider supplies a custom command using PointCloudType Create and PointCloudInstance Create to create and place point clouds of this type The Manage Links dialog will show the point clouds of this type but since there is no file associated with the point cloud the user cannot manage reload or remap point clouds of this type Regardless of the type of implementation a custom engine implementation consists of the following e Animplementation of IPointCloudEngine registered with Revit via the PointCloudEngineRegistry e Animplementation of IPointCloudAccess which will respond to
78. boundary location Units The Revit Unit System is based on seven base units for seven base quantities that are independent The base units are identified in the following table Table 9 7 Base Units in Revit Unit System Base Unit Unit In Revit Unit System Length Feet ft Imperial Angle Radian Metric Mass Kilogram kg Metric Time Seconds s Metric Electric Current Ampere A Metric Temperature Kelvin K Metric Luminous Intensity Candela cd Metric Note Since Revit stores lengths in feet and other basic quantities in metric units a derived unit involving length will be a non standard unit based on both the Imperial and the Metric systems For example since a force is measured in mass length per time squared it is stored in kg ft s The Revit Platform API provides access to project units and format via the Document ProjectUnit The APIs that provide access to Project units and format settings include the following Table 10 Project Unit Properties UI Command Corresponding Type in API Access API Slope Enums RiseRunOrAngleType ProjectUnit Slope Decimal symbol Enums DecimalSymbolType ProjectUnit DecimalSymbolType Discipline Enums UnitDiscipline ProjectUnit FormatOptions Discipline Units Enums DisplayUnitType ProjectUnit FormatOptions Units Rounding System Double ProjectUnit FormatOptions Rounding Unit suffix Enums UnitSuffixType ProjectUnit FormatOptions Unitsuffix Elements Essentials An Element corresponds to a
79. built in parameter ID to get the parameter Revit has a large number of built in parameters available using the BuiltlnParameter enumerated type For more details see Parameter Basic Interaction with Revit Elements Topics tn this section e Filtering e Selection e Parameters e Collections e Editing Elements e Views Filtering The Revit API provides a mechanism for filtering and iterating elements in a Revit document This is the best way to get a set of related elements such as all walls or doors in the document Filters can also be used to find a very specific set of elements such as all beams of a specific size The basic steps to get elements passing a specified filter are as follows 1 Create a new FilteredElementCollector 2 Apply one or more filters to it 3 Get filtered elements or element ids using one of several methods The following sample covers the basic steps to filtering and iterating elements in the document Code Region 6 1 Use element filtering to get all wall instances in document jf iaa etl Well aiosce ness io cle lorem ee los D ed est acpoly alle eue ElementCategoryFilter filter new ElementCategoryFilter BuiltInCategory OST Walls ASS tci seo e re leMmene crime rine waceu ele meme Use shortcut WhereElementIsNotElementType to find wall instances only Filteredel ment ollector collector New Ie Tees exe heneneeo Meer eoe document IList lt Element gt walls collector WherePasses filter
80. c O e u ri 5S gt d El Lu LL O mi OH 2 o E cl e el QD o 9 3 5 5 rn O d Qu Pa O a E TX mi La ES 2 50 E E TEE C n om B3 inten O Pt m Y C c dw m sr in ON 00 OY amp AAA B dad d T o Q rea o BS z o ome m Ka 7 Ka T Q o e sx Revit reverses changes made by the external command J Error message dialog box and highlighted elements The Return result indicates that the execution failed succeeded or is canceled by the user If it does not succeed Figure 13 Return Table 2 I ExternalCommand Result Member Name Description Autodesk Revit Ul Result Succeeded The external command completed successfully Revit keeps all changes made by the external command Autodesk Revit Ul Result Failed The external command failed to complete the task Revit reverses operations performed by the external command If the message parameter of Execute is set Revit displays a dialog with the text Error cannot be ignored Autodesk Revit Ul Result Cancelled The user cancelled the external command Revit reverses changes made by the external command If the message parameter of Execute is set Revit displays a dialog with the text Warning can be ignored The following example displays a greeting message and allows the user to select the return value Use the Execute method as the entrance to the Revit application Code Region 3 4 Prompting the user view plaincopy to clipboard
81. can be used to open any of these document types All open documents can be retrieved using the Documents property For more details see Document and Management Session Information Properties such as UserName and methods such as GetRevitServerNetworkHosts provide read only access to this session specific information Shared Parameter Management Revit uses one shared parameter file at a time The Application OpenSharedParameterFile method accesses the shared parameter file whose path is set in the SharedParametersFilename property For more details see Shared Parameter Events The Application class exposes document and application events such as document open and save Subscribing to these events notifies the application when the events are enabled and acts accordingly For more details see Access to Revit Event in the Add In Integration section Create The Create property returns an Object Factory used to create application wide utility and geometric objects in the Revit Platform API Create is used when you want to create an object in the Revit application memory rather than your application s memory Failure Posting and Handling The FailureDefinitionRegistry which contains all registered FailureDefinitions is available from the static GetFailureDefinitionRegistry method The static method RegisterFailuresProcessor can be used to register a custom IFailuresProcessor For more information on posting and handling failures see Failu
82. cannot retrieve a Sketch object by iterating Document Elements enumeration because all Sketch objects are transient Elements When accessing the Family s 3D modeling information Sketch objects are important to forming the geometry For more details refer to 3D Sketch SketchPlane is the basis for all 2D sketch classes such as ModelCurve and Sketch SketchPlane is also the basis for 2D Annotation Elements such as DetailCurve Both ModelCurve and DetailCurve have the SketchPlane property and need a SketchPlane in the corresponding creation method SketchPlane is always invisible in the Revit UI Every ModelCurve must lie in one SketchPlane In other words wherever you draw a ModelCurve either in the UI or by using the API a SketchPlane must exist Therefore at least one SketchPlane exists in a 2D view where a ModelCurve is drawn The 2D view contains the CeilingPlan FloorPlan and Elevation ViewTypes By default a SketchPlane is automatically created for all of these views The 2D view related SketchPlane Name returns the view name such as Level 1 or North Work Plane Current Work Plane M ame Level Level 1 Spech a new Work Plane Level Level 1 V C3 Pick a line and use the work plane it was sketched in Figure 77 Pick a Plane to identify a new Work Plane When you specify a new work plane you can select Pick a plane as illustrated in the previous picture After you pick a plane select a plane on a particular element such as a
83. checks and changes may make some failures disappear or more likely can post new failures Therefore conclusions cannot be drawn about the state of failures to be processed when Transaction Commit is called To process failures correctly it is necessary to hook up to the actual failures processing mechanism When failures processing begins all changes to a document that are supposed to be made in the transaction are made and all failures are posted Therefore no uncontrolled changes to a document are allowed during failures processing There is a limited ability to resolve failures via the restricted interface provided by FailuresAccessor If this has happened all end of transaction checks and failures processing have to be repeated So there may be a few failure resolution cycles at the end of one transaction Each cycle of failures processing includes 3 steps 1 Preprocessing of failures FailuresPreprocessor 2 Broadcasting of failures processing event FailuresProcessing event 3 Final processing FailuresProcessor Each of these 3 steps can control what happens next by returning different FailureProcessingResults The options are e Continue has no impact on execution flow If FailuresProcessor returns Continue with unresolved failures Revit will instead act as if ProceedWithRollBack was returned e ProceedWithCommit interrupts failures processing and immediately triggers another loop of end of transaction checks followed by a
84. curve and returns information about the nearest point on the curve its parameter and the distance from the projection point Tessellate This splits the curve into a series of linear segments accurate within a default tolerance For Curve Tessellate the tolerance is slightly larger than 1 16 This tolerance of approximation is the tolerance used internally by Revit as adequate for display purposes Note that only lines may be split into output of only two tessellation points non linear curves will always output more than two points even if the curve has an extremely large radius which might mathematically equate to a straight line Curve collections The Revit API uses different types of collections of curves as inputs e Curveloop this represents a specific chain of curves joined end to end It can represent a closed loop or an open one Create it using o Curveloop Create o CurveLoop CreateViaCopy o CurveLoop CreateViaThicken e CurveArray this collection class represents an arbitrary collection of curves Create it using its constructor e CurveArrArray this collection class is a collection of CurveArrays When this is used the organization of the sub elements of this array have meaning for the method this is passed to for example in NewExtrusion multiple CurveArrays should represent different closed loops Newer API methods use NET collections of Curves in place of CurveArray and CurveArrArray Curve creatio
85. e Only large buttons MAY have two line labels but MUST NOT have more than two lines Labels for all other controls MUST fit on a single line e Button labels MUST NOT contain ellipses e Every word MUST be in capital case except articles a an and the coordinating conjunctions for example and or but so yet with and nor and prepositions with fewer than four letters like in The first and last words are always capitalized Panel Labels These guidelines are English only All rules from the Command Labels section apply to Panel Labels in addition to the following e The name of the panel SHOULD be specific Vague non descriptive and unspecific terms used to describe panel content will reduce the label s usefulness e Applications MUST NOT use panel names that use the abbreviations misc or etc e Panel labels SHOULD NOT include the term add ins since it is redundant with the tab label e Panel labels MAY include the name of the third party product or provider Tooltips The following are guidelines for writing tooltip text Write concisely There is limited space to work with Localization Considerations e Make every word count This is particularly important for localizing tooltip text to other languages e Do not use gerunds verb forms used as nouns because they can be confused with participles verb forms used as adjectives In the example Drawing controls drawing could be used as a verb or a nou
86. filter doesn t support them In order to use a class filter to find elements of these types it is necessary to use a higher level class and then process the results further to find elements matching only the subtype Note that dedicated filters exist for some of these types The following types are affected by this restriction Type Dedicated Filter Subclasses of Autodesk Revit DB Material None Subclasses of Autodesk Revit DB CurveElement CurveElementFilter Subclasses of Autodesk Revit DB ConnectorElement None Subclasses of Autodesk Revit DB HostedSweep None Autodesk Revit DB Architecture Room RoomFilter Autodesk Revit DB Mechanical Space SpaceFilter Autodesk Revit DB Area AreaFilter Autodesk Revit DB Architecture RoomTag Autodesk Revit DB Mechanical SpaceTag Autodesk Revit DB AreaTag RoomTagFilter SpaceTagFilter AreaTagFilter Autodesk Revit DB CombinableElement None Autodesk Revit DB Mullion None Autodesk Revit DB Panel None Autodesk Revit DB AnnotationSymbol None Autodesk Revit DB Structure AreaReinforcementType None Autodesk Revit DB Structure PathReinforcementType None Autodesk Revit DB AnnotationSymbolType None Autodesk Revit DB Architecture RoomTagType None Autodesk Revit DB Mechanical SpaceTagType None Autodesk Revit DB AreaTagType None Autodesk Revit DB Structure TrussType None Slow filters require that the Element be obtained and expanded in memory first Thus it is preferable to couple slow filters with at least one
87. flip All 4 lines are FathReinforcementlure Figure 155 PathReinforcement PathReinforcementCurve in edit mode When using NewAreaReinforcement and NewPathReinforcement methods to create objects you must decide on which host Element face it will lay Currently AreaReinforcement and PathReinforcement are only created on the PlanarFace retrieved from the Wall or Floor object After removing the faces from the Wall or Floor geometry you can filter the PlanarFace out as follows e Downcast the Face to PlanarFace Code Region 29 5 Downcasting Face to PlanarFace view plaincopy to clipboardprint 1 PlanarFace planarFace face as PlanarFace e lfitis a PlanarFace get its Normal and Origin Code Region 29 6 Getting Normal and Origin view plaincopy to clipboardprint 2 private void GetPlanarFaceInfo Face face SEE 4 PlanarFace planarFace face as PlanarFace 5 if null planarFace 6 7 XYZ origin planarFace Origin 8 XYZ normal planarFace Normal 9 XYZ vector planarFace get Vector 0 10 11 e Filter out the right face based on normal and origin For example o Fora general vertical Wall the face is located using the following factors The face is vertical normal Z 0 0 Parallel face directions are opposite normal1 X normal2 X normal1 Y normal2 Y Normal must be parallel to the location line e Fora general Floor without slope the factors are The face is ho
88. gt 0 m wallType wallTypes Cast lt WallType gt HlementAt lt WallType gt 0 if m_wallType null Change the wall to the cached wall type foreach ElementId addedElemId in data GetAddedElementIds Wall wall doc GetElement addedElemlId as Wall aie rei igh wall WallType m_wallType bullae sao cercado nal nao no return Wall type updater example updates all newly created walls to a special wall pulus eee Eus ci tme 0 tenian cebo 5 8 IO Os oO ist ies Mall public UpdaterId GetUpdaterId TOC UCA mM pater Ed public string GetUpdaterName return Wall Type Updater The Execute method The purpose of the Execute method is to allow your Updater to react to changes that have been made to the document and make appropriate related This method is invoked by Revit at the end of a document transaction in which elements that matched the UpdateTrigger for this Updater were added changed or deleted The method may be invoked more than once for the same transaction due to changes made by other Updaters Updaters are invoked before the DocumentChanged event so this event will contain changes made by all updaters All changes to the document made during the invocation of this method will become a part of the invoking transaction and maintained for undo and redo operations When implementing this method you may not open any new transactions an exception will be thrown
89. in a collection an array a set etc regardless of its specific implementation Method A method is a function or procedure that belongs to a class and operates or accesses the class data members In procedural programming this is called a function Namespace A namespace is an organizational unit used to group similar and or functionally related classes together Overloading Method overloading is when different methods functions of the same name are invoked with different types and or numbers of parameters passed Properties Properties are data members of a class accessible to the class user In procedural programming this is called a variable Some properties are read only support Get method and some are modifiable support Set method Revit Families A Family is a collection of objects called types A family groups elements with a common set of parameters identical use and similar graphical representation Different types in a family can have different values of some or all parameters but the set of parameters their names and their meaning are the same Revit Parameters There are a number of Revit parameter types e Shared Parameters can be thought of as user defined variables e System Parameters are variables that are hard coded in Revit e Family parameters are variables that are defined when a family is created or modified Revit Types A Type is a member of a Family Each Type has specific parameters tha
90. in a host or the instance cannot be inserted into the specified host element the method NewFamilyInstance does nothing Code Region 12 5 Creating doors void CreateDoorsinNal l Autodesk Rev ln DIES Dee ee document Wall vall String fileName C Documents and Settings All Users Application Data Autodesk RST 2011 Imperial Libra Doors ye ac ihe Wels ole suis 2 Jeder e Family family null if document LoadFamily fileName out family throw new Exception Unable to load fileName Ji Gee tne erede yes level mor les Oronto Level level document ActiveView Level BamilysymbolSecelteravor symbolltor family scymools rorwardlzerauonr double x 0 y 0 z 0 while symbolltor MoveNext Bamilysymbol symbol symbolltor Current as Famalysymbol XYZ localo mew xu Ax 7 z FamilyInstance instance document Create NewFamilyInstance location symbol wall level SE US E lice Woo NOn b Ie DEO Eile ell E x or Bic yO a I S The result of the previous code in Revit is shown in the following picture Notice that if the specified location is not at the specified level the NewFamilyInstance method uses the location elevation instead of the level elevation Figure 48 Insert doors into a wall Create Familyl nstances Using Reference Directions Use reference directions to insert an item in a specific direction Code Region 12 6 Creating FamilyInstances using reference directions Str
91. in an exception The Mirrored property indicates whether the FamilyInstance object has been mirrored Orientation Work Plane Table 31 Door Mirrored Property Rotation Mirrored Door 2 Door 3 Door 4 Door 1 Boolean Property False True True False Mirrored HHHHHHHHI HHBHHHHHMIE 1h rH i Hi Door 1 rotated TIHHHHHT HHUHHHHE UTI TUR Door 1 HEUTE the CanRotate properties for Window 1 Casement 3x3 with Trim 36 x72 and Door 1 Double Glass 2 72 x82 are true h is false Window 2 cannot be rotated in the following picture A point location is a LocationPoint class object A footing a door or a table has a point location A line location is a LocationCurve class object A beam has a line location They are both subclasses of the Location class Window 1 rotated the Revit project the default result is either Door 1 or Door 2 To create a door like Door 3 or Door 4 you must flip the Door 1 and Door 2 hand orientation respectively The e flip operation is like a mirror transformation which is why the Door 3 and Door 4 Mirrored property is True If CanRotate is true you can call the family instance rotate method which flips the family instance by 180 degrees Otherwise the method does nothing and returns False The family instance Boolean CanRotate property is used to test whether the family instance can be rotate
92. include the following e The viewer s eye position e The viewing plane location where the projection is displayed Revit uses two coordinate systems e The global or model space coordinates where the building exists e The viewing coordinate system The viewing coordinate system represents how the model is presented in the observer s view Its origin is the viewer s eye position whose coordinates in the model space are retrieved by the View Origin property The X Y and Z axes are represented by the View RightDirection View UpDirection and View ViewDirection properties respectively e View RightDirection is towards the right side of the screen e View UpDirection towards the up side of the screen e View ViewDirection from the screen to the viewer The viewing coordinate system is right handed For more information see the Perspective Projection picture and the Parallel Projection picture in View3D Some portions of a 3D model space that do not display such as those that are behind the viewer or too far away to display clearly are excluded before being projected onto the projection plane This action requires cropping the view The following rules apply to cropping e Elements outside of the crop box are no longer in the view e The View CropBox property provides the geometry information for the box It returns an instance of BoundingBoxXYZ indicating a rectangular parallelepiped in the viewing coordinate system The coordinate system and th
93. including projection hard points approximation and rigid links e Support Information e Adjustment Information both Manual and Automatic e Analytical Offset Analytical Location Depending on the type of element that corresponds to the AnalyticalModel the location of the element with respect to analysis can be obtained by one of three methods GetPoint GetCurve or GetCurves Note that the curves retrieved from these methods do not have their Reference properties set Therefore they cannot be used for properties such as Curve EndPointReference Instead you can obtain References to the curves and their end points through construction of an AnalyticalModelSelector object containing the necessary information as the following example demonstrates Code Region 29 10 Getting a reference to analytical curve public bool GetReferenceData FamilyInstance familyInst Mol amo cian e o de Ie celine Ba db ye nse Gece ly eas IMC Curve analyticalCurve analyticalModelFrame GetCurve A adc pate ci IG mie yen test the stable reference to the curve AnalyticalModelSelector amSelector new AnalyticalModelSelector analyticalCurve amSelector CurveSelector AnalyticalCurveSelector WholeCurve Reference curveReference analyticalModelFrame GetReference amSelector i BS unes Sialoike ostende Lo Lie Siceiee jedi Oi elie OXIDE VAS amSelector CurveSelector AnalyticalCurveSelector StartPoint Reference startPointRefere
94. invoke it in Revit You also learn to create a addin manifest file to register the add in application as an external tool Another way to invoke the add in application in Revit is through a custom ribbon panel Create a New Project Complete the following steps to create a new project 1 Create a C project in Visual Studio using the Class Library template 2 Type AddPanel as the project name 3 Add references to the RevitAPI dll and RevitAPIUI dll using the directions in the previous walkthrough Walkthrough Hello World 4 Add the PresentationCore reference o Inthe Solution Explorer right click References to display a context menu o From the context menu click Add Reference The Add Reference dialog box appears o Inthe Add Reference dialog box click the NET Tab o From the Component Name list select PresentationCore o Click OK to close the dialog box PresentationCore appears in the Solution Explorer reference tree U mh Filtered to NET Framework 3 5 Component Name Version Runtime Path TE Microsoft VisualC STLCLR 1 0 0 0 v2 0 50727 CiWindows ia Sentinel v3 5 Client 350 0 v2 0 50727 CAWindows Microsoft ServiceModel C 3 5 0 0 v2 0 50727 CAProgram Microsoft ServiceModel C 3 5 0 0 v2 0 50727 CAProgram PresentationBuildTasks 3 0 0 0 v2 0 50727 CAProgram PresentationCore 3 0 0 0 v2 0 50727 CAProgram PresentationFramework A 3 0 0 0 v2 0 50727 CAProgram PresentationFramework Cl 3 0 0 0 v2 0 50727 C
95. located For more details about PlanCircuit see Plan Topology The following code illustrates the entire process Code Region 28 2 Creating and inserting a room into a plan circuit view plaincopy to clipboardprint 1 Room InsertNewRoomInPlanCircuit Autodesk Revit DB Document document Level level Phase newConstructionPhase 2 3 create room using Phase 4 Room newScheduleRoom document Create NewRoom newConstructionPhase 5 6 set the Room Number and Name Te string newRoomNumber 101 8 string newRoomName Class Room 1 9 newScheduleRoom Name newRoomName 10 newScheduleRoom Number newRoomNumber 11 12 Get a PlanCircuit 13 PlanCircuit planCircuit null 14 first get the plan topology for given level 15 PlanTopology planTopology document get PlanTopology level 16 17 Iterate circuits in this plan topology 18 foreach PlanCircuit circuit in planTopology Circuits 19 20 get the first circuit we find 21 if null circuit 22 23 planCircuit circuit 24 break 25 26 27 28 Room newRoom2 null 29 Transaction transaction new Transaction document Create Room 30 if transaction Start TransactionStatus Started 31 32 The input room must exist only in the room schedule 33 meaning that it does not display in any plan view 34 newRoom2 document Create NewRoom newScheduleRoom planCircuit 296 a model room wi
96. lt ElementId gt pointList AdaptiveComponentInstanceUtils GetInstancePointElementRefIds familyInstance ReferencePoint pointO doc GetElement pointList ElementAt 0 as ReferencePoint ReferencePoint point1 doc GetElement pointList ElementAt 1 as ReferencePoint move the adaptive component s points pointO amp point1 to match the position of the placement points point Position placementPoint0 Position point1 Position placementPoint1 Position j Datum and Information Elements This chapter introduces Datum Elements and Information Elements in Revit e Datum Elements include levels grids and ModelCurves e Information Elements include phases design options and EnergyDataSettings For more information about Revit Element classifications refer to Elements Essentials Note If you need more information refer to the related chapter e For LoadBase LoadCase LoadCombination LoadNature and LoadUsage refer toRevit Structure e For ModelCurve refer to Sketching e For Material and FillPattern refer to Material e For EnergyDataSettings refer to Revit Architecture Topics tn this section e Levels e Grids e Phase e Design Options Levels A level is a finite horizontal plane that acts as a reference for level hosted elements such as walls roofs floors and ceilings In the Revit Platform API the Level class is derived from the Element class The inherited Name property is used to retrieve the user visible level nam
97. more information see Editing Elements Annotation and Datum Elements Annotation and Datum Elements contain non physical items that are visible e Annotation Elements represent 2D components that maintain scale on paper and are only visible in one view For more information about Annotation Elements see Annotation Elements Note Annotation Elements representing 2D components do not exist only in 2D views For example dimensions can be drawn in 3D view while the shape they refer to only exists in a 2D planar face e Datum Elements represent non physical items that are used to establish project context These elements can exist in views Datum Elements are further divided into the following e Common Datum Elements Common Datum Elements represent non physical visible items used to store data for modeling e Datum FamilyInstance Datum FamilyInstance represents non physical visible items loaded into your project or created from family templates e NoteFor more information about Common Datum Elements and Datum FamilyInstance see Datum and Information Elements for ModelCurve related contents see Sketching e Structural Datum Elements Structural Datum Elements represent non physical visible items used to store data for structure modeling For more information about Structural Datum Elements see Revit Structure Sketch Elements Sketch Elements represent temporary items used to sketch 2D 3D form This group contains the following object
98. next to the image lt p gt 11 lt p gt when the user hovers the mouse over the control lt p gt 12 textData ToolTipImage 13 new BitmapImage new Uri D Sample HelloWorld bin Debug 39 Globe 32x32 png 14 15 IList lt RibbonItem gt stackedItems panel AddStackedItems textData cbData 16 if stackedItems Count gt 1 17 18 TextBox tBox stackedItems as TextBox 19 if tBox null 20 21 tBox PromptText Enter a comment 22 tBox ShowImageAsButton true 234 tBox ToolTip Enter some text 24 Register event handler ProcessText 25 tBox EnterPressed 26 new EventHandler lt Autodesk Revit UI Events TextBoxEnterPressedEventArgs gt ProcessText 27 28 29 ComboBox cBox stackedItems 1 as ComboBox 30 if cBox null 31 32 cBox ItemText ComboBox 33 cBox ToolTip Select an Option 34 cBox LongDescription Select a number or letter 354 30 ComboBoxMemberData cboxMemDataA new ComboBoxMemberData A Option A 37 cboxMemDataA Image 38 new BitmapImage new Uri D Sample HelloWorld bin Debug A bmp 39 cboxMemDataA GroupName Letters 40 cBox AddItem cboxMemDataA 41 42 ComboBoxMemberData cboxMemDataB new ComboBoxMemberData B Option B 43 cboxMemDataB Image 44 new BitmapImage new Uri D Sample HelloWorld bin Debug B bmp 45 cboxMemDataB GroupName Letters 46 cBox AddItem cboxMemDataB 47
99. non element geometry and to find intersections of solids Collection classes Includes classes derived from the IEnumerable or IEnumerator interface In this section you learn how to use various graphic related types how to retrieve geometry data from an element how to transform an element and more Topics in this section e Example Retrieve Geometry Data from a Wall e GeometryObject Classes e Geometry Helper Classes e Geometry Utility Classes e Collection Classes e Example Retrieve Geometry Data from a Beam e Extrusion Analysis of a Solid e Room and Space Geometry Example Retrieve Geometry Data from a Wall This walkthrough illustrates how to get geometry data from a wall The following information is covered e Getting the wall geometry edges e Getting the wall geometry faces Note Retrieving the geometry data from Element in this example is limited because Instance is not considered For example sweeps included in the wall are not available in the sample code The goal for this walkthrough is to give you a basic idea of how to retrieve geometry data but not cover all conditions For more information about retrieving geometry data from Element refer to Example Retrieving Geometry Data from a Beam Create Geometry Options In order to get the wall s geometry information you must create a Geometry Options object which provides detailed customized options The code is as follows Code Region 20 1 Creating Geometry Option
100. null geomSolid 11 12 int faces 0 13 double totalArea 0 14 foreach Face geomFace in geomSolid Faces 15 1 16 faces 17 faceInfo Face faces area geomFace Area ToString An 18 totalArea geomFace Area 19 20 faceInfo Number of faces faces Mn 21 faceInfo Total area totalArea ToString n 2 foreach Edge geomEdge in geomSolid Edges 23 24 get wall s geometry edges 2b 26 27 28 TaskDialog Show Revit faceInfo 29 GeometryObject Class The indexed property Element Geometry can be used to pull the geometry of any model element 3D element This applies both to system family instances such as walls floors and roofs and also to family instances of many categories e g doors windows furniture or masses The extracted geometry is returned to you as Autodesk Revit DB GeometryElement You can look at the geometry members of that element by iterating the Objects property Typically the objects returned at the top level of the extracted geometry will be one of Solid a boundary representation made up of faces and edges Mesh a 3D array of triangles Curve a bounded 3D curve Point a visible point datum at a given 3D location PolyLine a series of line segments defined by 3D points GeometryInstance an instance of a geometric element positioned within the element This figure illustrates the hierarchy o
101. o Inthe Add Reference dialog box click the Browse tab Locate the folder where Revit is installed and click the RevitAPl dll For example the installed folder location is usually C Program Files Autodesk Revit Architecture 20121ProgramiRevitAPl dll o Click OK to select the dll and close the dialog box RevitAPl appears in the Solution Explorer reference tree o Note You should always set the Copy Local property of RevitAPI dll to false for new projects This saves disk space and prevents the Visual Studio debugger from getting confused about which copy of the DLL to use Right click the RevitAPl dll select Properties and change the Copy Local setting from true the default to false 2 Repeat the steps above for the RevitAPI UI dll Add Code Add the following code to create the add in Code Region 2 1 Getting Started using System using Autodesk Revit UI using Aukodesk Revit DB namespace HelloWorld Autode k revit ALE totes DrancecrTten AUEOdeSsk hevluarAbErltoUtee ora ns cr ron Mo des Manual public class Classi TExternal Conmand public Autodesk Revit UI Result Execute ExternalCommandData revit ref string message ElementSet elements i TaskDialog chow Revi Hel lo Worldi retu urn Autodesk evi y UN Result Succeeded Tip The Visual Studio Intellisense feature can create a skeleton implementation of an interface for you adding stubs for all the required methods After you add iExternaComman
102. of the items If the collection is a flat list use the ListView and if the data is grouped into two or more columns use TableView or TreeTable instead A tree UI follows the principle of user initiated Progressive Disclosure Using a tree allows complex hierarchical data to be presented in a simple yet progressively complex manner If the data becomes too broad or deep a search box should be considered North South West ar Srp ce Figure 218 The Revit Project Browser is a good example of a tree view Tree Table As with a Tree View the user may need to view and browse a hierarchically organized collection of items with the intent of selecting one or more of the items However the user also needs to see more properties of the item than just the name To accommodate this present the user with a tree embedded within a table Each row presents additional attributes of the item Expanding a node exposes another row Visihil Projection Surace isibili E Aras El Casework NENNEN ERN Hidden Lines GMI Ceilings A v Common Edges B v Columns Figure 219 The Revit Visibility Graphics dialog is a good example of a Tree Table Collection Search Filter When the user is viewing a collection with many items they may need to filter the number of items To accomplish this provide a way for the user choose between either a system provided list of filter criteria and or user creatable criteria Selecting the criter
103. programmatic access to the same shared parameters feature that is available through the Revit Ul Shared parameters if defined as visible will be viewable to the user in an element s property window Shared parameters can be assigned to many but not all categories of elements The other option is extensible storage which allows you to create custom data structures and then assign instances of that data to elements in the model This data is never visible to the user in the Revit UI but may be accessible to other third party applications via the Revit API depending on the read write access assigned to the schema when it is defined Unlike Shared Parameters extensible storage is not limited to certain categories of elements Extensible storage data can be assigned to any object that derives from the base class Element in the Revit model Topics in this section e Shared Parameters e Definition File e Definition File Access e Binding e Extensible Storage Shared Parameters Shared Parameters are parameter definitions stored in an external text file The definitions are identified by a unique identifier generated when the definition is created and can be used in multiple projects This chapter introduces how to gain access to shared parameters through the Revit Platform API The following overview shows how to get a shared parameter and bind it to Elements in certain Categories e Set SharedParametersFileName e Get the External Definition
104. property to determine if rigid links are applicable to the AnalyticalModel Additionally you can use HasRigidLinksWith to determine whether the AnalyticalModel has rigid links with a specific element End links can be retrieved by specifying the AnalyticalCurveType options RigidLinkHead and RigidLinkTail with the AnalyticalModel GetCurves Method Or use AnalyticalModel GetRigidLink with an AnalyticalModelSelector object One difference between the AnalyticalModel methods GetCurve and GetCurves for a structural beam is that GetCurves includes the single Curve as well as the structural beam RigidLink Curve if it is present Pass the AnalyticalCurveType RigidLinkHead or AnalyticalCurveType RigidLinkTail enum values to the GetCurves method to get the RigidLink at the head or tail of a beam Although you cannot create a rigid link directly since it is not an independent object you can create it using the RigidLinksOption property on the analytical model for beams and or columns The rigid link option for a beam overrides the option for the column For Structural Beams the RigidLinksOption property can have the following values e AnalyticalRigidLinksOption Enabled Rigid links will be formed e AnalyticalRigidLinksOption Disabled Rigid links will not be formed e AnalyticalRigidLinksOption FromColumn Rigid links may be formed depending on the corresponding structural column s value For Structural Columns the RigidLinksOption
105. return that Curve Otherwise it will throw an Autodesk Revit Exceptions InapplicableDataException The IsSingleCurve method can be used to determine if the AnalyticalModel can be expressed by a single curve Code Region 29 12 Getting the curve for a structural column public void GerColunnCurve Pemilyinstance camalyinse j gee inealyverealMedal recon Ss ici b column sog Meat lvo ss terio Ene DOLO EDS UE des pe Sola AnalyticalModel modelColumn familyInst GetAnalyticalModel eolumma should be represented by smilies cui we if modelColumn IsSingleCurve true C r colum Ur mo cea l o umi GE Gulia AES GetCurves This method is required to get the Curves of an AnalyticalModel defined by more than one curve i e Structural Wall but can be used in all cases If the AnalyticalModel can be expressed by a single curve this method will return a List containing only one Curve If the AnalyticalModel can be expressed by a single point this method will return a Curve of almost O length containing the point This method takes an AnalyticalCurveType enum as a parameter The possible values are e RawCurves Base Analytical Model curves generated e ActiveCurves Curves displayed on screen not including Rigid Links e ApproximatedCurves Curves approximated using linear segments The following values related to Rigid Links are also available See the Rigid Links section later in this chapter for more information e R
106. returns a BoundingBoxXYZ object The CropBox Min and CropBox Max points are marked in the previous picture Note that the CropBox Min point in a perspective view is generated by projecting the crop box front clip plane onto the back clip plane Crop box coordinates are based on the viewing coordinate system Use Transform OfPoint to transform CropBox Min and CropBox Max to the world coordinate system For more detail about Transform refer to Geometry Transform in the Geometry section The project plane plus the front and back clip plane are all plumb to the view direction The line between CropBox Max and CropBox Min is parallel to the view direction With these factors the crop box geometry can be calculated View OutLine Max Crop Regin il F RE OBS Figure 97 Perspective 3D view The previous picture shows the projection plane on screen after cropping The crop region is the rectangle intersection of the projection plane and crop box e Geometry information is retrieved using the View CropRegion property This property returns a BoundingBoxUV instance e The View OutLine Max property points to the upper right corner e The View OutLine Min property points to the lower left corner e Like the crop box the crop region coordinates are based on the viewing coordinate system The following expressions are equal View CropBox Max X Y View OutLine Max X Y View CropBox Min X Y View OutLine Min X Y Since the size of an o
107. system is created from a selected piece of mechanical equipment such as a fan and all selected Air Terminals Code Region 30 4 Creating a new mechanical system view plaincopy to clipboardprint 1 create a connector set for new mechanical system 2 ConnectorSet connectorSet new ConnectorSet 3 Base equipment connector 4 Connector baseConnector null 5 6 Select a Parallel Fan Powered VAV and some Supply Diffusers 7 prior to running this example 8 ConnectorSetIterator csi null 9 ElementSet selection document Selection Elements 10 foreach Element e in selection 11 12 if e is FamilyInstance 13 14 FamilyInstance fi e as FamilyInstance 15 Family family fi Symbol Family 16 Assume the selected Mechanical Equipment is the base equipment for new system 17 if family FamilyCategory Name Mechanical Equipment 18 19 Find the Out and SupplyAir connector on the base equipment 20 if null fi MEPModel 21 22 csi fi MEPModel ConnectorManager Connectors ForwardIterator 23 while csi MoveNext 24 25 Connector conn csi Current as Connector 26 if conn Direction FlowDirectionType Out amp amp 27 conn DuctSystemType DuctSystemType SupplyAir 28 1 29 baseConnector conn 30 break 31 32 33 3458 35 else if family FamilyCategory Name Air Terminals 36 37 add selected Air Terminals to connector
108. the same category The more you know about the Element object the easier it is to get the material For example o If you know the Element is a beam you can get the instance parameter Structural Material o If you know the element is a window you can cast it to a FamilyInstance and get the FamilySymbol After that you can get the Parameters such as Frame Exterior Material or Frame Interior Material to get the Material object If you get null try to get the Material object from the FamilySymbol Category Not all Element Materials are available in the API Walkthrough Get Window Materials The following code illustrates how to get the Window Materials Code Region Getting window materials walkthrough view plaincopy to clipboardprint 1 2 3 4 5 6 7 8 9 10 11 qe 13 14 255 16 17 18 19 20 21 22 235 24 25 26 27 6 28 29 30 314 324 33 34 353 36 345 38 39 40 public void GetMaterial Document document FamilyInstance window Materials materials document Settings Materials FamilySymbol windowSymbol window Symbol Category category windowSymbol Category Autodesk Revit DB Material frameExteriorMaterial null Autodesk Revit DB Material frameInteriorMaterial null Autodesk Revit DB Material sashMaterial null Check the paramters first foreach Parameter parameter in windowSymbol Parameters switch parameter Definition Name case Frame Exterior Mate
109. the same state for the enumerator The preferred implementation is to move the enumerator to the collection beginning before the first element This invalidates the enumerator if the collection is modified after the enumerator was created which is consistent with the MoveNext and the Current properties Collections and Iterators In the Revit Platform API Collections and Iterators are generic and type safe For example ElementSet always contains Element and can be used as follows Code Region 9 1 Using ElementSet view plaincopy to clipboardprint 1 UIDocument uidoc new UIDocument document 2 ElementSet elems uidoc Selection Elements 3 4 string info Selected elements Mn 5 foreach Autodesk Revit DB Element elem in elems 6 Ta info elem Name n 8 9 10 TaskDialog Show Revit info 11 12 info Levels in document n 13 14 FilteredElementCollector collector new FilteredElementCollector document 15 ICollection Element collection collector OfClass typeof BoundaryConditions ToElements 16 foreach Element elem in collection 17 18 you need not check null for elem 19 info elem Name n 20 2l 22 TaskDialog Show Revit info All collections implement the IEnumerable interface and all relevant iterators implement the IEnumerator interface As a result all methods and properties are implemented in the Revit Platform API and can play a role
110. the second word in compound words if it is a noun or proper adjective an e word or the words have equal weight for example E Commerce Cross Reference Pre Microsoft Software Read Write Access Run Time Do not capitalize the second word if it is another part of speech such as a preposition or other minor word for example Add in How to Take off e Capitalize user interface and application programming interface terms that you would not ordinarily capitalize unless they are case sensitive for example The fdisk command e Follow the traditional capitalization of keywords and other special terms in programming languages for example The printf function Using the EVEN and ALIGN Directives e Capitalize only the first word of each column heading Sentence Case e Always capitalize the first word of a new sentence e Do not capitalize the word following a colon unless the word is a proper noun or the text following the colon is a complete sentence e Do not capitalize the word following an em dash unless it is a proper noun even if the text following the dash is a complete sentence e Always capitalize the first word of a new sentence following any end punctuation Rewrite sentences that start with a case sensitive lowercase word Common Definitions Ribbon The horizontally tabbed user interface across the top of the application frame in Revit 2010 and later Ribbon Tab The ribbon is separated into tabs The Add Ins ribbon tab
111. three kinds of Loads e Your Analysis Link Provides suggestions for API users who want to link the Revit Structure product to certain Structural Analysis applications This chapter contains some advanced topics If you are not familiar with the Revit Platform API read the basic sections first such as Getting Started Elements Essentials Parameter and so on Topics in this section e Structural Model Elements e AnalyticalModel e AnalyticalLink e Loads e Analysis Link Structural Model Elements Structural Model Elements are literally elements that support a structure such as columns rebar trusses and so on This section discusses how to manipulate these elements Column Beam and Brace Structural column beam and brace elements do not have a specific class such as the StructuralColumn class but they are in the Familylnstance class form NoteThough the StructuralColumn StructuralBeam and StructuralBrace classes do not exist in the current API they are used in this chapter to indicate the FamilyInstance objects corresponding to structural columns beams and braces Though Structural column beam and brace are all Familylnstance objects in the API they are distinguished by the StructuralType property Code Region 29 1 Distinguishing between column beam and brace view plaincopy to clipboardprint 1 public void GetStructuralType FamilyInstance familyInstance 2 345 string message 4 switch familyInsta
112. to see how to create a form from multiple CurveByPoints objects Code Region 14 1 Creating a new CurveByPoints view plaincopy to clipboardprint ReferencePointArray rpa new ReferencePointArray XYZ xyz document Application Create NewXYZ 0 0 0 ReferencePoint rp document FamilyCreate NewReferencePoint xyz rpa Append rp xyz document Application Create NewXYZ 0 30 10 rp document FamilyCreate NewReferencePoint xyz 9 rpa Append rp CON AU BWHN BE 11 xyz document Application Create NewXYZ 0 60 0 12 rp document FamilyCreate NewReferencePoint xyz 13 rpa Append rp 15 xyz document Application Create NewXYZ 0 100 30 16 rp document FamilyCreate NewReferencePoint xyz 17 rpa Append rp 19 xyz document Application Create NewXYZ 150 0 20 rp document FamilyCreate NewReferencePoint xyz 21 rpa Append rp 23 CurveByPoints curve document FamilyCreate NewCurveByPoints rpa Figure 54 CurveByPoints curve Reference points can be created based on XYZ coordinates as in the example above or they can be created relative to other geometry so that the points will move when the referenced geometry changes These points are created using the subclasses of the PointElementReference class The subclasses are e PointOnEdge e PointOnEdgeEdgelntersection e PointOnEdgeFacelntersection e PointOnFace e PointOnPlane For example the last two lines of code in the
113. type For more information review the information at WikiHelp CRevitPreviewExtractor implements standard API functions STDMETHOD GetLocation LPWSTR pszPathBuffer DWORD cchMax DWO DY prom GOS SIA m temen Sila DWORD dwRecClrDepth IUOS atlas OTOME Ol ducci n ea ee It registers itself in the registry Revit Structure Questions Q Sometimes the default end releases of structural elements render the model unstable How can deal with this situation A The Analytical Model Check feature introduced in Revit Structure R3 can find some of these issues When importing the analytical model you are asked if you want to retain the release conditions from RST Revit Structure or if you want to set all beams and columns to fixed When re importing the model to RST always update the end releases and do not overwrite the end releases on subsequent export to analysis programs Q lam rotating the beam orientation so they are rotated in the weak direction For example the of a W14X30 is rotated to look like an H by a 90 degree rotation How is that rotation angle accessed in the API Because the location is a LocationCurve not a LocationPoint do not have access to the Rotation value so what is it need to check have a FamilyInstance element to check so what do do with it A Take a look at the RotateFramingObject example in the SDK It has examples of how to get and change the beam braces and columns rotation angle Q Ho
114. viewFamilyTypeld parameter needs to be a three dimensional ViewType Revit determines the following e Position of the viewer e How to create the viewing coordinate system using the view direction e How to create the crop box to crop the model Once the view is created you can resize the crop box to view different portions of the model You can also change the default orientation The API does not support modifying the viewing coordinate system The following code sample illustrates how to create an isometric 3D view Code Region Creating an Isometric 3D view view plaincopy to clipboardprint 1 Find a 3D view type 2 3 IEnumerable ViewFamilyType viewFamilyTypes from elem in newFilteredElementCollector document OfClass typeof ViewFamilyType 4 let type elem as ViewFamilyType 5 where type ViewFamily ViewFamily ThreeDimensional 6 select type 7 8 Create a new View3D 9 View3D view3D View3D CreateIsometric document viewFamilyTypes First Id 10 if null view3D 11 12 By default the 3D view uses a default orientation 13 Change the orientation by creating and setting a ViewOrientation3D 14 XYZ eye new XYZ 10 10 10 15 XYZ up new XYZ 0 1 1 16 XYZ forward new XYZ 1 1 27 4 18 ViewOrientation3D viewOrientation3D newViewOrientation3D eye up forward 19 view3D SetOrientation viewOrientation3D 20 3D Views SectionBox Each view has a crop box T
115. views The resulting view will be either a ViewSection ViewPlan or ViewDetail depending on the ViewFamilyType used and will appear in the corresponding node in the Project Browser Code Region ViewSection CreateCallout view plaincopy to clipboardprint 1 public ViewSection ViewSection CreateCallout Document document De ElementId parentViewId 3a ElementId viewFamilyTypeld 4 XYZ pointl 5 XYZ point2 The parent view Id parameter can be the Id of any type of View on which callouts can be created The point parameters determine the extents of the callout symbol in the parent view A reference callout is a callout that refers to an existing view When you add a reference callout Revit does not create a view in the project Instead it creates a pointer toa specified existing view Multiple reference callouts can point to the same view Code Region ViewSection CreateReferenceCallout view plaincopy to clipboardprint 1 public ViewSection ViewSection CreateReferenceCallout Document document ze ElementId parentViewld 3a ElementId viewIdToReference 4 XYZ pointl 5 XYZ point2 Creation of a reference callout is similar to creation of a callout But rather than having the Id of the ViewFamilyType for the callout as a parameter the CreateReferenceCallout method takes the Id of the view to reference The ViewFamilyType of the referenced view will be used by the new reference callout Only cropped views can be referenced un
116. wall as the following picture shows In this case the SketchPlane Name property returns a string related to that element For example in the following picture the SketchPlane Name property returns Generic 8 the same as the Wall Name property Figure 78 Pick a Plane on a wall as Work Plane Note A SketchPlane is different from a work plane because a work plane is visible and can be selected It does not have a specific class in the current API but is represented by the Element class A work plane must be defined based on a specific SketchPlane Both the work plane and SketchPlane Category property return null Although SketchPlane is always invisible there is always a SketchPlane that corresponds to a work plane A work plane is used to express a SketchPlane in text and pictures The following information applies to SketchPlane members Plane contains the SketchPlane geometric information SketchPlane sets up a plane coordinate system with Plane as the following picture illustrates ID Uniqueld Name and Plane properties return a value Parameters property is empty Location property returns a Location object Other properties return null Figure 79 SketchPlane and Plane coordinate system The following code sample illustrates how to create a new SketchPlane Code Region 17 1 Creating a new SketchPlane private SketchPlane CreateSketchPlane UIApplication application try to create a new sketch plane Are Noam ae
117. when Revit is about to print a view of the document e ViewPrinted notification just after Revit has printed a view of the document User Inteface Events The following table lists user interface events their type and whether they are available at the application and or document level Table 54 UI Event Types Event Type UlApplication ControlledApplication UlDocument ApplicationClosing pre X Applicationlnitialized single X DialogBoxShowing single X DisplayingOptionsDialog single X Idling single X ViewActivating pre X ViewActivated post X e ApplicationClosing notification when the Revit application is about to be closed e Applicationlnitialized notification after the Revit application has been initialized after all external applications have been started and the application is ready to work with documents e DialogBoxShowing notification when Revit is showing a dialog or message box e DisplayingOptionsDialog notification when Revit options dialog is displaying e idling notification when Revit is not in an active tool or transaction e ViewActivating notification when Revit is about to activate a view of the document e ViewActivated notification just after Revit has activated a view of the document Registering Events Using events is a two step process First you must have a function that will handle the event notification This function must take two parameters the first is an Object that denotes the sen
118. y External Green Blue HelloWorld Option One Option A als Tools Select External HelloWorld Properties 8 Press Fl for more help mSS The following example associates a new ContextualHelp with a push button control Pressing F1 when hovered over the push button will open the Autodesk homepage in a new browser window Code Region Contextual Help view plaincopy to clipboardprint private void AddPushButton RibbonPanel panel PushButton pushButton panel AddItem new PushButtonData HelloWorld HelloWorld D Sample HelloWorld bin Debug HelloWorld d1l1 HelloWorld CsHelloWorld as PushButton pushButton ToolTip Say Hello World ContextualHelp contextHelp new ContextualHelp ContextualHelpType Url http www autodesk com 1 2 3 4 25 6 Set ToolTip and contextual help 7 8 9 10 pushButton SetContextualHelp contextHelp 11 12 Set the large image shown on button 13 pushButton LargeImage 14 new BitmapImage new Uri D Sample HelloWorld bin Debug 39 Globe_ 32x32 png 15 The ContextualHelp class has a Launch method that can be called to display the help topic specified by the contents of this ContextualHelp object at any time the same as when the F1 key is pressed when the control is active This allows the association of help topics with user interface components inside dialogs created by an add in application Associating images with controls All of the
119. 0 31 lt summary gt D This method does most of the work of the IPerformanceAdviserRule implementation 334 It is called by PerformanceAdviser 34 It examines the element passed to it which was previously filtered by the filter 35 returned by GetElementFilter see below After checking to make sure that the 36 element is an instance it checks the FacingFlipped property of the element 275 111 38 If it is flipped it adds the instance to a list to be used later 39 lt summary gt 40 param name document gt The active document lt param gt 41 param name element gt The current element being checked lt param gt 42 public void ExecuteElementCheck Autodesk Revit DB Document document Autodesk Revit DB Element element 43 44 45 46 47 48 49 50 5l 525 534 54 955 56 945 58 595 60 61 62 63 64 65 66 67 68 69 70 71 p 73 74 75 76 23 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 TO 113 114 115 116 117 118 I a IIT 7 Py fg 7 if element is Autodesk Revit DB FamilyInstance Autodesk Revit DB FamilyInstance doorCurrent element as Autodesk Revit DB FamilyInstance if doorCurrent FacingFlipped m FlippedDoors Add doorCurrent Id lt summary gt This met
120. 1 2 Start Ext End Extension Calculation default 10 0 amp 100 01 7 End Ext Figure 184 Precast L Shaped Beam Properties b 1 6 Seat 0 6 O 1 N X Figure 185 Precast L Shaped Beam Cross Section Length 5 0 10 0 10 a g i End Extension Calculation 10 0 Start Extension Calculation 10 0 Figure 186 Precast L Shaped Beam Precast Single Tee m Family Types E x Name E x18 M Construction Start Extension default Y 012 Rename Delete Parameters Materials and Finishes Beam Material default Concrete Precast Concrete NormalW Structural Angle default 0 0000 5 aaa f Add Dimensions Modify Length default A y Y jy IA Remove Slab Depth o 2 Manufacturer Figure 187 Precast Single Tee Properties Width 8 0 Slab Depth 0 2 E ECEQ AAA Stem Width 0 3 3 4 Figure 188 Precast Single Tee Cross Section Width 8 0 io n pE m i a 2 o ui ee nem n monz m ne ee ee W 3 9 ee e uS n ELLE NE E et MEDIUS cee Nm 2x dE Figure 189 Precast Single Tee Cross Section 2 Length 5 0 m_i L Stem Width 0 3 3 4 bL H Start Extension Calculation 10 0
121. 12 Wall Reflection relationship As the previous picture shows one wall is mirrored by a reference plane The Reflection property needs the geometry plane information for the reference plane Code Region 20 8 Using the Reflection property private Transform Reflect ReferencePlane refPlane Transform mirTrans Transform get Reflection refPlane Plane ice DET Mae T SP Rotation Rotate by a specified angle around a specified axis and point Translation Translate by a specified vector Given a vector XYZ data a transformation is created as follow 1 0 O x x y z gt 0 0 y 0 0 I z Determinant Transformation determinant BasisX X BasisY X BasisZ X BasisX Y BasisY Y BasisZ Y BasisX Z BasisY Z BasisZ Z HasReflection This is a Boolean value that indicates whether the transformation produces a reflection Scale A value that represents the transformation scale Inverse An inverse transformation Transformation matrix A is invertible if a transformation matrix B exists such that A B B A identity I sl dentity Boolean value that indicates whether this transformation is an identity IsTranslation Boolean value that indicates whether this transformation is a translation Geometry Transform provides methods to perform basal matrix operations Multiply Multiplies a transformation by a specified transformation and returns the result Operator Multiplies two specified transforms ScaleBasis Scal
122. 26 Autodesk Revit UI TaskDialog Show ElementsOfWorkset message 27 Worksharing information such as the current owner and checkout status of an element can be obtained using the WorksharingUtils class It is a static class that contains utility functions related to worksharing Code Region WorksharingUtils public oid GetElementWorksharingInfo Document doc ElementId elemId Do AK eint C aprint la IF TC i 2 Be String message String Empty 4 message Element Id elemId 5 6 Element elem doc GetElement elemId Te if null elem 8 9 message Element does not exist 10 return 11 12 13 The workset the element belongs to 14 WorksetId worksetId elem WorksetId 15 message nWorkset Id worksetId ToString 16 17 Model Updates Status of the element 18 ModelUpdatesStatus updateStatus WorksharingUtils GetModelUpdatesStatus doc elemId 19 message nUpdate status updateStatus ToString 20 21 Checkout Status of the element 22 CheckoutStatus checkoutStatus WorksharingUtils GetCheckoutStatus doc elemId 23 message nCheckout status checkoutStatus ToString 24 25 Getting WorksharingTooltipInfo of a given element Id 26 WorksharingTooltipInfo tooltipInfo WorksharingUtils GetWorksharingTooltipInfo doc elemId es message nCreator tooltipInfo Creator 28 message nCurrent Owner to
123. 3 build cylindrical shape around endpoint atc List lt CurveLoop gt curveloops new List lt CurveLoop gt 5 CurveLoop circle new CurveLoop 6 7 8 For solid geometry creation two curves are necessary even for closed cyclic shapes like circles 9 circle Append m app Create NewArc point radius 0 Math PI XYZ BasisX XYZ BasisY 10 circle Append m app Create NewArc point radius Math PI 2 Math PI XYZ BasisX XYZ BasisY 11 curveloops Add circle 12 13 14 Solid createdCylinder GeometryCreationUtilities CreateExtrusionGeometry curveloops XYZ BasisZ height 15 16 return createdCylinder 17 Boolean operations The BooleanOperationsUtils class provides methods for combining a pair of solid geometry objects The ExecuteBooleanOperation method takes a copy of the input solids and produces a new solid as a result Its first argument can be any solid either obtained directly from a Revit element or created via another operation like GeometryCreationUtils The method ExecuteBooleanOperationModifyingOriginalSolid performs the boolean operation directly on the first input solid The first input must be a solid which is not obtained directly from a Revit element The property GeometryObject IsElementGeometry can identify whether the solid is appropriate as input for this method Options to both methods include the operations type Union Difference or Intersect The following example demonstra
124. 30 XYZ point ii 31 XYZ transformedPoint instTransform OfPoint point 32 33 34 foreach Edge edge in solid Edges 35 36 foreach XYZ ii in edge Tessellate 37 38 XYZ point ii 39 XYZ transformedPoint instTransform OfPoint point 40 41 A2 43 44 45 Note For more details about the retrieved geometry of family instances refer to Example Retrieving Geometry Data from a Beam Meshes A mesh is a collection of triangular boundaries which collectively forms a 3D shape Meshes are typically encountered inside Revit element geometry if those elements were created from certain import operations and also are used in some native Revit elements such as TopographySurface You can also obtain Meshes as the result of calls to Face Triangulate for any given Revit face ERES Lu Pant Pat a ge cya a 2 mr IT nL del PL x Er rra e i oe It Dai ecd A oe A o RI E cancro BET 2 ie EE ee PCIE P EE d s r M xg T ar ig P Pari s et a fyir anak A ar eet LN y ul P4 T e ai ua E 47 IT M NEU Lm E T LM RAT S zw M See ap P aot on n RS APER era Lori A mesh representing a torus The following code sample illustrates how to get the geometry of a Revit face as a Mesh Code region Extracting the geometry of a mesh view plaincopy to clipboardprint 1 private void GetTrianglesFromFace Face face 25 3 3 4 Ds Get mesh 6 Fe Mesh mesh face Triangulate 8
125. 4 trans Start 5 6 Delete existing railings 7 ICollection lt ElementId gt railingIds stairs GetAssociatedRailings 8 foreach Elementld railingId in railinglds 9 10 document Delete railingId 11 12 Find RailingType 13 FilteredElementCollector collector new FilteredElementCollector document ila ICollection lt ElementId gt RailingTypeIds collector OfClass typeof RailingType ToElementIdsElementId 15 Railing Create document stairs Id RailingTypelds First RailingPlacementPosition Treads 16 trans Commit 1251 Railings The Autodesk Revit DB Architecture Railing class represents a railing element in an Autodesk Revit project Although railings are associated with stairs they can be associated with another host such as a floor or placed in space Railings can be continuous or non continuous If they are non continuous only a limited level of access is provided Railings associated with stairs can be retrieved from the Stairs class with the GetAssociatedRailings method There are only a few properties and methods specific to railings such as the TopRail property which returns the Elementld of the top rail and Flipped which indicates if the Railing is flipped The Railing Flip method flips the railing while the RemoveHost method will remove the association between the railing and its host The following example retrieves all of the railings associated with a Stairs object and flips ea
126. 44 45 46 else 47 48 message Empty 49 50 51 TaskDialog Show Removed Users Restored message 22 0 Worksets Worksets are a way to divide a set of elements in the Revit document into subsets for worksharing There may be one or many worksets in a document The document contains a WorksetTable which is a table containing references to all the worksets contained in that document There is one WorksetTable for each document There will be at least one default workset in the table even if worksharing has not been enabled in the document The Document IsWorkshared property can be used to determine if worksharing has been enabled in the document Code Region Get Active Workset view plaincopy to clipboardprint 1 ET 3 4 5 6 7 8 9 10 The FilteredWorksetCollector is used to search filter and iterate through a set of worksets Conditions can be assigned to filter the worksets that are returned If no condition is applied this filter will access all of the worksets in the document The WorksetKind enumerator is useful for filtering worksets as shown in the following example public Workset GetActiveWorkset Document doc Get the workset table from the document WorksetTable worksetTable doc GetWorksetTable Get the Id of the active workset WorksetId activeId worksetTable GetActiveWorksetId Find the workset with that Id Workset workset worksetTable GetWorkset activel
127. 44 AS Add a sketch plane for the curves 46 SketchPlane sketchPlane 47 itemFactory NewSketchPlane document Application Create NewPlane curves 48 document Regenerate 49 50 Add the shadow curves 51 ModelCurveArray curveElements itemFactory NewModelCurveArray curves sketchPlane 52 53 Return the ids of the curves created 54 List lt ElementId gt curveElementIds new List lt ElementId gt 55 foreach ModelCurve curveElement in curveElements 56 57 curveElementIds Add curveElement Id 58 59 60 return curveElementIds 61 The utility above above can be used to compute the shadow of a given mass with respect to the current sun and shadows settings for the view ps Sentember 14 cR E Finding geometry by ray projection Referencelntersector This class allows an application to use Revit s picking tools to find elements and geometry This class uses a ray from a point in a specified direction to find the geometry that is hit by the ray The class intersects 3D geometry only and requires a 3D view on creation It is possible to use a 3D view which has been cut by a section box or which has view specific geometry and graphics options set to find intersections which would not be found in the uncut and uncropped 3D model The Referencelntersector class supports filtering the output based on element or reference type The output can be customized based on which constructor is u
128. 6 17037 9 17037 9 1343 72 Gross valume cubic ft Net volume cubicft Gross area sq ft Net area sq ft 11835 92 9295 36 309 94 11356 5 8921 58 354 96 17753 89 17757 11 17757 11 17034 76 17037 9 17037 9 Gross volume cubic ft Net volume cubicft Gross area sq ft Net area sq ft 378 47 276 47 378 47 278 47 Gross volume cubic ft Net volume cubicft Gross area sq ft Net area sq ft 191 31 131 31 765 25 765 25 Gross volume cubic ft Met volume cubicft Gross area sq ft Net area sq ft 9397 86 3606 45 3343 51 9236 01 313 78 3324 94 0 0 3148 03 8675 3 313 78 14785 36 10805 74 10859 81 9022 4 80215 6 31666 31 13942 65 9961 67 10013 99 8176 57 75525 08 29743 58 555 04 Gross volume cubic ft Net volume cubicft Gross area sq ft Net area sq ft 621 26 977 43 ao EE E LOU pns 956 43 Stairs and Railings Stairs Classes in the Revit API in the Autodesk Revit DB Architecture namespace allow access to stairs and related components such as landings and runs Stairs can be created or modified using the Revit API The Stairs class represents stairs created by component Stair elements that were created by sketch cannot be accessed as a Stair object in the API The static method Stairs IsByComponent can be used to determine if an Elementld represents stairs that were created by component Topics in this Section e Stairs Components e Ra
129. 8 return Autodesk Revit UI Result Failed 9 10 Implementing the previous external command causes the following dialog box to appear an error or warning dialog box MEE EE EE EA E RE ea QNS A A NERIS n WM NE MM POR P iy A Ait d E a bt ERE 5n SUN Mu n UN Mum DEN NN SM Un a SN un NN on un NY SS MN RSEN mn UN E nm int NUN x E a Vu it TET t n t nr i EE ON da rit run um SENSN RV ine A ECGS ton SUY S As S RN RUN den nM d 0 0 0 Jj S AR SAN IN NN LEE ey us uM NE NA No E A ir NNNM 2 o m MA Ae ei od c E e pe d t OE ER m Me alah a a m Lr rp rper y n nir NN LATI ET Den n p aes a e S A A RE RUN p EA REI A A Mo a as anti ERAN Xv voe di ndr or rent uu xd Are uy LAREN nul SERES May Mak DNA VEMM NA sare TERR ADEST NR voip ie tat D T n RO EE RAN NS RSS md en i i 1 B a CC ui M S ENS NEN ON Li i Wil yl pur i VAT Uu LYT jd kr 1 i i vmm p gm e rim mS AD E n EUR VN p rn euro d uy mS VER EAE EA C EAT o 38 ds RA AR MSN X nA E M ie TAS i s NN AE d w xm NN ur m ue M ak RAT Wind EUN un n AA A PE Ln urn vr NUES ND SARGERAS NN TRY inh REOR An ED ENSE NA PON RE meh AA A A al IR NE ay PEN vr SEE ERE RAMS E i NR Sin NM um NS UIDES TENE LUUD NARIBUS ER EAE rt Phe rud Cancel unir T RP A EP EE PR Expand gt gt new FilteredElementCollector commandData Application ActiveUIDocument Document collector OfClass typeof Wall ToElements More Ira
130. AProgram PresentationFramework 3 0 0 0 v2 0 50727 CAProgram PresentationFramework Lu 3 0 0 0 v2 0 50727 CAProgram 4 n Figure 8 Add Reference 5 Add the WindowsBase reference as well as System Xaml following similar steps as above Change the Class Name To change the class name complete the following steps 1 Inthe class view window right click Class1 to display a context menu 2 From the context menu select Rename and change the class name to CsAddPanel 3 Inthe Solution Explorer right click the Class1 cs file to display a context 4 From the context menu select Rename and change the file s name to CsAddPanel cs 5 Double click CsAddPanel cs to open it for editing Add Code The Add Panel project is different from Hello World because it is automatically invoked when Revit runs Use the lExternalApplication interface for this project The IExternalApplication interface contains two abstract methods OnStartup and OnShutdown For more information about IExternalApplication refer to Add in Integration Add the following code for the ribbon panel Code Region 2 5 Adding a ribbon panel Using Autodesk Revit UI using Autodesk Revit DB using System Windows Media Imaging class CsAddpanel Autodesk Revit UI IExternalApplication publ Autode cki Revit Ui Result md cunt UNT omniu oleis lon appl ecaro add new ribbon panel RibbonPanel ribbonPanel application CreateRibbonPanel NewRibbonPanel C
131. Accessor FailuresAccessor A FailuresAccessor object is passed to each of failure processing steps as an argument and is the only available interface to fetch information about failures in a document While reading from a document during failure processing is allowed the only way to modify a document during failure resolution is via methods provided by this class After returning from failure processing the instance of the class is deactivated and cannot be used any longer Information Available from FailuresAccessor The FailuresAccessor object offers some generic information such as e Document for which failures are being processed or preprocessed e Highest severity of failures posted in the document e Transaction name and failure handling options for transaction being finished e Whether transaction was requested to be committed or rolled back The FailuresAccessor object also offers information about specific failures via the GetFailuresMessages method Options to resolve failures The FailuresAccessor object provides a few ways to resolve failures e Failure messages with a severity of Warning can be deleted with the DeleteWarning or DeleteAllWarnings methods e ResolveFailure or ResolveFailures methods can be used to resolve one or more failures using the last failure resolution type set for each failure e DeleteElements can resolve failures by deleting elements related to the failure e Or delete all failure messages and re
132. Angle Pron Project Worlli Lo True Nurlli 30 oo oo East Figure 129 Project location information Creating and Deleting Project Locations Create new project locations by duplicating an existing project location using the Duplicate method The following code sample illustrates how to create a new project location using the Duplicate method Code Region 21 2 Creating a project location public ProjectLocation DuplicateLocation Autodesk Revit DB Document document string newName Project Location Current Locakion gt document Act liver ro l locar on Prod CCELOCAETON SCE locations document Proe tLlocations Foreca n Proe c oc eon roe eLo aeon n oeaan if projectLocation Name newName throw new Exception The name is same as a project location s name please change one return currentLocation Duplicate newName The following code sample illustrates how to delete an existing project location from the current project Code Region 21 3 Deleting a project location public void DeleteLocation Autodesk Revit DB Document document PROJECELOCaETON Current location document Activerro ectlocakion There must be val least one Preece Vecactom an ene proyect Project Locationsoet locations document rovectLocarions if 1 locations Size return Seca e Te E on if name currentLocation Name Fore dad n oseebiltio co ron proyect Location mel oca eme
133. Application Visual Basic Reporting Silverlight ASP NET Web Application Visual Basic Test WCF Class Library Visual Basic Workflow 4 Other Languages 9 ASP NET MVC 2 Web Application Visual Basic Visual Basic zm v ee pes Cva Silverlight Application Visual Dasic Database gt Test Projects EEG Silverlight Class Library Visual Basic Online Templates WCF Service Application Visual Basic ASP NET Dynamic Data Entities Web Application Visual Basic Name HelloWarld Location Or sample Solution Create new solution Solution name HelloWarld Create directory for solution Add to source control OK Cancel OK E Cancel Figure 172 New Project dialog box Add Reference and Namespace VB NET uses a process similar to CH After you create the Hello World project complete the following steps 1 Right click the project name in the Solution Explorer to display a context menu 2 From the context menu select Properties to open the Properties dialog box In the Properties dialog box click the References tab A list of references and namespaces appears 3 Click the Add button to open the Add Reference dialog box 4 Inthe Add Reference dialog box click the Browse tab Locate the folder where Revit is installed and click the RevitAPI dll For example the installed folder location might be C Program Files Autodesk Revit Architecture 2012 Program RevitAPI dll 5 Click OK to add the
134. Beechwood Brown Appearance Wood Flooring Wood Masonry Metal B Beechwood Cherry Appearance Wood Flooring Wood Metallic Paint Mirror E Beechwood colate Brown Appearance Wood Flooring Wood Miscellaneous Paint Beechwood Galliano Appearance Wood Flooring Wood bis i secc d Gro Appearan Wood Flooring Wood Roofing eechwood Groove Appearance oo ooring Woo EMT a Beechwood Gunstock Appearance Wood Flooring Wood Sitework Stone Beechwood Honey Appearance Wood Flooring Wood Stucco Wall Covering Beechwood Java Appearance Wood Flooring Wood Wall Paint ia a Figure 106 Appearance Library The Materials sample application included with the SDK shows how to set the RenderApperance property to a material selected in a dialog The dialog is populated with all the Asset objects in Application Assets FillPattern All FillPatterns in a document are available using a FilteredElementCollector filtering on class FillPatternElement A FillPatternElement is an element that contains a FillPattern while the FillPattern class provides access to the pattern name and the set of FillGrids that make up the pattern There are two kinds of FillPatterns Drafting and Model In the Ul you can only set Drafting fill patterns to Material CutPattern The fill pattern type is exposed via the FillPattern Target property The following example shows how to change the material FillPattern Code Region 19 4 Setting the fill pattern view plain
135. BoundingBoxUV is retrieved from the View Outline property which is the boundary view in the paper space view Figure 120 View outline Two points define a BoundingBoxUV e Min point The bottom left endpoint e Max point The upper right endpoint Max Min Figure 121 BoundingBoxUV Max and Min Note BoundingBoxUV cannot present a gradient rectangle as the following picture shows Figure 122 Gradient rectangle Collection Classes The API provides the following collection classes based on the items they contain Table 50 Geometry Collection Classes Class Type Corresponding Collection Classes Corresponding Iterators Edge EdgeArray EdgeArraylterator EdgeArrayArray EdgeArrayArraylterator Face FaceArray FaceArraylterator GeometryObject GeometryObjectArray GeometryObjectArraylterator Instance InstanceArray InstanceArraylterator Mesh MeshArray MeshArraylterator Reference ReferenceArray ReferenceArraylterator Solid SolidArray SolidArraylterator Double value DoubleArray DoubleArraylterator All of these classes use very similar methods and properties to do similar work For more details refer to Collection Example Retrieve Geometry Data from a Beam This section illustrates how to get solids and curves from a beam You can retrieve column and brace geometry data in a similar way The GeometryElement may contain the desired geometry as a Solid or Geometrylnstance depending on whether a beam is joined or standalone a
136. CPU Compile Debug Start Action Start projec Feferences i e Start external program C Program Files Autodesk Revit Structure 2012 Pro Resources i Start browser with URL Services 3 i Settings Start Options Figure 175 Set Debug environment 5 From the Debug menu select Toggle Breakpoint or press F9 to set a breakpoint on the following line Code Region 30 11 TaskDialog TESIS loog mo Revit y Hello Weed ob Press F5 to start the debug procedure 7 Test the debugging o On the Add Ins tab HelloWorld appears in the External Tools menu button Autodesk Revit Structu Add Ins Figure 176 HelloWorld External Tools command o Click HelloWorld to execute the program activating the breakpoint o Press F5 to continue executing the program The following system message appears HelloWorld Revit Fxm Hello World Figure 177 TaskDialog message Material Properties Internal Units Internal Database Units Isotropic Currently exposed for Generic Only Orthotropic double Description Poisson ratio Y PoissonModulusY Poisson ratio Z PoissonModulusZ Shear modulus X ShearModulusX Shear modulus Y ShearModulusY Shear modulus Z ShearModulusZ Thermal Expansion ThermalExpansionCoefficientX UT TemperalExp coefficient X double Thermal Expansion ThermalExpansionCoefficientY UT TemperalExp coefficient Y double UT TemperalExp undi andi NEN mn pre a mn u
137. Collection lt Element gt collection collector1 OfClass typeof AnalysisDisplayStyle ToElements var displayStyle from element in collection where element Name Display Style 1 select element If display style does not already exist in the document create it if displayStyle Count 0 14 AnalysisDisplayColoredSurfaceSettings coloredSurfaceSettings new AnalysisDisplayColoredSurfaceSettings coloredSurfaceSettings ShowGridLines true AnalysisDisplayColorSettings colorSettings new AnalysisDisplayColorSettings Color orange new Color 255 205 0 Color purple new Color 200 0 200 colorSettings MaxColor orange colorSettings MinColor purple AnalysisDisplayLegendSettings legendSettings new AnalysisDisplayLegendSettings legendSettings NumberOfSteps 10 legendSettings Rounding 0 05 legendSettings ShowDataDescription false legendSettings ShowLegend true FilteredElementCollector collector2 new FilteredElementCollector doc ICollection lt Element gt elementCollection collector2 0fClass typeof TextNoteType ToElements var textElements from element in collector2 where element Name LegendText select element if LegendText exists use it for this Display Style if textElements Count 0 TextNoteType textType textElements Cast TextNoteType ElementAt TextNoteType 0 legendSettings SetTextTypeld textType Id doc analysisDisplayStyle An
138. ControlPoints order 25 double computedKnots new double numKnots 26 int iKnot 0 vay 28 Start knot with multiplicity degree 1 29 double startKnot 0 0 30 double knot startKnot 31 for iKnot 0 iKnot lt order iKnot 32 33 computedKnots iKnot knot 34 abs 36 Interior knots based on chord lengths 37 double prevKnot knot 38 39 for blank iKnot lt numControlPoints iKnot 40 Last loop computes end knot but does not set interior knot 41 ae double knotIncrement 0 0 43 for int jj iKnot order jj iKnot 1 jj 44 45 knotIncrement chordLengths jjl 46 47 48 knotIncrement degree 49 knot prevKnot knotIncrement 50 if iKnot lt numControlPoints 51 computedKnots iKnot knot 52 else 53 break Leave knot set to the end knot do not increment ii 54 55 prevKnot knot 56 br 58 End knot with multiplicity degree 1 59 for blank iKnot lt numKnots iKnot 60 61 computedKnots iKnot knot 62 HermiteSpline Hermite splines are used for curves which are interpolated between a set of control points like Curve by Points and flexible ducts and pipes in MEP They are also used to represent some types of imported geometry data In the Revit API the HermiteSpline class offers access to the arrays of points tangent vectors and parameters through the ControlPoints Tangents and
139. Create a category set and insert category of wall to it CategorySet myCategories app Application Create NewCategorySet Use BuiltInCategory to get category of wall Category myCategory app ActiveUIDocument Document Settings Categories get Item BuiltInCategory OST Walls myCategories Insert myCategory Create an object On SE oeste eo smesso Categories TypeBinding typeBinding app Application Create NewTypeBinding myCategories Get the BingdingMap of current document BindingMap bindingMap app ActiveUIDocument Document ParameterBindings E eine tle clei iit ions io as ene bmeae bool typeBindOK bindingMap Insert myDefinition_CompanyName typeBinding BuLlelibparamenerGroup Ge IEI return typeBindOK Instance Binding The Autodesk Revit Parameters InstanceBinding object indicates binding between a parameter definition and a parameter in certain category instances The following diagram illustrates Instance Binding in the Walls category Once bound the parameter appears in all property dialog boxes for the instance Changing the parameter in any one instance does not change the value in any other instance Parameter Properties Parameter Type Categories Project parameter Site Can appear in schedules but nat in tags Slab Edges Specialty Equipment Shared parameter Stairs Can be shared by multiple projects and Familles exported to ODBC and Structural Beam Systems appear in
140. CreateReferenceCallout document parentViewId view Id point1 point2 ViewSheet A sheet contains views and a title block When creating a sheet view with the ViewSheet Create method a title block family symbol Id is a required parameter for the method The Autodesk Revit Document TitleBlocks property contains all title blocks in the document Choose one title block to create the sheet Code Region ViewSheet Create view plaincopy to clipboardprint i public static ViewSheet ViewSheet Create Document document ElementId titleBlockTypeId The newly created sheet has no views The ViewPort Create method is used to add views The Viewport class is used to add regular views to a view sheet i e plan elevation drafting and three dimensional To add schedules to a view use Schedulelnstance Create instead Code Region Add views to sheet view plaincopy to clipboardprint 1 public static ViewPort ViewPort Create Document document ElementId viewSheetId ElementId viewId 2 XYZ point e The XYZ location parameter identifies where the added views are located It points to the added view s center coordinate measured in inches e The coordinates O 0 are relative to the sheet s lower left corner Each sheet has a unique sheet number in the complete drawing set The number is displayed before the sheet name in the Project Browser It is convenient to use the sheet number in a view title to cross reference the sheets in your dra
141. Curve object or a LocationPoint object move the curve or the point to a new place directly Code Region 10 2 Moving using Location bool MoveUsingLocationCurve Autodesk Revit ApplicationServices Application application Wall wall Location urve wallLine wall location as Location Urve X translat ionvec inew 30 IN 20 Ws certo wallLine Move translationveci When you move the element note that the vector 10 20 0 is not the destination but the offset The following picture illustrates the wall position before and after moving 10 s pr 2D 0 Figure 30 Move a wall using the LocationCurve In addition you can use the LocationCurve Curve property or the LocationPoint Point property to move one element in Revit Use the Curve property to move a curve driven element to any specified position Many elements are curve driven such as walls beams and braces Also use the property to resize the length of the element Code Region 10 3 Moving using Curve void MoveUsingCurveParam Autodesk Revit ApplicationServices Application application Wall wall Locationcurve wallLine wall Location as Location Curve XYZ pl XYZ Zero KVL pe new AVG HUP Line newWallLine application Create NewLineBound pl p2 Change the wall line to a new line wallLine Curve newWallLine You can also get or set a curve based element s join properties with the LocationCurve JoinType property Use the LocationPoint Po
142. DB ExternalDBApplicationResult OnShutdown ControlledApplication application 5 The ControlledApplication parameter provides access to Revit database events Events and Updaters to which the database level application will respond can be registered in the OnStartup method Application and Document The top level objects in the Revit Platform API are application and document These are represented by the classes Application UlApplication Document and UlDocument e The application object refers to an individual Revit session providing access to documents options and other application wide data and settings o Autodesk Revit Ul Ul Application provides access to Ul level interfaces for the application including the ability to add RibbonPanels to the user interface and the ability to obtain the active document in the user interface o Autodesk Revit ApplicationServices Application provides access to all other application level properties e The document object is a single Revit project file representing a building model Revit can have multiple projects open and multiple views for one project o Autodesk Revit UI Ul Document provides access to Ul level interfaces for the document such as the contents of the selection and the ability to prompt the user to make selections and pick points o Autodesk Revit DB Document provides access to all other document level properties e lf multiple documents are open the active document is the on
143. Data contains information such as ConceptualConstructionType used as part of the Conceptual Energy Analytical model The MassLevel data geometry is determined by combining all the geometry of a mass into a single geometry and then taking the area of intersection with the level of the MassLevelData MassZones MassZones are created by dividing a MassEnergyAnalyticalModel into pieces by intersecting MassLevelDatas associated with a Mass FamilyInstance with the geometries of the MassEnergyAnalyticalModel associated with the same Mass Familylnstance Elementlds of the MassZones associated with a MassEnergyAnalyticalModel can be retrieved using the GetMassZonelds method MassSurfaceData From a MassEnergyAnalyticalModel you can get References to all Faces which are meaningful for it Using these references you can get the MassSurfaceData associated with each one using the GetMassSurfaceDataldForReference method MassSurfaceData holds properties and other data about a face in the MassEnergyAnalyticalModel element such as the material value and dimensions of auto generated elements such as sill height and skylight width MassSurfaceData also holds the id of the ConceptualConstructionType associated with the reference surface ConceptualConstructionType describes the conceptual physical construction and energy properties in a manner that can be understood by both the Revit BIM model and Green Building Studio Green Building XML This class has numero
144. ElementBoundarySubface gt subfaceList results GetBoundaryFaceInfo face 15 foreach SpatialElementBoundarySubface subface in subfaceList 16 17 if subfaceList Count gt 1 there are multiple sub faces that define the face 18 19 get the area of each sub face 20 double subfaceArea subface GetSubface Area 21i 22 sub faces exist in situations such as when a room bounding wall has been 23 horizontally split and the faces of each split wall combine to create the 24 entire face of the room 25 26 27 The following example calculates a room s geometry and finds its the material of faces that belong to the elements that define the room Code Region Face Material using SpatialElementGeometryCalculator view plaincopy to clipboardprint 1 public void MaterialFromFace 2 35 string s ae Document doc this Document B UIDocument uidoc new UIDocument doc 6 Room room doc GetElement uidoc Selection PickObject ObjectType Element ElementId as Room 7 8 SpatialElementBoundaryOptions spatialElementBoundaryOptions new SpatialElementBoundaryOptions 9 SpatialElementBoundaryOptions SpatialElementBoundaryLocation SpatialElementBoundaryLocation Finish 10 SpatialElementGeometryCalculator calculator new SpatialElementGeometryCalculator doc spatialElementBoundaryOptions 11 SpatialElementGeometryResults results calculator CalculateSpatialElementGeometry room 12 Soli
145. FamilyInstanceMaterial Document document FamilyInstance beam 2 3 Material material document GetElement beam StructuralMaterialld as Material 4 5 return material 6 Material and Category Only model elements can have material From the Revit Manage tab click Settings Object Styles to display the Object Styles dialog box Elements whose category is listed in the Model Objects tab have material information Object Styles Line Weight Category a Line Color Line Pattern Paon H Specialty Equipment ao o 1o Black Solid Structural Beam Systems 1 B EB RGB 000 127 000 Structural Columns 1 mi W Structural Foundations EN Black Structural Framing E E EN Black Topography Solid Site Earth E Walls EE Black Solid Default Wall 2 gt Windows 2 2 Elevation Swing Dash 1 15 1 4 mc tcn jie Paint Finish T 2 ERG 000 000 127 3 MM Black Soi OO Ho A A 0 1 oo EN Black Sold ue E 1 Trim Projection do T Black 1 1 1 1 1 1 Modify Subcategories PS Delete Te Show categories from all disciplines Ne New Delete Select All Select None Invert c Lascano too n Figure 108 Category material Only Model elements can have the Material property assigned Querying Material for a category that corresponds to other than Model elements e g Annotations or Imported will therefore always result in a null For more details about the Element an
146. Figure 23 Elementid In the Revit Platform API you can create an Elementld directly and then associate a unique integer value to the new Elementld The new Elementld value is O by default Code Region 5 3 Setting Elementid Ecc fh tener I fiis Autodesk Revit DB ElementId selectedId element Id int idInteger selectedId IntegerValue J reace amp aew 1cl aincl Sete ile wae line Autodesk Revit DB Elementld id new Autodesk Revit DB ElementId idInteger Elementid has the following uses e Use Elementld to retrieve a specific element from Revit From the Revit Application class gain access to the active document and then get the specified element using the Document GetElement Elementld method Code Region 5 4 Using Elementld Ger ae ad OE ot nee ement Autodesk Revit DB ElementId scies esci mecnm int idInteger selectedId IntegerValue estee 2 Men duel cme see wine value Autodesk Revit DB Elementld id new Autodesk Revit DB ElementId idInteger ij Cr tae elemen Autodesk Revit Dash Lenehan first document cer Irem 1d If the ID number does not exist in the project the element you retrieve is null e Use Elementld to check whether two Elements in one project are equal or not It is not recommended to use the Object Equal method Every element has a Uniqueld represented by the String storage type The Uniqueld corresponds to the Elementld However unlike Elementid Uniqueld functions like a GUID Globally Uni
147. For Windows XP C Documents and Settings All Users Application Data Autodesk Revit Addins 2012 e For Vista Windows 7 C ProgramData Autodesk Revit Addins 2012 Refer to Add in Integration for more details using manifest files Build the Program After completing the code you must build the file From the Build menu click Build Solution Output from the build appears in the Output window indicating that the project compiled without errors Debug the Program Running a program in Debug mode uses breakpoints to pause the program so that you can examine the state of variables and objects If there is an error you can check the variables as the program runs to deduce why the value is not what you might expect In the Solution Explorer window right click the HelloWorld project to display a context menu 2 From the context menu click Properties The Properties window appears 3 Click the Debug tab 4 Inthe Debug window Start Action section click Start external program and browse to the Revit exe file By default the file is located at the following path C Program Files Autodesk Revit Structure 2012 Program Revit exe VBHelloWorld Microsoft Visual Studio Administrator File Edt View Project Build Debug Team Data Tools VMware Test Window Help dra cdas 3 0 0 E E Deug anycru 2 LESE VBHeloWorld xX Berri 2 g Application Configuration Active Debug Platform Active Any
148. I OS PES lese eve Ne omis edite scm cen e Reo SINGU Register wall updater with Revit WallUpdater updater new WallUpdater application ActiveAddinld UpdaterRegistry RegisterUpdater updater Change Scope any Wall element ElementClassFilter wallFilter new ElementClassFilter typeof Wall Change type element addition UpdaterRegistry AddTrigger updater GetUpdaterId wallFilter Element GetChangeTypeElementAddition recura ccu hee sueco s Public Texten de on leubheclownol Aro de sane WIL UlliCeimeiceul Ibe oye Ibaleeiealoim ppt alo WallUpdater updater new WallUpdater application ActiveAddInId UpdaterRegistry UnregisterUpdater updater GetUpdaterId retorn Resuli su eeeded public class WallUpdater IUpdater Separe Adeline m apple Static UpdaterId m updaterIg WallType m wallType null MENS ito poe ales ene Racional dius socia ec ns o caen public WallUpdater AddInId id Me OO LG ale m updaterlid new Usdarerla meacpld new Guid FP BEBP OBZ 4006 4204 97Cli_ DIB4ZEBSS3SEFE public void Execute UpdaterData data Document doc data GerDocument Cache the wall type if m_wallType null PilteredhlenenvGolleeruor collector new EPrltercdkE lennent Collector doc colector OrClass Ey Peor Wakil eu var wallTypes from element in collector where element Name Experto Brick on emos select element if wallTypes Count lt Element gt
149. ID 102 260 OD 114 300 128 194 OD 141 300 154 051 OD 168 275 202 717 OD 219 075 254 508 OD 273 050 303 225 OD 323 850 333 400 OD 355 600 381 000 OD 406 400 Nominal 450 000 ID 428 650 OD 457 200 Nominal 500 000 ID 477 876 OD 508 000 Nominal 600 000 ID 574 700 OD 609 600 Output of previous example To add new sizes to the list use the Segment AddSize method Use Segment RemoveSize to remove a size by nominal diameter Routing Preferences Routing prefences are accessible through the RoutingPreferenceManager class An instance of this class is available from a property of the MEPCurveType class Currently only PipeType and DuctType support routing preferences The RoutingPreferenceManager manages all rules for selecting segment types and sizes as well as fitting types based on user selection criteria The RoutingPreferenceRule class manages one segment or fitting preference and instances of this class can be added to the RoutingPreferenceManager Each routing preference rule is grouped according to what type of routing item in manages The type is represented by the RoutingPreferenceRuleGroupType and includes these options Member name Description Undefined Undefined group type default initial value Segments Segment types e g pipe stocks Elbows Elbow types Junctions Junction types e g takeoff tee wye tap Crosses Cross types Transitions Transition types Note that the multi shape tra
150. ING BuiltInParameter is set through the API Code Region 28 3 Setting room bounding view plaincopy to clipboardprint public void SetRoomBounding Wall wall Parameter parameter wall get Parameter BuiltInParameter WALL ATTR ROOM BOUNDING 1 2 3 4 parameter Set 1 set Room Bounding to true 5 parameter Set 0 set Room Bounding to false 6 Notice how the roof forms the BoundarySegment for a room in the following pictures The first picture shows Level 3 in the elevation view The room is created in the Level 3 floor view The latter two pictures show the boundary of the room and the house in 3D view Figure 142 Room created in level 3 view Figure 143 Room boundary formed by roof The area boundary can only be a ModelCurve with the category Area Boundary BuiltlnCategory OST AreaSchemeLines while the boundary of the displayed room can be walls and other elements Figure 144 Wall end edge If the BoundarySegment corresponds to the curve between the room separation and wall as the previous picture shows e he Element property returns null e The Curve is not null Boundary and Transaction When you call Room GetBoundarySegments after creating an Element using the API such as a wall the wall can change the room boundary You must make sure the data is updated The following illustrations show how the room changes after a wall is created using the Revit Platform API Figure 145 Added wall chan
151. LineBound aa cc LOC e locat vom RObakelaxms Matin Ep 20 perum oid e Mirror The ElementTransformUtils class provides two static methods to mirror one or more elements in the project Table 21 Mirror Methods Member Description MirrorElement Document Elementld Plane Mirror one element about a geometric plane MirrorElements Document ICollection Elementld Plane Mirror several elements about a geometric plane There are two ways to mirror one element and two ways to mirror several elements After performing the mirror operation you can access the new elements from the Selection ElementSet The following code illustrates how to mirror a wall using a plane calculated based on a side face of the wall Code Region 10 8 Mirroring a wall public void MirrorWall Autodesk Revit DB Document document Wall wall 1 Reference reference HostObjectUtils GetSideFaces wall ShellLayerType Exterior First get one of the wall s major side faces Face face wall GetGeometryObjectFromReference reference as Face UV bboxMin face GetBoundingBox Min Vias asp Landes Dased on this side face with an Onis pe ou O a the A r directions Plane plane new Plane face ComputeNormal bboxMin tace vell vere ole o Julia Adenine 536251 1E LO 0 E ElementTransformUtils MirrorElement document wall Id plane Every FamilyInstance has a Mirrored property It indicates whether a FamilyInstance for example a column is mirrored
152. Link public void CreateLink Document doc FamilyInstance fil FamilyInstance fi2 1 PEE 35 FilteredElementCollector hubCollector new FilteredElementCollector doc 4 hubCollector OfClass typeof Hub Get all hubs 5 ICollection lt Element gt allHubs hubCollector ToElements 6 FilteredElementCollector linktypeCollector new FilteredElementCollector doc 7 linktypeCollector OfClass typeof AnalyticalLinkType 8 ElementId firstLinkType linktypeCollector ToElementIds First Get the first analytical link type 10 Get hub Ids from two selected family instance items 11 ElementId startHubId GetHub fil GetAnalyticalModel Id allHubs 12 ElementId endHubId GetHub fi2 GetAnalyticalModel Id allHubs 13 14 Transaction tran new Transaction doc Create Link 15 tran Start 16 Create a link between these two hubs 17 AnalyticalLink createdLink AnalyticalLink Create doc firstLinkType startHubId endHubId 18 tran Commit 19 205 21 Get the first Hub on a given AnalyticalModel element 22 private ElementId GetHub ElementId hostId ICollection lt Element gt allHubs 23 24 foreach Element ehub in allHubs 25 26 Hub hub ehub as Hub 27 ConnectorManager manager hub GetHubConnectorManager 28 ConnectorSet connectors manager Connectors 29 foreach Connector connector in connectors 30 31 ConnectorSet refConnectors connector AllRefs 32 foreach
153. Location Start a 28 if null sweep 29 30 move to proper place 31 XYZ transPoint1 new XYZ 11 0 0 325 document Move sweep transPoint1 33 34 else 35 36 throw new Exception Failed to create a new Sweep 375 38 39 else 40 41 throw new Exception Please open a Family document before invoking this command am 43 return sweep 44 Y Figure 50 Ovoid sweep created by previous example Assigning Subcategories to forms After creating a new form in a family you may want to change the subcategory for the form For example you may have a Door family and want to create multiple subcategories of doors and assign different subcategories to different door types in your family The following example shows how to create a new subcategory assign it a material and then assign the subcategory to a form Code Region 13 7 Assigning a subcategory view plaincopy to clipboardprint public void AssignSubCategory Document document GenericForm extrusion create a new subcategory Category cat document OwnerFamily FamilyCategory Category subCat document Settings Categories NewSubcategory cat NewSubCat create a new material and assign it to the subcategory ElementId materialId Material Create document Wood Material subCat Material document GetElement materialld as Material WO JO uUi UN HB e He HG assign the subcategory to the element extrusion Su
154. Names Add Inches 4 IList double multipliers new List double 5 multipliers Add 1 6 multipliers Add 12 7 8 9 1 AnalysisResultSchema resultSchema new AnalysisResultSchema Schema Name Description 0 resultSchema SetUnits unitNames multipliers Once the AnalysisResultschema is configured it needs to be registered using the SpatialFieldManager RegisterResult method which will return a unique index for the result Use GetResultSchema and SetResultSchema using this unique index to get and change the result after it has been registered Creating analysis results data Once a primitive has been added to the SpatialFieldManager analysis results can be created and added to the analysis results container using the UpdateSpatialFieldPrimitive method This method takes a set of domain points FieldDomainPoints where results are calculated and a set of values FieldValues for each point The number of FieldValues must correspond to the number of domain points However each domain point can have an array of values each for a separate measurement at this point The following example creates a simple set of analysis results on an element face selected by the user The SDK sample SpatialFieldGradient demonstrates a more complex use case where each point has multiple associated values Code Region 27 1 Creating Analysis Results view plaincopy to clipboardprint 1 Document doc commandData Application ActiveUIDo
155. OCs T O ae oia vesiuor A A CO Oo gt e create geometry plane Plane geometryPlane application Application Create NewPlane newNormal newOrigin create sketch plane Shen cyeus laine Ske T eine lene application ActiveUIDocument Document Create NewSketchPlane geometryPlane return skere hPlane 3D Sketch 3D Sketch is used to edit a family or create a 3D object In the Revit Platform API you can complete the 3D Sketch using the following classes e Extrusion e Revolution e Blend e Sweep In other words there are four operations through which a 2D model turns into a 3D model For more details about sketching in 2D refer to 2D Sketch Revit uses extrusions to define 3D geometry for families You create an extrusion by defining a 2D sketch on a plane Revit then extrudes the sketch between a start and an end point Query the Extrusion Form object for a generic form to use in family modeling and massing The Extrusion class has the following properties Table 40 Extrusion Properties Property Description ExtrusionStart Returns the Extrusion Start point It is a Double type ExtrusionEnd Returns the Extrusion End point It is a Double type Sketch Returns the Extrusion Sketch It contains a sketch plane and some curves The value of the ExtrusionStart and ExtrusionEnd properties is consistent with the parameters in the Revit UI The following figure illustrates the corresponding parameters and the Extrusion result El
156. OST lOSRebarSystemSpanSymbolcCtrl In this section the main focus is on the tag type represented in the following picture Scope Box a Kevnate Bv Category Room Tag Multi Category je Tag All Mot Tagged Materia E symbol de Legend Component Figure 73 IndependentTag Every category in the family library has a pre made tag Some tags are automatically loaded with the default Revit application template while others are loaded manually The IndependentTag objects return different categories based on the host element if it is created using the By Category option For example the Wall and Floor IndependentTag are respectively OST WallTags and OST FloorTags If the tag is created using the Multi Category or Material style their categories are respectively OST MultiCategoryTags and OST MaterialTags Note that NewTag only works in the 2D view or in a locked 3D view otherwise an exception is thrown The following code is an example of IndependentTag creation Run it when the level view is the active view Note You can t change the text displayed in the IndependentTag directly You need to change the parameter that is used to populate tag text in the Family Type for the Element that s being tagged In the example below that parameter is Type Mark although this setting can be changed in the Family Editor in the Revit Ul Code Region 16 5 Creating an IndependentTag view plaincopy to clipboardprint 1 private IndependentTa
157. Only allowed in schedules that Projectinfo J include elements from linked files Material In a material takeoff a parameter of one of the materials of a scheduled element In a material takeoff a value representing how a particular material is used within a scheduled element The parameter ID can be MATERIAL AREA Material aterlalQuantity MATERIAL VOLUME or MATERIAL_ASPAINT A parameter of the RevitLinklnstance that an element in a linked file belongs to Currently RVT_LINK_INSTANCE_NAME is the only supported parameter RevitLinkInstance l l l Only allowed in schedules that include elements from linked files A parameter of the RevitLinkType that an element in a linked file belongs to Currently RVT LINK FILE NAME WITHOUT EXT is the only supported RevitLinkT i i i PENE parameter Only allowed in schedules that include elements from linked files StructuralMaterial A parameter of the structural material of a scheduled element Space A parameter of the space that a scheduled element belongs to Using one of the ScheduleDefinition AddField methods will add the field to the end of the field list To place a new field in a specific location in the field list use one of the ScheduleDefinition InsertField methods Fields can also be ordered after the fact using ScheduleDefinition SetFieldOrder The following is a simple example showing how to add fields to a view if they are not already in the view schedule Code Region
158. Parameters properties The equation for the curve between two nodes in a Hermite spline is P u hog u Py uy44 Up Ay My Ro Peed Uggs us dha CUM where P and P represent the points at each node M and M the tangent vectors and u and u 4 the parameters at the nodes and the basis functions are hofu 2u 3u 1 h4g u u 2u tu hg u 2u 3u hy u u u Geometrylnstances A GeometryInstance represents a set of geometry stored by Revit in a default configuration and then transformed into the proper location as a result of the properties of the element The most common situation where Geometrylnstances are encountered is in Family instances Revit uses Geometrylnstances to allow it to store a single copy of the geometry for a given family and reuse it in multiple instances Note that not all Family instances will include GeometryInstances When Revit needs to make a unique copy of the family geometry for a given instance because of the effect of local joins intersections and other factors related to the instance placement no Geometrylnstance will be encountered instead the Solid geometry will be found at the top level of the hierarchy A GeometrylInstance offers the ability to read its geometry through the GetSymbolGeometry and GetlnstanceGeometry methods These methods return another Autodesk Revit DB GeometryElement which can be parsed just like the first level return GetSymbolG
159. Revit API class Definition Notes A plane defined by the origin and unit vectors in U and V Plane PlanarFace Radius provides the radius vectors the unit vectors of the circle multiplied by the radius value A face defined by extruding a Cylinder CylindricalFace circle along an axis Radius provides the radius vectors the unit vectors of the circle multiplied by the radius value A face defined by rotation of a line about an axis Cone ConicalFace Radius provides the unit vectors of the plane of rotation there is no radius involved A face defined by rotation of an arbitrary curve about an axis Revolved face IRevolvedFace Both curve s and point s can be A face defined by sweeping a line obtained as properties Ruled surface RuledFace between two profile curves or one profile curve and one point A face defined by Hermite Hermite face HermiteFace l interpolation between points Mathematical representations of all of the Revit face types can be found lt lt need link here gt gt Mathematical representation of face types This section describes the face types encountered in Revit geometry their properties and their mathematical representations PlanarFace A plane defined by origin and unit vectors in U and V Its parametric equation is P u v P un vn CylindricalFace A face defined by extruding a circle along an axis The Revit API provides the
160. Revit API developer Guidelines Revit 2013 Autodesk WikiHelp gt Gn o your product og REE EE g Search WikiHelp a Choose a product to m qo ae e Print Lists Share Home English Autodesk WikiHelp Programmer y Revit API y Revit Core Software API Developer s Guide This guide describes how to use the API for Revit 2013 e Introduction e Basic Interaction with Revit Elements e Revit Geometric Elements e Discipline Specific Functionality e Advanced Topics e Appendices Introduction e Welcome to the Revit Platform API e Getting Started e Add In Integration e Application and Document e Elements Essentials Welcome to the Revit Platform API All Revit based products are Parametric Building Information Modeling BIM tools These tools are similar to Computer Aided Design CAD programs but are used to build 3D models as well as 2D drawings In Revit you place real world elements like columns and walls into the model Once the model is built you can create model views such as sections and callouts Views are generated from the 3D physical model consequently changes made in one view automatically propagate through all views This virtually eliminates the need to update multiple drawings and details when you make changes to the model e Introduction to the Revit Platform API e What Can You Do with the Revit Platform API e Requirements e Install and Learn
161. Revit UI Result Failed 41 y 42 I ExternalCommandAvailability This 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 the accessibility check allows a button to be clicked when there is no active selection or when at least one wall is selected Code Region 3 5 Setting Command Availability view plaincopy to clipboardprint 1 public class SampleAccessibilityCheck IExternalCommandAvailability 2 EN Sl public bool IsCommandAvailable AutodeskAutodesk Revit UI UIApplication applicationData 4 CategorySet selectedCategories 5 os Allow button click if there is no active selection Z3 if selectedCategories IsEmpty 8 return true 9 Allow button click if there is at least one wall selected 10 foreach Category c in selectedCategories 11 12 if c Id IntegerValue int BuiltInCategory OST Walls 13 return true 14 15 return false External Application Table of contents 1 IExternalApplication Developers can add functionality through External Applications as well as External Commands Ribbon tabs and ribbon panels are customized using the External Application Rib
162. Selection You can get the selected objects from the current active document using the UlDocument Selection Elements property The selected objects are in an ElementSet in Revit From this Element set all selected Elements are retrieved The Selection object can also be used to change the current selection programmatically Alternatively the Selection GetElementids method retrieves the same set of elements as the Selection Elements property The collection returned by this method can be used directly with FilteredElementCollector to filter the selected elements Topics in this section e Changing the Selection e User Selection e Filtered User Selection Changing the Selection To modify the Selection Elements 1 Create a new SelElementSet 2 Put Elements in it 3 Set the Selection Elements to the new SelElementSet instance The following example illustrates how to change the selected Elements Code Region 7 1 Changing selected elements private void ChangeSelection Document document Mee selecres l a onm e E S eg IBI DXX eeu uidoc new DIC Dex teda document Autodesk Revi JI election ce doe edbrewm cedat oet collection Babe OE Selection TE E SOLE eT Display current number of selected elements TaskDialog Show Revit Number of selected elements collection Size ToString Create a new SelElementSet gt e lETement oet new electedklementset gt ce lh lementser Create Viola men ao clas devel e
163. Structure e Thermal Properties e Opening Walls There are four kinds of Walls represented by the WallType WallKind enumeration e Stacked e Curtain e Basic e Unknown The Wall and WallType class work with the Basic wall type while providing limited function to the Stacked and Curtain walls On occasion you need to check a Wall to determine the wall type For example you cannot get sub walls from a Stacked Wall using the API WallKind is read only and set by System Family The Wall Flipped property and Wall flip method gain access to and control Wall orientation In the following examples a Wall is compared before and after calling the flip method e The Orientation property before is 0 0 1 0 0 0 e The Orientation property after the flip call is 0 0 1 0 0 0 e The Wall Location Line WALL KEY REF PARAM parameter is 3 which represents Finish Face Interior in the following table e Taking the line as reference the Wall is moved but the Location is not changed J o S Figure 33 Original wall A il th H Figure 34 Wall after flip Table 24 Wall Location Line Location Line Value Description 0 Wall Centerline 1 Core Centerline 2 Finish Face Exterior 3 Finish Face Interior 4 Core Face Exterior 5 Core Face Interior There are five static override methods in the Wall class to create a Wall Table 25 Create Overrides Name Description Create Document Curve WallType Level Doub
164. Structure and Revit MEP are specific to Architecture Structure and MEP respectively QJ M Revit GUI GUI API ota Loh PAGGO ur 0 02 a U E RAC API RST API REVIT REVIT Architecture Structure REVIT API REVIT Platform Figure 11 Revit RevitAPI and Add ins To create a RevitAPI based add in you must provide specific entrypoint types in your add in DLL These entrypoint classes implement interfaces either IExternalCommand IExternalApplication or IExternalDBApplication In this way the add in is run automatically on certain events or in the case of IExternalCommand and IExternalApplication manually from the External Tools menu button IExternalCommand IExternalApplication IExternalDBApplication and other available Revit events for add in integration are introduced in this chapter External Commands Developers can add functionality by implementing External Commands which appear in the External Tools menu button and Running External Commands When no other commands or edit modes are active in Revit registered external commands are enabled When a command is selected a command object is created and its Execute method is called Once this method returns back to Revit the command object is destroyed As a result data cannot persist in the object between command executions Howev
165. TEINS TORONTO INI Oriel ol Sie TE alo String prompt Show parameters in selected Element StringBuilder st new StringBuilder iterate element s parameters foreach Parameter para in element Parameters st AppendLine GetParameterInformation para document Give the user some information MessageBox Show prompt Revit MessageBoxButtons OK String GetParameterInformation Parameter para Document document suas eeu News Jena IDiesara deas eere ome NAMe a Ch Vien Use direret mer nod to Ger parameter data according Eo Ene storage type Switch para StorageType case StorageType Double Icomos ividlesie tiene Wheicis ie derName r 9 2 Operis t o Ic QU break case StorageType Elementld Line Ole he mane On the elenen Elementld id para AsElementId if id Value gt 0 def Name t 1 Eee ee dese cero lemon ret stoi Name else derName Sta Value loser break case etoceage le lincecec if ParameterType YesNo para Definition ParameterType if para AsInteger 0 A ar E I m IM else det Name e else defName para AsInteger ToString break case StorageType String defName para AsString break default defName Unexposed parameter break return defName Slow parameters selected Elenek Length 51 0 Base coHFscE 0 O Ares 1020 00 oF Phase Created Mew Construction Top onzkrainE
166. TUI lib eS e STE I eec hc given Owe lime La eae ocurren Oe e e Ome Lame Ourline y CUA Mew Cublinetmew xy 407 07 0 mew MO MOOT NOS Eicus ch POUN lso Minima cee lS Melee abe er elas Oe le Us s a minimum and maximum OY ZR ORIS Es OSTSEE SIE IRI the outline BoundingBoxIntersectsFilter filter new BoundingBoxIntersectsFilter myOutLn PAPI bi lwer worvrne elements wim she tai e ele mE TS SNC pexclhucdes aio beses Cera ved iwom Vilew anc Ooogeces Com es imeem qe Bi Tice exous liene CoL dieere collector me Ies Toe cue es eue Jom esee Collector document IList lt Element gt elements collector WherePasses filter ToElements enaa a GP don Teseo Uno O se ana eme cien to match elements Use choreo out commnand Or JE se qe o rind melts ie alk BoundingBoxIntersectsFilter invertFilter new BoundingBoxIntersectsFilter myOutLn true collector new FilieredElementCollector document IList Element notIntersectWalls collector OfClass typeof Wall WherePasses invertFilter ToElements The next example uses an exclusion filter to find all walls that are not currently selected in the document Code Region 6 3 Creating an exclusion filter Find all walls that are not currently selected j Gecrali element ads whiten ere cuercent selected by Users exclude these ids when filtering ICollection ElementId excludes new List lt Elementld gt ElementSetIterator elemIter uiDocument Selection Elem
167. Tags Window Tags Wire Tag Zone Tags Material Tags NewTag View Element Boolean TagMode TagMode should be TM ADDBY MATERIAL and there should be a material tag family TagOrientation XYZ loaded otherwise exception will be thrown Multi Category Tags NewTag View Element Boolean TagMode TagMode should be TM_ADDBY_MULTICATEGORY and there should be a multi category TagOrientation XYZ tag family loaded otherwise exception will be thrown Generic Annotations NewAnnotationSymbol XYZ AnnotationSymbolType View Title Blocks NewViewSheet FamilySymbol The titleblock will be added to the newly created sheet Families and family symbols are loaded using the Document LoadFamily or Document LoadFamilySymbol methods Some families such as Beams have more than one endpoint and are inserted in the same way as a single point instance Once the linear family instances are inserted their endpoints can be changed using the Element Location property For more information refer to Code Samples Code Samples Review the following code samples for more information about working with Family Instances Please note that in the NewFamilyInstance method a StructuralType argument is required to specify the type of the family instance to be created Here are some examples Table 34 The value of StructuralType argument in the NewFamilyl nstance method Type of Family Instance Value of StructuralType Doors tables etc NonStructural Beams Beam B
168. Tags NewTag View Element Boolean TagMode TagMode should be TM ADDBY CATEGORY and there should be a related tag family Area Load Tags TagOrientation XYZ loaded when try to create a tag otherwise exception will be thrown Area Tags Casework Tags Ceiling Tags Communication Device Tags Curtain Panel Tags Data Device Tags Detail Item Tags Door Tags Duct Accessory Tags Duct Fitting Tags Duct Tags Electrical Equipment Tags Electrical Fixture Tags Fire Alarm Device Tags Flex Duct Tags Flex Pipe Tags Floor Tags Furniture System Tags Furniture Tags Generic Model Tags Internal Area Load Tags Internal Line Load Tags Internal Point Load Tags Keynote Tags Lighting Device Tags Lighting Fixture Tags Line Load Tags Mass Floor Tags Mass Tags Mechanical Equipment Tags Nurse Call Device Tags Parking Tags Pipe Accessory Tags Pipe Fitting Tags Pipe Tags Planting Tags Plumbing Fixture Tags Point Load Tags Property Line Segment Tags Property Tags Railing Tags Revision Cloud Tags Roof Tags Room Tags Security Device Tags Site Tags Space Tags Specialty Equipment Tags Spinkler Tags Stair Tags Structural Area Reinforcement Tags Structural Beam System Tags Structural Column Tags Structural Connection Tags Structural Foundation Tags Structural Framing Tags Structural Path Reinforcement Tags Structural Rebar Tags Structural Stiffener Tags Structural Truss Tags Telephone Device Tags Wall
169. Text e Annotation Symbol Dimensions and Constraints e The Dimension class represents permanent dimensions and dimension related constraint elements Temporary dimensions created while editing an element in the UI are not accessible Spot elevation and spot coordinate are represented by the SpotDimension class The following code sample illustrates near the end how to distinguish permanent dimensions from constraint elements Code Region 16 1 Distinguishing permanent dimensions from constraints view plaincopy to clipboardprint 1 public void GetInfo Dimension Dimension dimension 2 4 3 string message Dimension 4 Get Dimension name 5 message nDimension name is dimension Name 6 7 Get Dimension Curve 8 Autodesk Revit DB Curve curve dimension Curve 9 if curve null 88 curve IsBound 10 11 Get curve start point AP message nCurve start point curve get EndPoint 0 X 13 curve get EndPoint 0 Y curve get EndPoint 0 Z 14 Get curve end point 15 message Curve end point curve get EndPoint 1 X 16 curve get EndPoint 1 Y curve get EndPoint 1 Z 17 18 19 Get Dimension type name 20 message nDimension type name is dimension DimensionType Name 21 2 Get Dimension view name 235 message nDimension view name is dimension View ViewName 24 255 Get Dimension reference cou
170. TransactionAttribute Autodesk Revit Attributes TransactionMode Manual 2 public class RevitCommand IExternalCommand 34 4 public Result Execute ExternalCommandData commandData D ref string messages ElementSet elements 6 7 UIApplication app commandData Application 8 Document doc app ActiveUIDocument Document 9 Transaction trans new Transaction doc ExComm 10 trans Start 11 string visiblePath ModelPathUtils GetRevitServerPrefix testmodel rvt 12 ModelPath serverPath ModelPathUtils ConvertUserVisiblePathToModelPath visiblePath 13 TransmissionData transData TransmissionData ReadTransmissionData serverPath 14 string mymessage null 15 if transData null los T7 access the data in the transData here 18 19 else 20 21 Autodesk Revit UI TaskDialog Show Unload Links 20 The document does not have any transmission data 23 24 trans Commit 25 return Result Succeeded 26 27 Way 2 Used if your program knows the local server name Not recommended as the server name may be changed by the Revit users from Revit UI e Create a ServerPath object using ServerPath constructor view plaincopy to clipboardprint i new ServerPath ServerNameOrServerIp relative path without the initial forward slash dt new ServerPath ServerNameOrServerlp relative path without the initial forward slash e Please note that the first paramet
171. Updater e GetUpdaterName This returns a name by which the Updater can be identified to the user if there is a problem with the Updater at runtime e GetAdditionallnformation This method should return auxiliary text that Revit will use to inform the end user when the Updater is not loaded e GetChangePriority This method identifies the nature of the changes the Updater will be performing It is used to identify the order of execution of updaters This method is called once during registration of the Updater e Execute This is the method that Revit will invoke to perform an update See the next section for more information on the Execute method If a document is modified by an Updater the document will store the unique Id of the updater If the user later opens the document and the Updater is not present Revit will warn the user that the 3 party updater which previously edited the document is not available unless the Updater is flagged as optional By default updaters are non optional and optional updaters should be used only when necessary The following code is a simple example of implementing the Updater interface to change the WallType for newly added walls and registering the updater in the OnStartup method It demonstrates all the key aspects of creating and using an updater Code Region 25 1 Example of implementing IUpdater public class WallUpdacerApplicarion Autodesk Revit Ul IExternmalApolicarion publ ES
172. V sheetBox Min V 2 sheetBox Min V 24 double xPosition sheetBox Max U sheetBox Min U 2 sheetBox Min U 25 26 XYZ origin new XYZ xPosition yPosition 0 2T Viewport viewport Viewport Create document viewSheet Id view3D Id origin 28 29 30 Print the sheet out 31 if viewSheet CanBePrinted 32 33 TaskDialog taskDialog new TaskDialog Revit 34 taskDialog MainContent Print the sheet 295 TaskDialogCommonButtons buttons TaskDialogCommonButtons Yes TaskDialogCommonButtons No 36 taskDialog CommonButtons buttons 37 TaskDialogResult result taskDialog Show 38 39 if result TaskDialogResult Yes 40 1 41 viewSheet Print 42 43 44 y Note You cannot add a sheet view to another sheet and you cannot add a view to more than one sheet otherwise an argument exception occurs Printer Setup You may want to change the settings of the printer before printing a sheet The API exposes the settings for the printer with the PrintManager class and related Autodesk Revit DB classes Class Functionality Autodesk Revit DB PrintManager Represents the Print information in Print Dialog File gt Print within the Revit UI Autodesk Revit DB PrintParameters An object that contains settings used for printing the document Autodesk Revit DB PrintSetup Represents the Print Setup File gt Print Setup within the Revit UI Autodesk Revit DB PaperSize An object that repres
173. View view plaincopy to clipboardprint 1 ViewSection CreateElevationView Document document FamilyInstance beam 2 1 3 Find an elevation view type 4 IEnumerable ViewFamilyType viewFamilyTypes from elem in new FilteredElementCollector document OfClass typeof ViewFamilyType Da let type elem as ViewFamilyType 6 where type ViewFamily ViewFamily Elevation 7 select type 8 9 LocationCurve lc beam Location as LocationCurve 10 XYZ xyz lc Curve get EndPoint 0 11 ElevationMarker marker ElevationMarker CreateElevationMarker document viewFamilyTypes First Id xyz 1 125 ViewSection elevationView marker CreateElevation document document ActiveView Id 1 13 14 return elevationView 15 The ElevationMarker CreateElevation method takes an id of a ViewPlan as a parameter That is the ViewPlan in which the ElevationMarker is visible The new elevation ViewSection will derive its extents and inherit settings from the ViewPlan The last parameter is the index on the ElevationMarker where the new elevation view will be placed The index on the ElevationMarker must be valid and unused The view s direction is determined by the index Callouts and Reference Callouts A callout shows part of another view at a larger scale Callout views can be created using the static method ViewSection CreateCallout Callouts can be created in FloorPlan CeilingPlan StructuralPlan Section Elevation Drafting and Detail
174. a Nor Eso une la Angles are in radians when coming from Revit API so we convert to degrees for display const double angleRatio Math PI 180 LV Emme Le Cu ecd sE CS SiteLocation site proj ctl Location ott choca nem promot Nair 4e a a e n prompt n t t Latitude site Latitude angleRatio pa Tt ie eye honed wade i Ub I OIN de an lero PRI ne Zone tnt ea odes lame eine Jd Give ume user some Larco men Lon icerum wa E vts Wee TIE Note There is only one active project location at a time To see the result after changing the ProjectLocation geographical offset and rotation change the Orientation property from Project North to True North in the plan view Properties dialog box Ivisibility Graphics Overrides 1 Edt 1 Model Graphics Style GMMR 0 00000 lAdvancec Model Graphics La Orientation Wall Join Display EA Discipline Color Scheme Ce Identity Data Figure 127 Set orientation value in plan view Properties dialog box A gt e Figure 128 Project is rotated 30 degrees from Project North to True North Manage Place and Locations Locations lised For nrismnbaFinmn and posibinm at Fhe perojert nn Fhie site and in relarion Fo other bulldings There may be many Shared Locations defined In one project Locations defined in this project Infernal criirrent Duplicate Rename Dalata Make Current
175. a family and add and modify types and their parameters The following example shows how to add a new type set its parameters and then assign the new type to a FamilyInstance Type editing is done on the current type by using the Set function The current type is available from the CurrentType property The CurrentType property can be used to set the current type before editing or use the NewType function which creates a new type and sets it to the current type for editing Note that once the new type is created and modified Document LoadFamily is used to load the family back into the Revit project to make the new type available Code Region 13 12 Editing Family Types public void EditFamilyTypes Document document FamilyInstance familyInstance example works best when familyInstance is a rectangular concrete element dde a ue TR EIS TE o CE Or vam 65 Get family associated with this Hana acum doc E A vell idee peut ene o Ee 12 eure by O Get Family document tor family Document camlyDoc document Edith anily family Te E Goro mal D ore FamilyManager familyManager familyDoc FamilyManager add a new type and edit its parameters FamilyType newFamilyType familyManager NewType 2X2 ji MOOK Ove taney par aeter S samc Sek neni tos Eee FamilyParameter familyParam familyManager get_Parameter b Sie Gauci a ieee mese Dun Fama Mn Si e IE Stk dele coe e 24 Ue j Ee wide eue ace eine el O
176. ab Source element is a Floor and there is one space adjacency and it is below grade nteriorFloor Source element is a Floor and there are two space adjacencies or the type Function parameter is set to Interior Roof Source element is a Roof or a Ceiling and there is one space adjacency UndergroundCeiling Source element is a Roof or a Ceiling and there is one space adjacency and it is below grade Ceiling Source element is a Roof or a Ceiling and there are two space adjacencies EnergyAnalysisOpening From an EnergyAnalysisOpening you can retrieve the associated parent analytical surface element The GetPolyloop method returns the opening geometry as a planar polygon A number of properties are available to obtain information about the analytical opening such as Height Width Corner and Name Similar as for analytical surfaces the analytical opening type can be obtained as a simple EnergyAnalysisOpeningType enumeration or as a gpXMLOpeningType attribute The type of the opening is based on the family category for the opening and in what element it is contained as shown in the following table Type Family Category or containing element OperableWindow Window NonSlidingDoor Door FixedSkylight Opening contained in a Roof FixedWindow Opening contained in a Curtain Wall Panel Air Opening of the category Openings Construction Modeling The Revit API allows elements to be divided into sub parts or collected into assemblies to support constructi
177. about how to gain access to these parameters through the built in parameters see Parameter in the Elements Essential section The recommended way to get project information is to use the Projectinfo properties e Fill Patterns Retrieve all Fill Patterns in the current document using a FilteredElementCollector filtering on class FillPatternElement Specific FillPatterns can be retrieved using the static methods FillPatternElement GetFillPattern Document Elementld or FillPatternElement GetFillPatternByName Document string e Object Styles Use Settings Categories to retrieve all information in Category objects except for Line Style For more details see Categories in the Elements Essentialand Material sections e Phases Revit maintains the element lifetime by phases which are distinct time periods in the project lifecycle All phases in a document are retrieved using the Document Phases property The property returns an array containing Phase class instances However the Revit API does not expose functions from the Phase class e Options The Options command configures project global settings You can retrieve an Options Application instance using the Application Options property Currently the Options Application class only supports access to library paths and shared parameters file e Area and Volume Calculations The Document Settings VolumeCalculationSetting allows you to enable or disable volume calculations and to change the room
178. access the cover settings of a host through the Autodesk Revit Elements RebarHostData object A simpler less powerful mechanism for accessing the same settings is provided through parameters Cover is defined by a named offset distance modeled as an element Autodesk Revit DB Structure RebarCoverType BoundaryConditions There are three types of BoundaryConditions e Point e Curve e Area The type and pertinent geometry information is retrieved using the following code Code Region 29 9 Getting boundary condition type and geometry view plaincopy to clipboardprint 1 public void GetInfo BoundaryConditions BoundaryConditions boundaryConditions 2 1 3 string message BoundaryConditions 4 5 Parameter param boundaryConditions get Parameter BuiltInParameter BOUNDARY CONDITIONS TYPE 6 switch param AsInteger 7 8 case 0 B XYZ point boundaryConditions Point 10 message nThis BoundaryConditions is a Point Boundary Conditions 11 message AnLocation point point X point Y point Z 12 13 break 14 case 1 15 message nThis BoundaryConditions is a Line Boundary Conditions 16 Curve curve boundaryConditions get Curve 17 Get curve start point 18 message nLocation Line start point curve get EndPoint 0 X curve get EndPoint 0 Y curve get EndPoint 0 Z sik ae 19 Get curve end point 20 message end poi
179. ach it to a wall populate it with data and retrieve the data back from the wall void otor c Datalnna T Ib Wadi well 4 leve e LoS eos Transaction eee eere sued esum oi ebsEct lt new Iransactionl wall Document tCreateandstore createSchemaAndStoreData Start SchemaBuilder schemaBuilder men semental cer asi Cua 7 2 0 0 9 0 18 D 9 S A IDC S4 152 5 Si 20 CAVA L IS D E schemaBuilder SetReadAccessLevel AccessLevel Public allow anyone to read the object exime cle eene eA eae e e escscheweUem encore rc citmci MEI Ni oue lid encon camente c See emo le ADS eo tec es aus ke wen Caste ends sb ede COL W edb EI ale ess schemaBuilder SetSchemaName WireSpliceLocation create a field to store an XYZ FieldBuilder fieldBuilder schemaBuilder AddSimpleField WireSpliceLocation typeof XY2 fieldBuilder SetUnitType UnitType UT Length fieldBuilder SetDocumentation A stored location value representing a wiring splice in a wall Schema schema schemaBuilder Finish register the Schema object Entity cnie Mew Ov anb Ie we Semele a ise El me Minin Col eel om nas ecc ellas get the field from the schema Field fieldSpliceLocation schema GetField WireSpliceLocation seu the value for Enis entity entity el XA ricldopliceLocation datalostore Display Unite DUT METERS wall SetEntity entity store the entity in the element get the data back from the wall Entity retrievedEntity wall GetEnt
180. agram shows the workflow to retrieve Element Materials Wall Floors ceilings HostObject with Category OST Ceilings and roofs HostObject with Category OST Roofs have CompoundStructure Is HostObject with CompoundsStructure Is FamilyInstance and Material parameter is in its FamilySymbol Get its FamilySymbol Find Elements included CompoundsStructureLayer Find components included If null returns find Category in the Element and SubCategory corresponding to the CompoundStructureLayer Get Material from Parameter if there is Parameter corresponds to the component Get Material from Category Material If the Parameter returns ElementId with 1 value find corresponding Category and SubCategory to the component Figure 110 Getting Element Material workflow This workflow illustrates the following process The workflow shows how to get the Material object not Autodesk Revit DB Structure StructuralMaterialType enumerated type that belongs to the element There are two element classifications when retrieving the Material o HostObject with CompoundStructure Get the Material object from the CompoundStructureLayer class Materialld property o Others Get the Material from the Parameters When you get a null Material object or an invalid Elementld with a value of Elementld InvalidElementld try the Material from the corresponding category Note that a FamilyInstance and its FamilySymbol usually have
181. ails see Editing Element Events Events are raised on certain actions such as when you save a project using Save or Save As To capture the events and respond in the application you must register the event handlers For more details see Events Document Status Several properties provide information on the status of the document e IsModifiable whether the document may be modified e IsModified whether the document was changed since it was opened or saved e IsReadOnly whether the document is currently read only or can be modified e IsReadOnlyFile whether the document was opened in read only mode e sFamilyDocument whether the document is a family document e sWorkshared whether worksets have been enabled in the document Others Document also provides other functions e ParameterBindings Property Mapping between parameter definitions and categories For more details see Shared Parameter e ReactionsAreUpToDate Property Reports whether the reactionary loads changed For more details see Loads in the Revit Structure section The UlDocument class represents an Autodesk Revit project opened in the Revit user interface Element Retrieval Retrieve selected elements using the Selection property in UlDocument This property returns an object representing the active selection containing the selected project elements It also provides UI interaction methods to pick objects in the Revit model For more details see Elements Es
182. al 39 allCategories get Item BuiltlInCategory OST WallsMembrane Material 40 break 41 case MaterialFunctionAssignment Structure 42 layerMaterial 43 allCategories get Item BuiltlInCategory OST WallsStructure Material 44 break 45 case MaterialFunctionAssignment Substrate 46 layerMaterial 47 allCategories get Item BuiltInCategory OST WallsSubstrate Material 48 break 49 case MaterialFunctionAssignment Insulation 50 layerMaterial 51 allCategories get_Item BuiltInCategory OST WallsInsulation Material 52 break 535 default 54 It 1s impossible to reach here 55 break 56 57 if null layerMaterial 58 59 CompoundStructureLayer s default Material is its SubCategory 60 layerMaterial wallMaterial 61 62 63 TaskDialog Show Revit Layer Material layerMaterial 64 65 66 Sometimes just the material from the structural layer is needed Rather than looking at each layer for the one whose function is MaterialFunctionAssignment Structure use the CompoundStructure StructuralMateriall ndex property to find the index of the layer whose material defines the structural properties of the type for the purposes of analysis Opening In the Revit Platform API the Opening object is derived from the Element object and contains all of the Element object properties and methods To retrieve all Openings in a project use Document Elementiterator to find the Ele
183. alog message Troubleshooting Q My add in application will not compile A If an error appears when you compile the sample code the problem may be with the version of the RevitAPI used to compile the add in Delete the old RevitAPl reference and load a new one For more details refer to Add Reference Q Why is there no Add Ins tab or why isn t my add in application displayed under External Tools A In many cases if an add in application fails to load Revit will display an error dialog on startup with information about the failure For example if the add in DLL cannot be found in the location specified in the manifest file a message similar to the following appears The External Command HelloWorld ts disabled because the file DXHelloWorld dll does not exist rl Do not show me this message again Figure 6 External Tools Error Message Error messages will also be displayed if the class name specified in ECClassName is not found or does not inherit from IExternalCommand However in some cases an add in application may fail to load without any message Possible causes include The add in application is compiled with a different RevitAPl version The manifest file is not found There is a formatting error in the addin manifest file Q Why does my add in application not work A Even though your add in application is available under External Tools it may not work This is most often caused by an exception in the code For ex
184. alysisDisplayStyle CreateAnalysisDisplayStyle doc Display Style 1 coloredSurfaceSettings ings else analysisDisplayStyle displayStyle Cast lt AnalysisDisplayStyle gt ElementAt lt AnalysisDisplayStyle gt 0 now assign the display style to the view doc ActiveView AnalysisDisplayStyleId analysisDisplayStyle Id colorSettings legendSett Updating Analysis Results The Revit analysis framework does not update results automatically and potentially any change to Revit model can invalidate results In order to keep results up to date API developers should use Dynamic Model Update triggers or subscribe to the DocumentChanged event to be notified when the Revit model has changed and previously calculated results may be invalid and in need of recalculation For an example showing Dynamic Model Update together with Analysis Visualization see the DistanceToSurfaces sample in the Revit SDK Conceptual Energy Analysis The Revit API provides access to the elements and objects created by Revit to perform energy analyses on conceptual design models The following classes allow you to work with this data e MassEnergyAnalyticalModel associates a mass instance with energy analytical model data and geometry e MassLevelData conceptual representation of an occupiable floor Mass Floor in a conceptual building model e MassSurfaceData holds properties and other data about a face in the MassEnergyAnalyticalModel element
185. ame click Class Library see Figure 1 Add New Project below This walkthrough assumes that the project location is D Sample 4 Inthe Name field type HelloWorld as the project name 5 Click OK Recent Templates NET Framework 4 Sort by Default v E Search Installed Templates Installed Templates Type Visual C pa 2 Windows Forms Application Visual C icm 4 Visual C A project for creating a C class library Windows Hs dll Y NPF Applicatio ual C3 x WPF Application Visual C Office Cloud e Console Application Visual Reporting Silverlight 2 ASP NET Web Application Visual WCF cf Class Library Visual C Workflow Other Languages 2 ASP NET MVC 2 Web Application Visual C Other Project Types peus El Silverlight Application Visual Test Projects e Online Templates Silverlight Class Library Visual C WCF Service Application Visual C ASP NET Dynamic Data Entities Web Application Visual Mame Hello World Location Ori sample F Solution Create new solution Solution name HelloWarld C eate directory for solution Add te source control Figure 1 Add New Project Add References 1 To add the RevitAPI reference o From the View menu select Solution Explorer if the Solution Explorer window is not open o Inthe Solution Explorer right click References to display a context menu o From the context menu click Add Reference The Add Reference dialog box appears
186. ample Code Region 2 3 Exceptions in Execute Command IExternalCommand Ae men Elo ia e public IExternalCommand Result Execute om Class A ee The following two exceptions clearly identify the problem e Anerror in line x e Anexception is thrown in the Execute method Revit will display an error dialog with information about the uncaught exception when the command fails Command Failure for External Command Revit could not complete the external command Contact the provider of the external command for help v Show details Figure 7 Unhandled exception in External Command This is intended as an aid to debugging your command commands deployed to users should use try catch finally in the example entry method to prevent the exception from being caught by Revit Here s an example Code Region 2 4 Using try catch in execute public IExternalCommand Result Execute ExternalCommandData commandData ref string message ElementSet elements ExternalCommandData cdata commandData Autodesk Revit ApplicationServices Application app cdata Application LEN i io BDE sou SEDE dE Catch Exception ex Message Ex Mes Seca returno AUO eok e wie DIES ee oule S Ies lec ene xblEOOIe sies serae y DIE ese sb S Sueleeeeleo Walkthrough Add Hello World Ribbon Panel In the Walkthrough Hello World section you learn how to create an add in application and
187. an Annotation Element the specific view is available using RoomTag View Never try to set the RoomTag Name property because the name is automatically assigned otherwise an exception is thrown Creating a room The following code illustrates the simplest way to create a room at a certain point in a specific level Code Region 28 1 Creating a room view plaincopy to clipboardprint 1 Room CreateRoom Autodesk Revit DB Document document Level level Lal 3 Create a UV structure which determines the room location 4 UV roomLocation new UV 0 0 5 6 Create a new room 7 Room room document Create NewRoom level roomLocation 8 if null room 9 10 throw new Exception Create a new room failed 11 125 13 return room 14 Rooms can be created in a room schedule then inserted into a plan circuit e The Document NewRoom Phase method is used to create a new room not associated with any specific location and insert it into an existing schedule Make sure the room schedule exists or create a room schedule in the specified phase before you make the call e The Document NewRoom Room room PlanCircuit circuit method is used to create a room from a room in a schedule and a PlanCircuit o The input room must exist only in the room schedule meaning that it does not display in any plan view o After invoking the method a model room with the same name and number is created in the view where the PlanCircuit is
188. and Area parameter These parameters are always read only because they depend on the element s internal state Value Parameter Room Bounding E 1 E A k A gt m El at Pi LO 113 mm Structural Structural Usage Non bearinc Dimensions F mnm AE dla Figure 29 Wall computed parameters In this code sample the Sill Height parameter for an opening is adjusted which results in the Head Height parameter being re computed Code Region 8 6 Parameter relationship example opening should be an opening such as a window or a door public void ShowParameterRelationship FamilyInstance opening M get the original Sill Height and Head Height parameters fom che epenimg Parameter sillPara opening get Parameter BuiltInParameter INSTANCE SILL HEIGHT PARAM Parameter headPara opening get Parameter BuiltInParameter INSTANCE HEAD HEIGHT PARAM double sillHeight sillPara AsDouble double origHeadHeight headPara AsDouble Change tne Ss eno conil s oncdemboti cesta Head Hellgate ls recaleulazed gill Parat oet subter 2 0 double newHeadHeight headPara AsDouble MessageBox Show Old head height origHeadHeight new head height newHeadHeight Adding Parameters to Elements In the Revit Platform API you can use all of the defined parameters and you can add custom parameters that you define using the Revit user interface and the Revit Platform API For more details
189. angeTypeGeometry e Changing value of a specific parameter via Element GetChangeTypeParameter e Anychange of element via Element GetChangeTypeAny Note that geometry changes are triggered due to potentially many causes like a change of element type modification of properties and parameters move and rotate or changes imposed on the element from other modified elements during regeneration Also note that the last option any change of element only triggers the Updater for modifications of pre existing elements and does not trigger the Updater for newly added or deleted elements Additionally when using this trigger for an instance only certain modifications to its type will trigger the Updater Changes that affect the instance itself such as modification of the instance s geometry will trigger the Updater However changes that do not modify the instance directly and do not result in any discernable change to the instance such as changes to text parameters will not trigger the Updater for the instance To trigger based on these changes the Type must also be included in the trigger s change scope Order of Execution The primary way that Revit sorts multiple Updaters to execute in the correct order is by looking at the ChangePriority returned by a given Updater An Updater reporting a priority for a more fundamental set of elements e g GridsLevelsReferencePlanes will execute prior to Updaters reporting a priority for elements driven b
190. ansaction may consist of one or more operations There are three main classes in the Revit API related to transactions Transaction SubTransaction TransactionGroup This chapter will discuss each of these classes in more depth Only the Transaction class is required to make changes to a document The other classes can be used to better organize changes Keep in mind that the TransactionMode attribute applied to the IExternalCommand definition will affect how Revit expects transactions to be handled when the command is invoked Review TransactionAttribute for more information Topics in this section e Transaction Classes e Transactions in Events e Failure Handling Options e Getting Element Geometry and AnalyticalModel Transaction Classes All three transaction objects share some common methods Table 51 Common Transaction Object Methods Method Start Commit Rollback GetStatus Description Will start the context Ends the context and commits all changes to the document Ends the context and discards all changes to the document Returns the current status of the transaction object In addition to the GetStatus method returning the current status the Start Commit and RollBack methods also return a TransactionStatus indicating whether or not the method was successful Available TransactionStatus values include Table 52 TransactionStatus values Status Uninitialized Started RolledBack Committ
191. apply to categories of elements where Category HasMaterialQuantities property is true In practice this is limited to elements that use compound structure like walls roofs floors ceilings a few other basic 3D elements like stairs plus 3D families where materials can be assigned to geometry of the family like windows doors columns MEP equipment and fixtures and generic model families Note that within these categories there are further restrictions about how material quantities can be extracted For example curtain walls and curtain roofs will not report any material quantities themselves the materials used by these constructs can be extracted from the individual panel elements that make up the curtain system Note that the volumes and areas computed by Revit may be approximate in some cases For example for individual layers within a wall minor discrepancies might appear between the volumes visible in the model and those shown in the material takeoff schedule These discrepancies tend to occur when you use the wall sweep tool to add a sweep or a reveal to a wall or under certain join conditions The SDK sample MaterialQuantities combines both the material quantity extraction tools and temporary suppression of cutting elements opening windows and doors to extract both gross and net material quantities Em ham CalculateMaterialQuantities csv Microsoft Excel Home Insert Page Layout F
192. ar to StairsRun there is a method to get all of the supports hosted by the landing The StairsLanding class has a method to create a new landing between two runs It is covered in the Creating and Editing Stairs section The StairsLandingType class represents a landing type in the Revit API The StairsLandingType class has only a couple of properties specific to it namely IsMonolithic which is true if the stairs landing is monolithic and Thickness representing the thickness of the stairs landing Supports The Revit API does not expose a class for stairs supports When getting the supports for Stairs StairsRun or a StairsLanding the supports will be generic Revit Elements The following example gets the names of all the supports for a Stairs object Code Region Getting Stairs Supports view plaincopy to clipboardprint 1 private void GetStairSupports Stairs stairs 2 1 cP ICollection lt ElementId gt supportIds stairs GetStairsSupports 4 string info Number of supports supportIds Count 5 6 int supportIndex 0 7 foreach ElementId supportId in supportIds 8 oy Supportindex 10 Element support stairs Document GetElement supportId 11 if null support DPA 13 info nName of support supportIndex support Name Tan 15 16 17 TaskDialog Show Revit info Discipline Specific Functionality Topics in this section e Revit Architecture e Revit Structure e Revit MEP Revit
193. area The internal representation will be in decimal square feet The user visible representation will be in the units that the user has chosen The parameter data should be interpreted as a whole number positive or negative The parameter type is invalid This value should not be used The parameter data represents a length The internal representation will be in decimal feet The user visible representation will be in the units system that the user has chosen The parameter data should be interpreted as a string of text For more details about ParameterType Material see Material ParameterGroup The Definition class ParameterGroup property returns the parameter definition group ID The BuiltlnParameterGroup is an enumerated type listing all built in parameter groups supported by Revit Parameter groups are used to sort parameters in the Element Properties dialog box BuiltinParameter The Revit Platform API has a large number of built in parameters defined in the Autodesk Revit Parameters BuiltInParameter enumeration see the RevitAPI Help chm file for the definition of this enumeration This enumeration has generated documentation visible from Visual Studio intellisense as shown below The documentation for each id includes the parameter name as found in the Element Properties dialog in the English version of Autodesk Revit Note that multiple distinct parameter ids may map to the same English name in those cases you must examine the para
194. arent view It is used to add more information to specific parts of the model The static ViewSection CreateDetail method is used to create a new detail ViewSection Code Region ViewSection CreateDetail view plaincopy to clipboardprint l1 public ViewSection ViewSection CreateDetail Document document ElementId viewFamilyTypeld BoundingBoxXYZ sectionBox The viewFamilyTypeld parameter is the Id for the ViewFamilyType which will be used by the new ViewSection The type needs to be a Detail ViewFamily Just as for a standard section view the sectionBox parameter is the section view crop box It provides the direction and extents which are required for the section view When a new detail ViewSection is added it will appear in the Detail Views Detail node in the Project Browser Elevation Views An elevation view is a cross section of the model where level lines are displayed An elevation view is represented by the ViewSection class However unlike the other types of section views you cannot create elevation views using a static method on the ViewSection class To create an elevation view first create an elevation marker then use the marker to generate the elevation view The newly created elevation view will appear in the Elevations Building Elevation node in the Project Browser It will be assigned a unique name The following example creates an elevation view based on the location of a beam Code Region Creating an Elevation
195. ariation A Horizontal Tabs Model Categories annotation Categories Imported Categories Filters Show model categories in this view IT Projection Surface isibilit y Lines Patterns W Boundary Conditions h F r rn Dingoes Figure 231 Horizontal Tabs Avoid more than one row of horizontal tabs If a second row is needed consider a vertical tab Variation B Vertical Tabs File Help ary ei Identific is Family r ee Distrbution bars Type t Dowels RETE d EHH nina Figure 232 Vertical Tabs Vertical tabs are useful e Inthe Left to right Layout Flow e If there are enough tabs that would force a second row in a horizontal layout Keyboard Accessibility Tab Order Pressing the tab key cycles the focus between each editable control in the dialog The general rule is left to right top to bottom The default tab stop is at the control at the topmost leftmost position in the dialog Move right until there are no more controls in the current row Move to the next row and start from the left most control moving right pe oU qM Repeat step 2 until there are no more rows Always end with the OK Cancel Apply row e Right and left arrow down and up arrows Tab and Shift tab all have the same behavior respectively Except for when the focus is on the following o List control or combo box The right left down up arrows move the cursor down up the list respectively o Gri
196. as concrete members which are automatically joined at their intersections Also elements which have no solid geometry such as Rebar will not pass this filter With ElementintersectsSolidFilter the target object is any solid This solid could have been obtained from an existing element created from scratch using the routines in GeometryCreationUtilities or the result of a secondary operation such as a Boolean operation Similar to the ElementlntersectsElementFilter this filter will not pass elements which lack solid geometry Both filters can be inverted to match elements outside the target object volume Both filters are slow filters and thus are best combined with one or more quick filters such as class or category filters Code region using Elementl ntersectsSolidFilter to match elements which block disabled egress to doors view plaincopy to clipboardprint summary Finds any Revit physical elements which interfere with the target solid region surrounding a door summary remarks This routine is useful for detecting interferences which are violations of the Americans with Disabilities Act or other local disabled access codes remarks param name doorInstance gt The door instance lt param gt param name doorAccessibilityRegion gt The accessibility region calculated to surround the approach of the door Because the geometric parameters of this region are code and do
197. atform API are represented by three objects e Family e FamilySymbol e Familylnstance Each object plays a significant role in the family structure The Family object represents an entire family such as Single Flush doors For example the Single Flush door Family corresponds to the Single Flush rfa file The Family object contains several FamilySymbols that are used to get all family symbols to facilitate swapping instances from one symbol to another The FamilySymbol object represents a specific set of family settings corresponding to a Type in the Revit UI such as 34 x80 The FamilyInstance object represents an actual Type FamilySymbol instance in the Revit project For example in the following picture the FamilyInstance is a single door in the project e Each FamilyInstance has one FamilySymbol The door is an instance of a 34 x80 e Each FamilySymbol belongs to one Family The 34 x80 symbol belongs to a Single Flush family e Each Family contains one or more FamilySymbols The Single Flush family contains a 34 x80 symbol a 34 x84 symbol a 36 x84 and so on Note that while most component elements are exposed through the API classes FamilySymbol and FamilyInstance some have been wrapped with specific API classes For example AnnotationSymbolType wraps FamilySymbol and AnnotationSymbol wraps FamilyInstance The Family class represents an entire Revit family It contains the FamilySymbols used by FamilyInstances Loading Families
198. ath is 3D or 2D Figure 89 Sweep profile sketch NoteThe ProfileSketch is perpendicular to the path Segmented sweeps are useful for creating mechanical duct work elbows Create a segmented sweep by setting two sweep parameters and sketching a path with arcs Element Properties Type Parameters Control all elements of this type Parameter value Farameter Value Graphics Ph n Instance Parameters Control selected ar to be created instance Materials and Finishes Identity Data Subcategory Rr The value of E o d EnableTrajSegmentation uu 21 property is True Maximum Segment Ange 300 The value of MaxSegmentAngle property is 30 x Figure 90 Corresponding segment settings in the UI NoteThe following information applies to segmented Sweeps e The parameters affect only arcs in the path e The minimum number of segments for a sweep is two e Change a segmented sweep to a non segmented sweep by clearing the Trajectory Segmentation check box The EnableTrajSegmentation property returns false e fthe EnableTrajSegmentation property is false the value of MaxSegmentAngle is the default 360 Figure 91 Sweep result ModelCurve ModelCurve represents model lines in the project It exists in 3D space and is visible in all views The following pictures illustrate the four ModelCurve derived classes Lines Model Lines Lines Model Lines Figure 92 ModelLine and ModelArc
199. ation 30 prompt an elevation view 31 break 32 case ViewType EngineeringPlan 33 prompt an engineering view 34 break 35 case ViewType FloorPlan 365 prompt a floor plan view 37 break 38 AET 39 default 40 break 41 42 Give the user some information 43 MessageBox Show prompt Revit MessageBoxButtons OK 44 The third way to classify views is using the ViewFamilyType class Most view creation methods required the Id of a ViewFamilyType for the new view The Id of the ViewFamilyType can be retrieved from the View GetTypeld method The ViewFamilyType ViewFamily property returns a ViewFamily enumeration which specifies the family of the ViewFamilyType and similar to the ViewType enum documented above The following example shows how to get the ViewFamily from a View Code Region Determining view type from ViewFamilyType view plaincopy to clipboardprint 1 public ViewFamily GetViewFamily Document doc View view 2 4 Ju ViewFamily viewFamily ViewFamily Invalid 4 5 ElementId viewTypeId view GetTypeId 6 if viewTypeld IntegerValue gt 1 some views may not have a ViewFamilyType 7 8 ViewFamilyType viewFamilyType doc GetElement viewTypeld as ViewFamilyType 9 viewFamily viewFamilyType ViewFamily 10 11 12 return viewFamily 13 Display Settings The view class has properties to get and set the display style settings and the detail level se
200. ation Dialog Button optional A dialog button performs an action on the dialog itself Examples include Reset and Tools for managing Favorites in an Open Dialog They should be aligned to the far left of the dialog to the right of the help button if present and should never be the default mplementation Notes e Keyboard Access each commit button should have a keyboard access key mapped to it The default button should be mapped to Enter e The close button whether it is Cancel or Close should be mapped to Esc e If Apply exists and is NOT the default button it should be mapped to Alt A Ribbon Guidelines The following are aspects of the ribbon UI that can be modified by individual API developers These guidelines must be followed to make your application s user interface Ul compliant with standards used by Autodesk Ribbon Tab Placement To make more room on the ribbon third party applications can now add ribbon controls to the Analyze tab as well as the Add Ins tab e Applications that add and or modify elements within Revit should be added to the Add Ins tab e Applications that analyze existing data within the Revit model should be added to the Analyze tab e Applications MUST NOT be added to both the Add Ins and Analyze tabs Contextual Tab Focus User Option The Revit 2012 product line contains a user option located on the User Interface tab of the Options dialog which allows users to choose whether or not to automaticall
201. ation should be located in a Slide out Panel Small button stack e The stack MUST have at least two buttons and MUST NOT exceed three e The order of the small buttons SHOULD follow most frequent on bottom to least frequent on top This is because the more frequently accessed command should be closer to the modeling window Panel Resizing and Collapsing By default panels will be placed left to right in descending order left to right based on the order in which they were installed by the customer Once the width of the combined panels exceeds the width of the current window the panels will start to resize starting from the right in the following order 1 Panels with large buttons 1 Small buttons lose their labels then 2 The panel collapses to a single large button the icon representing the panel will be the first icon on the left 2 Panels with ONLY small button stack s 1 Small buttons lose their labels and the panel label gets truncated to four characters and an ellipsis three periods in a row 2 Ifa small button stack is the left most control in a panel then the top button must have a large icon associated with it This icon will represent the panel when collapsed The About button link should be located within the main user interface and not on a ribbon panel Note Panel resizing and collapsing is handled automatically by the ribbon component Ribbon Controls Ribbon button A Ribbon button is the most basic and
202. aton Exception lt message e Message return Autodesk eya y UE S este Failed j return Au o cese evil y UE sees s Sueeeeeso After you get the selected elements you can get the properties or parameters for the elements For more information see Parameter Walkthrough Retrieve Filtered Elements You can use a filter to select only elements that meet certain criteria For more information on creating and using element filters see Iterating the Elements Collection This example retrieves all the doors in the document and displays a dialog listing their ids Code Region 2 8 Retrieve filtered elements ii Ga eeuE c illite coe cec all tae coses Ta ias ce Diae ElementClassFilter familyInstanceFilter new ElementClassFilter typeof FamilyInstance ElementCategoryFilter doorsCategoryfilter new ElementCategoryFilter BuiltInCategory OST Doors Logi o ao lAnari leer door lnstan cc skilter new LogicalAndFilter familyInstanceFilter doorsCategoryfilter EFilteredklementCollector collector new FilteredElementC Collector document ICollection Element id doors collator pMaerer eses coo seo cese ilter M e eeu els 1 SErIng promot The rds of the doors an the current document ares foreach Elementld id in doors Peon gt i Vn et bre a Give the user some information Tac kDa TO sev beso ce Add In Integration Developers add functionality by creating and implementing External Command
203. ave a bounding box inside a given outline Elements matching the input category id Elements matching the input runtime class or derived classes Elements in a particular design option Elements which are curve driven Elements which are Element types Elements matching any of a given set of categories Elements matching a given set of classes or derived classes Elements which are view specific Elements matching a given structural type All elements except the element ids input to the filter Symbols of a particular family Note The FamilySymbolFilter cannot be inverted Shortcut Method s None None None OfCategoryld OfClass ContainedInDesignOption WhereElementlsCurveDriven WhereElementlsElementType WhereElementlsNotElementType None None OwnedByView WhereElementIsViewIndependent None Excluding Note The bounding box filters exclude all objects derived from View and objects derived from ElementType The following example creates an outline in the document and then uses a BoundingBoxlntersectsFilter to find the elements in the document with a bounding box that intersects that outline It then shows how to use an inverted filter to find all walls whose bounding box do not intersect the given outline Note that the use of the OfClass method applies an ElementClassFilter to the collection as well Code Region 6 2 BoundingBoxlntersectsFilter example USE PouncingPoxinwersecus uiis Doce M emt SE EIS
204. ay phases doc Phases 5 Format the string which identifies all supported phases in the current document 6 String prompt null 7 if 0 phases Size 8 le prompt All the phases in current document list as follow 10 foreach Phase ii in phases 11 12 prompt n t 11 Name 13 IA 15 else 16 17 prompt There are no phases in current document 18 19 Give the user the information 20 TaskDialog Show Revit prompt 21 Design Options Design options provide a way to explore alternative designs in a project Design options provide the flexibility to adapt to changes in project scope or to develop alternative designs for review You can begin work with the main project model and then develop variations along the way to present to a client Most elements can be added into a design option Elements that cannot be added into a design option are considered part of the main model and have no design alternatives The main use for Design options is as a property of the Element class See the following example Code Region 15 7 Using design options void Getinfo_DesignOption Document document Ji eae che alla awe aaae m Ec A Document UiDOcC mMment solo me DUILDosumeane document Elenent oet selection Uro Eele eoan Elemen S foreach Autodesk Revit DB Element element in selection se ae Deena on erropea ox Ele ene if element DesignOption null TaskDialog S
205. ays remove attachments and edit Figure 228 Example of a task dialog using the DNSMA checkbox as an Always checkbox for one choice Where multiple are choices possible e The generic wording Always perform my current choice should be used e Command links should be used to show the available choices If buttons are used and a Cancel button is included it looks as though cancel is an option that could always be performed in future Footer Text optional Footer text is used to link to help It replaces the Help or button found on previous dialogs and will link to the same location as an existing help link On English language versions the text in the footer should read Click here to learn more The text should be written as a statement in sentence format but with no final punctuation See Figure 226 for an example of a Task Dialog with footer text Progress Bar optional rarely used In instances where a task dialog is showing progress or handling of an available option may take several seconds or more a progress bar can be used Command Links optional commonly used In task dialogs there are two ways a user can select an action command links and commit buttons Command links are used in the following situations e More than one option is available avoid situations where only one command link is shown e Anda short amount of text would be useful in helping a user determine the best choice Command links handle scenarios
206. bar Optional use this tag for ExternalCommands only The default is to show a Quick Access Toolbar button without an icon which can be confusing to users Long description of the command will be used as 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 this property and Tooltiplmage are not supplied the button will not have an extended tooltip 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 this property and Tooltiplmage are not supplied the button will not have an extended tooltip Localization setting for Text Description Largelmage LongDescription and Tooltiplmage 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 Table 3 VisibilityMode Members Member Name AlwaysVisible NotVisiblelnProject NotVisiblelnFamily Description The command is available in all possible modes supported by the Revit API The command is invisible when there is a project document active The command is invisi
207. bcategory subCat HP N 13 Creating Annotations New annotations such as Dimensions and ModelText and TextNote objects can also be created in families as well as curve annotation elements such as SymbolicCurve ModelCurve and DetailCurve See Annotation Elements TOPIC 24 for more information on Annotation elements Additionally a new Alignment can be added referencing a View that determines the orientation of the alignment and two geometry references The following example demonstrates how to create a new arc length Dimension Code Region 13 8 Creating a Dimension view plaincopy to clipboardprint 1 public Dimension CreateArcDimension Document document SketchPlane sketchPlane 2 35 Autodesk Revit Creation Application appCreate document Application Create An Line gLine1 appCreate NewLine new XYZ 0 2 0 new XYZ 2 2 0 true D Line gLine2 appCreate NewLine new XYZ 0 2 0 new XYZ 2 4 0 true 6 Arc arctoDim appCreate NewArc new XYZ 1 2 0 new XYZ 1 2 new XYZ 0 3 0 Ts Arc arcofDim appCreate NewArc new XYZ 0 3 0 new XYZ 1 2 0 new XYZ 0 8 2 8 0 8 9 Autodesk Revit Creation FamilyItemFactory creationFamily document FamilyCreate 10 ModelCurve modelCurvel creationFamily NewModelCurve gLine1 sketchPlane 11 ModelCurve modelCurve2 creationFamily NewModelCurve gLine2 sketchPlane T2 ModelCurve modelCurve3 creationFamily NewModelCurve arctoDim sketchPla
208. bject s perspective projection varies inversely with the distance from that object to the center of the projection scale is meaningless for perspective views The perspective 3D view Scale property always returns zero Isometric View A new isometric view can be created with the static View3D Createlsometric method Crop box CropBox Max a tit X ELI T a es BEE a TE ms lewer Figure 98 Parallel projection Isometric views are generated using parallel projection rays by projecting the model onto a plane that is normal to the rays The viewing coordinate system is similar to the perspective view but the crop box is a parallelepiped with faces that are parallel or normal to the projection rays The View CropBox property points to two diagonal corners whose coordinates are based on the viewing coordinate system Viewport n screen Pad Window on View plane Figure 99 Scale the window on view plane to screen viewport The model is projected onto a view plane and then scaled onto the screen The View Scale property represents the ratio of actual model size to the view size The related expressions are as follows View CropBox Max X Y View OutLine Max X Y View CropBox Min X Y View OutLine Min X Y View Scale Code Region View3D Createlsometric view plaincopy to clipboardprint i public static View3D View3D CreateIsometric Document document ElementId viewFamilyTypeld The
209. bject that includes the categories to which the parameter is bound 2 Add the binding and definition to the document using the Document ParameterBindings object The following list provides more information about the classes and methods in the previous diagram e Autodesk Revit Parameters BindingMap Class The BindingMap object is retrieved from the Document ParameterBindings property o Parameter binding connects a parameter definition to elements within one or more categories o The map is used to interrogate existing bindings as well as generate new parameter bindings using the Insert method e Parameters BindingMap Insert Definition Binding Method The binding object type dictates whether the parameter is bound to all instances or just types o A parameter definition cannot be bound to both instances and types o If the parameter binding exists the method returns false Type Binding The Autodesk Revit Parameters TypeBinding objects are used to bind a property to a Revit type such as a wall type It differs from Instance bindings in that the property is shared by all instances identified in type binding Changing the parameter for one type affects all instances of the same type Parameter Properties Parameter Type Categories C3 Project paramete Roots Can appear in schedules but not in tags Site Slab Edges Shared parameter Specialty Equipment Can be shared by multiple projects and families exported to ODEC an
210. bjects from the Dimension References property Figure 69 Linear and Radial dimension constraints Constraint elements are not view specific and can display in different views Therefore the View property always returns null In the following picture the constraint elements in the previous picture are also visible in the 3D view Figure 70 Linear and Radial dimension constraints in 3D view Although equality constraints are based on dimensions they are also represented by the Dimension class There is no direct way to distinguish linear dimension constraints from equality constraints in the API using a category or DimensionType Equality constraints return three or more References while linear dimension constraints return two or more References level ay i Level 5 MAA e i Level 2 1 MS i Figure 71 Equality constraints Note Not all constraint elements are represented by the Dimension class but all belong to a Constraints OST Constraints category such as alignment constraint Spot Dimensions Spot coordinates and spot elevations are represented by the SpotDimension class and are distinguished by category Like the permanent dimension spot dimensions are view specific The type and category for each spot dimension are listed in the following table Table 35 Spot dimension Type and Category Type Category Spot Coordinates OST SpotCoordinates Spot Elevations OST SpotElevations 12 z gr N amp 5 8 32
211. ble when there is a family document active NotVisibleWhenNoActiveDocument The command is invisible when there is no active document Table 4 Discipline Members Member Name Any Architecture Structure StructuralAnalysis MassingAndSite EnergyAnalysis Mechanical Electrical Piping MechanicalAnalysis Description The command is available in all possible disciplines supported by the Revit API The command is visible in Autodesk Revit Architecture The command is visible in Autodesk Revit Structure The command is visible when the Structural Analysis discipline editing tools are available The command is visible when the Massing and Site discipline editing tools are available The command is visible when Energy Analysis discipline editing tools are available The command is visible when the Mechanical discipline editing tools are available e g in Autodesk Revit MEP The command is visible when the Electrical discipline editing tools are available e g in Autodesk Revit MEP The command is visible when the Piping discipline editing tools are available e g in Autodesk Revit MEP The command is visible when the Mechanical Analysis discipline editing tools are available PipingAnalysis The command is visible when the Piping Analysis discipline editing tools are available ElectricalAnalysis The command is visible when the Electrical Analysis discipline editing tools are available NET Add in Utility for manifest files
212. bon panel buttons are bound to an External command IExternalApplication To add an External Application to Revit you create an object that implements the IExternalApplication interface The lExternalApplication interface has two abstract methods OnStartup and OnShutdown which you override in your external application Revit calls OnStartup when it starts and OnShutdown when it closes This is the OnStartup and OnShutdown abstract definition Code Region 3 6 OnShutdown and OnStartup public interface IExternalApplication public Aukodesk Revit UIR Sult omis curo Ue omis oie ezupuie action arr ie dte e m s public Autode k Revit Ul Result Onchucdownm UlConErolledAspli carion apolmeation The UlControlledApplication parameter provides access to certain Revit events and allows customization of ribbon panels and controls and the addition of ribbon tabs For example the public event DialogBoxShowing of UlControlledApplication can be used to capture the event of a dialog being displayed The following code snippet registers the handling function that is called right before a dialog is shown Code Region 3 7 DialogBoxShowing Event application DialogBoxShowing new EventHandler Autodesk Revit Events DialogBoxShowingEventArgs AppDialogShowing The following code sample illustrates how to use the UlControlledApplication type to register an event handler and process the event when it occurs Code Region 3 8 U
213. both ContFooting and ContFootingType except when using the GetAnalyticalModel method refer to AnalyticalModel in the Revit Structure section For example the attached wall is not available in Revit Architecture In Revit Structure the relationship between the Wall class and the ContFooting class is shown using the GetAnalyticalModelSupports method in the AnalyticalModel class For more details refer to AnalyticalModelSupport in the Revit Structure section E Brace gr Component mo Roof Ey Slab Ill Beam System i Foundation Figure 38 Wall ContFooting Modifying Slabs You can modify the form of slab based elements using the SlabShapeEditor class This class allows you to e Manipulate one or more of the points or edges on a selected slab based element e Add points on the element to change the element s geometry e Add linear edges and split the existing face of a slab into smaller sub regions e Remove the shape modifier and reset the element geometry back to the unmodified shape Here s an example of reverting a selected modified floor back to its original shape Code Region 11 2 Reverting a slab s shape view plaincopy to clipboardprint 1 private void ResetSlabShapes Autodesk Revit DB Document document 2E 3 UIDocument uidoc new UIDocument document 4 Selection choices uidoc Selection 5 ElementSet collection choices Elements 6 foreach Autodesk Revit DB Element elem in collection 7 8 Floor
214. c MyProgram Autodesk png lt TooltipImage gt lt LargeImage gt c MyProgram MyProgramlicon png lt LargeImage gt lt AddIn gt lt RevitAddIns gt A basic file adding one ExternalApplication looks like this Code Region 3 10 Manifest addin ExternalApplication lt xml vercsion 1 0 encoding uki o standalone Tno lt RevitAddiIns gt AddIn Type Application gt lt Name gt SampleApplication lt Name gt lt Assembly gt c MyProgram MyProgram d11l lt Assembly gt Acdinide6u4blis2 4272 49535 6 e261DI995107 lt 7 Edda Tas lt FullClassName gt Revit Samples SampleApplication lt FullClassName gt Mendo AnS a Vemncdoria lt VendorDescription gt Autodesk www autodesk com lt VendorDescription gt lt AddIn gt lt RevitAddIns gt A basic file adding one DB level External Application looks like this Code Region Manifest addin ExternalDBApplication lt 7 xmi version 1 0T encoding uti oT Stamcdalone noe gt lt RevitAddIns gt lt Addin Type DBApplication gt lt Assembly gt c MyDBLevelApplication MyDBLevelApplication dll lt Assembly gt Addintd DIS SEDIS 0A TAB cilio TE 00H SoC orar lt 7 Addinid lt FullClassName gt MyCompany MyDBLevelAddIn lt FullClassName gt lt Name gt My DB Level AddIn lt Name gt Vendor id gt ADok lt 7 Vendor ld lt VendorDescription gt Autodesk www autodesk com lt VendorDescription gt y Selanne RevitAddIns Multiple Addin elements may
215. ce 32 if null geomInst 33 34 Autodesk Revit DB GeometryElement transformedGeomElem geomInst GetInstanceGeometry geomInst Transform ab AddCurvesAndSolids transformedGeomElem ref curves ref solids 36 37 38 The above example uses the Familylnstance Geometry property to access the true geometry of the beam To obtain the original geometry of a family instance before it is modified by joins cuts coping extensions or other post processing use the Familylnstance GetOriginalGeometry method Note For more information about how to retrieve the Geometry Options type object refer to Geometry Options Extrusion Analysis of a Solid The utility class ExtrusionAnalyzer allows you to attempt to fit a given piece of geometry into the shape of an extruded profile An instance of this class is a single time use class which should be supplied a solid geometry a plane and a direction After the ExtrusionAnalyzer has been initialized you can access the results through the following members e The GetExtrusionBase method returns the calculated base profile of the extruded solid aligned to the input plane e The CalculateFaceAlignment method can be used to identify all faces from the original geometry which do and do not align with the faces of the calculated extrusion This could be useful to figure out if a wall for example has a slanted join at the top as would be the case if there is a join with a roof If a face i
216. ch as Autodesk Revit DB Element In C CLI Autodesk Revit Element is Autodesk Revit DB Element Since only C is used for sample code in this manual the default namespace is Autodesk Revit DB If you want to see code in Visual Basic you will find several VB NET applications in the SDK Samples directory Indexed Properties Some Revit Platform API class properties are indexed or described as overloaded in the API help file RevitAPl chm For example the Curve EndPoint property has two overloads In the text of this document these are referred to as properties although you access them as if they were methods in C code by pre pending the property name with get or set For example to use the Curve EndPoint int property overload you use Curve get_EndPoint int What s new in this release Please see the What s New section in Revit 2012 APl chm for information about changes and new features Getting Started The Revit Platform API is fully accessible by any language compatible with the Microsoft NET Framework 4 0 such as Visual C or Visual Basic NET VB NET Both Visual C and VB NET are commonly used to develop Revit Platform API applications However the focus of this manual is developing applications using Visual CH Topics in this section e Walkthroughs e Walkthrough Hello World e Walkthrough Add Hello World Ribbon Panel e Walkthrough Retrieve Selected Elements e Walkthrough Retrieve Filtered Elements Wa
217. ch railing that is the default railing that the system generates Code Region Working with Railings view plaincopy to clipboardprint 1 private void FlipDefaultRailings Stairs stairs 2 3 ICollection lt ElementId gt railingIds stairs GetAssociatedRailings a Transaction trans new Transaction stairs Document Flip Railings 5 trans Start 6 foreach Elementld railingId in railinglds 7 8 Railing railing stairs Document GetElement railingId as Railing 9 if railing IsDefault true 10 11 railing Flip 12 13 dal trans Commit 15 The Railing class has a Create method which automatically creates new railings with the specified railing type on all sides of a stairs element Railing creation is demonstrated in the Creating and Editing Stairs section The RailingType class represents the railing type used in the generation of a railing It contains a number of properties about the railing such as the height lateral offset and type of the primary and secondary handrails as well as the top rail Code Region RailingType view plaincopy to clipboardprint 1 private void GetRailingType Stairs stairs 2 3 ICollection lt ElementId gt railingIds stairs GetAssociatedRailings 4 foreach Elementld railingId in railinglds 5 6 Railing railing stairs Document GetElement railingId as Railing 7 RailingType railingType stairs Document GetElement railing GetTypeId as Rai
218. copy to clipboardprint 1 public void GetWallLayerMaterial Autodesk Revit DB Document document Wall wall 2 Su get WallType of wall 4 WallType aWallType wall WallType 5 Only Basic Wall has compoundStructure 6 if WallKind Basic aWallType Kind Te 8 9 Get CompoundStructure 10 CompoundStructure comStruct aWallType GetCompoundStructure 11 Categories allCategories document Settings Categories 2 13 Get the category OST Walls default Material 14 use if that layer s default Material is By Category 15 Category wallCategory allCategories get Item BuiltInCategory OST Walls 1635 Autodesk Revit DB Material wallMaterial wallCategory Material 17 18 foreach CompoundStructureLayer structLayer in comStruct GetLayers 19 20 Autodesk Revit DB Material layerMaterial 21 document GetElement structLayer Materialld as Material 22 23 If CompoundStructureLayer s Material is specified use default 24 Material of its Category 25 if null layerMaterial 26 27 switch structLayer Function 28 29 case MaterialFunctionAssignment Finish1 30 layerMaterial 31 allCategories get_Item BuiltInCategory OST WallsFinish1 Material 32 break 3345 case MaterialFunctionAssignment Finish2 34 layerMaterial 35 allCategories get_Item BuiltInCategory OST WallsFinish2 Material 36 break 37 case MaterialFunctionAssignment Membrane 38 layerMateri
219. copy to clipboardprint 1 public void SetFillPattern Document document Material material 2 35 FilteredElementCollector collector new FilteredElementCollector document 4 ICollection lt FillPatternElement gt fillPatternElements 5 collector OfClass typeof FillPatternElement Cast lt FillPatternElement gt ToList 6 foreach FillPatternElement fillPattern in fillPatternElements 7 8 E always set successfully 9 material CutPattern fillPattern 10 material SurfacePattern fillPattern 11 12 7 Material Management You can use filtering to retrieve all materials in the document Every Material object in the Document is identified by a unique name The following example illustrates how to use the material name to get material Code Region 19 5 Getting a material by name view plaincopy to clipboardprint 1 FilteredElementCollector elementCollector new FilteredElementCollector document 2 elementCollector WherePasses new ElementClassFilter typeof Material 3 IList Element materials elementCollector ToElements 4 5 Material floorMaterial null 6 string floorMaterialName Default Floor 7 8 foreach Element materialElement in materials 9 10 Material material materialElement as Material 11 if floorMaterialName material Name 12 13 floorMaterial material 14 break 15 16 17 if null floorMaterial 18 19 TaskDialog Show Revit
220. ct E her ainretclentatian enter of Beern A e gh ans OT Bl TT A Extension Calculation Level Figure 27 Storage type sample The following code sample shows how to check whether a parameter s value can be set to a double value based on its StorageType Code Region 8 4 Checking a parameter s StorageType public bool SetParameter Parameter parameter double value pool result ose MAS arameo nee close O ao o a Oi ie if null parameter amp amp parameter IsReadOnly SeOmecelyoS Sese eue woe joeicemereic s Se euer ed e if StorageType Double parameterType Taron mew Exes len me suorescery pes o value sue euseueune suse Cairweieeinc s Pj ise etc saul coe xe a6 ea result parameter Set value Perur recut The Set method return value indicates that the Parameter value was changed The Set method returns true if the Parameter value was changed otherwise it returns false Not all Parameters are writable An Exception is thrown if the Parameter is read only AsValueString and SetValueString AsValueString and SetValueString are Parameter class methods The two methods are only applied to value type parameters which are double or integer parameters representing a measured quantity Use the AsValueString method to get the parameter value as a string with the unit of measure For example the Base Offset value a wall parameter is a Double value Usually the value is shown a
221. ctLocations Document ActiveProjectLocation FilteredElementCollector filtering on class FillPatternElement Document Settings Materials Document Settings Categories Document Phases Load related structural settings are available in the API Document ProjectUnit Document Settings VoumeCalculationSetting Reference See the following note See Shared Parameter See Place and Locations See the following note See Materials Management See the following note See the following note See Revit Structure See Unit See the following note e Project Information The API provides the Projectinfo class which is retrieved using Document ProjectInformation to represent project information in the Revit project The following table identifies the corresponding APIs for the Project Information parameters Table 8 Projecti nformation Parameters Project Issue Date Project Status Client Name Project Address Project Name Project Number Corresponding API Projectinfo lssueDate ProjectInfo Status Projectinfo ClientName Projectinfo Address ProjectInfo Name ProjectInfo Number Built in Parameters PROJECT ISSUE DATE PROJECT STATUS CLIENT NAME PROJECT ADDRESS PROJECT NAME PROJECT NUMBER Use the properties exposed by Projectinfo to retrieve and set all strings These properties are implemented by the corresponding built in parameters You can get or set the values through built in parameters directly For more information
222. ction Vectors BasisX BasisY and BasisZ properties and Origin point provide all of the transform information The matrix formed by the four values is as follows BasisX X BasisY X BasisZ X Origin X BasisX Y BasisY Y BasisZ Y Origin Y BasisX Z BasisY Z BasisZZ Origin Z Applying the transformation to the point is as follows AYL AX AYLLY XYZ Z l BasisX X BasisY X BasisZ X Origin X BasisX Y BasisY Y BasisZ Y Origin Y x BasisX Z BasisY Z BasisZZ Origin Z The Transform OfPoint method implements the previous function The following code is a sample of the same transformation process Code Region 20 7 Transformation example jopuodba Siete a ONE Dame 247 io Wess iim I SiS 1 Cem double x TONNEN doub lio pon double TOES Means orm oasis Ol ehe old eo or danae e e ELT n o ne eoor dna ea e ZOO Eransrorm get Basis 0 XYZ bl Eransrorm get Basis 1 KMZ IS Evanston get cds 2 LAO US ie sc sigh tiene ah o dod o Paare re sico elie Xe MOIS SU Ci elie Olicl Cooreliimece eise com dia ele ney coordinate system double xlenmp EDU Fy lol a Oe One Gin double vlemnp x DPO rr cou y top Oromia Ve double zleomp x DPO Ay lol O LO SC return new XYZ xTemp yTemp zTemp The Geometry Transform class properties and methods are identified in the following sections Identity Transform the Identity 1 0 0 0 0 0 0 0 0 1 O0 Reflection Reflect a specified plane Figure 1
223. ction lt Autodesk Revit DB ElementId gt deletedIdSet document Delete idSelection if 0 deletedIdSet Count throw new Exception Deleting the selected elements in Revit failed y TaskDialog Show Revit The selected element has been removed Material chapter Material Management section Aligning Elements The ItemFactoryBase NewAlignment method can create a new locked alignment between two references These two references must be one of the following combinations These references must be already geometrically aligned as this function will not force them to become aligned If the alignment can be created a new Dimension object is 2 planar faces 2 lines line and point line and reference plane 2 arcs 2 cylindrical faces returned representing the locked alignment Otherwise an exception will be thrown The NewAlignment method also requires a view which will determine the orientation of the alignment See the CreateTruss example in the FamilyCreation folder included with the SDK Samples It has several examples of the use of NewAlignment such as locking the bottom chord of a new truss to a bottom reference plane Views Views are images produced from a Revit model with privileged access to the data stored in the documents They can be graphics such as plans or text such as schedules Each project document has one or more different views The last focused window is the active view The Autodesk
224. ctions 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 transactions 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 a name for they do not appear on the Undo menu in Revit TransactionGroup TransactionGroup allows grouping together several independent transactions which gives the owner of a group an opportunity to address many transactions at once When a transaction group is to be closed it can be rolled back which means that all previously committed transactions belonging to the group will be rolled back If not rolled back a group can be either committed or assimilated In the former case all committed 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 encl
225. cts For example a door can face the outside or the inside of a room or wall and it can be placed with the handle on the left side or the right side The following table compares door window and desk family instances Table 29 Compare Family Instances Boolean Property Door Window Fixed 36 w x 72 h X Desk CanFlipFacing True True False CanFlipHand True False False If CanFlipFacing or CanFlipHand is true you can call the flipFacing or flipHand methods respectively These methods can change the facing orientation or hand orientation respectively Otherwise the methods do nothing and return False When changing orientation remember that some types of windows can change both hand orientation and facing orientation such as a Casement 3x3 with Trim family There are four different facing orientation and hand orientation combinations for doors See the following picture for the combinations and the corresponding Boolean values are in the following table Figure 44 Doors with different Facing and Hand Orientations Table 30 Different I nstances of the Same Type Boolean Property Door 1 Door 2 Door 3 Door 4 FacingFlipped False True False True HandFlipped False True True False The work plane orientation for a FamilyInstance can be changed as well If CanFlipWorkPlane is true you can set the IsWorkPlaneFlipped property Attempting to set this property for a FamilyInstance that does not allow the work plane to be flipped will result
226. cument Document 2 UIDocument uiDoc commandData Application ActiveUIDocument 3 4 SpatialFieldManager sfm SpatialFieldManager GetSpatialFieldManager doc ActiveView 5 if null sfm SE 7 sfm SpatialFieldManager CreateSpatialFieldManager doc ActiveView 1 8 Ss 10 Reference reference uiDoc Selection PickObject ObjectType Face Select a face 11 int idx sfm AddSpatialFieldPrimitive reference 13 Face face doc GetElement reference GetGeometryObjectFromReference reference as Face 15 IList lt UV gt uvPts new List lt UV gt 16 BoundingBoxUV bb face GetBoundingBox 17 UV min bb Min 18 UV max bb Max 19 uvPts Add new UV min U min V 20 uvPts Add new UV max U max V 22 FieldDomainPointsByUV pnts new FieldDomainPointsByUV uvPts 24 List double doubleList new List double 25 IList lt ValueAtPoint gt valList new List ValueAtPoint 26 doubleList Add 27 valList Add new ValueAtPoint doubleList 28 doubleList Clear 29 doubleList Add 1 30 vallist Add new ValueAtPoint doubleList 32 FieldValues vals new FieldValues valList 34 AnalysisResultSchema resultSchema new AnalysisResultSchema Schema Name Description 35 int schemaIndex sfm RegisterResult resultSchema 36 sfm UpdateSpatialFieldPrimitive idx pnts vals schemaIndex Analysis Results Display The AnalysisDisplayStyle class can be used to control how t
227. cument GetElement ee as FamilyInstance 10 subElems subElems f Name An 11 12 TaskDialog Show Revit Subcomponent count subElemSet Count An subElems 13 14 FamilyInstance super familyInstance SuperComponent as FamilyInstance 15 if super null os 17 TaskDialog Show Revit SUPER component super Name 18 19 Other Properties The properties in this section are specific to Revit Architecture and Revit Structure They are covered thoroughly in their respective chapters Room Information FamilyInstance properties include Room FromRoom and ToRoom For more information about Room refer to Revit Architecture Space Information FamilyInstance has a Space property for identifying the space that holds an instance in MEP Revit Structure Related Analytical Model The GetAnalyticalModel method retrieves the family instance structural analytical model For more information about AnalyticalModel refer to Revit Structure Creating Familyl nstance Objects Typically a FamilyInstance object is created using one of the twelve overload methods of Autodesk Revit Creation Document called NewFamilyInstance The choice of which overload to use depends not only on the category of the instance but also other characteristics of the placement like whether it should be hosted placed relative to a reference level or placed directly on a particular face The details are included in Table
228. d return workset Code Region Filtering Worksets view plaincopy to clipboardprint 0 N dul UN A As shown in the previous example the Workset class provides many properties to get information about a given workset such as the owner and whether or not the public void GetWorksetsInfo Document doc String message String Empty Enumerating worksets in a document and getting basic information for each FilteredWorksetCollector collector new FilteredWorksetCollector doc find all user worksets collector OfKind WorksetKind UserWorkset IList Workset worksets collector ToWorksets get information for each workset int count 3 show info for 3 worksets only foreach Workset workset in worksets message Workset workset Name message MnUnique Id workset UniqueId message nOwner workset Owner message AnKind workset Kind message nIs default workset IsDefaultWorkset message nIs editable workset IsEditable message nIs open workset IsOpen message nIs visible by default workset IsVisibleByDefault TaskDialog Show GetWorksetsInfo message if 0 count break workset is editable Appendices Topics in this section e Glossary e FAQ e Hello World for VB NET e Material Properties Internal Units e Concrete Section Definitions e API User Interface Guidelines Glossary Topics in this sec
229. d Stairs appear in schedules and tags Structural Beam Systems Structural Columns Esport Structural Foundations Structural Framing Parameter Data Topography M ame Group parameter under Wall Sweeps Discipline Instance Type Common Check l Check None Type of Parameter T ext Show categories from al disciplines Hide un checked categories Add ta all elements in the selected categories Figure 132 Parameter Properties dialog box Type Binding The following code segment demonstrates how to add parameter definitions using a shared parameter file The following code performs the same actions as using the dialog box in the previous picture Parameter definitions are created in the following order 1 Ashared parameter file is created 2 Adefinition group and a parameter definition are created for the Walls type 3 The definition is bound to the wall type parameter in the current document based on the wall category Code Region 22 7 Adding type parameter definitions using a shared parameter file public bool SetNewParameterToTypeWall UIApplication app DefinitionFile myDefinitionFile Create a new group in the shared parameters file DefinitionGroups myGroups myDefinitionFile Groups DefinitionGroup myGroup myGroups Create MyParameters n Eccc pe ee tate om Definition myDefinition_CompanyName myGroup Definitions Create CompanyName ParameterType Text
230. d after Class1 in the example above you can select Implement IExternalCommand from the Intellisense menu to get the code public class Class1 IExternalCommand if y Figure 2 Using Intellisense to mplement Interface Every Revit add in application must have an entry point class that implements the IExternalCommand interface and you must implement the Execute method The Execute method is the entry point for the add in application similar to the Main method in other programs The add in entry point class definition is contained in an assembly For more details refer to Add in Integration Build the Program After completing the code you must build the file From the Build menu click Build Solution Output from the build appears in the Output window indicating that the project compiled without errors Create a addin manifest file The HelloWorld dll file appears in the project output directory If you want to invoke the application in Revit create a manifest file to register it into Revit 1 To create a manifest file create a new text file in Notepad 2 Add the following text Code Region 2 2 Creating a addin manifest file for an external command lt xml version 1 0 encoding UEE S Standelone no gt lt RevitAddiIns gt AddIn Type Commana gt lt Assembly gt D Sample HelloWorld bin Debug HelloWorld dll lt Assembly gt lt i elellimIbcl 23 Nes s 3 oad we Lipo Ly LoC SNC a Dada y 21
231. d 180 degrees This depends on the family to which the instance The previous picture also shows the Window 1 and Door 1 states after executing the rotate method In the previous door example the Mirrored property for Door 1 and Door 2 is False while for both Door 3 and Door 4 itis True This is because when you create a door in Recall from the Rotating elements section earlier in this document that family instances and other elements can be rotated a user specified angle usingElementTransformUtils RotateElement and ElementTransformUtils RotateElements The Location property determines the physical location of an instance in a project An instance can have a point location or a line location For more information about using the Mirror method in Revit refer to the Editing Elements chapter For more information about Location refer to Editing Elements Rotation CanRotate and rotate belongs For example while Window 2 Fixed 36 w x 72 Figure 45 Changes after rotate The following characteristics apply to Location Location Host and HostFace Host and HostFace are both FamilyInstance properties Host A FamilyInstance object has a Host property that returns its hosting element Some Familylnstance objects do not have host elements such as Tables and other furniture so the Host property returns nothing because no host elements are created However other objects such as doors and windows must have host elements
232. d Category classifications refer to Elements Essentials If an element has more than one component some of the Category Subcategories correspond to the components In the previous Object Styles dialog box the Windows Category and the Frame Mullion and Glass subcategories are mapped to components in the windows element In the following picture it seems the window symbol Glass Pane Material parameter is the only way to get the window pane material However the value is By Category and the corresponding Parameter returns Elementld InvalidElementld In this case the pane s Material is not null and it depends on the Category OST_WindowsFrameMullionProjection s Material property which is a subcategory of the window s category OST_Windows If it returns null as well the pane s Material is determined by the parent category OST_Windows For more details refer to Walkthrough Get Materials of a Window Element Properties lps Type Properties Type Parameters Parameter Value Construction Lis O mmm mem ee Construction Type Materials and Finishes Prane tmterior MEE SEE occ A mmm Dimensions Rough Wid Identity Data Me eme meme a e i ess A amp czambhlw Cieccrintinn Figure 109 Window material CompoundStructureLayer Material You can get the CompoundStructureLayer object from HostObjAttributes For more details refer to Walls Floors Ceilings Roofs and Openings Retrieve Element Materials The following di
233. d command link a simple lask Dialog reae by ee aee med chews normati on about che actie docu nent else if TaskDialogResult CommandLink2 tResult TaskDialog show Active Document Intormakion WINE wie CIOs 9 ae eiclea elo Waele ae Via tJ ACEI ve view name F eaeCriveboe Active View Nane return Ubecdect he Zits 01 Result slice eO DB level External Applications Database level add ins are External Applications that do not add anything to the Revit Ul DB level External Applications can be used when the purpose of the application is to assign events and or updaters to the Revit session To add a DB level External Application to Revit you create an object that implements the IExternalDBApplication interface The IExternalDBApplication interface has two abstract methods OnStartup and OnShutdown which you override in your DB level external application Revit calls OnStartup when it starts and OnShutdown when it closes This is very similar to IExternalApplication but note that these methods return Autodesk Revit DB ExternalDBApplicationResult rather than Autodesk Revit Ul Result and use ControlledApplication rather than UlControlledApplication Code Region I ExternalDBApplication OnShutdown and OnStartup view plaincopy to clipboardprint 1 public interface IExternalDBApplication 2E 3a public Autodesk Revit DB ExternalDBApplicationResult OnStartup ControlledApplication application 4 public Autodesk Revit
234. d control The right left move the cursor right left across columns And down up arrows move cursor down up the list respectively o Slider The right left down up arrows move the slider right left respectively o Spinner The right left down up arrows move the spinner down up respectively e Treat each Group conceptually as a nested dialog following the above rules within each Group first and moving from the top left Group moving to the right until no more groups are encountered and then moving to the next row of Groups e lf dialog is tabbed default tab stop should be the default tab Tip Visual Studio can assist with the creation and editing of tab order by toggling the Tab Order visual helper accessed from the View Tab Order menu Access Keys e Each editable control on a dialog should get a unique access key letter which is represented by an underlined letter in the control s label e The user presses Alt key plus the assigned key and that control is activated as if it was clicked e The default button does not require an access key since Enter is mapped to it e The Cancel or Close button also does not need access key since Esc is mapped to it See Committing Changes for more detail Show More Button Following the principle of Progressive Disclosure users may need a way of showing more data than is presented as a default in the user interface The Show More button is typically implemented in one of two ways Expander Button Pro
235. d flag for the user any elements and or settings that may cause performance degradation The Performance Adviser command executes a set of rules and displays their result in a standard review warnings dialog The API for performance adviser consists of 2 classes e PerformanceAdviser an application wide object that has a dual role as a registry of rules to run in order to detect potential performance problems and an engine to execute them e PerformanceAdviserRule an interface that allows you to define new rules for the Performance Adviser Performance Adviser PerformanceAdviser is used to add or delete rules to be checked enable and disable rules get information about rules in the list and to execute some or all rules in the list Applications that create new rules are expected to use AddRule to register the new rule during application startup and DeleteRule to deregister it during application shutdown ExecuteAllRules will execute all rules in the list on a given document while ExecuteRules can be used to execute selected rules in a document Both methods will return a list of failure messages explaining performance problems detected in the document The following example demonstrates looping through all performance adviser rules and executing all the rules for a document Code Region Performance Adviser view plaincopy to clipboardprint 1 Get the name of each registered PerformanceRule and then execute all of them 2 f
236. d from previous transactions The default value is False Note that this option is ignored in modal mode see ForcedModalHandling below ForcedModalHandling This options controls whether eventual failures will be handled modally or modelessly The default is True Be aware that if the modeless failure handling is set processing the transaction may be done asynchronously which means that upon returning from the Commit or RollBack calls the transaction will not be finished yet the status will be Pending SetFailuresPreprocessor This interface if provided is invoked when there are failures found at the end of a transaction The preprocessor may examine current failures and even try to resolve them See Failure Posting and Handling for more information SetTransactionFinalizer A finalizer is an interface which if provided can be used to perform a custom action at the end of a transaction Note that it is not invoked when the Commit or RollBack methods are called but only after the process of committing or rolling back is completed Transaction finalizers must implement the ITransactionFinalizer interface which requires two functions to be defined e OnCommitted called at the end of committing a transaction e OnRolledBack called at the end of rolling back a transaction Note that since the finalizer is called after the transaction has finished the document is not modifiable from the finalizer unless a new transaction is star
237. d is a Revit API object which represents a collection of faces and edges Typically in Revit these collections are fully enclosed volumes but a shell or partially bounded volume can also be encountered Note that sometimes the Revit geometry will contain unused solids containing zero edges and faces Check the Edges and Faces members to filter out these solids The Revit API offers the ability to read the collections of faces and edges and also to compute the surface area volume and centroid of the solid e Faces e Face analysis e Edge and face parameterization e Face types e Face Splitting e Mathematical representations of face types e Solid and face creation Edge and face parameterization Edges are boundary curves for a given face Iterate the edges of a Face using the EdgeLoops property Each loop represents one closed boundary on the face Edges are always parameterized from O to 1 It is possible to extract the Curve representation of an Edge with the Edge AsCurve and Edge AsCurveFollowingFace functions An edge is usually defined by computing intersection of two faces But Revit doesn t recompute this intersection when it draws graphics So the edge stores a list of points end points for a straight edge and a tessellated list for a curved edge The points are parametric coordinates on the two faces These points are available through the TessellateOnFace method Sections produce cut edges These are artificial ed
238. d roomSolid results GetGeometry 13 14 foreach Face roomSolidFace in roomSolid Faces 15 16 foreach SpatialElementBoundarySubface subface in results GetBoundaryFaceInfo roomSolidFace TA 18 Face boundingElementface subface GetBoundingElementFace 19 ElementId id boundingElementface MaterialElementId 20 S doc GetElement id Name id id IntegerValue ToString An 21 227 23 TaskDialog Show revit s Sketching To create elements or edit their profiles in Revit you must first create sketch objects Examples of elements that require sketches include e Roofs e Floors e Stairs e Railings Sketches are also required to define other types of geometry such as e Extrusions e Openings e Regions In the Revit Platform API sketch functions are represented by 2D and 3D sketch classes such as the following e 2Dsketch o SketchPlane o Sketch o ModelCurve o and more e 3Dsketch o GenericForm o Path3D In addition to Sketch Elements ModelCurve is also described in this chapter For more details about Element Classification see Elements Classification in the Elements Essential section Topics in this section e The 2D Sketch Class e 3D Sketch e ModelCurve The 2D Sketch Class The Sketch class represents enclosed curves in a plane used to create a 3D model The key features are represented by the SketchPlane and CurveLoop properties When editing a Revit file you
239. dNumber 16 SpacingRuleJustification Center 0 0 19 20 SpacingRule srV ds VSpacingRule 21 srV SetLayoutFixedNumber 24 SpacingRuleJustification Center 0 0 22 23 break just divide one face of form 24 25 26 225 RY Figure 60 Face of form divided by UV grids Accessing the USpacing and VSpacing properties of DividedSurface you can define the SpacingRule for the U and V gridlines by specifying either a fixed number of grids as in the example above a fixed distance between grids or a minimum or maximum spacing between grids Additional information is required for each spacing rule such as justification and grid rotation Patterning a surface A divided surface can be patterned Any of the built in tile patterns can be applied to a divided surface A tile pattern is an ElementType that is assigned to the DividedSurface The tile pattern is applied to the surface according to the UV grid layout so changing the USpacing and VSpacing properties of the DividedSurface will affect how the patterned surface appears The following example demonstrates how to cover a divided surface with the OctagonRotate pattern The corresponding figure shows how this looks when applied to the divided surface in the previous example Note this example also demonstrates how to get a DividedSurface on a form Code Region 14 8 Patterning a surface view plaincopy to clipboardprint 1 public void TileSurface Document document
240. ddin Code Region 3 12 Reading an existing manifest file Reyitrroduce revyvitrProducke ll RevitProduceUrEiility GerAllinstalledRevit Produces 0 RevitAddInManifest revitAddInManifest Autodesk RevitAddIns AddInManifestUtility GetRevitAddInManifest PVE rere tote Tb coe ETE Res ers clones ue Vy View rele aa o ela Os ele e e 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 character So the tag Code Region 3 13 Non localized Text Entry lt Text gt Extension Manager lt Text gt Becomes Code Region 3 14 Localized Text Entry lt Text gt dis eT ssec eod 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 See http msdn microsoft com en us library e9zazcx5 aspx 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 th
241. de the extents of the wall and looking for intersections with columns Example Find columns embedded in walls Measure distances This class could also be used to measure the vertical distance from a skylight to the nearest floor Distance Example Distance z Distance to floor 16 67 i Close Example measure with Referencelntersector FindNearest Code Region Measuring Distance using Ray Projection CON ADU UN A 10 12 13 14 15 16 17 18 19 20 21 22 234 24 295 26 27 28 294 30 31 32 J3 34 354 36 375 38 395 40 41 42 43 44 45 46 47 48 49 50 51 52 2954 54 55a 56 LY m 58 Dos 60 61 62 63 64 65 66 67 public class RayProjection IExternalCommand i public Result Execute ExternalCommandData revit ref string message ElementSet elements 1 Document doc revit Application ActiveUIDocument Document Selection selection revit Application ActiveUIDocument Selection If skylight is selected process it FamilyInstance skylight null if selection Elements Size 1 foreach Element e in selection Elements if e is FamilyInstance FamilyInstance instance e as FamilyInstance bool isWindow instance Category Id IntegerValue int BuiltInCategory OST Windows bool isHostedByRoof instance Host Category Id IntegerValue int BuiltInCategory OST Roofs if isWindow amp amp isHostedByRoof
242. der of the event notification the second is an event specific object that contains event arguments specific to that event For example to register the DocumentSavingAs event your event handler must take a second parameter that is a DocumentSavingAsEventArgs object The second part of using an event is registering the event with Revit This can be done as early as in the OnStartup function through the ControlledApplication parameter or at any time after Revit starts up Although events can be registered for External Commands as well as External Applications it is not recommended unless the External Command registers and unregisters the event in the same external command The following example registers the DocumentOpened event and when that event is triggered this application will set the address of the project Code Region 24 1 Registering Application DocumentOpened public elass police tion cine opened coc IB Bee ex cata ple ama er pulenta plato nte son Seu ome Oo essem cess teak tom iE we A Register event application DocumentOpened new EventHandler lt Autodesk Revit Events DocumentOpenedEventArgs gt application_DocumentOpened j AMA Eee ole diode return Autodesk eva UI ese s E eal lees j je deus eue elei E eB Su oueeeecdec pud TEx rna Api eis emeret onim teowmn e omo espe at on appr CHER remove the event application DocumentOpened application DocumentOpened return Autodesk evite 0d e s
243. document Element element Delete an element via its id Autodesk Revit DB ElementId elementId element Id ICollection Autodesk Revit DB ElementId deletedIdSet document Delete elementId if 0 deletedIdSet Count throw new Exception Deleting the selected element in Revit failed String prompt The selected element has been removed and prompt deletedIdSet Count 1 prompt more dependent elements have also been removed Give the user some information TaskDialog Show Revit prompt j NoteWhen an element is deleted any child elements associated with that element are also deleted as indicated in the samples above The API also provides a way to delete several elements Code Region Deleting multiple elements based on Id view plaincopy to clipboardprint COON ADU Bb UN FB NoteAfter you delete the elements any references to the deleted elements become invalid and throw an exception if they are accessed Some elements have special deletion methods For example the Materials Remove method is specifically for deleting Material objects For more information see the Delete all the selected elements via the set of element ids ICollection lt Autodesk Revit DB ElementId gt idSelection null UIDocument uidoc new UIDocument document foreach Autodesk Revit DB Element elem in uidoc Selection Elements 1 Autodesk Revit DB ElementId id elem Id idSelection Add id IColle
244. does the following 1 Searches filters the list 2 Selects an item 3 Commits or Cancels Air Barrier sphalt Variation B Left Right iren 1 Place UI items that Carpet 2 1 Initiate a task or change between modes in the far left see Tabs section Ceramic Tile gt 2 User must interact with to complete the task s in the middle This may be separated into Concrete separate distinct sections 3 Complete the task s in the lower right corner Concrete Precast Concrete Curtain Wall Mullions Default Default Floor Default Form Default Light Source Default Mass Exterior Wall Default Mass Floor Default Mass Interior Wall Default Mass Opening Default Mass Roof Default Mass Shade Default Mass Skylight Default Mass Window Categories Select one or more included in the filter common to these ca available for defining Mareas IF callouts casework Ceilings Columns Curtain Panels Curtain Systems T Curtain Wall Mullions Detail tems F Show categories from all disciplines Hide un checked categories Figure 199 Revit File Open dialog Note A top down flow can also be used within this dialog if they user is browsing the file hierarchy instead of the shortcuts on the far left Variation C Hybrid As seen in Variation B many windows that are laid out left to right are actually a hybrid of left right and top down
245. dules and non graphical data e Whether mullions should be exported as shading surfaces e Whether shading surfaces will be included e Whether to simplify curtain systems When true a single large window opening will be exported for a curtain wall system regardless of the number of panels in the system The following example creates a new energy analysis detailed model from the physical model then displays the originating element for each surface of each space in the model Code Region Energy Analysis Detail Model view plaincopy to clipboardprint 1 Collect space and surface data from the building s analytical thermal model 2 EnergyAnalysisDetailModelOptions options new EnergyAnalysisDetailModelOptions 3 options Tier EnergyAnalysisDetailModelTier Final include constructions schedules and non graphical data in the computation of the energy analysis model 4 EnergyAnalysisDetailModel eadm EnergyAnalysisDetailModel Create doc options Create a new energy analysis detailed model from the physical mo del 5 IList EnergyAnalysisSpace spaces eadm GetAnalyticalSpaces 6 StringBuilder builder new StringBuilder 7 builder AppendLine Spaces spaces Count 8 foreach EnergyAnalysisSpace space in spaces 9 10 builder AppendLine gt gt gt space Name related to space SpatialElementId 11 IList EnergyAnalysisSurface surfaces space GetAnalyticalSurfaces 125 builder App
246. dviser will pass to GetElementCheck In this case we are filtering for door elements lt summary gt lt param name document gt The document being checked lt param gt lt returns gt A door element filter lt returns gt public Autodesk Revit DB ElementFilter GetElementFilter Autodesk Revit DB Document document E return new Autodesk Revit DB ElementCategoryFilter Autodesk Revit DB BuiltInCategory OST Doors lt summary gt Gets the name of the rule lt summary gt lt returns gt The rule name lt returns gt public string GetName y return m name summary Returns true if this rule will iterate through elements and check them false otherwise summary lt returns gt True lt returns gt public bool WillCheckElements id return true endregion Point Clouds The Revit API provides 2 ways to work with point clouds The first way allows you to create new point cloud instances read and filter points select sub sets of the overall points and select points to be highlighted or isolated The second way allows you to use your own point cloud engine and process unsupported file formats i e other than pcg providing points to Revit for the user to see Client API o Create new Point Cloud instances o Read amp Filter Points o Point Set Selection o Control Point Cloud highlighting Engine API o Register Point Cloud file extension o Provide points
247. e definition Name ile Se Daleuliore Slovo Era eo eee ut dU OX E Te EQUO C IE Change the Parameter Definition Owner Group The following sample shows how to change the parameter definition group owner Code Region 22 6 Changing parameter definition group owner private void ReadEditExternalParam DefinitionFile file get ExternalDefinition from shared parameter file DefinitionGroups myGroups file Groups DefinitionGroup myGroup myGroups get Item MyGroup if null myGroup return Derinitio on Mm DI s SI OT S my rop s ETUR ExternalDefinition myExtDef myDefinitions get Item MyParam as ExternalDefinition if null myExtDef return StringBuilder strBuilder new StringBuilder se abewevery properey Ob Ene External Derinitionm strBuilder AppendLine GUID myExtDef GUID ToString AppendLine Name myExtDef Name AppendLine OwnerGroup myExtDef OwnerGroup Name AppendLine Parameter Group myExtDef ParameterGroup ToString AppendLine Parameter Type myExtDef ParameterType ToString Appr ndi ine eo wisi Tie e UE S qd esee Det e blo le Pes triana TaskDiralog suomi Revia Fe se mpi elio trm change the OwnerGroup of the ExternalDefinition myExtDef OwnerGroup myGroups get Item AnotherGroup Binding In the add in code complete the following steps to bind a specific parameter 1 Use an InstanceBinding or a TypeBinding object to create a new Binding o
248. e 24 sb AddPushButton bTwo 254 sb AddPushButton bThree 26 Radio buttons A radio button group is a set of mutually exclusive toggle buttons only one can be selected at a time After adding a RadioButtonGroup to a panel use the Addltem or Addltems methods to add toggle buttons to the group Toggle buttons are derived from PushButton The RadioButtonGroup Current property can be used to access the currently selected button Note that tooltips do not apply to radio button groups Instead the tooltip for each toggle button is displayed as the mouse moves over the individual buttons Code Region Adding radio button group view plaincopy to clipboardprint 1 private void AddRadioGroup RibbonPanel panel DE 35 add radio button group 4 RadioButtonGroupData radioData new RadioButtonGroupData radioGroup Da RadioButtonGroup radioButtonGroup panel AddItem radioData as RadioButtonGroup 6 7a create toggle buttons and add to radio button group 8 ToggleButtonData tb1 new ToggleButtonData toggleButton1 Red SM tb1 ToolTip Red Option 10 tb1 LargeImage new BitmapImage new Uri D Sample HelloWorld bin Debug Red bmp i ToggleButtonData tb2 new ToggleButtonData toggleButton2 Green 12 tb2 ToolTip Green Option 13 tb2 LargeImage new BitmapImage new Uri D Sample HelloWorld bin Debug Green bmp 14 ToggleButtonData tb3 new ToggleButtonData toggleButton3 Blue 15
249. e e If cases Size is M combinations Size is N e Factors Size should not be less than M N The first M factors map to M cases in order and the last N factors map to N combinations e Check that LoadCombination does not include itself There is no Duplicate method in the LoadCase and LoadNature classes To implement this functionality you must first create a new LoadCase or LoadNature object using the NewLoadCase or NewLoadNature method and then copy the corresponding properties and parameters from an existing LoadCase or LoadNature The following is a minimum sample code to demonstrate a creation of hosted point load in VB NET Code Region 29 15 NewPointLoad NewPointLoad with a host in VB NET Select a beam and get a curve of its analytical model Dim ref As Reference rvtUIDoc Selection PickObject ObjectType Element Select a beam Dim elem As Element ref Element Dim aModel As AnalyticalModel elem GetAnalyticalModel Dim aCurve As Curve aModel GetCurve For simplicity we assume we want to add a point load tal he start posnit Che curva Dim aSelector As New AnalyticalModelSelector aCurve aSelector CurveSelector AnalyticalCurveSelector StartPoint Dim startPointRef As Reference aModel GetReference aSelector Create a hosted point load IDEEN Ec uM OOO INE 0 ONO OSO 187 Daim inosine ENS SC NI ESCAS Ce de ONUS Qs deoa INGO O Dino So SEO EOS ae rvtDoc Create NewPoi
250. e Line FamilySymbol XYZ FamilySymbol Level StructuralType XYZ FamilySymbol Element StructuralType XYZ FamilySymbol XYZ Element StructuralType XYZ FamilySymbol Element Level StructuralType Curve FamilySymbol Level StructuralType XYZ FamilySymbol StructuralType XYZ FamilySymbol Element Level StructuralType XYZ FamilySymbol Level StructuralType XYZ FamilySymbol Element Comments Creates the instance in an arbitrary location without reference to a level or host element If itis to be hosted on a wall floor or ceiling If itis to be hosted on a wall floor or ceiling and needs to be oriented in a non default direction If itis to be hosted on a wall floor or ceiling and associated to a reference level If itis to be associated to a reference level If it is face based and needs to be oriented in a non default direction If it is face based and needs to be oriented in a non default direction accepts a reference to a face rather than a Face If it is face based and linear If it is face based and linear but accepts a reference to a face rather than a Face Creates the column so that its base lies on the reference level The column will extend to the next available level in the model or will extend the default column height if there are no suitable levels above the reference level Doors and windows must be hosted by a wall Use this method if they can be placed with the default orienta
251. e MassZone conceptual representations of individually heated and cooled sub volumes of a building e ConceptualConstructionType describes the conceptual physical construction and energy properties in a manner that can be understood by both the Revit BIM model and Green Building Studio Green Building XML e ConceptualSurfaceType represents a conceptual BIM object category to assign to faces in Mass geometries In addition to these classes there is a Document Export overload that takes a MassGBXMLExportOptions parameter which exports a gBXML file containing conceptual energy analysis elements mass elements only MassEnergyAnalyticalModel The main class associated with conceptual energy analysis is MassEnergyAnalyticalModel This class associates a mass instance with energy analytical model data and geometry The geometry begins as a copy of its associated mass instance geometry and is modified according to the requirements of the energy analytical model The static method MassEnergyAnalyticalModel GetMassEnergyAnalyticalModelldForMassInstance will return the Elementld for the MassEnergyAnalyticalModel for a given mass instance MassLevelData A MassLevelData is defined by associating a particular level with a particular mass element in a Revit project This can be done using the MassInstanceUtils AddMassLevelDataToMassInstance method MassLevelData reports metrics such as floor areas related to conceptual space planning MassLevel
252. e knowledge they developed while learning Revit Consistency can be obtained by re using certain dialog types instead of creating or re creating dialogs See the dialog types section for examples of dialogs you can leverage when creating your application Speak the Users Language Understanding and communicating within the user s language is always critical but particularly within a user interface Users will need to provide as well as receive feedback from the application The tone used in user interface language should be informal helpful and consultative in tone The user interface should politely provide information that is clear and informative to the user and that can be acted upon accordingly with confidence Good Layout A well balanced layout of information can be achieved by following Gestalt Principles e Proximity items placed close together are perceived as being closely associated e Similarity items that share similar appearance are perceived as being closely associated e Continuity humans tend to prefer simple unbroken contours over more complex yet similarly plausible forms Good Defaults When a user needs to edit data or change a setting the lack of any or obvious default can lead to errors and force users to re edit and re enter information Remember to e Set the control value with a reasonable default value for the current context by consulting usage data or using the previously entered values by the user The app
253. e PipeSettings object per document and it is accessible through the static method PipeSettings GetPipeSettings The PipeSettings class also provides access to the slope values available in the Ul under Pipe Settings Slopes Use GetPipeSlopes to retreive a list of slope values PipeSettings SetPipeSlopes provides the ability to set all the slope values at once while PipeSettings AddPipeSlope adds a single pipe slope Revit stores the slope value as a percentage 0 100 Mechanical Settings Pipe Slope Values The settings available in the UI under Pipe Settings Segments and Sizes are available as well Mechanical Settings Segment Carbon Steel Schedule 40 w t t Properties Roughness 0 046 mm Segment Description Size Catalog Nominal ID OD Used in Size Lists Used in Sizing 15 000 m 15 799 m 21 336 m Segments and Sizes This information is available through the Segment and MEPSize classes A Segment represents a length of MEPCurve that contains a material and set of available sizes The pipe sizes are represented by the MEPSize class The Segments available can be found using a filter The following example demonstrates how to get some of the information in the dialog above Code Region Traversing Pipe Sizes in Pipe Settings view plaincopy to clipboardprint 1 FilteredElementCollector collectorPipeType new FilteredElementCollector document 2 collectorPipeType OfClass typeof S
254. e a ModelArc element using the created geometry arc and sketch plane ModelArc arc document Create NewModelCurve geomArc sketch as ModelArc ModelCurve has properties that help you set specific GeometryCurves In this section the GeometryCurve and LineStyle properties are introduced GeometryCurve The GeometryCurve property is used to get or set the model curve s geometry curve Except for ModelHermiteSpline you can get different Geometry Curves from the four ModelCurves e Line e Arc e Ellipse e Nurbspline The following code sample illustrates how to get a specific Curve from a ModelCurve Code Region 17 3 Getting a specific Curve from a ModelCurve get the geometry modelCurve of the model modelCurve Autodesk Revit DB Curve geoCurve modelCurve GeometryCurve if geoCurve is Autodesk Revit DB Line Line geoLine geoCurve as Line The GeometryCurve property return value is a general Geometry Curve object therefore you must use an As operator to convert the object type NoteThe following information applies to GeometryCurve e In Revit you cannot create a Hermite curve but you can import it from other software such as AutoCAD Geometry Curve is the only geometry class that represents the Hermite curve e TheSetPlaneAndCurve method and the Curve and SketchPlane property setters are used in different situations o When the new Curve lies in the same SketchPlane or the new SketchPlane lies on the same planar
255. e an Assemblylnstance using an AssemblyType use the static method AssemblyInstance Placelnstance and specify the Elementld of the AssemblyType to use and a location at which to place the assembly Assembly Views Various assembly views can be created for an assembly instance using the AssemblyViewUtils class including an orthographic 3D assembly view a detail section assembly view a material takeoff multicategory schedule assembly view a part list multicategory schedule assembly view and a sheet assembly view The document must be regenerated before using any of these newly created assembly views You ll note in the example above that a transaction is committed after creating two new assembly views The Commit method automatically regenerates the document Parts Parts can be generated from elements with layered structures such as e Walls excluding stacked walls and curtain walls e Floors excluding shape edited floors e Roofs excluding those with ridge lines e Ceilings e Structural slab foundations In the Revit API elements can be divided into parts using the PartUtils class The static method PartUtils CreateParts is used to create parts from one or more elements Note that unlike most element creation methods in the API CreateParts does not actually create or return the parts but rather instantiates an element called a PartMaker The PartMaker uses its embedded rules to drive creation of the needed parts during regeneration
256. e below two quick filters are combined using a logical filter to get all door Familylnstance elements in the document Code Region 6 8 Using LogicalAndFilter to find all door instances eand a lb GoOor sins hanee suiting joo sel Oy E ndino eid dl elenen Ss asi Doth belong to rhe door category and are family instances ElementClassFilter familyInstanceFilter new ElementClassFilter typeof FamilyInstance 4 CieGeneS el Cercecioisy i3 Ee oie Daer ElementCategoryFilter doorsCategoryfilter new ElementCategoryFilter BuiltInCategory OST Doors cames a logic ct NI qoe OS ooo Hany imstamees LogicalAndFilter doorInstancesFilter new LogicalAndFilter familyInstanceFilter doorsCaregqoryriilter PETS the bilwer wo rene elements im che eise ele Tie Ts FilteredElementCollector collector new FilteredElementCollector document Msi llenen doors collector WherePasses doorlnsLancesrilier loElements Getting filtered elements or element ids Once one or more filters have been applied to the FilteredElementCollector the filtered set of elements can be retrieved in one of three ways 1 Obtain a collection of Elements or Elementlds o ToElements returns all elements that pass all applied filters o ToElementids returns Elementids of all elements which pass all applied filters 2 Obtain the first Element or Elementld that matches the filter o FirstElement returns first element to pass all applied filters o FirstElement
257. e beside the level bubble in the Revit UI To retrieve all levels in a project use the Elementlterator iterator to search for Level objects The Level class has the following properties e The Elevation property LEVEL ELEV is used to retrieve or change the elevation above or below ground level e The ProjectElevation property is used to retrieve the elevation relative to the project origin regardless of the Elevation Base parameter value e Elevation Base is a Level type parameter o Its BuiltlnParameter is LEVEL RELATIVE BASE TYPE o Its StorageType is Integer o Ocorresponds to Project and 1 corresponds to Shared Element Properties A Family Sustem Famil Level Load Edit Hew Type 1 4 Head Type Properties Tuae Peramecers Cantrcl all Constraints Elevation Base 0 ype 144 Head v Level 2 Graphics ZEN TD ex 0 5 Ep Family System Famil Level bal Load dui Louer A eee E Type Paremeters Instance Paramete s Contro Parameter Constraints Constraints Elevation Base Project Srojact llimetWeiht 0 0 uU Graphics Shared SM a a 01 gt T Figure 64 Level Type Elevation Base property The following code sample illustrates how to retrieve all levels in a project using Elementlterator Code Region 15 1 Retrieving all Levels private void Getinfo_Level Document document StringBuilder levellnformation new StringBuild
258. e crop box shape are illustrated in the View3D section e The View CropBoxVisible property determines whether the crop box is visible in the view e The View CropBoxActive property determines whether the crop box is actually being used to crop the view After cropping the model is projected onto the projection plane The following rules apply to the projection e The projection contents are mapped to the screen view port for display e During the mapping process the projection contents are scaled so that they are shown properly on the screen e The View Scale property is the ratio of the actual model size to the view size e The view boundary on paper is the crop region which is a projection of the crop box on the projection plane e The size and position of the crop region is determined by the View OutLine property View Types A project model can have several view types The following picture demonstrates the different types of views in the Project browser EB Legends Legend 1 a E Schedules Q uantities Floor Schedule d Sheets all 0 c A101 Unnamed Figure 95 Different views in the Project browser In the API there are three ways to classify views The first way is by using the view element View ViewType property It returns an enumerated value indicating the view type The following table lists all available view types Table 44 Autodesk Revit DB ViewType Member Name Description AreaPlan Area view CeilingPlan Re
259. e in the Element Properties dialog box select any element and click the Properties button next to the type selector For example the following image shows Room parameters Instance Parameters Control selected or to be created instance value E Design Return Airflow O DUDS s Actual Return Airflow ODD LIS e Design Exhaust Airflow DD LIS C Actual Exhaust Airflow OUO LIS oe Dimensions Ars D m nn E Pe 30000 vm is Height yaaa AA h O g aaa E Identity Data A Number e Name s Rom s Comments Figure 25 Room parameters In the Revit Platform API each Element object has a Parameters property which is a collection of all the properties attached to the Element You can change the property values in the collection For example you can get the area of a room from the room object parameters additionally you can set the room number using the room object parameters The Parameter is another way to provide access to property information not exposed in the element object In general every element parameter has an associated parameter ID Parameter IDs are represented by the Elementid class For user created parameters the IDs correspond to real elements in the document However most parameters are built in and their IDs are constants stored in Elementlds Parameter is a generic form of data storage in elements In the Revit Platform API it is best to use the
260. e language and culture explicitly with a LanguageType tag Code Region 3 15 Using LanguageType Tag lt LanguageType gt English_USA lt LanguageType gt For example the entry above 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 Attributes The Revit API provides several attributes for configuring ExternalCommand and ExternalApplication behavior TransactionAttribute The custom attribute Autodesk Revit Attributes TransactionMode must be applied to your implementation class of the IExternalCommand interface to control transaction behavior for external command There is no default for this option This mode controls how the API framework expects transactions to be used when the command is invoked The supported values are e TransactionMode Automatic Revit will create a transaction in 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 The command cannot create and start its own Transactions b
261. e method of interface IExporterIFC to perform an export to IFC 3 It also implements the methods of interface IExternalDBApplication to register the IFC export client to Autodesk Revit 4 lt summary gt 5 class Exporter IExporterIFC IExternalDBApplication 6 1 7 public ExternalDBApplicationResult OnStartup Autodesk Revit ApplicationServices ControlledApplication application 8 9 ExporterIFCRegistry RegisterIFCExporter this 10 return ExternalDBApplicationResult Succeeded 11 H 12 Note that ExporterlFCRegistry is an application level singleton and only one lExporterIFC can be registered in a given session of Revit Registration is on a first come first served basis If RegisterlFCExporter is called when there is already an IFC exporter registered it will throw an InvalidOperationException You can check the journal file for the path of the DLL which was successfully registered as the IFC exporter for the session IExporterlFC The interface IExporterlFC has only one method to implement ExportIFC This method is invoked by Revit to perform an export to IFC An ExporterlFC object is passed to this method as one of its parameters ExporterlFC is the main class provided by Revit to allow implementation of an IFC export It contains information on the options selected by the user for the export operation as well as members used to access specific types of data needed to implement the export properly The Autodesk Rev
262. e push buttons pulldown buttons containing multiple commands or split buttons which are pulldown buttons with a default push button attached In addition to buttons panels can include radio groups combo boxes and text boxes Panels can also include vertical separators to help separate commands into logical groups Finally panels can include a slide out control accessed by clicking on the bottom of the panel Please see Ribbon Guidelines in the API User Interface Guidelines section for information on developing a user interface that is compliant with the standards used by Autodesk Create a New Ribbon Tab Although ribbon panels can be added to the Add Ins or Analyze tab they can also be added to a new custom ribbon tab This option should only be used if necessary To ensure that the standard Revit ribbon tabs remain visible a limit of 20 custom ribbon tabs is imposed The following image shows a new ribbon tab with one ribbon panel and a few simple controls This Tab Name My Button 1 MyButton 2 This Panel Name A Below is the code that generated the above ribbon tab Code Region New Ribbon tab view plaincopy to clipboardprint 1 publicResult OnStartup UIControlledApplication application 2T du Create a custom ribbon tab 4 String tabName This Tab Name 5 application CreateRibbonTab tabName 6 7 8 Create two push buttons PushButtonData button1 newPushButtonData Button1 My Button
263. e shadow lt param gt 10 param name sunDirection The direction from the sun or light source lt param gt 11 returns The curves created for the shadow returns 12 throws cref Autodesk Revit Exceptions InvalidOperationException gt 13 Thrown by ExtrusionAnalyzer when the geometry and 14 direction combined do not permit a successful analysis lt throws gt 15 private static ICollection lt ElementId gt DrawShadow Document document Solid solid 16 Level targetLevel XYZ sunDirection 17 1 18 Create target plane from level 19 Plane plane document Application Create NewPlane XYZ BasisZ 20 new XYZ 0 0 targetLevel ProjectElevation 21 22 Create extrusion analyzer 23 ExtrusionAnalyzer analyzer ExtrusionAnalyzer Create solid plane sunDirection 24 25 Get the resulting face at the base of the calculated extrusion 26 Face result analyzer GetExtrusionBase 27 28 Convert edges of the face to curves 29 CurveArray curves document Application Create NewCurveArray 30 foreach EdgeArray edgeLoop in result EdgeLoops 31 32 foreach Edge edge in edgeLoop 33 34 curves Append edge AsCurve 35 36 37 38 Get the model curve factory object 39 Autodesk Revit Creation ItemFactoryBase itemFactory 40 if document IsFamilyDocument 41 itemFactory document FamilyCreate 42 else 43 itemFactory document Create
264. e whose view is active in the Revit session This chapter identifies all Application and Document functions and then focuses on file management settings and units For more details about the Element class refer to Elements Essentials and Editing Elements and refer to the Views for more details about the view elements Topics in this section e Application Functions e Document Functions e Document and File Management e Settings e Units Application Functions Application functions provide access to documents objects and other application data and settings All Application and UlApplication functions are identified and defined in the following sections Application The class represents the Autodesk Revit Application providing access to documents options and other application wide data and settings Application Version Information Application properties include VersionBuild VersionNumber and VersionName These can be used to provide add in behavior based on the release and build of Revit as shown in How to use Application properties to enforce a correct version for your add in Application wide Settings The SharedParametersFilename property and GetLibraryPaths and SetLibraryPaths methods provide access to these application wide settings Document Management The Application class provides methods to create the following types of documents e Family document e Project document e Project template The OpenDocumentFile method
265. eElement method to change the LocationPoint This changes both the Group location and the LocationPoint For more information about LocationCurve and LocationPoint see Move Level Levels are finite horizontal planes that act as a reference for level hosted or level based elements such as roofs floors and ceilings The Revit Platform API provides a Level class to represent level lines in Revit Get the Level object to which the element is assigned using the API if the element is level based Code Region 5 6 Assigning Level Get the level object to which the element as assigned Level level element level A number of elements such as a column use a level as a basic reference When you get the column level the level you retrieve is the Base Level Instance Parameters Control selected or to be created instance Parameter Value Constraints E Dase Level Level 1 p E I 5 1 Figure 24 Column Base Level parameter Note Get the Beam or Brace level using the Reference Level parameter From the Level property you only get null instead of the reference level information Level is the most commonly used element in Revit In the Revit Platform API all levels in the project are located by iterating over the entire project and searching for Elements Level objects For more Level details see Datum and Information Elements Every element has a set of parameters that users can view and edit in Revit The parameters are visibl
266. eResolutionType resolutionTypeList new List FailureResolutionType IList lt FailureMessageAccessor gt failList new List lt FailureMessageAccessor gt Inside event handler get all warnings failList failuresAccessor GetFailureMessages Sad Sho otra bool hasFailures false foreach FailureMessageAccessor failure in failList i ene eck how amen yrs Ollie ems SS SS SM me On c DT eon pile eM en terio dedisset wel o resolutionTypeList failuresAccessor GetAttemptedResolutionTypes failure ces clon yooh st Ub S Ta dus oso Eq CCo eso c qug so as acia eo le ciao return FailureProcessingResult ProceedWithRollBack j EPTO rS o OS N foreach Elementld id in failure GetFailingElementIds SIE ORS eat er Cl ls Clee en ae hasFailures true errorString nWill be deleted because failure GetDescriptionText failuresAccessor DeleteElements failure GetFailingElementIds as IList lt ElementId gt j if hasFailures crepat eene we Eod e EO tio return FailureProcessingResult ProceedWithCommit j return FailureProcessingResult Continue Place and Locations Every building has a unique place in the world because the Latitude and Longitude are unique In addition a building can have many locations in relation to other buildings The Revit Platform API Site namespace uses certain classes to save the geographical location information for Revit projects NoteThe Revit Platform API does
267. eated instance Parameter O ET H a Constraimts Elevation Graphics Visibility Graphics Overrides Identity Data Comments OK Cancel AN PanelEdgeLengthAngle results Faces a 2 Faces in the Revit API can be described as mathematical functions of two input parameters u and v where the location of the face at any given point in XYZ space is a function of the parameters The U and V directions are automatically determined based on the shape of the given face Lines of constant U or V can be represented as gridlines on the face as shown in the example below ga C NEL PIL NLL PIC PT ALTE YY Pe EL EE Bi CALCE OC A AAA AAA MOSSOS ARAN NN A LLLEBRRSLLLLLLD LI AAA MAA U and V gridlines on a cylindrical face You can use the UV parameters to evaluate a variety of properties of the face at any given location e Whether the parameter is within the boundaries of the face using Face IsInside e The XYZ location of the given face at the specified UV parameter value This is returned from Face Evaluate If you are also calling ComputeDerivatives this is also the Origin property of the Transform returned by that method e The tangent vector of the given face in the U direction This is the BasisX property of the Transform returned by Face ComputeDerivatives e The tangent vector of the given face in the V direction This is the
268. ecessary to check if the result is null or not Code Region 28 5 Getting a room from the family instance view plaincopy to clipboardprint 1 public void GetRoomInfo FamilyInstance familyInstance 2 4 3 Room room familyInstance Room 4 room familyInstance FromRoom for door and window family only Da room familyInstance ToRoom for door and window family only 6 if null room 7 8 9 y use the room 10 Other Room Properties The Room class has several other properties you can use to get information about the object Rooms have these read only dimension properties e Area e Perimeter e UnboundedHeight e Volume e ClosedShell Instance Parameters Control selected or to be created instance Parameter ve Constraints LEFT S RS MER Tat ma eR Fal LL This example displays the dimension information for a selected room Note that the volume calculations setting must be enabled or the room volume is returned as O Code Region 28 6 Getting a room s dimensions view plaincopy to clipboardprint 1 public void GetRoomDimensions Document doc Room room 2 1 3 String roominfo Room dimensions n 4 turn on volume calculations Ds VolumeCalculationOptions options new VolumeCalculationOptions 6 options VolumeComputationEnable true 7 doc Settings VolumeCalculationSetting VolumeCalculationOptions options 8 roominfo Vol room Volume An 9
269. ected in Revit MEP one being a piece of mechanical equipment and the other a duct fitting with a connector that lines up with the SupplyAir connector on the equipment Code Region 30 3 Adding a duct between two connectors view plaincopy to clipboardprint 1 public Duct CreateDuctBetweenConnectors UIDocument uiDocument 2 3 prior to running this example 4 select some mechanical equipment with a supply air connector Ss and an elbow duct fitting with a connector in line with that connector 6 Connector connector1 null connector2 null Ta ConnectorSetIterator csi null 8 ElementSet selection uiDocument Selection Elements 9 First find the selected equipment and get the correct connector 10 foreach Element e in selection 11 12 if e is FamilyInstance 13 14 FamilyInstance fi e as FamilyInstance 15 Family family fi Symbol Family 16 if family FamilyCategory Name Mechanical Equipment 17 18 csi fi MEPModel ConnectorManager Connectors ForwardIterator 19 while csi MoveNext 20 21 Connector conn csi Current as Connector 225 if conn Direction FlowDirectionType Out amp amp 23 conn DuctSystemType DuctSystemType SupplyAir 24 255 connectorl conn 26 break e 28 29 30 31 32 next find the second selected item to connect to 33 foreach Element e in selection 34 35 if e is FamilyInstance 36 375 FamilyI
270. ecute method In this simple example it will display a TaskDialog with the text Click Close to close as shown in the first code region above For a more complex example of using the External Events framework see the sample code in the SDK under the ModelessDialog ModelessForm_ExternalEvent folder It uses a modeless dialog with numerous buttons and the IExternalEventHandler implementation has a public property to track which button was pressed so it can switch on that value in the Execute method IFC Export The Revit API allows custom applications to override the default implementation for the IFC export process To create a custom IFC Exporter implement the lExporterlFC interface and register it with the ExporterlFCRegistry class When an IExporterlFC object is registered with Revit it will be used both when the user invokes an export to IFC from the UI as well as from the API method Document Export String String IFCExportOptions In both cases if no custom IFC exporter if registered the default Revit implementation for IFC export is used When invoking an IFC export from the API IFCExportOptions can be used to set the same export options as are available to the user from the Export IFC dialog box ExporterlFCRegistry The following example registers a custom IFC exporter in the OnStartup method Code Region Registering a custom IFC exporter view plaincopy to clipboardprint 1 summary 2 This class implements th
271. ed Pending Description The initial value after object is instantiated the context has not started yet Transaction object has successfully started Start was called Transaction object was successfully rolled back Rollback was called Transaction object was successfully committed Commit was called Transaction object was attempted to be either submitted or rolled back but due to failures that process could not be finished yet and is waiting for the end user s response in a modeless dialog Once the failure processing is finished the status will be automatically updated to either Committed or RolledBack Status A transaction is 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 committed Code Region 23 1 Using transactions L1 eres eae melee ume Autodesk Revit DB Document document uiApplication ActiveUIDocument Document ji Cees 2 cecmetey Lime iim Exerc ec ejeeliese om DA DA DA AA Ronen Ronne Pointes Ronne new x14 OO ON new KA O A mew ra OO New KA OA Transient Elements so they are not managed by transactions Line geomLinel application Create NewLine Pointl Point2 true Line geomLine2 application ee rcatrerNewbine Pointa bom te Line geomLine3 application Create NewLine Pointl
272. ed The ScheduleDefinition GetSchedulableFields method will return a list of SchedulableField objects representing the non calculated fields that may be included in the schedule A new field can be added from a SchedulableField object or using a ScheduleFieldType The following table describes the options available from the ScheduleFieldType enumeration Member name Description Instance An instance parameter of the scheduled elements All shared parameters also use this type regardless of whether they are instance or type parameters ElementType A type parameter of the scheduled elements Count The number of elements appearing on the schedule row A specialized type of field used for a few parameters whose displayed values can change based on the settings of the view ROOM AREA and ROOM PERIMETER in room and space schedules ViewBased l PROJECT REVISION REVISION NUM in revision schedules KEYNOTE NUMBER in keynote legends that are numbered by sheet Formula A formula calculated from the values of other fields in the schedule Percentage A value indicating what percent of the total of another field each element represents Room A parameter of the room that a scheduled element belongs to FromRoom A parameter of the room on the from side of a door or window ToRoom A parameter of the room on the to side of a door or window A parameter of the Project Info element in the project that the scheduled element belongs to which may be a linked file
273. ed by a mass instance as well as to create a MassLevelData Mass Floor to associate a Level with a mass instance as discussed above Detailed Energy Analysis Model The Autodesk Revit DB Analysis namespace includes several classes to obtain and analyze the contents of a project s detailed energy analysis model The Export to gbXML and the Heating and Cooling Loads features produce an analytical thermal model from the physical model of a building The analytical thermal model is composed of spaces zones and planar surfaces that represent the actual volumetric elements of the building The classes related to the detailed energy analysis model are e EnergyAnalysisDetailModel e EnergyAnalysisDetailModelOptions e EnergyAnalysisOpening e EnergyAnalysisSpace e EnergyAnalysisSurface e Polyloop Use the static method EnergyAnalysisDetailModel Create to create and populate the energy analysis model Set the appropriate options using the EnergyAnalysisDetailModelOptions The generated model is always returned in world coordinates but the method TransformModel transforms all surfaces in the model according to ground plane shared coordinates and true north The options available when creating the energy analysis detail model include e The level of computation for energy analysis model NotComputed FirstLevelBoundaries meaning analytical spaces and zones SecondLevelBoundaries meaning analytical surfaces or Final meaning constructions sche
274. ed event handler cast the sender object to TextBox to get the value the user has entered as shown in the following example Code Region TextBox EnterPressed event handler view plaincopy to clipboardprint 1 void ProcessText object sender Autodesk Revit UI Events TextBoxEnterPressedEventArgs args 2 E 3 cast sender as TextBox to retrieve text value 4 TextBox textBox sender as TextBox 5 string strText textBox Value as string 6 The inherited ItemText property has no effect for TextBox The user entered text can be obtained from the Value property which must be converted to a string See the section on stacked ribbon items for an example of adding a TextBox to a ribbon panel including how to register the event above Combo box A combo box is a pulldown with a set of selectable items After adding a ComboBox to a panel use the Addltem or Addltems methods to add ComboBoxMembers to the list Separators can also be added to separate items in the list or members can be optionally grouped using the ComboBoxMember GroupName property All members with the same GroupName will be grouped together with a header that shows the group name Any items not assigned a GroupName will be placed at the top of the list Note that when grouping items separators should not be used as they will be placed at the end of the group rather than in the order they are added Enter a comment af 5 Option A Letters Option B Numb
275. ee marlon CurveArray footprint application Create NewCurveArray UlDo cuna rico Aew Dome iae coe Unie tue if uidoc Selection Elements Size 0 foreach Autodesk Revit DB Element element in uidoc Selection Elements Wall wall element as Wall e A Ale OC se Loin teve eddie ed oe cte ed dels Ieee ic E CU CDU WAS footprint Append wallCurve Curve conce MeodelCurve mode lcuryes element as Modeltcuryes it model urve T null Ino onem cn d mese Some cia AOS else pIsbpow new Excepuron otvousshould seleoucacubweueop vor wall Loop Greate a boob DI oO LA vo ModelCurveArray footPrintToModelCurveMapping new ModelCurveArray EGOELELINEROOL PootprasnbRoor documene Creare NewFPOorPrine Root footprine level Or OOIES rooftype ModelCurveArrayIterator iterator footPrintToModelCurveMapping ForwardIterator combinaron ls STE selina sab out footPrintToModelCurveMapping renato Res lt warile iterator MoveNexte 00 ModelCurve modelCurve iterator Current as ModelCurve footprintRoof set_DefinesSlope modelCurve true 1 oO 9e Loe oO Ser soe ae mode bis 10 3 For an example of how to create an ExtrusionRoof see the NewRoof sample application included with the Revit API SDK Gutter and Fascia Gutter and Fascia elements are derived from the HostedSweep class which represents a roof They can be created deleted or modified via the API To create these
276. eeds to e provide users with information e ask users a question e orallow users to select options to perform a command or task The image below shows a mockup of a task dialog with all possible controls enabled Most of the controls shown are optional and one would never create a task dialog that had everything on The mockup below simple illustrates all the parts of a task dialog that could be utilized in one image 5 Example Task Dialog All Components Shown Main image 1 These are the main instructions for the task dialog Main instructions Optional Main Content for a task dialog goes here This is where onger text would go H the main instructions area was not sufficient Main content This region is for optional Expanded Content This text is not shown by default The show hide button in the footer expands and collapses this section of text Progress bar Expanded content Apply the first command option The first command link is the default action for the task dialog Do something else instead Optionally enter supporting content here Command links show Hide button for expanded content 3 Do nothing and proceed Hide details _ Clos Comm t button Do not show me again Da not show me this message again checkbox Click here ta learn more Footer text Figure 224 Atask dialog with all components visible Note that this particular task dialog would never happen in a real implementation Onl
277. efault is a tooltip with just the command text The modes in which the external command will 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 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 See table below for more information The disciplines in which the external command will 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 disciplines If any specific disciplines are listed the command will only be visible in those disciplines See table below for more information 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 The icon to use for the button in the External Tools pulldown menu Optional use this tag for ExternalCommands only The default is to show a button without an icon The icon to use if the button is promoted to the Quick Access Tool
278. eft of the list control e Managing list is primary task place at top left of list control e When the main collection being managed is represented as a combo box place to the right of the combo box Add Remove A slight variation on the Edit Bar is the use of Add and Remove buttons denoted by plus and minus icons as shown below Add and Remove is used when data is being added to an existing item in the model The following is a good example of a Collection Editor dialog that uses both forms of the Edit Bar The Add and Remove buttons are used to add values to an already existing demand factor type Demand factor types Mame Default Calculation method By quantity Calculation options Total at one percentage fon JIncrementally for each range Example If 2 items all loads calculated at 10072 If 10 items all loads calculated at bh Quantity Demand Factor Add an additianal load to the calculated result OVA o x J _ ew Figure 221 Demand Factors dialog in Revit MEP 2011 List Builder Use when there is a number of items that the user has to add remove from one list to another This is typically used when there is a list located on the right that needs to have items added to it from an existing list located on the left Provide a List Box View of the two lists with button controls between one for adding and the other for removing items IC S jm SELLE system SS Cur
279. egment 35 4 IEnumerable Segment segments collectorPipeType ToElements Cast Segment 5 foreach Segment segment in segments OE rip StringBuilder strPipeInfo new StringBuilder 8 strPipeInfo AppendLine Segment segment Name 9 10 strPipeInfo AppendLine Roughness segment Roughness 11 12 strPipeInfo AppendLine Pipe Sizes 13 double dLengthFac 304 8 used to convert stored units from ft to mm for display date foreach MEPSize size in segment GetSizes 15 16 strPipeInfo AppendLine string Format Nominal 0 F3 ID 1 F3 OD 2 F3 17 size NominalDiameter dLengthFac size InnerDiameter dLengthFac size OuterDiameter dLengthFac 18 19 20 21 TaskDialog Show PipeSetting Data strPipeInfo ToString 22 break 23 Pipe Settings PipeSe n Segment Carbon Steel Schedule 40 Roughness 0 00015 Pipe Sizes Nominal 15 000 ID 15 799 OD 21 336 Nominal 20 000 ID 20 930 OD 26 670 Nominal 25 000 ID 26 645 OD 33 401 Nominal 32 000 ID 35 052 OD 42 164 Nominal 40 000 ID 40 894 OD 48 260 Nominal 50 000 ID 52 502 OD 60 325 Nominal 65 000 ID 62 713 OD 73 025 Nominal 80 000 ID 77 927 OD 88 900 Nominal 90 000 ID 90 119 OD 101 600 Nominal 100 000 ID Nominal 125 000 ID Nominal 150 000 ID Nominal 200 000 ID Nominal 250 000 ID Nominal 300 000 ID Nominal 350 000 ID Nominal 400 000
280. el Additionally the GetManualAdjustmentMatchedElements method retrieves a collection of element Ids against which the Analytical Model has been adjusted Analytical Offset Another way to adjust an analytical model is to use an offset Setting the analytical offset is different than manually adjusting the analytical model The analytical offset is a basic offset applied to the entire analytical model and is independent of any other elements AnalyticalModel has methods to get and set the analytical offset as well as to determine if the analytical offset can be changed CanSetAnalyticalOffset AnalyticalModelSupport AnalyticalModel provides the method IsElementFullySupported to determine if the analytical model is fully supported For additional information about what is supporting the analytical model the GetAnalyticalModelSupports method retrieves a collection of AnalyticalModelSupport objects that provide information on how the element is supported by other structural elements including the priority of each support if multiple elements provide support and the point curve or face that provides the support The following examples illustrate how to use the AnalyticalModelSupport objects in different conditions Floor and StructuralBeam Support Information When drawing a slab in sketch mode select Pick Supports on the design bar As shown in the following picture a slab has three support beams By iterating the slab s collection of Anal
281. element Parameter foundParameter null A This will find the firs parameter thal measures Length foreach Parameter parameter in element Parameters if parameter Definition ParameterType ParameterType Length foundParameter parameter break return foundParameter ParameterType This property returns parameter data type which affects how the parameter is displayed in the Revit Ul The ParameterType enumeration members are Member name Number Moment AreaForce LinearForce Force YesNo Material URL Angle Volume Area Integer Invalid Length Text Description The parameter data should be interpreted as a real number possibly including decimal points The data value will be represented as a moment The data value will be represented as an area force The data value will be represented as a linear force The data value will be represented as a force A boolean value that will be represented as Yes or No The value of this property is considered to be a material A text string that represents a web address The parameter data represents an angle The internal representation will be in radians The user visible representation will be in the units that the user has chosen The parameter data represents a volume The internal representation will be in decimal cubic feet The user visible representation will be in the units that the user has chosen The parameter data represents an
282. elements use one of the Document Create NewFascia or Document Create NewGutter overrides For an example of how to create new gutters and fascia see the NewHostedSweep application included in the SDK samples Below is a code snippet showing you can modify a gutter element s properties Code Region 11 4 Modifying a gutter public void ModifyGutter Autodesk Revit DB Document document UIP SCCUNeEta IEC me DULDocumeane cos line mir DlemeMrsoceeOllectlony uldo Selena tom Te Te ETT SHE S foreach Autodesk Revit DB Element elem in collection if elem is Gutter Gutter gutter elem as Gutter convert degrees to rads quieren angle md be Mme o MasicDa clog Simons amp Revie M Omsugee etree ume Curtains Curtain walls curtain systems and curtain roofs are host elements for CurtainGrid objects A curtain wall can have only one CurtainGrid while curtain systems and curtain roofs may contain one or more CurtainGrids For an example of how to create a CurtainSystem see the CurtainSystem sample application included with the Revit SDK For an example of creating a curtain wall and populating it with grid lines see the CurtainWallGrid sample application Other Elements Some Elements are not HostObjects and don t have a specific class but are special cases that can host other objects For example ramp and its associated element type do not have specific classes in the API and instead are represented as Element and Elem
283. elements allows for the use of foreach to examine each element in the set as is shown below Code Region 6 9 Using ToElements to get filter results view plaincopy to clipboardprint Use ElementClassFilter to find all loads in the document Using typeof LoadBase will yield all AreaLoad LineLoad and PointLoad ElementClassFilter filter new ElementClassFilter typeof LoadBase Apply the filter to the elements in the active document FilteredElementCollector collector new FilteredElementCollector document collector WherePasses filter ICollection Element allLoads collector ToElements COON AOU E UN A 10 String prompt The loads in the current document are n 11 foreach Element loadElem in allLoads Jo 13 LoadBase load loadElem as LoadBase IS prompt load GetType Name 15 load Name An INE 18 TaskDialog Show Revit prompt When just one passing element is needed use FirstElement Code Region 6 10 Get the first passing element view plaincopy to clipboardprint Create a filter to find all columns StructuralInstanceUsageFilter columnFilter new StructuraliInstanceUsageFilter StructuralInstanceUsage Column Apply the filter to the elements in the active document FilteredElementCollector collector new FilteredElementCollector document collector WherePasses columnFilter Get the first column from the filtered results 0 Element will be a Fami
284. eloper Center Figure 19 Revit style Task Dialog There are two ways to create and show a task dialog to the user The first option is to construct the TaskDialog set its properties individually and use the instance method Show to show it to the user The second is to use one of the static Show methods to construct and show the dialog in one step When you use the static methods only a subset of the options can be specified Please see Task Dialog in the API User Interface Guidelines section for information on developing a task dialog that is compliant with the standards used by Autodesk The following example shows how to create and display the task dialog shown above Code Region 3 27 Displaying Revit style TaskDialog Autodesk Revit ALE ribubkes Transaction AUwodesk Revit Attributes I ransactionMode Automatic class TaskDialogExample IExternalCommand public Autodesk Revit UI Result Execute ExternalCommandData commandData ref string message Autodesk Revit DB ElementSet elements Get the application and document from external command data App ILMGeVE LOI aor COmMent el MOL ue ene 00905 OO Lae sig ioe Document activeDoc commandData Application ActiveUIDocument Document Creates a Revit task dialog Co communicate inlormation Co the user TaskDialog mainDialog new TaskDialog Hello Revit ie iab ae osea Oe TODA wei Vine ble yr MESS qe fs mainDialog MainContent This sample shows how to use a
285. ement Properties Type Edit Mew Type Parameters Control all elements of this type Parameter Value Instance Parameters Control selected or ta be created instance Parameter fale E The value of ExtrusionEnd Constraints property is 20 0 The value of ExtrusionStart property is 0 0 Visibility Graphics Overrides Materials and Finishes Material Identity Data Subcategory Figure 80 Extrusion parameters in the UI de CU COS NS Figure 81 Extrusion result The Revolve command creates geometry that revolves around an axis You can use the revolve command to create door knobs or other knobs on furniture a dome roof or columns Query the Revolution Form object for a generic form to use in family modeling and massing The Revolution class has the following properties Table 41 Revolution Properties Property Description Axis Returns the Axis It is a ModelLine object EndAngle Returns the End Angle It is a Double type Sketch Returns the Extrusion Sketch It contains a SketchPlane and some curves EndAngle is consistent with the same parameter in the Revit Ul The following pictures illustrate the Revolution corresponding parameter the sketch and the result Element Properties Family Load Type mE Type Parameters Control all elements of this type Parameter Value Instance Parameters Control sslected or to be created instance A nee The value of EndAngle Constraints E 160 000
286. ementId 5 oe PropertySetElement pse document GetElement strucAssetId asPropertySetElement 7 if pse null 8 9 StructuralAsset asset pse GetStructuralAsset 19 Tl Check the material behavior and only read if Isotropic 125 if asset Behavior StructuralBehavior Isotropic 13 14 Get the class of material 15 StructuralAssetClass assetClass asset StructuralAssetClass Get other material properties 16 17 Get other material properties 18 double poisson asset PoissonRatio X 19 double youngMod asset YoungModulus X 20 double thermCoeff asset ThermalExpansionCoefficient X 21 double unitweight asset Density 22 double shearMod asset ShearModulus X 23 double dampingRatio asset DampingRatio 24 if assetClass StructuralAssetClass Metal 25 26 double dMinStress asset MinimumYieldStress 27 28 elseif assetClass StructuralAssetClass Concrete 29 30 double dConcComp asset ConcreteCompression 31 32 33 34 35 The material classification relevant to structural analysis i e steel concrete wood can be obtained from the StructuralAssetClass property of the StructuralAsset associated with the material Note The API does not provide access to the values of Concrete Type for Concrete material The material classification relevant to energy analysis i e solid liquid gas can be obtained from the ThermalMaterialType property of the
287. ements appearing in the schedule are sorted based on their values for the field by which the schedule is sorted grouped which automatically causes elements with identical values to be grouped together By enabling extra header footer or blank rows visual separation between groups can be achieved If the ScheduleDefinition Isltemized property is false elements having the same values for all of the fields used for sorting grouping will be combined onto the same row Otherwise the schedule displays each element on a separate row A schedule can be sorted or grouped by data that is not displayed in the schedule by marking the field used for sorting grouping as hidden using the ScheduleField IsHidden property Filtering A ScheduleFilter can be used to filter the elements that will be displayed in a schedule A filter is a condition that must be satisfied for an element to appear in the schedule All filters must be satisfied for an element to appear in the schedule A schedule can be filtered by data that is not displayed in the schedule by marking the field used for filtering as hidden using the ScheduleField IsHidden property Placing Schedules on Sheets The static ScheduleSheetInstance Create method creates an instance of a schedule on a sheet It requires the ID of the sheet where the schedule will be placed the ID of the schedule view and the XYZ location on the sheet where the schedule will be placed The ScheduleSheetInstance object has prop
288. endLine has surfaces Count surfaces 13 foreach EnergyAnalysisSurface surface in surfaces 14 15 builder AppendLine Surface from surface OriginatingElementDescription 16 17 18 19 TaskDialog Show EAM builder ToString After creating the EnergyAnalysisDetailModel the spaces openings and surfaces associated with it can be retrieved with the GetAnalyticalOpenings GetAnalyticalSpaces GetAnalyticalShadingSurfaces and GetAnalyticalSurfaces methods Be sure to call EnergyAnalysisDetailModel Destroy to clean up the Revit database after finishing with the analysis results EnergyAnalysisSpace From an EnergyAnalysisSpace you can retrieve the collection of EnergyAnalysisSurfaces which define an enclosed volume bounded by the center plane of walls and the top plane of roofs and floors Alternatively GetClosedShell retrieves a collection of Polyloops which are planar polygons that define an enclosed volume measured by interior bounding surfaces For two dimensions use GetBoundary which returns a collection of Polyloops representing the 2D boundary of the space that defines an enclosed area measured by interior bounding surfaces The EnergyAnalysisSpace class also has a number of properties for accessing information about the analysis space such as AnalyticalVolume Name and Area EnergyAnalysisSurface From an EnergyAnalysisSpace you can retrieve the primary analysis space associated with
289. ension NewDimension View view Line line ReferenceArray references 2 DimensionType dimensionType Using the NewDimension method input parameters you can define the visible View dimension line and References two or more However there is no easy way to distinguish a linear dimension DimensionType from other types The overloaded NewDimension method with the DimensionType parameter is rarely used The following code illustrates how to use the NewDimension method to duplicate a dimension Code Region 16 3 Duplicating a dimension with NewDimension view plaincopy to clipboardprint 1 public void DuplicateDimension Document document Dimension dimension ZEN 3 Line line dimension Curve as Line 4 if null line Ds 1 6 Autodesk Revit DB View view dimension View 7 ReferenceArray references dimension References 8 Dimension newDimension document Create NewDimension view line references 9 10 Though only linear dimensions are created you can delete all dimensions and constraints represented by Dimension and SpotDimension using the Document Delete method Detail Curve Detail curve is an important Detail component usually used in the detail or drafting view Detail curves are accessible in the DetailCurve class and its derived classes DetailCurve is view specific as are other annotation elements However there is no DetailCurve View property When creating a detail curve you must compare the de
290. ent and displays a TaskDialog summarizing the number of automatically generated and manually created AnalyticalLinks Code Region Reading AnalyticalLinks 1 public void ReadAnalyticalLinks Document document 2 34 FilteredElementCollector collectorAnalyticalLinks new FilteredElementCollector document 4 collectorAnalyticalLinks OfClass typeof AnalyticalLink 5 6 IEnumerable lt AnalyticalLink gt alinks collectorAnalyticalLinks ToElements Cast lt AnalyticalLink gt 7 int nAutoGeneratedLinks Q 8 int nManualLinks 0 9 foreach AnalyticalLink alink in alinks 10 11 if alink IsAutoGenerated true qo nAutoGeneratedLinks 13 else 14 nManualLinks 15 16 string msg Auto generated AnalyticalLinks nAutoGeneratedLinks 17 msg nManually created AnalyticalLinks nManualLinks 18 TaskDialog Show AnalyticalLinks msg 19 The static method AnalyticalLink Create creates a new analytical link Rather than connecting the two elements directly the connection is created between two Hubs The Hub class represents a connection between two or more Autodesk Revit Elements The following example creates a new analytical link between two selected FamilyInstance objects It uses a filter to find all Hubs in the model and then the GetHub method searches the hubs to find one which references the Id of the AnalyticalModel of each FamilyInstance Code Region Creating a new Analytical
291. ent connSupply ConnectorElement CreatePipeConnector uiDocument Document 29 PipeSystemType SupplyHydronic 30 planarFaces 0 Reference 31 Parameter param connSupply get Parameter BuiltInParameter CONNECTOR RADIUS 32 param Set 1 0 1 radius 335 param connSupply get Parameter BuiltlInParameter RBS PIPE FLOW DIRECTION PARAM 34 param Set 2 35 36 Create the Return Hydronic pipe connector 57 ConnectorElement connReturn ConnectorElement CreatePipeConnector uiDocument Document 38 PipeSystemType ReturnHydronic 39 planarFaces 1 Reference 40 param connReturn get Parameter BuiltInParameter CONNECTOR RADIUS 41 param Set 0 5 6 radius 42 param connReturn get Parameter BuiltlInParameter RBS PIPE FLOW DIRECTION PARAM 43 param Set 1 44 y 45 The following illustrates the result of running this example using in a new family document created using a Mechanical Equipment template and passing in an extrusion 2 x2 x1 Note that the connectors are placed at the centroid of the planar faces A d x dis Maret Figure 169 Two connectors created on an extrusion Mechanical Settings Some of the settings available on the Manage tab under MEP Settings Mechanical Settings are also available through the Revit API Mechanical Settings Pipe Settings The PipeSettings class provides access to the settings shown above such as Pipe Size Suffix and Pipe Connector Tolerance There is on
292. entType in the OST Ramps category CompoundStructure Walls floors ceilings and roofs are all children of the API class HostObject HostObject and its related type class HostObjAttributes provide read only access to the CompoundStructure The CompoundStructure class offers read and write access to a set of layers consisting of different materials e CompoundStructure GetLayers e CompoundStructure SetLayers Normally these layers are parallel and extend the entire host object with a fixed layer width However for walls the structure can also be vertically compound where the layers vary at specified vertical distances from the top and bottom of the wall Use CompoundStructure IsVerticallyCompound to identify these For vertically compound structures the structure describes a vertical section via a rectangle which is divided into polygonal regions whose sides are all vertical or horizontal segments A map associates each of these regions with the index of a layer in the CompoundStructure which determines the properties of that region It is possible to use the compound structure to find the geometric location of different layer boundaries The method CompoundStructure GetOffsetForLocationLine provides the offset from the center location line to any of the location line options core centerline finish faces on either side or core sides With the offset to the location line available you can obtain the location of each layer boundary b
293. entVisiblelnTemporaryViewMode identifies if an element should be visible in the indicated view mode This applies only to the TemporaryHidelsolate and AnalyticalModel view modes Other modes will result in an exception Creating and Deleting Views The Revit Platform API provides numerous methods to create the corresponding view elements derived from Autodesk Revit DB View class Most view types are created using static methods of the derived view classes If a view is created successfully these methods return a reference to the view otherwise they return null The methods are described in the following sections specific to each view class Views can also be created using the View Duplicate method A new view can be created from an existing view with options for the new view to be dependent or to have detailing Delete a view by using the Document Delete method with the view ID You can also delete elements associated with a view For example deleting the level element causes Revit to delete the corresponding plan view or deleting the camera element causes Revit to delete the corresponding 3D view The View3D Class View3D is a freely oriented three dimensional view There are two kinds of 3D views perspective and isometric also referred to as orthographic in the Revit user interface The difference is based on the projection ray relationship The View3D IsPerspective property indicates whether a 3D view is perspective or isometric Perspecti
294. ently the API does not provide access to the Floor Slope Arrow in the Floor class However in Revit Structure you can create a sloped slab with NewSlab Code Region 11 1 NewSlab view plaincopy to clipboardprint 1 public Floor NewSlab CurveArray profile Level level Line slopedArrow double slope 2 bool isStructural The Slope Arrow is created using the slopedArrow parameter Figure 36 slopedArrow parameter in NewSlab The unit for the slope parameter in NewSlab is rise run The Floor FloorType property is an alternative to using the Floor GetTypeld method For more information about structure related functions such as SpanDirectionSymbols and SpanDirectionAngle refer to the Revit Structure chapter When editing an Isolated Foundation in Revit you can perform the following actions e You can pick a host such as a floor However the Familylnstance object Host property always returns null e When deleting the host floor the Foundation is not deleted with it e The Foundation host is available from the Host INSTANCE FREE HOST PARAM parameter e Use another related Offset INSTANCE FREE HOST OFFSET PARAM parameter to control the foundation offset from the host Element Moves With arid Fick Host Edi Family Pick a new host For the selection Figure 37 Pick Host for FoundationSlab Familyl nstance Continuous footings are represented by the ContFooting class in the API The API provides limited access to
295. ents ForwardIterator elemen escis while elemIter MoveNext Element curke len elentter Current ao Element exe ludes sce ell hem Id y Quee dades co exclude ell selecteo eleme ace Exe lusion slicer rallies gt me 8e pusiat ome a douces ese Ties IA ene er to Nice remm simt esie 4 ee sot cobi meted Oiclass te awe Walle only Eiler dJdEl mentCollecror collector new e qi Toe eee eue Le elarecoJL Lector uUrDocument Document IList Element walls collector WherePasses filter OfClass typeof Wall ToElements Note that the ElementClassFilter will match elements whose class is an exact match to the input class or elements whose class is derived from the input class The following example uses an ElementClassFilter to get all loads in the document Code Region 6 4 Using an ElementClassFilter to get loads Se lemon ias spero na as mece E DENS nite Using typeof LoadBase will yield all AreaLoad LineLoad and Pointload ElementClassFilter filter new ElementClassFilter typeof LoadBase i 7 Pop ly Edu ciMeSIIceelemem su tc Weise elo Ts I3 Toc ee exous Llene Cod lecuo eodeueweu m ipo ime Cl Le enecoJL Lector t exea e ICollection lt Element allLoads coloco Tcu c basses MEE 1 mue eme Ss There is a small subset of Element subclasses in the API which are not supported by the element class filter These types exist in the API but not in Revit s native object model which means that this
296. ents a Paper Size of Print Setup within the Autodesk Revit project Autodesk Revit DB PaperSizeSet A set that can contain any number of paper size objects Autodesk Revit DB PaperSource An object that represents a Paper Source of Print Setup within the Autodesk Revit project Autodesk Revit DB PaperSourceSet A set that can contain any number of paper source objects Autodesk Revit DB ViewSheetSetting Represents the View Sheet Set File gt Print within the Revit UI Autodesk Revit DB PrintSetting Represents the Print Setup File gt Print Setup within the Revit UI For an example of code that uses these objects see the ViewPrinter sample application that is included with the Revit Platform SDK UlView While the View class is the base class for all view types in Revit and keeps tracks of elements in the view the UlView class contains data about the view windows in the Revit user interface A list of all open views can be retrieved from the UlDocument using the GetOpenUlViews method The UlView class has methods to get information about the views drawing area as well as to pan and zoom the active view UlView GetWindowRectangle returns a rectangle that describes the size and placement of the UlView window It does not include the window border or title bar UlView GetZoomCorners gets the corners of the view s rectangle in model coordinates and UlView ZoomAndCenterRectangl offers the ability to zoom and pan the active view to center o
297. ents in the project Topics in this section e Worksets e Elements in Worksets e Visibility and Displa Elements in Worksets Each element in the document must belong to one and only one workset Each element has a Worksetld which identifies the unique workset to which it belongs Additionally given a Worksetld it is possible to get all of the elements in the document belonging to that Workset using the ElementWorksetFilter as shown below Code Region Element WorksetFilter laincopy to clipboar void WorksetElements Document doc Workset workset 1 public 2E 3 filter all elements that belong to the given workset 4 FilteredElementCollector elementCollector new FilteredElementCollector doc D ElementWorksetFilter elementWorksetFilter new ElementWorksetFilter workset Id false 6 ICollection element worksetElemsfounds elementCollector WherePasses elementWorksetFilter ToElements 7 8 how many elements were found 9 int elementsCount worksetElemsfounds Count 10 String message Element count elementsCount Il 12 Get name and or Id of the elements that pass the given filter and show a few of them 13 int count 5 show info for 5 elements only 14 foreach Element ele in worksetElemsfounds 15 16 if null ele 17 18 message nElementId ele Id 19 message Element Name ele Name 20 21 if 0 count 20 break 29 24 25
298. ents of the standards These words are capitalized This section defines how these special words should be interpreted The interpretation has been copied from Internet Engineering Task Force RFC 2119 WORD DEFINITION MUST This word or the term SHALL mean that the item is an absolute requirement MUST This phrase or the phrase SHALL NOT means that the item is an absolute prohibition NOT SHOULD This word or the adjective RECOMMENDED mean that there may exist valid reasons in particular circumstances to ignore the item but the full implications must be understood and carefully weighed before choosing a different course SHOULD This phrase or the phrase NOT RECOMMENDED mean that there may exist valid reasons in particular circumstances when the particular behavior is NOT acceptable or even useful but the full implications should be understood and the case carefully weighed before implementing any behavior described with this label MAY This word or the adjective OPTIONAL means that the item is truly optional One product team may choose to include the item because a particular type of user requires it or because the product team feels that it enhances the product while another product team may omit the same item
299. eof View3D 12 13 Func View3D bool isValidForPreview v gt settings IsViewIdValidForPreview v Id 14 15 View3D viewForPreview collector OfType View3D First View3D isValidForPreview 16 17 Set the preview settings 18 Transaction setTransaction new Transaction document Set preview view id 19 setTransaction Start 20 settings PreviewViewId viewForPreview Id 21 setTransaction Commit 22 23 Save the document 24 document Save 256 Load Family The Document class provides you with the ability to load an entire family and all of its symbols into the project Because loading an entire family can take a long time and a lot of memory the Document class provides a similar method LoadFamilySymbol to load only specified symbols For more details see Loading Families Settings The following table identifies the commands in the Revit Platform UI Manage tab and corresponding APIs Table 7 Settings in API and UI Ul command Settings Project Information Settings Project Parameters Project Location panel Settings Additional Settings Fill Patterns Settings Materials Settings Object Styles Phasing Phases Settings Structural Settings Settings Project Units Area and Volume Calculations on the Room amp Area panel Note Associated API Document Projectlnformation Document ParameterBindings Only for Shared Parameter Document Proje
300. eometry returns the geometry represented in the coordinate system of the family Use this for example when you want a picture of the generic table without regards to the orientation and placement location within the project This is also the only overload which returns the actual Revit geometry objects to you and not copies This is important because operations which use this geometry as input to creating other elements for example dimensioning or placement of face based families require the reference to the original geometry GetlnstanceGeometry returns the geometry represented in the coordinate system of the project where the instance is placed Use this for example when you want a picture of the specific geometry of the instance in the project for example ensuring that tables are placed parallel to the walls of the room This always returns a copy of the element geometry so while it would be suitable for implementation of an exporter or a geometric analysis tool it would not be appropriate to use this for the creation of other Revit elements referencing this geometry There are also overloads for both GetlnstanceGeometry and GetSymbolGeometry that transform the geometry by any arbitrary coordinate system These methods always return copies similar to GetInstanceGeometry The Geometrylnstance also stored a transformation from the symbol coordinate space to the instance coordinates This transform is accessible as the Transform prope
301. er int levelNumber 0 FilteredElementCollector collector new FilteredElementCollector document TCollection lt Element gt collection collector OfClass typeof Level ToEHElements foreach Element e in collection Level level e as Level if null level keep track of number of levels levelNumber get the name of the level levelInformation Append nLevel Name level Name Gel elas Slleveuciem ue idas Level len tormar uo apena Ee suom essc see CSc cee fro jece elewsundcomn or ae level esed ets enm crise oq re bdsm EE ect nitens eel l FP oe Elevate onmes aiii oF coral levels au Guiana cocuuenie Jus wre IIE Gis On Eyojoeincl Mae cus wp diee Sus ae levels La tele coctel show the level information in the messagebox TaskDiaTog Slovo Revir iene lin orma ton ING Sic 16 aL ove Creating a Level Using the Level command you can define a vertical height or story within a building and you can create a level for each existing story or other building references Levels must be added in a section or elevation view Additionally you can create a new level using the Revit Platform API The following code sample illustrates how to create a new level Code Region 15 2 Creating a new Level Level CreateLevel Autodesk Revit Document document The elevation to apply to the new level double se kevat Ton 20 0 Begin to create a level Level level document Crea
302. er 0 25 reFrom Beginning PointOnEdge poeA app Create NewPointOnEdge curvel GeometryCurve Reference pointLocationOnCurve25 ReferencePoint rpA document FamilyCreate NewReferencePoint poeA PointLocationOnCurve pointLocationOnCurve75 new PointLocationOnCurve PointOnCurveMeasurementType NormalizedCurveParameter 0 75 reFrom Beginning PointOnEdge poeB app Create NewPointOnEdge curvel GeometryCurve Reference ReferencePoint rpB document FamilyCreate NewReferencePoint poeB rpAr Clear rpAr Append rp1 rpAr Append rp3 CurveByPoints curve2 document FamilyCreate NewCurveByPoints rpAr PointOnEdge poeC app Create NewPointOnEdge curve2 GeometryCurve Reference ReferencePoint rpC document FamilyCreate NewReferencePoint poeC PointOnEdge poeD app Create NewPointOnEdge curve2 GeometryCurve Reference ReferencePoint rpD document FamilyCreate NewReferencePoint poeD pointLocationOnCurve75 pointLocationOnCurve25 pointLocationOnCurve75 throw new Exception Please open a curtain family document before calling this command Figure 62 Curtain panel family Figure 63 Curtain panel assigned to divided surface PointOnCurveM PointOnCurveM Adaptive Components Adaptive Components are designed to handle cases where components need to flexibly adapt to many unique contextual conditions For example adaptive components could be used in repeating systems generated by arraying multi
303. er there are other ways to save data between command executions for example you can use the Revit shared parameters mechanism to store data in the Revit project You can add External Commands to the External Tools Panel under the External Tools menu button or as a custom ribbon panel on the Add Ins tab Analyze tab or a new custom ribbon tab See the Walkthrough Hello World and Walkthrough Add Hello World Ribbon Panel for examples of these two approaches External tools ribbon tabs and ribbon panels are initialized upon start up The initialization steps are as follows e Revit reads manifest files and identifies o External Applications that can be invoked o External Tools that can be added to the Revit External Tools menu button e External Application session adds panels and content to the Add ins tab I ExternalCommand You create an external command by creating an object that implements the IExternalCommand interface The IExternalCommand interface has one abstract method Execute which is the main method for external commands The Execute method has three parameters e commandData ExternalCommandData e message String e elements ElementSet commandData ExternalCommandData The ExternalCommandData object contains references to Application and View which are required by the external command All Revit data is retrieved directly or indirectly from this parameter in the external command For example the following stateme
304. er in UI but an integer value in API A dr Ore eT IG Ema 0 Oj else int isTrue param AsInteger occupe cus Esc c Creating a Family Document The ability to modify Revit Family documents and access family types and parameters is available from the Document class if the Document is a Family document as determined by the IsFamilyDocument property To edit an existing family while working in a Project document use the EditFamily functions available from the Document class and then use LoadFamily to reload the family back into the owner document after editing is complete To create a new family document use Application NewFamilyDocument Code Region 13 3 Creating a new Family document create a new family document using Generic Model rft template string templateFileName C Documents and Settings All Users Application Data Autodesk RST 2011 Imperial Templates Generic Mode mri eae Document familyDocument application NewFamilyDocument templateFileName if null familyDocument throw new Exception Cannot open family document Nested Family Symbols You can filter a Family Document for FamilySymbols to get all of the FamilySymbols loaded into the Family In this code sample all the nested FamilySymbols in the Family for a given Familylnstance are listed Code Region 13 4 Getting nested Family symbols in a Family public void GetLoadedSymbols Autodesk Revit DB Document document FamilyInstance familyI
305. er is the server name not the string returned by the ModelPathUtils GetRevitServerPrefix The second parameter does not include the initial forward slash See the following sample code The folder separator 1s a forward slash too Read the TransmissionData object via the TransmissionData ReadTransmissionData method Pass in the ServerPath obtained in the previous step Here is the code showing the implementation of way 2 view plaincopy to clipboardprint 1 TransactionAttribute Autodesk Revit Attributes TransactionMode Manual 2 public class RevitCommand IExternalCommand 3 4 public Result Execute ExternalCommandData commandData Ds ref string messages ElementSet elements 6 7E UIApplication app commandData Application 8 Document doc app ActiveUIDocument Document 9 Transaction trans new Transaction doc ExComm 10 trans Start 11 ServerPath serverPath new ServerPath SHACNGO35WQRP testmodel rvt 12 TransmissionData transData TransmissionData ReadTransmissionData serverPath 13 string mymessage null 14 if transData null 15 16 access the data in the transData here 17 18 else 19 20 Autodesk Revit UI TaskDialog Show Unload Links 21 The document does not have any transmission data 20 23 trans Commit 24 return Result Succeeded 25 F Performance Adviser The performance adviser feature of the Revit API is designed to analyze a document an
306. erial 25 26 27 TaskDialog Show Revit Element material material Name 28 break 29 30 31 B2 m Note If the material property is set to By Category in the UI the Elementld for the material is Elementld InvalidElementld and cannot be used to retrieve the Material object as shown in the sample code Try retrieving the Material from Category as described in the next section Some material properties contained in other compound parameters are not accessible from the API As an example in the following figure for System Family Railing the Rail Structure parameter s StorageType is StorageType None Asa result you cannot get material information in this situation Type Properties System Family Railing Steel Rail no offset Type Parameters ame e j Railing Height Rail Structure E EEE Edit Rails Family Railing Type Steel Rail no offset Rails DC Mee 3 Rail 3 609 6 0 0 Circular Handrall 12 By Category gt Figure 107 Rail structure property Material and Familyl nstance Beam Column and Foundation Familylnstances have another way to get their material using their StructuralMaterialld property This property returns an Elementld which identifies the material that defines the instance s structural analysis properties Code Region Getting an element material from a family instance view plaincopy to clipboardprint 1 public Material Get
307. ernalEventExampleApp thisApp ShowForm commandData Application 55 return Result Succeeded 56 57 catch Exception ex 58 59 message ex Message 60 return Result Failed 61 62 63 Raise Event Once the modeless dialog is displayed the user may interact with it Actions in the dialog may need to trigger some action in Revit When this happens the ExternalEvent Raise method is called The following example is the code for a simple modeless dialog with two buttons one to raise our event and one to close the dialog Code Region Raise the Event public partial class ExternalEventExampleDialog Form private ExternalEvent m ExEvent private ExternalEventExample m Handler public ExternalEventExampleDialog ExternalEvent exEvent ExternalEventExample handler InitializeComponent m ExEvent exEvent m Handler handler protected override void OnFormClosed FormClosedEventArgs e we own both the event and the handler we should dispose it before we are closed m ExEvent Dispose m ExEvent null m Handler null do not forget to call the base class base OnFormClosed e private void closeButton Click object sender EventArgs e Closet private void showMessageButton_Click object sender EventArgs e m ExEvent Raise When the ExternalEvent Raise method is called Revit will wait for an available Idling timecycle and then call the IExternalEventHandler Ex
308. ers Option 1 2 Option 2 3 Option 3 Figure 17 Combo box with grouping ComboBox has three events e CurrentChanged triggered when the current item of the ComboBox is changed e DropDownClosed triggered when the drop down of the ComboBox is closed e DropDownClosed triggered when the drop down of the ComboBox is opened See the code region in the following section on stacked ribbon items for a sample of adding a ComboBox to a ribbon panel Stacked Panel Items To conserve panel space you can add small panel items in stacks of two or three Each item in the stack can be a push button a drop down button a combo box or a text box Radio button groups and split buttons cannot be stacked Stacked buttons should have an image associated through their Image property rather than Largelmage A 16x16 image is ideal for small stacked buttons The following example produces the stacked text box and combo box in Figure 13 Code Region Adding a text box and combo box as stacked items view plaincopy to clipboardprint 1 private void AddStackedButtons RibbonPanel panel 2 1 3 ComboBoxData cbData new ComboBoxData comboBox 4 5 TextBoxData textData new TextBoxData Text Box 6 textData Image 7 new BitmapImage new Uri D Sample HelloWorld bin Debug 39 Globe 16x16 png 8 textData Name Text Box 9 textData ToolTip Enter some text here 10 textData LongDescription p This is text that will appear
309. ers 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 The following example uses an ElementClassFilter to get all Familylnstance elements in the document and then uses a LINQ query to narrow down the results to those FamilyInstances with a specific name Code Region 6 15 Using LI NQ query 7 hee Bleu ec ders et white to mind amily instances aos nane la OOO Soluce ElementClassFilter filter new ElementClassFilter typeof FamilyInstance 7 Aeply tne filter wor kne velemenes tame tac ve doc nen Eil er edElementCollector collector men FilteredElementCollector document collector Ulmer sis NINE CTS Use Vining quer to els E mede ASSI cime e Sube s exe eme i eO es DIESE var query from element in collector where element Neame GO x 90 student select element M ae round elemento to famil instan eS this cast to FamilyInstance is safe because ElementClassFilter for FamilyInstance was used DMst bamilyinstamee gt toamulyinstances query Case Family instance 2loliste lt Pamilyinstance gt s Bounding Box filters The BoundingBox filters e BoundingBoxlsinsideFilter e BoundingBoxintersectsFilter e BoundingBoxContainsPointFilter help you find elements whose bounding boxes meet a certa
310. erties to access the ID of the master schedule that generates this ScheduleSheetInstance the rotation of the schedule on the sheet the location on the sheet where the schedule is placed in sheet coordinates as well as a flag that identifies if the ScheduleSheetInstance is a revision schedule in a titleblock family Revit Geometric Elements Topics tn this section e Walls Floors Roofs and Openings e Family Instances e Stairs and Railings e Family Creation e Conceptual Design e Datum and Information Elements e Annotation Elements e Geometry e Sketching e Material Walls Floors Ceilings Roofs and Openings This chapter discusses Elements and the corresponding ElementTypes representing built in place construction e HostObject The first two sections focus on HostObject and corresponding HostObjAttributes subclasses e Foundation Different foundations in the API are represented as different classes including Floor ContFooting and FamilyInstance The Floor and Foundation section compares them in the API e CompoundStructure This section describes the CompoundStructure class and provides access to Material Some host element types have thermal properties which are described in the Thermal Properties section In addition to host Elements the Opening class is introduced at the end of this section Topics in this section e Walls e Floors Ceilings and Foundations e Roofs e Curtains e Other Elements e Compound
311. es SIS O Worse ve abr OCA IO MARE o EHE ce qu M MEC M E ME Eq M Create Opening In the Revit Platform API use the Document NewOpening method to create an opening in your project There are four method overloads you can use to create openings in different host elements Code Region 11 7 NewOpening Create a new Opening in a beam brace and column public Opening NewOpening Element famInstElement CurveArray profile eRefFace iFace Cresta mer Oasis da vel eee dB db eXONS elo Geil bibere ulol e Costing NewCprsiniLine Cg Lee Mosca lem nte Cuicyvelutices uelle loool Jo exer euisuce eue Create a new Opening Element public Opening NewOpening Level bottomLevel Level topLevel CurveArray profile Create an opening in a straight wall or arc wall public Opening NewOpening Wall XYZ pntStart XYZ pntEnd e Create an Opening in a Beam Brace or Column Use to create an opening in a family instance The Face parameter indicates the face on which the opening is placed e Create a Roof Floor or Ceiling Opening Use to create an opening in a roof floor or ceiling e The bPerpendicularFace parameter indicates whether the opening is perpendicular to the face or vertical e Ifthe parameter is true the opening is perpendicular to the host element face See the following picture Level 2 4 D Figure 39 Opening cut perpendicular to the host element face Level 2 10 26 y Figure 40 Open
312. es the basis vectors and returns the result ScaleBasisAndOrigin Scales the basis vectors and the transformation origin returns the result OfPoint Applies the transformation to the point The Origin property is used OfVector Applies the transform to the vector The Origin property is not used AlmostEqual Compares two transformations AlmostEqual is consistent with the computation mechanism and accuracy in the Revit core code Additionally Equal and the operator are not implemented in the Transform class The API provides several shortcuts to complete geometry transformation The Transformed property in several geometry classes is used to do the work as shown in the following table Table 48 Transformed Methods Class Name Function Description Curve get_Transformed Transform transform Applies the specified transformation to a curve GeometryElement GetTransformed Transform transform Transforms a copy of the geometry in the original element Profile get Transformed Transform transform Transforms the profile and returns the result Mesh get Transformed Transform transform Transforms the mesh and returns the result Note The transformed method clones itself then returns the transformed cloned result In addition to these methods the Instance class which is the parent class for elements like family instances link instances and imported CAD content has two methods which provide the transform for a given Instance The GetTra
313. es to represent the same properties available when editing a cut mark type in the UI such as CutLineAngle and CutLineExtension It is associated with a StairsType object and can be retrieved using the BuiltInParameter STAIRSTYPE CUTMARK TYPE as shown below Code Region Getting the CutMarkType for Stairs te utMarkType GetCutMark Stairs stairs ew plaincopy 1 priv 2o 34 CutMarkType cutMarkType null 4 StairsType stairsType stairs Document GetElement stairs GetTypeld as StairsType 5 Parameter paramCutMark stairsType get Parameter BuiltInParameter STAIRSTYPE CUTMARK TYPE 6 if paramCutMark StorageType StorageType ElementId should be an element id 7 8 ElementId cutMarkId paramCutMark AsElementId 9 cutMarkType stairs Document GetElement cutMarkId as CutMarkType 10 11 12 return cutMarkType 13 Stairs Components The Stairs class represents a stairs element in Revit and contains properties that represent information about the treads risers number of stories as well as the height of the stairs and base and top elevation Methods of the Stairs class can be used to get the stairs landing components stairs run components and stairs supports The following example finds all of the Stairs that are by component and outputs some information on each of the Stairs to a Task Dialog Note that this example uses a category filter with the BuiltInCategory OST_Stairs which will return Elementlds for all
314. ettings GetGraphicOverrides userName 11 12 get graphicSettings for a workset if specified 13 else if worksetId WorksetId InvalidWorksetId dal graphicSettings displaySettings GetGraphicOverrides worksetId 15 16 get graphic settings for the OwnedByCurrentUser status T else if ownedbyCurrentUser 18 graphicSettings displaySettings GetGraphicOverrides CheckoutStatus OwnedByCurrentUser 19 20 otherwise get graphic settings for the CurrentWithCentral status 21 else 22 graphicSettings displaySettings GetGraphicOverrides ModelUpdatesStatus CurrentWithCentral 235 24 return graphicSettings 125 y The overloaded method WorksharingDisplaySettings SetGraphicOverrides sets the graphic overrides assigned to elements based on the given criteria Code Region Graphic Overrides view plaincopy to clipboardprint 1 public void SetWorksharingDisplaySettings Document doc WorksetId worksetId String userName 2 3 String message String Empty 4 5 get or create a WorksharingDisplaySettings current active document 6 WorksharingDisplaySettings displaySettings WorksharingDisplaySettings GetOrCreateWorksharingDisplaySettings doc 7 8 set a new graphicSettings for CheckoutStatus NotOwned 9 WorksharingDisplayGraphicSettings graphicSettings new WorksharingDisplayGraphicSettings true new Color 255 0 0 10 displaySettings SetGraphicOverrides CheckoutStatus NotOwned graphicSettin
315. etween paragraphs of text Smallest space between interactive controls Smallest space between a non interactive control and any other control When a control is dependent on another control it should be indented 12 DLUS or 18 relative pixels which by design is the distance between check boxes and radio buttons from their labels Paper Size Letter S Ounce Automatically Se ect rientatian 7 above the bottom of the group box 3 down from the top of the control 3 or no space 12 Portrait Landscape Figure 201 Group box within a standard Print dialog e Exists with at least one other group box e A label that o describes the group o follows sentence style o isinthe form of a noun or noun phrase o does not use ending punctuation e ASpacing and Margins section describes spacing rules 11 above the bottom of the group box 5 down from the top of the control 11 5 or no space 18 Poor Examples What Not to Use The following are examples of what should not be done Group boxes without a label or a group box with only one control When Dragging the ViewCube Iv Snap to closest view One group box in a dialog The Materials single group box title is redundant with the dialog title and can be removed oaterials errar Padre Tile 24 EF Figure 202 Group box with no label and group box with one control and Group box with title that is redundant with d
316. event handler view plaincopy to clipboardprint 1 private static void AddSlideOut RibbonPanel panel 2 3 string assembly D Sample HelloWorld bin Debug Hello d1l 4 5 panel AddSlideOut 6 y create some controls for the slide out 8 PushButtonData b1 new PushButtonData ButtonName1 Button 1 9 assembly Hello HelloButton 10 bl Largelmage 11 new BitmapImage new Uri Q D NSampleNMHelloWworldNbinNDebugN39 Globe 32x32 png 12 PushButtonData b2 new PushButtonData ButtonName2 Button 2 13 assembly Hello HelloTwo 14 b2 Largelmage 15 new BitmapImage new Uri Q D NSampleMHelloWorldNbinNDebugN39 Globe 16x16 png 16 17 items added after call to AddSlideOut are added to slide out automatically 18 panel AddItem b1 19 panel AddItem b2 Revit style Task Dialogs A TaskDialog is a Revit style alternative to a simple Windows MessageBox It can be used to display information and receive simple input from the user It has a common set of controls that are arranged in a standard order to assure consistent look and feel with the rest of Revit Display Task Dialog Hello Revit Hello Revit his sample shows how to use a Revit task dialog to communicate with the user The command links below open additional task dialogs with more information View information about the Revit installation View information about the active document Click here forthe Revit API Dev
317. events are enabled and acts accordingly For more details see Access to Revit Event in the Add In Integration section Discipline Controls The properties e Application IsArchitectureEnabled e Application IsStructureEnabled e Application IsStructuralAnalysisEnabled e Application lsMassingEnabled e Application IsEnergyAnalysisEnabled e Application IsSystemsEnabled e Application lsMechanicalEnabled e Application lsMechanicalAnalysisEnabled e Application IsElectricalEnabled e Application IsElectricalAnalysisEnabled e Application IsPipingEnabled e Application IsPipingAnalysisEnabled provide read and modify access to the available disciplines An application can read the properties to determine when to enable or disable aspects of it s UI When a discipline s status is toggled Revit s UI will be adjusted and certain operations and features will be enabled or disabled as appropriate Enabling an analysis mode will only take effect if the corresponding discipline is enabled For example enabling mechanical analysis will not take effect unless the mechanical discipline is also enabled How to use Application properties to enforce a correct version for your add in Sometimes you need your add in to operate only in the presence of a particular Update Release of Revit due to the presence of specific fixes or compatible APIs The following sample code demonstrates a technique to determine if the Revit version is any Update Release a
318. f objects found by geometry extraction GeometryElement eometrylnstances NM ET Nested Solids Meshes Curves Palylines Nested Geametrylnstances lore nesting Curves A curve represents a path in 2 or 3 dimensions in the Revit model Curves may represent the entire extent of an element s geometry e g CurveElements or may appear as a single piece of the geometry of an element e g the centerline of a wall or duct Curves and collections of curves are used as inputs in many element creation methods in the API e Curve parameterization e Curve analysis e Curve types e Mathematical representations of curve types e Curve creation e Curve collections Curve analysis There are several Curve members which are tools suitable for use in geometric analysis In some cases these APIs do more than you might expect by a quick review of their names Intersect The Intersect method allows you compare two curves to find how they differ or how they are similar It can be used in the manner you might expect to obtain the point or point s where two curves intersect one another but it can also be used to identify e Collinear lines e Overlapping lines e Identical curves e Totally distinct curves with no intersections The return value identifies these different results and the output IntersectionSetResult contains information on the intersection point s Project The Project method projects a point onto the
319. f the element is known the element can be retrieved from the document e Element filtering and iteration this is a good way to retrieve a set of related elements in the document e Selected elements retrieves the set of elements that the user has selected e Specific elements some elements are available as properties of the document Each of these methods of element retrieval is discussed in more details in the following sections Getting an Element by ID When the Elementld of the desired element is known use the Document Element property to get the element Filtering the Elements Collection The most common way to get elements in the document is to use filtering to retrieve a collection of elements The Revit API provides the FilteredElementCollector class and supporting classes to create filtered collections of element which can then be iterated See Filtering for more information Rather than getting a filtered collection of all of the elements in the model you can access just the elements that have been selected You can get the selected objects from the current active document using the UlDocument Selection Elements property For more information on using the active selection see Selection Accessing Specific Elements from Document In addition to using the general way to access Elements the Revit Platform API has properties in the Document class to get the specified Elements from the current active document without iterating a
320. face with the old SketchPlane use the Curve or SketchPlane property setters o If new Curve does not lay in the same SketchPlane or the new SketchPlane does not lay on the same planar face with the old SketchPlane you must simultaneously change the Curve value and the SketchPlane value using SetPlaneAndCurve to avoid internal data inconsistency LineStyle Line style does not have a specific class but is represented by the Document Element class e Allline styles for a ModelCurve are available from the LineStyles property in the Element Properties dialog box e The Element object that represents line style cannot provide information for all properties Most properties will return null or an empty collection e The only information returned is the following o Id o Uniqueld o Name e Use the getLineStyle method to retrieve the current line style or use the setLineStyle method to set the current line style to one returned from the LineStyles property Material In the Revit Platform API material data is stored and managed as an Element Just as in the Revit Ul a material can have several assets associated with it but only thermal and structural referred to as Physical in the Revit Ul assets can be assigned using the API Some material features are represented by properties on the Material class itself such as FillPattern Color or Render while others are available as properties of either a structural or thermal asset associated
321. flected ceiling plan view ColumnSchedule CostReport Detail DraftingView DrawingSheet Elevation EngineeringPlan FloorPlan Internal Legend LoadsReport PanelSchedule PressureLossReport Rendering Coulmn schedule view Cost report view Detail view Drafting view Drawing sheet view Elevation view Engineering view Floor plan view Revit s internal view Legend view Loads report view Panel schedule view Pressure Loss Report view Rendering view Report Report view Schedule Schedule view Section Cross section view ThreeD 3 D view Undefined Walkthrough Undefined unspecified view Walkthrough view The second way to classify views is by the class type The following table lists the view types and the corresponding views in the Project browser Table 45 Project Browser Views Project Browser Views Area Plans Ceiling Plans Graphic Column Schedule Detail Views Drafting Views Sheets Elevations Structural Plans Revit Structure Floor Plans Legends Reports Revit MEP Reports Revit MEP Reports Revit MEP Renderings Reports Schedules Quantities Sections 3D Views Walkthroughs View Type ViewType AreaPlan ViewType CeilingPlan ViewType ColumnSchedule ViewType Detail ViewType DraftingView ViewType DrawingSheet ViewType Elevation ViewType EngineeringPlan ViewType FloorPlan ViewType Legend ViewType LoadsReport ViewType PanelSchedule ViewType PresureLossReport Vie
322. floor elem as Floor 9 if floor null 10 11 SlabShapeEditor slabShapeEditor floor SlabShapeEditor 12 slabShapeEditor ResetSlabShape 13 14 15 For more detailed examples of using the SlabShapeEditor and related classes see the SlabShapeEditing sample application included in the Revit SDK Roofs Roofs in the Revit Platform API all derive from the RoofBase object There are two classes e FootPrintRoof represents a roof made from a building footprint e ExtrusionRoof represents roof made from an extruded profile Both have a RoofType property that gets or sets the type of roof This example shows how you can create a footprint roof based on some selected walls Code Region 11 3 Creating a footprint roof Before invoking this sample select some walls to add a roof over Mae Litem ih here xe a level named Rooi in th do e ES Woe Aes inven qe lain SHE level pi dbi eoe Llene do lec collleccoic mew lillie eee eue dictare C ll aee Oe Veloce USE collector WherePasses new ElementClassFilter typeof Level var elements ron clement dea collector where clement Nahe xo select element Leve lm evel elements aE eVe e eom eA lLene EO ROOLTYpS TOOTEV pS nul i e e ea a e OO foreach RoofType rt in document RoofTypes rooftype rt break CSS acoso le ato Autodesk Revit ApplicationServices Application application document Application DS RO Okage a C a a ONES CO en e l
323. following properties e The origin of the face e The axis of extrusion e The radius vectors in X and Y These vectors are the circle s unit vectors multiplied by the radius of the circle Note that the unit vectors may represent either a right handed or left handed control frame The parametric equation for this face is P u v Py ry cos u ry sin u vn ConicalFace A face defined by rotation of a line about an axis The Revit API provides the following properties e The origin of the face e The axis of the cone e The radius vectors in X and Y These vectors are the unit vectors multiplied by the radius of the circle formed by the revolution Note that the unit vectors may represent either a right handed or left handed control frame e The half angle of the face The parametric equation for this face is P u v Py v sin a r cos u ry sin u cos a ngyis RevolvedFace A face defined by rotation of an arbitrary curve about an axis The Revit API provides the following properties e The origin of the face e The axis of the face e The profile curve e The unit vectors for the rotated curve incorrectly called Radius The parametric equation for this face is Pu v P5 C v r cos u r sin u Maris RuledFace A ruled surface is created by sweeping a line between two profile curves or between a curve and a point The Revit API provides the curve s and point s as properties The pa
324. for Name Id Uniqueld and Parameters The following code sample uses the EnergyDataSettings class The result appears in a TaskDialog after invoking the command Code Region 28 7 Using the EnergyDataSettings class public void GetInfo EnergyData Document document EnergyDataSettings energyData EnergyDataSettings GetFromDocument document if null energyData string message energyData message t midi Oem eme Detail pe TaskDialog Show Revit message Analysis Visualization The Revit API provides a mechanism for external analysis applications to easily display the results of their computation in the Revit model The SpatialFieldManager class is the main class for communicating analysis results back to Revit It is used to create delete and modify the containers in which the analysis results are stored The AnalysisResultSchema class contains all information about one analysis result such as a description and the names and multipliers of all units for result visualization Multiple AnalysisResultSchemas can be registered with the SpatialField Manager The AnalysisDisplayStyle class can then be used to control the appearance of the results Creation and modification of AnalysisDisplayStyle from a plug in is optional end users can have the same control over the presentation of the analysis results with the Revit UI The data model supported by Revit API requires that analysis results are specified at a certai
325. fter the initial known Revit release Code Region Use VersionBuild to identify if your add in is compatible view plaincopy to clipboardprint 1 public void GetVersionInfo Autodesk Revit ApplicationServices Application app 2 EN 35 20110309 2315 is the datecode of the initial release of Revit 2012 4 if app VersionNumber 2012 amp amp 5 String Compare app VersionBuild 20110309 2315 gt 0 6 Te TaskDialog Show Supported version 8 This application supported in this version 9 10 else 11 12 TaskDialog dialog new TaskDialog Unsupported version 13 dialog MainIcon TaskDialogIcon TaskDialoglIconWarning T4 dialog MainInstruction This application is only supported in Revit 2012 UR1 and later 15 dialog Show 16 Document Functions Document stores the Revit Elements manages the data and updates multiple data views The Document class mainly provides the following functions The Document class represents an open Autodesk Revit project Settings Property The Settings property returns an object that provides access to general components within Revit projects For more details see Settings Place and Locations Each project has only one site location that identifies the physical project location on Earth There can be several project locations for one project Each location is an offset or rotation of the site location For more details see Place and Locations Type C
326. g CreateIndependentTag Autodesk Revit DB Document document Wall wall 2 0 3 make sure active view is not a 3D view ae Autodesk Revit DB View view document ActiveView 5 6 define tag mode and tag orientation for new tag 7 TagMode tagMode TagMode TM_ADDBY_CATEGORY 8 TagOrientation tagorn TagOrientation Horizontal 9 10 Add the tag to the middle of the wall 11 LocationCurve wallLoc wall Location as LocationCurve 12 XYZ wallStart wallLoc Curve get EndPoint 0 13 XYZ wallEnd wallLoc Curve get_EndPoint 1 14 XYZ wallMid wallLoc Curve Evaluate 5 true 15 16 IndependentTag newTag document Create NewTag view wall true tagMode tagorn wallMid 17 if null newTag ig 19 throw new Exception Create IndependentTag Failed 20 21 newTag TagText is read only so we change the Type Mark type parameter to 224 set the tag text The label parameter for the tag family determines 23 what type parameter is used for the tag text 24 25 WallType type wall WallType 26 275 Parameter foundParameter type get Parameter Type Mark 28 bool result foundParameter Set Hello 29 30 set leader end condition free SL otherwise leader end point move with elbow point 32 233 newTag LeaderEndCondition LeaderEndCondition Free 34 XYZ elbowPnt wallMid new XYZ 5 0 5 0 0 0 255 newTag LeaderElbow elbowPnt 363 XYZ headerPnt wallMid new XYZ
327. ge the box capacity and display it in the view However you can assign a null value to the SectionBox to keep the modified value and make the section box invisible in the view To avoid displaying the section box change the section box value then set the section box to null The following code sample illustrates this process Notice it only works when the Section Box check box is selected in the View property dialog box Code Region Hiding the Section Box view plaincopy to clipboardprint 1 private void ExpandSectionBox View3D view 2 1 35 The orignial section box 4 BoundingBoxXYZ sectionBox view SectionBox 5 6 Expand the section box 7 XYZ deltaXYZ sectionBox Max sectionBox Min 8 sectionBox Max deltaXYZ 2 9 sectionBox Min deltaXYZ 2 10 11 After reseting the section box it will be shown in the view d It only works when the Section Box check box is 13 checked in View property dialog 14 view SectionBox sectionBox 15 16 Setting the section box to null will make it hidden 17 view SectionBox null line x 18 Note If you set view SectionBox to null it has the same effect as hiding the section box using the Section Box parameter The current section box is stored by view and is restored when you show the section box using the SectionBox parameter The coordinate of Max and Min points of BoundingBoxXYZ returned from SectionBox property is not WCS To convert the coordina
328. ges not representing a part of the model level geometry and thus do not provide a Reference Edge direction Direction is normally clockwise on the first face first representing an arbitrary face which Revit has identified for a particular edge But because two different faces meet at one particular edge and the edge has the same parametric direction regardless of which face you are concerned with sometimes you need to figure out the direction of the edge on a particular face The figure below illustrated how this works For Face 0 the edges are all parameterized clockwise For Face 1 the edge shared with Face 0 is not re parameterized thus with respect to Face 1 the edge has a reversed direction and some edges intersect where both edges parameters are O or 1 Direction of edge wa This should be the direction of the edge on this face but it is reversed due to the evaluation on the other face Edge parameterization The API sample PanelEdgeLengthAngle shows how to recognize edges that are reversed for a given face It uses the tangent vector at the edge endpoints to calculate the angle between adjacent edges and detect whether or not to flip the tangent vector at each intersection to calculate the proper angle a C2 Instance Properties xj Ux i Family Rectangle Surface with length angle parai Load pm Type Solid z Edit Type Instance Parameters Control selected ar Ea be cr
329. ges the room boundary To update the room boundary data use the transaction mechanism in the following code Code Region 28 4 Using a transaction to update room boundary public void UpdateRoomBoundary UIApplication application Room room Level level Document document application ActiveUIDocument Document Get the size before creating a wall int size room GetBoundarySegments new SpatialElementBoundaryOptions First Count string message Room boundary size before wall size Prepare a line Dac MATAS nce C PEDE XYZ endrRos mew xx CUL Line line application Application Create NewLine startPos endPos true Create a new wall and enclose the creating into a single transaction Transaction transaction new Transaction document Create Wall it transaction start TransactionStatus Started Wall wall Welil Ciceece document line level lo false IE JE Gud Sar ron Committee Gee Tae may slze size room GetBoundarySegments new SpatialElementBoundaryOptions First Count message nRoom boundary size after wall size TaskDialog Show Revit message ieee is ele ds Ome CAO Id IL E E e For more details see Transaction Plan Topology The level plan that rooms lie in have a topology made by elements such as walls and room separators The PlanTopology and PlanCircuit classes are used to present the level topology e Get the PlanTopology object from the Docume
330. gh Get Selected Element Parameters e By accessing the parameter directly through the overloaded Element Parameter property If the Parameter doesn t exist the property returns null e By accessing a parameter by name via the Element ParametersMap collection You can retrieve the Parameter object from an Element if you know the name string built in ID definition or GUID The Parameter String property overload gets a parameter based on its localized name so your code should handle different languages if it s going to look up parameters by name and needs to run in more than one locale The Parameter GUID property overload gets a shared parameter based on its Global Unique ID GUID which is assigned to the shared parameter when it s created Topics in this section e Walkthrough Get Selected Element Parameters e Definition e BuiltlnParameter e StorageType e AsValueString and SetValueString e Parameter Relationships e Adding Parameters to Elements Walkthrough Get Selected Element Parameters The Element Parameters are retrieved by iterating through the Element ParameterSet The following code sample illustrates how to retrieve the Parameter from a selected element NoteThis example uses some Parameter members such as AsValueString and StorageType which are covered later in this chapter Code Region 8 1 Getting selected element parameters void GetElementParameterInformation Document document Element element Rima
331. grid failed MS en ae ene Gteoated Grid lineGrid Name New Namel Create the geometry arc which the grid locates XYZ endo new XYZ 0 O 0 XYZ endl new XYZ 10 40 0 XYZ pointOnCurve new XYZ 5 7 0 Arc geomArc document Application Create NewArc end0 endl pointOnCurve Create a grid using the geometry arc Grid arcGrid document Create NewGrid geomArc if null arcGrid throw new Exception Create a new curved grid failed Modity Ene name of Ene created grid arcGrid Name New Name2 Noteln Revit the grids are named automatically in a numerical or alphabetical sequence when they are created You can also create several grids at once using the Document NewGrids method which takes a CurveArray parameter Phase Some architectural projects such as renovations proceed in phases Phases have the following characteristics e Phases represent distinct time periods in a project lifecycle e The lifetime of an element within a building is controlled by phases e Each element has a construction phase but only the elements with a finite lifetime have a destruction phase All phases in a project can be retrieved from the Document object A Phase object contains three pieces of useful information Name ID and Uniqueld The remaining properties always return null or an empty collection Each new modeling component added to a project has a Created Phase ID and a Demolished Phase ID
332. gs 11 12 set a new graphicSettings for ModelUpdatesStatus CurrentWithCentral 13 graphicSettings new WorksharingDisplayGraphicSettings true new Color 128 128 0 14 displaySettings SetGraphicOverrides ModelUpdatesStatus CurrentWithCentral graphicSettings 15 16 set a new graphicSettings by a given userName 17 graphicSettings new WorksharingDisplayGraphicSettings true new Color 255 18 displaySettings SetGraphicOverrides userName graphicSettings 19 20 set a new graphicSettings by a given workset Id 21 graphicSettings new WorksharingDisplayGraphicSettings true new Color 0 0 255 22 displaySettings SetGraphicOverrides worksetId graphicSettings 23 The WorksharingDisplaySettings class can also be used to control which users are listed in the displayed users for the document The RemoveUsers method removes users from the list of displayed users and permanently discards any customization of the graphics Only users who do not own any elements in the document can be removed The RestoreUsers method adds removed users back to the list of displayed users and permits customization of the graphics for those users Note that any restored users will be shown with default graphic overrides and any customizations that existed prior to removing the user will not be restored Code Region Removing Users VIC nlaincnnys ta rlinhnarnnrint view plaincopy to clipboardprint 1 public void Remo
333. gure 118 Created section view The previous picture displays the corresponding section view The wall outside the view boundary is not displayed Define a Section Box BoundingBoxXYZ is also used to define a section box for a 3D view retrieved from the View3D SectionBox property Select the Section Box property in the Properties Dialog box The section box is shown as follows Section Box Crop Region Figure 119 3D view section box Other Uses e Defines a box around an element s geometry Element BoundingBox Property The BoundingBoxXYZ instance retrieved in this way is parallel to the coordinate axes e Used in the NewViewSection method in the Creation Document class The following table identifies the main uses for this class Table 49 BoundingBoxXYZ properties Property Name Usage Max Min Maximum Minimum coordinates These two properties define a 3D box parallel to any coordinate axis The Transform property provides a transform matrix that can transform the box to the appropriate position Transform Transform from the box coordinate space to the model space Enabled Indicates whether the bounding box is turned on MaxEnabled Defines whether the maximum minimum bound is active for a given dimension MinEnabled If the Enable property is false these two properties should also return false If the crop view is turned on both MaxEnabled property and MinEnabled property return true Dod ajen g If the crop view is
334. h OK and Cancel buttons Default button or link All tasks dialogs should have a default button or link explicitly assigned If the task dialog contains an OK button it should be the default NoteThe exception is custom task dialogs with command links which have actions that are equally viable with none being better than the other should not get assigned a default choice All dialogs using only commit buttons must be assigned a default button Navigation Tabs Use when there are loosely related yet distinct chunks of information need to exist within the same UI but there is not enough room to display it all in a clear manner Separate the UI into distinct modal zones each one represented by a tab with a descriptive label The entire dialog should be treated as a single window with a single set of Commit buttons e All of the tabs should be visible at the same time e Never have a single tab in a static Ul such as dialog Instead use the tab s title for the page or dialog Exception if the number of tabs grows dynamically and the default is one e g Excel s open workbook tabs e Tabs are for navigation only Selecting a tab should not perform any other action such as a commit besides simply switching to that page in the window e Avoid nesting tabs within tabbed windows In this case consider launching a child window e Donotchange the label on a tab dynamically based on interaction within the parent window Variations V
335. h Start Sa 6 Find StairsPathType 7 FilteredElementCollector collector new FilteredElementCollector document 8 ICollection lt ElementId gt stairsPathIds collector OfClass typeof StairsPathType ToElementIdsElementId eu 10 Find a FloorPlan 11 ElementId planViewId ElementId InvalidElementId 12 FilteredElementCollector viewCollector new FilteredElementCollector document 13 ICollection ElementId viewIds viewCollector OfClass typeof View ToElementIdsElementId 14 foreach ElementId viewId in viewIds 15 16 View view document GetElement viewId as View 17 if view ViewType ViewType FloorPlan 18 19 planViewId view Id 20 break 21 22 23 24 LinkElementId stairsLinkId new LinkElementId stairs Id 25 StairsPath Create stairs Document stairsLinkId stairsPathIds First planViewId 26 transNewPath Commit 27 A StairsPath has a StairsPathType Stair path types are available from 2 predefined system families Automatic Up Down Direction and Fixed Up Direction The properties available for these two types are available as properties in the StairsPathType class such as FullStepArrow and DistanceToCutMark Type Properties y System Family Automatic Up Down Di Load Standard Duplicate Type Parameters Parameter Value Graph Start Symbol Type The CutMarkType class represents a cut mark type in the Revit Ul and it has properti
336. h are accessible in the Revit API directly from the Arc class as properties Circles have the IsBound property set to true This means they can only be evaluated by using a raw parameter range from O to 27 and the equation for a point on the circle in terms of the raw parameter is P u C r n cosu ny sinu where the assumption is made that the circle lies in the XY plane Arcs begin and end at a certain angle These angles can be obtained by the raw parameter values at each end of the arc and angular values between these values can be plugged into the same equation as above Cylindrical Helixes Cylindrical helixes are represented in the Revit API by the CylindricalHelix class They are defined in terms of the base point of the axis of the cylinder around which the helix is wound radius x and y vectors pitch and start and end angles Ellipse and elliptical arcs Ellipses and elliptical arcs segments are represented in the Revit API by the Ellipse class Similar to arcs and circles they are defined in a given plane in terms of their X and Y radii center and vector normal to the plane of the ellipse Full ellipses have the IsBound property set to true Similar to circles they can be evaluated via raw parameter between 0 and 27 P u C n 7 cosu n r sinu NurbSpline NURBS nonuniform rational B splines are used for spline segments sketched by the user as curves or portions of 3D object sketches They are also used to re
337. h other action buttons e In modal dialogs clicking OK means apply the values perform the task and close the window Do not use OK buttons to respond to questions e Label OK buttons correctly The OK button should be labeled OK not Ok or Okay e Do not use OK buttons in modeless dialog boxes Use a action button or Close button Action buttons Action buttons have descriptive verbs that will be defined by the designer Action button rules e Action buttons can be used to describe more clearly the action that will be taken when clicked e One action button must be set as the default This should be the action most closely mapped to the primary task of the dialog e There can be one or more action buttons but do not mix OK button with action buttons e Use Cancel or Close button for negative commit buttons instead of specific responses to the main instruction e Otherwise if user wants to cancel the negative commit would require more thinking than needed for this particular small task Cancel or Close Button e Verify the Close button on the title bar has the same effect as Close or Cancel e Escisthe keyboard shortcut for Cancel or Close Cancel button e Cancel button should only be used when a task will be aborted and no change will be committed e Clicking the Cancel button means abandon all changes cancel the task close the window and return the environment to its previous state and leaving no side effect e For nested choice dialog boxes cl
338. he analysis results are displayed in the view The static CreateAnalysisDisplayStyle method can create either a colored surface display style a markers with text style a deformed shape style diagram style or vector style For any style the color and legend settings can also be set Once a new AnalysisDisplayStyle is created use the View AnalysisDisplayStyleld to assign the style to a view Although the analysis results are not saved with the document analysis display styles and their assignment to a view are saved with the model T I on y 1 P A ya 00s x b i 8 874 0 00 i A L ds A x A 10 am 10 00 e X SUR ci Vries pa ini hh ALI DTI 5 y dH esa 42m F SSMUS n X 5 18 uc 3 70 BIO gt i ng EEN EEE S i 1011 FEI 000 pe TUM ab 10 OU k A air 5 02 ao no Pl 10 10 00 Colored surface Display Style Markers with text Display Style The following example creates a new colored surface analysis display style if not already found in the document and then assigns it to the current view Code Region 27 2 Setting analysis display style for view view plaincopy to clipboardprint CON dul UNA 43 45 46 47 48 49 50 Document doc commandData Application ActiveUIDocument Document AnalysisDisplayStyle analysisDisplayStyle null Look for an existing analysis display style with a specific name FilteredElementCollector collector1 new FilteredElementCollector doc I
339. he crop box focuses on a portion of the model to project and show in the view For 3D views there is another box named section box e The section box determines which model portion appears in a 3D view e The section box is used to clip the 3D model s visible portion e The part outside the box is invisible even if it is in the crop box e The section box is different from the crop box in that it can be rotated and moved with the model The section box is particularly useful for large models For example if you want to render a large building use a section box The section box limits the model portion used for calculation To display the section box in the 3D view Element Properties dialog box select Section Box in the Extents section You can also set it using the API Code Region Showing the Section Box view plaincopy to clipboardprint 1 private void ShowHideSectionBox Autodesk Revit DB View3D view3D 2T 3 foreach Parameter p in view3D Parameters 4 5 Get Section Box parameter 6 if p Definition Name Equals Section Box 7 8 Show Section Box 9 p Set 1 10 Hide Section Box 11 p Set 0 qoc break 13 14 15 Section Box ___ 7 dies ponte Handles andle Section Box Figure 100 Section box The View3D SectionBox property is used to get and change the box extents In some cases setting the View3D SectionBox can have a side effect Setting the property to certain values can chan
340. he default file path from the Application menu select Options and then the File Locations tab Close _ Figure 226 A task dialog that uses both main instructions and main content Expanded Content optional rarely used This text is hidden by default and will display at the bottom of the task dialog when the Show button is pressed e Expanded content is optional and should be rarely used It is used for information that is not essential advance or additional information or that doesn t apply to most situations e English Language Versions Expanded content should be written in sentence format normal capitalization and punctuation e English Language Versions Address the user directly as you when needed Minor ict NNNM Mirrors all model elements model views and annotations in non drafting views About which axis do you want to mirror the project gt North South axis East West axis gt Northeast Southwest axis gt Northwest Southeast axis Y Show details Click here to learn more Figure 227 The Show Details button displays additional Main Content text Main Image optional low usage Task dialogs support the inclusion of an image to the left of the main instructions Prior to task dialogs it has been common for most dialogs to have some sort of icon to show that the information it contained was informative a warning and error etc Because images were used all the time the value of any i
341. he following example creates a new assembly instance changes the name of its AssemblyType and then creates some views for the assembly instance Code Region Create Assembly and Views view plaincopy to clipboardprint 1 void CreateAssemblyAndViews Autodesk Revit DB Document doc ICollection lt ElementId gt elementIds Ao 3 Transaction transaction new Transaction doc 4 use category of one of the assembly elements 5 ElementId categoryId doc GetElement elementIds First Category Id 6 if AssemblyInstance IsValidNamingCategory doc categoryId elementIds 7 8 transaction Start Create Assembly Instance 9 AssemblyInstance assemblyInstance AssemblyInstance Create doc elementIds categoryId 10 commit the transaction that creates the assembly instance before modifying the instance s name 11 transaction Commit 12 13 transaction Start Set Assembly Name 14 assemblyInstance AssemblyTypeName My Assembly Name 15 transaction Commit 16 T create assembly views for this assembly instance 18 if assemblyInstance AllowsAssemblyViewCreation 19 20 transaction Start View Creation 21 View3D view3d AssemblyViewUtils Create3DOrthographic doc assemblyInstance Id 22 ViewSchedule partList AssemblyViewUtils CreatePartList doc assemblyInstance Id 23 transaction Commit 24 25 26 y Another way to create an AssemblylInstance is to use an existing AssemblyType To creat
342. he panel Tooltips Most controls can have a tooltip set using the ToolTip property which is displayed when the user moves the mouse over the control When the user hovers the mouse over a control for an extended period of time an extended tooltip will be displayed using the LongDescription and the ToolTiplmage properties If neither LongDescription nor ToolTiplmage are set the extended tooltip is not displayed If no ToolTip is provided then the text of the control Ribbonltem ItemText is displayed when the mouse moves over the control Enter a comment Af A Option A Enter some text This i5 text that will appear next to the image when the user hovers the mouse over the control e Figure 15 Extended Tooltip Contextual Help Controls can have contextual help associated with them When the user hovers the mouse over the control and hits F1 the contextual help is triggered Contextual help options include linking to an external URL launching a locally installed help chm file or linking to a topic on the Autodesk help wiki The ContextualHelp class is used to create a type of contextual help and then Ribbonltem SetContextualHelp or RibbonltemData SetContextualHelp associates it with a control When a ContextualHelp instance is associated with a control the text Press F1 for more help will appear below the tooltip when the mouse hovers over the control as shown below HF 1 Enter a comment Af
343. he user sees when editing the element i e the center plane of a window family instance The default for this property is false However some of this conditionally visible geometry represents real world objects such as insulation surrounding ducts in Revit MEP and it should be extracted View If users set the View property to a different view the retrieved geometry information can be different Review the following examples for more information 1 In Revit draw a stair in 3D view then select the Crop Region Crop Region Visible and Section Box properties in the 3D view In the Crop Region modify the section box in the 3D view to display a portion of the stair If you get the geometry information for the stair using the API and set the 3D view as the Options View property only a part of the stair geometry can be retrieved The following pictures show the stair in the Revit application left and one drawn with the API right Section Box ad Figure 113 Different section boxes display different geometry Draw a Stair in Revit then draw a section as shown in the left picture If you get the information for this stair using the API and set this section view as the Options View property only a part of the stair geometry can be retrieved The stair drawn with the API is shown in the right picture Figure 114 Retrieve Geometry section view DetailLevel The API defines three enumerations in Geometry Options DetailLevels The three enu
344. her one the UID of the wall is certain to change to maintain universal uniqueness but the ID of the wall may not change Q Revit takes a long time to update when my application sends data back to the model What do need to do to speed it up A Make sure you only call Document Regenerate as often as necessary Although this method is required to make sure the elements in the Revit document reflect all changes it can slow down your application Keep in mind too that when a transaction is committed there is an automatic call to regenerate the document Q What do do if want to add shared parameters to elements that do not have the ability to have shared parameters bound to them For example Grids or Materials A If an element type does not have the ability to add shared parameters you need to add a project parameter This does make it a bit more complicated when it is time to access the shared parameter associated with the element because it does not show up as part of the element s parameter list By using tricks like making the project shared parameter a string and including the element ID in the shared parameter you can associate the data with an element by first parsing the string Q How do l access the saved models and content BMP A The Preview dll is a shell plug in which is an object that implements the lExtractlmage interface IExtractlmage is an interface used by the Windows Shell Folders to extract the images for a known file
345. hod is called by PerformanceAdviser after all elements in document matching the ElementFilter from GetElementFilter are checked by ExecuteElementCheck This method checks to see if there are any elements door instances in this case in the m FlippedDoor instance member If there are it iterates through that list and displays the instance name and door tag of each item lt summary gt lt param name document gt The active document lt param gt public void FinalizeCheck Autodesk Revit DB Document document if m FlippedDoors Count 0 System Diagnostics Debug WriteLine No doors were flipped Test passed else Pass the element IDs of the flipped doors to the revit failure reporting APIs Autodesk Revit DB FailureMessage fm new Autodesk Revit DB FailureMessage m doorWarningId fm SetFailingElements m FlippedDoors Autodesk Revit DB Transaction failureReportingTransaction new Autodesk Revit DB Transaction document Failure reporting transaction failureReportingTransaction Start document PostFailure fm failureReportingTransaction Commit m FlippedDoors Clear summary Gets the description of the rule L lt summary gt lt returns gt The rule description lt returns gt public string GetDescription i return m_description lt summary gt This method supplies an element filter to reduce the number of elements that PerformanceA
346. how Revit element DesignOption Name ToString The following rules apply to Design Options e The value of the DesignOption property is null if the element is in the Main Model Otherwise the name you created in the Revit UI is returned e Only one active DesignOption Element can exist in an ActiveDocument o The primary option is considered the default active DesignOption For example a design option set is named Wall and there are two design options in this set named brick wall and glass wall If brick wall is the primary option only this option and elements that belong to it are retrieved by the Element Iterator Glass wall is inactive Annotation Elements This chapter introduces Revit Annotation Elements including the following e Dimension e DetailCurve e IndependentTag e extNote e AnnotationSymbol Note that e Dimensions are view specific elements that display sizes and distances in a project e Detail curves are created for detailed drawings They are visible only in the view in which they are drawn Often they are drawn over the model view e Tags are an annotation used to identify elements in a drawing Properties associated with a tag can appear in schedules e AnnotationSymbol has multiple leader options when loaded into a project For more information about Revit Element classification refer to Elements Essentials Topics in this section e Dimensions and Constraints e Detail Curve e Tags e
347. ia automatically filters the collection The two most common ways are demonstrated in the Revit Materials dialog e A search box allows the list to be filtered based on a keyword e A drop down allows the list to be filtered based on a set of defined criteria Collection Editor In addition to viewing a collection of items a user will also typically want to edit the collection This can be accomplished by associating a toolbar for editing creating duplicating renaming and deleting items The Edit Bar The buttons should be ordered left to right in the following order and with the following as tooltip labels Edit New Duplicate Delete Rename If a feature does not utilize one or more buttons the rest move to the left 4 n ub Ti 2B diu Figure 220 The Edit Bar Action Context 1 Edit Use If an item can be edited Editing an item may launch a separate dialog if there are less than three properties to edit See the Collection Viewer section for more details on displaying collection items 2 New Use New if the application is creating a new item 3 Duplicate Use Duplicate if the feature can only duplicate existing items 4 Rename Use Rename if the feature allows items to be renamed 5 Delete Use Delete to remove the feature To ensure that the primary UI element is placed first in the layout path the following rules should be followed when placing the manage controls e Navigating list is primary task place at the bottom l
348. ialog title Avoid nesting two of more group boxes within one another and placing Commit buttons inside a group box Horizontal Separator An alternative to the traditional group box is a horizontal separator Use this only when the groups are stacked vertically in a single column The following example is from Microsoft Outlook 2007 E mail accounts ea Set up e mail accounts and directories Send Receive A Set send and receive settings for e mail messages and documents Send immediately when connected Send Receive Data files l Change settings for the files Outlook uses to store e mail messages Va mimos Figure 203 Horizontal separators in Microsoft Outlook 2007 Spacing between the last control in the previous group and the next grouping line should be 12 DLUs 18 relative pixels Dynamic Layout Content that is presented on different types or sizes of display devices usually requires the ability to adapt to the form that it is displayed in Using a dynamic layout can help when environment changes such as localizing to other languages changing the font size of content and for allowing user to manually expand the window to see more information To create a dynamic layout e Treat the content of the window as dynamic and expand to fill the shape of its container unless constrained e Add a resizing grip to the bottom right corner of the dialog e The dialog should not be resizable to a size smaller than the default size
349. ible 11 qu m MyForm Close 13 14 15 return Result Succeeded 16 3175 18 public Result OnStartup UIControlledApplication application 19 20 m MyForm null no dialog needed yet the command will bring it ZI thisApp this static access to this application instance 22 23 return Result Succeeded 27 2s 26 The external command invokes this on the end user s request 27 public void ShowForm UIApplication uiapp 28 29 If we do not have a dialog yet create and show it 30 if m MyForm null m MyForm IsDisposed als 32 A new handler to handle request posting by the dialog 33 ExternalEventExample handler new ExternalEventExample 34 35 External Event for the dialog to use to post requests 36 ExternalEvent exEvent ExternalEvent Create handler 37 38 We give the objects to the new dialog 39 The dialog becomes the owner responsible for disposing them eventually 40 m_MyForm new ExternalEventExampleDialog exEvent handler 41 m MyForm Show 42 43 44 y 45 46 Autodesk Revit Attributes Transaction Autodesk Revit Attributes TransactionMode Manual 47 Autodesk Revit Attributes Regeneration Autodesk Revit Attributes RegenerationOption Manual 48 public class Command IExternalCommand 50 public virtual Result Execute ExternalCommandData commandData ref string message ElementSet elements 51 52 try 53 54 Ext
350. ich it cannot be modified The programmer should check the properties Document IsModifiable and Document IsReadOnly to determine whether the model may be modified Topics in this section e Database Events e User Inteface Events e Registering Events e Canceling Events Database Events The following table lists database events their type and whether they are available at the application and or document level Table 53 DB Event Types Event Type Application Document DocumentChanged single X DocumentClosing pre X X DocumentClosed post X DocumentCreating pre X DocumentCreated post X DocumentOpening pre X DocumentOpened post X DocumentPrinting pre X X DocumentPrinted post X X DocumentSaving pre X X DocumentSaved post X X DocumentSavingAs pre X X DocumentSavedAs post X X DocumentSynchronizingWithCentral pre X DocumentSynchronizedWithCentral post X FailuresProcessing single X FileExporting pre X FileExported post X Filelmporting pre X Filelmported post X ProgressChanged single X ViewPrinting pre X X ViewPrinted post X X e DocumentChanged notification when a transaction is committed undone or redone e DocumentClosing notification when Revit is about to close a document e DocumentClosed notification just after Revit has closed a document e DocumentCreating notification when Revit is about to create a new document e DocumentCreated notification when Revit has finished creating a new document e DocumentOpeni
351. icking the Cancel button in the owner choice dialog typically means any changes made by owned choice dialogs are also abandoned e Don t use Cancel button in modeless dialog boxes Use Close button instead Close Button e Use Close button for modeless dialog boxes as well as modal dialogs that cannot be canceled e Clicking Close button means close the dialog box window leaving any existing side effects Apply button optional Apply button will commit any changes made within the dialog on all tabs pages or levels within a hierarchy without closing the dialog Optimally the user will receive visual feedback of the applied changes Here are some basic Apply Button rules e In modal or modeless dialogs clicking Apply means apply the values perform the task and do not close the window e In modeless dialog use Apply button only on those tasks that require significant or unknown upfront time to be performed otherwise data change should be applied immediately e The Apply button is disabled when no changes have been made It becomes enabled when changes have been made e Clicking cancel will NOT undo any changes that have been already committed with the Apply button e Interacting with a child dialog such as a confirmation should not cause the Apply function to become enabled e Clicking the Apply button after committing a child dialog such as a confirmation message will apply all the changes made previous to the action triggering the confirm
352. idated into quadrilaterals e FacetingUtils ConvertTrianglesToQuads this method takes a TriangulationInterface constructed from a TriangulatedSolidOrShell as input and returns a collection of triangles and quadrilaterals representing the original triangulated object Room and Space Geometry The Revit API provides access to the 3D geometry of spatial elements rooms and spaces The SpatialElementGeometryCalculator class can be used to calculate the geometry of a spatial element and obtain the relationships between the geometry and the element s boundary elements There are 2 options which can be provided to this utility e SpatialElementBoundaryLocation whether to use finish faces or boundary element centerlines for calculation e StoredFreeBoundaryFaces whether to include faces which don t map directly to a boundary element in the results The results of calculating the geometry are contained in the class SpatialElementGeometryResults From the SpatialElementGeometryResults class you can obtain e The Solid volume representing the geometry GetGeometry method e The boundary face information a collection SpatialElementBoundarySubfaces Each subface offers e The face of the spatial element e The matching face of the boundary element e The subface the portion of the spatial element face bounded by this particular boundary element e The subface type bottom top or side Some notes about the use of this utility e The calcula
353. if projectLocation Name name ICollection ElementId elemSet document Delete projectLocation if elemSet Count gt 0 laskDialog sthow Revac Project Locacion Delered s NoteThe following rules apply to deleting a project location e The active project location cannot be deleted because there must be at least one project location in the project e You cannot delete the project location if the ProjectLocationSet class instance is read only Analysis Topics in this section e Energy Data e Analysis Visualization e Detailed Energy Analysis Model e Conceptual Energy Analysis Energy Data The EnergyDataSettings object represents the gbXML Parameters in the Revit project To view the parameters from the Revit UI select Project Information from the Project Settings panel on the Manage tab The Project Information dialog box appears Instance Parameters Control selected or to be created instance Issue Date Project Status Project Status Type Properties Family System Family Energy Data me eee Type Energy Data v Duplicate Type Parameters Figure 153 EnergyDataSettings The EnergyDataSettings object is derived from the Element base object It is unique in each project similar to ProjectIinformation Though EnergyDataSettings is a subclass of the Element class most of the members inherited from the Element return null or an empty set except
354. if selecting more than one option is required The Microsoft Windows User Experience Guidelines should be followed when using a list box Locations defined in this project Internal current Mew Location Mew Location 2 Rotate 15 degrees North Figure 212 List box List View Use when the data includes the option of list details and or graphical thumbnail previews such as a Windows Open Dialog etim ms Ed 3 Ej views Preview ah LEE Tau Details Thumbnails Frames House Jenkins Figure 213 List view Table View Users often need to view the contents of a collection so that they can easily comprehend and compare the attributes of many items at once To accommodate this present the user with a table that is formatted in such a way that is conducive to scanning Examples Good Example The following is an example of a well formatted table Note the header cells are differentiated from the data cells and the alignment differs to makes it easier to scan the data Annual Design Conditions Figure 214 Good table example Poor Example The following is an example of a poorly formatted table Note the header cells are not differentiated from the data cells and the alignment makes it difficult to scan the data Figure 215 Bad table example Table title and header cells e Highlight and bold the table title to differentiate it from the data cells and the header cell
355. ight LightWeight Bool double UT UnitWeight UT Number UT Stress Concrete compression stress capacity F c for US codes If true then lightweight concrete is defined KLEELELEELLLEBEELELEELLELEELL UT Number When Lightweight True then this value is available It is the reduction of the concrete compression capacity for shear Concrete Shear stress Capacity ConcreteCompression ShearStrengthReduction ShearStrengthReduction double UT Stress Young Modulus PoissonModulus i double Shear modulus ShearModulus double double UT Number UT Stress Thermal Expansion ThermalExpansionCoefficient UT UnitWeight Unit Weight ewe o p double UT Stress CompressionParallel UT Stress CompressionPerpendicular double UT Stress ShearParallel double UT Stress ShearPerpendicular double UT Stress perpendicular to grain MEL Internal Representation UT UnitWeight Kg mass Foot Sec Concrete Section Definitions Topics in this section e Concrete Rectangular Beam e Precast Rectangular Beam e Precast L Shaped Beam e Precast Single Tee e Precast Inverted Tee e Precast Double Tee Concrete Rectangular Beam m Family Types x Family Types Hew Materials and Finishes Beam Material default Rename Structural Delete Angle default Dimensions Length default Parameters Add Ko difs Identity Data Assembly Code A Fs Ramove
356. ight line You can calculate a normal vector to the straight line in a given plane using the tangent vector The API sample DirectionCalculation uses the tangent vector to the wall location curve to find exterior walls that face south Finding and highlighting south facing exterior walls Curve types Revit uses a variety of curve types to represent curve geometry in a document These include Curve type Revit API class Definition Notes A line segment defined by its Obtain endpoints from B li Li ound line ds endpoints Curve get Endpoint Identify these with Curve IsBound Evaluate point and tangent vector at raw parameter O to find the input parameters for the equation of the line An infinite line defined by a location and direction Unbound line lLine Begin and end at a certain angle These angles can be obtained by the raw parameter values at each end of the arc Arc Arc A bound circular arc Identify with Curve IsBound Circle Arc An unbound circle Use raw parameter for evaluation from O to 211 Used only in specific applications in A helix wound around a cylinder stairs and railings and should not be Cylindrical ee i ik CylindricalHelix making constant angle with the lused or encountered when accessing axis of the cylinder curves of other Revit elements and geometry Elliptical arc Ellipse A bound elliptical segment Identify with Curve IsBound Use raw Ellipse Ellipse An
357. igidLinkHead Rigid Link at end O head of the Beam e RigidLinkTail Rigid Link at end 1 tail of the Beam e AllRigidLinks All Rigid Link curves Rigid Link at end O head will be in the first entry Rigid Link at end 1 tail will be in the last entry The following example demonstrates the use of AnalyticalModel for structural walls Code Region 29 13 Getting the curves for a structural wall I retrieve une iterate current eeleceecd lement UIDocument uidoc commandData Application ActiveUlDocument ElementSet selection uidoc Selection Elements torcach Element e In selection Wall aWall e as Wall if null aWall get AnalyticalModelWall from Structural Wall AnalyticalModel modelWall aWall GetAnalyticalModel as AnalyticalModel if null modelWall Architecture wall doesn t have analytical model continue get analytical information int modelCurveNum modelWall GetCurves AnalyticalCurveType ActiveCurves Count IList lt AnalyticalModelSupport gt supportList new List lt AnalyticalModelSupport gt supportList modelWall GetAnalyticalModelSupports SS NS TOXOe te Da ste s Coma Parameter Information AnalyticalModel provides access to Parameter information such as rigid links projection and approximation Rigid Links A rigid link connects the analytical model of a beam to the analytical model of a column Use the CanHaveRigidLinks method and the AnalyticalModel RigidLinksOption
358. igure 234 Commit Button sizes taken from Microsoft Windows User Experience Guidelines A summary of commit button styles for different window types Pattern Commit Button style Modal Dialog OK Cancel or Action Cancel Modeless dialog Close button on dialog box and title bar Progress Indicator Use Cancel if returns the environment to its previous state leaving no side effect otherwise use Stop Commit buttons should follow this layout pattern O D Cancel Action1 Action 2 Figure 235 Standard Commit Button layouts Button Type 1 Default OK and other Action buttons 2 Cancel or Close Button 3 Apply Button 4 Dialog buttons optional Position the Default Cancel and Apply button s in this order and right aligned The Dialog button s if present are aligned to the left but to the right of the help button if present Default OK and other Action buttons The dialog must have a default action button This button should be closely mapped to the primary task of the dialog This can either be labeled OK or a more descriptive verb that describes the action e Make the button with less destructive result to be the Default button e Enter key is the keyboard access point for the Default button OK buttons can be used when saving a setting or series of settings OK button rules e OK button should be used when it is the ONLY action besides cancel that can be committed from the dialog Do not mix OK wit
359. ilings e Creating and Editing Stairs e Stairs Annotations Creating and Editing Stairs StairsEditScope As with other types of elements in the Revit document a Transaction is necessary to edit stairs and stairs components However to create new components such as runs and landings or to create new stairs themselves it is necessary to use an Autodesk Revit DB StairsEditScope object which maintains a stairs editing session StairsEditScope acts like a TransactionGroup After a StairsEditScope is started you can start transactions and edit the stairs Individual transactions created inside StairsEditScope will not appear in the undo menu All transactions committed during the edit mode will be merged into a single one which will bear the name passed into the StairsEditScope constructor StairsEditScope has two Start methods One takes the Elementld for an existing Stairs object for which it starts a stairs editing session The second Start method takes the Elementids for base and top levels and creates a new empty stairs element with a default stairs type in the specified levels and then starts a stairs edit mode for the new stairs After runs and landings have been added to the Stairs and editing is complete call StairsEditScope Commit to end the stairs editing session Adding Runs The StairsRun class has three static methods for creating new runs for a Stairs object e CreateSketchedRun Creates a sketched run by providing a group of bo
360. ilter Quick filters operate only on the ElementRecord a low memory class which has a limited interface to read element properties Elements which are rejected by a quick filter will not be expanded in memory e ElementSlowFilter Slow filters require that the Element be obtained and expanded in memory first Thus it is preferable to couple slow filters with at least one ElementQuickFilter which should minimize the number of Elements that are expanded in order to evaluate against the criteria set by this filter e ElementLogicalFilter Logical filters combine two or more filters logically The component filters may be reordered by Revit to cause the quickest acting filters to be evaluated first Most filters may be inverted using an overload constructor that takes a Boolean argument indicating to invert the filter so that elements that would normally be accepted by the filter will be rejected and elements that would normally be rejected will be accepted Filters that cannot be inverted are noted in their corresponding sections below There is a set of predefined filters available for common uses Many of these built in filters provide the basis for the FilteredElementCollector shortcut methods mentioned in the FilteredElementCollector section above The next three sections provide more information on the built in filters Once a filter is created it needs to be applied to the FilteredElementCollector The generic method WherePasses is used t
361. ily family document OwnerFamily 2 if family IsCurtainPanelFamily true amp amp 3 family CurtainPanelTilePattern TilePatternsBuiltIn Rectangle 4 5 first change spacing of grids in family document 6 family CurtainPanelHorizontalSpacing 20 7 family CurtainPanelVerticalSpacing 30 8 9 create new points and lines on grid 10 Autodesk Revit ApplicationServices Application app document Application 11 FilteredElementCollector collector new FilteredElementCollector document 12 ICollection lt Element gt collection collector OfClass typeof ReferencePoint ToElements 13 int ctr 0 14 ReferencePoint rpO0 null rp1 null rp2 null rp3 null 15 foreach Autodesk Revit DB Element e in collection 16 1 17 ReferencePoint rp e as ReferencePoint 18 switch ctr 19 20 case 0 21 rpo rp 22 break 23 case 1 24 rp1 rp 25 break 26 case 2 Zl rp2 rp 28 break 29 case 3 30 rp3 rp 31 break 32 33 ctr 34 35 36 ReferencePointArray rpAr new ReferencePointArray 37 rpAr Append rpo 38 39 40 easu 41 42 43 easu 44 45 46 47 48 49 50 51 52 53 54 55 56 else 57 58 59 rpAr Append rp2 CurveByPoints curvel document FamilyCreate NewCurveByPoints rpAr PointLocationOnCurve pointLocationOnCurve25 new PointLocationOnCurve PointOnCurveMeasurementType NormalizedCurveParamet
362. ilyCreate NewReferencePoint Xyz rpa Append rp xyz document Application Create NewXYZ 0 100 0 rp document FamilyCreate NewReferencePoint xyz rpa Append rp CurveByPoints cbp document FamilyCreate NewCurveByPoints rpa ref ar Append cbp GeometryCurve Reference ref ar ar Append ref ar mos Teor E ref ar new ReferenceArray JB SQ eNES Ce OMe mo dod E Uke CN nee DING xyz document Pop dua cdi Lom Create Nevra SO 0 rp document FamilyCreate NewReferencePoint xyz Lyon Pencil ou COCUIMeEIE Pop DX e ote o me tree Newer Aa oye O30 rp document FamilyCreate NewReferencePoint Xyz rpa Append rp Su documente Ap por e oie do mec redieelewsnzui opp 1090 CON rp document FamilyCreate NewReferencePoint Xyz rpa Append rp Cop document anio te NeweuLyeby EOS SN IBS TSE DEMO INS Ge ONS AIG cnc mc MINCE ref ar ar Append ref ar Cerere eoe qu ref ar new ReferenceArray jo Makes icc pice ta lec ues omo te Zya document Applicat ion C reatenwNewxy o 0 29 rp document FamilyCreate NewReferencePoint Xyz rpa Append rp x VU document AOOLACau hom Orea ren New A 57 OU 5 rp document FamilyCreate NewReferencePoint Xyz rpa Append rp xyz document Application Create NewXYZ 75 100 0 rp document FamilyCreate NewReferencePoint Xyz rpa Append rp cbp document FamilyCreate NewCurveByPoints rpa ccu epe ee ons d M cc cese
363. in Level1 and then move it to the new location 10 20 30 the column is placed at the location 10 20 0 instead of 10 20 30 and the MoveElement method returns success Code Region 10 1 Using MoveElement public void MoveColumn Autodesk Revit DB Document document FamilyInstance column 1 Ce ue CO lua Cuisine o cin Boce e abo Oubiieae Gil lUmMinnec ce dor me Glan boxe etie e Ss lie ae Lol O Lie X462 dole laces te de DUC XE Ent on c E An e E Mie collin ice mea loe sico XYA newPlace new XYZ 10 20 30 Element rans e on ees Mover eem oce Column Loewe lace now get the column s new location CoMo bocak ron 1e Olio cise mec Loser do TUE C gane Mena tual co lan Location rola Sao ano O a ie oe ao o bla ec A E XaNew 2 location newActual Z Tes Dro ss noni Revia nO e When you move one or more elements associated elements are moved For example if a wall with windows is moved the windows are also moved e Ifyou pin the element in Revit the Element Pinned property is true This means that the element cannot be moved or rotated Another way to move an element in Revit is to use Location and its derivative objects In the Revit Platform API the Location object provides the ability to translate and rotate elements More location information and control is available using the Location object derivatives such as LocationPoint or LocationCurve If the Location element is downcast to a Location
364. in criteria You can check if each element s bounding box is inside a given volume intersects a given volume or contains a given point You can also reverse this check to find elements which do not intersect a volume or contain a given point BoundingBox filters use Outline as their inputs Outline is a class representing a right rectangular prism whose axes are aligned to the Revit world coordinate system These filters work best for shapes whose actual geometry matches closely the geometry of its bounding box Examples might include linear walls whose curve aligns with the X or Y direction rectangular rooms formed by such walls floors or roofs aligned to such walls or reasonably rectangular families Otherwise there is the potential for false positives as the bounding box of the element may be much bigger than the actual geometry In these cases you can use the actual element s geometry to determine if the element really meets the criteria Element Intersection Filters The element filters e ElementintersectsElementFilter e ElementintersectsSolidFilter pass elements whose actual 3D geometry intersects the 3D geometry of the target object With ElementlntersectsElementFilter the target object is another element The intersection is determined with the same logic used by Revit to determine if an interference exists during generation of an Interference Report This means that some combinations of elements will never pass this filter such
365. in in these locations will be read and processed by Revit during startup All of the files in both the user specific location and the all users location are considered together and loaded in alphabetical order If an all users manifest file shares the same name with a user specific manifest file the all users manifest file is ignored Within each manifest file the external commands and external applications are loaded in the order in which they are listed A basic file adding one ExternalCommand looks like this Code Region 3 9 Manifest addin ExternalCommand oom decus cu on docs cuc elis cu Ese sumi doncc no gt RevitAddIns Keine Taxe VOTO e RO Lr o lt Assembly e MyProgram MyProgvam ali lt 7 Assembly gt AddInId 76eb700a 2c85 4888 a78d 31429ecae9ed AddInId lt FullClassName gt Revit Samples SampleCommand lt FullClassName gt lt Text gt Sample command lt Text gt MEMO O LO bok eineleigiel sorelle Se beim AIO de S www aulodesk com lt VendorMescripe em lt VisibilityMode gt NotVisiblelnFamily lt VisibilityMode gt lt Dursict lle orr eure DESSEN S Dabo eugene Ar hire Ure Diac eret e db abore lt AvailabilityClassName gt Revit Samples SampleAccessibilityCheck lt AvailabilityClassName gt TOn S ripe ons Soe lias us as Lome ele a or Lol wor why e Oum uote es e T6 lt p gt This is another descriptive paragraph with notes about how to use the command properly lt p gt lt KeomgquUecctcipr lon lt TooltipImage gt
366. in the document that are face flipped See the sample project for the complete class implementation Code Region Implementing IPerformanceAdviserRule view plaincopy to clipboardprint 1 public class FlippedDoorCheck Autodesk Revit DB IPerformanceAdviserRule 2 1 3 region Constructor 4 summary 5 Set up rule name description and error handling 6 lt summary gt 7 public FlippedDoorCheck 8 9 m name Flipped Door Check 10 m description An API based rule to search for and return any doors that are face flipped 11 m_doorWarningId new Autodesk Revit DB FailureDefinitionId new Guid 25570B8FD4AD42baBD78469ED60FB9A3 12 m doorWarning Autodesk Revit DB FailureDefinition CreateFailureDefinition m doorWarningId Autodesk Revit DB FailureSeverity Warning Som e doors in this project are face flipped 13 14 endregion 15 16 region IPerformanceAdviserRule implementation 17 lt summary gt 18 Does some preliminary work before executing tests on elements In this case 19 we instantiate a list of FamilyInstances representing all doors that are flipped 20 lt summary gt 2l lt param name document gt The document being checked lt param gt 20 public void InitCheck Autodesk Revit DB Document document 23 24 if m FlippedDoors null 25 m FlippedDoors new List Autodesk Revit DB ElementId 201 else 275 m FlippedDoors Clear 28 return 29 3
367. in the relevant collections Implementing all of the collections is similar The following example uses ElementSet and ModelCurveArray to demonstrate how to use the main collection properties Code Region 9 2 Using collections UrDOcumenc uidoc new UID exeo document SelElementSet selection uidoc Selection Elements Store the ModelLine references ModelCurveArray lineArray new ModelCurveArray So POO ee ae LO assume 131943 is a model line element id AUTO des Reville dE e Ie dE eqq ean dE OE id new Aro desire Vile Dee element le db db Sj SE lineArray Append document GetElement id as ModelLine fi bbs s Size oo eu day laskDialog show Revi Berore Insere lineavray size 2 mer dq Use TTS Em ty property on Array nog mea rey bs timp fy Sey tem Gini Com ela XE Nici ModelCurve modelCurve lineArray get_Item 0 as ModelCurve j Sease Ene spes cs lemene ron thewsee Gt elements selection tease modelCurve 7 Creake a new model Pine and insert Lo array of model line SketchPlane sketchPlane modelCurve SketchPlane OCA sc Hee oa US OA Wp o 77 tele T elles E joomla ol elas i dbi Xyz ol elut E OEA O O O A e cado oo Onn ae di Tra create geometry line Line geometryLine document Application Create NewlLine startPoint endPoint true 7 1 eee ene Mode lame ModelLine line document Create NewModelCurve geometryLine sketchPlane as ModelLine lineArray Insert line lineArray Size 1
368. ing Opening opening string message Opening get wae laos Element Gir wads oe ing mess adi ule tel eur eo pena o lae s eo cxlo elsi O Oem mc o a ae get the information whether the opening has a rect boundary T the opening has a rect boundary get the geom info from BoundaryRect property Otherwise we should get the geometry information from BoundaryCurves property if opening IsRectBoundary message nThe opening has a rectangular boundary array contains Evo xYZ obe to ene Max and Mim cooras ei boundary XYZArray boundaryRect opening BoundaryRect get the coordinate value of the min coordinate point CE OIE O SM O bd e Cee Mice x message r T MI cime oum cS O oF Oda 6S aes ctore UE p us get the coordinate value of the Max coordinate point HOMME Osma Bon Carey Nec ec les ll p message t gilet Coor libe te om O jooliat a Vy 7 eodd EE E MeV j esc message nThe opening doesn t have a rectangular boundary Get curve number int curves opening BoundaryCurves Size message aio cu GE eNews ans 3 Y o ENDE WEISE por Guaro O a os mele Autodesk Revit Geometry Curve curve opening BoundaryCurves get_Item i Get curve start and end points message t n urve slart pones Ya DOLO Cie Mac eu Ye y est oo mime 10 message gt Curve end Point XYZ2Mostriung curve gee EndPoume s MessageBox Show message Revit output the point s three coordinat
369. ing and the model lines category is OST_AreaSeparationLines If an element is not Room Bounding it is excluded from the elements to make the boundary Figure 139 Rooms 1 2 3 4 Separation Figure 140 Room 5 6 The following table provides the Room GetBoundarySegments Size results for the previous rooms Table 56 Room GetBoundarySegments Size Room Room GetBoundarySegments Size Room 1 1 Room 2 Room 3 Room 4 2 Room 5 3 Room 6 Note Walls joined by model lines are considered continuous line segments Single model lines are ignored After getting IList IList BoundarySegment get the BoundarySegment by iterating the list BoundarySegment The segments that make the region are represented by the BoundarySegment class its Element property returns the corresponding element with the following conditions e Fora ModelCurve element the category must be BuiltlnCategory OST AreaSeparationLines meaning that it represents a Room Separator e For other elements such as wall column and roof if the element is a room boundary the Room Bounding parameter BuiltInParameter WALL_ATTR ROOM BOUNDING must be true as in the following picture o ARR RR ZssssuassaunuanuanuuauuauuauaaRuusaausEuuasRuuREAuSRUSARHEURZARERESAAREERARRREERRRR ARR RR ARR Ro Top Offset He UN Structural Structural Usage Dimensions Length Figure 141 Room Bounding property The WALL ATTR ROOM BOUND
370. ing cut vertically to the host element e Create a New Opening Element Use to create a shaft opening in your project However make sure the topLevel is higher than the bottomLevel otherwise an exception is thrown e Create an Opening in a Straight Wall or Arc Wall Use to create a rectangle opening in a wall The coordinates of pntStart and pntEnd should be corner coordinates that can shape a rectangle For example the lower left corner and upper right corner of a rectangle Otherwise an exception is thrown NoteUsing the Opening command you can only create a rectangle shaped wall opening To create some holes in a wall edit the wall profile instead of the Opening command Thermal Properties Certain assembly types such as Wall Floor Ceiling Roof and Building Pad have calculated and settable thermal properties which are represented by the ThermalProperties class type Properties i System Family Basic Wall oad Exterior 300mm Concrete Duplicate Rename Type Parameters The ThermalProperties class has properties for the values shown above Absorptance and Roughness are modifiable while HeatTransferCoefficient ThermalResistance and ThermalMass are read only The units for these calculated values are shown in the table below Property Unit o watts per meter squared kelvin HeatTransferCoefficient W m 2 K meter squared kelvin per watt ThermalResistance m 2 K Watt kilogram feet squared per second squared
371. ing fileName C Documents and Settings All Users Application Data Autodesk RST 2011 Imperial Library Furniture Bed Boxart ia Autodesk Revit DB Family family null if document LoadFamily fileName out family throw new Exception Couldn t load fileName pales reo llenen Ol oue Oe OMe ees E howe IL Toe ae e Jes e oae eoliano elo DU eS que Floor tloor collecror O1rClass eyocor Floor bParseblemene sas Floor EA sio Besmilyesy moler lector symoolileou rami ces vmi odks devictis eT adc SENE SC O lt O O xo S RT AE while symbolltor MoveNext Ramis meo ose Sao e 1 Es ym obi OU cuecen as Pam oaa OHNE XM ot donc xs ev O 2 361 X5 qe So FS MEE O Sum Ce AS case O0 Gameeek Icon mae OZ ly le 36 break case 1 SS On c Uu AN T break case 2 ciues eicit break j FamilyInstance instance document Create NewFamilyInstance location symbol direction floor decur deste ATENTO EIS au lite cael x 10 a j j else throw new Exception Please open a model with at least one floor element before invoking this command The result of the previous code appears in the following picture Figure 49 Create family instances using different reference directions FamilySymbol The FamilySymbol class represents a single Type within a Family Each family can contain one or more family symbols Each Familylnstance has an associated FamilySymbol which can be acce
372. ing the facing The table lists the FromRoom ToRoom and Room properties for each door The Door elements can exist without a room In the API and only in the API a Door element has two additional properties that refer to the regions on the two opposite sides of a door ToRoom and FromRoom If the region is a room the property s value would be a Room element If the region is not a room the property will return null Both properties may be null at the same time The region on the side into which a door opens will be ToRoom The room on the other side will be FromRoom Both properties get dynamically updated whenever the corresponding regions change Room property belongs to all Family Instances T E bl Figure 148 Door 1 Figure 152 Door 5 Table 58 Door Properties Door Door 1 Door 2 Door 3 Door 4 Door 5 FromRoom null Room 1 Room 3 Room 4 null ToRoom null null Room 2 null Room 6 Room null null Room 2 null Room 6 All family instances have the Room property which is the room where an instance is located in the last project phase Windows and doors face into a room Change the room by flipping the door or window facing or by calling FamilyInstance FlipFromToRoomY For other kinds of instances such as beams and columns the Room is the room that has the same boundary as the instance The following code illustrates how to get the Room from the family instance It is n
373. ingCommandData public class Comiand TExtrermalLComnuand public Autodesk Revit IExternalCommand Result Execute Autodesk Revit ExternalCommandData commandData ref string message Autodesk Revit DB ElementSet elements return Autodesk Revit UI Result Succeeded Revit Exceptions When API methods encounter a non fatal error they throw an exception Exceptions should be caught by Revit add ins The Revit API help file specifies exceptions that are typically encountered for specific methods All Revit API methods throw a subclass of Autodesk Revit Exceptions ApplicationException These exceptions closely mirror standard NET exceptions such as e ArgumentException e InvalidOperationException e FileNotFoundException However some of these subclasses are unique to Revit e AutoJoinFailedException e RegenerationFailedException e ModificationOutsideTransactionException In addition there is a special exception type called InternalException which represents a failure path which was not anticipated Exceptions of this type carry extra diagnostic information which can be passed back to Autodesk for diagnosis Ribbon Panels and Controls Revit provides API solutions to integrate custom ribbon panels and controls These APIs are used with IExternalApplication Custom ribbon panels can be added to the Add Ins tab the Analyze tab or to a new custom ribbon tab Panels can include buttons both large and small which can be either simpl
374. inquiries from Revit regarding the properties of a single point cloud e Animplementation of IPointSetlterator which will return sets of points to Revit when requested In order to supply the points of the point cloud to Revit there are two ReadPoints methods which must be implemented e PointCloudAccess ReadPoints this provides a single set of points in a one time call either from Revit or the API Revit uses this during some display activities including selection pre highlighting It is also possible for API clients to call this method directly via PointCloudInstance GetPoints e PointSetlterator ReadPoints this provides a subset of points as a part of a larger iteration of points in the cloud Revit uses this method during normal display of the point cloud quantities of points will be requested repeatedly until it obtains enough points or until something in the display changes The engine implementation must keep track of which points have been returned to Revit during any given point set iteration See the PointCloudEngine folder under the Samples directory included with the Revit API SDK for a complete example of registering and implementing both file based and non file based point cloud engines Worksharing Worksharing is a design method that allows multiple team members to work on the same project model at the same time When worksharing is enabled a Revit document can be subdivided into worksets which are collections of elem
375. int property to set the element s physical location Code Region 10 4 Moving using Point aoo LocarronMoy e Bani nestane a eoa umn i HOCAbLOne Olne colon colocaciones ITO e HE TURO EIQUE P abus nUll VS ere Tet grt QUE ini OOF newlocatlion new 2362 ILO 20 0 Move the column to the new location coliinto POIN en XO SUE OJOL Rotating elements The ElementTransformUtils class provides two static methods to rotate one or several elements in the project Table 20 Rotate Methods Member Description RotateElement Document Elementld Line double Rotate an element in the document by a specified number of radians around a given axis RotateElements Document ICollection Elementld Line double Rotate several elements by IDs in the project by a specified number of radians around a given axis Inthese methoos the angle of rotation is in radians The positive radian means rotating counterclockwise around the specified axis while the negative radian means clockwise as the following pictures illustrates After Rotation b Rotate Angle Math PI 3 0 Before Rotation Figure 31 Counterclockwise rotation Before Rotation 3 amp Rotate Angle Math PI 3 0 After Rotation Figure 32 Clockwise rotation Note When you rotate an element the axis line must be bound An unbounded axis line results in a failed rotation even if Succeeded is returned to Revit In this situation the RotateElement
376. intCloudlnstance The static PointCloudType Create method requires the engine identifier as it was registered with Revit by a third party or the file extension of the point cloud file if it is a supported file type It also requires a file name or the identification string for a non file based engine In the following sample a pcg file is used to create a point cloud in a Revit document Code Region Create a point cloud from a pcg file view plaincopy to clipboardprint La 2 Sa Document doc commandData View Document PointCloudType type PointCloudType Create doc pcg c Pipe pcg PointCloudInstance Create doc type Id Transform Identity i pt xm Mac iecit nec ry or prese X Koo 0 E di DE TE inis m Aca A t On Y Br we ol Figure Point Cloud from Pipe pcg with all points selected Accessing Points in a Point Cloud There are two ways to access the points in a point cloud 1 Iterate the resulting points directly from the PointCollection return using the IEnumerable CloudPoint interface 2 Geta pointer to the point storage of the collection and access the points directly in memory in an unsafe interface Either way you first access a collection of points from the PointCloudInstance using the method e PointCloudInstance GetPoints PointCloudFilter filter int numPoints Note that as a result of search algorithms used by Revit and the point cloud engine the exact requested number of
377. ion e Perform analysis of all sorts using BIM e Automatically create project documentation Requirements To go through the user manual you need the following 1 Aworking understanding of Revit Architecture 2013 Revit Structure 2013 or Revit MEP 2013 2 Familiarity with a Common Language Specification compliant language like C or VB NET 3 Microsoft Visual Studio 2010 or Microsoft Visual Studio 2010 Express Edition Alternatively you can use the built in SharpDevelop development environment in Revit Microsoft NET Framework 4 0 5 The Revit Software Developer s Kit SDK which you can download from the Autodesk Developer Network ADN or the Revit installation CD DVD lt DVD_Drive gt Utilities Common Software Development Kit Install and Learn the Revit Based Product The examples in this document use Microsoft Visual Studio 2010 for the Integrated Development Environment IDE If you are a Revit novice go through the tutorials which are accessible from the Revit Help menu If possible take a training class from your local Autodesk reseller to help you quickly get up to speed Regardless of your experience level you can join one of the many discussion groups dedicated to Revit and the Revit Platform API The following resource links are a good Starting point www autodesk com revitbuilding www autodesk com revitstructure www autodesk com revitsystems www autodesk com bim www revitcity com www augi com http
378. ion Point XYZ normal new XYZ 1 0 0 XYZ rebarLineEnd new XYZ origin X origin Y origin Z 9 Line rebarLine document Application Create NewLineBound origin rebarLineEnd Create the line rebar IList Curve curves new List Curve curves Add rebarLine Rebar rebar Rebar CreateFromCurves document Autodesk Revit DB Structure RebarStyle Standard barType hookType hookType column origin curves RebarHookOrientation Right RebarHookOrientation Left true true if null rebar i set specific layout for new rebar Parameter paramLayout rebar get Parameter BuiltInParameter REBAR ELEM LAYOUT RULE paramLayout Set 1 1 Fixed Number Parameter paramNum rebar get Parameter BuiltInParameter REBAR ELEM QUANTITY OF BARS paramNum Set 10 rebar ArrayLength 1 5 y return rebar NoteFor more examples of creating rebar elements see the Reinforcement and NewRebar sample applications included with the Revit SDK The following table lists the integer value for the Parameter REBAR_ELEM_LAYOUT_RULE Table 59 Rebar Layout Rule Value Description 0 1 2 3 A None Fixed Number Maximum Spacing Number with Spacing Minimum Clear Spacing The Rebar ScaleToBox method provides a way to simultaneously set all the shape parameters The behavior is similar to the UI for placing Rebar RebarHostData and RebarCoverType Clear cover is associated with individual faces of valid rebar hosts You can
379. ion is simply omitted Code Region 26 3 Handling failures from IFailuresPreprocessor public class SwallowTransactionWarning IExternalCommand public Autodesk Revit UI Result Execute ExternalCommandData commandData ref string message ElementSet elements Autodesk Revit ApplicationServices Application app Comma ndDat application Document doc commandData Application ActiveUIlDbDocument Document UIDo c ument uridoc commandat a Appl leak lon ACrIvVeU I DoOCuUment Filtered temen Collector collector new FilteredeElement ollector doc Tota e s Ee amna eea Soo collector OfClass typeof Level ToElements Level level elementCollection Cast lt Level gt ElementAt lt Level gt 0 ee Eo tt mew a e o doc Ee Sects OOM JS Hot ble Selec dati g re Orriols rat Oj gt e ore llana Oros Oy ea OE Seur es Soto css ser me TENOXSNOUNSV oras sa lomera OI ee oeePadlurenandlingOperons Tallopt doc Create Newkoon level new UY DES Es Cm 4 returno S3bEOOe SI Revit y Result sueo sedec public class RoomWarningSwallower IFailuresPreprocessor public FailureProcessingResult PreprocessFailures FailuresAccessor failuresAccessor IList FailureMessageAccessor failList new List lt FailureMessageAccessor gt Inside event handler get all warnings failList failuresAccessor GetFailureMessages foreach FailureMessageAccessor failure in failList check FailureDefinitionlds against
380. irection Edges v Load 7 Ref Plane e when selected ro Major Direction Type Parameters Control all elements of this type Es Area Reinforce ES aja Finish Sketch Quit Sketch Instance Parameters Control selected or tobe created instance Construction A Override Area Reinforcement Settings lst Rebar Cover Side Edge E Top Major Hook Type purple curve in N edit mode Dimensions Length x Figure 154 AreaReinforcementCurve in edit mode The Major Direction of the area reinforcement can be set when creating a new AreaReinforcement using the NewAreaReinforcement method the last XYZ direction input parameter and by using the AreaReinforcement Direction property Code Region 29 3 NewAreaReinforcement view plaincopy to clipboardprint 1 public AreaReinforcement NewAreaReinforcement Ze Element host CurveArray curves XYZ direction Although the AreaReinforcement GetCurveElementlds method returns a set of Elementlds representing AreaReinforcementCurves which have a property that returns a Curve the PathReinforcement GetCurveElementlds method returns a collection of Elementlds that represent ModelCurves There is no way to flip the PathReinforcement except by using the NewPathReinforcement method the last input parameter Code Region 29 4 NewPathReinforcement view plaincopy to clipboardprint 1 public PathReinforcement NewPathReinforcement 25 Element host CurveArray curves bool
381. it Creation Document NewAreaReinforcement e Autodesk Revit Creation Document NewPathReinforcement In addition to the forbidden methods listed above other API methods that require documents to be in transaction free state may not be called either Such methods include but are not limited to Save SaveAs Close LoadFamily etc Please refer to the documentation of the respective methods for more information Calls to the UpdaterRegistry class such as RegistryUpdater or AddTrigger from within the Execute method of an updater are also forbidden Calling any of the UpdaterRegistry methods will throw an exception The one exception to this rule is the UpdaterRegistry UnregisterUpdater method which may be called during execution of an updater as long as the updater to be unregistered is not the one currently being executed Although the following methods are allowed during execution of an Updater they can also throw ForbiddenForDynamicUpdateException when cross references between elements are established as a result of the call One such example could be creating a face wall that intersects with an existing face wall so those two would have to be joined together Apply caution when calling these methods from an Updater e Autodesk Revit Creation ltemFactoryBase NewFamilylnstances e Autodesk Revit Creation ItemFactoryBase NewFamilyInstance Autodesk Revit DB XYZ Autodesk Revit DB FamilySymbol Autodesk Revit DB Element Autodesk Rev
382. it DB IFC namespace contains numerous IFC related API classes that can be utilized by a custom implementation of the IFC export process For a complete sample of a custom IFC export application see the Open Source example at http sourceforge net projects ifcexporter Linked Files The Revit API can determine which elements in Revit are references to external files linked files and can make some modifications to how Revit loads external files An Element which contains an ExternalFileReference is an element which refers to some file outside of the base rvt file Examples include Revit links CAD links the element which stores the location of the keynote file and rendering decals Element IsExternalFileReference returns whether or not an element represents an external file And Element GetExternalFileReference returns the ExternalFileReference for a given Element which contains information pertaining to the external file referenced by the element The following classes are associated with linked files in the Revit API e ExternalFileReference A non Element class which contains path and type information for a single external file which a Revit project references e ExternalFileUtils A utility class which allows the user to find all external file references get the external file reference from an element or tell whether an element is an external file reference e RevitLinkType An element representing a Revit file linked into a Revi
383. it DB Structure StructuralType e Autodesk Revit Creation Document NewFamilyInstance Autodesk Revit DB XYZ Autodesk Revit DB FamilySymbol Autodesk Revit DB Element Autodesk Revit DB Level Autodesk Revit DB Structure StructuralType e Autodesk Revit DB FaceWall Create It should also be noted that deleting and recreating existing elements should be avoided if modifying them would suffice While deleting elements may be a simpler solution it will not only affect Revit s performance but it will also destroy any references to recreated objects from other elements This could cause the user to lose work they have done to constrain and annotate the elements in question Managing Changes Updaters need to be able to handle complex issues that may arise from their use possibly reconciling subsequent changes to an element Elements modified by an updater may change by the time the updater is next invoked and those changes may impact information modified by the updater For example the element may be explicitly edited by the user or implicitly edited due to propagated changes triggered by a regeneration It is also possible that the same element may be modified by another updater possibly even within the same transaction Although explicit changes of exactly the same data is tracked and prohibited indirect or propagated changes are still possible Perhaps the most complex case is that an element could be changed by the user and or the same update
384. ity schema XYZ retrievedData retrievedEntity Get lt XYZ gt schema GetField WireSplicelocation DisplayUnitType DUT METERS creates cnens andas Oe Diele S Coni Extensible Storage Advantages Self Documenting and Self Defining Creating a schema by adding fields units sub entities and description strings is not only a means for storing data It is also implicit documentation for other users and a way for others to create entities of the same schema later with an easy adoption path Takes Advantage of Locality Because schema entities are stored on a per element basis there is no need to necessarily read all extensible storage data in a document e g all data from all beam family instances when an application might only need data for the currently selected beam This allows the potential for more specifically targeted data access code and better data access performance overall Transactions Transactions are context like objects that encapsulate any changes to a Revit model Any change to a document can only be made while there is an active transaction open for that document Attempting to change the document outside of a transaction will throw an exception Changes do not become a part of the model until the active transaction is committed Consequently all changes made in a transaction can be rolled back either explicitly or implicitly by the destructor Only one transaction per document can be open at any given time A tr
385. ject or PickObjects Types of objects that can be specified are Element PointOnElement Edge or Face The StatusbarTip property shows a message in the status bar when your application prompts the user to pick objects or elements Each of the Pick functions has an overload that has a String parameter in which a custom status message can be provided Code Region 7 2 Adding selected elements with PickObject and PickElementsByRectangle view plaincopy to clipboardprint UIDocument uidoc new UIDocument document Selection choices uidoc Selection Pick one object from Revit Reference hasPickOne choices PickObject ObjectType Element if hasPickOne null TaskDialog Show Revit One element added to Selection COON ADU UNA j H Ww int selectionCount choices Elements Size Choose objects from Revit IList Element hasPickSome choices PickElementsByRectangle Select by rectangle if hasPickSome Count 0 d 15 int newSelectionCount choices Elements Size 16 string prompt string Format 0 elements added to Selection T7 newSelectionCount selectionCount 18 TaskDialog Show Revit prompt 19 Se HH PUNE The PickPoint method has 2 overloads with an ObjectSnapTypes parameter which is used to specify the type of snap types used for the selection More than one can be specified as shown in the next example Code Region 7 3 Snap points view plainco
386. k o GUID Identifies the parameter definition o NAME Parameter definition name o DATATYPE Parameter type This field can be a common type TEXT INTEGER etc structural type FORCE MOMENT etc or common family type Area Tags etc Common type and structural type parameters are specified in the text file directly e g TEXT FORCE If the value of the DATATYPE field is FAMILYTYPE an extra number is added For example FAMILYTYPE followed by 2005020 represents Family type Area Tags Code Region 22 2 Shared Parameter FAMILYTYPE example FAMILYIYPE 2009020 Parameter Properties x area Taga Discipline Common Type of Parameter Family type Area Tags hal Figure 131 New parameter definition o GROUP A group ID used to identify the group that includes the current parameter definition o VISIBLE Identifies whether the parameter is visible The value of this field is O or 1 O invisible l visible As the definition file sample shows there are two groups e MyGroup ID 1 Contains the parameter definition for MyParam which is a Text type parameter e AnotherGroup ID 2 Contains the parameter definition for Price which is an Integer type parameter Definition File Access In the add in code complete the following steps to gain access to the definition file 1 Specify the Autodesk Revit Options Application SharedParametersFilename property with an existing text file or a new one 2 Open the
387. kDialog Show External Event Click Close to close 6 7 8 public string GetName 9 10 return External Event Example 11 12 ExternalEvent The ExternalEvent class is used to create an ExternalEvent An instance of this class will be returned to an external event s owner upon the event s creation The event s owner will use this instance to signal that the event should be called by Revit Revit will periodically check if any of the events have been signaled raised and will execute all events that were raised by calling the Execute method on the events respective handlers The following example shows the implementation of an IExternalApplication that has a method ShowForm that is called from an ExternalCommand shown at the end of the code region The ShowForm method creates a new instance of the external events handler from the example above creates a new ExternalEvent and then displays the modeless dialog box which will later use the passed in ExternalEvent object to raise events Code Region Create the ExternalEvent view plaincopy to clipboardprint 1 public class ExternalEventExampleApp IExternalApplication 2 4 3 class instance A public static ExternalEventExampleApp thisApp null 5 ModelessForm instance 6 private ExternalEventExampleDialog m_MyForm 7 8 public Result OnShutdown UIControlledApplication application 9 10 if m MyForm null amp amp m MyForm Vis
388. kelvin kg ft 2 s 2 K Thermal properties can be retrieved using the ThermalProperties property on the following types ThermalMass e WallType e FloorType e CeilingType e RoofType e BuildingPadType Family Instances In this section you will learn about the following e The relationship between family and family instance e Family and family instance features e How to load or create family and family instance features e The relationship between family instance and family symbol Topics in this section e Identifying Elements e Family e Familylnstances e FamilySymbol e Code Samples Identifying Elements In Revit the easiest way to judge whether an element is a FamilyInstance or not is by using the properties dialog box e Ifthe family name starts with System Family and the Load button is disabled it belongs to System Family Element Properties Figure 41 System Family e AgeneralFamilyInstance which belongs to the Component Family does not start with System Family e For example in the following picture the family name for the desk furniture is Desk In addition the Load button is enabled Element Properties Family Desk Type BO x 30 Figure 42 Component Family e There are some exceptions for example Mass and in place member The Family and Type fields are blank Element Properties m Edit Mew Figure 43 Mass or in place member example Families in the Revit Pl
389. l be based on the approximation deviation value GetApproximationDeviation and the Use Hard points parameter UsesHardPoints These values have corresponding Set methods as well The approximation deviation limits the distance between the smooth curve and a line segment generated by an approximation Hard points are the locations on the curved beam where other structural elements are touching When you set this parameter to true it forces the segmented analytical model to have nodal points at the ends of the members attached to the curved beam AnalyzeAs The Analyze As parameter can be retrieved and set via the AnalyticalModel This parameter indicates to analysis programs how an element should be analyzed or whether the element is NotForAnalysis Since the AnalyzeAs enum used by GetAnalyzeAs and SetAnalyzeAs contains enum values used for different types of elements not all values are applicable for all analytical models Use the IsAnalyzeAsValid method to determine if a particular value is applicable for the analytical model Manual Adjustment The geometry of the structural member analytical model may also be adjusted in relation to those elements to which it joins assuming the SupportsManualAdjustment method returns true Use the AnalyticalModel ManuallyAdjust method to adjust the analytical model in relation to another element Code Region 29 14 Adjusting the analytical model in relation to another element Pick Ene source ana
390. l selected or ta be created instance Fi arameter ae E The value of FirstEnd Constraints Second End feo o 3 property is OO i NC The value of Graphics a SecondEnd is 20 0 visible Visibility Graphics Overrides Materials and Finishes Material Identity Data Subcategory Figure 85 Blend parameters in the UI Bottom Figure 86 Blend top sketch and bottom sketch E Figure 87 Blend result The Sweep command sweeps one profile along a created 2D path or selected 3D path The path may be an open or closed loop but must pierce the profile plane Query the Sweep Form object for a generic form for use in family modeling and massing The Sweep class has the following properties Table 43 Sweep Properties Property Description Path3d Returns the 3D Path Sketch It is a Path3D object PathSketch Returns the Plan Path Sketch It is a Sketch object ProfileSketch Returns the profile Sketch It is a Sketch object EnableTrajSegmentation Returns the Trajectory Segmentation state It is a Boolean MaxSegmentAngle Returns the Maximum Segment Angle It is a Double type Creating a 2D Path is similar to other forms The 3D Path is fetched by picking the created 3D curves Profile SketchPlane Figure 88 Pick the Sweep 3D path Note The following information applies to Sweep e The Path3d property is available only when you use Pick Path to get the 3D path e PathSketch is available whether the p
391. lTypeld ElementId InvalidElementId 3 if ldoc AnnotationSymbolTypes IsEmpty 4 Ds foreach AnnotationSymbolType type in doc AnnotationSymbolTypes 6 7 annotationSymbolTypeld type Family Id 8 break 9 Ee ho 12 Create a noteblock view schedule 13 ViewSchedule noteBlockSchedule ViewSchedule CreateNoteBlock doc annotationSymbolTypeId Schedule Contents The ScheduleDefinition class contains various settings that define the contents of a schedule view including e The schedule s category and other basic properties that determine the type of schedule e Aset of fields that become the columns of the schedule e Sorting and grouping criteria e Filters that restrict the set of elements visible in the schedule Most schedules contain a single ScheduleDefinition which is retrieved via the ViewSchedule Definition property In Revit MEP schedules of certain categories can contain an embedded schedule containing elements associated with the elements in the primary schedule for example a room schedule showing the elements inside each room or a duct system schedule showing the elements associated with each system An embedded schedule has its own category fields filters etc Those settings are stored ina second ScheduleDefinition object When present the embedded ScheduleDefinition is obtained from the ScheduleDefinition EmbeddedDefinition property Adding Fields Once a ViewSchedule is created fields can be add
392. ld returns id of first element to pass all applied filters 3 Obtain an Elementld or Element iterator o GetElementldlterator returns FilteredElementiditerator to the element ids passing the filters o GetElementlterator returns FilteredElementlterator to the elements passing the filters o GetEnumerator returns an IEnumerator lt Element gt that iterates through collection of passing elements You should only use one of the methods from these groups at a time the collector will reset if you call another method to extract elements Thus if you have previously obtained an iterator it will be stopped and traverse no more elements if you call another method to extract elements Which method is best depends on the application If just one matching element is required FirstElement or FirstElementld is the best choice If all the matching elements are required use ToElements If a variable number are needed use an iterator If the application will be deleting elements or making significant changes to elements in the filtered list ToElementids or an element id iterator are the best options This is because deleting elements or making significant changes to an element can invalidate an element handle With element ids the call to Document GetElement with the Elementid will always return a valid Element or a null reference if the element has been deleted Using the ToElements method to get the filter results as a collection of
393. le Do not warn about this updater again and continue working with the file Figure 135 Missing Third Party Updater Warning Updater performs invalid operation If an updater has an error such as an unhandled exception a message similar to the following is displayed giving the user the option to disable the updater Error cannot be ignored Third par Ly upoaler Wall Type Updater has per farmed an invalid per a liar l Figure 136 Updater performed an invalid operation If the user selects Cancel the entire transaction is rolled back In the Wall Updater example from earlier in this chapter the newly added wall is removed If the user selects Disable Updater the updater is no longer called but the transaction is not rolled back I nfinite loop In the event that an updater falls into an infinite loop Revit will notify the user and disable the updater for the duration of the Revit session Two updaters attempt to edit same element If an updater attempts to edit the same parameter of an element that was updated by another updater in the same transaction or if an updater attempts to edit the geometry of an element in a way that conflicts with a change made by another updater the updater is canceled an error message is displayed and the user is given the option to disable the updater Central document modified by updater not present locally If the user reloads latest or saves to central with a central file
394. le Double Creates a new rectangular profile wall within the project using the specified wall type height and Boolean Boolean offset Create Document IList lt Curve gt Boolean Creates a non rectangular profile wall within the project using the default wall style Create Document Curve Elementld Boolean Creates a new rectangular profile wall within the project on the level specified by Elementld using the default wall style Create Document IList lt Curve gt Elementld Elementid Boolean Creates a non rectangular profile wall within the project using the specified wall type Create Document IList lt Curve gt Elementld Elementld Boolean Creates a non rectangular profile wall within the project using the specified wall type and normal XYZ vector The WallType Wall Function WALL ATTR EXTERIOR parameter influences the created wall instance Room Bounding and Structural Usage parameter The WALL ATTR EXTERIOR value is an integer Table 26 Wall Function Wall Function Interior Exterior Foundation Retaining Soffit Value 0 1 2 3 4 The following rules apply to Walls created by the API e lf the input structural parameter is true or the Wall Function WALL ATTR EXTERIOR parameter is Foundation the Wall StructuralUsage parameter is Bearing otherwise it is NonBearing e The created Wall Room Bounding WALL ATTR ROOM BOUNDING parameter is false if the Wall Function WALL ATTR EXTERIOR parameter is Retaining For more infor
395. lector collector new FilteredElementCollector document 10 ICollection Element collection collector OfClass typeof FamilySymbol ToElements 11 foreach Element e in collection Td 13 familySymbol e as FamilySymbol 14 if null familySymbol Category 15 16 if Structural Columns familySymbol Category Name 17 18 break 19 20 21 224 23 if null familySymbol 24 25 Create 10 FamilyInstanceCreationData items for batch creation 26 for int i 1 i lt 11 i 27 28 XYZ location new XYZ i 10 100 0 29 FamilyInstanceCreationData fiCreationData new FamilyInstanceCreationData location familySymbol level 30 StructuralType Column 31 if null fiCreationData 32 33 fiCreationDatas Add fiCreationData 34 db 36 37 if fiCreationDatas Count gt 0 38 39 Create Columns 40 elementSet document Create NewFamilyInstances2 fiCreationDatas ai 42 else 43 44 throw new Exception Batch creation failed 45 46 47 else 48 49 throw new Exception No column types found 50 51 52 return elementSet 53 Instances of some family types are better created through methods other than Autodesk Revit Creation Document NewFamilyInstance These are listed in the table below Table 33 Options for creating instances with other methods Category Creation method Comments Air Terminal
396. lement id as Wall Autodesk Revit DB Parameter p wall get Parameter Unconnected Height Hie je MEE TOWEL TE AS SS c eB FailureMessage failMessage new FailureMessage Failureld failMessage SetFailingElement 1d doc PostFailure failMessage j else if p AsDouble 100 FailureMessage failMessage new FailureMessage Warnld failMessage SetFailingElement id doc PostFailure failMessage public Foar l ureDer r nition Eauduceld der ise UL PI meas T c e Seq e m fal Llureld yain eu blire kar ure Derer rOn Ga Were el get return m warnId Set 4 mo warna value i pusiese e eA e oa Orma ETON tenian lesiona tana ero e eli bis Saree emacs ible pulento cce qe ES A Fatima so Os pisa llei Ma ie public UpdaterId GetUpdaterId rottur moupaster ic public string GetUpdaterName return Wall Height Check Removal of posted failures Because there may be multiple changes to a document and multiple regenerations in the same transaction it is possible that some failures are no longer relevant and they may need to be removed to prevent false alarms Specific messages can be un posted by calling the Document UnpostFailure method and passing in the FailureMessageKey obtained when PostFailure was called UnpostFailure will throw an exception if the severity of the failure is DocumentCorruption It is also possible to automatically remove all posted fail
397. lems may resul P Eccc SEE Neb SC E ue c NCC wallUpdater WarnId warnId wa Up darer kar lure deea FailureDefinitionld A unique FailureDefinitionld must be used as a key to register the FailureDefinition Each unique FailureDefinitionld should be created using a GUID generation tool Later the FailureDefinitionld can be used to look up a FailureDefinition in FailureDefinitionRegistry and to create and post FailureMessages Severity When registering a new failure a severity is specified along with the FailureDefinitionld and a text description of the failure that can be displayed to the user The severity determines what actions are allowed in a document and whether the transaction can be committed at all The severity options are e Warning Failure that can be ignored by end user Failures of this severity do not prevent transactions from being committed This severity should be used when Revit needs to communicate a problem to the user but the problem does not prevent the user from continuing to work on the document e Error Failure that cannot be ignored If FailureMeassage of this severity is posted the current transaction cannot be committed unless the failure is resolved via an appropriate FailureResolution This severity should be used when work on the document cannot be continued unless the problem is resolved If the failure has no predefined resolutions available or these resolutions fail to resolve the problem the transacti
398. les lie log onm O nBU CE ONS OU Took Daloa GT o Rs de TS cancel as Lese log Comm mete cons loumcicoms TaskDialogResult result taskDialog Show if TaskDialogResult Cancel result 1L 1 Die mer Simow Tele evi Cla lloc args OverrideResult 1 Continue to show the Revit dialog args OverrideResult 0 E Add in Registration Table of contents 1 Manifest Files 2 NET Add in Utility for manifest files External commands and external applications need to be registered in order to appear inside Revit They can be registered by adding them to a addin manifest file The order that external commands and applications are listed in Revit is determined by the order in which they are read in when Revit starts up Manifest Files Starting with Revit 2011 the Revit API offers the ability to register API applications via a addin manifest file Manifest files are read automatically by Revit when they are placed 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 2012 For Vista Windows 7 C ProgramData Autodesk Revit Addins 2012 In a user specific location in application data For Windows XP C Documents and Settings lt user gt Application Data Autodesk Revit Addins 2012 For Vista Windows 7 C Users lt user gt AppData Roaming Autodesk Revit Addins 2012 All files named add
399. less the referenced view is a Drafting view Drafting views can always be referenced regardless of the parent view type Elevation views can be referenced from Elevation and Drafting parent views Section views can be referenced from Section and Drafting parent views Detail views can be referenced from all parent views except for in FloorPlan CeilingPlan and StructuralPlan parent views where only horizontally oriented Detail views can be referenced FloorPlan CeilingPlan and StructuralPlan views can be referenced from FloorPlan CeilingPlan and StructuralPlan parent views The following example creates a new callout using a Detail ViewFamilyType and then uses the new callout view to create a reference callout Code Region Creating a callout and reference callout view plaincopy to clipboardprint 1 public void CreateCalloutView Document document View parentView 2 3 Find a detail view type 4 IEnumerable ViewFamilyType viewFamilyTypes from elem in new FilteredElementCollector document OfClass typeof ViewFamilyType 5 let type elem as ViewFamilyType 6 where type ViewFamily ViewFamily Detail 7 select type 8 9 ElementId viewFamilyTypeld viewFamilyTypes First Id 10 XYZ point1 new XYZ 2 2 2 11 XYZ point2 new XYZ 30 30 30 12 ElementId parentViewId parentView Id a ViewPlan 13 View view ViewSection CreateCallout document parentViewId viewFamilyTypeId point1 point2 14 15 ViewSection
400. lingType 8 9 Format railing type info for display 10 string info Railing Type railingType Name 11 info nPrimary Handrail Height railingType PrimaryHandrailHeight 12 info nTop Rail Height railingType TopRailHeight 13 14 TaskDialog Show Revit info 15 16 Stairs Annotations class can be used to annotate the slope direction and walk line of a stair The static StairsPath Create method will create a new stairs path for the specified stairs with the specified stairs path type in a specific plan view in which the stairs must be visible The StairsPath class has the same properties that are available in the Properties window when editing a stairs path in the Revit UI such as properties to set the up and down text along or whether the text should be shown at all Additionally offsets for the up and down text can be specified as can an offset for the stairs path from the stairs centerline Modify Stair Paths Properties s Automatic Up Down Direction Standard Stair Paths 1 Frio Text Show Up Text The following example finds a StairsPathType and a FloorPlan in the project and uses them to create a new StairsPath for a given Stairs Code Region Create a StairsPath view plaincopy to clipboardprint 1 private void CreateStairsPath Document document Stairs stairs 2E 3 Transaction transNewPath new Transaction document New Stairs Path 4 transNewPat
401. lkthroughs If you are new to the Revit Platform API the following topics are good starting points to help you understand the product Walkthroughs provide step by step instructions for common scenarios helping you learn about the product or a particular feature The following walkthroughs will help you get started using the Revit Platform API Walkthrough Hello World Illustrates how to create an add in using the Revit Platform API Walkthrough Add Hello World Ribbon Panel Illustrates how to add a custom ribbon panel Walkthrough Retrieve Selected Elements Illustrates how to retrieve selected elements Walkthrough Retrieve Filtered Elements Illustrates how to retrieve elements based on filter criteria Walkthrough Hello World Use the Revit Platform API and C to create a Hello World program using the directions provided For information about how to create an add in application using VB NET refer to Hello World for VB NET The Hello World walkthrough covers the following topics e Create a new project e Add references e Change the class name e Write the code e Debug the add in All operations and code in this section were created using Visual Studio 2010 Create a New Project The first step in writing a C program with Visual Studio is to choose a project type and create a new Class Library From the File menu select New Project 2 Inthe Installed Templates frame click Visual C 3 Inthe right hand fr
402. ll Elements The specified Elements you can retrieve are listed in the following table Table 11 Retrieving Elements from document properties Element Access in property of Document Projectinfo Document Projectlnformation ProjectUnit Document ProjectUnit ProjectLocation Document ProjectLocations Document ActiveProjectLocation SiteLocation Document SiteLocation Phase Document Phases Material Document Settings Materials FamilySymbol relative to the deck Document DeckProfiles profile of the layer within a structure FamilySymbol in the Title Block category Document TitleBlocks All Element types Document AnnotationSymbolTypes BeamSystemTypes ContFootingTypes DimensionTypes FloorTypes GridTypes LevelTypes RebarBarTypes RebarHookTypes RoomTagTypes SpotDimensionTypes WallTypes TextNoteTypes General Properties The following properties are common to each Element created using Revit Every element in an active document has a unique identifier represented by the Elementld storage type Elementld objects are project wide It is a unique number that is never changed in the element model which allows it to be stored externally to retrieve the element when needed To view an element ID in Revit complete the following steps 1 From the Modify tab on the nquiry panel select Element I D The Element ID drop down menu appears 2 Select IDs of Selection to get the ID number for one element we Select by ID
403. ll are created using the NewGroup method The created Group s type depends on the Elements passed e If no detail Element is passed a Model Group is created e If all Elements are detail elements then a Detail Group is created e lf both types of Elements are included a Model Group that contains an Attached Detail Group is created and returned Note When elements are grouped they can be deleted from the project e When a model element in a model group is deleted it is still visible when the mouse cursor hovers over or clicks the group even if the application returns Succeeded to the Ul In fact the model element is deleted and you cannot select or access that element e When the last member of a group instance is deleted excluded or removed from the project the model group instance is deleted When elements are grouped they cannot be moved or rotated If you perform these operations on the grouped elements nothing happens to the elements though the Move or Rotate method returns true You cannot group dimensions and tags without grouping the elements they reference If you do the API call will fail You can group dimensions and tags that refer to model elements in a model group The dimensions and tags are added to an attached detail group The attached detail group cannot be moved copied rotated arrayed or mirrored without doing the same to the parent group Array The Revit Platform API provides two classes LinearArray
404. lli n Thermal Expansion hermalExpansionCoefficientZ coefficient Z Unit Weight UnitWeight double Damping ratio DampingRatio double Minimum Yield MinimumYieldStress double Stress Minimum tensile MinimumTensileStrength double stress Reduction factor ReductionFactor double for shear NEN M peor mn YoungModulusX UT UnitWeight UT Number UT Stress Fy in US codes Also can be considered as the compression stress capacity UT Stress Only used for steel Reduction of Minimum Yield Stress for Shear Shear Yield Stress MinimumYieldStress ReductionFactor UT Number Isotropic Currently exposed for Generic Only Orthotropic LELEEBBELELELEEEELEEEELLLEN double UT Stress YoungModulusY double UT Stress double YoungModulusZ UT Stress Poisson ratio X PoissonModulusX double UT Number Poisson ratio Y PoissonModulusY double UT Number Poisson ratio Z PoissonModulusZ double UT Number Shear modulus X ShearModulusX double UT Stress double UT Stress Shear modulus Y ShearModulusY double UT Stress Thermal Expansion ThermalExpansionCoefficientX double UT TemperalExp coefficient X double Thermal Expansion hermalExpansionCoefficientY UT TemperalExp coefficient Y double UT TemperalExp UT TemperalExp Thermal Expansion ThermalExpansionCoefficientZ coefficient Z Unit Weight UnitWeight double Damping ratio DampingRatio double Concrete ConcreteCompression double compression Lightwe
405. lse 21 22 23 24 make sure the IsTransmitted property is set 254 transData IsTransmitted true 26 modified transmission data must be saved back to the model 27 TransmissionData WriteTransmissionData location transData 28 29 else 30 31 Autodesk Revit UI TaskDialog Show Unload Links The document does not have any transmission data B22 Construct ModelPath for the model file stored in Revit Server To read the TransmissionData object you need to call the static method TransmissionData ReadTransmissionData It requires a ModelPath object We will show you how to construct the ModelPath object that refering to the central file There are two ways to construct a ModelPath object Way 1 e Compose the user visible path string of the central file ModelPathUtils GetRevitServerPrefix relative path Note The folder separator used in the relative path is a forward slash The correct separator is a forward slash e Create a ModelPath object via the ModelPathUtils ConvertUserVisiblePathToModelPath method Pass in the string composed in the previous step e Read the transmission data via the TransmissionData ReadTransmissionData method Pass in the ModelPath obtained in the previous step Suppose the central file testmodel rvt is stored in the root folder of Revit Server SHACNGO35WQRP Here is the code showing the implementation of way 1 view plaincopy to clipboardprint 1
406. lter filter new FamilyStructuralMaterialTypeFilter StructuralMaterialType Wood fj Sep ky ene virile sO uk ne lens a as Elec Oc TIE Tas Isi Tbecee exo lg leere CO b Tee ector 160 1 lee eacus enews ab Toe exse uh temen tolero documen ICollection lt Element gt woodFamiles eellecueox uaeseEss ses ade ee 5 10 eI exiens C E Bind Families are not Wood Use inverted tilter to match tamilies FamilyStructuralMaterialTypeFilter notWoodFilter new FamilyStructuralMaterialTypeFilter StructuralMaterialType Wood true collector new FilteredElementCollector document ICollection Element ier VooCchanmlmes colector nher Passe S NoOne Miren tor ltemenes ie The last two slow filters derive from ElementlntersectsFilter which is a base class for filters used to match elements which intersect with geometry See Code Region Find Nearby Walls in the section Geometry Utility Classes for an example of the use of this type of filter Logical filters Logical filters combine two or more filters logically The following table summarizes the built in logical filters Table 15 Built in Logical Filters Built in Filter What it passes Shortcut Method s LogicalAndFilter Elements that pass 2 or more filters WherePasses adds one additional filter IntersectWith joins two sets of independent filters LogicalOrFilter Elements that pass at least one of 2 or more filters UnionWith joins two sets of independent filters In the exampl
407. lyInstance 1 FamilyInstance column collector FirstElement as FamilyInstance RRO0OXN A UU UNA In some cases FirstElement is not sufficient This next example shows how to use extension methods to get the first non template 3D view which is useful for input to the Referencelntersector constructors Code Region 6 11 Get first passing element using extension methods view plaincopy to clipboardprint Use filter to find a non template 3D view This example does not use FirstElement since first filterd view3D might be a template FilteredElementCollector collector new FilteredElementCollector document Func lt View3D bool isNotTemplate v3 gt v3 IsTemplate collector OfClass typeof View3D use extension methods to get first non template View3D 1 2 3 4 os 6 apply ElementClassFilter 7 8 gs 10 View3D view3D collector Cast lt View3D gt First lt View3D gt isNotTemplate The following example demonstrates the use of the FirstElementid method to get one passing element a 3d view in this case and the use of ToElementlds to get the filter results as a collection of element ids in order to delete a set of elements in this case Code Region 6 12 Using Getting filter results as element ids view plaincopy to clipboardprint FilteredElementCollector collector new FilteredElementCollector document Use shortcut OfClass to get View elements collector OfClass typeof View3D
408. lytical ime to adjust to Selection sel app ActiveUIDocument Selection Reference refAnalytical sel PickObject ObjectType Element Please Pick the source analytical line to adjust to AnalyticalModel aModel doc GetElement refAnalytical as AnalyticalModel Curve aCurve aModel GetCurve Get the reference of the start point AnalyticalModelSelector aSelector new AnalyticalModelSelector aCurve aSelector CurveSelector AnalyticalCurveSelector StartPoint Reference refSourceae aModel Getkeferencelaselector M Pick the source analytical line to be adjusted Reference refAnalytical2 sel PickObject ObjectType Element Please pick the source analytical line to be adjusted AnalyticalModel aModel2 doc GetElement refAnalytical2 as AnalyticalModel Get the reference of the start point Curve aCurve2 aModel2 GetCurve AnalyticalModelSelector aSelector2 new AnalyticalModelSelector aCurve2 aselector2 Curveselector Analytic cal urve elector StarerPoint CE dore ssl ae ms Ene aae c else linen ee eaa as sel aselector2 Curveselector Analywica lCurveselecton Wholegurve Reference refTarget aModel2 GetReference aSelector2 Adjust the analytical line aModel ManuallyAdjust refSource refTarget true AnalyticalModel also provides methods to determine if the analytical model has been manually adjusted and to reset it back to its original location relative to its corresponding physical mod
409. m elem in new FilteredElementCollector document OfClass typeof ViewFamilyType 15 let type elem as ViewFamilyType 16 where type ViewFamily ViewFamily CeilingPlan 17 select type 19 elevation 10 0 20 Level level2 document Create NewLevel elevation 21 ViewPlan ceilingView ViewPlan Create document viewFamilyTypes First Id level2 Id After creating a new plan view the Discipline for the view can be set using the Discipline parameter which is type ViewDiscipline Options include Architectural Structural Mechanical Electrical Plumbing and Coordination For structural plan views the view direction can be set to either Up or Down using the ViewFamilyType PlanViewDirection property Although it is a property of the ViewFamilyType class an exception will be thrown if the property is accessed for views other than StructuralPlan views The view range for plan views can be retrieved via the ViewPlan GetViewRange method The returned PlanViewRange object can be used to find the levels which a plane is relative to and the offset of each plane from that level It is the same information that is available in the View Range dialog in the Revit user interface View Range Primary Range Tap Associated Level 01 Entr Cut plane Associated Level 01 Entr Bottom Associated Level 01 Entr View Depth Level Associated Level 01 Entr The following example shows how to get the top clip plane and the associa
410. mage in a dialog was low For Autodesk products the warning icon exclamation point in a yellow triangle should only be used in situations where a possible action will be destructive in some way and likely cause loss of data or significant loss of time in rework A few examples include e Overwriting a file e Saving to an older or different format where data may be lost e Permanently deleting data e Breaking associations between files through moving or renaming This is only a partial list With the exception of such situations usage of a main image should be avoided See Figure 228 for an example of a Task Dialog with a warning icon Do not show me again DNSM Checkbox optional Task dialogs support a Do not show me again checkbox that can be enabled on dialogs that users can opt to not see in the future The standard wording for the label on this checkbox for English language versions is Do not show me this message again Do not is not contracted to Don t and there is no punctuation at the end of the line For the single action the working should be Always lt action gt for example e ftheaction is Save current drawing the checkbox label would read Always save current drawing e lf the action is Convert objects to linework the checkbox label would read Always convert objects to linework Truss Attachments Removed for Editing Revit must remove the top attachments to edit the profile of the truss Alw
411. manipulate the options set for Updaters Updaters may be registered from any API callback In order to use the UpdaterRegistry functionality the Revit add in must be registered in a manifest file and the Id returned by Updaterld GetAddInId for any Updater obtained from GetUpdaterld must match the AddInid field in the add in s manifest file An add in cannot add remove or modify Updaters that do not belong to it In addition to calling the UpdaterRegistry RegisterUpdater method Updaters should add one or more update triggers via the AddTrigger methods These triggers indicate to the UpdaterRegistry what events should trigger the Updaters Execute method to run They can be set application wide or can apply to changes made in a specific document Update triggers are specified by pairing a change scope and a change type The change scope is one of two things e Anexplicit list of element Ids in a document only changes happening to those elements will trigger the Updater e An implicit list of elements communicated via an ElementFilter every changed element will be run against the filter and if any pass the Updater is triggered There are several options available for change type ChangeTypes are obtained from static methods on the Element class e Element addition via Element GetChangeTypeElementAddition e Element deletion via Element GetChangeTypeElementDeletion e Change of element geometry shape or position via Element GetCh
412. mation about structure related functions such as the AnalyticalModel property refer to Revit Structure Floors Ceilings and Foundations Floor Ceiling and Foundation related API items include Table 28 Floors Ceilings and Foundations in the API Object Element Type ElementType Type Element Creation Other Floor Floor FloorType NewFloor NewSlab FloorType lsFoundationSlab false Slab Floor FloorType NewSlab FloorType IsFoundationSlab false Ceiling Ceiling CeilingType No Category OST Ceilings Wall Foundation ContFooting ContFootingType No Category OST_StructuralFoundation Isolated Foundation Familylnstance FamilySymbol NewFamilyInstance Category OST StructuralFoundation Foundation Slab Floor FloorType NewFloor Category OST_StructuralFoundation FloorType IsFoundationSlab true Note Floor and Ceiling derive from the class CeilingAndFloor The following rules apply to Floor e Elements created from the Foundation Design bar have the same category OST StructuralFoundation but correspond to different Classes e The FloorType IsFoundationSlab property sets the FloorType category to OST StructuralFoundation or not When you retrieve FloorType to create a Floor or Foundation Slab with NewFloor use the following methods Document FloorTypes Fal To create Slab i NewSlab To create Foundation Slab NewFoundationSlab IsFoundationSlab Figure 35 Create foundation and floor slab Curr
413. mation in the FailureMessage object such as failing elements and then call Document PostFailure passing in the new FailureMessage Note that the document must be modifiable in order to post a failure A unique FailureMessageKey returned by PostFailure can be stored for the lifetime of transaction and used to remove a failure message if it is no longer relevant If the same FailureMessage is posted two or more times the same FailureMessageKey is returned If a posted failure has a severity of DocumentCorruption an invalid FailureMessageKey is returned This is because a DocumentCorruption failure cannot be unposted The following example shows an lUpdate class referenced in the Defining and registering a failure code region above that posts a new failure based on information received in the Execute method Code Region 26 2 Posting a failure public class WallWarnUpdater IUpdater bario olo allia OE m oppid Updarer r mupa ene ld Boiro nn eds ole Ma ales Panero a Ae EOUSErTUCEOR bakes Ene o Sa io ton Ene Ecos sores e clie Ines Eois SORT Gleis public WallWarnUpdater AddInId id Hie OO Cla lr m updaterId new UpdaterId m applId new Guid 69797663 7BCB 44f9 B756 E4189FEODED8 public void Execute UpdaterData data Document doc dara cetuecumenmni Autodesk Revit ApplicationServices Application app doc Application foreach Elementia id an data GetModiriedE lemenrids Wall wall doc GetE
414. mbol is loaded instead of a family because loading a single FamilySymbol is faster than loading a Family that contains many FamilySymbols Code Region 12 4 Creating a beam get the active view s level for beam creation Level level document ActiveView Level cata tam by symbol trom tale FamilySymbol gotSymbol null String fileName C Documents and Settings All Users Application Data Autodesk RST 2011 Imperial Librar Siero Ulies IL rami na Sigel VS de le ane seua E String name UOS FamilyInstance instance null if document LoadFamilySymbol fileName name out gotSymbol Jf Loole iow a model lume an tas duet o Sselecced elsmente UiDoC mMment uldoc menos unen documente ElementSet sel uidoc Selection Elements ModelLine modelLine null foreach Autodesk Revit DB Element elem in sel if elem is Modelline modelLine elem as ModelLine break it null modelLine B hESC A inven lose instance document Create NewFamilyInstance modelLine GeometryCurve gotSymbol level StructuralType Beam else throw new Exception Please select a model line before invoking this command else throw new Exception Couldn t load fileName Create a long wall about 180 in length and select it before running this sample The host object must support inserting instances otherwise the NewFamilyInstance method will fail If a host element is not provided for an instance that must be created
415. me types as simple fields Use the SchemaBuilder AddMapField method to create a field containing an ordered key value map in the Schema with given name type of key and type of contained values Supported types for values are the same as for simple fields Supported types for keys are limited to int short byte string bool Elementld and GUID Once the schema is finalized using SchemaBuilder fields can no longer be edited using FieldBuilder At that stage the Schema class provides methods to get a Field by name or a list of all Fields defined in the Schema After all fields have been defined for the schema SchemaBuilder Finish will return the finished Schema A new Entity can be created using that schema For each Field in the Schema the value can be stored using Entity Set which takes a Field and a value whose type is dependent on the field type Once all applicable fields have been set for the entity it can be assigned to an element using the Element SetEntity method To retrieve the data later call Element GetEntity passing in the corresponding Schema If no entity based on that schema was saved with the Element an invalid Entity will be returned To check that a valid Entity was returned call the Entity IsValid method Field values from the entity can be obtained using the Entity Get method The following is an example of all these steps put together Code Region 22 9 Extensible Storage Create a data structure att
416. ment to connect to a system Duct electrical and pipe connectors can all be added similarly using a reference plane where the connector will be placed and a system type for the connector The static methods provided by the ConnectorElement class are e CreateCableTrayConnector e CreateConduitConnector e CreateDuctConnector e CreateElectricalConnector e CreatePipeConnector The following code demonstrates how to add two pipe connectors to faces on an extrusion and set some properties on them Code Region 30 6 Adding a pipe connector view plaincopy to clipboardprint 1 public void CreatePipeConnectors UIDocument uiDocument Extrusion extrusion 2 Su get the faces of the extrusion 4 Options geoOptions uiDocument Document Application Create NewGeometryOptions 5 geoOptions View uiDocument Document ActiveView 6 geoOptions ComputeReferences true 7 8 List lt PlanarFace gt planarFaces new List lt PlanarFace gt 9 Autodesk Revit DB GeometryElement geoElement extrusion get Geometry geoOptions 10 foreach GeometryObject geoObject in geoElement Ti 12 Solid geoSolid geoObject as Solid 13 if null geoSolid 14 15 foreach Face geoFace in geoSolid Faces 16 17 if geoFace is PlanarFace dee 19 planarFaces Add geoFace as PlanarFace 20 21 DON y 295 24 25 if planarFaces Count gt 1 26 235 Create the Supply Hydronic pipe connector 28 ConnectorElem
417. ments Opening objects General Properties This section explains how to use the Opening properties e sRectBoundary Identifies whether the opening has a rectangular boundary o If true it means the Opening has a rectangular boundary and you can get an IList XYZ collection from the Opening BoundaryRect property Otherwise the property returns null o If false you can get a CurveArray object from the BoundaryCurves property e BoundaryCurves If the opening boundary is not a rectangle this property retrieves geometry information otherwise it returns null The property returns a CurveArray object containing the curves that represent the Opening object boundary For more details about Curve refer to Geometry e BoundaryRect If the opening boundary is a rectangle you can get the geometry information using this property otherwise it returns null o The property returns an IList lt XYZ gt collection containing the XYZ coordinates o The IList lt XYZ gt collection usually contains the rectangle boundary minimum lower left and the maximum upper right coordinates e Host The host property retrieves the Opening host element The host element is the element cut by the Opening object Note If the Opening object s category is Shaft Openings the Opening host is null The following example illustrates how to retrieve the existing Opening properties Code Region 11 6 Retrieving existing opening properties private void Getinfo Open
418. merations correspond to the three Detail Levels in the Revit application shown as follows Coarse E medium Fine Figure 115 Three detail levels Different geometry information is retrieved based on different settings in the DetailLevel property For example draw a beam in the Revit application then get the geometry from the beam using the API to draw it The following pictures show the drawing results Coarse Medium Figure 116 Detail geometry for a beam BoundingBoxXYZ BoundingBoxXYZ defines a 3D rectangular box that is required to be parallel to any coordinate axis Similar to the Instance class the BoundingBoxXYZ stores data in the local coordinate space It has a Transform property that transforms the data from the box local coordinate space to the model space In other words to get the box boundary in the model space the same one in Revit transform each data member using the Transform property The following sections illustrate how to use BoundingBoxXYZ Define the View Boundaries BoundingBoxXYZ can be used to define the view boundaries through View CropBox property The following pictures use a section view to show how BoundingBoxXYZ is used in the Revit application Floor Plan View North Elevation View Figure 117 BoundingBoxXYZ in section view The dash lines in the previous pictures show the section view boundary exposed as the CropBox property a BoundingBoxXYZ instance de Fi
419. meters associated with a specific element to determine which parameter id to use BuiltInParameter WALL BASE OFFSET jt Parameter paral 6 itinParameter BuiltinParameter WALL BASE OFFSET Base Offset The parameter ID is used to retrieve the specific parameter from an element if it exists using the Element Parameter property However not all parameters can be retrieved using the ID For example family parameters are not exposed in the Revit Platform API therefore you cannot get them using the built in parameter ID The following code sample shows how to get the specific parameter using the BuiltInParameter Id Code Region 8 3 Getting a parameter based on BuiltInParameter view plaincopy to clipboardprint 1 public Parameter FindWithBuiltinParameterID Wall wall DE 35 Use the WALL BASE OFFSET paramametId 4 to get the base offset parameter of the wall De BuiltInParameter paraIndex BuiltInParameter WALL BASE OFFSET 6 Parameter parameter wall get Parameter paraIndex rin 8 return parameter 9 y Note With the Parameter overload you can use an Enumerated type BuiltInParameter as the method parameter For example use BuiltlnParameter GENERIC WIDTH If you do not know the exact BuiltlnParameter ID get the parameter by iterating the ParameterSet collection Another approach for testing or identification purposes is to test each BuiltInParameter using the get Parameter method When you use this method it i
420. method still returns a true value Code Region 10 5 Using Rotate public void RotateColumn Autodesk Revit DB Document document Autodesk Revit DB Element element Oa Point I igen Ze INO o AM New O AO SO The axis should be a bound line Line axis document Application Create NewLineBound pointl point2 ElementTransformUtils RotateElement document element Id axis Math PI 3 0 If the element Location can be downcast to a LocationCurve or a LocationPoint you can rotate the curve or the point directly Code Region 10 6 Rotating based on location curve bool LocationRotate Autodesk Revit ApplicationServices Application application Autodesk Revit Element element bool rotated false 7 Weicece uns eGllemeinc vile mes loeaciem ETE es LocationCurve curve element Locatilion as S c ENS USA te null curve Curve line curve Curve XYZ aa line get EndPoint 0 KYA CO mew NZ as as Y aa A m0 Line axis application Create NewLineBound aa cc rotated curve Rotate axis Math PI 2 0 Deque me ee cse Code Region 10 7 Rotating based on location point bool LocationRotate Autodesk Revit ApplicationServices Application application Autodesk Revit Element element bool rotated Ealsce LocationPoint location edente Location as NOGab loner GOL e Gali des EO ecu Leia OLA aa LOC cios Gime A CG new XY aa A aa ada A T IO Line axis application Create New
421. metry element with a transformation applied Because this geometry is a copy its members cannot be used as input references to other Revit elements but it can be used geometric analysis and extraction Geometry creation utilities The GeometryCreationUtilities class is a utility class that allows construction of basic solid shapes e Extrusion Revolution Sweep Blend SweptBlend The resulting geometry is not added to the document as a part of any element However the created Solid can be used as inputs to other API functions including e As the input face s to the methods in the Analysis Visualization framework SpatialFieldManager AddSpatialFieldPrimitive this allows the user to visualize the created shape relative to other elements in the document e As the input solid to finding 3D elements by intersection e Asoneor more of the inputs to a Boolean operation e Asa part of a geometric calculation using for example Face Project Face Intersect or other Face Solid and Edge geometry methods The following example uses the GeometryCreationUtilities class to create cylindrical shapes based on a location and height This might be used for example to create volumes around the ends of a wall in order to find other walls within close proximity to the wall end points Code Region Create cylindrical solid view plaincopy to clipboardprint 1 private Solid CreateCylindricalVolume XYZ point double height double radius 2
422. mily object has the following characteristics e Represents an entire family such as a beam e Represents the entire family file on a disk e Contains a number of FamilySymbols The FamilySymbol object represents a specific set of family settings in the Family such as the Type Concrete Rectangular Beam 16x32 The FamilyInstance object is a FamilySymbol instance representing a single instance in the Revit project For example the FamilyInstance can be a single instance of a 16x32 Concrete Rectangular Beam in the project NoteRemember that the FamilyInstance exists in FamilyInstance Elements Datum Elements and Annotation Elements Consequently the following rules apply e Each FamilyInstance has one FamilySymbol e Each FamilySymbol belongs to one Family e Each Family contains one or more FamilySymbols For more detailed information see Family Instances ElementType In the Revit Platform API Symbols are usually non visible elements used to define instances Symbols are called Types in the user interface e Atype can be a specific size in a family such as a 1730 x 2032 door or an 8x4x1 2 angle e Atype can be a style such as default linear or default angular style for dimensions Symbols represent Elements that contain shared data for a set of similar elements In some cases Symbols represent building components that you can get from a warehouse such as doors or windows and can be placed many times in the same building In other ca
423. mode that isolates the analytical model Rayrace The mode that shows the model in interactive raytracing The View IsInTemporaryViewMode method can be used to determine whether the view is currently in the specified TemporaryViewMode Element Visibility in a View Views keep track of visible elements All elements that are graphical and visible in the view can be retrieved using a FilteredElementCollector constructed with a document and the id of the view However some elements in the set may be hidden or covered by other elements You can see them by rotating the view or removing the elements that cover them Accessing these visible elements may require Revit to rebuild the geometry of the view The first time your code uses this constructor for a given view or the first time your code uses this constructor for a view whose display settings have just been changed you may experience a significant performance degradation Elements are shown or hidden in a view by category e The View getVisiblility method queries a category to determine if it is visible or invisible in the view e The View setVisibility method sets all elements in a specific category to visible or invisible A FilteredElementCollector based on a view will only contain elements visible in the current view You cannot retrieve elements that are not graphical or elements that are invisible A FilteredElementCollector based on a document retrieves all elements in the document includi
424. most frequently used control Pressing a button invokes a command Ribbon buttons can be one of the three sizes e Large MUST have a text label e Medium MAY have a text label e Small MAY have a text label Radio Buttons A radio button group represents a set of controls that are mutually exclusive only one can be chosen at a time These groups can be stacked horizontally as seen in the justification buttons in the example below Figure 237 The Format text panel from Revit 2011 Drop down button e Thetop label SHOULD sufficiently describe the contents of the drop down list e Every item in the list SHOULD contain a large icon e A horizontal separator can be optionally added between controls This should be used if the items are logically grouped under one button but are separated into distinct groups a Floor by Face Lp Goff Slab Edge Figure 238 Floor drop down button in Revit Architecture Split Button A split button is a drop down button with a default command that can be accessed by pressing the left side of the button The right side of the button separated by a small vertical separator opens a drop down list The default command SHOULD be duplicated with the top command in the list A split button s default command can be synchronized That is the default command changes depending on the last used command in the drop down list Combo Box and Text Box The guidelines for combo boxes a
425. mple e Write At least one referenced drawing contains one or more objects that were created in instead of The referenced drawing s contains object s that were created in e Include acopyright symbol after any third party application called out in a task dialog Title required All task dialogs require a title Titles of task dialogs should be descriptive and as unique as possible Task dialog titles should take the format of the following lt featureName gt lt shortTitle gt e Where lt featureName gt is the module from which the task dialog was triggered e And lt shortTitle gt is the action that resulted in the task dialog being shown e Examples o Reference Edit Version Conflict o Layer Delete o BOM Edit Formula Where possible use verbs on the second lt shortTitle gt part of the title such as Create Delete Rename Select etc In cases where there is no obviously applicable feature name or several applying a short title alone is sufficient A task dialog title should never be the product name such as AutoCAD Architecture Title bar Icon The icon appearing in the far left to the title bar should be that of the host application this includes third party plug ins Task dialogs may contain plug in names in the title to specify the source of the message but the visual branding of all task dialogs should match the host application such as Revit Structure Inventor AutoCAD Electrical etc Main Instructions
426. mple CHECK BOX The choice being made and its opposite can be clearly expressed to the user with a single ener pde abatido label The opposite of enable is disable RADIO There are between 2 5 mutually exclusive but related choices and the user can only make one BUTTON selection per choice Mew pages should be opened in 5 a new window a new tab TEXT BOX This choice requires manually entering a numerical text value Mew pages should be opened in CO a new window a new tab DROP DOWN Select from a list of mutually exclusive choices LIST It is appropriate to hide the rest of the choices and only show the default selection Also use this instead of radio buttons when there are more than four choices or if real estate is Tooltip assistance limited COMBO BOX Similar to a drop down list box but allows the user to enter information not pre populated in the drop down 9 10 111 14 SLIDER Use when the expected input or existing data will be in a specific range Sliders can also be combined with text boxes to give additional level of user control and give feedback as the slider is moved Exposure Value 4 Brighter Darker SPINNER Use this option if the data can be entered sequentially and has a logical limit This can be used in conjunction with an editable text box Time 12 00 PM es Laying Out a Dialog Basic Elements Every dialog contains the following elements Element Requirements Illustration 1 Title bar Title bars
427. n Curves are often needed as inputs to Revit API methods Curves can be created in several ways e Factory methods on Autodesk Revit Creation Application o NewLineBound o NewLineUnbound o NewLine o NewArc o NewEllipse o NewNurbSpline o NewHermiteSpline e Members of the Curve class o Curve Clone o Curve Transformed property Curve Parameterization Curves in the Revit API can be described as mathematical functions of an input parameter u where the location of the curve at any given point in XYZ space is a function of u Curves can be bound or unbound Unbound curves have no endpoints representing either an infinite abstraction an unbound line or a cyclic curve a circle or ellipse In Revit the parameter u can be represented in two ways e A normalized parameter The start value of the parameter is 0 0 and the end value is 1 0 For some curve types this makes evaluation of the curve along its extents very easy for example the midpoint of a line is at parameter 0 5 Note that for more complex curve equations like Splines this assumption cannot always be made e A raw parameter The start and end value of the parameter can be any value For a given curve the value of the minimum and maximum raw parameter can be obtained through Curve get EndParameter int CH or Curve EndParameter int VB NET Raw parameters are useful because their units are the same as the Revit default units feet So to
428. n A better example is Controls for drawing e Do not include lengthy step by step procedures in tooltips These belong in Help e Use terminology consistently e Make sure that your use of conjunctions does not introduce ambiguities in relationships For example instead of saying replace and tighten the hinges it would be better to split the conjunction up into two simple and redundant sentences Replace the hinges Then tighten the hinges e Be careful with helping verbs Examples of helping verbs include shall may would have should have might have and can For example can and may could be translated as capability and possibility respectively e Watch for invisible plurals such as object and attribute settings Does this mean the settings for one object and one attribute or the settings for many objects and many attributes e Be cautious about words that can be either nouns or verbs Use articles or rewrite phrases like Model Display where model can be a noun or a verb in our software Another example is empty file It can mean to empty a file or a file with no content e Be careful using metaphors Metaphors can be subtle and are often discussed in the context of icons that are not culturally appropriate or understood across cultures Text metaphors such as places the computer in a hibernating state can also be an issue Instead you might say places the computer in a low power state Writing Wording Conside
429. n set of points and that at each point one or more distinct numbers measurements are computed The number of measurements must be the same at all model points The results data is transient it is stored only in the model until the document is closed If the model is saved closed and reopened the analysis results will not be present Topics in this section e Manager for analysis results e Creating analysis results data e Analysis Results Display e Updating Analysis Results Manager for analysis results A new SpatialFieldManager can be added to a view using the static SpatialFieldManager CreateSpatialFieldManager method Only one manager can be associated with a view If a view already has a SpatialFieldManager it can be retrieved with the static method GetSpatialFieldManager CreateSpatialFieldManager takes a parameter for the number of measurements that will be calculated for each point This number defines how many results values will be associated with each point at which results are calculated For example if average solar radiation is computed for every month of the year each point would have 12 corresponding values To add analysis results to the view call AddSpatialFieldPrimitive to create a new analysis results container Four overloads of this method exist to create primitives associated with e A Reference to a curve or a face e Acurve anda transform e Afaceanda transform e No Revit geometry To improve perfo
430. n the input region of the model ViewSchedule A schedule is a tabular representation of data A typical schedule shows all elements of a category doors rooms etc with each row representing an element and each column representing a parameter The ViewSchedule class represents schedules and other schedule like views including single category and multi category schedules key schedules material takeoffs view lists sheet lists keynote legends revision schedules and note blocks The ViewSchedule Export method will export the schedule data to a text file Schedule Creation The ViewSchedule class has several methods for creating new schedules depending on the type of schedule All of the methods have a Document parameter that is the document to which the new schedule or schedule like view will be added The newly created schedule views will appear under the Schedules Quantities node in the Project Browser A standard single category or multi category schedule can be created with the static ViewSchedule CreateSchedule method Code Region ViewSchedule CreateSchedule view plaincopy to clipboardprint i public ViewSchedule ViewSchedule CreateSchedule Document document ElementId categoryId The second parameters the ID of the category whose elements will be included in the schedule or InvalidElementld for a multi category schedule A second CreateSchedule method can be used to create an area schedule and takes an additional
431. n work with multiple shared parameter files but you can only read parameters from one file at a time It is then up to you to choose the same shared parameter file for all models or a different one for each model In addition your API application should avoid interfering with the user s parameter file Ship your application with its own parameter file containing your parameters To load the parameter s into a Revit file e The application must remember the user parameter file name e Switch to the application s parameter file and load the parameter e Then switch back to the user s file Q Do need to distribute the shared parameters file with the model so other programs can use the shared parameters A No The shared parameters file is only used to load shared parameters After they are loaded the file is no longer needed for that model Q Are shared parameter values copied when the corresponding element is copied A Yes If you have a shared parameter that holds the unique ID for an element in your database append the Revit element Unique ID or add another shared parameter with the Revit element unique ID Do this so that you can check it and make sure you are working with the original element ID and not a copy Q Are element Unique IDs UID universally unique and can they ever change A The element UIDs are universally unique but element IDs are only unique within a model For example if you copy a wall from one Revit project to anot
432. n you first obtain the enumerator o The Reset method moves the enumerator back to the original position At this position calling the Current property throws an exception o Call the MoveNext method to advance the enumerator to the collection s first element before reading the current iterator value e The Current property returns the same object until either the MoveNext method or Reset method is called The MoveNext method sets the current iterator to the next element e f MoveNext passes the end of the collection the enumerator is positioned after the last element in the collection and MoveNext returns false o When the enumerator is in this position subsequent calls to the MoveNext also return false o Ifthe last call to the MoveNext returns false calling the Current property throws an exception o To set the current iterator to the first element in the collection again call the Reset method followed by MoveNext e Anenumerator remains valid as long as the collection remains unchanged o If changes are made to the collection such as adding modifying or deleting elements the enumerator is invalidated and the next call to the MoveNext or the Reset method throws an InvalidOperationException o If the collection is modified between the MoveNext and the current iterator the Current property returns to the specified element even if the enumerator is already invalidated NoteAll calls to the Reset method must result in
433. nce analyticalModelFrame GetReference amSelector Jy CSS elos Scout cd cuscueic Eo IIS SEHE Toon Oi llas cias amSelector CurveSelector AnalyticalCurveSelector EndPoint Reference endPointReference analyticalModelFrame GetReference amSelector return true GetPoint If the AnalyticalModel can be expressed by a single point i e Structural Footing this method will return that point Otherwise it will throw an Autodesk Revit Exceptions InapplicableDataException The IsSinglePoint method can be used to determine if the AnalyticalModel can be expressed by a single point The following example demonstrates how to get the analytical location for a structural footing Code Region 29 11 Getting the location for a structural footing retrieve and iterate current selected element UIDocument uidoc commandData Application ActiveUIDocument Elementset selection uUidoc Selection Elements foreach Element e in selection EISE ehe element io Structural rooting FamilyInstance familyInst e as FamilyInstance AS el dieat ec ee a ases aleta cil gt teruel per Eo ot ame AnalyticalModel model familyInst GetAnalyticalModel MS stub eue bas OO ab qus ssi ulen loli Ee OUS ess ab leas tas io lee oi if model IsSinglePoint true XOU ES e ILI oeste T O10 de Olle MOE EE xum o GetCurve If the AnalyticalModel can be expressed by a single curve i e Structural Column or Structural Framing this method will
434. nce StructuralType 5 1 6 case StructuralType Beam 7 message FamilyInstance is a beam 8 break 9 case StructuralType Brace 10 message FamilyInstance is a brace 11 break 12 case StructuralType Column 13 message FamilyInstance is a column 14 break 15 case StructuralType Footing 16 message FamilyInstance is a footing 17 break 18 default 19 message FamilyInstance is non structural or unknown framing 20 break 21 22 TaskDialog Show Revit message 23 You can filter out FamilySymbol objects corresponding to structural columns beams and braces in using categories The category for Structural beams and braces is BuiltlnCategory OST StructuralFraming Code Region 29 2 Using BuiltInCategory OST_StructuralFraming view plaincopy to clipboardprint 1 public void GetBeamAndColumnSymbols Document document 2 3 FamilySymbolSet columnTypes new FamilySymbolSet 4 FamilySymbolSet framingTypes new FamilySymbolSet 5 FilteredElementCollector collector new FilteredElementCollector document 6 ICollection Element elements collector OfClass typeof Family ToElements 7 8 foreach Element element in elements 9 A 10 11 Family tmpFamily element as Family 12 Category category tmpFamily FamilyCategory 13 if null category 14 15 if int BuiltInCategory OST StructuralColumns category Id IntegerValue 16 17 f
435. nd Y Direction Yes but not smaller then the biggest text contained List View Dynamic X and Y Direction Yes but not smaller then the biggest text contained Text Box Dynamic Xand Y if multi line Yes Date Time Box Dynamic X Direction Yes but not smaller then the biggest text contained Tree View Dynamic X and Y Direction Yes but not smaller then the biggest text contained Canvas Dynamic X and Y Direction Yes Group Box Dynamic X and Y Direction Yes but not smaller then the biggest control contained Progress Bar Static X Yes Status Bar Dynamic X Yes Table or data grid Dynamic XandY Yes table columns should grow proportionally in the X direction Tip For more detail on using a FlowLayoutPanel to build a resizable dialog see Walkthrough Arranging Controls on Windows Forms Using a FlowLayoutPanel Dialog Types There are a handful of dialog types that persist throughout the Revit products Utilizing these standard types helps to drive consistency and leverage users existing learning and knowledge patterns Standard input dialog This is the most basic dialog type This should be used when the user needs to make a number of choices and then perform a discrete operation based on those choices Controls should follow rules for Grouping Spacing and Margins and Layout Flow The Revit Export 2D DWF Options dialog is a good example of a Standard Input dialog Title bar Export Object Data F Model Elements Rooms and Areas Grachics Sall O
436. nd text boxes in the ribbon are the same for those used within dialogs See the Dialog Controls section Slide out Panel x Area g set Legend fil Show al lag I Ref Plane Work Plane Room kd e Color Schemes En Area and Volume Computations Room amp rea Figure 239 Floor drop down button in Revit Architecture In general slide outs should be used for commands relevant to the panel but not primary or commonly used ones Each open panel can be optionally pinned open Otherwise once the mouse leaves the panel it closes by itself Three suggested uses of slide outs are commands that launch settings dialogs related to the panel s task s a Help button and an About button Vertical separator A vertical separator MAY be added between a control or sets of controls to create distinct groupings of commands within a panel A panel SHOULD have no more than two separators Icons For proper icon design see the icon design guidelines Text Usage Button Labels These guidelines are for English language only e MUST not have any punctuation except hyphen ampersand or forward slash e MUST be no longer than three words e MUST be no longer than 36 characters e MUST be Title Case e g Show Mass e The ampersand amp MUST be used instead of and A space should appear before and after the ampersand e The forward slash MUST be used instead of or No spaces should appear before and after the slash
437. nd this code covers both cases Note If you want to get the beam and brace driving curve call the FamilyInstance Location property where a LocationCurve is available The sample code is shown as follows Code Region 20 10 Getting solids and curves from a beam view plaincopy to clipboardprint 1 public void GetCurvesFromABeam Autodesk Revit DB FamilyInstance beam Autodesk Revit DB Options options 2E Bu Autodesk Revit DB GeometryElement geomElem beam get Geometry options 4 5 Autodesk Revit DB CurveArray curves new CurveArray 6 Autodesk Revit DB SolidArray solids new SolidArray Ts 8 Find all solids and insert them into solid array 9 AddCurvesAndSolids geomElem ref curves ref solids 10 11 12 private void AddCurvesAndSolids Autodesk Revit DB GeometryElement geomElem 13 ref Autodesk Revit DB CurveArray curves 14 ref Autodesk Revit DB SolidArray solids 15 16 foreach Autodesk Revit DB GeometryObject geomObj in geomElem 17 18 Autodesk Revit DB Curve curve geomObj as Autodesk Revit DB Curve 19 if null curve 20 1 els curves Append curve 295 continue 23 24 Autodesk Revit DB Solid solid geomObj as Autodesk Revit DB Solid 25 if null solid 26 27 solids Append solid 28 continue 29 30 If this GeometryObject is Instance call AddCurvesAndSolids 314 Autodesk Revit DB GeometryInstance geomInst geomObj as Autodesk Revit DB GeometryInstan
438. nding Element Category sub Category Material in a Parameter If the Element object has a Parameter where ParameterType is ParameterType Material you can get the element material from the Parameter For example a structural column FamilySymbol a Familylnstance whose Category is BuiltlnCategory OST StructuralColumns has the Structural Material parameter Get the Material using the Elementld The following code example illustrates how to get the structural column Material that has one component Code Region Getting an element material from a parameter view plaincopy to clipboardprint 1 public void GetMaterial Document document FamilyInstance familyInstance 2 0 35 foreach Parameter parameter in familyInstance Parameters 4 a Definition definition parameter Definition 6 material is stored as element id 7 if parameter StorageType StorageType ElementId 8 SN if definition ParameterGroup BuiltInParameterGroup PG MATERIALS amp amp 10 definition ParameterType ParameterType Material 11 12 Autodesk Revit DB Material material null 13 Autodesk Revit DB ElementId materialId parameter AsElementId lalo if 1 materialld IntegerValue 15 16 Invalid ElementId assume the material is By Category 17 if null familyInstance Category 18 19 material familyInstance Category Material 20 21 22 else 23 24 material document GetElement materialId as Mat
439. ne 13 get their reference 14 Reference ref1 modelCurvel GeometryCurve Reference 15 Reference ref2 modelCurve2 GeometryCurve Reference 16 Reference arcRef modelCurve3 GeometryCurve Reference 17 18 Dimension newArcDim creationFamily NewArcLengthDimension document ActiveView arcofDim arcRef ref1 ref2 19 if newArcDim null 20 21 throw new Exception Failed to create new arc length dimension 2o 23 24 return newArcDim 25 Figure 51 Resulting arc length dimension Some types of dimensions can be labeled with a FamilyParameter Dimensions that cannot be labeled will throw an Autodesk Revit Exceptions InvalidOperationException if you try to get or set the Label property In the following example a new linear dimension is created between two lines and labeled as width Code Region 13 9 Labeling a dimension view plaincopy to clipboardprint CON DU E UNA public Dimension CreateLinearDimension Document document first create two lines XYZ pt1 new XYZ 5 5 XYZ pt2 new XYZ 5 10 0 Line line document Application Create NewLine pti1 pt2 true Plane plane document Application Create NewPlane pt1 Cross pt2 pt2 SketchPlane skplane document FamilyCreate NewSketchPlane plane ModelCurve modelcurvel document FamilyCreate NewModelCurve line skplane pt1 new XYZ 10 5 0 pt2 new XYZ 10 10 0 line document Application Create NewLi
440. ne pti1 pt2 true plane document Application Create NewPlane pt1 Cross pt2 pt2 skplane document FamilyCreate NewSketchPlane plane ModelCurve modelcurve2 document FamilyCreate NewModelCurve line skplane now create a linear dimension between them ReferenceArray ra new ReferenceArray ra Append modelcurve1 GeometryCurve Reference ra Append modelcurve2 GeometryCurve Reference pt1 new XYZ 5 10 0 pt2 new XYZ 10 10 0 line document Application Create NewLine pti1 pt2 true Dimension dim document FamilyCreate NewLinearDimension document ActiveView line ra create a label for the dimension called width FamilyParameter param document FamilyManager AddParameter width Autodesk Revit Parameters BuiltInParameterGroup PG CONSTRAINTS Autodesk Revit Parameters ParameterType Length false dim Label param return dim width 5 0 Figure 52 Labeled linear dimension Family Element Visibility The FamilyElementVisibility class can be used to control the visibility of family elements in the project document For example if you have a door family you may only want the door swing to be visible in plan views in the project document in which doors are placed not 3D views By setting the visibility on the curves of the door swing you can control their visibility FamilyElementVisibility is applicable to the following family element classes which have the SetVisibility function
441. neric 8 Reference Figure 67 Dimension references A dimension is created by selecting geometric references as the previous picture shows Geometric references are represented as a Reference class in the API The following dimension references are available from the References property For more information about Reference please see Reference in the Geometry section e Radial and diameter dimensions One Reference object for the curve is returned e Angular and arc length dimensions Two Reference objects are returned e Linear dimensions Two or more Reference objects are returned In the following picture the linear dimension has five Reference objects to pg Ct y gm 1 E t ye t l l 17 l Figure 68 Linear dimension references Dimensions like other Annotation Elements are view specific They display only in the view where they are added The Dimension View property returns the specific view Constraint Elements Dimension objects with Category Constraints BuitlnCategory OST Constraints represent two kinds of dimension related constraints e Linear and radial dimension constraints e Equality constraints In the following picture two kinds of locked constraints correspond to linear and radial dimension In the application they appear as padlocks with green dashed lines The green dashed line is available from the Dimension Curve property Both linear and radial dimension constraints return two Reference o
442. new UIiDocument document iSelect on ab dore ee selil r new Planari ee cessi diee iion ileer document IList Reference faces uidoc Selection PickObjects ObjectType Face selFilter Select multiple planar faces j public class PlanarFacesSelectionFilter ISelectionFilter Document doc mull public PlanarFacesSelectionFilter Document document doe documen public bool AllowElement Element element return true public bool AllowReference Reference refer XYZ point if doc GetElement refer GetGeometryObjectFromReference refer is PlanarFace Only return true for planar faces Non planar faces will not be selectable return true I cutn For more information about retrieving Elements from selected Elements see Walkthrough Retrieve Selected Elements in the Getting Started section Parameters Revit provides a general mechanism for giving each element a set of parameters that you can edit In the Revit Ul parameters are visible in the Element Properties dialog box This chapter describes how to get and use built in parameters using the Revit Platform API For more information about user defined shared parameters see Shared Parameters In the Revit Platform API Parameters are managed in the Element class You can access Parameters in these ways e By iterating through the Element Parameters collection of all parameters for an Element for an example see the sample code in Walkthrou
443. new XYZ 15 10 0 50 Line curve 1 Line get Bound p1 p2 51 Line curve_2 Line get_Bound p2 p3 52 Line curve_3 Line get_Bound p3 p4 53 Line curve_4 Line get_Bound p4 p1 54 55 landingLoop Append curve_1 56 landingLoop Append curve_2 57 landingLoop Append curve_3 58 landingLoop Append curve 4 59 StairsLanding newLanding StairsLanding CreateSketchedLanding document newStairsId landingLoop newRun1 TopElevation 60 61 stairsTrans Commit 62 newStairsScope Commit 63 64 return newStairsId 65 The stairs resulting from the above example Adding Railings When new stairs are created using the StairsEditScope Start Elementid Elementid method they have default railings associated with them However the Railing Create method can be used to create new railings with the specified railing type on all sides of a stairs element for stairs without railings Unlike run and landing creation which require the use of StairsEditScope railing creation cannot be performed inside an open stairs editing session Since railings cannot be created for Stairs that already have railings associated with them the following example deletes the existing railings associated with a Stairs object before creating new railings Code Region Create Railings 1 private void CreateRailing Document document Stairs stairs 2 25 Transaction trans new Transaction document Create Railings
444. ng notification when Revit is about to open a document e DocumentOpened notification after Revit has opened a document e DocumentPrinting notification when Revit is about to print a view or ViewSet of the document e DocumentPrinted notification just after Revit has printed a view or ViewSet of the document e DocumentSaving notification when Revit is about to save the document e DocumentSaved notification just after Revit has saved the document e DocumentSavingAs notification when Revit is about to save the document with a new name e DocumentSavedAs notification when Revit has just saved the document with a new name e DocumentSynchronizingWithCentral notification when Revit is about to synchronize a document with the central file e DocumentSynchronizedWithCentral notification just after Revit has synchronized a document with the central file e FailuresProcessing notification when Revit is processing failures at the end of a transaction e FileExporting notification when Revit is about to export to a file format supported by the API e FileExported notification after Revit has exported to a file format supported by the API e Filelmporting notification when Revit is about to import a file format supported by the API e Filelmported notification after Revit has imported a file format supported by the API e ProgressChanged notification when an operation in Revit has progress bar data e ViewPrinting notification
445. ng example creates two new failures a warning and an error that can be used for walls that are too tall In this example they are used in conjunction with an Updater that will do the failure posting in a subsequent code sample in this chapter The FailureDefinitionlds are saved in the Updater class since they will be required when posting failures The sections following explain the FailureDefinition CreateFailureDefinition method parameters in more detail Code Region 26 1 Defining and registering a failure WallWarnUpdater wallUpdater new WallWarnUpdater UpdaterRegistry RegisterUpdater wallUpdater ElementClassFilter filter new ElementClassFilter typeof Wall UpdaterRegistry AddTrigger wallUpdater GetUpdaterId filter Element GetChangeTypeGeometry define a new failure id for a warning about walls eal lwaselbesE bestie oa e weeuexalbel mew la vue Drini Lon lo mew ultor t e dug SNE S4 2 EIE d 5 lE S5 EIE 54 be c register the new warning using FailureDefinition FailureDefinition failDef FailureDefinition CreateFailureDefinition warnlId FailureSeverity Warning Wall is too big gt 100 Performance problems may result Pail lur Derinicionid deal le mew PaaluceDeriaLelomlel mew Guutet 6G5591g5S295 95DO 4it9 92 90 90 72241655JJX c FailureDefinition failDefError FailureDefinition CreateFailureDefinition failld FailureSeverity Error Wall is WAY too big 2200 Performance prob
446. ng invisible elements and non graphical elements For example when creating a default 3D view in an empty project there are no elements in the view but there are many elements in the document all of which are invisible The following code sample counts the number of wall category elements in the active document and active view The number of elements in the active view differs from the number of elements in the document since the document contains non graphical wall category elements Code Region Counting elements in the active view view plaincopy to clipboardprint 1 private void CountElements Autodesk Revit DB Document document 2 3 StringBuilder message new StringBuilder 4 FilteredElementCollector viewCollector new 5 FilteredElementCollector document document ActiveView Id 6 viewCollector OfCategory BuiltInCategory OST Walls 7 message AppendLine Wall category elements within active View 8 viewCollector ToElementIds Count 9 10 FilteredElementCollector docCollector new FilteredElementCollector document 11 docCollector OfCategory BuiltInCategory OST Walls 12 message AppendLine Wall category elements within document 13 docCollector ToElementIds Count 14 15 TaskDialog Show Revit message ToString 16 Temporary view modes can affect element visibility The View IsInTemporaryViewMode method can be used to determine if a View is in a temporary view mode The method View IsElem
447. nnot be inverted e RoomFilter e RoomTagFilter e AreaFilter e AreaTagFilter e SpaceFilter e SpaceTagFilter e FamilylnstanceFilter As mentioned in the quick filters section some classes do not work with the ElementClassFilter Some of those classes such as Room and RoomTag have their own dedicated filters Code Region 6 5 Using the Room filter P ice vee hooker sO EINEN omes ememsisesimstic seme mI Snc scs O Use ae loci ae sus soe ec ei la lee else sale eua Gre ils loja e be imleicinec OE less 0 loSeeulisS as Noon elle ls io Suomi sed oy aos ume mods Roomkilter filter new exo ms les E ETE buco uc eiememise gc eerie aoc men iss c alb THO GNE eds ONSE NM TESI wise cedem ec sex documen lines lt b llene rooms collector WherePasses filter ToElements The ElementParameterFilter is a powerful filter that can find elements based on values of parameters they may have It can find elements whose parameter values match a specific value or are greater or less than some value ElementParameterFilter can also be used to find elements that support a specific shared parameter The example below uses an ElementParameterFilter to find rooms whose size is more than 100 square feet and rooms with less than 100 square feet Code Region 6 6 Using a parameter filter J Cisetes em IHleuwemtbsedxeueter alter to Tind mooms Wiose ar d 18 meter wien Sosei ried ale Ges cer Ma lacio by prover ame evellliat on BuiltInParame
448. not expose the Site menu functions Only Site namespace provides functions corresponding to the Location options found on the Project Location panel on the Manage tab Topics in this section e Place e City e ProjectLocation e Project Position Place In the Revit Platform API the SiteLocation class contains place information including Latitude Longitude and Time Zone This information identifies where the project is located in the world When setting either the Latitude or Longitude note that 1 Revit will attempt to match the coordinates to a city it knows about and if a match is found will set the name accordingly 2 Revit will attempt to automatically adjust the time zone value to match the new Longitude or Latitude value set using SunAndShadowSettings CalculateTimeZone For some boundary cases the time zone calculated may not be correct and the TimeZone property can be set directly if necessary Manage Place and Locations Locations Place There is a single Place for eadli Rewil project Lial defines vil iere tlie project is placed in Fhe vanrld CIty Boston M U54 Latitude 47 5557 Longitude F1 000 Time Zone SMT 05 00 Indiana Cast ck J Ce Hop Figure 123 Project Place City City is an object that contains geographical location information for a known city in the world It contains longitude latitude and time zone information The city list is retrieved by the Cities pro
449. nother failures processing Should be returned after an attempt to resolve failures Can easily lead to an infinite loop if returned without any successful failure resolution Cannot be returned if transaction is already being rolled back and will be treated as ProceedWithRollBack in this case e ProceedWithRollback continues execution of failure processing but forces transaction to be rolled back even if it was originally requested to commit If before ProceedWithRollBack is returned FailureHandlingOptions are set to clear errors after rollback no further error processing will take place all failures will be deleted and transaction is rolled back silently Otherwise default failure processing will continue failures may be delivered to the user but transaction is guaranteed to be rolled back e WaitForUserlnput Can be returned only by FailuresProcessor if it is waiting for an external event typically user input to complete failures processing Depending on the severity of failures posted in the transaction and whether the transaction is being committed or rolled back each of these 3 steps may have certain options to resolve errors All information about failures posted in a document information about ability to perform certain operations to resolve failures and API to perform such operations are provided via the FailuresAccessor class The Document can be used to obtain additional information but it cannot be changed other than via Failures
450. ns Another use of the Referencelntersector class would be to detect intersections such as beams or pipes which intersect interference with the centerline of a given beam or pipe Example Reroute elements around interferences Geometry Utility Classes HostObjectUtils The HostObjectUtils class offers methods as a shortcut to locate certain faces of compound HostObjects These utilities retrieve the faces which act as the boundaries of the object s CompoundStructure e HostObjectUtils GetSideFaces applicable to Walls and FaceWalls you can obtain either the exterior or interior finish faces e HostObjectUtils GetTopFaces and HostObjectUtils GetBottomFaces applicable to roofs floors and ceilings SolidUtils The SolidUtils class contains methods to perform operations on solids e SolidUtils SplitVolumes takes a solid which includes disjoint enclosed volumes and returns newly created Solid objects representing each volume If no splitting is necessary the input solid is returned e SolidUtils TessellateSolidOrShell triangulates a given input Solid which can be one or more fully closed volumes or an open shell Returns a TriangulatedSolidOrShell object which allows access to the stored triangulated boundary component of a solid or a triangulated connected component of a shell FacetingUtils This class is used to convert a triangulated structure into a structure in which some of the triangles have been consol
451. nsform method obtains the basic transform for the instance based on how the instance is placed while GetTotalTransform provides the transform modified with the true north transform for instances like import instances Reference The Reference is very useful in element creation e Dimension creation requires references e The reference identifies a path within a geometric representation tree in a flexible manner e The tree is used to view specific geometric representation creation The API exposes four types of references based on different Pick pointer types They are retrieved from the API in different ways 1 For Point Curve EndPointReference property 2 For Curve Line Arc and etc Curve Reference property 3 For Face Face Reference property 4 For Cut Edge Edge Reference property Different reference types cannot be used arbitrarily For example e The NewLineBoundaryConditions method requires a reference for Line e The NewAreaBoundaryConditions method requires a reference for Face e The NewPointBoundaryConditions method requires a reference for Point The Reference ConvertToStableRepresentation method can be used to save a reference to a geometry object for example a face edge or curve as a string and later in the same Revit session or even in a different session where the same document is present use ParseFromStableRepresentation method to obtain an identical Reference using the string as input Geometry is ty
452. nsitions may have their own groups Unions Union types that connect two segments together MechanicalJoints Mechanical joint types that connect fitting to fitting segment to fitting or segment to segment TransitionsRectangularToRound Multi shape transition from the rectangular profile to the round profile TransitionsRectangularToOval Multi shape transition from the rectangular profile to the oval profile TransitionsOvalToRound Multi shape transition from the oval profile to the round profile Each routing preference rule can have one or more selection criteria represented by the RoutingCriterionBase class and the derived type PrimarySizeCriterion PrimarySizeCriterion selects fittings and segments based on minimum and maximum size constraints The RoutingConditions class holds a collection of RoutingCondition instances The RoutingCondition class represents routing information that is used as input when determining if a routing criterion such as minimum or maximum diameter is met The RoutingPreferencesManager GetMEPPartld method gets a fitting or segment id based on a RoutingPreferenceRuleGroupType and RoutingConditions The following example gets all the pipe types in the document gets the routing preference manager for each one then gets the sizes for each segment based on the rules in the routing preference manager 28 Code Region Using Routing Preferences private List lt double gt GetAvailablePipeSegmentSizesFromDocument Doc
453. nstance th Sa Stan TUS dee Sel ess mb sl Get family associated with this Hail cc ed ds tenes oy moo E liv Get Family document for family Document ias Doc do ment ai ante mac if null familyDoc amp amp familyDoc IsFamilyDocument true Serang loaded MS E AS O6 Eis na ss No A FilteredElementCollector collector new FilteredElementCollector document ICollection lt Element gt collection Collector OL class typ o r Pamily symbol lobklements gt foreach Element e in collection Ip suadeo aule as e cis email e loo ll Ioaded a milies ee tse Nemes e TaskDialog Show Revit loadedFamilies Family Item Factory The FamilyltemFactory class provides the ability to create elements in family documents It is accessed through the Document FamilyCreate property FamilyltemFactory is derived from the ItemFactoryBase class which is a utility to create elements in both Revit project documents and family documents Creating Forms The FamilyltemFactory provides the ability to create form elements in families such as extrusions revolutions sweeps and blends See section 17 2 for more information on these 3D sketch forms The following example demonstrates how to create a new Extrusion element It creates a simple rectangular profile and then moves the newly created Extrusion to a new location Code Region 13 5 Creating a new Extrusion view plaincopy to clipboardprint 1 private Extru
454. nstance fi e as FamilyInstance 38 Family family fi Symbol Family 39 if family FamilyCategory Name Mechanical Equipment 40 41 csi fi MEPModel ConnectorManager Connectors ForwardIterator 42 while csi MoveNext 43 44 if null connector2 45 46 Connector conn csi Current as Connector 47 48 make sure to choose the connector in line with the first connector 49 if Math Abs conn Origin Y connector1 Origin Y 0 001 50 51 connector2 conn 52 break 53 54 55 56 57 58 59 Duct duct null 60 if null connector1 amp amp null connector2 61 62 find a duct type 63 FilteredElementCollector collector 64 new FilteredElementCollector uiDocument Document 65 collector OfClass typeof DuctType 66 67 Use Linq query to make sure it is one of the rectangular duct types 68 var query from element in collector 69 where element Name Contains Mitered Elbows true 70 select element 71 2 use extension methods to get first duct type ER DuctType ductType collector Cast lt DuctType gt First lt DuctType gt 74 755 if null ductType 76 77 duct uiDocument Document Create NewDuct connector1 connector2 ductType 78 79 80 81 return duct 82 Below is the result of running this code after selecting a VAV Unit Parallel Fan Powered and a rectangular elbow duct fitting
455. nt curve get EndPoint 1 X curve get EndPoint 1 Y curve get EndPoint 1 Z 21 break 22 case 2 235 message nThis BoundaryConditions is an Area Boundary Conditions 24 for int i 0 i boundaryConditions NumCurves i 25 1 26 Autodesk Revit DB Curve areaCurve boundaryConditions get Curve i 27 Get curve start point 28 message nCurve start point areaCurve get EndPoint 0 X areaCurve get EndPoint 0 Y areaCurve get EndPoin t 0 Z 29 Get curve end point 30 message Curve end point areaCurve get EndPoint 1 X areaCurve get EndPoint 1 Y areaCurve get EndPoint qo ZU MES 31 324 break 33 default 34 break 35 36 37 TaskDialog Show Revit message 38 Other Structural Elements Some Element derived classes exist in Revit Architecture and Revit Structure products In this section methods specific to Revit Structure are introduced For more information about these classes see the corresponding parts in Walls Floors Roofs and Openings and Family Instances Slab Both Slab Structural Floor and Slab Foundation are represented by the Floor class and are distinguished by the IsFoundationSlab property The Slab Span Directions are represented by the IndependentTag class in the API and are available as follows Figure 157 Slab span directions When using NewSlab to create a Slab Soan Directi
456. nt 26 message nDimension references count is dimension References Size 27 28 if int BuiltInCategory OST Dimensions dimension Category Id IntegerValue 29 30 message nDimension is a permanent dimension Sd 32 else if int BuiltInCategory OST Constraints dimension Category Id IntegerValue 335 34 message nDimension is a constraint element 35 36 TaskDialog Show Revit message 37 There are five kinds of permanent dimensions e Linear dimension e Radial dimension e Diameter Dimension e Angular dimension e Arc length dimension Diameter Dimension z z y P Angular uu Dimension n AT cai i Le GL Cn la i A Radial N 2 N da imension Arc Length Dimension J Linear A 0 Dimension Figure 66 Permanent dimensions The BuiltInCategory for all permanent dimensions is OST Dimensions There is not an easy way to distinguish the four dimensions using the API Except for radial and diameter dimensions every dimension has one dimension line Dimension lines are available from the Dimension Curve property which is always unbound In other words the dimension line does not have a start point or end point Based on the previous picture e A Line object is returned for a linear dimension e Anarc object is returned for a radial dimension or angular dimension e A radial dimension returns null e Adiamter diimension returns null Walls Basic Wall Ge
457. nt Settings M Et all Calbecorlas om cuiden o 5X6 DUTIES dq Categories groups documentSettings Categories show the number or alll Ene categorie Lo the use Sering prompt Number of all categorics in Current Revit document F groups ze get Floor category according to OST Floors and show its name Category floorCategory groups get Item BuiltInCategory OST Floors prompte Malo od EE exero c INS E 4 due wie user some XB 019 96 LOM MessageBox Show prompt Revit MessageBoxButtons OK Category is used in the following manner e Category is used to classify elements The element category determines certain behaviors For example all elements in the same category can be included in the same schedule e Elements have parameters based on their categories e Categories are also used for controlling visibility and graphical appearance in Revit Visibility Graphic Overrides for Floor Plan Level 1 Eg Model Categories Annotation Categories Imported Categories Filters Iw Show model categories in this view IF a categcry iz unchecked it will not be visible Line Style E Visibility Halftone Detail Level K T m Lu wo E IK UE Casework oM Curtain Panels Curtain Systems Curtain Wall Mullians etail Items By Category By Category By Category By Category Buy Category Ey Category Buy Category Furniture Sustems Buy Category Generic Models Buy Category HW Lighting Fix
458. nt document is workshared paths will be treated as relative to the central model To create a ModelPath use one of the derived classes FilePath or ServerPath The class ModelPathUtils contains utility functions for converting ModelPaths to and from user visible path strings as well as to determine if a string is a valid server path Transmission Data TransmissionData stores information on both the previous state and requested state of an external file reference This means that it stores the load state and path of the reference from the most recent time this TransmissionData s document was opened It also stores load state and path information for what Revit should do the next time the document is opened As such TransmissionData can be used to perform operations on external file references without having to open the entire associated Revit document The methods ReadTransmissionData and WriteTransmissionData can be used to obtain information about external references or to change that information For example calling WriteTransmissionData with a TransmissionData object which has had all references set to LinkedFileStatus Unloaded would cause no references to be loaded upon next opening the document TransmissionData cannot add or remove references to external files If AddExternalFileReference is called using an Elementld which does not correspond to an element which is an external file reference the information will be ignored on file load The f
459. nt illustrates how to retrieve Autodesk Revit Document from the commandData parameter Code Region 3 1 Retrieving the Active Document Document doc commandabData Application ActiveUI Document Document The following table illustrates the ExternalCommandData public properties Table 1 ExternalCommandData public properties Property Description Application Autodesk Revit Ul UlApplication Retrieves an object that represents the current UlApplication for external command JournalData A data map that can be used to read and write data to the Revit journal file IDictionary lt String String gt View Autodesk Revit DB View Retrieves an object that represents the View external commands work on message String Error messages are returned by an external command using the output parameter message The string type parameter is set in the external command process When Autodesk Revit Ul Result Failed or Autodesk Revit Ul Result Cancelled is returned and the message parameter is set an error dialog appears The following code sample illustrates how to use the message parameter Code Region 3 2 Setting an error message string view plaincopy to clipboardprint 1 class IExternalCommand message IExternalCommand 2 1 3 public Autodesk Revit UI Result Execute 4 Autodesk Revit ExternalCommandData commandData ref string message 5 Autodesk Revit ElementSet elements 6 7 message Could not locate walls for analysis
460. nt object using the Level In each plan view there is one PlanTopology corresponding to every phase e The same condition applies to BoundarySegment except room separators and Elements whose Room Bounding parameter is true can be a side boundary in the PlanCircuit PlanTopology Level PlanTopologys PlanTopologySet PlanTopology PlanCircuitSet KOy PlanCircuit Rooms Rom Figure 146 Room and Plan Topology diagram The PlanCircuit SideNum property returns the circuit side number which is different from the BoundarySegmentArray Size e The BoundarySegmentArray Size recognizes the bottom wall as two walls if there is a branch on the wall e PlanCircuit SideNum always sees the bottom wall in the picture as one regardless of the number of branches A IN LON ircuit 1 ircuit 3 Circuit4 and Circuit 5 Figure 147 Compare room boundary with PlanCircuit Table 57 Compare Room Boundary with PlanCircuit Circuit Circuit SideNum BoundarySegmentaArray Size for Room Circuit 1 3 3 Room1 Circuit2 442 26 4 3 7 Room2 Circuit3 342 25 3 3 6 Room3 Circuit4 3 3 Room4 Circuit5 3 3 Room5 Room and Familyl nstance Doors and Windows are special family instances related to Room Only doors are discussed here since the only difference is that windows have no handle to flip The following characteristics apply to doors In the following pictures five doors are inserted into walls without flipp
461. ntLoad sb armPoseboi c LEOree Moment False Nornung os usi Analysis Link With Revit Structure an analytical model is automatically generated as you create the physical model The analytical model is linked to structural analysis applications and the physical model is automatically updated from the results through the Revit Structure API Some third party software developers already provide bi directional links to their structural analysis applications These include the following e ADAPT Builder Suite from ADAPT Corporation www adaptsoft com revitstructure e Fastrak and S Frame from CSC www cscworld com e ETABS from CSI www csiberkeley com e RFEM from Dlubal www dlubal com FEA Software RFEM integrates with Revit Structure aspx e Advance Design VisualDesign Arche Effel and SuperSTRESS from GRAITEC www graitec com En revit asp e Scia Engineer from Nemetschek www scia online com en revit html e GSA from Oasys Software Arup www oasys software com products e ProDESK from Prokon Software Consultants www prokon com e RAM Structural System from Bentley www bentley com en US Products RAM Structural System e RISA 3D and RISAFloor from RISA Technologies www risatech com partner revit structure asp e SOFIiSTiK Structural Desktop Suite from SOFiSTiK http www sofistik com revit to sofistik e SPACE GASS from SPACE GASS www spacegass com index asp resend revit asp e Revit Structure STAAD Pro interface from Struc
462. o apply a single ElementFilter to the FilteredElementCollector Filters can also be applied using a number of shortcut methods provided by FilteredElementCollector Some apply a specific filter without further input such as WhereElementlsCurveDriven while others apply a specific filter with a simple piece of input such as the OfCategory method which takes a BuiltInCategory as a parameter And lastly there are methods such as UnionWith that join filters together All of these methods return the same collector allowing filters to be easily chained together Quick filters operate only on the ElementRecord a low memory class which has a limited interface to read element properties Elements which are rejected by a quick filter will not be expanded in memory The following table summarizes the built in quick filters and some examples follow for a few of the filters Table 13 Built in Quick Filters Built in Filter BoundingBoxContainsPointFilter BoundingBoxlntersectsFilter BoundingBoxlsInsideFilter ElementCategoryFilter ElementClassFilter ElementDesignOptionFilter ElementIsCurveDrivenFilter ElementlsElementTypeFilter ElementMulticategoryFilter ElementMulticlassFilter ElementOwnerViewFilter ElementStructuralTypeFilter ExclusionFilter FamilySymbolFilter What it passes Elements which have a bounding box that contains a given point Elements which have a bounding box which intersects a given outline Elements which h
463. obtain a location 5 feet along the curve from the start point you can take the raw parameter at the start and add 5 to it Raw parameters are also the only way to evaluate unbound curves The methods Curve ComputeNormalizedParameter and Curve ComputeRawParameter automatically scale between the two parameter types The method Curve IsInside evaluates a raw parameter to see if it lies within the bounds of the curve You can use the parameter to evaluate a variety of properties of the curve at any given location e The XYZ location of the given curve This is returned from Curve Evaluate Either the raw or normalized parameter can be supplied If you are also calling ComputeDerivatives this is also the Origin property of the Transform returned by that method e The first derivative tangent vector of the given curve This is the BasisX property of the Transform returned by Curve ComputeDerivatives e The second derivative normal vector of the given curve This is the BasisY property of the Transform returned by Curve ComputeDerivatives e The binormal vector of the given curve defined as the cross product of the tangent and normal vector This is the BasisZ property of the Transform returned by Curve ComputeDerivatives All of the vectors returned are non normalized but you can normalize any vector in the Revit API with XYZ Normalize Note that there will be no value set for the normal and binormal vector when the curve is a stra
464. ode Region 3 18 TransactionAttribute Transaction TransactionMode Automatic pull elase C omnmand cuc cmd emmsel public Autodesk Revit IExternalCommand Result Execute Autodesk Revit ExternalCommandData commandData ref string message Autodesk Revit DB ElementSet elements Command implementation which modifies the active document directly Wo ccu S bie eq node See Transactions JournalingAttribute 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 There are two options for journaling e JournalMode NoCommandData Contents of the ExternalCommandbData J ournalData map are not written to the Revit journal This option allows Revit API calls to write to the journal as needed This option allows commands which invoke the Revit UI for selection or responses to task dialogs to replay correctly e JournalMode UsingCommandData Uses the IDictionary String String gt supplied in the command data This will hide all Revit journal entries between the external command invocation and the IDictionary String String gt entry Commands which invoke the Revit UI for selection or responses to task dialogs may not replay correctly This is the default if the J ournalingAttribute is not specified Code Region 3 19 J ournalingAttribute Journaling JournalingMode Us
465. oints into filter 12 View view uiDoc ActiveView 13 XYZ right view RightDirection 14 XYZ up view UpDirection 15 16 List lt Plane gt planes new List lt Plane gt 17 18 X boundaries 19 bool directionCorrect IsPointAbovePlane right min max 20 planes Add app Create NewPlane right directionCorrect min max 21 planes Add app Create NewPlane right directionCorrect max min 22 23 Y boundaries 24 directionCorrect IsPointAbovePlane up min max 255 planes Add app Create NewPlane up directionCorrect min max 26 planes Add app Create NewPlane up directionCorrect max min N N 28 Create filter 29 PointCloudFilter filter PointCloudFilterFactory CreateMultiPlaneFilter planes 30 Transaction t new Transaction uiDoc Document Highlight 31 t Start 32 pcInstance SetSelectionFilter filter 33 pcInstance FilterAction SelectionFilterAction Highlight 34 t Commit 35 uiDoc RefreshActiveView 36 37 38 private static bool IsPointAbovePlane XYZ normal XYZ planePoint XYZ point 39 40 XYZ difference point planePoint 41 difference difference Normalize 42 double dotProduct difference DotProduct normal 43 return dotProduct gt 0 44 Filtered User Selection PickObject PickObjects and PickElementsByRectangle all have overloads that take an ISelectionFilter as a parameter ISelectionFilter is an in
466. ollections Document provides properties such as FloorTypes WallTypes and so on All properties return a collection object containing the corresponding types loaded into the project View Management A project document can have multiple views The ActiveView property returns a View object representing the active view You can filter the elements in the project to retrieve other views For more details see Views Element Retrieval The Document object stores elements in the project Retrieve specific elements by Elementld or Uniqueld using the Element property For more details see Elements Essential File Management Each Document object represents a Revit project file Document provides the following functions e Retrieve file information such as file path name and project title e Provides Close and Save methods to close and save the document For more details see Document and File management Element Management Revit maintains all Element objects in a project To create new elements use the Create property which returns an Object Factory used to create new project element instances in the Revit Platform API such as FamilyInstance or Group The Document class can also be used to delete elements Use the Delete method to delete an element in the project Deleted elements and any dependent elements are not displayed and are removed from the Document References to deleted elements are invalid and cause an exception For more det
467. ollowing example reads the TransmissionData for a file at the given location and sets all Revit links to be unloaded the next time the document is opened Code Region Unload Revit Links view plaincopy to clipboardprint 1 void UnloadRevitLinks ModelPath location 2 This method will set all Revit links to be unloaded the next time the document at the given location is opened 3 The TransmissionData for a given document only contains top level Revit links not nested links 4 However nested links will be unloaded if their parent links are unloaded so this function only needs to look at the document s immediate links 5 1 6 access transmission data in the given Revit file 7 TransmissionData transData TransmissionData ReadTransmissionData location 8 if transData null 9 10 collect all immediate external references in the model 11 ICollection lt ElementId gt externalReferences transData GetAllExternalFileReferenceIds 12 find every reference that is a link 13 foreach ElementId refId in externalReferences 14 15 ExternalFileReference extRef transData GetLastSavedReferenceData refId 16 if extRef ExternalFileReferenceType ExternalFileReferenceType RevitLink 17 18 we do not want to change neither the path nor the path type 19 we only want the links to be unloaded shouldLoad false 20 transData SetDesiredReferenceData refId extRef GetPath extRef PathType fa
468. oltipInfo Owner 29 message nLast Changed by tooltipInfo LastChangedBy 30 31 Autodesk Revit UI TaskDialog Show GetElementWorksharingInfo message 32 Visibility and Display A workset s visibility can be set for a particular view using View SetWorksetVisibility The WorksetVisibility options are Visible it will be visible if the workset is open Hidden and UseGlobalSetting indicating not to override the setting for the view The corresponding View GetWorksetVisibility method retrieves the current visibility settings for a workset in that view However this method does not consider whether the workset is currently open To determine if a workset is visible in a View including taking into account whether the workset is open or closed use View IsWorksetVisible The class WorksetDefaultVisibilitySettings manages default visibility of worksets in a document It is not available for family documents If worksharing is disabled in a document all elements are moved into a single workset that workset and any worksets re created if worksharing is re enabled is visible by default regardless of any current settings The following example hides a workset in a given view and hides it by default in other views Code Region Hide a Workset view plaincopy to clipboardprint 1 public void HideWorkset Document doc View view WorksetId worksetId 2f 35 get the current visibility 4 WorksetVisibility visibility
469. on modeling workflows much the same way as can be done with the Revit user interface Both parts and assemblies can be independently scheduled tagged filtered and exported You can also divide a part into smaller parts After creating an assembly type you can place additional instances in the project and generate isolated assembly views The main classes related to Construction Modeling are e Assemblyinstance This class combines multiple elements for tagging filtering scheduling and creating isolated assembly views e AssemblyType Represents a type for construction assembly elements Each new unique assembly created in the project automatically creats a corresponding AssemblyType A new AssemblyInstance can be placed in the document from an existing AssemblyType e PartUtils This utility class contains general part utility methods including the ability to create parts divide parts and to get information about parts e AssemblyViewUctils A utility class to create various types of assembly views Topics in this section e Parts e Assemblies and Views Assemblies and Views Assemblies The static Create method of the AssemblylInstance class is used to create a new assembly instance in the project The Create method must be created inside a transaction and the transaction must be committed before performing any action on the newly created assembly instance The assembly type is assigned after the transaction is complete T
470. on must be aborted in order to continue working with the document It is strongly encouraged to have at least one resolution in each failure of this severity e DocumentCorruption Failure that forces the Transaction to be rolled back as soon as possible due to known corruption to a document When failure of this severity is posted reading of information from a document is not allowed The current transaction must be rolled back first in order to work with the document This severity is used only if there is known data corruption in the document This type of failure should generally be avoided unless there is no way to prevent corruption or to recover from it locally A fourth severity None cannot be specified when defining a new FailureDefinition Failure Resolutions When a failure can be resolved all possible resolutions should be predefined in the FailureDefinition class This informs Revit what failure resolutions can possibly be used with a given failure The FailureDefinition contains a full list of resolution types applicable to the failure including a user visible caption of the resolution The number of resolutions is not limited however as of the 2011 Revit API the only exposed failure resolution is DeleteElements When more than one resolution is specified unless explicitly changed using the SetDefaultResolutionType method the first resolution added becomes the default resolution The default resolution is used by the Revit failu
471. ones that you want to dismiss FailureDefinitionId failID tei Luce e e 61 LuceWeic sob oe det t 2 prevent Revit from showing Unenclosed room warnings if failID BuiltInFailures RoomFailures RoomNotEnclosed failuresAccessor DeleteWarning failure return FailureProcessingResult Continue FailuresProcessing Event The FailuresProcessing event is most suitable for applications that want to provide custom failure handling without a user interface either for the entire session or for many unrelated transactions Some use cases for handling failures via this event are e automatic removal of certain warnings and or automatic resolving of certain errors based on office standards or other criteria e custom logging of failures The FailuresProcessing event is raised after IFailuresPreprocessor if any has finished It can have any number of handlers and all of them will be invoked Since event handlers have no way to return a value the SetProcessingResult on the event argument should be used to communicate status Only Continue ProceedWithRollback or ProceedWithCommit can be set The following example shows an event handler for the FailuresProcessing event Code Region 26 4 Handling the FailuresProcessing Event private void CheckWarnings object sender FailuresProcessingEventArgs e FailuresAccessor fa e GetFailuresAccessor IList FailureMessageAccessor failList new List lt FailureMessageAccessor gt failList
472. ons are not automatically created There is also no way to create them directly The Slab compound structure layer Structural Deck properties are exposed by the following properties e CompoundStructuralLayer DeckUsage e DeckProfile The properties are outlined in the following dialog box Edit Assembly Family Floor Type 3 OW Concrete on Metal Deck Total thick aess O E Default Structural Deck Properties Deck Profile Deck Usage Form Deck Man Compoasite 2 w E Bound Layer Above bal Figure 158 Floor CompoundStructuralLayer properties Analytical Model In Revit Structure an analytical model is the engineering description of a structural physical model The following structural elements have structural member analytical models e Structural Columns e Structural Framing elements such as beams and braces e Structural Floors e Structural Footings e Structural Walls An Element s AnalyticalModel can be obtained using the GetAnalyticalModel method Note that the AnalyticalModel for a newly created structural element is not available until a Regeneration occurs Depending on the element s family the AnalyticalModel may not exist If the AnalyticalModel value does not apply to an element s family the GetAnalyticalModel method returns null Check the value before using this class AnalyticalModel is made up of the following information e Location of the Element with respect to analysis e Parameter Information
473. op half of the split button can be synchronized with the last used command By default it will be synched Selecting Option Two in the split button from Figure 13 above yields Enter a comment Figure 16 Split button synchronized with current item Note that the ToolTip ToolTiplmage and LongDescription properties for SplitButton are ignored The tooltip for the current push button is shown instead Code Region Adding a split button view plaincopy to clipboardprint private void AddSplitButton RibbonPanel panel string assembly D Sample HelloWorld bin Debug Hello d1l create push buttons for split button drop down PushButtonData bOne new PushButtonData ButtonNameA Option One 1 2 3 4 5 6 y assembly Hello HelloOne 8 bOne LargeImage 9 new BitmapImage new Uri D Sample HelloWorld bin Debug One bmp 10 11 PushButtonData bTwo new PushButtonData ButtonNameB Option Two 12 assembly Hello HelloTwo 13 bTwo Largelmage lie new BitmapImage new Uri D Sample HelloWorld bin Debug Two bmp 15 16 PushButtonData bThree new PushButtonData ButtonNameC Option Three 17 assembly Hello HelloThree 18 bThree Largelmage 19 new BitmapImage new Uri Q D NSampleMHelloWorldNbinNDebugNThree bmp 20 21 SplitButtonData sb1 new SplitButtonData splitButton1 Split 225 SplitButton sb panel AddItem sb1 as SplitButton 23 sb AddPushButton bOn
474. or specific calculation of the geometry of the region is not demonstrated in this example lt param gt returns A collection of interfering element ids lt returns gt private ICollection lt ElementId gt FindElementsInterferingWithDoor FamilyInstance doorInstance Solid doorAccessibilityRegion WO CON NN UE UN FE Ra NBEO ERP eR nu Au Setup the filtered element collector for all document elements FilteredElementCollector interferingCollector new FilteredElementCollector doorInstance Document NR HH Xo OO Only accept element instances interferingCollector WhereElementlIsNotElementType NNN N AUNE Exclude intersections with the door itself or the host wall for the door List ElementId excludedElements new List ElementId exc ludedElements Add doorInstance Id exc ludedElements Add doorInstance Host Id ExclusionFilter exclusionFilter new ExclusionFilter excludedElements interferingCollector WherePasses exclusionFilter UJ N N N N N wW Oon dd ul Set up a filter which matches elements whose solid geometry intersects with the accessibility region ElementIntersectsSolidFilter intersectionFilter new ElementIntersectsSolidFilter doorAccessibilityRegion interferingCollector WherePasses intersectionFilter UJ UJ UJ UJ UJ UJ Nun dh UN ER Return all elements passing the collector return interferingCollector ToElementIds UJ N 38
475. oreach FamilySymbol tmpSymbol in tmpFamily Symbols 18 19 columnTypes Insert tmpSymbol 20 21 225 else if int BuiltInCategory OST StructuralFraming category Id IntegerValue 255 24 foreach FamilySymbol tmpSymbol in tmpFamily Symbols 25 1 26 framingTypes Insert tmpSymbol 27 28 29 30 31 string message Column Types 32 FamilySymbolSetIterator fsItor columnTypes ForwardIterator 23 fsItor Reset 34 while fsItor MoveNext 35 36 FamilySymbol familySybmol fsItor Current as FamilySymbol 37 message Mn familySybmol Name 38 39 TaskDialog Show Revit message 40 You can get and set beam setback properties with the FamilyInstance ExtensionUtility property If this property returns null the beam setback can t be modified AreaReinforcement and PathReinforcement Find the AreaReinforcementCurves for AreaReinforcement by calling the GetCurveElementlds method which returns an IList of Elementlds that represent AreaReinforcementCurves In edit mode AreaReinforcementCurves are the purple curves red when selected in the Revit Ul From the Element Properties dialog box you can see AreaReinforcementCurve parameters Parameters such as Hook Types and Orientation are editable only if the Override Area Reinforcement Setting parameter is true s Modif CL Element Properties 4 Dimension Lines as S Red curve Family System Famil Span D
476. oreach PerformanceAdviserRuleId id in PerformanceAdviser GetPerformanceAdviser GetAllRuleIds 3 1 4 string ruleName PerformanceAdviser GetPerformanceAdviser GetRuleName id 5 d 6 PerformanceAdviser GetPerformanceAdviser ExecuteAllRules document IPerformanceAdviserRule Create an instance of the IPerformanceAdviserRule interface to create new rules for the Performance Adviser Rules can be specific to elements or can be document wide rules The following methods need to be implemented e GetName a short string naming the rule e GetDescription a one to two sentence description of the rule e nitCheck method invoked by performance advisor once in the beginning of the check If rule checks the document as a whole rather than specific elements the check should be performed in this method e FinalizeCheck method invoked by performance advisor once in the end of the check Any problematic results found during rule execution can be reported during this message using FailureMessage s e WillCheckElements indicates if rule needs to be executed on idividual elements e GetElementFilter retrieves a filter to restrict elements to be checked e ExecuteElementCheck method invoked by performance advisor for each element to be checked The following excerpt from the PerformanceAdviserControl sample in the Revit API SDK Samples folder demonstrates the implementation of a custom rule used to identify any doors
477. ormulas Data Review View Add Ins 0 x E X 3 p ee insert Xx gt A eae E A o lan F J nsert ES MEC sen J A domm zr uu a8 58 Conditional Format Cell Sort amp Find amp BIU Formatting as Table Styles BE Format lt 27 Filter Select Number E Styles Cells A TN Cr A M cn LD cO J 28 29 Id 4 b Fl Totals for Roof elements Concrete Precast Concrete Insulation Thermal Barriers Rigid insulation Roofing EPDM Membrane Default Roof Totals for Roof element Concrete Deck w Tapered Insulation id 180471 Concrete Precast Concrete Insulation Thermal Barriers Rigid insulation Roofing EPDM Membrane Totals for Raof element Generic 12 id 188333 Default Roof Totals for Raof element Generic 3 id 246676 Default Roof Totals for Wall elements Masonry Concrete Masonry Units EIFS Exterior Insulation and Finish System Air Barrier Air Infiltration Barrier Vapor Moisture Barriers Vapor Retarder Gypsum Wall Board Metal Stud Layer Concrete Cast in Place Concrete Totals for Wall element Exterior EIFS on CMU id 180225 Masonry Concrete Masonry Units CalculateMaterialQuantities J Enter t Gross volume cubic ft Net volume cubicft Gross area sq ft Net area sq ft 11835 92 9295 30 369 94 709 78 11356 5 8921 58 354 96 709 78 17753 89 17757 11 17757 11 1343 72 17034 7
478. ory Dead Loads OST LoadCasesDead Live Loads OST LoadCasesLive Wind Loads OST LoadCasesWind Snow Loads OST LoadCasesSnow Roof Live Loads OST LoadCasesRoofLive Accidental Loads OST LoadCasesAccidental Temperature Loads OST LoadCasesTemperature Seismic Loads OST LoadCasesSeismic The following Document creation methods create corresponding subclasses e NewLoadUsage creates LoadUsage e NewLoadNature creates LoadNature e NewLoadCase creates LoadCase e NewLoadCombination creates LoadCombination e NewPointLoad creates PointLoad an overload allows you to specify the load host element as a Reference You can optionally specify a load type and sketch plane e NewLineLoad creates LineLoad overloads allow you to specify the host element as a Reference or an Element You can optionally specify a load type and sketch plane e NewAreaLoad creates AreaLoad overloads allow you to specify the host element as a Reference or an Element You can optionally specify a load type and sketch plane Because they are all Element subclasses they can be deleted using Document Delete Code Region 29 14 NewLoadCombination public LoadCombination NewLoadCombination string name int typelnd int statelnd double factors LoadCaseArray cases LoadCombinationArraycombinations LoadUsageArray usages For the NewLoadCombination method the factor size must be equal to or greater than the sum size of cases and combinations For exampl
479. osing group is closed Transaction groups are optional They are not required in order to make modifications to a model The following example shows the use of a TransactionGroup to combine two separate Transactions using the Assimilate method The following code will result in a single Undo item added to the Undo menu with the name Group Change Code Region 23 2 Combining multiple transactions into a TransactionGroup public TransactionStatus TransactionGroupDemo Autodesk Revit DB Document document Transaction tarus starls Iranta elon tactus UMN ise ell ae 0 bool bAssimilate true TransactionGroup transGroup new TransactionGroup document Group Change Mie ideas Cro oo otari ransa tion ee t DIS y ele cecal Transaction levelIransacLion Mew Iransaction document Adda Level EGS if levelTransaction Start TransactionStatus Started document Create Newhevel 25 0 Lee Iie aa See 15 euge Comins e cacc ar either interni Eran e on eo a eI elena TEES leve TE De eau eie E OW lo ls e k bAssimilate false iras altos me ees e nue Wien In e xc if bAssimilate true ansa tion gridiransa tIon mew canse ton document Acad Grid Ery We lene O e Sos aci ans eos e XO Pont mew LA 0 Un 10 Ne Point mew Ie IO Oj Line gridLine document Application Create NewLine Pointl Point2 true document Create NewGrid gridLine Sos edi ola Coniate 0 e
480. ot always required to commit a transaction The transaction framework also allows for Trasactions to be rolled back This is useful when there is an error during the processing of the transaction but can also be leverage directly as a technique to create a temporary transaction Using a temporary transaction can be useful for certain types of analyses For example an application looking to extract geometric properties from a wall or other object before it is cut by openings should use a temporary transaction in conjunction with Document Delete When the application deletes the elements that cut the target elements the cut element s geometry is restored to its original state after the document has been regenerated To use a temporary transaction Instantiate the Transaction using the Transaction constructor and assign it a name 2 Call Transaction Start 3 Make the temporary change s to the document element modification deletion or creation 4 Regenerate the document 5 Extract the desired geometry and properties 6 Call Transaction RollBack to restore the document to the previous state This technique is also applicable to SubTransactions Events Events are notifications that are triggered on specific actions in the Revit user interface or API workflows By subscribing to events an add in application can be notified when an action is about to happen or has just happened and take some action related to that event Some events come in
481. oup You may use the Ungroup option to proceed with this change by ungrouping the changed group instances A Currently the API does not permit changes to group members You can programmatically ungroup make the change regroup and then swap the other instances of the old group to the new group to get the same effect Hello World for VB NET Directions for creating the sample application for Visual Basic NET are available in the following sections The sample application was created using Microsoft Visual Studio Topics in this section e Create a New Project e Add Reference and Namespace e Change the Class Name e Add Code e Create a addin manifest file e Build the Program e Debug the Program Create a New Project The first step in writing a VB NET program with Visual Studio is to choose a project type and create a new project 1 From the File menu select New Project 2 Inthe Installed Templates frame click Visual Basic 3 Inthe right hand frame click Class Library The application assumes that your project location is D Sample 4 Inthe Name field type HelloWorld as the project name 5 Click OK New Project Recent Templates NET Framework 4 Sort by Defaut a Search Installed Ternplates insted eee Type Visual Basic nO B Windows Forms Application Visual Basic 4 Visual C A project for creating a VB class library Windows dll Web WPF Application Visual Basic Office Cloud Console
482. pairs around actions one occurring before the action takes place pre event and the other happening after the action takes place post event Events that do not occur in these pre post pairs are called single events Revit provides access to events at both the Application level such as ApplicationClosing or DocumentOpened and the Document level such as DocumentClosing and DocumentPrinting The same application level events available from the Application class are also available from the ControlledApplication class which represents the Revit application with no access to documents It is ControlledApplication that is available to add ins from the OnStartup and OnShutdown methods In terms of subscribing and unsubscribing to events these classes are interchangeable subscribing to an event from the ControlledApplication class is the same as subscribing from the Application class Events can also be categorized as database DB events or user interface UI events DB events are available from the Application and Document classes while Ul events are available from the UlApplication class Currently all Ul events are at the application level only Some events are considered read only which means that during their execution the model may not be modified The fact that an event is read only is documented in the API help file It is important to know that even during regular events i e not read only events the model may be in a state in wh
483. parameter that is the ID of an area scheme for the schedule Code Region Creating an area schedule view plaincopy to clipboardprint 1 FilteredElementCollector collector1 new FilteredElementCollector doc 2 collector1 OfCategory BuiltInCategory OST AreaSchemes 3 Get first ElementId of AreaScheme 4 ElementId areaSchemeId collector1 FirstElementla 5 6 If you want to create an area schedule you must use CreateSchedule method with three arguments 7 The input of second argument must be ElementId of BuiltInCategory OST_Areas category and the input of third argument must be ElementId of a areaSc heme 8 ViewSchedule areaSchedule Autodesk Revit DB ViewSchedule CreateSchedule doc new ElementId BuiltInCategory OST Areas areaSchemeld A key schedule displays abstract key elements that can be used to populate parameters of ordinary model elements and can be created with the static ViewSchedule CreateKeySchedule method whose second parameter is the ID of the category of elements with which the schedule s keys will be associated A material takeoff is a schedule that displays information about the materials that make up elements in the model Unlike regular schedules where each row before grouping represents a single element each row in a material takeoff represents a single lt element material gt pair The ViewSchedule CreateMaterialTakeoff method has the same parameters as the ViewSchedule CreateSchedule me
484. pecific operation on a specific element For example you can get or change an element s parameter value Complete the following steps to get a parameter value 1 Create a new project and add the references as summarized in the previous walkthroughs 2 Use the UlApplication ActiveUlDocument Selection Elements property to retrieve the selected object The selected object is a Revit SelElementSet Use the IEnumerator interface or foreach loop to search the ElementSet The following code is an example of how to retrieve selected elements Code Region 2 7 Retrieving selected elements Autodesk Revit Attributes Transaction TransactionMode ReadOnly public class Document selection IExternalCommand public Autodesk Revit Ul Result Execute ExternalCommandData commandData ref string message ElementSet elements Lacy Select some elements in Revit before invoking this command Get the handle of current document UrIDecumente uidoe commandData Application AckiveulDocumentr Get the element selection of current document peleci Iion c eleccion Uidoe selecruaon Element o ecek coe como cueotbum omnei ewemim s ie 0 collect von 5ze If no elements selected TaskDialog Show Revit You haven t selected any elements else String info Ids of selected elements in the document are foreach Element elem in collection jo mm ot neem ida mite ale Masas now Rew ihe o j j C
485. perty in the Application object New cities cannot be added to the existing list in Revit The city where the current project is located is not exposed by the Revit Platform API ProjectLocation A project only has one site which is the absolute location on the earth However it can have different locations relative to the projects around it Depending on the coordinates and origins in use there can be many ProjectLocation objects in one project By default each Revit project contains at least one named location Internal It is the active project location You can retrieve it using the Document ActiveProjectLocation property All existing ProjectLocation objects are retrieved using the Document ProjectLocations property Project Position Project position is an object that represents a geographical offset and rotation It is usually used by the ProjectLocation object to get and set geographical information The following figure shows the results after changing the ProjectLocation geographical rotation and the coordinates for the same point However you cannot see the result of changing the ProjectLocation geographical offset directly Specify Shared Coordinates Relocate this project in Shared Coordinates by specifying KW vales ar PAE pant wai selerted Current prajert will nove celalive Lu globally pusibiuried links New Coordnakes 30 10 53 84 LaskiWesk Mur if Saut i is 611 52
486. phical representation of the model including the three classes that describe and store the geometry information Place and Locations Defines the project location including city country latitude and longitude Shared Parameters Shared parameters are external text files containing parameter specifications This chapter introduces how to access to shared parameters through the Revit Platform API Transaction Introduces the two uses for Transaction and the limits that you must consider when using Transaction Events Discusses how to take advantage of Revit Events Dynamic Model Update Learn how to use updaters to modify the model in reaction to changes in the document Failure Posting and Handling Learn how to post failures and interact with Revit s failure handling mechanism Analysis Visualization How to display analysis results in a Revit project Product Specific Revit products include Revit Architecture Revit Structure and Revit MEP Some APIs only work in specific products Revit Architecture Discusses the APIs specific to Revit Architecture Revit Structure Discusses the APIs specific to Revit Structure Revit MEP Discusses the APIs specific to Revit MEP Glossary Definitions of terms used in this document Appendix Additional information such as Frequently Asked Questions Using Visual Basic Net for programming and more Documentation Conventions This document contains class names in namespace format su
487. pically extracted from the indexed property Element Geometry The original geometry of a beam column or brace before the instance is modified by joins cuts coping extensions or other post processing can be extracted using the FamilyInstance GetOriginalGeometry method Both Element Geometry and FamilyInstance GetOriginalGeometry accept an options class which you must supply The options class customizes the type of output you receive based on its properties e ComputeReferences Indicates whether to compute the geometry reference when retrieving geometry information The default value is false so if this property is not set to true the reference will not be accessible e IncludeNonVisibleObjects Indicates to also return geometry objects which are not visible in a default view e View Gets geometry information from a specific view Note that if a view is assigned the detail level for this view will be used in place of DetailLevel e Detaillevel Indicates the preferred detail level The default is Medium ComputeReferences If you set this property to false the API does not compute a geometry reference All Reference properties retrieved from the geometry tree return nothing For more details about references refer to the Reference section This option cannot be set to true when used with FamilyInstance GetOriginalGeometry I ncludeNonVisibleObjects Most of the non visible geometry is construction and conditional geometry that t
488. pitalization Code Region 30 9 Hello World in VB NET Moss e N Imports Autodesk Revit UI Imports Autodesk Revit DB lt Autodesk Revit Attributes Transaction Autodesk Revit Attributes TransactionMode Automatic gt Pub lic lacs Class Implements IExternalCommand Public Function Execute ByVal revit As ExternalCommandData ByRef message As String ByVal elements As ElementSet As Autodesk Revit UI Result _ Implements IExternalCommand Execute iaskDiaalegqsonow evt Hello World Return Autodesk Revit UI Result Succeeded yo ane talon End Class Create a addin manifest file The HelloWorld dll file appears in the project output directory If you want to invoke the application in Revit create a manifest file to register it into Revit 1 Tocreate a manifest file create a new text file in Notepad 2 Add the following text Code Region 30 10 Creating a addin manifest file for an external command reis Ole IO ne Ocio BTE TES 9 sSirbaicalenma me a gt lt RevitAddiIns gt lt Addin Type Command gt lt Assemoly D Semple Hel lowor la oin Debug Helloworla cil Assembly gt lt Molc ba Ce 2 6 SIBI 5 5 5 md a6 Jefe 9 Ly LC SNC DAs LE zoll IE QOL lt FullClassName gt Class1 lt FullClassName gt exe le Loiola hex Vendor ASK Vendo lt VendorDescription gt Autodesk www autodesk com lt VendorDescription gt eere messem eo 1 Save the file as HelloWorld addin and put it in the following location e
489. place them with one generic failure using the ReplaceFailures method FailuresPreprocessor The IFailuresPreprocessor interface can be used to provide custom failure handling for a specific transaction only IFailuresPreprocessor is an interface that may be used to perform a preprocessing step to either filter out anticipated transaction failures or to post new failures Failures can be filtered out by e silently removing warnings that are known to be posted for the transaction and are deemed as irrelevant for the user in the context of a particular transaction e silently resolving certain failures that are known to be posted for the transaction and that should always be resolved in a context of a given transaction e silently aborting the transaction in cases where imperfect transactions should not be committed or aborting the transaction is preferable over user interaction for a given workflow The IFailuresPreprocessor interface gets control first during the failure resolution process It is nearly equivalent to checking and resolving failures before finishing a transaction except that IFailuresPreprocessor gets control at the right time after all failures guaranteed to be posted and or after all irrelevant ones are deleted There may be only one IFailuresPreprocessor per transaction and there is no default failure preprocessor If one is not attached to the transaction via the failure handling options this first step of failure resolut
490. ple components that conform to user defined constraints The following code shows how to create an instance of an adaptive component family into a massing family and align the adaptive points in the instance with points in the massing family Code Region Creating an Instance of an Adaptive Component Family in VIEW plall ICODy tO clip DOaraprints 15 16 17 18 19 20 2L 229 235 24 25 26 27 28 find the first placement point that will host the adaptive component IEnumerable lt ReferencePoint gt points from obj in new FilteredElementCollector doc OfClass typeof ReferencePoint Cast ReferencePoint let type obj as ReferencePoint where type Name PlacementPointO these names were manually assigned to the points select obj ReferencePoint placementPointO points0 First find the 2nd placement point that will host the adaptive component IEnumerable ReferencePoint points1 from obj in new FilteredElementCollector doc OfClass typeof ReferencePoint Cast ReferencePoint let type obj as ReferencePoint where type Name PlacementPoint1 select obj ReferencePoint placementPoint1 points1 First if AdaptiveComponentInstanceUtils IsAdaptiveFamilySymbol symbol create an instance of the adaptive component FamilyInstance familyInstance AdaptiveComponentInstanceUtils CreateAdaptiveComponentInstance doc symbol find the adaptive points in the family instance IList
491. plication OpenSharedParameterFile Method This method returns an object representing a Revit shared parameter file o Revit uses one shared parameter file at a time o The file name for the shared parameter file is set in the Revit Application Options object If the file does not exist an exception is thrown Create a Shared Parameter File Because the shared parameter file is a text file you can create it using code or create it manually Code Region 22 3 Creating a shared parameter file private void CreateExternalSharedParamFile string sharedParameterFile System IO FileStream fileStream System IO File Create sharedParameterFile filestream C lose Access an Existing Shared Parameter File Because you can have many shared parameter files for Revit it is necessary to specifically identify the file and external parameters you want to access The following two procedures illustrate how to access an existing shared parameter file Get DefinitionFile from an External Parameter File Set the shared parameter file path to app Options SharedParametersFilename as the following code illustrates then invoke the Autodesk Revit Application OpenSharedParameterFile method Code Region 22 4 Getting the definition file from an external parameter file private DefinitionFile SetAndOpenExternalSharedParamFile Autodesk Revit ApplicationServices Application application string sharedParameterFile set the path of shared paramete
492. png This provides more detailed information and gives the user more insight into the feature Poor Example Insert Picture from File Insert a picture from a file Press F1 for more help In this example the tooltip content repeats the tooltip title verbatim and does not add value to the tooltip Additionally if the translator cannot identify whether this string is a name title or a descriptive sentence it will be difficult for them to decide on the translation style As with other guideline issues follow Microsoft Guidelines for title and sentence case listed below Title Case e Capitalize all nouns verbs including is and other forms of to be adverbs including than and when adjectives including this and that and pronouns including its e Capitalize the first and last words regardless of their parts of speech for example The Text to Look For e Capitalize prepositions that are part of a verb phrase for example Backing Up Your Disk e Do not capitalize articles a an the unless the article is the first word in the title e Do not capitalize coordinate conjunctions and but for nor or unless the conjunction is the first word in the title e Do not capitalize prepositions of four or fewer letters unless the preposition is the first word in the title e Do not capitalize to in an infinitive phrase for example How to Format Your Hard Disk unless the phrase is the first word in the title e Capitalize
493. points may not be returned Although you must deal with pointers directly in the second option there may be performance improvements when traversing large buffers of points However this option is only possible from CH and C CLI The following two examples show how to iterate part of a point cloud using on one of these two methods Code Region Reading point cloud points by iteration view plaincopy to clipboardprint 1 private void GetPointCloudDataByIteration PointCloudInstance pcInstance PointCloudFilter pointCloudFilter 2E 34 read points by iteration 4 Get points Number of points is determined by the needs of the client 5 PointCollection points pcInstance GetPoints pointCloudFilter 10000 6 foreach CloudPoint point in points 7 8 Process each point 9 System Drawing Color color System Drawing ColorTranslator FromWin32 point Color 10 String pointDescription String Format 0 1 2 3 11 point X point Y point Z color ToString 12 13 Code Region Reading point cloud points by pointer Ini nih VIEW ola INCOPY to cli pboaraprintt 1 public unsafe void GetPointCloudDataByPointer PointCloudInstance pcInstance PointCloudFilter pointCloudFilter DUE 3 PointCollection points pcInstance GetPoints pointCloudFilter 10000 AL CloudPoint pointBuffer CloudPoint points GetPointBufferPointer ToPointer 5 int totalCount points Count 6 for int numberOfPoints
494. ported from disk Use the static ImageView Create method to create new rendering views B 2D 12 1 0 BO East North South Renderings Schedules Quantities Sheets all 3 9 Families 3 8 Groups amp Revit Links ViewSection The ViewSection class can be used to create section views detail views callout views reference callouts and reference sections It also represents elevation views Section Views and Reference Sections Section views cut through the model to expose the interior structure The ViewSection CreateSection method creates the section view Code Region ViewSection CreateSection view plaincopy to clipboardprint i public ViewSection ViewSection CreateSection Document document ElementId viewFamilyTypeId BoundingBoxXYZ sectionBox The viewFamilyTypeld parameter is the Id for the ViewFamilyType which will be used by the new ViewSection The type needs to be a Section ViewFamily The sectionBox parameter is the section view crop box It provides the direction and extents which are required for the section view Usually another view s crop box is used as the parameter You can also build a custom BoundingBoxXYZ instance to represent the direction and extents The following code shows how to create a section view A bounding box for the section view is created at the center of a wall The resulting section view will be located in the Sections Building Section node in the Project Brow
495. present some types of imported geometry data The data for the NurbSpline include e The control points array of length n 1 e The weights array also of length n 1 e The curve degree whose value is equal to one less than the curve order k e The knot vector of length n k 1 P u Zizo PiwiNi klu 0zuz ER wii glu H max NurbSplines as used in Revit s sketching tools can be generated from the control points and degree alone using an algorithm The calculations performed by Revit s algorithm can be duplicated externally see this sample below view plaincopy to clipboardprint NurbSplinespline curve GeometryCurve as NurbSpline DoubleArrayknots spline Knots List double knotList new List lt double gt for int i 0 i knots Size i 9 10 11 Preparation get distance between each control point 12 IList lt XYZ gt controlPoints spline CtrlPoints 13 int numControlPoints controlPoints Count 14 double chordLengths new double numControlPoints 1 15 for int iControlPoint 1 iControlPoint numControlPoints iControlPoint 1 2 34 4 Convert to generic collection 5 6 7 8 knotList Add knots get_Item i 16 275 double chordLength 18 controlPoints iControlPoint DistanceTo controlPoints iControlPoint 1 19 chordLengths iControlPoint 1 chordLength 20 21 22 int degree spline Degree 23 int order degree 1 24 int numKnots num
496. previous example create a reference point in the middle of the CurveByPoints Forms can be created using model lines or reference lines Model lines are consumed by the form during creation and no longer exist as separate entities Reference lines on the other hand persist after the form is created and can alter the form if they are moved Although the API does not have a ReferenceLine class you can change a model line to a reference line using the ModelCurve ChangeToReferenceLine method Code Region 14 2 Using Reference Lines to create Form view plaincopy to clipboardprint private FormArray CreateRevolveForm Document document 1 2 3 4 Da 6 7 8 9 i 10 11 12 13 14 15 16 17 18 I9 20 21 22 23 24 25 20 274 28 29 30 31 32 EEN 34 3D 365 37 38 j 39 public ModelCurve MakeLine Document doc XYZ ptA XYZ ptB 40 41 42 43 44 45 46 47 48 49 50 51 527 FormArray revolveForms null Create one profile ReferenceArray ref ar new ReferenceArray XYZ ptA new XYZ 0 0 10 XYZ ptB new XYZ 100 0 10 Line line document Application Create NewLine ptA ptB true ModelCurve modelcurve MakeLine document Application ptA ptB ref ar Append modelcurve GeometryCurve Reference ptA new XYZ 100 0 10 ptB new XYZ 100 100 10 modelcurve MakeLine document ptA ptB ref ar Append modelcurve GeometryCurve Refe
497. print 1 public Autodesk Revit UI Result Execute ExternalCommandData commandData ps ref string message ElementSet elements 3 4 4 try 5 6 Document doc commandData Application ActiveUIDocument Document Ta UIDocument uidoc commandData Application ActiveUIDocument 8 Delete selected elements 9 ICollection Autodesk Revit DB ElementId ids 10 doc Delete uidoc Selection GetElementIds 114 12 TaskDialog taskDialog new TaskDialog Revit 134 taskDialog MainContent 14 Click Yes to return Succeeded Selected members will be deleted n 15 Click No to return Failed Selected members will not be deleted n 16 Click Cancel to return Cancelled Selected members will not be deleted 17 TaskDialogCommonButtons buttons TaskDialogCommonButtons Yes 18 TaskDialogCommonButtons No TaskDialogCommonButtons Cancel 19 taskDialog CommonButtons buttons 20 TaskDialogResult taskDialogResult taskDialog Show 21 22 if taskDialogResult TaskDialogResult Yes 23 PAN return Autodesk Revit Ul Result Succeeded 25 26 else if taskDialogResult TaskDialogResult No 245 28 elements uidoc Selection Elements 29 message Failed to delete selection 30 return Autodesk Revit UI Result Failed 31 325 else 33 34 return Autodesk Revit UI Result Cancelled 35 36 375 catch 38 39 message Unexpected Exception thrown 40 return Autodesk
498. property The Element AllowPhases method indicates whether its phase ID properties can be modified The Created Phase ID property has the following characteristics e tidentifies the phase in which the component was added e The default value is the same ID as the current view Phase value e Change the Created Phase ID parameter by selecting a new value corresponding to the drop down list The Demolished Phase ID property has the following characteristics e tidentifies in which phase the component is demolished e The default value is none e Demolishing a component with the demolition tool updates the property to the current Phase ID value in the view where you demolished the element e You can demolish a component by setting the Demolished Phase ID property to a different value e If you delete a phase using the Revit Platform API all modeling components in the current phase still exist The Created Phase ID parameter value for these components is changed to the next item in the drop down list in the Properties dialog box Phase Created PhaseDemolsFed Figure 65 Phase created component parameter value The following code sample displays all supported phases in the current document The phase names are displayed in a message box Code Region 15 6 Displaying all supported phases view plaincopy to clipboardprint 1 void Getinfo Phase Document doc 2f 3 Get the phase array which contains all the phases 4 PhaseArr
499. property can have the following values e AnalyticalRigidLinksOption Enabled Rigid links will be formed unless corresponding structural beam s setting overrides e AnalyticalRigidLinksOption Disabled Rigid links will not be formed unless corresponding structural beam s setting overrides Note that in addition to the correct values being set the elements must also overlap for the rigid link to be created Figure 159 RigidLink Analytical Projection The horizontal and vertical projection parameters for an AnalyticalModel can be retrieved and set using the GetAnalyticalProjectionType and SetAnalyticalProjectionType methods These methods take an AnalyticalDirection as an input The SetAnalyticalProjectionDatumPlane can also be used to set the specified projection to a specific Datum Plane and GetAnalyticalProjectionDatumPlane will retrieve the analytical projection when set to a Datum Plane Approximation When an AnalyticalModel is defined by a curve rather than a straight line i e for a curved beam an approximation comprised of straight lines may be preferable AnalyticalModel has several methods related to curve approximation If CanApproximate returns true use the Approximate method to switch between non approximated curved Analytical Models and approximated made up of lines only Analytical Models After switching to approximated use GetCurves to get the lines of the approximated curve The approximation wil
500. ption controls Use standard Format 1 Use compressed raster Format mea s F Create separate files for each view sheet C oox Lance Commit buttons Figure 205 The Export 2D DWF Options dialog Property Editor Use when an item s properties need to be modified by the user To create a property editor provide a Table View that presents a name property pair The property field can be modified by a Text Box Check Box Command Button Drop Down List or even a slider Fiver Fme JA de Grouping 2 Controls 3 Button cancel _Apply c O Figure 206 Property Grid Supported Behaviors ID Behavior Description Required 1 Filter Filters the list of properties based on specified criteria No 2 Grouping Grouping the properties makes them easier to scan No 3 Controls Edit properties of an item Each value cell can contain a control that can be edited or disabled depending on the context Yes 4 Commit Buttons Optional only use if within a modal dialog No Content Editor If multiple action controls interoperate with the same content control such as a list box vertically stack them to the right of and top aligned with the content control or horizontally place them left aligned under the content control This layout decision is at the developer s discretion Button Button Button Label OK Cancel Figure 207 Action controls to the right of conten
501. pulates these properties Code Region 23 3 Transaction populating Geometry and AnalyticalModel properties public void TransactionDuringElementCreation UlApplication uiApplication Level level Autodesk Revit DB Document document uiApplication ActiveUIDocument Document Build a location line for the wall creation AYA Start new XY21 0 0 0 5 TA end new MOLA I 10 0 Autodesk Revit DB Line geomLine uiApplication Application Create NewLineBound start end To create a wall a transaction must be first started Mans cr Lon welliranscackion Hew dites tal exe ede ron accent Creacime wall tt wallilransection cstark Trasmsaetrlonstetusestdab5ted Create a wall using the location line Wall wall Wall Create document geomLine level Id true the transaction must be committed before you can get the value of Geometry and AnalyticalModel ion wa TELE TS s nosse oca tons tal tc COM ic ECOL Autodesk Revit DB Options options uiApplication Application Create NewGeometryOptions Autodesk Revit DB GeometryElement geoelem wall get_Geometry options AnalyticalModel analyticalmodel wall GetAnalyticalModel The transaction timeline for this sample is as follows CreateWall get Geometry AnalyticalModel UnTransacted You can get those properties only after using transaction Transaction Figure 134 Transaction timeline Temporary transactions It is n
502. py to clipboardprint 1 public void PickPoint UIDocument uidoc 2R 3 4 ObjectSnapTypes snapTypes ObjectSnapTypes Endpoints ObjectSnapTypes Intersections 5 XYZ point uidoc Selection PickPoint snapTypes Select an end point or intersection 6 7 string strCoords Selected point is point ToString 8 9 TaskDialog Show Revit strCoords 10 The PickBox method takes a PickBoxStyle enumerator The options are Crossing the style used when selecting objects completely or partially inside the box Enclosing the style used selecting objects that are completely enclosed by the box and Directional in which the style of the box depends on the direction in which the box is being drawn It uses the Crossing style if it is being drawn from right to left or the Enclosing style when drawn in the opposite direction PickBox returns a PickedBox which contains the Min and Max points selected The following example demonstrates the use of PickBox in Point Cloud selection Code Region PickBox view plaincopy to clipboardprint 1 public void PromptForPointCloudSelection UIDocument uiDoc PointCloudInstance pcInstance 2 35 Application app uiDoc Application Application 4 Selection currentSel uiDoc Selection Ds 6 PickedBox pickedBox currentSel PickBox PickBoxStyle Enclosing Select region of cloud for highlighting 7 8 XYZ min pickedBox Min 9 XYZ max pickedBox Max 10 1l Transform p
503. que Identifier which is unique across separate Revit projects Uniqueld can help you to track elements when you export Revit project files to other formats Code Region 5 5 Uniqueld String uniqueId element Uniqueld NoteThe Elementld is only unique in the current project It is not unique across separate Revit projects Uniqueld is always unique across separate projects The location of an object is important in the building modeling process In Revit some objects have a point location For example a table has a point location Other objects have a line location representing a location curve or no location at all A wall is an element that has a line location The Revit Platform API provides the Location class and location functionality for most elements For example it has the Move and Rotate methods to translate and rotate the elements However the Location class has no property from which you can get information such as a coordinate In this situation downcast the Location object to its subclass like LocationPoint or LocationCurve for more detailed location information and control using object derivatives Retrieving an element s physical location in a project is useful when you get the geometry of an object The following rules apply when you retrieve a location e Wall Beam and Brace are curve driven using LocationCurve e Room RoomTag SpotDimension Group Familyl nstances that are not curve driven and all In Place Familyl ns
504. r Offseting faces of a selected Part External Events The Revit API provides an External Events framework to accommodate the use of modeless dialogs It is tailored for asynchronous processing and operates similarly to the Idling event with default frequency To implement a modeless dialog using the External Events framework follow these steps 1 Implement an external event handler by deriving from the IExternalEventHandler interface 2 Create an ExternalEvent using the static ExternalEvent Create method 3 When an event occurs in the modeless dialog where a Revit action needs to be taken call ExternalEvent Raise 4 Revit will call the implementation of the IExternalEventHandler Execute method when there is an available Idling time cycle IExternalEventHandler This is the interface to be implemented for an external event An instance of a class implementing this interface is registered with Revit and every time the corresponding external event is raised the Execute method of this interface is invoked The IExternalEventHandler has only two methods to implement the Execute method and GetName which should return the name of the event Below is a basic implementation which will display a TaskDialog when the event is raised Code Region Implementing IExternalEventHandler view plaincopy to clipboardprint 1 public class ExternalEventExample IExternalEventHandler 2 35 public void Execute UIApplication app 4 5 Tas
505. r file to current Revit application Options SharedParametersFilename sharedParameterFile Oy cnc return application OpenSharedParameterFile Note Consider the following points when you set the shared parameter path e During each installation Revit cannot detect whether the shared parameter file was set in other versions You must bind the shared parameter file for the new Revit installation again e If Options SharedParametersFilename is set to a wrong path an exception is thrown only when OpenSharedParameterFile is called e Revit can work with multiple shared parameter files Even though only one parameter file is used when loading a parameter the current file can be changed freely Traverse All Parameter Entries The following sample illustrates how to traverse the parameter entries and display the results in a message box Code Region 22 5 Traversing parameter entries private void ShowDefinitionFileInfo DefinitionFile myDefinitionFile sica lso Ss ral TE SUITE TS EIL IOTER ET mine bI redet SOO get the file name fileInformation AppendLine File Name myDefinitionFile Filename ie tae ae Delta Gud Clowes Ci elas Ele toe maps SNO CUT mM ECroup Tn my Dorin ten Mle Groups get the group name fileInformation AppendLine Group Name myGroup Name ff iterate Cae Ob dX 1 omn LopeschsDesarnicuoemsdetcmis onmi oupbesi nd ons Gee Cetisition meme fileInformation AppendLine Definition Nam
506. r in different versions of the file After the user reloads the latest or saves to central the modified target element will be brought from the other file and the updater will need to reconcile changes It is also important to realize that when a document synchs with the central file the Elementld of elements may be affected If new elements have been added to two versions of the same file and the same Elementld is used in both places this will be reconciled when the files are synched to the central database For this reason when using updaters to cross reference one element in another element they should use Element Uniqueld which is guaranteed to be unique Another issue to consider is if an updater attaches some data i e as a parameter to an element it not only must be sure to maintain that information in the element to which it was added but also to reconcile data in cases when that element is duplicated via copy paste or group propagation For example if an updater adds a parameter Total weight of rebar to a rebar host that parameter and its value will be copied to the duplicated rebar host even though the rebar itself may be not copied with the host In this case the updater needs to ensure the parameter value is reset in the newly copied rebar host Registering Updaters Updaters must be registered in order to be notified of changes to the model The application level UpdaterRegistry class provides the ability to register unregister and
507. r type parameter of elements appearing in the schedule Some fields represent parameters of other related elements like the room to which a scheduled element belongs Fields can also represent data calculated from other fields in the schedule specifically Formula and Percentage fields The ScheduleField class has properties to control column headings both the text as well as the orientation Column width and horizontal alignment of text within a column can also be defined The ScheduleField IsHidden property can be used to hide a field A hidden field is not displayed in the schedule but it can be used for filtering sorting grouping and conditional formatting and can be referenced by Formula and Percentage fields Some ScheduleFields can be totaled and if the HasTotals property is set to true totals will be displayed if a footer row is enabled where the totals will be displayed It can either be a grand total row at the end of the schedule or a footer row for one of the schedule s grouped fields In a non itemized schedule totals are also displayed in regular rows when multiple elements appear on the same row Grouping and Sorting Fields A schedule may be sorted or grouped by one or more of the schedule s fields Several methods can be used to control grouping and sorting of fields The ScheduleSortGroupField class represents one of the fields that the schedule is sorted or grouped by Sorting and grouping are related operations In either case el
508. rType Text ESOS Sc etd insert estero wo CN CategorySet myCategories app Application Create NewCategorySet ise Bumlrinm akeqony to der category OF wall Category myCategory app ActiveUIDocument Document Settings Categories get Item BOIE Win ee orn Os Medi myCategories Insert myCategory Create an instance of InstanceBinding InstanceBinding instanceBinding app Application Create NewInstanceBinding myCategories Get the BingdingMap of current document BindingMap bindingMap app ActiveUIDocument Document ParameterBindings 77 ea ila Peinados Lo ela creeuiimeiae bool instanceBindOK bindingMap Insert myDefinition_ProductDate Imskancebancding EUIS IEEE cS Smet ei Group nEXI jy cuoummeunmnsctomeesumcdoN Extensible Storage The Revit API allows you to create your own class like Schema data structures and attach instances of them to any Element in a Revit model Schema based data is saved with the Revit model and allows for higher level metadata enhanced object oriented data structures Schema data can be configured to be readable and or writable to all users just a specific application vendor or just a specific application from a vendor The following steps are necessary to store data with Elements in Revit 1 Create and name a new schema Set the read write access for the schema Define one or more fields of data for the schema Create an entity based on the schema Assign values to the field
509. races Brace Columns Column Footings Footing Create Tables The following function demonstrates how to load a family of Tables into a Revit project and create instances from all symbols in this family The LoadFamily method returns false if the specified family was previously loaded Therefore in the following case do not load the family Table Dining Round w Chairs rfa before this function is called In this example the tables are created at Level 1 by default Code Region 12 3 Creating tables String fileName C Documents and Settings All Users Application Data Autodesk RST 2011 Imperial Library Furniture Table Di Aa eaae a fi deu ie Leech Tem Ly Family family null ie document sloadmemily ri leName outs aima throw new Exception Unable to load fileName j Loop through table symbols and add a new table for each Family mbolo crt iteratror se ces coru Sr mao ls Forwardit toT double sx 0207 ccs while symbolltor MoveNext Fanilysymbo e symool symbol current as E Hei STD A eme ac ZEE ED Do not use the overloaded NewFamilyInstance method that contains the Level argument otherwise Revit cannot show the instances e xexcasterene a 59 AE deer e Egi E Sob as ao level oe cl XH OX DUE FamilyInstance instance document Create NewFamilyInstance location symbol StructuralType NonStructural Figure 47 Load family and create tables in the Revit project In this sample a family sy
510. rames etc as large as possible to allow for longer translated text These frames should be at least 30 larger than the English text Refer to the User Interface Text Guidelines for Microsoft Windows User Experience Guidelines for additional information regarding localizing text Dialog Guidelines A dialog is a separate controllable area of the application that contains information and or controls for editing information Dialogs are the primary vehicle for obtaining input from and presenting information to the user Use the following guidelines when deciding which dialog to use Dialog Type Definition Use When Modal Halts the rest of the application and waits for user input Task s in the dialog are infrequent It is acceptable to halt the system while the user enters data Modeless User can switch between the dialog and the rest of the application without closing the Task s in the dialog are frequent dialog Halting the system would interrupt the user workflow Behavior Rules e Adialog can either be user initiated prompted by clicking a control or system initiated a warning triggered by a system event e The initial dialog location typically should be centered on the screen but this rule may vary based on variation or on a particular context of use but should have an immediate focus e Dialogs should be resizable when the content is dynamic please see Dynamic Layout section for more on this topic Dialog Controls Control Use When Exa
511. rametric equation for this surface is P u v C4 u v Cz u Ey u if both curves are valid If one of the curves is replaced with a point the equations simplify to one of P u v Py v C5 u P4 P u v C u v P Cy u A ruled face with no curves and two points is degenerate and will not be returned HermiteFace A cubic Hermite spline face The Revit API provides e Arrays of the u and v parameters for the spline interpolation points e An array of the 3D points at each node the array is organized in increasing u then increasing v e An array of the tangent vectors at each node e Anarray of the twist vectors at each node The parametric representation of this surface between nodes u1 v1 and u2 v2 is Plu v U Mp B M V O la342441T XP e3 4242417 Where U u u u 1 V v v vi My is the Hermite matrix 2 e 1 1 s 3 x IMi log 10 10 00 And B is coefficient matrix obtained from the face properties at the interpolation points Pt a P ofur Puss Prous P ous P o ugvs B Puta Puw Puruwa Purina P alura P ust P us uzv P uv ugea Solid and face creation Solids and faces are sometimes used as inputs to other utilities The Revit API provides several routines which can be used to create such geometry from scratch or to derive it from other inputs Transformed geometry The method e GeometryElement GetTransformed returns a copy of the input geo
512. ration such as the maximum height of each riser on the stair element The following example gets the StairsType for a Stairs element and displays some information about it in a TaskDialog Code Region Getting StairsType I nfo AH E R E A S E EA ia DialncCcODV TO CIIDDOarabprint i I J l 1 private void GetStairsType Stairs stairs 2t 3 StairsType stairsType stairs Document GetElement stairs GetTypeld as StairsType 4 5 Format stairs type info for display De string info Stairs Type stairsType Name 7 info nLeft Lateral Offset stairsType LeftLateralOffset 8 info nRight Lateral Offset stairsType RightLateralOffset 9 info nMax Riser Height stairsType MaxRiserHeight 10 info nMin Run Width stairsType MinRunWidth 11 T27 TaskDialog Show Revit info 13 Runs Stairs by component are composed of runs landings and supports Each of these items can be retrieved from the Stairs class A run is represented in the Revit API by the StairsRun class The following example gets each run for a Stairs object and makes sure that it begins and ends with a riser Code Region Working with StairsRun ew PDlaINCODPY to CIID 1 private void AddStartandEndRisers Stairs stairs 2 3 ICollection lt ElementId gt runIds stairs GetStairsRuns 4 5 foreach ElementId runId in runlds 6 7 StairsRun run stairs Document GetElement runlId as StairsRun 8 if null run
513. rations e Use simple sentences The Verb Object Adverb format is recommended e Use strong and specific verbs that describe a specific action such as tile rather than weak verbs such as use to e Write in the active voice for example Moves objects between model space and paper space e Use the descriptive style instead of the imperative style Opens an existing drawing file vs Open an existing drawing file e Make the tooltip description easily recognizable by using the third person singular for example Specifies the current color instead of Specify the current color e Don t use slang jargon or hard to understand acronyms Formatting Considerations e Use only one space between sentences e Avoid repetitive text The content in the tooltip should be unique and add value e Focus on the quality and understandability of the tooltip Is the description clear Is it helpful e Unless it s a system variable or command do not use bold Although bold is supported in Asian languages it is strongly recommended to avoid using bold and italics because of readability and stylistic issues e Avoid Dabbreviations For example the word Number has many common abbreviations No Nbr Num Numb It is best to spell out terms Good Example Insert Picture from File Adds a file such as a bmp or jpg Press F1 for more help An example of a more useful descriptive sentence might be Adds a file such as a bmp or
514. re Posting and Handling Ul Application This class represents an active session of the Autodesk Revit user interface providing access to Ul customization methods events and the active document Document Management The UlApplication provides access to the active document using the UlActiveDocument property Additionally a Revit document may be opened using the overloaded OpenAndActivateDocument method The document will be opened with the default view active This method may not be called inside a transaction and may only be invoked during an event when no active document is open yet in Revit and the event is not nested inside another event Add in Management The ActiveAddinld property gets the current active external application or external command id while the LoadedApplications property returns an array of successfully loaded external applications Ribbon Panel Utility Use the UlApplication object to add new ribbon panels and controls to Revit For more details see Ribbon Panel and Controls in the Add In Integration section Extents The DrawingAreaExtents property returns a rectangle that represents the screen pixel coordinates of drawing area while the MainWindowExtents property returns the rectangle that represents the screen pixel coordinates of the Revit main window Events The UlApplication class exposes UI related events such as when a dialog box is displayed Subscribing to these events notifies the application when the
515. re processing mechanism to resolve failures automatically when applicable The Revit UI only uses the default resolution but Revit add ins via the Revit API can use any applicable resolution and can provide an alternative UI for doing that as described in the Handling Failures section later in this chapter In the case of a failure with a severity of DocumentCorruption by the time failure resolution could occur the transaction is already aborted so there is nothing to resolve Therefore FailureResolutions should not be added to API defined Failures of severity DocumentCorruption Posting a failure The Document PostFailure method is used to notify the document of a problem Failures will be validated and possibly resolved at the end of the transaction Warnings posted via this method will not be stored in the document after they are resolved Failure posting is used to address a state of the document which may change before the end of the transaction or when it makes sense to defer resolution until the end of the transaction Not all failures encountered by an external command should post a failure If the failure is unrelated to the document a task dialog should be used For example if the Revit Ul is in an invalid state to perform the external command To post a failure create a new FailureMessage using the FailureDefinitionld from when the custom failure was defined or use a BuiltInFailure provided by the Revit API Set any additional infor
516. reate a push button in the ribbon panel NewRibbonPanel Ems eerie eeolieaicied Mad Treue do wail Ise cice erecl masa lolicon dise pushed Eure wieso wet wie one ribbon anel Adelreen new psi He llower iad Malo Majes SIDES e Ta Ecos etel d oce MTS TET se o or he ess IP SET e UR EE OX OLG Set the large image shown on button Uri urilmage new Uri D Sample HellowWorld bin Debug 39 Globe_32x32 png BitmapImage largeImage new BitmapImage urilmage pushButton Largelmage largeImage returni Resto mece esceas Slots woo M hemo mo mule clone WRC Om Erol TE SOUS Ore stie ene ab onm Suejedbabreren cab Or Bpeuturmmebesuliueeuseececec Build the Application After completing the code build the application From the Build menu click Build Solution Output from the build appears in the Output window indicating that the project compiled without errors AddPanel dll is located in the project output directory Create the addin manifest file To invoke the application in Revit create a manifest file to register it into Revit 1 Create a new text file using Notepad 2 Add the following text to the file Code Region 2 6 Creating a addin file for an external application lt xml version Y1 0 eneoding UEi s Stamdelone mo gt lt RevitAddiIns gt lt Addin Type Application gt lt Name gt SampleApplication lt Name gt lt Assembly gt D Sample AddPanel AddPanel bin Debug AddPanel dll l
517. refer to Shared Parameter Collections Most Revit Platform API properties and methods use NET Framework collection classes when providing access to a group of related items The IEnumerable and IEnumerator interfaces implemented in Revit collection types are defined in the System Collection namespace Topics tn this section e Interface e Collections and Iterators Interface The following sections discuss interface related collection types IEnumerable The IEnumerable interface is in the System Collections namespace It exposes the enumerator which supports a simple iteration over a non generic collection The GetEnumerator method gets an enumerator that implements this interface The returned IEnumerator object is iterated throughout the collection The GetEnumerator method is used implicitly by foreach loops in CH The IEnumerator interface is in the System Collections namespace It supports a simple iteration over a non generic collection IEnumerator is the base interface for all non generic enumerators The foreach statement in CH hides the enumerator s complexity NoteUsing foreach is recommended instead of directly manipulating the enumerator Enumerators are used to read the collection data but they cannot be used to modify the underlying collection Use IEnumerator as follows e Initially the enumerator is positioned in front of the first element in the collection However it is a good idea to always call Reset whe
518. reference and close the dialog box 6 Repeat steps above to add a reference to RevitAPIUI dll which is in the same folder as Revit API dll e VBHelloWorld Microsoft Visual Studio Administrator 00 h Eta x File Edt View Project Build Debug Team Data Tools VMware Test Window Help Palm ed ug x u o ew E E bines ayeu Move ARA x Classl wb Solution Explorer l x 35 5314 33 L VBHellaWc Application m Solution VBHelloWo d 1 project Configuration N A Platform N A i Ea VBHelloWorld Compile Sa My Project e du Reference Name Type Version Copy Local Path 2012 0 0 0 False C Program Files Autodesk Revit Structu 20120 0 0 False CAProgram Files Autodesk Revit Structu Resources RevitAPIUI Sene System J C Program Files 086 Reference Assert uo System Core NET 4 0 0 0 False C Program Files x86 Reference Assert Settings System Data MFT 400 0 Falee C Program Files RON Reference Accert System Data DataSetExtensions MET 4 0 0 0 False CAProgram Files x66 Reference Assemt Signing System Xml MET 4 0 0 0 False C Program Files x86 Reference Assert System Xml Linq MET 4 0 0 0 False C Program Files x86 Reference Assert My Extensions el Solution Explorer LME Properties yi x RevitAPI Reference Properties sid Update ME Imported namespaces Name bs Microsoft VisualBasic Add User Im po rt Culture Microsoft VisualBasic Desc
519. rence ptA new XYZ 100 100 10 ptB new XYZ 0 0 10 modelcurve MakeLine document ptA ptB ref ar Append modelcurve GeometryCurve Reference Create axis for revolve form ptA new XYZ 5 0 10 ptB new XYZ 5 10 10 ModelCurve axis MakeLine document ptA ptB make axis a Reference Line axis ChangeToReferenceLine Typically this operation produces only a single form but some combinations of arguments will create multiple froms from a single profile revolveForms document FamilyCreate NewRevolveForms true ref ar axis GeometryCurve Reference 0 Math PI 4 return revolveForms Autodesk Revit ApplicationServices Application app doc Application Create plane by the points Line line app Create NewLine ptA ptB true XYZ norm ptA Cross ptB if norm Length 0 norm XYZ BasisZ Plane plane app Create NewPlane norm ptB SketchPlane skplane doc FamilyCreate NewSketchPlane plane Create line here ModelCurve modelcurve doc FamilyCreate NewModelCurve line skplane return modelcurve Figure 55 Resulting Revolve Form Forms Creating Forms Similar to family creation the conceptual design environment provides the ability to create new forms The following types of forms can be created extrusions revolves sweeps swept blends lofts and surface forms Rather than using the Blend Extrusion Revolution Sweep and SweptBlend classes used in Famil
520. required This is the large primary text that appears at the top of a task dialog e Every task dialog should have main instructions of some kind e Text should not exceed three lines e English Language Versions Main instructions should be written in sentence format normal capitalization and punctuation e English Language Versions Address the user directly as you e English Language Versions When presented with multiple command link options the standard final line for the main instructions should be What do you want to The last item in the size list cannot be deleted do Figure 225 Avery simple task dialog with only main instructions for text Main Content optional commonly used This is the smaller text that appears just below the main instructions e Main content is optional It s primarily used when all the required instructions for a task dialog will not fit in the main instruction area e Main content should not simply restate the main instructions in a different way it should contain additional information that builds upon or reinforces the main instructions e English Language Versions Main instructions should be written in sentence format normal capitalization and punctuation e English Language Versions Address the user directly as you when needed Default Template File Invalid The default template file you have specified does not exist C Revit DailyBuild Data Imperial Te default rte To change t
521. rial frameExteriorMaterial materials get Item parameter AsElementId break case Frame Interior Material frameInteriorMaterial materials get Item parameter AsElementId break case Sash sashMaterial materials get Item parameter AsElementId break default break Try category if the material is set by category if null frameExteriorMaterial frameExteriorMaterial category Material if null frameInteriorMaterial framelInteriorMaterial category Material if null sashMaterial sashMaterial category Material Show the result because the category may have a null Material the Material objects need to be checked string materialsInfo Frame Exterior Material null frameExteriorMaterial frameExteriorMaterial Name null An materialsInfo Frame Interior Material null frameInteriorMaterial frameInteriorMaterial Name null An materialsInfo Sash null sashMaterial sashMaterial Name null An TaskDialog Show Revit materialsInfo j Material quantities There are methods to directly obtain the material volumes and areas computed by Revit for material takeoff schedules Element Materials obtains a list of materials within an element Element GetMaterialVolume obtains the volume of a particular material in an element Element GetMaterialArea obtains the area of a particular material in an element The methods
522. ription Autodesk Revit 201 system m Embed Interop False TAE EE f File Type Assembly al identity RevitAPI E pe Path C Program Files A aan dE Resolved True System Ling System Aml Line Runtime Versior v2 0 50727 Specific Version False Autodesk Revit DB Autodesk Revit Ul r ae Strong Name False Display name of the reference Update User Import Figure 173 Add references and import Namespaces 7 After adding the reference you must import the namespaces used in the project For this example import the Autodesk Revit DB and Autodesk Revit Ul namespaces 8 To complete the process click RevitAPI in the Reference frame to highlight it Set Copy Local to False in the property frame Repeat for the RevitAPIUI dll Change the Class Name To change the class name complete the following steps 1 Inthe Solution Explorer right click Class1 vb to display a context menu 2 From the context menu select Rename Rename the file HelloWorld vb 3 Inthe Solution Explorer double click HelloWorld vb to open it for editing Lo out plorer SA leq mu Solution HelleWorld 1 project 4 2 HelloWorld Ea My Project TE Class v cer ri m F Tm Open With View Code View Class Diagram Exclude From Project Cut Ctrl X Copy Ctrl C Delete Alt Enter Figure 174 Change the class name Add Code When writing the code in VB NET you must pay attention to key letter ca
523. rizontal normal X 0 0 amp amp normal Y 0 0 Judge the top and bottom face distinguish 2 faces by normal Z For more details about retrieving an Element s Geometry refer to Geometry Note that project wide settings related to area and path reinforcement are accessible from the ReinforcementSettings class Currently the only setting available is the HostStructuralRebar property BeamSystem BeamSystem provides you with full access and edit ability You can get and set all of its properties such as BeamSystemType BeamType Direction and Level BeamSystem Direction is not limited to one line of edges It can be set to any XYZ coordinate on the same plane with the BeamSystem Note You cannot change the StructuralBeam AnalyticalModel after the Elevation property is changed in the UI or by the API In the following picture the analytical model lines stay in the original location after BeamSystem Elevation is changed to 10 feet Figure 156 Change BeamSystem elevation Truss The Truss class represents all types of trusses in Revit The TrussType property indicates the type of truss Code Region 29 7 Creating a truss over two columns view plaincopy to clipboardprint 1 Truss CreateTruss Autodesk Revit DB Document document 2 FamilyInstance columni FamilyInstance column2 3 4 Truss truss null 5 Transaction transaction new Transaction document Add Truss 6 if transaction Start TransactionStatus Sta
524. rmance when creating many data points that are not related to Revit geometry it is recommended to create multiple primitives with no more than 500 points each instead of one large primitive containing all points A typical use of the transform overloads will be to locate the results data offset from geometry in the Revit model for example 3 feet above a floor The AddSpatialFieldPrimitive method returns a unique integer identifier of the primitive within the SpatialFieldManager which can later be used to identify the primitive to remove it RemoveSpatialFieldPrimitive or to modify the primitive UpdateSpatialFieldPrimitive Note that the AddSpatialFieldPrimitive method creates an empty analysis results primitive UpdateSpatialFieldPrimitive must be called in order populate the analysis results data with points and values as shown in the Creating analysis results data section The UpdateSpatialFieldPrimitive method requires the unique index of an AnalysisResultSchema that has been registered with the SpatialFieldManager An AnalysisResultSchema holds information about an analysis results such as a name description and the names and multipliers of all units for result visualization The following example demonstrates how to create a new AnalysisResultSchema and set its units Code Region AnalysisResultsSchema view plaincopy to clipboardprint 1 IList string unitNames new List lt string gt 2 unitNames Add Feet 3 unit
525. rmation The Document class provides two properties for each corresponding file PathName and Title e PathName returns the document s fully qualified file path The PathName returns an empty string if the project has not been saved since it was created e Title is the project title which is usually derived from the project filename The returned value varies based on your system settings Open a Document The Application class provides an overloaded method to open an existing project file Table 3 Open Document in API Method Event Document OpenDocumentFile string filename DocumentOpened Document OpenDocumentFile ModelPath modelPath OpenOptions openOptions When you specify a string with a fully qualified file path Revit opens the file and creates a Document instance Use this method to open a file on other computers by assigning the files Universal Naming Conversion UNC name to this method The file can be a project file with the extension rvt a family file with the extension rfa or a template file with the extension rte The method throws Autodesk Revit Exceptions InvalidOperationException if you try to open unsupported file types If the document is opened successfully the DocumentOpened event is raised The second overload takes a path to the model as a ModelPath rather than a string and the OpenOptions parameter offerst the ability to detach the opened document from central if applicable Create a Document Create new doc
526. rofile ReferenceArray ra form get CurveLoopReferencesOnProfile profileIndex 0 foreach Reference r InN ra ReferenceArbay az Torm GercConurolPoines r foreach Reference r2 In raz Point vertex document GetElement r2 GetGeometryObjectFromReference r2 as Point KYZ CoObtseb new XYZ 0 15 055 Form MONK Sloe E SUED QUE O Se luego NIME as Else Som Figure 59 Modified extrusion form Rationalizing a Surface Dividing a surface Faces of forms can be divided with UV grids You can access the data for a divided surface using the Form GetDividedSurfaceData method as is shown in a subsequent example as well as create new divided surfaces on forms as shown below Code Region 14 7 Dividing a surface view plaincopy to clipboardprint 1 public void DivideSurface Document document Form form 2T 35 Application application document Application 4 Options opt application Create NewGeometryOptions E opt ComputeReferences true Ge 75 Autodesk Revit Geometry Element geomElem form get Geometry opt 8 foreach GeometryObject geomObj in geomElem 9 10 Solid solid geomObj as Solid 11 foreach Face face in solid Faces 12 13 if face Reference null 14 15 DividedSurface ds document FamilyCreate NewDividedSurface face Reference 16 create a divided surface with fixed number of U and V grid lines 17 SpacingRule srU ds USpacingRule 18 srU SetLayoutFixe
527. roominfo Area room Area An 10 roominfo Perimiter room Perimeter An 11 roominfo Unbounded height room UnboundedHeight An 12 TaskDialog Show Revit roominfo 13 The ClosedShell property for a Room or Space is the geometry formed by the boundaries of the open space of the room walls floors ceilings roofs and boundary lines This property is useful if you need to check for intersection with other physical element in the model with the room for example to see if part or all of the element is located in the room For an example see the RoofsRooms sample application included with the Revit SDK where ClosedShell is used to check whether a room is vertically unbounded In addition you can get or set the base offset and limit offset for rooms with these properties e BaseOffset e limitOffset You can get or set the level that defines the upper limit of the room with the UpperLimit property Revit Structure Certain API features that only exist in Revit Structure products are discussed in the following sections e Structural Model Elements Discusses specific Elements and their properties that only exist in the Revit Structure product e AnalyticalModel Discusses analytical model related classes such as AnalyticalModel RigidLink and AnalyticalModelSupport e AnalyticalLink Discusses creating new analytical links between analytical beams and columns e Loads Discusses Load Settings and
528. ropriate default may be blank e Where appropriate remember the last used setting of the user instead of always presenting the same system default A common example is pre setting certain settings or options which would be the most often selected Progressive Disclosure As an application s complexity increases it becomes harder for the user to find what they need To accommodate the complexity of a user interface it is common to separate the data or options into groupings The concept of Progressive Disclosure shows the needed information as necessary Progressive Disclosure may be user initiated system initiated or a hybrid of the two User initiated action Examples here include a Show More button for launching a child dialog Tabs for chunking interface elements into logical chunks and a Collection Search Filter for selectively displaying items in a collection by certain criteria System initiated action These can either be e Event based An event within the product initiates the disclosure of more information such as with a Task Dialog e Time based More information is disclosed after specified amount of time passes such as in an automatic slide show Hybrid user and time initiated An example of a hybrid is Progressive Tooltips where the user initiates the initial tooltip by hovering the mouse over the control but after a set amount of time a more detailed tooltip appears Localization of the User Interface If yo
529. rst two steps of failures processing The IFailuresProcessor ProcessFailures method is allowed to return WaitForUserlnput which leaves the transaction pending It is expected that in this case FailuresProcessor leaves some UI on the screen that will eventually commit or rollback a pending transaction otherwise the pending state will last indefinitely essentially freezing the document The following example of implementing the IFailuresProcessor checks for a failure deletes the failing elements and sets an appropriate message for the user Code Region 26 5 IFailuresProcessor Autodesk Revit Attributes Transaction Autodesk Revit Attributes TransactionMode Automatic public class MyFailuresUI IExternalApplication stare Addiaid weappld mew Addtatd mey Curd nU ooo Zo opu ADD LB CAES Publi Autodesk Regie Ul Result misc iX UC Controlled pplication ui ent ol eT Tue is om IFailuresProcessor myFailUI new FailUI Autodesk Revit ApplicationServices Application RegisterFailuresProcessor myFailULIl return Resins s usecccesi Public Autodesk Fevir Result mie Wn ge one col clade a me Ne ciis IP PS eSI ecco j pulo ccr cc Eu esiboGN PublieG void Dismiss Document document b IM ANO co io eal LIkeiel ak cc te cac ome cele PIC qe Ss LICE aL eign Ico Ecl mis Say OOS Sloe pend no NS cies S ina Ain ce let Ome Ne S Ce cm j public FailureProcessingResult ProcessFailures FailuresAccessor failuresAccessor IList Failur
530. rted 7 8 sketchPlane 9 XYZ origin new XYZ 0 0 0 10 XYZ xDirection new XYZ 1 0 0 11 XYZ yDirection new XYZ 0 1 0 12 Plane plane document Application Create NewPlane xDirection yDirection origin 13 SketchPlane sketchPlane document Create NewSketchPlane plane 14 15 new base Line use line that spans two selected columns 16 AnalyticalModel frame1 columni GetAnalyticalModel as AnalyticalModel 17 XYZ centerPoint1 framel GetCurve as Line get EndPoint 0 18 19 AnalyticalModel frame2 column2 GetAnalyticalModel as AnalyticalModel 20 XYZ centerPoint2 frame2 GetCurve as Line get EndPoint 0 713 22 XYZ startPoint new XYZ centerPoint1 X centerPoint1 Y 0 23 XYZ endPoint new XYZ centerPoint2 X centerPoint2 Y 0 24 Autodesk Revit DB Line baseLine null 25 26 try 275 28 baseLine document Application Create NewLineBound startPoint endPoint 29 30 catch System ArgumentException 31 22 throw new Exception Selected columns are too close to create truss 335 34 354 Get a truss type for the truss 36 TrussType trussType null 37a foreach TrussType currentType in document TrussTypes 38 39 if null currentType 40 41 trussType currentType 42 break 43 44 45 46 if null trussType 47 48 truss document Create NewTruss trussType sketchPlane baseLine 49 transaction Commi
531. rty It is also the transformation used when extracting a the copy of the geometry via GetInstanceGeometry For more details refer to Geometry Transform 2 family instances placed with different transforms the same geometry will be acquired from both Instances may be nested several levels deep for some families If you encounter nested instances they may be parsed in a similar manner as the first level instance Two samples are presented to explain how geometry of instances can be parsed In this sample curves are extracted from the Geometrylnstance method GetlnstanceGeometry Code Region Getting curves from an instance view plaincopy to clipboardprint 1 public void GetAndTransformCurve Autodesk Revit ApplicationServices Application app 2 Autodesk Revit DB Element element Options geoOptions 3 4 4 Get geometry element of the selected element 5 Autodesk Revit DB GeometryElement geoElement element get Geometry geoOptions 6 da Get geometry object 8 foreach GeometryObject geoObject in geoElement S 10 Get the geometry instance which contains the geometry information 11 Autodesk Revit DB GeometryInstance instance 12 geoObject as Autodesk Revit DB GeometryInstance 135 if null instance 14 15 GeometryElement instanceGeometryElement instance GetInstanceGeometry 16 foreach GeometryObject o in instanceGeometryElement 17 18 Try to find curves 19 Curve curve o as Curve
532. rveVisibility new FamilyElementVisibility FamilyElementVisibilityType Model c rvevisibility sohownilnitoarss ina lee mode lCurve loser visibiliety curveVisibaliry Family Manager Family documents provide access to the FamilyManager property The FamilyManager class provides access to family types and parameters Using this class you can add and remove types add and remove family and shared parameters set the value for parameters in different family types and define formulas to drive parameter values Getting Types in a Family The FamilyManager can be used to iterate through the types in a family as the following example demonstrates Code Region 13 11 Getting the types in a family public void GetFamilyTypesInFamily Document familyDoc if familyDoc IsFamilyDocument true FamilyManager familyManager familyDoc FamilyManager i eyed ESOS un iets Ly string types Family Types FamilyTypeSet familyTypes familyManager Types FamilyTypeSetlterator familyTypesItor familyTypes Forwardlterator familyTypesItor Reset while familyTypesItor MoveNext FamilyType familyType familyTypesItor Current as FamilyType types An familyType Name MessageBox Show types Revit Family Types 12x18 18x24 24 x 30 Figure 53 Family types in Concrete Rectangular Column family Editing FamilyTypes FamilyManager provides the ability to iterate through existing types in
533. s Autodesk Revit DB Options geomOption application Create NewGeometryOptions if null gegmOptIion geomOption ComputeReferences true geomOption DetailLevel Autodesk Autodesk Revit DB DetailLevels Fine AD A cic ule Waen Ge los set lotic pe ex hn geomOption View commandData Application ActiveUIDocument Document ActiveView TaskDialog Show Revit Geometry Option created successfully Note For more information refer to Geometry Options Retrieve Faces and Edges Wall geometry is a solid made up of faces and edges Complete the following steps to get the faces and edges 1 Retrieve a Geometry Element instance using the Wall class Geometry property This instance contains all geometry objects in the Object property such as a solid a line and so on 2 Iterate the Object property to get a geometry solid instance containing all geometry faces and edges in the Faces and Edges properties 3 terate the Faces property to get all geometry faces 4 Iterate the Edges property to get all geometry edges The sample code follows Code Region 20 2 Retrieving faces and edges view plaincopy to clipboardprint 1 private void GetFacesAndEdges Wall wall 2 3 String faceInfo 4 A Autodesk Revit DB Options opt new Options 6 Autodesk Revit DB GeometryElement geomElem wall get Geometry opt Te foreach GeometryObject geom0bj in geomElem 8 9 Solid geomSolid geomObj as Solid 10 if
534. s e For columns that are sort able clicking the header sorts the collection To differentiate table rows from each other a different shade is used as background color for every second row Keep the difference between the two colors to a minimum to preserve a gentle feeling The colors should be similar in value and low in saturation the one should be slightly darker or lighter than the other It is often seen that one of the two colors is the background color of the page itself e Ensure that the colors are different than header and title rows e Title and header cells should be in title case Columns containing numeric data e Right align the column headings for the data column e Right decimal align data in numeric columns e Format the values in percentage columns with percentage signs immediately to the right of the values to ensure that users are aware that the values are percentages NotePeople can easily forget that they are looking at percentages so the redundancy is important here especially for tables with many values Columns containing numerical data e Right align the column headings for the data column e Right decimal align data in financial columns Columns with a mix of positive and negative numeric data Align the data so that decimals align Figure 216 Properly aligned numeric data Columns containing only single letter or control such as check box e Center the data or check symbol in this column e Cen
535. s unaligned something is joined to the geometry that is affecting it e Todetermine the element that produced the non aligned face pass the face to Element GetGeneratingElementlds For more details on this utility see the following section The ExtrusionAnalyzer utility works best for geometry which are at least somewhat extrusion like for example the geometry of a wall which may or may not be affected by end joins floor joins roof joins openings cut by windows and doors or other modifications Rarely for specific shape and directional combinations the analyzer may be unable to determine a coherent face to act as the base of the extrusion an InvalidOperationException will be thrown in these situations In this example the extrusion analyzer is used to calculate and outline a shadow formed from the input solid and the sun direction Code Region Use Extrusion Analyzer to calculate and draw a shadow outline view plaincopy to clipboardprint 1 summary 2 Draw the shadow of the indicated solid with the sun direction specified 3 lt summary gt 4 remarks The shadow will be outlined with model curves added to the document 5 A transaction must be open in the document lt remarks gt 6 param name document gt The document lt param gt 7 param name solid gt The target solid lt param gt 8 param name targetLevel gt The target level where to measure and 9 draw th
536. s a string like 20 0 in the Element Properties dialog box Instance Farameters Control selected or ta be created instance Parameter Walue Constraints Location Line 00 Id ah Ps wall Centerline Let OG ASIII eee pura are P D I 1 1 e crensian puistance LI Uptelewelevelt 0 op Constraint Figure 28 AsValueString and SetValueString sample Using the AsValueString method you get the 20 0 string value directly Otherwise you get a double value like 20 without the units of measure if you use the AsDouble method Use the SetValueString method to change the value of a value type parameter instead of using the Set method The following code sample illustrates how to change the parameter value using the SetValueString method Code Region 8 5 Using Parameter Set ValueString public bool SetWithValueString Parameter foundParameter Poo mre sult ce if foundParameter IsReadOnly lt Suecescrul ene mesure recule Sonn Parane er ae Vell Wie Sic eme gene tia Mass blac Parameter Relationships There are relationships between Parameters where the value of one Parameter can affect e whether another Parameter can be set or is read only e what parameters are valid for the element e the computed value of another parameter Additionally some parameters are always read only Some parameters are computed in Revit such as wall Length
537. s and External Applications Revit identifies the new commands and applications using addin manifest files e External Commands appear under the External Tools menu button on the Add Ins tab e External Applications are invoked when Revit starts up and unloaded when Revit shuts down This chapter focuses on the following e Learning how to add functionality using External Commands and External Applications e How to access Revit events e How to customize the Revit Ul Topics tn this section e Overview e External Commands e External Applications e DB Level External Applications e Add in Registration e Localization e Attributes e Revit Exceptions e Ribbon Panels and Controls e Revit style Task Dialogs Overview The Revit Platform API is based on Revit application functionality The Revit Platform API is composed of two class Libraries that only work when Revit is running The RevitAPI dll contains methods used to access Revit s application documents elements and parameters at the database level It also contains IExternalDBApplication and related interfaces The RevitAPIUI dll contains all API interfaces related to manipulation and customization of the Revit user interface including IExternalCommand and External Command related interfaces e ExternalApplication and related interfaces e Selection e RibbonPanel Ribbonltem and subclasses e TaskDialogs As the following picture shows Revit Architecture Revit
538. s and flex ducts can all be created similarly Code Region 30 1 Creating a new Pipe view plaincopy to clipboardprint 1 public Pipe CreateNewPipe Document document 2 0 LT find a pipe type 4 5 FilteredElementCollector collector new FilteredElementCollector document 6 collector OfClass typeof PipeType 7 PipeType pipeType collector FirstElement as PipeType 8 9 Pipe pipe null 10 if null pipeType 11 12 create pipe between 2 points 13 XYZ p1 new XYZ 0 0 0 14 XYZ p2 new XYZ 10 0 15 16 pipe document Create NewPipe p1 p2 pipeType 17 18 19 return pipe 20 After creating a pipe you might want to change the diameter The Diameter property of Pipe is read only To change the diameter get the RBS PIPE DIAMETER PARAM built in parameter Code Region 30 2 Changing pipe diameter view plaincopy to clipboardprint 1 public void ChangePipeSize Pipe pipe 3 Parameter parameter pipe get Parameter BuiltInParameter RBS PIPE DIAMETER PARAM 7 string message Pipe diameter parameter AsValueString J parameter Set 5 set to 6 message nPipe diameter after set parameter AsValueString Em MessageBox Show message Revit 2280 Another common way to create a new duct or pipe is between two existing connectors as the following example demonstrates In this example it is assumed that 2 elements with connectors have been sel
539. s for the entity Ur x m cw qu Associate the entity with a Revit element Schemas and SchemaBuilder The first step to creating extensible storage is to define the schema A schema is similar to a class in an object oriented programming language Use the SchemaBuilder class constructor to create a new schema SchemaBuilder is a helper class used to create schemas Once a schema is finalized using SchemaBuilder the Schema class is used to access properties of the schema At that stage the schema is no longer editable Although the SchemaBuilder constructor takes a GUID which is used to identify the schema a schema name is also required After creating the schema call SchemaBuilder SetSchemaName to assign a user friendly identifier for the schema The schema name is useful to identify a schema in an error message The read and write access levels of entities associated with the schema can be set independently The options are Public Vendor or Application If either the read or write access level is set to Vendor the Vendorld of the third party vendor that may access entities of the schema must be specified If either access level is set to Application the GUID of the application or add in that may access entities of the schema must be supplied Note that schemas are stored with the document and any Revit API add in may read the available schemas in the document It is the actual data in the entities stored with specific elements that is restric
540. s possible that the ParameterSet collection may not contain all parameters returned from the get Parameter method though this is infrequent Storage lype StorageType describes the type of parameter values stored internally Based on the property value use the corresponding get and set methods to retrieve and set the parameter data value The StorageType is an enumerated type that lists all internal parameter data storage types supported by Revit Table 16 Storage Type Member Name Description String Internal data is stored as a string of characters Elementid Data type represents an element and is stored as an Element ID Double Data is stored internally as an 8 byte floating point number Integer Internal data is stored as a signed 32 bit integer None None represents an invalid storage type For internal use only In most cases the Elementld value is a positive number However it can be a negative number When the Elementld value is negative it does not represent an Element but has another meaning For example the storage type parameter for a beam s Vertical Projection is Elementid When the parameter value is Level 1 or Level 2 the Elementid value is positive and corresponds to the Elementld of that level However when the parameter value is set to Auto detect Center of Beam or Top of Beam the Elementld value is negative lengd PT Erud I hol Vertical Projection 00 PA amp uta debeck Horizontal Projection p uto dete
541. s used in family modeling and massing e SketchPlane e Sketch e Path3D e GenericForm For Sketch details see Sketching Information Elements Information Elements contain non physical invisible items used to store project and application data Information Elements are further separated into the following e Project Datum Elements e Project Datum Elements Unique For more information about Datum Elements see Datum and Information Elements Other Classifications Elements are also classified by the following e Category Family Symbol e Instance There are some relationships between the classifications For example e You can distinguish different kinds of FamilyInstances by the category Items such as structural columns are in the Structural Columns category beams and braces are in the Structural Framing category and so on e You can differentiate structural FamilyInstance Elements by their symbol Category The Element Category property represents the category or subcategory to which an Element belongs It is used to identify the Element type For example anything in the walls Category is considered a wall Other categories include doors and rooms Categories are the most general class The Document Settings Categories property is a map that contains all Category objects in the document and is subdivided into the following e Model Categories Model Categories include beams columns doors windows and walls e Anno
542. schedules and tags O Structural Columns Structural Foundations Export Structural Framing Topography Parameter Data Views M ame Group parameter under Wal Sweep sss Instance ProductD ate iv walls A ME CI ARI Shed oe hed OTe windows Discipline 5 5 Instance O Type EE O instance O Tape E Ca Type of Parameter Text Show categories fram all disciplines Hide un checked categories Add to all elements in the selected categories Figure 133 Parameter Properties dialog box I nstance Binding The following code sample demonstrates how to add parameter definitions using a shared parameter file Parameter definitions are added in the following order 1 Ashared parameter file is created 2 Adefinition group and a definition for all Walls instances is created 3 Definitions are bound to each wall instance parameter in the current document based on the wall category Code Region 22 8 Adding instance parameter definitions using a shared parameter file public bool SetNewParameterToInsanceWall UIApplication app DefinitionFile myDefinitionFile 1 Mare are el JEN CROOUIS Tua aS snared a ranme tere T alle DefinitionGroups myGroups myDefinitionFile Groups DefinitionGroup myGroup myGroups Create MyParameters1 Sees re tan instance de rin enim detinit tom NS OUI MyParamckens Definition myDefinition ProductDate myGroup Definitions Create Instance ProductDate Paramete
543. se controls can have an image associated with them using the Largelmage property The best size for images associated with large controls such as non stacked ribbon and drop down buttons is 32x32 pixels but larger images will be adjusted to fit the button Stacked buttons and small controls such as text boxes and combo boxes should have a 16x16 pixel image set Large buttons should also have a 16x16 pixel image set for the Image property This image is used if the command is moved to the Quick Access Toolbar If the Image property is not set no image will be displayed if the command is moved to the Quick Access Toolbar Note that if an image larger than 16x16 pixels is used it will NOT be adjusted to fit the toolbar The ToolTiplmage will be displayed below the LongDescription in the extended tooltip if provided There is no recommended size for this image Ribbon control availability Ribbon controls can be enabled or disabled with the Ribbonltem Enabled property or made visible or invisible with the Ribbonltem Visible property Ribbon Controls In addition to the following controls vertical separators can be added to ribbon panels to group related sets of controls Push Buttons There are three types of buttons you can add to a panel simple push buttons drop down buttons and split buttons The HelloWorld button in Figure 13 is a push button When the button is pressed the corresponding command is triggered In addition to the Enabled propert
544. section click Start external program and browse to the Revit exe file By default the file is located at the following path C Program Files Autodesk Revit Structure 2012 Program Revit exe HelloWorld Microsoft Visual Studio Administrator File Edt View Project Build Debug Team Data Jools VMware Test Window Help Ej HelloWaorld Balti ea Application Configuration Active Debug Platform Active Any CPU Start Action Build Events Start projec EE J start project a Start external program IC AProgram FileA amp uludesksRevil Archibecture 20125 m Resources Hr O Start browser with URL p Services i sA Start Options Command line arguments Reference Paths Signing Working directory Use remote machine Figure 3 Set debug environment 5 From the Debug menu select Toggle Breakpoint or press F9 to set a breakpoint on the following line Mas Diao os now Revi CS Wonda 6 Press F5 to start the debug procedure Test debugging e On the Add Ins tab HelloWorld appears in the External Tools menu button APA A 43 0 5 amp fo gt Autodesk Revit Structu Figure 4 HelloWorld External Tools command e Click HelloWorld to execute the program activating the breakpoint e Press F5 to continue executing the program The following system message appears HelloWorld Revit m m Hello World Figure 5 TaskDi
545. sed or by using methods and properties of the class prior to calling a method to perform the ray projection There are 4 constructors Name Description Constructs a Referencelntersector which is set to return intersections from all elements and Referencelntersector View3D representing all reference target types Constructs a Referencelntersector which is set to return intersections from any element which passes Referencelntersector ElementFilter FindReferenceTarget View3D echter Constructs a Referencelntersector which is set to return intersections from a single target element Referencelntersector Elementld FindReferenceTarget View3D only Referencelntersector ICollection lt Elementid gt FindReferenceTarget Constructs a Referencelntersector which is set to return intersections from any of a set of target View3D elements The FindReferenceTarget enumeration includes the options Element Mesh Edge Curve Face or All There are two methods to project a ray both of which take as input the origin of the ray and its direction The Find method returns a collection of ReferenceWithContext objects which match the Referencelntersector s criteria This object contains the intersected reference which can be both the elements and geometric references which intersect the ray Some element references returned will have a corresponding geometric object which is also intersected for example rays passing through openings in walls will in
546. sent an introduction to the Revit Platform API and provide an overview of the User Manual Welcome to the Revit Platform API Presents an introduction to the Revit Platform API and necessary prerequisite knowledge before you create your first add in Getting Started Step by step instructions for creating your first Hello World add in application using Visual Studio 2010 and four other walkthroughs covering primary add in functions Basic Topics These chapters cover the Revit Platform API basic mechanisms and functionality Add in Integration Discusses how an add in is integrated into the Revit UI and invoked by user commands or specific Revit events such as program startup Application and Document Application and Document classes respectively represent the Revit application and project file in the Revit Platform API This chapter explains basic concepts and links to pertinent chapters and sections Elements Essentials The bulk of the data in a Revit project is in a collection of Elements This chapter discusses the essential Element mechanism classification and features Filtering Filtering is used to get a set of elements from the document Selection Working with the set of selected elements in a document Parameters Most Element information is stored as Parameters This chapter discusses Parameter functionality Collection Utility collection types such as Array Map Set collections and related Iterators Element Topics
547. sential Element Display The ShowElements method uses zoom to fit to focus in on one more elements View Management The UlDocument class can be used to refresh the active view in the active document by calling the RefreshActiveView method The ActiveView property can be used to retrieve or set the active view for the document Changing the active view has some restrictions It can only be used in an active document which must not be in read only state and must not be inside a transaction Additionally the active view may not be changed during the ViewChanging or ViewChanged event or during any pre action event such as DocumentSaving DocumentExporting or other similar events The UlDocument can also be used to get a list of all open view windows in the Revit user interface The GetOpenUlViews method returns a list of UlViews which contain data about the view windows in the Revit user interface Document and File Management Document and file management make it easy to create and find your documents Document Retrieval The Application class maintains all documents As previously mentioned you can open more than one document in a session The active document is retrieved using the UlApplication class property ActiveUIDocument All open documents including the active document are retrieved using the Application class Documents property The property returns a set containing all open documents in the Revit session Document File Info
548. ser Code Region Creating a section view view plaincopy to clipboardprint Find a section view type IEnumerable ViewFamilyType viewFamilyTypes from elem in new FilteredElementCollector document OfClass typeof ViewFamilyType let type elem as ViewFamilyType where type ViewFamily ViewFamily Section select type Create a BoundingBoxXYZ instance centered on wall LocationCurve lc wall Location as LocationCurve 9 Transform curveTransform lc Curve ComputeDerivatives 0 5 true 10 using 0 5 and true to specify that the parameter is normalized 11 places the transform s origin at the center of the location curve 12 CON ADU Ab UN A 13 XYZ origin curveTransform Origin mid point of location curve 14 XYZ viewDirection curveTransform BasisX Normalize tangent vector along the location curve 15 XYZ normal viewDirection CrossProduct XYZ BasisZ Normalize location curve normal mid point 16 17 Transform transform Transform Identity 18 transform Origin origin 19 transform BasisX normal 20 transform BasisY XYZ BasisZ 21 22 can use this simplification because wall s up is vertical 23 For a non vertical situation such as section through a sloped floor the surface normal would be needed 24 transform BasisZ normal CrossProduct XYZ BasisZ 25 26 BoundingBoxXYZ sectionBox new BoundingBoxXYZ 27 sectionBox Transform transform 28 sectionBox
549. ses Symbols contain host object parameters or other elements For example a WallType Symbol contains the thickness number of layers material for each layer and other properties for a particular wall type FamilySymbol is a symbol in the API It is also called Family Type in the Revit user interface FamilySymbol is a class of elements in a family with the exact same values for all properties For example all 32x78 six panel doors belong to one type while all 24x80 six panel doors belong to another type Like a Family a FamilySymbol is also a template The FamilySymbol object is derived from the ElementType object and the Element object Instances are items with specific locations in the building model instances or on a drawing sheet annotation instances Instance represents transformed identical copies of an ElementType For example if a building contains 20 windows of a particular type there is one ElementType with 20 Instances Instances are called Components in the user interface Note For FamilyInstance the Symbol property can be used instead of the GetTypeld method to get the corresponding FamilySymbol It is convenient and safe since you do not need to do a type conversion Element Retrieval Elements in Revit are very common Retrieving the elements that you want from Revit is necessary before using the API for any Element command There are several ways to retrieve elements with the Revit API e Elementld If the Elementid o
550. set for new mechanical system 38 csi fi MEPModel ConnectorManager Connectors ForwardIterator 39 csi MoveNext 40 connectorSet Insert csi Current as Connector 41 42 43 44 MechanicalSystem mechanicalSys null 45 if null baseConnector amp amp connectorSet Size gt 0 46 47 create a new SupplyAir mechanical system 48 mechanicalSys document Create NewMechanicalSystem baseConnector connectorSet DuctSystemType SupplyAir 49 Connectors As shown in the previous section new pipes and ducts can be created between two connectors Connectors are associated with a domain ducts piping or electrical which is obtained from the Domain property of a Connector Connectors are present on mechanical equipment as well as on ducts and pipes To traverse a system you can examine connectors on the base equipment of the system and determine what is attached to the connector by checking the IsConnected property and then the AllRefs property When looking for a physical connection it is important to check the ConnectionType of the connector There are both physical and logical connectors in Revit but only the physical connectors are visible in the application The following imagine shows the two types of physical connectors end connections and curve connectors EndConn EndConn EndConn EndConn EndConn Takeoff Transition Curve Conn EndConn EndConn EndConn Figure 167 Physical connectors
551. set or if the saving target file is read only Note The Close method does not affect the active document or raise the DocumentClosed event because the document is used by an external application You can only call this method on non active documents The UlDocument class also provides methods to save and close instances Table 6 Save and Close UI Document in API Method Event SaveAndClose DocumentSaved DocumentClosed SaveAs DocumentSavedAs SaveAndClose closes the document after saving it If the document s path name has not been set the Save As dialog will be shown to the Revit user to set its name and location The SaveAs method saves the document to a file name and path obtained from the Revit user via the Save As dialog Document Preview The DocumentPreviewSettings class can be obtained from the Document and contains the settings related to the saving of preview images for a given document Code Region Document Preview view plaincopy to clipboardprint 1 public void SaveActiveViewWithPreview UIApplication application 2 q 34 Get the handle of current document 4 Autodesk Revit DB Document document application ActiveUIDocument Document Ds 6 Get the document s preview settings 7 DocumentPreviewSettings settings document GetDocumentPreviewSettings 8 9 Find a candidate 3D view 10 FilteredElementCollector collector new FilteredElementCollector document 11 collector OfClass typ
552. shared parameters file using the Application OpenSharedParameterFile method 3 Open an existing group or create a new group using the DefinitionFile Groups property 4 Openan existing external parameter definition or create a new definition using the DefinitionGroup Definitions property The following list provides more information about the classes and methods in the previous diagram e Autodesk Revit Parameters DefinitionFile Class The DefinitionFile object represents one shared parameter file o The object contains a number of Group objects o Shared parameters are grouped for easy management and contain shared parameter definitions o You can add new definitions as needed o The DefinitionFile object is retrieved using the Application OpenSharedParameterFile method e Autodesk Revit Parameters ExternalDefinition Class The ExternalDefinition class is derived from the Definition class o The ExternalDefinition object is created by a DefinitionGroup object from a shared parameter file o External parameter definitions must belong to a Group which is a collection of shared parameter definitions e Autodesk Revit Options Application SharedParametersFilename Property Get and set the shared parameter file path using the Autodesk Revit Options SharedParametersFilename property o By default Revit does not have a shared parameter file o Initialize this property before using If it is not initialized an exception is thrown e Autodesk Revit Ap
553. simple buttons in the footer of the task dialog Standard English terms include e OK e Cancel e Yes e NO e Retry e Close It is possible to use custom text on commit buttons but that is not recommended Notes on proper usage of each of the primary button types e The OK button should only be used in situations where a task dialog poses a question that can be answered by OK e The Cancel button should only be used when a task can truly be canceled meaning the action that triggered the task dialog will be aborted and no change will be committed It can be used in combination with other commit buttons or command links e The Yes amp No button s should always be used in combination and the text in the main instructions and or main content should end in a yes no question e The Retry button must appear with at least a Cancel button as an alternate option so a user can choose not to retry e The Close button is used on any purely informational task dialog i e where the user has no action to choose but can just read the text and close the dialog Previously the OK button was often used on such dialogs It should not be used in task dialogs for this purpose The following are some examples of how commit buttons should be used e See Figure 226 for an example of a Cancel button with command links e See Figure 224 for an example of a purely informative task dialog with a close button e See Figure 227 for an example of a task dialog wit
554. sing ControlledApplication Probie llas oe ep eee don Dass o EO e Owain Esencia plano implement ene Onstareup mernod to register events when Revit stars CULLE Ares iO sima iere UC onic ico ll ise ee bab eene Loin jeje diste eee O31 Register related events cuo pue Ses one posee RE new EventHandler lt Autodesk Revit UI Events DialogBoxShowingEventArgs gt AppDialogShowing recur Result uccecded Implement this method to unregister the subscribed events when Revit exits outset Dite loose QU RIS Comer eee GASTO OS lei ORIS apo hear hom eos ter vevemrs Soles Lon De doc Bo comas new EventHandler lt Autodesk Revit UI Events DialogBoxShowingEventArgs gt AppDialogShowing return Recull uUccecded 7 Tne Dialogboxsheowing evene handler whieh allow yeu to do some work before the dialog shows void AppDialogShowing object sender DialogBoxShowingEventArgs args i Get the help id of the showing dialog int al ios Ile uds Helpi 7 IB SENSU E Ele TO E s HUE OL mene loi Sica String promptInfo A Revit dialog will be opened n prom TEE CN r Vere laisse ake exh icles alto ale 4 ae elase Loe lie Needs bte iat promptior TIF you donit want Ene dialog to open please press cancel ui iom Show the preompt message and allow time cer to close the dialog directly TaskDialog taskDialog new TaskDialog Revit EaskDaalog MainConkzene Tomis Wes elabi loc Colmenero lobiccoms
555. single building or drawing component such as a door a wall or a dimension In addition an Element can be a door type a view or a material definition Topics tn this section e Element Classification e Other Classifications e Element Retrieval e General Properties Element Classification Revit Elements are divided into six groups Model Sketch View Group Annotation and Information Each group contains related Elements and their corresponding symbols Model Elements Model Elements represent physical items that exist in a building project Elements in the Model Elements group can be subdivided into the following e Family Instances Family Instances contain family instance objects You can load family objects into your project or create them from family templates For more information see Family Instances e Host Elements Host Elements contain system family objects that can contain other model elements such as wall roof ceiling and floor For more information about Host Elements see Walls Floors Roofs and Openings e Structure Elements Structure Elements contain elements that are only used in Revit Structure For more information about Structure Elements see Revit Structure View Elements View Elements represent the way you view and interact with other objects in Revit For more information see Views Group Elements Group Elements represent the assistant Elements such as Array and Group objects in Revit For
556. sion CreateExtrusion Autodesk Revit DB Document document SketchPlane sketchPlane 2 1 3 Extrusion rectExtrusion null 4 make sure we have a family document 5 if true document IsFamilyDocument 6 7 define the profile for the extrusion 8 CurveArrArray curveArrArray new CurveArrArray 9 CurveArray curveArray1 new CurveArray 10 CurveArray curveArray2 new CurveArray 11 CurveArray curveArray3 new CurveArray 12 create a rectangular profile 13 XYZ pO XYZ Zero 14 XYZ p1 new XYZ 10 0 15 XYZ p2 new XYZ 10 10 0 16 XYZ p3 new XYZ 0 10 0 17 Line linel document Application Create NewLineBound p0 p1 18 Line line2 document Application Create NewLineBound p1 p2 19 Line line3 document Application Create NewLineBound p2 p3 20 Line line4 document Application Create NewLineBound p3 p0 21 curveArray1 Append line1 Dye curveArray1 Append line2 23 curveArray1 Append line3 24 curveArray1 Append line4 255 curveArrArray Append curveArray1 26 create solid rectangular extrusion 275 rectExtrusion document FamilyCreate NewExtrusion true curveArrArray sketchPlane 10 28 29 if null rectExtrusion 30 21 move extrusion to proper place 32 XYZ transPoint1 new XYZ 16 0 0 33 document Move rectExtrusion transPoint1 34 25s else 36 ore throw new Exception Create new Extrusion failed 38 39
557. ssed from its Symbol property Thermal Properties Certain types of families doors windows and curtain wall panels contain thermal properties as shown in the Type Properties window below for a window Type Properties Family M Window Square Opening Rename Type Parameters Operation Analytic Construction None Heat Transter Coefficient U ioo M E dabei NU I Solar Heat Gain Coefficient a EE CLE TECHTETEEEEE HERE rr Visual Light Transmittance The thermal properties for a FamilySymbol are represented by the FamilyThermalProperties class and are retrieved using the FamilySymbol GetThermalProperties method The FamilyThermalProperties for a FamilySymbol can be set using SetThermalProperties The properties of the FamilyThermalProperties class itself are read only The units for the calculated values are shown in the table below Property Unit o watts per meter squared kelvin HeatTransferCoefficient W m 2 K meter squared kelvin per watt m 2 K Watt The AnalyticConstructionTypeld property is the construction gbXML type and returns the value that corresponds to the id property of a constructionType node in Constructions xml The static FamilyThermalProperties Find method will find the FamilyThermalProperties by the id property of a constructionType node in Constructions xml ThermalResistance Family Creation This chapter discusses families and how to e Create and modify
558. stairs therefore requiring a test to see if each Elementld represents a Stairs By Component before being cast to a Stairs class when retrieved from the document Code Region Getting stairs information nlaincernniws tn er AA nRnaraAnrint DIaINCOPY LO CIIDDOdI UpPIINLU M 1 private Stairs GetStairInfo Document document ZE 35 Stairs stairs null 4 Ds FilteredElementCollector collector new FilteredElementCollector document 6 ICollection ElementId stairsIds collector WhereElementIsNotElementType OfCategory BuiltInCategory OST Stairs ToElementIdsElementId 7 foreach ElementId stairId in stairsIds 8 9 if Stairs IsByComponent document stairId true 10 12 stairs document GetElement stairId as Stairs 12 13 Format the information 14 String info nNumber of stories stairs NumberOfStories 15 info nHeight of stairs stairs Height 16 info nNumber of treads stairs ActualTreadsNumber 17 info nTread depth stairs ActualTreadDepth 18 19 Show the information to the user 20 TaskDialog Show Revit info 21 227 23 24 return stairs 25 The StairsType class represents the type for a Stairs element It contains information about the Stairs such as the type of all runs and landings in the stairs object types and offsets for supports on the left right and middle of the stairs and numerous other properties related to stair gene
559. such as e DoA B orC e DoAorBorAandB e DoAordo not do A e Etc Command link text has two parts e Main content This is required for any command link It is one line written as a statement For English language versions it is in sentence format without final punctuation e Supplemental content This is optional additional text to clarify the main content For English language versions it is written in normal sentence format with final punctuation The first command link one at the top is the default action for the task dialog It should be the most common action or the least potentially damaging action if no choice is substantially more likely than the other for the common use case Revit encountered a fatal error and must close the application What do you want to do To avoid data loss save recovery files for all of your changed projects gt Save to recovery files with new names and close gt Close without saving to recovery files Figure 229 Atask dialog with two command links amp Changes Not Synchronized with Central Your local file contains changes that have not been synchronized with the central file What do you want to do gt Synchronize with central gt Synchronize with central and set reminder intervals gt Do not synchronize and set reminder intervals Figure 230 Task Dialog with command links and a command button Commit Buttons optional commonly used Commit buttons are
560. t 50 51 else 527 53 transaction RollBack 54 throw new Exception No truss types found in document 55 56 57 58 return truss 59 A The Rebar class represents rebar used to reinforce suitable elements such as concrete beams columns slabs or foundations You can create rebar objects using one of three static Rebar methods Name Description HERD EO by ero sc SEDES Creates a new instance of a Rebar element within the project All curves must belong to the plane 1 public static Rebar Rebar CreateFromCurves defined by the normal and origin 2 Document doc 3 RebarStyle style 4 RebarBarType rebarType 5 RebarHookType startHook 6 RebarHookType endHook 7 Element host 8 XYZ norm 9 IList Curve curves 10 RebarHookOrientation startHookOrient 11 RebarHookOrientation endHookOrient 12 bool useExistingShapeIfPossible 13 bool createNewShape Ta view plaincopy to clipboardprint Creates a new Rebar as an instance of a RebarShape The instance will have the default shape 1 public static Rebar Rebar CreateFromRebarShape parameters from the RebarShape and its location is based on the bounding box of the shape in the 2 Document doc shape definition Hooks are removed from the shape before computing its bounding box If 3 RebarShape rebarShape appropriate hooks can be found in the document they will be assigned arbitrarily A RebarBarType rebarType 5 Element host 6 XYZ origin
561. t Assembly gt ouystelatie del SOAS LOE 2 9 4 2 41 955 ls O CL LDL OS SLO A lt FullClassName gt AddPanel CsAddPanel lt FullClassName gt VendorId ADSK VendorId lt VendorDescription gt Autodesk www autodesk com lt VendorDescription gt lt AddIn gt lt RevitAddIns gt 3 Savethe file as HelloWorldRibbon addin and put it in the following location o For Windows XP C Documents and Settings All Usersl Application Data Autodesk Revit Addins 2012 o For Vista Windows 7 C ProgramData Autodesk Revit Addins 2012 Note The AddPanel dll file is in the default file folder in a new folder called Debug D Sample HelloWorld bin Debug AddPanel dll Use the file path to evaluate Assembly Refer to Add in Integration for more information about addin manifest files Debugging To begin debugging build the project and run Revit A new ribbon panel appears on the Add Ins tab named NewRibbonPanel and Hello World appears as the only button on the panel with a large globe image Autodesk Revit Struct T T TY Ie J a B Til ay Select NewRibbonPanel SSS Figure 9 Add a new ribbon panel to Revit Click Hello World to run the application and display the following dialog box Les Hello World Figure 10 Hello World dialog box Walkthrough Retrieve Selected Elements This section introduces you to an add in application that gets selected elements from Revit In add in applications you can perform a s
562. t and action controls below content Collection Viewer In applications such as Revit the user must view and manage collections of items to complete their tasks The Collection View provides the user a variety of ways of viewing the items browsing searching and filtering in the collection Provide a way for a user to easily browse through a collection of items for the purpose of selecting an item to view or edit see Collection Editor Optionally provide the ability to search and or filter the collection Materials Materials 2 Enter Search Words E zu Acoustic Ceiling Tile 24 x 2 acohatt Acoustic Ceiling Tile 24 x 4 Brick 5 Acoustical Treatment Carpet dar Air tofilteating Ceramic Air edd Air Infiltration E silane Asphalt Fabric Carpet 1 Generic Carpet 2 Glass Ceramic Tile 4 Blue Liquid Metal Concrete Miscellaneous Concrete Cast in Place Co Paint Concrete Cast in Place Lig Paper Concrete Cast in Place Lig td Concrete Precast Concrete ec Curtain Wall Mullions Stone Default Stucco Default Floor e Default Form Wood Default Light Source m Default Mass Floor Default Roof Default Wall Default Zoning Envelope Door Frame Door Panel EIFS Exterior Insulation and Finish System Figure 208 Materials dialog from Revit Graphics Render Appearance ety Shading Use Render Appearance for Shading i RGB 232 232 232 Transparency 0 Surface Pattern Ceiling 24x24
563. t are constant for all instances of the Type that exist in your model these are called Type Properties Types have other parameters called Instance parameters which can vary in your model Sets A set is a collection container of values without a particular order and no repeated values It corresponds with the mathematical concept of set except for the restriction that it has to be finite Element ID Each element has a corresponding ID It is identified by an integer value It provides a way of uniquely identifying an Element within an Autodesk Revit project It is only unique for one project but not unique across separate Autodesk Revit projects Element UID Each element has a corresponding UID It is a string identifier that is universally unique That means it is unique across separate Autodesk Revit projects FAQ Topics in this section e General Questions e Revit Structure Questions General Questions Q How do reference an element in Revit A Each element has an ID The ID that is unique in the model is used to make sure that you are referring to the same element across multiple sessions of Revit Q Can a model only use one shared parameter file A Shared parameter files are used to hold bits of information about the parameter The most important piece of information is the GUID Globally Unique Identifier that is used to insure the uniqueness of a parameter in a single file and across multiple models Revit ca
564. t project e ModelPath A non Element class which contains path information for a file not necessarily a rvt file Paths can be to a location on a local or network drive or to a Revit Server location e ModelPathUtils A utility class which provides methods for converting between strings and ModelPaths e TransmissionData A class which stores information about all of the external file references in a document The TransmissionData for a Revit project can be read without opening the document ExternalFileUtils As its name implies this utility class provides information about external file references The ExternalFileUtils GetAllExternalFileReferences method returns a collection of Elementids of all elements that are external file references in the document Note that it will not return the ids of nested Revit links it only returns top level references This utility class has two other methods IsExternalFileReference and GetExternalFileReference which perform the same function as the similarly named methods of the Element class but can be used when you have an Elementld rather than first obtaining the Element ModelPath ModelPaths are paths to another file They can refer to Revit models or to any of Revit s external file references such as DWG links Paths can be relative or absolute but they must include an extension indicating the file type Relative paths are generally relative to the currently opened document If the curre
565. tail curve to the model curve view Code Region 16 4 NewDetailCurve and NewModelCurve public DetailCurve NewDetailCurve View Curve SketchPlane public ModelCurve NewModelCurve Curve SketchPlane Generally only 2D views such as level view and elevation view are acceptable otherwise an exception is thrown Except for view related features DetailCurve is very similar to ModelCurve For more information about ModelCurve properties and usage see ModelCurve in the Sketching section Tags A tag is an annotation used to identify drawing elements The API exposes the IndependentTag and RoomTag classes to cover most tags used in the Revit application For more details about RoomTag see Room in the Revit Architecture section NoteThe IndependentTag class represents the tag element in Revit and other specific tags such as keynote beam system tag electronic circuit symbol Revit MEP and so on In Revit internal code the specific tags have corresponding classes derived from IndependentTag As a result specific features are not exposed by the API and cannot be created using the NewTag method They can be distinguished by the following categories Table 37 Tag Name and Category Tag Name BuiltInCategory Keynote Tag OST KeynoteTags Beam System Tag OST BeamSystemTags Electronic Circuit Tag OST ElectricalCircuitTags Span Direction Tag OST SpanDirectionSymbol Path Reinforcement Span Tag OST PathReinSpanSymbol Rebar System Span Tag
566. tain Systems Uncovered Faces Curtain Grids RS l Grid on Face 4 Figure 222 The Curtain System SDK sample Supported Behaviors Action Description Required 1 Add to list Takes an item from list A and adds it to list B Yes 2 Remove from list Removes item from List B Yes 3 Collection Editor If List A can be managed in this context use Collection Manager No Depending on the feature the List Builder can act in one of two ways e tem can only be added once items from List A can only be added to List B once In this case the Add button should be disabled when a previously added item is selected in List A e temcan be added multiple times In this case the Add button is not disabled and the user can add an item from List A to List B multiple times the amount determined by the feature See Edit Label example below If the user needs to arbitrarily move an item up or down in a collection provide up down buttons next to the list Customize Quick Access Toolbar gt 9 S Measure Between Two References Split Button Aligned Dimension i Tag by Category Text Default 3D View Split Button Secton Thin Lines Close Hidden Windows F Show Quick Access Toolbar below Ribbon Figure 223 Up down buttons Task Dialog Task dialogs are a type of modal dialog They have a common set of controls that are arranged in a standard order to assure consistent look and feel A task dialog is used when the system n
567. tances use LocationPoint In the Revit Platform API curve driven means that the geometry or location of an element is determined by one or more associated curves Almost all analytical model elements are curve driven linear and area loads walls framing elements and so on Other Elements cannot retrieve a LocationCurve or LocationPoint They return Location with no information Table 12 Elements Location Information Location Information Elements LocationCurve Wall Beam Brace Structural Truss LineLoad without host LocationPoint Room RoomTag SpotDimension Group Column Mass Only Location Level Floor some Tags BeamSystem Rebar Reinforcement PointLoad AreaLoad without Host Span Direction IndependentTag No Location View LineLoad with host AreaLoad with Host BoundaryCondition NoteThere are other Elements without Location information For example a LineLoad with host or an AreaLoad with host have no Location Some Familyl nstance LocationPoints such as all in place Familyl nstances and masses are specified to point 0 0 0 when they are created The LocationPoint coordinate is changed if you transform or move the instance To change a Group s LocationPoint do one of the following e Drag the Group origin in the Revit Ul to change the LocationPoint coordinate In this situation the Group LocationPoint is changed while the Group s location is not changed e Move the Group using the ElementTransformUtils Mov
568. tation Categories Annotation Categories include dimensions grids levels and textnotes Model Beams Columns Windows Dimensions Grids Levels Doors TextNotes PT Figure 20 Categories Note The following guidelines apply to categories e n general the following rules apply to categories o Each family object belongs to a category o Non family objects like materials and views do not belong to a category o There are exceptions such as Projectinfo which belongs to the Project Information category e Anelement and its corresponding symbols are usually in the same category For example a basic wall and its wall type Generic 8 are all in the Walls category e The same type of Elements can be in different categories For example SpotDimensions has the SpotDimensionType but it can belong to two different categories Spot Elevations and Spot Coordinates e Different Elements can be in the same category because of their similarity or for architectural reasons ModelLine and DetailLine are in the Lines category To gain access to the categories in a document Setting class for example to insert a new category set use one of the following techniques e Get the Categories from the document properties e Get a specific category quickly from the categories map using the BuiltInCategory enumerated type Code Region 5 1 Getting categories from document settings Get settings of current document Settings documentSettings docume
569. tb3 ToolTip Blue Option 165 tb3 Largelmage new BitmapImage new Uri Q D NSampleNHelloWorldNbinNDebugNBlue bmp 17 radioButtonGroup AddItem tb1 18 radioButtonGroup AddItem tb2 19 radioButtonGroup AddItem tb3 20 Text box A text box is an input control for users to enter text The image for a text box can be used as a clickable button by setting the ShowlmageAsButton property to true The default is false The image is displayed to the left of the text box when ShowlmageAsButton is false and displayed at the right end of the text box when it acts as a button as in Figure 13 The text entered in the text box is only accepted if the user hits the Enter key or if they click the associated image when the image is shown as a button Otherwise the text will revert to its previous value In addition to providing a tooltip for a text box the PromptText property can be used to indicate to the user what type of information to enter in the text box Prompt text is displayed when the text box is empty and does not have keyboard focus This text is displayed in italics The text box in Figure 13 has the prompt text Enter a comment The width of the text box can be set using the Width property The default is 200 device independent units The TextBox EnterPressed event is triggered when the user presses enter or when they click on the associated image for the text box when ShowlmageAsButton is set to true When implementing an EnterPress
570. te NewLevel elevation if null level throw new Exception Create a new level failed Change the level name level Name New level ipee Note After creating a new level Revit does not create the associated plan view for this level If necessary you can create it yourself For more information about how to create a plan view refer to Views Grids Grids are represented by the Grid class which is derived from the Element class It contains all grid properties and methods The inherited Name property is used to retrieve the content of the grid line s bubble Curve The Grid class Curve property gets the object that represents the grid line geometry e Ifthe IsCurved property returns true the Curve property will be an Arc class object e Ifthe IsCurved property returns false the Curve property will be a Line class object For more information refer to Geometry The following code is a simple example using the Grid class The result appears in a message box after invoking the command Code Region 15 3 Using the Grid class public void GerInto Gra Geld grid SCLC message Guia 2 s fi Siow LeCuievecl ous OO S IE Y Message Wilt Craideds stew Lcd Cine si 1 Sato Cuero abge NETS E alien Autodesk Revit DB Curve curve grid Curve ten no eis Cilia SO e res wail selec ee carbo amc rachis O amaron Autodesk Revit DB Arc arc curve as Autodesk Revit DB Arc message nArc s radius
571. te lee camera ae ou EE cui ievs teen familyManager Set familyParam 2 0 Mow pate ne Reval eio melt nex mcis e as amen pe family familyDoc LoadFamily document Me new ey pe and ass tonto E cma sus cance Hans mesita eed SEAT SX tte eno Aran e Sa mo cs bo cea eran ee Simo ows iow Ne sel 0 while symbolsItor MoveNext Pamio mool al Sa miooo symbols Leo UE tas amis mb ol if familySymbol Name 2X2 family instando oai 619 Aaa y no OH break Conceptual Design This chapter discusses the conceptual design functionality of the Revit API for the creation of complex geometry in a family document Form making is supported by the addition of new objects points and spline curves that pass through these points The resulting surfaces can be divided patterned and panelized to create buildable forms with persistent parametric relationships Topics in this section e Point and curve objects e Forms e Rationalizing a Surface Point and curve objects A reference point is an element that specifies a location in the XYZ work space of the conceptual design environment You create reference points to design and plot lines splines and forms A ReferencePoint can be added to a ReferencePointArray then used to create a CurveByPoints which in turn can be used to create a form The following example demonstrates how to create a CurveByPoints object See the Creating a loft form example in the next section
572. ted Getting Element Geometry and AnalyticalModel After new elements are created or elements are modified regeneration and auto joining of elements is required to propagate the changes throughout the model Without a regeneration and auto join when relevant the Geometry property and the AnalyticalModel for Elements are either unobtainable in the case of creating a new element or they may be invalid It is important to understand how and when regeneration occurs before accessing the Geometry or AnalyticalModel of an Element Although regeneration and auto join are necessary to propagate changes made in the model it can be time consuming It is best if these events occur only as often as necessary Regeneration and auto joining occur automatically when a transaction that modifies the model is committed successfully or whenever the Document Regenerate or Document AutoJoinElements methods are called Regenerate and AutoJoinElements may only be called inside an open transaction It should be noted that the Regeneration method can fail in which case the RegenerationFailedException will be thrown If this happens the changes to the document need to be rolled back by rolling back the current transaction or subtransaction For more details about the AnalyticalModel object refer to AnalyticalModel in Revit Structure For more details about the Geometry property refer to Geometry The following sample program demonstrates how a transaction po
573. ted based on the read and write access levels set in the schema when it is defined Fields and FieldBuilder Once the schema has been created fields may be defined A field is similar to a property of a class It contains a name documentation value type and unit type Fields can be a simple type an array or a map The following simple data types are allowed Type Default Value int 0 short 0 byte 0 double 0 0 float 0 0 bool false string Empty string GUID Guid Empty 00000000 0000 0000 0000 000000000000 Elementid Elementid InvalidElementld Autodesk Revit DB XYZ 0 0 0 0 0 0 Autodesk Revit DB UV 0 0 0 0 Additionally a field may be of type Autodesk Revit DB ExtensibleStorage Entity In other words an instance of another Schema also known as a SubSchema or SubEntity The default value for a field of this type is Entity with null schema and guid of Guid Empty A simple field can be created using the SchemaBuilder AddSimpleField method to specify a name and type for the field AddSimpleField returns a FieldBuilder which is a helper class for defining Fields If the type of the field was specified as Entity use FieldBuilder SetSubSchemaGUID to specify the GUID of the schema of the Entities that are to be stored in this field Use the SchemaBuilder AddArrayField method to create a field containing an array of values in the Schema with a given name and type of contained values Array fields can have all the sa
574. ted offset for a plan view Code Region Getting information on the view range view plaincopy to clipboardprint 1 private void ViewRange Document doc View view 2 1 3 if view is ViewPlan 4 5 ViewPlan viewPlan view as ViewPlan 6 PlanViewRange viewRange viewPlan GetViewRange 8 ElementId topClipPlane viewRange GetLevelId PlanViewPlane TopClipPlane 9 double dOffset viewRange GetOffset PlanViewPlane TopClipPlane 10 11 if topClipPlane IntegerValue gt 0 T2 13 Element levelAbove doc GetElement topClipPlane 14 TaskDialog Show view Name Top Clip Plane levelAbove Name r nTop Offset dOffset ft 15 16 17 ViewDrafting The drafting view is not associated with the model It allows the user to create detail drawings that are not included in the model e Inthe drafting view the user can create details in different view scales coarse fine or medium e You can use 2D detailing tools including Detail lines Reference planes Detail regions Dimensions Detail components Symbols Insulation Text These tools are the same tools used to create a detail view e Drafting views do not display model elements Use the Autodesk Revit Creation NewViewDrafting method to create a drafting view Model elements are not displayed in the drafting view I mageView The ImageView class is derived from ViewDrafting It can be used to create rendering views containing images im
575. ter areaParam BuiltInParameter ROOM_AREA provider ParameterValueProvider pvp new ParameterValueProvider new ElementId int areaParam a evaluator Tob eas Nae des e ExUIM e Poetis o Enuy new El lrerNumerreGrearer gt rule value double ruleValue 100 0f M tiltrer room whose dared is greater Chan 100 SF A nule FilterRule fRule new FilterDoubleRule pvp fnrv ruleValue 1E 6 Se are eu db essel ara meter UE db Ibis ee ElementParameterFilter filter new ElementParameterFilter fRule SR me allas o Ncc mcmssg tc wacr ine Cec NITE TUS EFEilteredElementCollector collector new FilteredElementCollector document ILisi lt Element rooms collector WherePasses fEllter ToElements Find rooms whose area is less than or equal to 100 ii Ue smi TE COL ial le eue o meda elements ElementParameterFilter lessOrEqualFilter new ElementParameterFilter fRule true collector new FilileredElemaen Collector documen IList lt Element gt lessOrEqualFounds collector WherePasses lessOrEqualFilter ToElements The following example shows how to use the FamilyStructuralMaterialTypeFilter to find all families whose material type is wood It also shows how to use an inverted filter to find all families whose material type is not wood Code Region 6 7 Find all families with wood material Use FamilyStructuralMaterialType filter to find families whose material type is Wood FamilyStructuralMaterialTypeFi
576. ter the heading for the column Columns with text that does not express numbers or dates e Left align the column header of the number column e Left align the text data e Left align data that are not used as numbers like product IDs or registration numbers Columns containing dates treat dates as text e Left align the column header of a date column e Left align the dates e Include a date format in the column header if you are presenting to an international audience to avoid confusion Column Sorter Use a column sorter when users are viewing a collection such as a large table possibly spanning multiple pages that they must scan for interesting values There are several meaningful possibilities for sorting the table and users may be more effective if they can dynamically change the column that is used for sorting the values on e Allow users to sort a collection of items by clicking on a column header e As users click on the column label the table is sorted by that column e Another click reverses the order which should be visualized using an up or down wards pointing arrow e Make sure it is visible which columns can be clicked on and which one is active now Column header 1 WF Column header 2 A 3 A EN qM Figure 217 Column sorter Often a user may need to understand complex relationships within a hierarchy of items and this can often best displayed within a tree view The user may also need to select one or more
577. terface that can be implemented to filter objects during a selection operation It has two methods that can be overridden AllowElement which is used to specify if an element is allowed to be selected and AllowReference which is used to specify if a reference to a piece of geometry is allowed to be selected The following example illustrates how to use an ISelectionFilter interface to limit the user s selection to elements in the Mass category It does not allow any references to geometry to be selected Code Region 7 4 Using ISelectionFilter to limit element selection public static IList lt Element gt GetManyRefByRectangle UIDocument doc ReferenceArray ra new ReferenceArray ISselectiontilter seller gt new Meses selec cl ae Toe exe Cure IList Element eList doc Selection PickElementsByRectangle selFilter Select multiple faces as IList lt Elem ent gt T enETDDETSV ell ele gt public class MassSelectionFilter ISelectionFilter public bool AllowElement Element element if element Category Name Mass return true return talse public bool AllowReference Reference refer XYZ point return talse The next example demonstrates the use of ISelectionFilter to allow only planar faces to be selected Code Region 7 5 Using ISelectionFilter to limit geometry selection public void SelectPlanarFaces Autodesk Revit DB Document document UrDocument ulidoc lt
578. tersect the wall and the opening element If interested only in true physical intersections an application should discard all references whose Reference is of type Element The FindNearest method behaves similarly to the Find method but only returns the intersected reference nearest to the ray origin The ReferenceWithContext return includes a proximity parameter This is the distance between the origin of the ray and the intersection point An application can use this distance to exclude items too far from the origin for a particular geometric analysis An application can also use this distance to take on some interesting problems involving analyzing the in place geometry of the model Notes e This method finds both References will be found and returned only for elements that are in front of the ray e This method will not return intersections in linked files e This method will not return intersections with elements which are not in the active design option Find elements near elements One major use for this tool is to find elements in close proximity to other elements This allows an application to use the tool as its eyes and determine relationships between elements which don t have a built in relationship already Fro example the ray tracing capability can be used to find columns embedded in walls As columns and walls don t maintain a relationship directly this class allows us to find potential candidates by tracing rays just outsi
579. tes how to get the intersection of two solids and then find the volume Code Region Volume of Solid Intersection view plaincopy to clipboardprint 1 private void ComputeIntersectionVolume Solid solidA Solid solidB D 3 1 4 5 Solid intersection BooleanOperationsUtils ExecuteBooleanOperation solidA solidB BooleanOperationsType Intersect 6 7 double volumeOfIntersection intersection Volume 8 9 Geometry Helper Classes Several Geometry Helper classes are in the API The Helper classes are used to describe geometry information for certain elements such as defining a CropBox for a view using the BoundingBoxXYZ class e BoundingBoxXYZ A 3D rectangular box used in cases such as defining a 3D view section area e Transform Transforming the affine 3D space e Reference A stable reference to a geometric object in a Revit model which is used when creating elements like dimensions e Plane A flat surface in geometry e Options User preferences for parsing geometry e XYZ Object representing coordinates in 3D space e UV Object representing coordinates in 2D space e BoundingBoxUV A 2D rectangle parallel to the coordinate axes Transforms are limited to 3x4 transformations Matrix in the Revit application transforming an object s place in the model space relative to the rest of the model space and other objects The transforms are built from the position and orientation in the model space Three dire
580. tes of Max and Min to WCS you need to convert point via the transform obtained from BoundingBoxXYZ Transform property Code Region Convert Max and Min to WCS private void ConvertMaxMinToWCS View3D view out XYZ max out XYZ min 1 Boumcumgboxx v2 Sect ronbox View sect LonBoXx Transrtorm transtorm sectionbox Iranstorm max IE TE ELBUS Olan mE Oui ce Ce ab Cua DO e Ilse min erans POR tele Ome Ss Saldos y Min View Locking The View3D class has methods and properties corresponding to the locking feature available in the Revit user interface i8 Save Orientation and Lock View e Restore Orientation and Lock View t Unlock View 1 100 HOR Baro 9 8 The View3D SaveOrientationAndLock method will save the orientation and lock the view while View3D RestoreOrientationAndLock will restore the view s orientation and lock it View3D Unlock will unlock the view if it is currently locked The IsLocked property will return whether the 3D view is currently locked ViewPlan Plan views are level based There are three types of plan views floor plan view ceiling plan view and area plan view e Generally the floor plan view is the default view opened in a new project e Most projects include at least one floor plan view and one ceiling plan view e Plan views are usually created after adding new levels to the project Adding new levels using the API does not add plan views automatically Use the static ViewPlan Create
581. text describes the contents of the window 2 Help A button in the title bar next to the close button button Help button is optional use only when a relevant section is available in the documentation Materials 3 Controls 4 Commit Buttons Layout Flow Note that many legacy dialogs in Revit still have the Help button located in the bottom right of the dialog The bulk of a dialog consists of controls used to change settings and or interact with data within an application The layout of the controls should follow the Layout Flow Spacing and Margins Grouping and Dialog Controls sections outlined below When an action control interacts with another control such as a text box with a Browse button denote the relationship by placing the RELATED controls in one of three places To the right of and top aligned with the other control Below and left aligned with the other control See Content Editor Vertically centered between related controls See List Builder See the Committing Changes section The most frequently used Commit buttons include OK Cancel Yes No Retry Close Enter Search Words Material Class lt All gt Acoustic Ceiling Tile 24 x 24 Acoustic Ceiling Tile 24 x 48 Acoustical Treatment Air Barrier Air Infiltration Barrier Carpet 1 Carpet 2 Ceramic Tile 4 Blue Concrete Concrete Cast in Place Concrete Concrete Cast in Place Lightweight Concrete Concrete Cast in Place Ligh
582. th the currently selected item See Show More Button No List View When the user needs to view and browse and optionally select sort group filter or search a flat collection of items If the list is hierarchical use Tree View or Tree Table and if the data is grouped into two or more columns use Table View instead a 88 BB 63 BB Figure 209 List View showing different ways of presenting the data There are four basic variations of this pattern that includes the following Drop down list Use a drop down list box when you only need to present a flat list of names only a single selection is required and space is limited The Microsoft Windows User Experience Guidelines should be followed when using a drop down list Boston MA Boston M Boulder CO Bountiful LIT B Bowie MD Pa Bowling Green KY Roiman Ky Figure 210 Drop down list Combo box Use a combo box when you want the functionality of the drop down list box but also need to the ability to edit the drop down list box The Microsoft Windows User Experience Guidelines should be followed when using this option including for how to decide between drop down and combo box Figure 211 The font selector in Microsoft Office 2007 is an example of a combo box List box Use when you only need to present a list of names it benefits the user to see all items and when there is sufficient room on the UI to display list box Use also
583. th the same name and number is created in the 36 view where the PlanCircuit is located 37 if null newRoom2 38 39 Give the user some information 40 TaskDialog Show Revit Room placed in Plan Circuit successfully 41 y 42 transaction Commit 43 44 45 return newRoom2 46 Once a room has been created and added to a location it can be removed from the location but still remains in available in the project by using the Room Unplace method It can then be placed in a new location Room Boundary Rooms have boundaries that create an enclosed region where the room is located e Boundaries include the following elements o Walls o Model lines o Columns o Roofs Retrieving Room Boundaries The boundary around a room is obtained from the base class method SpatialElement GetBoundarySegments The method returns null when the room is not in an enclosed region or only exists in the schedule Each room may have several regions each of which have several segments hence the data is returned in the form of a list of BoundarySegment lists The following figure shows a room boundary selected in the Revit UI Figure 138 Room boundary The size of the segment list depends on the enclosed region topology Each BoundarySegment list makes a circuit or a continuous line in which one segment joins the next The following pictures provide several examples In the following pictures all walls are Room Bound
584. that was modified by an updater that is not installed locally a task dialog is presented giving them the option to continue or cancel the synchronization The warning indicates that proceeding may cause problems with the central model when it is used with the third party updater at a later time Failure Posting and Handling The Revit API provides the ability to post failures when a user visible problem has occurred and to respond to failures posted by Revit or Revit add ins Topics in this section e Posting Failures e Handling Failures Posting Failures To use the failure posting mechanism to report problems the following steps are required 1 New failures not already defined in Revit must be defined and registered in the FailureDefinitionRegistry during the OnStartup call of the ExternalApplication 2 Find the failure definition id either from the BuiltinFailures classes or from the pre registered custom failures using the class related to FailureDefinition 3 Post the failure to the document that has a problem using the classes related to FailureMessage to set options and details related to the failure Defining and registering a failure Each possible failure in Revit must be defined and registered during Revit application startup by creating a FailureDefinition object that contains some persistent information about the failure such as identity severity basic description types of resolution and default resolution The followi
585. the Revit Based Product e Installation e Supported Programming Languages e User Manual e Documentation Conventions e What s new in this release Introduction to the Revit Platform API The Revit NET API allows you to program with any NET compliant language including Visual Basic NET C and C CLI Revit Architecture 2013 Revit Structure 2013 and Revit MEP 2013 all contain the Revit Platform API so that you can integrate your applications into Revit The three APIs are very similar and are jointly referred to as the Revit Platform API Before using the API learn to use Revit and its features so that you can better understand the relevant areas related to your programming Learning Revit can help you e Maintain consistency with the Revit Ul and commands e Design your add in application seamlessly e Master API classes and class members efficiently and effectively If you are not familiar with Revit or BIM learn more in the Revit product center at www autodesk com revit What Can You Do with the Revit Platform API You can use the Revit Platform API to e Gain access to model graphical data e Gain access to model parameter data e Create edit and delete model elements like floors walls columns and more e Create add ins to automate repetitive tasks e Integrate applications into Revit based vertical products Examples include linking an external relational database to Revit or sending model data to an analysis applicat
586. the surface as well as the secondary adjacent analytical space The GetAnalyticalOpenings method will retrieve a collection of all analytical openings in the surface The GetPolyloop method obtains the planar polygon describing the surface geometry as described in gbXML The EnergyAnalysisSpace class has numerous properties to provide more information about the analytical surface such as Height Width Corner lower left coordinate for the analytical rectangular geometry viewed from outside and an originating element description The surface type is available either as an EnergyAnalysisSurfaceType or as a gbXMLSurfaceType The gbXML surface type attribute is determined by the source element and the number of space adjacencies Possible types are Type Source element and space adjacencies Shade No associated source element and no space adjacencies Air No associated source element and at least one space adjacency ExteriorWall Source element is a Wall or a Curtain Wall there is one space adjacency nteriorWall Source element is a Wall or a Curtain Wall and there are two space adjacencies or the type Function parameter is set to Interior or CoreShaft UndergroundWall Source element is a Wall or a Curtain Wall and there is one space adjacency and if it is below grade SlabOnGrade Source element is a Floor and there is one space adjacency RaisedFloor Source element is a Floor and there is one space adjacency and it is above grade UndergroundSl
587. thod and allows for both single and multi category material takeoff schedules View lists sheet lists and keynote legends are associated with a designated category and therefore their creation methods do take a category ID as a parameter A view list is a schedule of views in the project It is a schedule of the Views category and is created using ViewSchedule CreateViewList A sheet list is a schedule of sheets in the project It is a schedule of the Sheets category and is created using the ViewSchedule CreateSheetList method A keynote legend is a schedule of the Keynote Tags category and is created using ViewSchedule CreateKeynoteLegend Revision schedules are added to titleblock families and become visible as part of titleblocks on sheets The ViewSchedule CreateRevisionSchedule method will throw an exception if the document passed in is not a titleblock family A note block is a schedule of the Generic Annotations category that shows elements of a single family rather than all elements in a category Code Region ViewSchedule CreateNoteBlock view plaincopy to clipboardprint i public ViewSchedule ViewSchedule CreateNoteBlock Document document ElementId familyId The second parameter is the ID of the family whose elements will be included in the schedule Code Region Creating a note block schedule view plaincopy to clipboardprint 1 Get first ElementId of AnnotationSymbolType families 2 ElementId annotationSymbo
588. tion If the created instance needs to be oriented in a non default direction If the instance needs to be associated to a reference level Creates a level based brace or beam given its curve This is the recommended method to create Beams and Braces Creates instance in an arbitrary location If it is hosted on an element floor etc and associated to a reference level T n 1 If it is associated to a reference level If it is hosted on an element floor etc StructuralType Detail Component Line FamilySymbol View Applies only to 2D family line based detail symbols The structural instance will be of zero length after creation Extend it by setting its curve FamilyInstance Location as LocationCurve using LocationCurve Curve property You can simplify your code and improve performance by creating more than one family instance at a time using Document NewFamilyInstances This method has a single parameter which is a list of FamilyInstanceCreationData objects describing the family instances to create Code Region 12 2 Batch creating family instances view plaincopy to clipboardprint 1 ICollection ElementId BatchCreateColumns Autodesk Revit DB Document document Level level DEN 3 List FamilyInstanceCreationData fiCreationDatas new List FamilyInstanceCreationData 4 D ICollection ElementId elementSet null 6 E Try to get a FamilySymbol 8 FamilySymbol familySymbol null 9 FilteredElementCol
589. tion e Array e BIM e Class e Events e Iterator e Method e Namespace e Overloading e Properties e Revit Families e Revit Parameters e Revit Types e Sets e Element ID e Element UID Array Arrays hold a series of data elements usually of the same size and data type Individual elements are accessed by their position in the array The position is provided by an index which is also called a subscript The index usually uses a consecutive range of integers but the index can have any ordinal set of values BIM Building Information Modeling is the creation and use of coordinated internally consistent computable information about a building project in design and construction In a BIM application the graphics are derived from the information and are not the original information itself like in general CAD applications Class In object oriented programming OOP classes are used to group related Properties variables and Methods functions together A typical class describes how those methods operate upon and manipulate the properties Classes can be standalone or inherited from other classes In the latter a class from which others are derived is usually referred to as a Base Class Events Events are messages or functions that are called when an event occurs within an application For example when a model is saved or opened Iterator An iterator is an object that allows a programmer to traverse through all elements
590. to Revit for rendering Topics in this section Point Cloud Client Point Cloud Engine Point Cloud Client The point cloud client API supports read and modification of point cloud instances within Revit The points supplied by the point cloud instances come from the point cloud engine which is either a built in engine within Revit or a third party engine loaded as an application A client point cloud API application doesn t need to be concerned with the details of how the engine stores and serves points to Revit Instead the client API can be used to create point clouds manipulate their properties and read the points found matching a given filter The main classes related to point clouds are PointCloudType type of point cloud loaded into a Revit document Each PointCloudType maps to a single file or identifier depending upon the type of Point Cloud Engine which governs it PointCloudInstance an instance of a point cloud in a location in the Revit project PointCloudFilter a filter determining the volume of interest when extracting points PointCollection a collection of points obtained from an instance and a filter Pointlterator an iterator for the points in a PointCollection CloudPoint an individual point cloud point representing an X Y Z location in the coordinates of the cloud and a color Creating a Point Cloud To create a new point cloud in a Revit document create a PointCloudType and then use it to create a Po
591. top left and expands to the right and to the bottom Implementation Notes Here are the some steps to consider when implementing a dynamic layout e Break the design on sections based on the structure of the content and flow you would like to achieve when container s size changes e Define the minimum maximum and other size constrains for the various sections and control used This is usually driven by the purpose of the data type we are presenting images supplemental information and controls e Consider alignment that is how the content will flow when re sized Consider which items should be static and which dynamic and how they are expandable which should usually be for left to right languages and dialogs should flow to the right and bottom being anchored and aligned to the top and left For guidelines on how different controls should handle resizing see the table below Control Content X Re sizable Moveable Button Static No Yes Link Static No Yes Radio Button Static No Yes Spin Control Static No Yes based on the element to which it is attached Slider Static X Direction Yes Scroll Bar Static X Direction Yes Tab Dynamic X and Y Direction Yes but not smaller then the biggest control contained Progressive Disclosure Dynamic X and Y Direction Yes but not smaller then the biggest control contained Check Box Static No Yes Drop Down List Dynamic X Direction Yes but not smaller then the biggest text contained Combo Box Dynamic X a
592. tor maintains an internal cache for geometry it has already processed If you intend to calculate geometry for several elements in the same project you should use a single instance of this class Note that the cache will be cleared when any change is made to the document e Floors are almost never included in as boundary elements Revit uses the 2D outline of the room to form the bottom faces and does not match them to floor geometry e Openings created by wall cutting features such as doors and windows are not included in the returned faces e The geometry calculations match the capabilities offered by Revit In some cases where Revit makes assumptions about how to calculate the volumes of boundaries of rooms and spaces these assumptions will be present in the output of the utility The following example calculates a room s geometry and finds its boundary faces Code Region Face Area using SpatialElementGeometry Calculator view plaincopy to clipboardprint 1 SpatialElementGeometryCalculator calculator new SpatialElementGeometryCalculator doc Ze 3 compute the room geometry 4 SpatialElementGeometryResults results calculator CalculateSpatialElementGeometry room D 6 get the solid representing the room s geometry 7 Solid roomSolid results GetGeometry 8 9 foreach Face face in roomSolid Faces 10 11 double faceArea face Area 12 13 get the sub faces for the face of the room 14 IList lt Spatial
593. trics section from the Microsoft guidelines Tip Visual Studio makes it easy to follow these guidelines using a combination of Margin and Padding properties and the Snap lines feature For more information see Walkthrough Laying Out Windows Forms Controls with Padding Margins and the Auto Size Property Spacing and Margins Table Element Placement Dialog units Relative pixels Dialog box margins 7 on all sides 11 on all sides Between text labels and their associated controls for example 3 5 text boxes and list boxes label Between related controls 4 7 E Check box T Y Check box Between unrelated controls 7 11 Label List Ite eee A Pee f Check Bo First control in a group box 11 down from the top of the 16 down from the top of the group box align vertically to group box align vertically to the group box title the group box title labet List It AA eres bar J d pea box Group Box Check box abel 9 Option button label i Option button label E Check box label E Check box label Grouping Group boxes are the most common solution used to explicitly group related controls together in a dialog and give them a common grouping A group box should include e Two or more related controls Between controls in a group box Between horizontally or vertically arranged buttons Last control in a group box From the left edge of a group box Text label beside a control B
594. ttings The View DisplayStyle property uses the DisplayStyle enumeration and corresponds to the display options available at the bottom of the Revit window as shown below 2 Graphic Display Options E Wireframe C1 Hidden Line ET Shaded ET Consistent Colors El Realistic Because setting a view s display style to raytrace enters a special restricted mode with limited capabilities it is not permitted to directly assign the display style to this value The View DetailLevel property uses the ViewDetailLevel enumeration and corresponds to the detail level options available at the bottom of the Revit window as shown below lCoarse zx Co ep td c E The ViewDetailLevel enumeration includes Undefined in the case that a given View does not use detail level Temporary View Modes The View class allows for control of temporary view modes The View EnableRevealHiddenMode method turns on the reveal hidden elements mode for the view View EnableTemporaryAnalyticalDisplayMode enables temporary display of Analytical Model categories only And the View DisableTemporaryViewMode will disable the specified temporary view mode The DisableTemporaryViewMode method takes a TemporaryViewMode enum The possible options are shown below Member Name Description RevealHiddenElements The reveal hidden elements mode TemporaryHidelsolate The temporary hide isolate mode WorksharingDisplay One of the worksharing display modes AnalyticalModel The
595. tural Integrators structuralintegrators com products si xchange php The key to linking Revit Structure to other analysis applications is to set up the mapping relationship between the objects in different object models That means the difficulty and level of the integration depends on the similarity between the two object models For example during the product design process design a table with at least the first two columns in the object mapping in the following table one for Revit Structure API and the other for the structural analysis application shown as follows Table 62 Revit and Analysis Application Object Mapping Revit Structural API Analysis Application Import to Revit StructuralColumn Column NewStructuralColumn Property Location Read only Parameter Analyze as Editable AnalyticalModel Profile Read only RigidLink Read only Material Analytical Links An analytical link is an element connecting 2 separate analytical nodes which has properties such as fixity state Analytical links can be created automatically by Revit from analytical beams to analytical columns during modeling based on certain rules And they can also be created manually both in the Revit Ul and using the Revit API In the Revit API an analytical link is represented by the AnalyticalLink class Fixity values are available from its associated AnalyticalLinkType The example below demonstrates how to read all of the AnalyticalLinks in the docum
596. tures By Category L BeVew All Mane Invert E spand All Include categories from all disciplines in the list above IK 1 T e E s 1 2 Z La TEEHB IK KI fF B x IK tte IK amp amp amp amp T amp TY TI TI FATT mMm 7 co o 9 S AL m m lectrical Equipment lectrical Fistures ntaurage ES IK IK s Is Override Host Lavers Cut Line Styles Override Model Patterns Items marked By Category use this project s l Model Object Styles Object Styles Cut Pattern Color Surface Pattern Color eae ey eras AGB 127 127 127 Cancel Apply Help Figure 21 Visibility by Category An element s category is determined by the Category ID e Category IDs are represented by the Elementld class e Imported Category IDs correspond to elements in the document e Most categories are built in and their IDs are constants stored in Elementlds e Each built in category ID has a corresponding value in the BuiltlnCategory Enumeration They can be converted to corresponding BuiltInCategory enumerated types e Ifthe category is not built in the ID is converted to a null value Code Region 5 2 Getting element category Element selectedElement null toreo c N neie ment e lin dor men dee onmi lle qme selectedElement e break Just get one selected element Gee e e E OUS 7 ua ea ee o e aaa qoe
597. turned off both MaxEnabled property and MinEnabled property return false Op uy bo Not cop veo This property indicates whether the view s crop box face can be used to clip the element s view If BoundingBoxXYZ is retrieved from the View3D SectionBox property the return value depends on whether the Section Box property is selected in the 3D view Properties dialog box If so all Enabled properties return true If BoundingBoxXYZ is retrieved from the Element BoundingBox property all the Enabled properties are true Bounds Wrapper for the Max Min properties BoundEnabled Wrapper for the MaxEnabled MinEnabled properties The following code sample illustrates how to rotate BoundingBoxXYZ to modify the 3D view section box Code Region 20 9 Rotating BoundingBoxXYZ private void RotateBoundingBox View3D view3d ISO niox 789 view d secu Llonsox if false box Enabled TaskDialog Show Revit The section box for View3D isn t Enable return Create a rotation transform OG AO ea SAA Oe Opa 20A aes i Me ver 7 OO QE Iran Corm rora te ns fom olet OE SEE OI Oiled a 72 MANSO E Ven sD sn ete TE OUI OP Whee Eile 16 OE EE Omnia co box Iransiorm Ox e ams me Multiply rotate views d sect lomo DOx BoundingBoxUV BoundingBoxUV is a value class that defines a 2D rectangle parallel to the coordinate axes It supports the Min and Max data members Together they define the BoundingBoxUV s boundary
598. tusInitial Object sender DocumentSavingAsEventArgs args Document doc args DoOcCuUmMmenl Proect Ini o Tron o doe Pro norna Lon EE a e T e ae a 1S a evedielole fer pro eee E E Mie o Oo mor Suc eine Ie BLISS mie y Sie Olli ike Se UE Us cancel the save as process args Cancel true MessageBox Show Status project parameter is not set Save is aborted j Note that although most event arguments have the Cancel and Cancellable properties the DocumentChanged and FailuresProcessing events have corresponding Cancel and IsCancellable methods 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 when those changes are about to be committed at the end of a transaction Revit API applications can create updaters by implementing the lUpdater interface and registering it with the UpdaterRegistry class Registering includes specifying what changes in the model should trigger the updater Topics in this section e Implementing lUpdater e The Execute method e Registering Updaters e Exposure to End User Implementing Updater The lUpdater interface requires that the following 5 methods to be implemented e GetUpdaterld This method should return a globally unique Id for the Updater consisting of the application Id plus a GUID for this Updater This method is called once during registration of the
599. tweight Concrete 4 ksi Concrete Precast Concrete Curtain Wall Mullions Default Default Floor Default Form Default Light Source Default Mass Floor Default Roof Default Wall Default Zoning Envelope Door Frame Door Panel EIFS Exterior Insulation and Finish System D alo gt When viewing a dialog within a user interface the user has multiple tasks to accomplish How the information is designed and laid out must support the user in accomplishing their task s Keeping this in mind it is important to remember users e Scan not read an interface and then stop when they get to what they were looking for and ignore anything beyond it e Focus on items that are different e Not scroll unless they need to Lay out the window in such a way that suggests and prompts a path with a beginning middle and end This path should be designed to be easily scanned The information and controls in the middle of the path must be designed to be well balanced and clearly delineate the relationship between controls Of course not all users follow a strictly linear path when completing a task The path is intended for a typical task flow Variation A Top Down Place Ul items that 1 Initiate a task in the upper left corner or upper center 2 User must interact with to complete the task s in the middle 3 Complete the task s in the lower right corner In this example Materials dialog the user
600. u plan to localize the user interface into languages other than English be aware of the space requirements The English language is very compact so translated text usually ends up taking up more space 30 on average for longer strings 100 or more on short strings a word or short phrase This can present problems if translated text is inserted into dialog boxes that were designed for an English product because there is not usually sufficient space in available to fit the translated text The common solution to this problem is to resize the dialog box so that the translated text fits properly but most times this isn t the best solution Instead by careful design of the dialog box by the developer the same dialog box resource can be used for most if not all languages without the need for costly and time consuming re engineering This paper tells you how to design global dialog boxes These following design rules must be adhered to at all times to prevent globalization and localization problems e The English dialog must be at least 30 smaller than the minimum screen size specified by the product e Adialog must be designed with the following amounts of expansion in mind This amount of extra space should look good in English and avoid resizing for most localization CHARACTERS PERCENTAGE 1 5 characters 100 6 10 characters 40 11 100 characters 30 100 characters or greater 20 e Make the invisible control frame around text controls f
601. ulle Suceeeceex public void application _DocumentOpened object sender DocumentOpenedEventArgs args get document from event args Document doc args Document ITransaction Lransactlion Mew Iransgactlon doc TEdit Address if Transaction So lart lransactlonstati s Starred doc Eus oe TUNE CONSTI ede Lon Address United States Massachusetts Waltham 1560 Trapelo Road AIMS eve ion C ommi Canceling Events Events that are triggered before an action has taken place i e DocumentSaving are often cancellable Use the Cancellable property to determine if the event can be cancelled For example you may want to check some criteria are met in a model before it is saved By registering for the DocumentSaving or DocumentSavingAs event for example you can check for certain criteria in the document and cancel the Save or Save As action Once cancelled an event cannot be un cancelled Note that if a pre event is cancelled other event handlers that have subscribed to the event will not be notified However handlers that have subscribed to a post event related to the pre event will be notified The following event handler for the DocumentSavingAs event checks if the ProjectInformation Status parameter is empty and if it is cancels the SaveAs event Note that if your application cancels an event it should offer an explanation to the user Code Region 24 2 Canceling an Event private void CheckProjectSta
602. ument document 1 System Collections Generic HashSet double sizes new HashSet double FilteredElementCollector collectorPipeType new FilteredElementCollector document collectorPipeType OfClass typeof PipeType IEnumerable PipeType pipeTypes collectorPipeType ToElements Cast PipeType foreach PipeType pipeType in pipeTypes RoutingPreferenceManager rpm pipeType RoutingPreferenceManager int segmentCount rpm GetNumberOfRules RoutingPreferenceRuleGroupType Segments for int index 0 index segmentCount index RoutingPreferenceRule segmentRule rpm GetRule RoutingPreferenceRuleGroupType Segments index Segment segment document GetElement segmentRule MEPPartId as Segment foreach MEPSize size in segment GetSizes sizes Add size NominalDiameter Use a hash set to remove duplicate sizes among Segments and PipeTypes List lt double gt sizesSorted sizes ToList sizesSorted Sort return sizesSorted Advanced Topics Topics in this section e Storing Data in the Revit model e Transactions e Events e External Events e Dynamic Model Update e Failure Posting and Handling e Performance Adviser e Analysis e Place and Locations e Worksharing e Construction Modeling e Linked Files e IFC Export Storing Data in the Revit model The Revit API provides two methods for storing data in the Revit model The first is using shared parameters The Revit API gives
603. uments using the Application methods in the following table Table 4 Create Document in the API Method Event view plaincopy to clipboardprint DocumentCreated 1 Document NewProjectDocument string templateFileName view plaincopy to clipboardprint DocumentCreated i Document NewFamilyDocument string templateFileName view plaincopy to clipboardprint Document Created i Document NewProjectTemplateDocument string templateFilename Each method requires a template file name as the parameter The created document is returned based on the template file Save and Close a Document The Document class provides methods to save or close instances Table 5 Save and Close Document in API Method Event Save DocumentSaved SaveAs DocumentSavedAs Close DocumentClosed SaveAs has 3 overloads Two overloads take the filename as an argument and but an exception will be thrown if another file exists with the given filename The third overload takes a filename as an argument as well as a second argument that specifies whether to rename the file and or whether to overwrite and existing file if it exists Close has two overloads One takes a Boolean argument that indicates whether to save the file before closing it The second overload takes no arguments and if the document was modified the user will be asked if they want to save the file before closing This method will throw an exception if the document s path name is not already
604. unbound ellipse parameter for evaluation from O to 2n Used for splines sketched in various NURBS NurbSpline A non uniform rational B spline p l inne Revit tools plus imported geometry Used for tools like Curve by Points and flexible ducts pipes plus imported geometry A spline interpolate between a set of points Hermite HermiteSpline Mathematical representations of all of the Revit curve types can be found here Mathematical representations of curve types This section describes the curve types encountered in Revit geometry their properties and their mathematical representations Bound lines Bound lines are defined by their endpoints In the Revit API obtain the endpoints of the line from the Curve level get_EndPoint method The equation for a point on a bound line in terms of the normalized parameter u and the line endpoints is P u P u P B4 Unbound lines Unbound lines are handled specially in the Revit API Most curve properties cannot be used however Evaluate and ComputeDerivatives can be used to obtain locations along the curve when a raw parameter is provided The equation for a point for an unbound line in terms of the raw parameter u and the line origin and normalized direction vector is P u P uV Arcs and Circles Arcs and Circles are represented in the Revit API by the Arc class They are defined in terms of their radius center and vector normal to the plane of the arc whic
605. undary curves and riser curves e CreateStraightRun Creates a straight run e CreateSpiralRun Creates a spiral run by providing the center start angle and included angle Adding Landings The static StairsLanding CreateSketchedLanding method creates a customized landing between two runs by providing the closed boundary curves of the landing One of the inputs to the CreateSketchedLanding method is a double value for the base elevation The elevation has following restriction e The base elevation is relative to the base elevation of the stairs e The base elevation will be rounded automatically to a multiple of the riser height e The base elevation should be equal to or greater than half of the riser height Example The following example creates a new Stairs object two runs one sketched one straight and a landing between them Code Region Creating Stairs Runs and a Landing view plaincopy to clipboardprint 1 private ElementId CreateStairs Document document Level levelBottom Level levelTop Zo o 3 StairsEditScope newStairsScope new StairsEditScope document New Stairs 4 ElementId newStairsId newStairsScope Start levelBottom Id levelTop Id 5 6 Transaction stairsTrans new Transaction document Add Runs and Landings to Stairs 7 stairsTrans Start 8 9 Create a sketched run for the stairs 10 IList Curve bdryCurves new List Curve 11 IList Curve riserCurves new List Curve
606. ures when a transaction is about to be rolled back so that the user is not bothered to hit Cancel by using the Transaction SetFailureHandlingOptions method Handling Failures Normally posted failures are processed by Revit s standard failure resolution UI at the end of a transaction specifically when Transaction Commit or Transaction Rollback are invoked The user is presented information and options to deal with the failures If an operation or set of operations on the document requires some special treatment from a Revit add in for certain errors failure handling can be customized to carry out this resolution Custom failure handling can be supplied e Fora given transaction using the interface IFailuresPreprocessor e Forall possible errors using the FailuresProcessing event Finally the API offers the ability to completely replace the standard failure processing user interface using the interface IFailuresProcessor Although the first two methods for handling failures should be sufficient in most cases this last option can be used in special cases such as to provide a better failure processing Ul or when an application is used as a front end on top of Revit Overview of Failure Processing It is important to remember there are many things happening between the call to Transaction Commit and the actual processing of failures Auto join overlap checks group checks and workset editability checks are just to name a few These
607. us static methods to get the Elementld of the ConceptualConstructionType for different aspects of a building such as walls and windows in a given document Another property of MassSurfaceData is CategoryldForConceptualSurfaceType which provides the mass subcategory Elementld used for its ConceptualSurfaceType ConceptualSurfaceType represents a conceptual BIM object category to assign to faces in Mass geometries There is one ConceptualSurfaceType element for each of the Mass Surface Subcategories Using the static method ConceptualSurfaceType GetByMassSubCategoryld the ConceptualSurfaceType for a MassSurfaceData can be obtained from the mass subcategory id When Conceptual Energy Analysis is enabled in a Revit Project massing faces will be assigned to the subcategories of Mass category with which these ConceptualSurfaceType s are associated A default ConceptualConstructionType is associated with the ConceptualSurfaceType This default ConceptualConstructionType is assigned to Mass faces with the corresponding subcategory Changing the default ConceptualConstructionType associated with the ConceptualSurfaceType will update the ConceptualConstruction type for all Mass faces of that subcategory for which the user has not specifically provided an override value MassInstanceUtils The MassInstancesUtils utility class provides static methods to get information about a mass instance such as the total occupiable floor area or total building volume represent
608. ut it can create SubTransactions The command must report its success or failure status with the Result return value e TransactionMode Manual Revit will not create a transaction but it will create an outer transaction group to roll back all changes if the external command returns a failure 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 transactions 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 Revit will discard all changes made to the model e 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 only use methods that read from the model 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 C
609. ut placeholder elements into a system when the exact design of the layout is not yet know Using placeholder ducts and pipes can allow for a well connected system while the design is still unknown and then which can then be elaborated in the final design at a later stage The two static methods Duct CreatePlaceholder and Pipe CreatePlaceholder create placeholder elements The IsPlaceholder property of Duct and Pipe indicates whether they are a placeholder element or not When ready to create actual ducts and pipes from the placeholders use the MechanicalUtils ConvertDuctPlaceholders and PlumbingUtils ConvertPipePlaceholders methods to convert a set of placeholder elements to ducts and pipes Once conversion succeeds the placeholder elements are deleted The new duct pipe and fitting elements are created and connections are established Systems Creating a new system New piping and mechanical systems can be created using the Revit API NewPipingSystem and NewMechanicalSystem both take a Connector that is the base equipment connector such as a hot water heater for a piping system or a fan for a mechanical system They also take a ConnectorSet of connectors that will be added to the system such as faucets on sinks in a piping system The last piece of information required to create a new system is either a PipeSystemType for NewPipingSystem or a DuctSystemType for NewMechanicalSystem In the following sample a new SupplyAir duct
610. ut restrictions on groups and arrays e Arrays are not supported by most annotation symbols Delete The Revit Platform API provides Delete methods to delete one or more elements in the project Table 23 Delete Members Member Description Delete Element Delete an element from the project Delete Elementld Delete an element from the project using the element ID Delete ICollection Elementld Delete several elements from the project by their IDs You can delete the element specified using the element object or the Elementld These methods delete a specific element and any elements dependent on it Code Region Deleting an element based on object view plaincopy to clipboardprint 1 private void DeleteElement Autodesk Revit DB Document document Element element 2 ER Delete a selected element 4 ICollection Autodesk Revit DB ElementId deletedIdSet document Delete element T Ge if 0 deletedIdSet Count 7 8 throw new Exception Deleting the selected element in Revit failed 9 10 11 String prompt The selected element has been removed and 12 prompt deletedIdSet Count 1 13 prompt more dependent elements have also been removed 14 15 Give the user some information 16 TaskDialog Show Revit prompt Code Region Deleting an element based on Elementid view plaincopy to clipboardprint CON dl UA UN A private void DeleteElement Autodesk Revit DB Document
611. ve View The following picture illustrates how a perspective view is created Back clipping plane Projection plane j Crop box F n VA IN IN CropBox Min Front clipping IR l planes E NN i da BET 3D model De Viewer Target point CropBox Max Figure 96 Perspective projection e The straight projection rays pass through each point in the model and intersect the projection plane to form the projection contents e To facilitate the transformation from the world coordinate onto the view plane the viewing coordinate system is based on the viewer e ts origin represented by the View Origin property is the viewer position e The viewer s world coordinates are retrieved using the View3D EyePosition property Therefore in 3D views View Origin is always equal to View3D EyePosition e As described the viewing coordinate system is determined as follows o The X axis is determined by View RightDirection o The Y axis is determined by View UpDirection o The Z axis is determined by View ViewDirection e The view direction is from the target point to the viewer in the 3D space and from the screen to the viewer in the screen space The static method View3D CreatePerspective method can be used to create new perspective views Code Region View3D CreatePerspective view plaincopy to clipboardprint i public static View3D View3D CreatePerspective Document document ElementId viewFamilyTypeld
612. veAndRestoreUsers Document doc 2 3 get or create a WorksharingDisplaySettings current active document 4 WorksharingDisplaySettings displaySettings WorksharingDisplaySettings GetOrCreateWorksharingDisplaySettings doc 5 6 get all users with GraphicOverrides 7 ICollection string users displaySettings GetAllUsersWithGraphicOverrides 8 9 remove the users from the display settings they will not have graphic overrides anymore 10 ICollection lt string gt outUserList 11 displaySettings RemoveUsers doc users out outUserList 125 13 show the current list of removed users 14 ICollection string removedUsers displaySettings GetRemovedUsers 15 16 String message Current list of removed users 17 if removedUsers Count gt 18 19 foreach String user in removedUsers 20 21 message n user DM 23 24 else 25 26 message Empty 27 28 29 TaskDialog Show Users Removed message 30 31l restore the previously removed users 327 int number displaySettings RestoreUsers outUserList 335 34 again show the current list of removed users 35 it should not contain the users that were restored 36 removedUsers displaySettings GetRemovedUsers 37 38 message Current list of removed users 39 if removedUsers Count gt 0 40 41 foreach String user in removedUsers 42 43 message Mn user
613. vide a button with a label such as Preview or Show more The double brackets should point towards where the new information pane will be presented When opened the double brackets should switch to indicate how the additional pane will be closed See Figure 207 Materials dialog from Revit for an example Dialog Launcher A button with ellipses that launches a separate dialog This is typically used to provide a separate UI for editing a selected item Filter Rules aer y Interior zx Figure 233 Dialog launcher button as implemented in the Revit View Filters dialog Committing Changes Modal dialogs are used to make changes to data within the project file Use when there is an editor a series of edits have been queued up in a modal dialog or form and need to be committed at once If the dialog is purely informational in nature use a Task Dialog which has its own committing rules Each modal dialog or web form must have a set of commit buttons for committing the changes and or canceling the task and or closing the dialog Actual control size 30 DLUs 75 pixels 1 Cancel 14 DLUs 23 pixels ok Ji Cancel 14 DLUs 23 pixels F l 4 DLUs 6 pixels Visible size The wsible size is smaller than the AQ DLUs 73 pixels control size because there is a s 73 pixels transparent 1 pixel border around the outside of the control T 13DLUs 21 pixels at ie 2 DLUs 8 pixels F
614. w do add new concrete beam and column sizes to a model A Take a look at the FrameBuilder sample code in the SDK Q How do view the true deck layer A There is an example in the SDK called DeckProperties that provides information about how to get the layer information for the deck The deck information is reported in exactly the same way as it is in the Ul The deck dimension parameters are shown as follows ion ala Sia Figure 170 Deck dimension parameters Q How do tell when have a beam with a cantilever A There is no direct way in the Revit database to tell if a beam has a cantilever However one or more of the following options can give you a good guess at whether a section is a cantilever There are two parameters called Moment Connection Start and Moment Connection End If the value set for these two is not None then you should look and see if there is a beam that is co linear and also has the value set to something other than None Also ask the user to make sure to select Cantilever Moment option rather than Moment Frame option Trace the connectivity back beyond the element approximately one or two elements Look at element release conditions Q When exporting a model containing groups to an external program the user receives the following error at the end of the export Changes to group Group 1 are allowed only in group edit mode Use the Edit Group command to make the change to all instances of the gr
615. wType Rendering ViewType Report ViewType Schedule ViewType Section ViewType ThreeD ViewType Walkthrough Class Type Elements ViewPlan Elements ViewPlan Elements View Elements ViewSection Elements ViewDrafting Elements ViewSheet Elements ViewSection Elements ViewPlan Elements ViewPlan Elements View Elements View Elements PanelScheduleView Elements View Elements ViewDrafting Elements View Elements ViewSchedule Elements ViewSection Elements View3D Elements View3D This example shows how to use the ViewType property of a view to determine the view s type Code Region Determining the View type view plaincopy to clipboardprint 1 public void GetViewType Autodesk Revit DB View view 2 221 3a Get the view type of the given view and format the prompt string 4 String prompt The view is 5 Ge Switch view ViewType Te 8 case ViewType AreaPlan 9 prompt an area view 10 break 11 case ViewType CeilingPlan 12 prompt a reflected ceiling plan view 13 break 14 case ViewType ColumnSchedule 15 prompt a column schedule view 16 break 17 case ViewType CostReport 18 prompt a cost report view 19 break 20 case ViewType Detail 21 prompt a detail view 22 break 235 case ViewType DraftingView 24 prompt a drafting view 254 break 26 case ViewType DrawingSheet 27 prompt a drawing sheet view 28 break 29 case ViewType Elev
616. while the Face GetRegions method will return a list of faces one for the main face of the object hosting the Split Face such as wall of floor and one face for each Split Face region The FaceSplitter class represents an element that splits a face The FaceSplitter SplitElementid property provides the id of the element whose face is split by this element The FaceSplitter class can be used to filter and find these faces by type as shown below Code Region Find face splitting elements view plaincopy to clipboardprint 1 Autodesk Revit DB Options opt app Create NewGeometryOptions 2 opt ComputeReferences true 3 opt IncludeNonVisibleObjects true 4 FilteredElementCollector collector new FilteredElementCollector doc 5 ICollection FaceSplitter splitElements collector OfClass typeof FaceSplitter Cast FaceSplitter ToList 6 foreach FaceSplitter faceSplitter in splitElements 7 8 Element splitElement doc GetElement faceSplitter SplitElementId 9 Autodesk Revit DB GeometryElement geomElem faceSplitter get_Geometry opt Tos foreach GeometryObject geom0bj in geomElem 11 12 Line line geomObj as Line 13 if line null 14 15 XYZ endi line get EndPoint 0 16 XYZ end2 line get_EndPoint 1 17 double length line ApproximateLength 18 19 20 Face types Revit uses a variety of curve types to represent face geometry in a document These include Face type
617. wing set You can retrieve or modify the number using the SheetNumber property The number must be unique otherwise an exception is thrown when you set the number to a duplicate value The following example illustrates how to create and print a sheet view Begin by finding an available title block in the document using a filter in this case and use it to create the sheet view Next add a 3D view The view is placed with its lower left hand corner at the center of the sheet Finally print the sheet by calling the View Print method Code Region Creating a sheet view view plaincopy to clipboardprint 1 private void CreateSheetView Autodesk Revit DB Document document View3D view3D 2o 3 4 Get an available title block from document 5 IEnumerable lt FamilySymbol gt familyList from elem in new FilteredElementCollector document 6 OfClass typeof FamilySymbol 7 OfCategory BuiltInCategory OST TitleBlocks 8 let type elem as FamilySymbol 9 where type Name Contains E1 10 select type 11 12 Create a sheet view 13 ViewSheet viewSheet ViewSheet Create document familyList First Id 14 if null viewSheet 15 16 throw new Exception Failed to create new ViewSheet 17 18 19 Add passed in view onto the center of the sheet 20 if Viewport CanAddViewToSheet document viewSheet Id view3D Id 21 224 BoundingBoxUV sheetBox viewSheet Outline 23 double yPosition sheetBox Max
618. with the material In this chapter you learn how to access material elements and how to manage the Material objects in the document Walkthrough Get Materials of a Window provides a walkthrough showing how to get a window material Topics in this section e General Material Information e Material Management e Element Material General Material Information Before you begin the walkthrough read through the following section for a better understanding of the Material class All Material objects can be retrieved using a Material class filter Material objects are also available in Document Category Element Face and so on and are discussed in the pertinent sections in this chapter Wherever you get a material object it is represented as the Material class A material will have one or more aspects pertaining to rendering appearance structure or other major material category Each aspect is represented by properties on the Material class itself or via one of its assets structural or thermal The StructuralAsset class represents the properties of a material pertinent to structural analysis The ThermalAsset class represents the properties of a material pertinent to energy analysis Code Region 19 3 Getting material properties view plaincopy to clipboardprint 1 private void ReadMaterialProps Document document Material material 2 3 ElementId strucAssetId material StructuralAssetId 4 if strucAssetId ElementId InvalidEl
619. xel elemen sere foreach Autodesk Revit DB Element elements in collection if elements is Wall newselectedklenentoer Add elements 41 Set the created element sec es current select element set uidoc SsSelection Elements newSelectedElementsSet 7 Solve tnie user some INi ormation if O newSelectedElementSet Size TaskDra log o NOn S Revit Urddo e selection Elemente suze lo salino at Wallis are selected j else TaskDialog Show Revit No Walls have been selected User Selection The Selection class also has methods for allowing the user to select new objects or even a point on screen This allows the user to select one or more Elements or other objects such as an edge or a face using the cursor and then returns control to your application These functions do not automatically add the new selection to the active selection collection e The PickObject method prompts the user to select an object in the Revit model e The PickObjects method prompts the user to select multiple objects in the Revit model e The PickElementsByRectangle method prompts the user to select multiple elements using a rectangle e The PickPoint method prompts the user to pick a point in the active sketch plane e The PickBox method invokes a general purpose two click editor that lets the user to specify a rectangular area on the screen The type of object to be selected is specified when calling PickOb
620. y PushButton has the AvailabilityClassName property which can be used to set the name of an IExternalCommandAvailability interface that controls when the command is available Code Region Adding a push button view plaincopy to clipboardprint private void AddPushButton RibbonPanel panel PushButton pushButton panel AddItem new PushButtonData HelloWorld Helloworld D HelloWorld d1l1l HelloWorld CsHelloWorld as PushButton Set the large image shown on button pushButton LargeImage 1 2 3 4 S 6 pushButton ToolTip Say Hello World 7 8 9 new BitmapImage new Uri D Sample HelloWorld bin Debug 39 Globe_32x32 png al o Drop down buttons Drop down buttons expand to display two or more commands in a drop down menu In the Revit API drop down buttons are referred to as PulldownButtons Horizontal separators can be added between items in the drop down menu Each command in a drop down menu can also have an associated Largelmage as shown in the example above Split buttons Split buttons are drop down buttons with a default push button attached The top half of the button works like a push button while the bottom half functions as a drop down button The Option One button in Figure 13 is a split button Initially the push button will be the top item in the drop down list However by using the IsSynchronizedWithCurrentltem property the default command which is displayed as the push button t
621. y switch to a contextual tab upon selection This option is set to automatically switch by default For some API applications it may be favorable to have this option disabled to prevent users from being switched away from the Add ins or Analyze tab In these cases it is best to inform users of this option in the documentation and or as informational text in the installer user interface Number of Panels per Tab Each API application SHOULD add only one panel to either the Add Ins tab Panel Layout The following guidelines define the proper way to lay out a panel on the Add ins tab The following panel under General Layout provides an example to follow General layout Area Legend Roum Z bi ll Tag ll Room amp rea Figure 236 Room amp Area panel in the 2011 Revit products A panel SHOULD have a large button as the left most control This button SHOULD be the most commonly accessed command in the application The left most button icon will represent the entire panel when it collapses see Panel Resizing and Collapsing below This button MAY be the only button in the group or this button MAY be followed by a large button and or a small button stack Panels SHOULD NOT exceed three columns If more controls are necessary use a drop down button Panels SHOULD only contain controls for launching commands and controlling the application Controls for managing settings or launching help and about this applic
622. y Material Material material document GetElement materialId as Material Create a new property set that can be used by this material StructuralAsset strucAsset new StructuralAsset My Property Set StructuralAssetClass Concrete strucAsset Behavior StructuralBehavior Isotropic strucAsset Density 232 0 WON DU UN BP 10 Assign the property set to the material 11 PropertySetElement pse PropertySetElement Create document strucAsset 12 material SetMaterialAspectByPropertySet MaterialAspect Structural pse Id Deleting Materials To delete a material use e Document Delete Document Delete is a generic method See Editing Elements for details Element Material One element can have several elements and components For example Familylnstance has SubComponents and Wall has CompoundStructure which contain several CompoundStructureLayers For more details about SubComponents refer to the Family Instances section and refer to Walls Floors Roofs and Openings for more information about CompoundStructure In the Revit Platform API get an element s materials using the following guidelines e f the element contains elements get the materials separately e f the element contains components get the material for each component from the parameters or in specific way see Material section in Walls Floors Roofs and Openings e f the component s material returns null get the material from the correspo
623. y a small subset would ever be used at one time Task dialogs cannot display other controls such as text inputs list boxes combo boxes check boxes etc They also only accommodate single step single action operations meaning a user may make a single choice and complete the task dialog operation As a result any dialog that requires such additional controls or multiple steps operations as with a wizard are not task dialog candidates They would need to be implemented as custom dialogs using NET controls to have a similar look amp feel to Task Dialogs The sections to follow explain when where and how each task dialog component should be used to be consistent with others in Autodesk products General Design Principles These are a few guiding principles that can be applied globally to task dialogs When reviewing the contents of a task dialog ask e Does it provide all the information needed to take informed action e ls the information too technical or jargon filled to be understood by the target user The following points apply to English language versions of product releases e Text should be written in sentence format normal capitalization and punctuation Titles and command button text are the exceptions which are written in title format e Usea single space after punctuation For example DO NOT put two spaces after a period at the end of a sentence Avoid the use of parentheses to address plurals Instead recast sentences For exa
624. y creation Mass families use the Form class for all types of forms An extrusion form is created from a closed curve loop that is planar A revolve form is created from a profile and a line in the same plane as the profile which is the axis around which the shape is revolved to create a 3D form A sweep form is created from a 2D profile that is swept along a planar path A swept blend is created from multiple profiles each one planar that is swept along a single curve A loft form is created from 2 or more profiles located on separate planes A single surface form is created from a profile similarly to an extrusion but is given no height The following example creates a simple extruded form Note that since the ModelCurves used to create the form are not converted to reference lines they will be consumed by the resulting form Code Region 14 3 Creating an extrusion form private Form CreateExtrusionForm Autodesk Revit Document document Form etru cT onkori anull Create one profile ReferenceArray ref ar new ReferenceArray X ACA mew XYZ 10 0 0 XIA eit New OSO dog O0 ModelCurve modelcurve MakeLine document ptA ptB ISIE elie cya et morer ILO Une ws o GOONS ti y Cura RSIS ISIS 5 Sus mew UEM E pt new A SU Uy modelcurve MakeLine document ptA ptB Wee els AOS dox cd eaae wis GSCI ie eC BIOS I NSIS nece ta mew OGAX LU 50 E pus new uz LU 10 bys modelcurve
625. y starting from a known location and obtaining the widths of each bounding layer using CompoundStructure GetLayerWidth Some notes about the use of CompoundStructure e The total width of the element is the sum of each CompoundStructureLayer s widths You cannot change the element s total width directly but you can change it via changing the CompoundStructureLayer width The index of the designated variable length layer if assigned can be obtained from CompoundStructure VariableLayerlndex e You must set the CompoundStructure back to the HostObjAttributes instance using the HostObjAttributes SetCompoundStructure method in order for any change to be stored e Changes to the HostObjAttributes affects every instance in the current document If you need a new combination of layers you will need to create a new HostObjAttributes use ElementType Duplicate and assign the new CompoundStructure to it e The CompoundStructureLayer DeckProfileld and DeckEmbeddingType properties only work with Slab in Revit Structure For more details refer to Revit Structure Each CompoundStructureLayer in HostObjAttributes is typically displayed with some type of material If CompoundStructureLayer Materialld returns 1 it means the Material is Category related For more details refer to Material Getting the CompoundStructureLayer Material is illustrated in the following sample code Code Region 11 5 Getting the CompoundStructureLayer Material view plain
626. y these fundamental elements e g Annotations Reporting a proper change priority for the elements which your Updater modifies benefits users of your application Revit is less likely to have to execute the Updater a second time due to changes made by another Updater For Updaters which report the same change priority execution is ordered based on a sorting of Updaterld The method UpdaterRegistry SetExecutionOrder allows you set the execution order between any two registered Updaters even updaters registered by other API add ins so long as your code knows the ids of the two Updaters Exposure to End User When updaters work as they should they are transparent to the user In some special cases though Revit will display a warning to the user concerning a 3 party updater Such messages will use the value of the GetUpdaterName method to refer to the updater Updater not installed If a document is modified by a non optional updater and later loaded when that updater is not installed a task dialog similar to the following is displayed Missing Third Party Updater A The file sample_project was modified by the third party updater Unknown Wall Type Updater which is not currently installed If you continue to edit the file data maintained by Unknown Wall Type Updater will not be updated properly This may create problems when sample project is later opened when Unknown Wall Type Updater is present Continue working with the i
627. yticalModelSupports you get the three Beams as well as th lo pg eee Th 5 92 IK Boundary Line 7 E a ge I g z jx azz Hose E M r Eg E SlopeAmow FL F Nel ea a Bae Fea PEA F Set Show Ret zt z 2 7 It Span Direction i E E m Plane Modi CIEN T View Dimension Create Mode Draw Pick Supports Adds sketch lines based on existing structural walls or beams Use this tool to pick beams to define split lines and create constant bearing lines for the structural floor Figure 160 Floor and StructuralBeam Support Information Floor and Wall Support Information After drawing a slab by picking walls as the support you cannot get Walls from the Floor s AnalyticalModelSupport collection Instead Floor is available in the Wall s collection of AnalyticalModelSupports Collaborate View Manage Modify Create Floor Boundary Debug Iv ne ol ga ojo 4 _ J X na Boundary Line Fi pet x cr Gi A ka a oo a oo pu mm BB E M h ih Slope Arow E f de a As E 3 C MN zt zt Ei ra de v ttl Span Direction D 2 Jt lie Tl E Set Show Ref Plane View Dimension Create Pick 5upports Adds sketch lines based on existing structural walls or beams Use this tool to pick beams to define split lines and create constant bearing lines for the structural floor Figure 161 Floor
Download Pdf Manuals
Related Search
Related Contents
intext:Bedienungsanleitung filetype:pdf MX-E5xc SERVICE MANUAL 20G214-00 E1 User Manual ダウンロード - ユーラステクノ RASS-S Toolbox User Manual DX-7AH - 竹中電子工業株式会社 Copyright © All rights reserved.
Failed to retrieve file