You are on page 1of 81

AutoCAD .

NET API

Developer Technical Services

Autodesk Presentation Title 1


Getting Acquainted

The Developer Technical Services Group

Who Are You?

Autodesk Presentation Title 2 © 2005 Autodesk


Developer Technical Services
Worldwide Workgroup
 Over 25 Specialists World Wide
 Virtually 24 hour support, 5 days a week
Americas Team
 US (CA, AZ, WA), Canada, Brazil
European Team
 Switzerland, United Kingdom, France, Czech Republic, Russia
APac Team
 China, Japan, India

Autodesk Presentation Title 3 © 2005 Autodesk


Getting Support
http://www.autodesk.com/adn-devhelp
 Provides access to
 On-line knowledge base
 Call submission
 Newsgroups
 Calls are logged automatically
 1-3 day turnaround
 Callbacks as needed
 Answers to frequently asked questions are posted in our on-line
knowledge base

Autodesk Presentation Title 4 © 2005 Autodesk


Course Objective
It is to understand:
 the fundamentals of the AutoCAD .NET API
 how to teach yourself the AutoCAD .NET API
 where to get help afterwards

What it is not:
 Teach you .NET framework or C# , VB programming language
 Give you complete of coverage of all API functions

Autodesk Presentation Title 5 © 2005 Autodesk


Class Agenda
Lectures with Labs
 Slides give an abstract overview
 Labs and discussion give a practical perspective
Lectures
 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 6 © 2005 Autodesk


Class Schedule
Time 9:00 - 5:00
 Lunch 12:00 - 1:00
Day 1
 Overview of .NET
 Visual Studio Project Settings – Lab 1
 Simple User Input – Lab 2
 Database Fundamentals – Lab 3
 More Database Fundamentals – Lab 4
Day 2
 More User Input – Lab5
 User Interface Design – Winform Dialogs and Palettes – Lab 6
 Event Handling – Lab 7

Autodesk Presentation Title 7 © 2005 Autodesk


Questions?

Autodesk Presentation Title 8 © 2005 Autodesk


.NET Overview

 What is .NET?

 Benefits of programming in .NET

 Important Concepts

Autodesk Presentation Title 9 © 2005 Autodesk


.NET Overview
What is .NET?

 Microsoft’s Technology of a Web based infrastructure

 Seamless interaction between applications and the Internet

 Access information across anytime, anywhere from any


device

Autodesk Presentation Title 10 © 2005 Autodesk


.NET Overview
What is .NET?

Components of .NET

 The .NET Framework used for building and running all kinds of
software, including Web-based applications, smart client applications,
and XML Web Services
 Developer tools such as Microsoft Visual Studio .NET
 A set of servers that integrate, run, operate, and manage Web
services and Web-based applications
 Client software that helps developers deliver a deep and compelling
user experience across a family of devices and existing products.

Autodesk Presentation Title 11 © 2005 Autodesk


.NET Framework
VB C++ C# JScript …

Common Language Specification

Visual Studio.NET
ASP.NET Windows Forms

Data and XML

Base Class Library

Common Language Runtime

Autodesk Presentation Title 12 © 2005 Autodesk


.NET Overview
What is .NET?

NET Framework
 Common Language Runtime (CLR)
 Object-Oriented programming environment
 Common execution environment for .NET applications
-Similar to Java VM – but with much stronger
interoperability

 Framework Class Library (FCL)


 Object Oriented Collection of re-usable types

(Source: MSDN)
Autodesk Presentation Title 13 © 2005 Autodesk
.NET Overview
CLR Execution Model
Source code
VB C# C++

Compiler vbc.exe csc.exe cc.exe

Managed Assembly Assembly Assembly


Code IL Code IL Code IL Code
(dll or exe)

Common Language Runtime

JIT Compiler

Native Code

Operating System Services

Autodesk Presentation Title 14 © 2005 Autodesk


What is Microsoft .NET?
What we know from our experience so far…

Intelligent symbolic representation


 Mature language constructs
 Collections, Events, Delegates
 Common programming pitfalls addressed
 Memory management, consistent Exception handling, unified strings

Source and binary inter-module communication


 goes beyond C++ and COM
 Meta data allows design- and run-time object usage and extension

Programming style
 Multiple supported languages – Choose your weapons

