Sie sind auf Seite 1von 11

AutoCAD .

NET Basics, Part II

AutoCAD .NET Basics, Part II


Stephen Preston Autodesk Inc

DE115-2 Wondering what all the hype is around .NET? Well give you the basic information you need to get up to speed on writing your own .NET applications based on the AutoCAD .NET API. In this class, youll learn about the.NET Framework and what is means for programmers; how to write your first AutoCAD .NET add-in; the simple user interaction required, including point selection and keyword entry; a discussion of the DWG database structure; how to add CAD entities to the DWG database; and how to traverse the entities already in the DWG.

About the Speaker:


Stephen has been a member of the Autodesk Developer Technical Services Team since 2000, first as a support engineer and then as manager of the EMEA (Europe, Middle East, and Africa) Team. In those roles, his responsibilities included support for the AutoCAD APIs, including ObjectARX and AutoCAD .NET, as well as AutoCAD OEM and RealDWG technologies. Currently, he manages the Developer Technical Services Team in the Americas and serves as Workgroup Lead, working closely with the AutoCAD engineering team on future improvements in the AutoCAD APIs. Stephen started his career as a scientist, and has a PhD in Atomic and Laser Physics from the University of Oxford.

AutoCAD .NET Basics, Part II

AutoCAD .NET Basics, Part II

AutoCAD.NETBasics,PartII
Whatthisseminaris(andwhatitisnt)
AutoCAD .NET Basics is an introduction to the AutoCAD .NET API. This seminar is a continuation of DE111-2 AutoCAD .NET Basics, Part I Because this seminar spans two sessions, this handout is a continuation of the handout for DE111-2. If youve signed up for this seminar, but not Part I, then I strongly recommend you try to squeeze in at the back of the first one. Theres no natural break between the two, so youll be walking in on the middle if you only attend this. These two seminars are intended to form a foundation for the other .NET seminars being delivered by the Autodesk Developer Network team. These are: DE205-2 AutoCAD .NET Show and Tell DE201-2 AutoCAD .NET: Tell Me About It! DE211-2 The Best of Both Worlds: .NET and LISP Can Coexist This is not a beginners class on programming. The seminar assumes that you have a basic understanding of simple programming concepts, and that you are familiar with AutoCAD. Experience of programming in the .NET environment is not required, but is a nice to have. The same applies for an understanding of Object Oriented programming concepts. It is assumed that you have never before used the AutoCAD .NET API 1 . That said, even if youve never programmed before, this series of seminars will show you whats possible with AutoCAD .NET. Knowing whats possible is the first step in learning how to make it so.

TheDWGDatabaseformat
In the handout for DE111-2 AutoCAD .NET Basics, Part I, we worked through the ubiquitous Hello World tutorial. At the end of that, we waved a magic wand to add some MText to ModelSpace. That was our first glimpse of the DWG Database structure. You wont understand the ObjectARX or AutoCAD .NET API until you understand the DWG Database structure. Its as simple as that. So lets take a quick look at it now. The DWG Database is not that different to any other database (an MS Access Database, for example). If youve ever done any database programming, then youre halfway there already.
1

A note to beginners API means Application Programming Interface. Thats the set of functions that AutoCAD exposes that you can use in your application to make AutoCAD do what you want.

AutoCAD .NET Basics, Part II

Like any database, the DWG Database consists of a number of tables in which are stored records. For example, an MS Access database might contain a table of employees (lets call it the EmployeeTable), which might contain a record for each Employee (an EmployeeTableRecord). Like this -

In the same way, most of the information in a DWG Database is stored in SymbolTables as SymbolTableRecords. We have several types of Symbol in AutoCAD, such as Blocks, Dimension Styles, Layers, LineTypes, UCSs, Views, Viewports, and Registered Applications (used for storing Xdata). Each of these SymbolTables stores a different type of SymbolTableRecord. The most important thing about a CAD application is to be able to draw something, so lets concentrate on how AutoCAD stores the graphical Entities 2 (Lines, Circles, Polylines, etc) you draw on-screen. Graphical Entities are always stored in (or are owned by) a BlockTableRecord. Think of a BlockTableRecord as containing all the Entities that make up the definition of a Block. But just to complicate things, ModelSpace and PaperSpace are also represented in the DWG Database by BlockTableRecords. This makes sense if you think about it - Block definitions and ModelSpace both just store a bunch of graphical Entities. The only difference is that you have a window to look into the ModelSpace BlockTableRecord the drawing document. To view other BlockTableRecords, you have to insert a BlockReference into ModelSpace or PaperSpace. And, of course, all the BlockTableRecords are stored in the BlockTable. Below is a screenshot from the Inspector DWG Database viewing utility 3 , with the tree expanded to show some BlockTableRecords and LinetypeTableRecords. Note the names of the BlockTableRecords in the BlockTable shown on the left screenshot they include Model_Space and Paper_Space. The righthand screenshot expands the ModelSpace BlockTableRecord to show the Entities it contains (two Lines, a Circle and a Polyline in this case). Dont worry about the AcDb prefix on the class names for now.

