103
Copyright Autodesk Developer Network 2010 Introduction to .NET AutoCAD .NET API

AutoCAD .NET Training

Embed Size (px)

Citation preview

Page 1: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Introduction to .NETAutoCAD .NET API

Page 2: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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: Give you complete of coverage of all API functions

Special topics: Teach you the basics of .NET framework with VB.NET Language

Page 3: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 4: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Overview of .NET: Framework basics

Why .NET?

Most used features

The development environment

Page 5: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Why are we using .NET?

The Microsoft standard development tool

Autodesk use .NET as 3rd party development platform for almost all products

We can use the same programming skills across multiple Autodesk products

Page 6: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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

Page 7: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Most used features of .NET

Basic types Allow easy manipulation of basic data (integers, doubles, strings,

arrays)

WinForms Easy to create forms (dialogs)

Create by drag’n’drop Lots of ready-to-use controls

Lots of 3rd party developers create and expose features to .NET

Page 8: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Autodesk products are exposed to .NET

Not all products, but several

To use it, your add-in just have to reference the product API assembly (.dll)

Deeply integrated with Microsoft .NET You can use them together, mixed, merged, blended…

Page 9: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

The IDE - Visual Studio

Professional and Free editions For AutoCAD R18 (2010/2011): Visual Studio 2008 SP1

Intelisense Assist you by auto completing your code

Page 10: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Key learning points

.NET is used across several Autodesk products Powerful and easy to learn

We commonly use basic types and WinForms

Reference other assemblies (.dll) to access new features

The IDE is Visual Studio Express edition - FREE

Page 11: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 12: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Plugin Basics: Organizing the code

Namespaces

Methods and Properties

Best practices

Parameters and return values

Page 13: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Namespaces

Group object by features Example:

The namespace Autodesk.AutoCAD.EditorInput group all features related to geometry in AutoCAD

Define the full qualified name of an object Example:

Autodesk.AutoCAD.EditorInput.Editor.WriteMessage

Use the imports keyword reduce the typing Example:

Imports Autodesk.AutoCAD.EditorInputthen use the short Editor.WriteMessage

Page 14: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Methods

Parameters – some methods require data

Return value – we can use the returned value For example to make a comparison or assign to another

variable/object

Page 15: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Calling methods

Some methods just perform an action, just call line.DrawOnScreen()

When a method require data, you need to create the data before call the method myInteger = 10

line.Resize(myInteger)

Or pass the data directly line.Resize(10)

Some methods return data myInteger = spatialPoint.CalculateDistanceTo(anotherPoint)

Page 16: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Property

It is a method that do not require parameters

Usually do not execute an action

Always return a value

Page 17: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Method and Properties for Objects

A method execute an action for the context of the object line.Resize(10)

Only this line will be resized, not any other line

A property return a value that is used to define the object myInteger = line.Length

The length of this line only

Page 18: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Methods versus Properties

Method names contain verbs Define an action Performa a task each time you call it

Property names contain nouns or adjectives Refer to a sub data or characteristic

Page 19: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Best Practices to Create Methods

Use a name that make sense Instead CrNLine, use CreateNewLine

Prefer create small/short methods that perform one task Task equals the name of the method

Page 20: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Creating a Method

First declare the access level 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

Page 21: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Return value

Returning value Sub return empty or Function return some valuePublic Sub MethodName()Public Function MethodName() As String

Do not return value Return a String

Page 22: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Parameters

The parameter name is the variable name You will use this variable inside the method

Can receive values to work with Public Sub MethodName(param1 As String)

Parameter name

Parameter type

Page 23: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Method example

Multiply a number by other number Public Function Multiply(number1 As Integer, _ number2 as Integer) as Integer Return number1 * number2End Sub

Indicate an ENTER

Notice the SPACE before

Page 24: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Key learning points

Methods can receive parameters and return values

Properties always return values

