auto cad 2006_api_overview
DESCRIPTION
TRANSCRIPT
www.autodesk.comIntroduction to the AutoCAD 2006 Application Programming Interface
www.autodesk.com
AutoCAD 2006 API Overview
• How to port your application to AutoCAD 2006
• The New .NET Interface
• Why do we want to use .NET?
• How can I use it to develop with AutoCAD 2006?
• How can I build on top of my existing code?
• ObjectARX API and UI customization updates
• Where to learn more…
Agenda:
www.autodesk.com
The AutoCAD 2006 API Overview
• The Rice• Making sure your application runs• Basic steps to support Rio
• The Wine• Opportunities to add value• Leveraging the new features and
API’s to increase the value of your and our products
www.autodesk.com
The Rice
• Install Update• Test• That’s it – binary application compatibility!
• Minor Registry version incremented to 16.2• Installers need updating for this key• e.g. demand loading keys, etc.
www.autodesk.com
The Wine – New API’s
•AutoCAD Managed .NET API
•ObjectARX SDK and UI customization updates
www.autodesk.com
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
www.autodesk.com
What is Microsoft .NET?More of what we know …
• Common Base Class Library• Unified solutions for common design patterns
• E.g. File I/O is the same for VB, C# and managed C++!
• API Interop is very easy!• C++ and COM interop is built into .NET!
www.autodesk.com
VBVBSource codeSource code
vbc.exevbc.exe
C++C++C#C#
cc.execc.execsc.execsc.exe
Operating System ServicesOperating System Services
Common Language RuntimeCommon Language Runtime
JIT CompilerJIT Compiler
Native CodeNative Code
ManagedManagedCodeCode(dll or exe)(dll or exe)
AssemblyAssemblyIL CodeIL Code
AssemblyAssemblyIL CodeIL Code
AssemblyAssemblyIL CodeIL Code
CLR Execution Model
CompilerCompiler
www.autodesk.com
Why use the AutoCAD Managed API (.NET)?
Pros Cons • Powerful, modern streamlined API
• Metadata resolves “DLL hell” versioning
• Mixed languages – choose your weapons
• Resolves MFC and CRT dependency – Use either VS 2002 or VS 2003
• Events are part of CLS specification
• 64-bit portable code by default
• Reusable code – MS and industry investment
• Clean memory management• Consistent error handling
• Strings are all Unicode!• APIs are simple: Make the class
public!
• Performance hit from ARX, but not bad …
• Some Interop performance costs• Jit compiling takes CPU cycles• Raw Performance is near native x86
• Natural learning curve associated with new platforms
www.autodesk.com
Programming in .NET - Advantages
Clean 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’!
www.autodesk.com
Programming in .NET - Advantages
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 .NETTry
Dim x As Double = 10/0 ‘…error which throws exceptionCatch
‘…what happened? Division by Zero!Finally
‘…cleanup - do this either wayEnd Try
www.autodesk.com
Programming in .NET - Advantages
Strings are all Unicode!
• Old Way – Unmanaged C++/COMCComBSTR bStr(newVal);
COLE2T szName(bStr);_tcscpy(m_szLayer,szName); // <sigh>
• New Way – .NET• C++: String *m_pszLayer=new String(newVal);• VB: Dim Name As String = newVal• C#: String Name=newVal;
www.autodesk.com
Why move to .NET in AutoCAD?Mature API constructs
What’s wrong with this function declaration?
int acedSSGet(const char * str,const void * pt1,const void * pt2,const struct resbuf * filter,ads_name ss);
www.autodesk.com
Why move to .NET in AutoCADMature API constructs
Some 6 new classes defined to encapsulate acedSSGet()
Dim values() As TypedValue = { _ New TypedValue(DxfCode.Start, "CIRCLE"), _ New TypedValue(DxfCode.Color, 1) _ }Dim sfilter As New SelectionFilter(values)
Dim SelOpts As New PromptSelectionOptions()SelOpts.MessageForAdding = "Select Red Circles:"SelOpts.AllowDuplicates = True
Dim res As PromptSelectionResult = ed.GetSelection(SelOpts, sfilter)
www.autodesk.com
Why do we want to use .NET?Mature API constructs
virtual Acad::ErrorStatus AcEdInputPointFilter::processInputPoint(bool& changedPoint,AcGePoint3d& newPoint,bool& displayOsnapGlyph,bool& changedTooltipStr,char*& newTooltipString,bool& retry,AcGiViewportDraw* drawContext,AcApDocument* document,bool pointComputed,int history,const AcGePoint3d& lastPoint,const AcGePoint3d& rawPoint,const AcGePoint3d& grippedPoint,const AcGePoint3d& cartesianSnappedPoint,const AcGePoint3d& osnappedPoint,AcDb::OsnapMask osnapMask,const AcArray<AcDbCustomOsnapMode*>& customOsnapModes,AcDb::OsnapMask osnapOverrides,const AcArray<AcDbCustomOsnapMode*>& customOsnapOverrides,const AcArray<AcDbObjectId>& pickedEntities,const AcArray< AcDbObjectIdArray, AcArrayObjectCopyReallocator< AcDbObjectIdArray > >& nestedPickedEntities,const AcArray<int>& gsSelectionMark,const AcArray<AcDbObjectId>& keyPointEntities,const AcArray< AcDbObjectIdArray, AcArrayObjectCopyReallocator< AcDbObjectIdArray > >& nestedKeyPointEntities,const AcArray<int>& keyPointGsSelectionMark,const AcArray<AcGeCurve3d*>& alignmentPaths,const AcGePoint3d& computedPoint,const char* tooltipString);
www.autodesk.com
Why do we want to use .NET? Mature API constructs
Is now…
‘Define the event handlerm_ed.PointMonitor += new
PointMonitorEventHandler(callback_PointMonitor);
‘Define the callback function – no crazy reference parameters!private void callback_PointMonitor(object sender, PointMonitorEventArgs e){
WriteLine(String.Format("PointMonitor :", e.Context.ComputedPoint)); }
www.autodesk.com
AutoCAD .NET and C++ DevelopersTwo FAQs
• Q: Why should an ObjectARX developer use managed C++?• Expose existing ARX code to managed languages• .NET platform development enhancements
• Garbage collection, reflection, serialization, XML, etc.• WinForms
• Access to AutoCAD Managed API beyond• Q: Why should an AutoCAD developer use C++?
• Custom Object/Entity available in C++/ARX only.• Native platform interop - mixed managed and unmanaged code• Leverage C++’s unique strengths (e.g., templates, generic
programming, multiple inheritance, deterministic resource management and cleanup)
• C++ native platform performance edge
www.autodesk.com
AutoCAD .NET API Documentation
How do I get started?
ObjectARX SDK Includes:• SDK Samples!• ObjectARX Developer’s
Guide• Managed Reference Guide
• Acad_Mgd.chm
• ADN extranet• DevNotes• DevHelp Online
• Visual Studio Class Browser
www.autodesk.com
Dictionary Entry
R12 Symbol Tables
Header Variables Named Object Dictionary
Other BTR
Paper Space Model Space
Entity
Entity
Entity
DATABASE
Block Table
AutoCAD Database Ownership Hierarchy
See the ObjectARX Developer’s Guide and SDK samples for reference…
www.autodesk.com
Important Managed Classes
www.autodesk.com
Demand Loading .NET applications
[HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\AutoCAD\R16.2\ACAD-4001:409\Applications\AcLayer]"DESCRIPTION"="AutoCAD Layer Manager""LOADER"="C:\\Program Files\\AutoCAD 2006\\aclayer.dll""LOADCTRLS"=dword:0000000e"MANAGED"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\AutoCAD\R16.2\ACAD-4001:409\Applications\AcLayer\Commands]"LAYER"="LAYER"
[HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\AutoCAD\R16.2\ACAD-4001:409\Applications\AcLayer\Groups]"ACLAYER_CMDS"="ACLAYER_CMDS“
Use Installers to set these keys!
www.autodesk.com
What’s new in AutoCAD’s .NET API ?What happened to Open/Close?
Managed Applications use Transactions exclusively
Why?
• Exception handling is vastly simpler• Cleaner, more robust code
• Less likely to leave objects in an open state• Performance is superior to Open/Close
• Each Close() has associated overhead• Simultaneous write access
• Multiple write-enabled pointers allowed• Nested transactions allowed
www.autodesk.com
Managed .NET API for AutoCAD 2006 Using Open/Close with Exceptions
TryBlockTable = Database.BlockTableId.Open(OpenMode.ForRead)ModelSpace = BlockTable(BlockTableRecord.ModelSpace).Open(OpenMode.ForWrite)Text = New MTextText.SetContents("Hello World !!")ModelSpace.AppendEntity(text)
FinallyIf Not BlockTable Is Nothing Then
BlockTable.Close()End IfIf Not ModelSpace Is Nothing Then
ModelSplace.Close()End IfIf Not Text Is Nothing Then
Text.Close()End If
End Try
www.autodesk.com
Managed .NET API for AutoCAD 2006 Using Transactions with Exceptions
Dim Trans As TransactionTrans = db.TransactionManager.StartTransaction()Try
BlockTable = Trans.GetObject(Database.BlockTableId, OpenMode.ForRead)ModelSpace = Trans.GetObject(BlockTable(BlockTableRecord.ModelSpace), OpenMode.ForWrite)Text = New MText()Text.Contents = "Hello World !!"ModelSpace.AppendEntity(Text)Trans.AddNewlyCreatedDBObject(Text, True)Trans.Commit()
Finally Trans.Dispose()End Try
www.autodesk.com
Nesting Transactions
1. Client starts Trans1 and gets Obj1 & Obj2 2. Client starts Trans2 and gets Obj2 & Obj33. Client commits Trans2
• Trans2 changes are committed4a. Client commits Trans1
• Trans1 changes are committed4b. Client aborts Trans1 instead
• Trans1 (and Trans2) changes are rolled back
obj1 obj2Transaction 1
1
obj1 obj2
obj1 obj3
obj2
obj1
obj2
obj3
obj2Database
obj2 obj3Transaction 2
2 3 4
obj1 obj3
obj2
obj2 obj3
www.autodesk.com
Managed .NET API for AutoCAD 2006
AutoCAD 2006 Managed SDK Samples:
• Tab Extension
• Selection Set
• Docking Palette
• Events/Reactors
• Custom Jig
www.autodesk.com
AutoCAD API Interoperability
.NET COM VB/A ObjectARX Lisp
.NET XExpose a COM server from the .NET app. Develop VB/A COM client to connect.
Use /clr mixed-managed C++ or…Expose a COM server from the .NET app. Develop COM client in ARX to connect.or…Export unmanaged functions, using .NET delegates to call.
Expose custom commands in NET. Call from Lisp.
COM VB/A
Port to VB7or…Expose a COM server from VB. Use COM interop to connect.
XExpose a COM server from VB. Develop a COM client in ARX to connect.or…VBARUN for VBA macros
SendCommandor
VBARUN
ObjectARX
Use /clr managed C++ and/or write a managed wrapper …or…Export global functions in your ARX, and use P/invoke to access.
Expose a COM server from the ARX app. Develop a COM client in VBA to connect.
XUse acedDefun() to define Lisp functions. Call from LISP.
Lisp
Expose custom commands in Lisp. Call from .NET.
Expose custom commands in Lisp. Call from VBA.
acedCommand()or
Call custom commands X
New API Development
Exis
tin
g c
od
e b
ase
www.autodesk.com
ObjectARX Interop – Platform Invoke
How do I access my old unmanaged code?
Declare Auto Function MessageBox Lib "user32.dll" (ByVal hWnd As Integer, _
ByVal txt As String, ByVal caption As String, ByVal Typ As Integer) As Integer
<Autodesk.AutoCAD.Runtime.CommandMethod("pinvoke")> _ Public Function platformInvoke() mgPolyTestApp.MessageBox(0, “Houston, we have a problem",
"Platform Invoke Example", 0) End Function
www.autodesk.com
AutoCAD API Interoperability
Mixed Module
(e.g. acdbmgd.dll)
Mixed mode modules: Wrapping ObjectARX for a Managed API
Unmanaged C++/ObjectARX API
Managed C++ code
AutoCAD 2006 .NET Applications (Any .NET language)
AutoCAD
It Just Works (IJW) and P/Invoke
C++ Only!
www.autodesk.com
ObjectARX Interop – Project SettingsSetup for Managed C++ extensions in ObjectARX modules
Compiler settings for using managed C++• General – Use managed extensions = Yes• C++ - General – Compile as Managed = Assembly Support (/CLR)• C++ - General – Debug information format = not Edit and Continue• C++ - General – Detect 64-bit portability = No• C++ - Code Generation – Basic runtime checks = Default• C++ - Code Generation – Enable Minimal Rebuild =No• C++ - Precompiled Headers – Create/Use Precompiled header = No• Link – Input - Force Symbol References - __DllMainCRTStartup@12• Link – Command Line – Addition Options - /NOENTRY
Comment out dbgrip.h in dbxheaders.h (in the SDK includes)• Suggested: use #ifdef _MANAGED or similar for conditional #include
Add references to standard and AutoCAD managed assemblies:#using <mscorlib.dll> #using <c:\Program Files\AutoCAD 2006\acmgd.dll>#using <c:\Program Files\AutoCAD 2006\acdbmgd.dll>//…and any others required for you
Use the ‘managed’ compiler directive to compile managed ARX code#pragma managed
Optional: Remove warnings regarding incompatibilities with __fastcall#pragma warning(disable: 4561)
www.autodesk.com
ObjectARX Interop – Entry Point
/NOENTRY used in mixed managed modules – Use acrxEntryPoint instead: See: http://support.microsoft.com/?id=81442
extern "C" AcRx::AppRetCodeacrxEntryPoint(AcRx::AppMsgCode msg, void* pkt){
if(msg==AcRx::kInitAppMsg)__crt_dll_initialize();// Manually initialize static
and global varsif(msg==AcRx::kPreQuitMsg)
__crt_dll_terminate();return AcRx::kRetOK;
}
Good News is: ObjectARX 2006 Wizard handles this for you in mixed-managed projects!!
www.autodesk.com
AutoCAD 2006: Dynamic Blocks API
• API Provides programmatic manipulation of block intelligence
• Access underlying intelligence of enhanced blocks
• Managed, ActiveX and ObjectARX APIs
– Developed managed API SDK Sample “DynBlockProps” – Modifying properties
• Dynamic Blocks uses several new core API technologies
• “Technology” APIs can be used as general purpose tools for existing ARX classes!
– AcDbEvalGraph – provide intelligent inter-object references
– AcDbBlockInsertionPoints – application-defined grip points for blocks
– AcDbAlignment – intelligent alignment of entities
» Includes managed RxEvent reactor delegate
• SDK samples created to demonstrate core APIs
• Specify Block Insertion points, Entity Grips, and Alignment
www.autodesk.com
New Compiler-neutral string utility class - AcString
• No dependency on ATL/MFC
• Provides conversion between UNICODE and ANSI
• Comparable functionality to MFC’s ‘CString’ class
• See the ‘SheetSet’ SDK sample
New Arc-length Dimension class – AcDbArcDimension
• Represents AutoCAD Arc length Dimensions
Tool Palette ObjectARX/COM Enhancements
• Context Menu enhancements
• API Support for new Multi-Edit feature – IAcadTool2
2006: New Classes and Enhancements
www.autodesk.com
Only the file format
Is different…
Deployment model
• Same as Menus/Toolbars
• Per-user support folder
• Existing ActiveX interface
• Same as always
2006: Menu and Toolbar Customization
www.autodesk.com
AutoCAD 2006 API Wishlist1 .NET API - On-Screen input acquisition (Jigs, prompts, selection
sets, input filters…) 34%
2 .NET API - More UI support (docking windows, extended tabs on AutoCAD dialogs)
30%
3 .NET API - Custom Objects 30%
4 .NET API - Reactors 24%
5 DWF metadata publishing API 21%
6 Undo API 20%
7 Zoom factor dependent custom graphics 19%
8 Publish API for automating paper and DWF plotting on a server 20%
9 .NET API - Top level object (Application, document object, preferences)
17%
10
.NET API - Tool Palette support 16%
11
.NET API - AcGe 2d curves and 3d surfaces 11%
12
.NET API - Xref management 10%
13
.NET API - Boundary Representation support 7%
Items in green delivered in AutoCAD 2006
www.autodesk.com
Where to Learn More – ADN and ADN Mentoring
ADN• The Autodesk support program for professional software developers.• Unlimited direct support from Autodesk software engineers• Access to virtually all Autodesk software including betas (for software development
use only)• Technical briefings and API training classes• Learn more at www.autodesk.com/joinadn
ADN Mentoring Program• Onsite Mentoring by Autodesk software engineer for up to 1 week at your site• Offsite mentoring – phone, video email etc from engineer who visited• Complements ADNsupport:
• Your mentor knows much more about your issues and can help direct you in the future
• Your Mentor can liaise with internal Autodesk product and API experts• Your Mentor can access Autodesk source code, and internal knowledge bases
www.autodesk.comWhere to Learn More about .NET – Books & Blogs
• Visual Basic .NET and the .NET Platform by Andrew Troelsen APress
• Visual Basic .NET Programming by Gary Cornell and Jonathan Morrison APress
• Applied Microsoft .NET Framework Programming by Jeffrey Richter Microsoft Press
• Windows Forms Programming in C# by Chris Sells
• Blogs (WebLogs)
• MSDN
www.autodesk.comWhere to Learn More about .NET – Tips & Tricks
• 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/
www.autodesk.com
Introduction to the AutoCAD 2006 API