AutoCAD .NET Training
AutoCAD .NET Training
AutoCAD .NET Training
NET API
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:
Special topics:
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
Why .NET?
Autodesk use .NET as 3rd party development platform for almost all products
We can use the same programming skills across multiple Autodesk products
Benefits of .NET
A huge collection of ready-to-use functions available inside the .NET Framework Many different languages available choose your weapon Learning curve quick start and development
Basic types
WinForms
To use it, your add-in just have to reference the product API assembly (.dll)
Deeply integrated with Microsoft .NET
Intelisense
We commonly use basic types and WinForms Reference other assemblies (.dll) to access new features The IDE is Visual Studio
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
Namespaces
Namespaces
Example: The namespace Autodesk.AutoCAD.EditorInput group all features related to geometry in AutoCAD
Example: Autodesk.AutoCAD.EditorInput.Editor.WriteMessage
Methods
Calling methods
line.DrawOnScreen()
When a method require data, you need to create the data before call the method
myInteger = 10 line.Resize(myInteger)
line.Resize(10)
myInteger = spatialPoint.CalculateDistanceTo(anotherPoint)
Property
line.Resize(10) Only this line will be resized, not any other line
Creating a Method
Public: accessible from outside, required for custom commands Private: accessible only inside, usually used for internal methods
Method name cannot contain special chars or spaces and cannot start with numbers
Return value
Returning value
Sub return empty or Function return some value Public Sub MethodName() Public Function MethodName() As String
Return a String
Parameters
Parameter name
Parameter type
Method example
Public Function Multiply(number1 As Integer, _ number2 as Integer) as Integer Return number1 * number2 End Sub
ObjectARX SDK
Project VB.NET
Compile
Assembly (.dll)
Add references
Regular VB routine
Imports Autodesk.AutoCAD.Runtime Imports Autodesk.AutoCAD.ApplicationServices Imports Autodesk.AutoCAD.EditorInput Public Class Class1 <CommandMethod("myCommand")> _ Public Sub myRoutine() 'Access the AutoCAD Editor Dim ed As Editor = Application. _ DocumentManager. _ MdiActiveDocument. _ Editor 'Write a simple message ed.WriteMessage(My Hello World") End Sub End Class
2.
3. 4. 5.
AutoCAD Imports
Mark the routine as command Access the editor Write a message
Now just compile, load inside AutoCAD with NETLOAD and call myCommand
HKEY_LOCAL_MACHINE For a specific user only SOFTWARE Autodesk AutoCAD R18.1 R17.0: 2007 .1: 2008 .2: 2009 R18.0: 2010 .1: 2011 409: English 416: Portuguese X000: Civil3D X001: AutoCAD 040A: Spanish "DESCRIPTION"="Custom App Name" "LOADER"="C:\\folder\\appName.dll" "LOADCTRLS"=dword:0000000e "MANAGED"=dword:00000001
ACAD-9001:409 Applications
YourAppName
Copyright Autodesk Developer Network 2010
Add-In
http://blogs.autodesk.com/through-the-interface
Reflector
http://sharptoolbox.madgeek.com
Ildasm
Fuslogv
FxCop
http://www.gotdotnet.com/team/fxcop/
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
XXX is the value type we want to prompt, Angle, String, Distance Use Message and Keywords properties Use AllowYYY to set conditions for prompting. For e.g., AllowNegative
Ask the user to select the point and store the selection result
Dim pointResult As PromptPointResult = ed.GetPoint(pointOptions)
Enter Number of Sides: Enter Number of Sides [Triangle/Square/Pentagon] : Enter Number of Sides [Triangle/Square/Pentagon] <3>:
Additional prompts
Types:
PromptPointOptions PromptStringOptions PromptDoubleOptions PromptAngleOptions PromptCornerOptions PromptDistanceOptions PromptEntityOptions PromptIntegerOptions PromptKeywordOptions PromptNestedEntityOptions PromptNestedEntityOptions PromptSelectionOptions Etc.
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
Is unique per session (or instance) of AutoCAD Not persistent Is generated automatically for an object when it is added Non-database resident objects do not have an ObjectId set Get it using ObjectId property
May NOT be unique per session Persistent Get it using Handle property
BlockTable
LayerTable
Other tabels
TextStyleTable
DimStyleTable BlockTableRecord Model Space Paper Space 0 Paper Space 1 Other blocks LayerTableRecord 0 Other layers UcsTable LineTypeTable
ViewTable
ViewportTable RegAppTable
MgdDbg(C#) ADN
Transactions: Overview
Transaction.GetObject method
ForRead: only to read information, faster ForWrite: to read and write information, fill the UNDO mechanism
Recommend procedure:
Open ForRead, then if required, UpgradeOpen to ForWrite Open ForWrite if you will write
'Acess the Database Dim db As Database = Application.DocumentManager.MdiActiveDocument.Database 'Start a transaction Using trans As Transaction = db.TransactionManager.StartTransaction
Transactions: Scope
Can be:
Committed: all operations are saved - Transaction.Commit() Aborted: all operations are discarded Transaction.Abort()
Can be nested
The outermost still have control e.g. if aborted, all nested are too
1
Transaction 2 Transaction 1
obj1 obj2
2
obj2 obj3
obj1 Database
Copyright Autodesk Developer Network 2010
obj3 obj2
Symbol Tables
'Create a new block Dim myBlock As New BlockTableRecord myBlock.Name = "myBlock" 'Change the bt (BlockTable) to ForWrite bt.UpgradeOpen()
Create a new block (in memory) Change the block table to ForWrite
'Add the new block to the BlockTable Append the new block to block table bt.Add(myBlock) Now it is database resident Inform the transaction about new objects trans. AddNewlyCreatedDBObject(myBlock, True) ALWAYS inform the transaction End If 'Save changes to the Database Save changes trans.Commit() Tip: Commit is faster than Abort End Using 'Dispose the transaction
Copyright Autodesk Developer Network 2010
This will list all BTRs, includins Model Space, all Paper Spaces, and any other block (internal or user-defined)
Dim db As Database = Application.DocumentManager.MdiActiveDocument.Database Using trans As Transaction = db.TransactionManager.StartTransaction Dim bt As BlockTable = trans.GetObject(db.BlockTableId, OpenMode.ForRead)
'Iterate through the collection of BTRs For Each btrId As ObjectId In bt 'open each BTR Dim btr As BlockTableRecord = trans.GetObject(btrId, OpenMode.ForRead)
'Write the block table record name ed.WriteMessage(btr.Name) Next End Using
Copyright Autodesk Developer Network 2010
Under BlockTable
Database BlockTable
This concept also applies to Paper Spaces and other internal and user-defined blocks
BlockTableRecord
Model Space
Open the current space for 'Create and configure a new line write. Can be any other BTR. Dim newLine As New Line newLine.StartPoint = New Point3d(0, 0, 0) Create and configure a newLine.EndPoint = New Point3d(10, 10, 0) new line (in-memory)
'Append to model space mSpace.AppendEntity(newLine)
'Inform the transaction trans.AddNewlyCreatedDBObject(newLine, True) End Using 'Dispose the transaction
Copyright Autodesk Developer Network 2010
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.
Manual Dispose is required in a few cases, e.g. Transaction (Using)
Error or Exception
The runtime throw an error/exception when cannot execute one line of code
Several different reasons, sometimes unpredictable Autodesk host application usually throw treatable exceptions
Usually we can treat add-in level exception Good mechanism to try something we are not sure if will work fine often used on our trainings
Be fearless: Try
VB.NET
Try 'try something here Catch End Try
Investigate: Catch
VB.NET
Try Catch (ex As Exception) 'something went wrong 'treat it here End Try
Optional This ex variable contains valuable information to understant the exception
If something went wrong during TRY, the runtime stop the execution and move to CATCH
Be organized: Finally
VB.NET
Try Catch Finally 'clean up here End Try
Optional We usually clean up a variable or close a connection This block is always executed, regardless if succeed (TRY) or fail (CATCH)
Summary of Try/Catch/Finally
Examples:
Try get an collection item, if does not exist, create inside Catch Open a document and Try change it, Catch if is read-only, Finally close it (for success or fail)
Reusable transaction
Dim db As Database = Application.DocumentManager.MdiActiveDocument.Database Using trans As Transaction = db.TransactionManager.StartTransaction Try trans.Commit() Catch ex As Exception trans.Abort() End Try End Using
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
Dictionaries
Each item has a string key Items searchable with a string key using GetAt() or Item
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
Dictionary Hierarchy
Named Object Dictionary
Extension Dictionary
DBDictionary
SetAt GetAt
DBDictionary
SetAt GetAt
One DBDictionary can contain others. Good to organize the structure. Also avoid conflict with other apps.
Xrecord
Data
ResultBuffer
New AsArray
Array of TypeValues
Lab 5 - Dictionary
Type comparison
First and very important: We cannot convert from any type to any type
For .NET types, there are method for it For AutpCAD API, you need to consult the Class Map
The variable parameter can be almost anything that make sense (string or numeric)
TryCast(variable, type)
Dim myString As String myString = TryCast(someVariable, String) If (myString IsNot Nothing) Then 'ok, the conversion went fine End If
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
The window with focus is usually highlighted and will receive keyboard input
Forms Controls for forms (button, textbox, combobox) Ready to use forms (dialogs to open, save, folder) Others (menus, ribbon, tooltip)
Properties
Copyright Autodesk Developer Network 2010
For some controls we need execute something when the user interacts with it
Select Events Select a button, mouse right-click, Properties Select Click, then mouse double-click to create the method button1_click
TIP
Modal forms
Application.ShowModalDialog
Application.ShowModelessDialog
Context menu
Application Level
Application.AddDefaultContextMenuExtension
Object Level
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
PaletteSet
Use Visual Studio wizards to create the controls Use the Add method of the PaletteSet the add the UserControl
PaletteSet 2
PaletteSet Constructor takes a unique GUID In Visual Studio On the Tools menu select "Create Guid".
Before creating the PaletteSet test to see if it already exists. Use a global member variable for the PaletteSet
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
InputPoint Monitor
Allows you to monitor relevant inputs in AutoCAD, an extremely powerful API. Provides relevant data to the input received - OSnap, Draw context, various computed points, Entities underneath the aperture, etc. Also allows you to draw temporary graphics, and to easily implement Tooltips Created with the PointMonitor event the Editor
Lab 6 - PointMonitor
Class Agenda
Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs
Jigs
Need to use a Class that Inherits from EntityJig or DrawJig Two functions that must be overriden: Sampler and Update
The constructor for this class takes the entity being jigged
Lab 7 - Jig
Thank You!
Autodesk