Autodesk Presentation Title 15 © 2005 Autodesk


.NET Overview

 What is .NET?

 Benefits of programming in .NET

 Important Concepts

Autodesk Presentation Title 16 © 2005 Autodesk


.NET Overview
Benefits of programming in .NET
 Consistent Object Oriented Development
platform

 Automatic memory management – Garbage


collection

 Support for multiple languages

(Source: MSDN)

Autodesk Presentation Title 17 © 2005 Autodesk


.NET Overview
Consistent Object Oriented Development platform

Everything you see can be treated as an Object!

Dim myLine As New Line()


myLine.StartPoint = New Point3d(0, 0, 0)
myLine.EndPoint = New Point3d(10, 10, 0)
myLine.GetClosestPointTo(New Point3d(5, 5.1, 0), False)

Dim x as Interger = 7
Dim s as String = x.ToString()

 Objects are instances of a Type or Class (for example myLine


is an object and Line is a type)

 Objects have properties such as StartPoint, and methods such


as GetClosestPointTo()
Autodesk Presentation Title 18 © 2005 Autodesk
.NET Overview

Consistent Object Oriented Development platform

Mature API Constructs

What’s wrong with this function?

int acedSSGet(const char * str,


const void * pt1,
const void * pt2,
const struct resbuf * filter,
ads_name ss);

Autodesk Presentation Title 19 © 2005 Autodesk


.NET Overview

Consistent Object Oriented Development platform


Mature API Constructs

Some 6 new classes defined to encapsulate acedSSGet()

Dim values(2) As TypedValue

‘Define the selection criteria


values(0) = New TypedValue(DxfCode.Start, “Circle”)
values(1) = New TypedValue(DxfCode.Color, 1)

Dim selFilter As New SelectionFilter(values)


Dim selOpts As New PromptSelectionOptions()
selOpts.AllowDuplicates = True

‘Run the selection


Dim res As PromptSelectionResult = Editor.GetSelection(selOpts, selFilter)

Autodesk Presentation Title 20 © 2005 Autodesk


.NET Overview

Benefits of programming in .NET

 Consistent Object Oriented Development platform

 Automatic memory management (Garbage collection)


and consistent exception handling

 Support for multiple languages

(Source: MSDN)

Autodesk Presentation Title 21 © 2005 Autodesk


.NET Overview

Benefits of programming in .NET

Automatic memory management


 Old Way (C++) - Potential for memory leaks!
char *pName=(char*)malloc(128);
strcpy(pName,"Hello");
//...
free(pName);
 New Way - .NET
 C++ - String *pName=new String("Hello")
 VB - Dim Name As String = "Hello"
 C# - String Name=“Hello”;
 // Garbage collection handles deallocation; no ‘delete’!

Autodesk Presentation Title 22 © 2005 Autodesk


.NET Overview

Benefits of programming in .NET


Consistent exception handling
 Old Way – VB: Can be very confusing and problematic!
On Error GoTo UnexpectedError
Dim x As Double=10/0 ‘…error!
UnexpectedError:
MsgBox Str$(Err.Number)
 New – VB .NET
Try
Dim x As Double=10/0 ‘…error which throws exception
Catch
‘…what happened? Division by Zero!
Finally
‘…cleanup - do this either way
End Try

Autodesk Presentation Title 23 © 2005 Autodesk


.NET Overview

Benefits of programming in .NET

 Consistent Object Oriented Development platform

 Automatic memory management (Garbage collection)


and consistent exception handling

 Support for multiple languages

(Source: MSDN)

Autodesk Presentation Title 24 © 2005 Autodesk


.NET Overview
Benefits of programming in .NET

Support for multiple languages

 C#, VB most commonly used

 Can interop between code written in different languages. For


example, a class written in C# can be inherited from a class
written in VB! In fact, AutoCAD’s managed assemblies are
written using managed C++ which you will access from VB.NET.

 No significant difference in performance as all languages


compile to IL (Intermediate Language) executed by the CLR

Autodesk Presentation Title 25 © 2005 Autodesk


.NET Overview

 What is .NET?

 Benefits of programming in .NET

 Important Concepts

Autodesk Presentation Title 26 © 2005 Autodesk


.NET Overview
Important Concepts