Best practice: Methods with verbs Properties with nouns/adjectives

Page 25: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Preparing for first plugin: ObjectARX SDK

ObjectARX SDK Help files Supporting files Samples

Page 26: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

How does a plugin for AutoCAD works?

Assembly(.dll)

Compile

Code witten in Visual Basic .NET

Load inside AutoCAD with NETLOAD

Reference to AutoCAD DLLs. Use it from

ObjectARX INC folder

Project VB.NET

Page 27: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Crearing a new VB.NET Project

Create a new project

Plugin for AutoCAD must be of typeClass Library

Page 28: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Adding reference to AutoCAD

Add references

AcMdgInterface resourcesC:\ObjectARX 2011\inc\AcMgd.dll

AcDbMgdDatabase resourcesC:\ObjectARX 2011\inc\AcDbMgd.dll

IMPORTANT:Set Copy Local as FALSE

Page 29: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Routine as an AutoCAD custom command

1. Regular VB routine

2. AutoCAD Imports

3. Mark the routine as command

4. Access the editor

5. Write a message

Now just compile, load inside AutoCAD with NETLOAD and call myCommand

Imports Autodesk.AutoCAD.RuntimeImports Autodesk.AutoCAD.ApplicationServicesImports Autodesk.AutoCAD.EditorInput

Public Class Class1

End Class

Public Sub myRoutine()

End Sub

<CommandMethod("myCommand")> _

'Access the AutoCAD Editor Dim ed As Editor = Application. _ DocumentManager. _ MdiActiveDocument. _ Editor

'Write a simple message ed.WriteMessage(“My Hello World")

Page 30: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lab 1 – Hello World

Page 31: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

NETLOAD or Registry Keys

HKEY_CURRENT_USER

HKEY_LOCAL_MACHINE

SOFTWARE

Autodesk

AutoCAD

R18.1

ACAD-9001:409

Applications

YourAppName

R17.0: 2007 .1: 2008 .2: 2009R18.0: 2010 .1: 2011

X000: Civil3DX001: AutoCAD

409: English416: Portuguese040A: Spanish

"DESCRIPTION"="Custom App Name""LOADER"="C:\\folder\\appName.dll""LOADCTRLS"=dword:0000000e"MANAGED"=dword:00000001

For all users

For a specific user only

Page 32: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Object ARX Wizards

Add-In <<ObjectARX SDK folder>>\utils\ObjARXWiz\ArxWizards.msi

Templates for a VB.NET or C# application

Up-to-date version at the blog http://blogs.autodesk.com/through-the-interface

Page 33: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

.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/

Page 34: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 35: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Prompting for User Input

Use PromptXXXOptions to set the parameters for prompting 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

To prompt, use Editor’s GetXXX functions Examples - GetAngle, GetString, GetDistance Pass PromptXXXOptions into Editor.GetXXX

Result of prompting stored in PromptResult or derived types Examples – PromptDoubleResult, PromptIntegerResult etc.

Page 36: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Prompt for a point on screen

Config the options to select a point on screen

Ask the user to select the point and store the selection result

Create a Point3d variable to store the selected point Requires an additional imports for Point3d: Autodesk.AutoCAD.Geometry

Write the point coordinates (XYZ)

Dim pointOptions As New PromptPointOptions("Select a point: ")

Dim pointResult As PromptPointResult = ed.GetPoint(pointOptions)

Dim selectedPoint As Point3d = pointResult.Value

ed.WriteMessage(selectedPoint.ToString())

Page 37: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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

Page 38: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lab 2 –User Input

Page 39: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Additional prompts

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

Help file for the rescue!

Page 40: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Help File: Reference Guide

<<ObjectARX SDK folder>>\docs\arxmgd.chm

Page 41: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 42: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

AutoCAD DWG as a 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 can refer to other objects – such as a line having a reference to a layer

Page 43: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Database Primary Key: Object Identity (ObjectID)