Entity has a special meaning in AutoCAD. This is the name given to anything in the DWG Database that is represented graphically. More generally, we use the word Object (or the DBObject class) to describe anything in the database that includes both Entities and non-graphical objects.
3

Available as an ObjectARX sample on the ADN website.

AutoCAD .NET Basics, Part II

Theres a little more to the DWG Database than just Tables. Notice the Named Objects Dictionary and Extension Dictionary shown in the Inspector tree. These are used for storing data in the DWG. Well discuss these in detail in the seminar.

Transactions
Continuing with our database theme, it shouldnt come as a surprise that we have a similar mechanism for modifying the DWG Database as for modifying a relational database we use Transactions. The concept of a transaction is simple. Any changes you make within a transaction are only committed to the database when the transaction is committed. If anything goes wrong while youre modifying the database within a transaction, then you simply abort the transaction and the database is returned to the state it was in before the transaction started.

AutoCAD .NET Basics, Part II

HelloWorldagain
Now weve covered the basics of the DWG Database structure and Transactions, lets look again at the code for the Hello World MText example we used in the DE112.2 handout. Here it is again in its entirety.
Imports Autodesk.AutoCAD.Runtime Imports Autodesk.AutoCAD.ApplicationServices Imports Autodesk.AutoCAD.DatabaseServices Public Class Class1 <CommandMethod("HelloWorld")> _ Public Sub MyMethod() ' Some Dim DB Dim BT Dim MS variable definitions As Database As BlockTable As BlockTableRecord

' Start a transaction to edit the DWG database Using trans As Transaction = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartT ransaction() ' Open ModelSpace BlockTableRecord ready to add entity DB = Application.DocumentManager.MdiActiveDocument.Database BT = trans.GetObject(DB.BlockTableId, OpenMode.ForRead) MS = trans.GetObject(BT(BlockTableRecord.ModelSpace), OpenMode.ForWrite) ' Create a new MText entity and set its text Dim txt As MText = New MText txt.Contents = "Hello World from VB.NET" ' Add the MText to ModelSpace MS.AppendEntity(txt) ' Add the MText to the transaction trans.AddNewlyCreatedDBObject(txt, True) ' Commit transaction so changes persist in the DWG Database. trans.Commit() End Using End Sub End Class

AutoCAD .NET Basics, Part II

Now lets walk through it line by line, starting just after the variable declarations in the function Before we can access the Database, we have to start a new transaction. We do that with
Using trans As Transaction = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransac tion()

The Application.DocumentManager.MdiActiveDocument part is just retrieving a reference to the currently active document. We then ask the TransactionManager for that document to start a new transaction for us. To add an Entitiy to ModelSpace, we have to work down the structure of the Database. First we need to access the Database for the currently active AutoCAD DWG document. Thats this line of code
DB = Application.DocumentManager.MdiActiveDocument.Database

Next we open the BlockTable. We open it inside the transaction using the Transaction.GetObject() method. Like in any database, we have a choice of opening the table for Write if were planning on adding or removing any records, or for Read if were only interested in querying the contents. In this case, we not planning on adding or deleting any records, so we open it for Read.
BT = trans.GetObject(DB.BlockTableId, OpenMode.ForRead)

Then we open the ModelSpace BlockTable record (again using the transaction)
MS = trans.GetObject(BT(BlockTableRecord.ModelSpace),OpenMode.ForWrite)

This looks a bit funny, because the BlockTable class is a collection of BlockTableRecords. BlockTableRecord.ModelSpace is a pre-defined constant that returns the name of the ModelSpace BlockTableRecord. If wed wanted the BlockTableRecord defining Block_A, wed have called BT(Block_A). And notice that were opening the ModelSpace BlockTableRecord for Write thats because were planning on adding some MText to ModelSpace. Next we create a new instance of an MText Entity, set its contents to the text we want to display, and add it to ModelSpace. The commented code is pretty obvious here.
' Create a new MText entity and set its text Dim txt As MText = New MText txt.Contents = "Hello World from VB.NET" ' Add the MText to ModelSpace MS.AppendEntity(txt)

The next part isnt quite so obvious

AutoCAD .NET Basics, Part II

' Add the MText to the transaction trans.AddNewlyCreatedDBObject(txt, True)

Weve created a new MText instance and added it to ModelSpace, so we need to let the Transaction know about that change. Thats how we can make sure the MText is removed from the Database if the Transaction is aborted, or permanently add it if its committed. You have to notify the Transaction like this every time you add something new to the DWG Database. Finally, we commit the Transaction. If we get to this line of code, then everything worked fine and there were no errors. Committing the Transaction makes our changes permanent and tidies up after us (closing everything that we opened).
' Commit transaction so changes persist in the DWG Database. trans.Commit()

By the way, Ive not put any error handling in this simple code. Error handling is a very important part of .NET, and we will cover that in the seminar.