Assemblies Assembly

• Fundamental unit of deployment and Manifest


execution in .NET Name?
 Contains a manifest that describes
What files make up the assembly?
the assembly
Dependent assemblies?
• Boundary for code execution and Version and Culture?
access permission

netmodule Dlls Bmp

(Source: MSDN)

Autodesk Presentation Title 27 © 2005 Autodesk


Class Agenda
Lectures and Labs

 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 28 © 2005 Autodesk


AutoCAD .NET API Documentation
How do I get started?

ObjectARX SDK Includes:


 SDK Samples!
 ObjectARX Developer’s Guide
 Managed Reference Guide
 Arxmgd.chm

ADN website
 DevNotes
 DevHelp Online

Visual Studio Class Browser

Autodesk Presentation Title 29 © 2005 Autodesk


Development Environment
Microsoft Visual Studio 2008 or 2005

AutoCAD 2010

Microsoft Windows XP

or

Microsoft Windows vista

Autodesk Presentation Title 30 © 2005 Autodesk


.NET Debugging Tools
 Reflector
 Browse .NET assemblies, disassemble, decompile
 http://sharptoolbox.madgeek.com
 Ildasm
 Disassemble .NET assemblies
 Visual Studio Tools
 Fuslogv
 Diagnose load time problems
 Visual Studio Tools
 FxCop
 Check conformance with Design Guidelines
 http://www.gotdotnet.com/team/fxcop/

Autodesk Presentation Title 31 © 2005 Autodesk


Snoop Tools (for AutoCAD’s database)

 ArxDbg (C++) ObjectARX SDK

 MgdDbg(C#) ADN

Autodesk Presentation Title 32 © 2005 Autodesk


Visual Studio project settings– Hello World!

 Start with a Class Library application type with DLL output.

 Add references to AutoCAD’s managed assemblies


 acdbmgd.dll
 Database services and DWG file manipulation (like
ObjectDBX)
 acmgd.dll
 AutoCAD Application specific (like ObjectARX)

 Find them in the AutoCAD install folder


(set COPY LOCAL = FALSE)
C:\Program Files\AutoCAD 2010\
C:\ObjectARX 2010\inc-win32 (or C:\ObjectARX 2010\inc-x64)

Autodesk Presentation Title 33 © 2005 Autodesk


Visual Studio project settings– Hello World!

Reference namespaces you will use in your project

In VB.NET Use Imports keyword:

Imports Autodesk.AutoCAD.ApplicationServices
Access to the AutoCAD application
Imports Autodesk.AutoCAD.EditorInput
Access to the AutoCAD editor
Imports Autodesk.AutoCAD.Runtime
Command registration
Imports Autodesk.AutoCAD.DatabaseServices
Access to the AutoCAD Database and Entities

Autodesk Presentation Title 34 © 2005 Autodesk


Visual Studio project settings– Hello World!

Add a simple command – HelloWorld

 Make a function an AutoCAD command by adding an attribute

Public Class Class1


<CommandMethod("HelloWorld")> _
Public Function HelloWorld()
End Function
End Class

 The attribute is added to the metadata for that function

 CommandMethod or CommandMethodAttribute type accepts


several parameters in its constructor such as group name, global
and local names, command flags and more (Use the object
browser)
Autodesk Presentation Title 35 © 2005 Autodesk
Visual Studio project settings– Hello World!

To print a string to command line

 Get the editor object for the active document

Dim ed As Editor =
Application.DocumentManager.MdiActiveDocument.Editor

 Call the editor’s WriteMessage method

Public Class Class1


<CommandMethod("HelloWorld")> _
Public Function HelloWorld()
ed.WriteMessage("Hello World")
End Function
End Class

Autodesk Presentation Title 36 © 2005 Autodesk


Loading .NET assembly

 NETLOAD command
 Demand Load (Registry)
 Startup
 On command invocation
 On request
 From another application
 On proxy detection

[HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\AutoCAD\R18.0\ACAD-
8001:409\Applications\AcLayer]
"DESCRIPTION"="AutoCAD Layer Manager"
"LOADER"="C:\\Program Files\\AutoCAD 2010\\aclayer.dll"
"LOADCTRLS"=dword:0000000e
"MANAGED"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\AutoCAD\R18.0\ACAD-
8001:409\Applications\AcLayer\Commands]
"LAYER"="LAYER"

[HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\AutoCAD\R18.0\ACAD-
8001:409\Applications\AcLayer\Groups]
"ACLAYER_CMDS"="ACLAYER_CMDS“

Use Installers to set these keys!

Autodesk Presentation Title 37 © 2005 Autodesk


Lab 1 – Hello World!

Autodesk Presentation Title 38 © 2005 Autodesk


Class Agenda
Lectures and Labs

 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 39 © 2005 Autodesk


Prompting for User Input

 Use PromptXXXOptions to set the parameters for prompting

 XXX is the value type we want to prompt, such as Angle, String,


Distance, Corner etc.
 Use Message and Keywords properties to set the prompt string and
list of keywords
 Use AllowYYY to set conditions for prompting. For e.g.,
AllowNegative

 To prompt, use Editor’s GetXXX functions


 Examples - GetAngle, GetString, GetDistance, GetCorner etc
 Pass PromptXXXOptions into GetXXX

 Result of prompting stored in PromptResult or derived types


 Examples – PromptDoubleResult, PromptIntegerResult etc.

Autodesk Presentation Title 40 © 2005 Autodesk


ObjectARX 2010 Wizards

AppWizard – Templates for a VB.NET or C# application

Add-In

Autodesk Presentation Title 41 © 2005 Autodesk


Lab 2 – Simple User Input

Autodesk Presentation Title 42 © 2005 Autodesk


Class Agenda
Lectures and Labs

 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 43 © 2005 Autodesk


AutoCAD Drawing Database
 In-Memory representation of the Dwg File
 Objects are stored hierarchically in the database - Db Structure
 All objects have identities – ObjectId, like Primary Key in a relational
database
 Objects are always accessed in a transaction
 The transaction defines the boundary of database operations
 Objects have to be opened first in a transaction before they can
be used
 Objects can refer to other objects – such as a line having a
reference to a layer

DWG

Autodesk Presentation Title 44 © 2005 Autodesk


Database Structure
DATABASE

R12 SymbolTables Block Table Named Object Header Variables


Dictionary
Model Space
Paper Space
Dictionary Entry
Other BTR
Entity

Entity Entity

Autodesk Presentation Title 45 © 2005 Autodesk


Database Components

 Symbol Tables
 Examples Layer Table, Linetype Table, Textstyle Table etc.
 Containers to store Symbol Table Records
 Example LayerTableRecord, LinetypeTableRecord etc
 All Symbol Tables have common methods of a container such as
 Add – to add a record
 Item – to lookup an entry with a search string
 Has – To know if an entry exists
 Is enumerable
 Each symbol table can hold only records of a specific type
 For example, a LayerTable can hold only LayerTableRecords

 Use SnoopDb to see where the Layers reside

Autodesk Presentation Title 46 © 2005 Autodesk


Database Components
 Block Table
 Child of Symbol Table
 Holds a collection of BlockTableRecords (or Block Definitions)
 BlockTableRecords (BTR) in turn is a container that
holds only graphical entities (i.e., those derived from
Entity type)
 Two default BlockTableRecords cannot be removed –
Model Space and one Paper Space
 Searchable with a string or an ObjectId (more on this later)
 Neither the Block Table nor the Symbol Tables are created by the
user. They are created by default when you create a new database.

 Create a block definition and use ArxDbg or MgdDbg to see


where the block definition is stored and peek into its contents

Autodesk Presentation Title 47 © 2005 Autodesk


Getting a Database Object
 Construct One
 In Memory

 Get the one currently active in AutoCAD


 HostApplicationServices.WorkingDatabase()

Autodesk Presentation Title 48 © 2005 Autodesk


Object Identity - ObjectID
 All Objects that exist in the database have an ObjectId
 Is unique per session (or instance) of AutoCAD
 Is generated automatically for an object when it is added to the
database
 Non-database resident objects do not have an ObjectId set
 Can be cached to open an object later

 Get it using ObjectId property

Autodesk Presentation Title 49 © 2005 Autodesk


Transactions
 Transactions
 Sets the boundary for database operations
 Handles exception cleanly
 Operates with a single Undo filer
 Can be
 committed – All database operations are saved
 rolled back – All database operations are aborted
 Can be nested