All Objects that exist in the database have an ObjectId 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

All database objects also have an Handle May NOT be unique per session Persistent Get it using Handle property

Page 44: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Database Structure: Overview

Database

BlockTable LayerTable Other tabels

Model Space

Paper Space 0

BlockTableRecord

Other blocks

0

LayerTableRecord

Other layers

TextStyleTable

DBDictionary

Paper Space 1

DimStyleTable

UcsTable

Materials

Visual Styles

Others(Custom)

LineTypeTable

ViewTable

ViewportTable

RegAppTable

Page 45: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Snoop Tools (for AutoCAD’s database)

ArxDbg (C++) ObjectARX SDK

MgdDbg(C#) ADN

Page 46: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Transactions: Overview

Every operation should be done inside a transaction, read or write

AutoCAD never return the object/entity directly, only the ObjectId

Use the ObjectId with a Transaction to GetObject

Each outermost transaction represents an UNDO

Database Transaction

StartTransaction

Commit

GetObject ( Model Space ID )

Model Space . Append ( Entity )

Page 47: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Transaction.GetObject method

Use GetObject to open an object Transaction.GetObject( ObjectId , OpeningMode)

ObjectId: obtained from different ways

Opening Mode: 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

Page 48: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Using a Transaction to Get an Object

First access the Database

The Using keyword dispose (finish) the transaction

Finally open the object using its objectId

'Acess the DatabaseDim db As Database = Application.DocumentManager.MdiActiveDocument.Database

'Start a transactionUsing trans As Transaction = db.TransactionManager.StartTransaction

'Get the BlockTable Dim bt As BlockTable = trans.GetObject(db.BlockTableId, OpenMode.ForRead)

End Using 'Dispose the transaction

Page 49: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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

obj1 obj2Transaction 1

1

obj1 obj2

obj1 obj3

obj2

obj1

obj2

obj3

obj2Database

obj2 obj3Transaction 2

2 3 4

obj1 obj3

obj2

obj2 obj3

Page 50: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Database Components: Symbol Tables

SymbolTables: BlockTable, LayerTable and others

Symbol Tables Containers to store Symbol Table Records Example BlockTableRecord, LayerTableRecord

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 – Iterate with ‘For Each’

Page 51: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Using Transaction: new block definition

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)

'Check if contains 'myBlock' If Not (bt.Has("myBlock")) Then

'Create a new block Dim myBlock As New BlockTableRecord myBlock.Name = "myBlock"

'Change the bt (BlockTable) to ForWrite bt.UpgradeOpen()

'Add the new block to the BlockTable bt.Add(myBlock) ‘Inform the transaction about new objects

trans. AddNewlyCreatedDBObject(myBlock, True) End If 'Save changes to the Database trans.Commit() End Using 'Dispose the transaction

Same as previous slideCheck if the block already exist

Create a new block (in memory)

Change the block table to ForWrite

Append the new block to block table Now it is database

resident

Save changesTip: Commit is faster than Abort

ALWAYS inform the transaction

Page 52: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Using Transaction: list all block table records

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

Page 53: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Database Structure: Model Space

Under BlockTable

Model Space is a BlockTableRecord (BTR) This concept also applies to Paper Spaces

and other internal and user-defined blocks

Each BTR contains Entities

One type of entity for each geometric type

Is enumerable – Iterate with ‘For Each’

Database

BlockTable

Model Space

BlockTableRecord

Entity

Line

Circle

MText

Polyline

Many others...

Page 54: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Append an Entity to Model Space

Dim db As Database = Application.DocumentManager.MdiActiveDocument.Database Using trans As Transaction = db.TransactionManager.StartTransaction

'open the current space (can be any BTR, usually model space) Dim mSpace As BlockTableRecord = trans.GetObject(db.CurrentSpaceId, _ OpenMode.ForWrite)