NavigatingtheAutoCAD.NETObjectModel
By now, youll be starting to grasp whats needed to add stuff to your drawings. The AutoCAD .NET API exposes a number of namespaces (some of which we touched on briefly already when we introduced the Imports keyword in the Part I handout). These namespaces hold the classes you need to work with AutoCAD. Lets take a quick look at how you can find out the classes and functions available to you. Well focus here on the Autodesk.AutoCAD.DatabaseServices namespace, because (as its name suggests) thats the namespace that stores the .NET classes used to access the DWG Database. What follows assumes knowledge of basic Object-Oriented programming concepts 4 , particularly inheritance. A good way to view the classes available in a namespace is to use the Visual Studio Object Browser (the View->Object Browser menu item).

See (for example) http://en.wikipedia.org/wiki/Object-oriented_programming for an overview of this.

AutoCAD .NET Basics, Part II

If you open the Object Browser for the Hello World application we created in our first handout (or any AutoCAD .NET add-in project), then you can expand the acdbmgd assembly to see the namespaces it contains.

Now expand the DatabaseServices namespace in the Object Browser, scroll down to the MText class and expand the tree below it as far as DBObject. Do the same with Line.

Expanding the tree in this way exposes the inheritance hierarchy of that class 5 . We can see that MText is derived from (or is a type of) Entity, which in turn is derived from (or is a type of) DBObject. For a Line, we see that theres a further layer of abstraction. A Line is a type of Curve, which is a type of Entity, which is a type of DBObject. Arcs, Circles and Polylines (to name but a few) are also types of Curve. For our purposes, we can consider the base class for every object that can reside in a DWG Database to be DBObject. This means that anything you can access inside the DWG is derived from DBObject. There are other classes further up the hierarchy, but we dont normally work with those. Every DBObject in the Database that displays graphics is also an Entity.

Object Browser shows a child to parent inheritance hierarchy. A parent to child diagram is better for studying which classes share common ancestors. The ObjectARX SDK includes such a diagram in the <ObjectARX SDK>\classmap folder.

AutoCAD .NET Basics, Part II

How do you view the properties and events exposed by these classes? Click on MText, and youll see these listed to the right. Here weve scrolled down to show the Contents property we used in the sample code. Clicking on a method or property displays a function signature (as shown in the screenshot). If you now click on Entity in the expanded MText class node, youll see all the methods, properties and events that MText inherits from its parent Entity class (and that are common to every other class that is also a type of Entity).

Take some time to browse through and expand the different class nodes in the browser to see whats there. Here are the inheritance hierarchies for BlockTable and BlockTableRecord. You can see that BlockTable is a type of SymbolTable, and BlockTableRecord is a type of SymbolTableRecord as discussed earlier. Notice that these are not graphical entities, so theyre not a type of Entity. Look at the other Autodesk.AutoCAD namespaces as well and notice the different class hierarchies in those.

And a final note about the class names displayed by Inspector we showed earlier. The language of AutoCAD is ObjectARX. The .NET API is a thin wrapper on top of this. The classes in the DatabaseServices namespace are the same as those prefixed by AcDb in ObjectARX. So when you see AcDbLine in ObjectARX, this translates to Autodesk.AutoCAD.DatabaseServices.Line in .NET.

AnoteaboutRealDWG
RealDWG is a software development kit that allows you to add the capability to create, modify or read a DWG file from your own application. That means your application can work with the DWG format even without AutoCAD installed. RealDWG is used internally by all our Autodesk applications, including AutoCAD itself. RealDWG includes a .NET API that is a subset of the full AutoCAD .NET API. Obviously, an API that works without requiring AutoCAD doesnt include an AutoCAD Editor specific functionality (e.g. viewing a drawing, defining commands, responding to mouse movements, creating selectionsets, etc.), but it does include all of the AutoCAD .NET API needed to directly access the DWG Database from a standalone application. Thats the

AutoCAD .NET Basics, Part II

Autodesk.AutoCAD.DatabaseServices namespace (and the other namespaces that namespace is dependent on). Visit www.autodesk.com/realdwg for more information on RealDWG, or step into DE319-2 There's More to .DWG Than AutoCAD.

Furtherreading
Here are a few places you can go to for more information on the AutoCAD .NET API: www.autodesk.com/developautocad - for a general overview of the AutoCAD APIs and publicly available resources. www.autodesk.com/apitraining - if youre interested in attending classroom training delivered by the Autodesk Developer Network team. www.autodesk.com/joinadn - to find out how becoming a member of the Autodesk Developer Network can help your application development efforts, including our members-only knowledgebase and unlimited technical support. www.objectarx.com to download the ObjectARX SDK, which includes AutoCAD .NET API documentation and samples. blogs.autodesk.com/through-the-interface Kean Walmsleys blog focussing primarily on AutodCAD APIs. Kean is senior manager of the global Autodesk Developer Technical Services team. discussion.autodesk.com/forum.jspa?forumID=152 the Autodesk public discussion group for the AutoCAD .NET API.

Acknowledgements
Thank you to everyone in the Autodesk Developer Technical Services team (past and present) for their contributions to the training material and SDK samples on which Ive based AutoCAD .NET Basics.

Das könnte Ihnen auch gefallen