Autodesk Presentation Title 50 © 2005 Autodesk


Nesting Transactions
1 2 3 4
Transaction 2 obj2 obj3

Transaction 1 obj1 obj2

obj1 obj3
obj2
Database

1. Client starts Trans1 and gets Obj1 & Obj2


2. Client starts Trans2 and gets Obj2 & Obj3
3. Client commits Trans2
 Trans2 changes are committed
4a. Client commits Trans1
 Trans1 changes are committed
4b. Client aborts Trans1 instead
 Trans1 (and Trans2) changes are rolled back

Autodesk Presentation Title 51 © 2005 Autodesk


Transactions
 To start a transaction, use Databases’ StartTransaction()

For example:
Dim db As Database = HostApplicationServices.WorkingDatabase()
‘Get the current db used by AutoCAD

Dim trans As Transaction =


db.TransactionManager.StartTransaction() ' begin the transaction

 To commit a transaction, use transaction’s Commit()


 To Abort a transaction, use transaction’s Abort()
 When done with a transaction it must be
explicitly disposed!

Autodesk Presentation Title 52 © 2005 Autodesk


Transactions
 Standard db access with Transactions
Public Function MyFunc()

‘Get the database current in AutoCAD


Dim db As Database = HostApplicationServices.WorkingDatabase()

‘Start a transaction using the database transaction manager


Dim trans As Transaction = db.TransactionManager.StartTransaction()

Try
‘Do all database operations here
‘Lets get the block table from the database
‘Drill into the database and obtain a reference to the BlockTable
Dim bt As BlockTable = trans.GetObject(db.BlockTableId, OpenMode.ForWrite)
‘Everything successful, so commit the transaction
trans.commit()
Catch
trans.Abort()
Finally
‘All ok. Call Dispose explicitly before exiting
trans.dispose()
End Try

End Function

Autodesk Presentation Title 53 © 2005 Autodesk


Transaction - Opening an Object
• Use transaction’s GetObject to open an object
 The first parameter is the ObjectId
 Second parameter is the open mode
 ForRead – Access but not Modify
 ForWrite – Modify and Access
 ForNotify – When the object is notifying

Dim bt As BlockTable = trans.GetObject( _


db.BlockTableId, _
OpenMode.ForWrite _
)

Autodesk Presentation Title 54 © 2005 Autodesk


Adding an Object to the database
 Find the right owner to add a newly created object to
 All objects have exactly one owner
 The owner can be the database itself!
 For example, newly created LayerTableRecord can only be added to the
Layer Table, its owner, or a newly created entity can be only added to a
block table record

 Use Add method for adding Symbol Table Records to add to Symbol
Table

 Use AppendXXX to add add other kinds of objects to its owners For
example
 AppendEntity to add to BlockTableRecord

 Once an object is added to an owner, always let the transaction know!


For example
newBtr.AppendEntity(circle) ‘Add our circle to its owner the BTR
trans.AddNewlyCreatedDBObject(circle, True)

Autodesk Presentation Title 55 © 2005 Autodesk


Important Managed Classes

Autodesk Presentation Title 56 © 2005 Autodesk


Object memory management

 Note managed objects wrap an unmanaged C++ object!

 So we create them with New, Do they need to be disposed?


 No - garbage collection disposes the object when it wants to reclaim memory

 If the object is not in the database –– this deletes the underlying


unmanaged object

 If the object is in the database – this Closes the underlying unmanaged


object

 If opened in a transaction, disposing or committing the transaction closes


it automatically! – Clean memory management.

Autodesk Presentation Title 57 © 2005 Autodesk


Lab 3
Create Employee block Definition

Autodesk Presentation Title 58 © 2005 Autodesk


Class Agenda
Lectures and Labs

 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 59 © 2005 Autodesk


Recommended Transaction Use
 Standard db access with Transactions

Public Function MyFunc()

‘Get the database current in AutoCAD


Dim db As Database = HostApplicationServices.WorkingDatabase()

‘Start a transaction using the database transaction manager


Using trans As Transaction = db.TransactionManager.StartTransaction()

‘Do all database operations here