'Create and configure a new line Dim newLine As New Line newLine.StartPoint = New Point3d(0, 0, 0) newLine.EndPoint = New Point3d(10, 10, 0)

'Append to model space mSpace.AppendEntity(newLine)

'Inform the transaction trans.AddNewlyCreatedDBObject(newLine, True)

End Using 'Dispose the transaction

Open the current space for write. Can be any other BTR.

Create and configure a new line (in-memory)

Append to the current space, now the line it is database resident

Page 55: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Database Components: Class Map

Page 56: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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.

Manual Dispose is required in a few cases, e.g. Transaction (Using)

Page 57: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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 e.g. invalid variable, data or context

Page 58: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Dealing with exceptions

A .NET add-in code cannot treat ALL exceptions Specially when occur at the host application

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

Page 59: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Be fearless: Try

VB.NET

Try 'try something hereCatch

End Try

Try some code inside TRY

RequiredMore next slide

Page 60: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Investigate: Catch

VB.NET

Try Catch (ex As Exception) 'something went wrong 'treat it hereEnd Try

If something went wrong during TRY, the runtime stop the execution and move to

CATCH

OptionalThis ex variable

contains valuable information to

understant the exception

Page 61: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Be organized: Finally

VB.NET

Try

Catch

Finally 'clean up hereEnd Try

OptionalWe usually clean up a variable or close a connection

This block is always executed, regardless if succeed (TRY) or fail (CATCH)

Page 62: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Summary of Try/Catch/Finally

To handle exception, try and catch are required ex parameter is optional Finally block is optional

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)

Page 63: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Reusable transaction

Drag’n’drop to Visual Studio Toolbox

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

Page 64: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lab 3 – Create Entity, Block and Block Reference

Page 65: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 66: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Dictionaries

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

Page 67: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Named Object Dic. and Extension Dic.

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

Page 68: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

How open a Dictionary

Named Object Dictionary (Database-level)

Extension Dictionary (Entity-level)

'The NOD always exist, can open directlyDim nod As DBDictionary = trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead)

'The Extension Dictionary may not exist for a specific entityDim line As Line = trans.GetObject(lineId, OpenMode.ForRead)

‘Check if the ObjectId is null, create if necessaryIf (line.ExtensionDictionary.IsNull) Then line.CreateExtensionDictionary() 'Create the Ext. Dic.End If

'Open the Extension DictionaryDim extDic As DBDictionary = trans.GetObject(line.ExtensionDictionary, OpenMode.ForRead)

Page 69: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Dictionary Hierarchy

Named Object Dictionary

Extension Dictionary

DBDictionary

Xrecord

DBDictionary

ResultBufferArray of

TypeValuesNew

AsArray

SetAt GetAt

SetAt GetAt

Data

One DBDictionary can contain others. Good to organize the structure.Also avoid conflict with other apps.

Page 70: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lab 5 - Dictionary

Page 71: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Runtime Type Identification

Why we need to know the type of an Entity?

Some collections can contain different types

Get the type of each item, then decide what to do

This is very common and useful for Autodesk add-in development

Page 72: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Get Type of a Variable

Every variable have a GetType method

Dim myString As StringmyString = "something text here"

Dim variableType As TypevariableType = myString.GetType()

MessageBox.Show(variableType.ToString())

Page 73: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Type comparison

Compare one variable type against another

Useful when we don’t know the type Very common with Autodesk APIs

If (someVariable.GetType() Is GetType(String)) Then 'now we know is a String!End If

Page 74: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Convert between types

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

Technical name: cast

Page 75: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Direct conversion: The easy way

You know is possible, but you are not sure

Common used: CInt(variable): convert to Integer CStr for string, CDbl for double

The variable parameter can be almost anything that make sense (string or numeric)

Page 76: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Direct conversion: The faster way

You are sure is possible

Faster than CInt, CStr, etc

CType(variable, type)

Throw exception when it is not possible

Page 77: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lets try before convert

