2. www.autodesk.com
AutoCAD 2006 API Overview
Agenda:
• 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…
3. 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
4. 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.
5. www.autodesk.com
The Wine – New API’s
• AutoCAD Managed .NET API
• ObjectARX SDK and UI customization
updates
6. 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
7. 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!
8. www.autodesk.com
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
9. www.autodesk.com
Why use the AutoCAD Managed API (.NET)?
Pros Cons
• Powerful, modern streamlined API • Performance hit from ARX, but not bad …
• Some Interop performance costs
• Metadata resolves “DLL hell” versioning • Jit compiling takes CPU cycles
• Raw Performance is near native x86
• Mixed languages – choose your weapons • Natural learning curve associated with
• Resolves MFC and CRT dependency – new platforms
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
10. 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’!
11. 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 .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
12. www.autodesk.com
Programming in .NET - Advantages
Strings are all Unicode!
• Old Way – Unmanaged C++/COM
CComBSTR 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;
13. 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);
14. www.autodesk.com
Why move to .NET in AutoCAD
Mature 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)
16. www.autodesk.com
Why do we want to use .NET?
Mature API constructs
Is now…
‘Define the event handler
m_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));
}
17. www.autodesk.com
AutoCAD .NET and C++ Developers
Two 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
18. 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
19. www.autodesk.com
AutoCAD Database Ownership Hierarchy
DATABASE
R12 Symbol Tables Block Table Named Object Header Variables
Dictionary
Model Space
Paper Space
Dictionary Entry
Other BTR
Entity
Entity Entity
See the ObjectARX Developer’s Guide and SDK samples for
reference…
21. www.autodesk.com
Demand Loading .NET applications
[HKEY_LOCAL_MACHINESOFTWAREAutodeskAutoCADR16.2ACAD-
4001:409ApplicationsAcLayer]
"DESCRIPTION"="AutoCAD Layer Manager"
"LOADER"="C:Program FilesAutoCAD 2006aclayer.dll"
"LOADCTRLS"=dword:0000000e
"MANAGED"=dword:00000001
[HKEY_LOCAL_MACHINESOFTWAREAutodeskAutoCADR16.2ACAD-
4001:409ApplicationsAcLayerCommands]
"LAYER"="LAYER"
[HKEY_LOCAL_MACHINESOFTWAREAutodeskAutoCADR16.2ACAD-
4001:409ApplicationsAcLayerGroups]
"ACLAYER_CMDS"="ACLAYER_CMDS“
Use Installers to set these keys!
22. 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
23. www.autodesk.com
Managed .NET API for AutoCAD 2006
Using Open/Close with Exceptions
Try
BlockTable = Database.BlockTableId.Open(OpenMode.ForRead)
ModelSpace =
BlockTable(BlockTableRecord.ModelSpace).Open(OpenMode.ForWrite)
Text = New MText
Text.SetContents("Hello World !!")
ModelSpace.AppendEntity(text)
Finally
If Not BlockTable Is Nothing Then
BlockTable.Close()
End If
If Not ModelSpace Is Nothing Then
ModelSplace.Close()
End If
If Not Text Is Nothing Then
Text.Close()
End If
End Try
24. www.autodesk.com
Managed .NET API for AutoCAD 2006
Using Transactions with Exceptions
Dim Trans As Transaction
Trans = 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
26. www.autodesk.com
Managed .NET API for AutoCAD 2006
AutoCAD 2006 Managed SDK Samples:
• Tab Extension
• Selection Set
• Docking Palette
• Events/Reactors
• Custom Jig
27. www.autodesk.com
AutoCAD API Interoperability
New API Development
.NET COM VB/A ObjectARX Lisp
Expose a COM server from Use /clr mixed-managed C++ Expose custom
the .NET app. Develop or…Expose a COM server from commands in NET.
.NET
X VB/A COM client to the .NET app. Develop COM
client in ARX to connect.
Call from Lisp.
connect.
or…Export unmanaged functions,
using .NET delegates to call.
Port to VB7
Expose a COM server from
Existing code base
X
or… SendCommand
COM VB/A VB. Develop a COM client
Expose a COM or
in ARX to connect.
server from VB. VBARUN
or…
Use COM interop
to connect. VBARUN for VBA macros
Use /clr managed
C++ and/or write a Expose a COM server from Use acedDefun() to
managed wrapper the ARX app. Develop a define Lisp
ObjectARX
…or… COM client in VBA to X functions. Call from
Export global connect. LISP.
functions in your
ARX, and use
P/invoke to access.
Expose custom Expose custom commands acedCommand()
commands in Lisp. in Lisp. Call from VBA.
X
Lisp or
Call from .NET. Call custom commands
28. 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
29. www.autodesk.com
AutoCAD API Interoperability
Mixed mode modules: Wrapping ObjectARX for a Managed API
AutoCAD
Unmanaged C++/ObjectARX API
It Just Works (IJW) Mixed Module
and P/Invoke (e.g.
acdbmgd.dll)
Managed C++ code
C++ Only!
AutoCAD 2006 .NET Applications
(Any .NET language)
30. www.autodesk.com
ObjectARX Interop – Project Settings
Setup 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 FilesAutoCAD 2006acmgd.dll>
#using <c:Program FilesAutoCAD 2006acdbmgd.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)
31. 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::AppRetCode
acrxEntryPoint(AcRx::AppMsgCode msg, void* pkt)
{
if(msg==AcRx::kInitAppMsg)
__crt_dll_initialize();// Manually initialize static and global vars
if(msg==AcRx::kPreQuitMsg)
__crt_dll_terminate();
return AcRx::kRetOK;
}
Good News is: ObjectARX 2006 Wizard handles this for
you in mixed-managed projects!!
32. 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
33. www.autodesk.com
2006: New Classes and Enhancements
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
34. www.autodesk.com
2006: Menu and Toolbar Customization
Only the file format
Is different…
Deployment model
• Same as Menus/Toolbars
• Per-user support folder
• Existing ActiveX interface
• Same as always
35. www.autodesk.com
AutoCAD 2006 API Wishlist
1 .NET API - On-Screen input acquisition (Jigs, prompts, selection sets, input 34%
filters…)
2 .NET API - More UI support (docking windows, extended tabs on AutoCAD 30%
dialogs)
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
36. 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
37. www.autodesk.com
Where 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
38. www.autodesk.com
Where 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/
The diagram above illustrates the process used to compile and execute managed code, that is, code that uses the CLR. Source code written in C#, VB.NET, or some other language that targets the CLR is first transformed into MSIL by the appropriate language compiler. Before execution, this MSIL is JIT compiled into native code for whatever processor the code will run on. The default is to JIT compile each method when it is first called, but it’s also possible to “pre-JIT” the MSIL. With this option, all methods are compiled before the application is loaded, so the overhead of JIT compilation on each initial method call is avoided. One point worth noting is that all languages targeting the CLR should exhibit roughly the same performance. While some compilers may produce better MSIL code than others, large variations in execution speed are unlikely.
Cross language Exception handling!
This is probably one of the most used functions in ObjectARX, and it demonstrates an example of API calls that don’t lend themselves to good coding practices. It is probably the antithesis of good API design…
In the Managed API, we have gone to great lengths to clear up some of the ambiguities which can be encountered by such API functions. I believe that no less than 6 classes were defined just to formalize with the complexity that you had to deal with using that single ARX function.
One of the main points of rewriting the .NET library has been about lessons learned in our collective coding experience. We know from millions of projects how not to write code. We, as an industry, have agreed upon standards which reflect code which can be developed, and reused efficiently. We are happy to see that Microsoft has paid attention to these coding principles in designing this framework. One of the most important points for us is what it allows us to do for our AutoCAD and vertical developers. For instance, we spent a considerable amount of time making our API use more mature coding constructs. Rather than simply ‘wrapping’ all the global functions into various classes, we reexamined how they should be used, and designed the best possible conduit for each of them. Constructs like collections, enumerators and events are some examples… Here is a prime example of a function which demonstrates techniques that are less than savory. This function takes no less than thirty arguments. Nearly all of them are pass by reference so the arguments are yours to interrogate and manipulate.
Here is how this same functionality is represented in the managed API.
Developers need to understand the database structure.
ObjectARX programmers will already be familiar with this type of inheritance, but for VB programmers this is all new stuff.
Accessing the HKLM section of the registry requires adminstrative (or at least power user) privileges on the machine. An installer is the best way to set these.
Every object opened anywhere within the try block needs to be checked for validity and closed within the Finally because it is not known when the exception could have occurred. This leads to really ugly code. This example only uses three objects…
In contrast, transactions can handle exceptions very elegantly. In fact, while it looks as though there is no handler for a catch(), the transaction knows that if Dispose() is called before Commit(), then the transaction is to be aborted, and the changes rolled back. So this demonstrates that exceptions are basically handled automatically.
In addition, transactions handle nesting quite nicely too…
AutoCAD which shown at the top, is unmanaged. Normally in C++ ObjectARX programmers access AutoCAD through an entirely unmanaged API. We’ve written a managed wrapper for the unmanaged ObjectARX API. This has been done using the Visual C++ managed extensions. So basically, now we have a DLL which mixes managed and unmanaged code and enables the communication between them both.
This is done because it is unsafe to run managed code within DllMain(), which is what would happen if we have static or global vars in our ARX. Most importantly to note: The ObjectARX Wizard has been updated to handle mixed-managed projects, and wraps the above entry point code into it’s acrxEntryPoint macros. Show the new ARX Wizard in use!
CUI file is brand new file, which represents menus toolbars, workspaces and lisp files. Your customization will now be represented by these new files. For AutoCAD 2006, older MNC, MNU files will be migrated to the new CUI format automatically, so legacy deployment models will work. Beyond AutoCAD 2006, the deployment model will be: Build the menus/toolbars/workspaces the way you want in your development machine. Create a ‘Partial CUI’ file. This is the file that you will distribute in your installer. The menu can be loaded in the deployment machine with the CUI command, the MENULOAD command or with the ActiveX MenuGroup object – MenuLoad() API (passing the CUI filename). Once a menu/toolbar etc is loaded with one of these, it is added to the ‘currently loaded’ partial menus in the main CUI file for the profile. Do not try to parse the main CUI file. The format is likely to change since this is the first go-round of the format. If you want your menus added, you can have an ARX demand load at startup, calling the COM apis (or just MENULOAD) to have them available. Modifying the registry for this will not work in AutoCAD 2006! MNC MNU and MNS files are no longer used in AutoCAD 2006, but are used only to migrate to CUI files. MNR (resource) and MNL (lisp) files are still used. A CUI file can reference a MNL as easily as it can reference a LSP file…so it is a bit more flexible.
ADN Mentoring Summary There are times in your software development cycle when you need specific, intensive help from Autodesk. You want us to understand what you're trying to do, to provide expert and detailed advice on how to proceed, and to be by your side so you can avoid the pitfalls that software developers can stumble into. The ADN Mentoring service combines onsite consulting with telephone consulting to quickly get your development team up to speed. Audience Our Mentoring service is available to ADN members only. It is particularly suited to software developers who are starting development on a new Autodesk product, are migrating their product to a new version, or who require intensive development or debugging support for a short period of time. Description The ADN Mentoring service provides you with an experienced Autodesk Software Engineer to help and advise you on all aspects of your application design and implementation. Your Mentor will visit you at your office so that they can thoroughly understand your project, and provide you with expert advice on how to proceed.? When onsite, your Mentor becomes a part of your development team - at your choice, they can consult on software architecture, train your people, help debug your code, and do what it takes to make your development project a success.? Your Mentor will then be available offsite by telephone, email and Instant Messenger ? providing follow-on advice and assistance as and when you need it.