‘Lets get the block table from the database
‘Drill into the database and obtain a reference to the BlockTable
Dim bt As BlockTable = trans.GetObject(db.BlockTableId,
OpenMode.ForWrite)
‘Everything successful, so commit the transaction
trans.commit()
End Using
End Function

Autodesk Presentation Title 60 © 2005 Autodesk


Dictionaries and XRecords
 Dictionaries (Type DbDictionary)
 Containers to hold data only
 Holds other Dictionaries
 Holds non-graphical Objects (derived from DbObject but not DbEntity!)
 Is enumerable
 Each item has a string key
 Items searchable with a string key using GetAt() or Item
 Two Root dictionaries
 Named Objects Dictionary (NOD)
 Owned by the database
 Available by default
 Used to store database level data
 Extension Dictionary
 Owned by an Entity
 Created by the user only when needed
 Used to store entity level data
 Use SnoopDb to look where the dictionaries are stored

Autodesk Presentation Title 61 © 2005 Autodesk


Dictionaries and XRecords
 XRecord

 Data containers

 Holds data in a Resbuf chain (Result Buffer)


 Resbuf – Linked List of TypedValues (DataType–Value pair)

 No “Key” to search values within a Resbuf. Should know the order


data is stored in the list

 XRecords can be added to Dictionaries


 If stored in NOD –database level data
 If stored in Extension Dictionary – entity-level data

Autodesk Presentation Title 62 © 2005 Autodesk


Get NOD
 To get the NOD for the database

Dim db = HostApplicationServices.WorkingDatabase

Dim NOD As DBDictionary =


trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite, False)

 To create an ExtensionDictionary for an entity

myEntity.CreateExtensionDictionary()

Autodesk Presentation Title 63 © 2005 Autodesk


Iterating Through Containers
Objects that are enumerable
 Symbol Tables
 Block Table Records
 Dictionaries
 Polylines
 PolyFaceMesh & PolygonMesh
 ACIS Solids
 Called traversers
 BlockReferences (Inserts)
 Only useful when attributes are present

Autodesk Presentation Title 64 © 2005 Autodesk


Symbol Table Traversal
 Start with a database pointer
 HostApplicationServices.WorkingDatabase – Get used to this one!

 Iterate down into each sub-table from there…

Dim db As Database = HostApplicationServices.WorkingDatabase()

Dim bt As BlockTable = trans.GetObject(db.BlockTableId,


OpenMode.ForWrite)

Dim id As ObjectId
For Each id In bt
Dim btr As BlockTableRecord = trans.GetObject(id,
OpenMode.ForRead)

Next

Autodesk Presentation Title 65 © 2005 Autodesk


Runtime Type Identification (RTTI)
 Type information (such as constructors, methods, properties, events
etc) are contained in the Metadata

 Query metadata at runtime using types defined in System.Reflection


namespace
 Not only to query type information but also dynamically create them.
 Heart of Reflection is provided by System.Type class
 The class is abstract. Implementers need to inherit methods to