Good when you do not know if is possible If failed, just return Nothing (no exception)

TryCast(variable, type)

Dim myString As StringmyString = TryCast(someVariable, String)If (myString IsNot Nothing) Then 'ok, the conversion went fineEnd If

Page 78: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Key learning points

The GetType return the type of any variable

Use Is or IsNot keyword to compare types

Direct conversions with CInt, CStr, etc, and with CType

TryCast if you are not sure, then check if is not Nothing

Page 79: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 80: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Forms and UI Basics

WinForm API basics

How create a form

Common used controls

Respond to user actions

Using the form

Page 81: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Windows® OS is based on windows

Everything on screen is some type of window

You move focus across windows The window with focus is usually “highlighted” and will receive

keyboard input

Forms are specialized windows Can host other windows, in this case controls

Page 82: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Forms with WinForms API

Require reference to System.Windows.dll The DevCamp template already have the assemblies

Namespace System.Windows.Forms

Main features Forms Controls for forms (button, textbox, combobox) Ready to use forms (dialogs to open, save, folder) Others (menus, ribbon, tooltip)

Page 83: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Forms in real life

Form without focus

Form with focus (highlighted)

Form control: Label

Form control: Textbox (with focus, cursor)

Form control: Button

Page 84: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Creating my first Form

Add a Windows Form

Add controls for the form

Page 85: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Controls are variable too

Each control is a variable – rename for further use

Select a control, mouse right-click

Properties

Current variable name and type

Change the name here

Page 86: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Do something when the user click!

For some controls we need execute something when the user interacts with it Example: when the user clicks on a button

Select a button, mouse right-click, “Properties”

Select “Events”

Select “Click”, then mouse double-click to

create the method button1_click

Or just double-click on the button, same result

Page 87: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Key learning points

Create a new form using menu Project, Add Windows Form

Common used controls: label, textbox, button

Perform actions after interaction with user using events

How use a form with ShowDialog method

Page 88: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Create the control events

TIP

Page 89: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Using a form inside AutoCAD

Modal forms Application.ShowModalDialog

Modeless forms (consider Palette instead) Application.ShowModelessDialog

Persists size and position automatically

Page 90: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Context menu

Application Level Application.AddDefaultContextMenuExtension

Object Level Application. AddObjectContextMenuExtension –per RXClass

Page 91: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Tabbed Dialog Extensions

Create a new tab inside Options dialog

Page 92: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 93: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Event Handling - Example

Create the event handler (callback)

Associate the event handler with an event

Disconnect the event handler

Sub objAppended(ByVal o As Object, ByVal e As ObjectEventArgs) 'Do something here 'Do something else, etc. End Sub

Dim db As Database = Application.DocumentManager.MdiActiveDocument.Database AddHandler db.ObjectAppended, New ObjectEventHandler(AddressOf objAppended)

RemoveHandler db.ObjectAppended, AddressOf objAppended

Page 94: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

PaletteSet

Custom dockable window inside AutoCAD

In the Autodesk.AutoCAD.Windows namespace

PaletteSets contain controls such as a UserControl Use Visual Studio wizards to create the controls Use the Add method of the PaletteSet the add the UserControl

Page 95: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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

Page 96: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lab 4 - PaletteSet and Database Events

Page 97: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 98: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

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 The Delegate is a PointMonitorEventHandler

Page 99: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lab 6 - PointMonitor

Page 100: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Class Agenda

Overview of .NET Plugin Basics User Interaction Database fundamentals Dictionaries User Interface Events Input PointMonitor Jigs

Page 101: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Jigs Allows you to graphically manipulate and form an Entity in real time

Two types of Jig available EntityJig – controls only one entity DrawJig – controls one or more

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 Use the Editor Drag function to start the jig

Page 102: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Lab 7 - Jig

Page 103: AutoCAD .NET Training

Copyright Autodesk Developer Network 2010

Autodesk

Thank You!