describe the type
 Get it using
 Object.GetType
 TypeOf operator (VB, C# or C++)

Autodesk Presentation Title 66 © 2005 Autodesk


Casting*
 VB.NET
 Casting is automatic by assignment – Only if OptionStrict is turned
off
 Explicit casting – CType( expression, type )
 TypeOf – If TypeOf myObject is Line Then…
 If obj1.GetType() Is obj2.GetType() Then…

 In C#
 Line myLine = (Line)myObject;
 ‘as’ operator - Line myLine = myObject as Line; -
 if it fails, no exception, but object gets set to null!
 ‘is’ operator – if (myObj is Line) …
 typeof operator – if typeof (obj1) == typeof(obj2)…
 GetType - If obj1.GetType() == obj2.GetType() …

(* Source: The Code Project)

Autodesk Presentation Title 67 © 2005 Autodesk


Lab 4
Adding Custom Data

Autodesk Presentation Title 68 © 2005 Autodesk


Class Agenda
Lectures and Labs

 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 69 © 2005 Autodesk


More User Interaction
 PromptsXXXOptions is used to control prompting such as

 Set the Message


Enter Number of Sides:

 Set Keywords
Enter Number of Sides [Triangle/Square/Pentagon] :

 Set Defaults
Enter Number of Sides [Triangle/Square/Pentagon] <3>:

 Set Allowed values


Enter Number of Sides [Triangle/Square/Pentagon] <3>: -5
Value must be positive and nonzero.

 PromptXXXResult is used to obtain result of prompting

Autodesk Presentation Title 70 © 2005 Autodesk


Prompts
Types:
 PromptPointOptions
 PromptStringOptions
 PromptDoubleOptions
 PromptAngleOptions
 PromptCornerOptions
 PromptDistanceOptions
 PromptEntityOptions
 PromptIntegerOptions
 PromptKeywordOptions
 PromptNestedEntityOptions
 PromptNestedEntityOptions
 PromptSelectionOptions
 Etc.

Autodesk Presentation Title 71 © 2005 Autodesk


Lab 5
Prompts and Selection

Autodesk Presentation Title 72 © 2005 Autodesk


Class Agenda
Lectures and Labs

 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 73 © 2005 Autodesk


User Interface Design
 AutoCAD Defined
 Menus – Application level menu, Context menu
 Dialogs
 AutoCAD’s Enhanced Secondary Windows ( Palettes )
 Color, Linetype, Lineweight, OpenFile dialogs
 Tabbed Dialog Extensions (to Options Dialog)
 Status Bar
 Tray
 Drag-Drop
 And more. Explore Autodesk.AutoCAD.Windows namespace

 Windows Defined
 Windows Forms (Winform)
 Host of other controls defined in CLR

Autodesk Presentation Title 74 © 2005 Autodesk


User Interface
 Add Context Menu
 Application Level – Application.AddDefaultContextMenuExtension
 Object Level – Application. AddObjectContextMenuExtension –per
RXClass

 Showing Modal and ModelessDialogs


 Application.ShowModalDialog
 Application.ShowModelessDialog
 Persists size and position automatically

Autodesk Presentation Title 75 © 2005 Autodesk


Lab 6
User Interface Design

Autodesk Presentation Title 76 © 2005 Autodesk


Class Agenda
Lectures and Labs

 Overview of .NET.
 AutoCAD .NET Visual Studio project settings – Hello World!
 User Interaction - Simple User Input and Entity Selection
 Database Fundamentals – Symbol tables, Transactions
 Database Fundamentals – Dictionaries, XRecords, Table Traversal
 More User Interaction – Advanced Prompts
 User Interface design - WinForm Dialogs and Palettes
 Event handling – Reacting to AutoCAD Events in .NET.

Autodesk Presentation Title 77 © 2005 Autodesk


Handling Events
 Event
 message sent by an object to notify something has happened
 message is received in a function call by one or more listeners
 event sender only requires function pointer to dispatch a message
 any interested party can implement the function and receive the event
 function must have a specific signature that the sender requires
 Use .NET delegates to ‘wire’ sender and receiver

 Delegates
 Like a class (can be instantiated) but with a signature
 Holds references to functions having same signature
 Like ‘Type-Safe’ function pointer
 Can encapsulate any method which matches the specific signature

Autodesk Presentation Title 78 © 2005 Autodesk


Using Delegates
 Delegates in AutoCAD’s .NET API usually have ‘EventHandler’ suffix
 Lookup the signature of the delegate in the object browser

 Implement a function with same signature


 Instantiate the delegate passing address of the function into its constructor
 Add the delegate instance to sender’s list of listeners
 C#, use += operator
 VB, use AddHandler

Delegate myDelegate = new Delegate(address of myFunction);


EventSender.Event += myDelegate;

myFunction(delegate signature)
{
}
 Don’t forget to remove the listener!

Autodesk Presentation Title 79 © 2005 Autodesk


Event Handling - Example
 Create the event handler (callback)
Sub objAppended(ByVal o As Object, ByVal e As ObjectEventArgs)
MessageBox.Show("ObjectAppended!")
‘Do something here
‘Do something else, etc.
End Sub

 Associate the event handler with an event


Dim db As Database
db = HostApplicationServices.WorkingDatabase()
AddHandler db.ObjectAppended,
NewObjectEventHandler(AddressOf objAppended)

 Disconnect the event handler


RemoveHandler db.ObjectAppended, AddressOf objAppended
Autodesk Presentation Title 80 © 2005 Autodesk
Lab 7
Event Handling

Autodesk Presentation Title 81 © 2005 Autodesk

You might also like