Post on 11-May-2018
Overview
Topicsinthissection
IntroductionUsingtheAPIReferenceSettingUpVisualStudioAutoCAD
Pleasesendusyourcommentaboutthispage
Introduction
TheAutoCAD®Map3D2008.NETAPIprovidesaccesstoAutoCADMap3Dfunctionalitysoyoucanmodifyandextenditforyourownpurposes.TheAPIcanbeusedbyany.NETlanguage.
ThesnippetsinthisguidearemainlyinVB.NET,butmostsamplesareavailableinVB.NET,C#,andC++.
SomeoftheshortsnippetsinthisguidewritetotheAutoCADMap3Dconsole.Ensurethattheconsoleisvisible.PressCTRL+9todisplaytheorhideconsole.
Namespaces
TheAutodesk.Gis.Mapnamespacecontainsthe.NETclassesforAutoCADMap3D.Someofthegeneral-purposeclassesaredefineddirectlywithinthetop-levelAutodesk.Gis.Mapnamespace,butmostaregroupedintolower-levelnamespacesbelowAutodesk.Gis.Map.
Forthesakeofcleanercode,allexampleswithinthisguidewillassumethefollowingImports:
ImportsAutodesk.Gis.Map
ImportsAutodesk.AutoCAD.DatabaseServices
ImportsAutodesk.AutoCAD.ApplicationServices
Inthisguide,objectsfromnamespaceswithinAutodesk.Gis.Maparepartiallyqualified.Forexample,theTableclassintheAutodesk.Gis.Map.ObjectDatanamespaceisgenerallygivenasObjectData.Table.ThismakesitsimpletofindtheclassdetailsintheAPIReference.
Certainchaptersmaydefineadditionalimports.Forexample,thechapteraboutObjectDatadefines
ImportsAutodesk.Gis.Map.ObjectData
RelatedDocumentation
AutoCADMap3D2009includesthenewGeospatialPlatformAPIforworkingwithgeospatialdata.SeetheGeospatialPlatformDeveloper’sGuidefordetails.
Pleasesendusyourcommentaboutthispage
UsingtheAPIReference
TheAPIreferenceappliestomultiplelanguages.Becauseofdifferencesbetweenlanguages,thetermsandsyntaxusedinthereferencemaynotmatchagivenlanguage.Somedifferencesare:
APIRef VB.NET C#
__abstract MustInherit abstract
__sealed NotInheritable sealed
__gc
:: . .
NULL Nothing Null
ThisguideusesVB.NETformostexamples.ThesampleapplicationsareavailableinVB.NET,C#,andC++;
Pleasesendusyourcommentaboutthispage
SettingUpVisualStudio
TheAutoCADMap3DSDKrequiresMicrosoftVisualStudio2005.Tosetupaprojectforacustomapplication,opentheprojectproperties.
Note TheseinstructionsapplytoVB.NET.SettingupaprojectforC#isslightlydifferent.
OntheApplicationtab,settheapplicationtypetoClasslibrary.
Addthefollowingreferences.TheDLLsareintheAutoCADMap3Dinstallationfolder:
acdbmgd.dll
acmgd.dll
ManagedMapApi.dll
acdbmgd.dllcontainsthefollowingAutoCADnamespaces:
Autodesk.AutoCAD.Colors
Autodesk.AutoCAD.ComponentModel
Autodesk.AutoCAD.DatabaseServices
Autodesk.AutoCAD.DatabaseServices.Filters
Autodesk.AutoCAD.Geometry
Autodesk.AutoCAD.GraphicsInterface
Autodesk.AutoCAD.GraphicsSystem
Autodesk.AutoCAD.LayerManager
Autodesk.AutoCAD.Runtime
acmgd.dllcontainsthefollowingAutoCADnamespaces:
Autodesk.AutoCAD.ApplicationServices
Autodesk.AutoCAD.EditorInput
Autodesk.AutoCAD.GraphicsSystem
Autodesk.AutoCAD.PlottingServices
Autodesk.AutoCAD.Publishing
Autodesk.AutoCAD.Runtime
Autodesk.AutoCAD.Windows
Autodesk.AutoCAD.Windows.ToolPalette
ManagedMapApi.dllcontainsthefollowingAutoCADMap3Dnamespaces:
Autodesk.Gis.Map
Autodesk.Gis.Map.Annotation
Autodesk.Gis.Map.Classification
Autodesk.Gis.Map.Constants
Autodesk.Gis.Map.DisplayManagement
Autodesk.Gis.Map.Filters
Autodesk.Gis.Map.ImportExport
Autodesk.Gis.Map.MapBook
Autodesk.Gis.Map.ObjectData
Autodesk.Gis.Map.Project
Autodesk.Gis.Map.Query
Autodesk.Gis.Map.Topology
Autodesk.Gis.Map.Utilities
Foreachofthereferences,settheCopyLocalpropertytoFalse.Double-clickthereferencetoopentheproperties.
SetthereferencepathtotheAutoCADMap3Dinstallationdirectory.
OntheDebugtab,set:
Startexternalprogram:InstallDir\acad.exe,whereInstallDiristheinstallationdirectoryforAutoCADMap3D.
Workingdirectory:InstallDir\UserDataCache\
RunningAutoCADMap3DCustomApplications
EverycustomapplicationrequiresatleastonesubroutinethatcanbecalledfromAutoCADMap3D.IdentifythisusingtheCommandMethodattribute.Forexample,usingVB.NETthesyntaxis:
<CommandMethod("CustomCommand")>_
PublicSubCommandSub()
UsingC#thesyntaxis:
[CommandMethod("CustomCommand")]
publicvoidCommandSub();
Torunacustomapplication,typetheNETLOADcommandattheAutoCADMap3Dcommandprompt.BrowsetotheDLLcontainingthecustomapplicationassembly.Opentheassembly.ThismakesanycustomcommandsdefinedusingtheCommandMethodattributeavailabletotheAutoCADMap3Dsession.
Toexecuteacommand,typethecommandmethodatthecommandprompt.Intheexampleabove,thiswouldbe
CustomCommand
Formoredetails,refertotheAutoCADdocumentation.
Pleasesendusyourcommentaboutthispage
AutoCAD
AutoCADMap3DreliesonAutoCADformuchofitsfunctionality.ItisimportanttounderstandsomebasicAutoCADconceptsbeforewritingAutoCADMap3Dapplications.Forcompletedetails,refertotheAutoCADdeveloperdocumentation.
Inparticular,managingobjectsintheAutoCADdatabaseisimportant.
Transactions
TheAutoCADdatabaseusesatransactionmodelforaccesstoallobjects.
Touseanyobjectinthedatabase,startatransactionandusethetransactiontoopenthedatabaseobjectineitherread-onlyorread-writemode.Transaction.Open()returnsagenericreference.Castthattothetypeofobjectbeingreturned.Forexample,givenadatabaseobjectidforaMapBookobject,thefollowingwillreturnareferencetotheobject:
DimbookObjAsMapBook.Book
bookObj=CType(trans.GetObject(mapBookId,OpenMode.ForWrite),
MapBook.Book)
Shortexamplesinthisguidemaynotincludeallthetransactionprocessing,sotheycanhighlighttheconceptsbeingdiscussed.Inallcases,though,ifanychangesarebeingmadetothedrawing,itshouldbeassumedthatthefollowinggeneralstructureisinplace:
DimtransAsTransaction=Nothing
DimdocsAsDocumentCollection=Application.DocumentManager
DimactiveDocAsDocument=docs.MdiActiveDocument
Try
trans=activeDoc.TransactionManager.StartTransaction()
'
'Openobject(s)
'
DimbookObjAsMapBook.Book
bookObj=CType(trans.GetObject(mapBookId,OpenMode.ForWrite),
MapBook.Book)
'
'Insertcodetoprocesstransaction
'
'Committransaction
'
trans.Commit()
Catch
'
'Handleexception,andcanceltransaction
'
Finally
trans.Dispose()
EndTry
Althoughtransactionscanbenested,thisisnotrecommended.Onecomplicationisthataddinganentitytakesplaceimmediately,butremovinganentitydoesnottakeeffectuntilthetransactionhasbeencommitted.
Note ManyexamplesinthisguideassumethatactiveDocreferstotheactivedocument.
Pleasesendusyourcommentaboutthispage
Overview
AnAutoCADMap3DsessionrepresentstheactivestateoftheMap3Dapplication.
MostoftheclassesforworkingwiththesessionaredefinedintheAutodesk.Gis.Mapnamespace.
ThereisasingleinstanceoftheMapapplication,availablethroughtheApplicationpropertyoftheabstractclass
Autodesk.Gis.Map.HostMapApplicationServices
ThisreturnsaMapApplicationobjectthatrepresentstheentireapplication.Ithassomeread-onlypropertiesthatprovideaccesstoobjectsinthesession.OneofthemainpropertiesisProjects.
Projectsreturnsacollectionofallopenprojects,aProjectCollectionobjectintheAutodesk.Gis.Map.Projectnamespace.AprojectisrepresentedbyaProjectModelobject.AprojectisthecontainerforaMap3Ddrawingandallitsassociatedobjects.Nearlyallinteractionwithadrawingbeginswithaproject.
ActiveProjectreturnstheProjectModelforthecurrentlyactiveproject.
Note Forhistoricalreasons,theAPIusesthetermprojectwheretheuserinterfacewillnormallyusemapordrawing.
Forexample,thefollowinggetsthecurrentproject:
DimmapAppAsMapApplication
mapApp=HostMapApplicationServices.Application
DimactiveProjAsProject.ProjectModel
activeProj=mapApp.ActiveProject
Thefollowingprocessesallopenprojects:
DimmapAppAsMapApplication
mapApp=HostMapApplicationServices.Application
DimprojListAsProject.ProjectCollection
projList=mapApp.Projects
ForEachprojectAsProject.ProjectModelInprojList
'Processprojects
Next
Note ManyoftheexamplesinthisguideassumethatmapAppandactiveProjhavealreadybeendefinedasintheexampleabove.
AprojectiscloselyrelatedtoanAutoCADdrawing.InAutoCADMap3D,openingadrawingautomaticallycreatesanewproject.Youcannotinstantiateanewprojectdirectly.
MapApplication.GetDocument()returnstheAutoCADdocumentassociatedwithaproject.Conversely,Project.ProjectCollection.GetProject()returnstheProjectModelforanAutoCADdocument.
Forexample,thefollowingdiagramshowsasessionthathasthreeopenprojects.Thefirstprojectreferstoexternaldrawingsinitsdrawingset.Anyoneoftheprojectscouldbeactiveatonetime.EachprojecthasacorrespondingAutoCADdrawing.
AdditionalProjectProperties
ProjectModelobjectshavemanypropertiesthatprovideaccesstodifferentaspectsofthedrawing.Forexample,theDrawingSetpropertygetsthedrawingsetfortheproject.
Someoftheimportantprojectpropertiesare:
Annotations
Database
DrawingSet
ODTables
Topologies
Formoredetailsaboutthevariousproperties,refertotheappropriatechaptersinthisguide.
AutoCADDatabase
TheProjectModel.Databasepropertyreturnsareferencetothe
AutoCADdatabase.ThisisnecessaryformanyAutoCADoperations.
ProjectOptions
TheProjectModel.Optionspropertyreturnsareferencetotheproject’soptions.
Pleasesendusyourcommentaboutthispage
DrawingObjects
DrawingobjectsarethevisibleitemsinanAutoCADdrawing.
Note TheAutoCADdeveloperdocumentationgenerallyusesthetermentityorAcDbentitywhendiscussingdrawingobjects.
IntheAutoCADAPI,anAutodesk.AutoCAD.DatabaseServices.DBObjectobjectrepresentsanyobjectinthedrawingdatabase,includingdrawingobjects.ADBObjectcanbereferredtobyeither:
Autodesk.AutoCAD.DatabaseServices.Handle
Autodesk.AutoCAD.DatabaseServices.ObjectID
AHandleisapersistentidentifierthatisstoredwiththeAutoCADdatabasewhenitissaved.Eachhandleisuniquewithinasingledrawing,butdifferentdrawingsarelikelytohaveduplicatehandlesreferringtoseparateobjects.
AnObjectIDisusedforquickaccesstodrawingobjectswithinanAutoCADsession.Theyarenotpersistent,though.Theyexpirewhenthedrawingisclosed.
MapObjects
BecauseasingleAutoCADMap3DprojectcanincludemorethanoneAutoCADdrawing,anAutoCADhandleisnotsufficienttouniquelyidentifyanobject.
AMapObjectId,definedinthenamespaceAutodesk.Gis.Map.Utilities,identifiesanobjectbyitsAutoCADhandleandbyitsdrawingidentifier.TheMapObjectId.ObjectHandlepropertyistheAutoCADhandle,andMapObjectId.DrawingIdisthedrawingidentifier,anobjectoftypeUtilities.MapId.
ObjectData
Topicsinthissection
IntroductionCreatingaTableAttachingObjectDataGettingObjectDataUpdatingandDeletingRecords
Pleasesendusyourcommentaboutthispage
Introduction
Objectdataprovidesawayofattachingadditionalinformationtodrawingobjects.ItismorepowerfulandflexiblethanAutoCADblockattributesbecauseobjectdatacanbeattachedtoanyobjectinadrawing.
Note Objectdatacanonlybeattachedtodrawingobjects.FDOfeaturesourceshaveadifferentwaytohandlefeatureproperties.
TheclassesforhandlingobjectdataaremostlywithintheObjectDatanamespace.Codeinthischapterassumesthefollowing:
ImportsAutodesk.Gis.Map.ObjectData
Tables
Internally,objectdataisstoredintables.Eachdrawinghasitsownsetoftables,availablefromtheProjectModel.ODTablesproperty.ThisreturnsanobjectoftypeObjectData.Tables.
Forexample,ifmapAppistheMapapplication,thefollowingwillgettheobjectdatatablesfortheactivedrawing:
DimactiveProjectAsProject.ProjectModel=mapApp.ActiveProject
DimtableListAsObjectData.Tables=activeProject.ODTables
ObjectData.Tables.GetTableNames()returnsalistofthetablenamesthathavebeendefinedforthedrawing.
Togetasingletablefromthesetoftables,usetheObjectData.Tables.Itemproperty.Notethatthisrequiresatablenameasaparameter,notatablenumber.Forexample:
DimtableAsObjectData.Table=tableList.Item("table1")
or
DimtableAsObjectData.Table=tableList("table1")
UseTables.IsTableDefined()toseeifatablenameexists.Anattempttogetatablethatdoesnotexistthrowsanexception.
FieldDefinitions
ColumnsinatablearedefinedbyObjectData.FieldDefinitionobjects,whichdescribethedatatypeanddefaultvalue.ThedatatypesaredefinedintheConstants.DataTypeenum:
UnknownType
Integer
Real
Character
Point
Records
EachrowinthetableisoftypeObjectData.Record.Everyrecordinthetableisassociatedwithadrawingobject.
TheItempropertyofanObjectData.Recordcontainsthevaluesfortherecord,oneforeachfielddefinitioninthetable.EachitemisoftypeUtilities.MapValue,whichisageneral-purposeclassforstoringdata.
Pleasesendusyourcommentaboutthispage
CreatingaTable
Creatingatablerequires:
CreatinganObjectData.FieldDefinitionsobject
Addingfielddefinitionsforeverycolumninthetable
CreatingthetablebyaddingthefielddefinitionstotheODTablesobjectforthedrawing
CreateanObjectData.FieldDefinitionsobjectusingtheProjectModel.MapUtility.NewODFieldDefinitions()method.AddfieldsusingtheFieldDefinitions.Add()method.Forexample,ifmapAppistheMapapplication,thefollowingcreatesfielddefinitionsfor2columns:
DimfieldDefsAsObjectData.FieldDefinitions
fieldDefs=_
mapApp.ActiveProject.MapUtility.NewODFieldDefinitions()
Dimdef1AsObjectData.FieldDefinition
def1=fieldDefs.Add("FIRST_FIELD","Ownername",_
Autodesk.Gis.Map.Constants.DataType.Character,0)
def1.SetDefaultValue("A")
Dimdef2AsObjectData.FieldDefinition
def2=fieldDefs.Add("SECOND_FIELD","Assessmentyear",_
Autodesk.Gis.Map.Constants.DataType.Integer,1)
def2.SetDefaultValue(0)
GetareferencetotheODTablespropertyforthedrawing,andaddthefielddefintionstocreateanewtable.
DimtablesAsObjectData.Tables
tables=mapApp.ActiveProject.ODTables
tables.Add("NewTable",fieldDefs,"Description",True)
GetareferencetothetableusingTables.Item().Thisexpectsastringparameter.
DimtableAsObjectData.Table
table=tables("NewTable")
RemovingaTable
Toremoveatable,getareferencetotheODTablespropertyforthedrawing,andcallTables.RemoveTable().
DimtablesAsObjectData.Tables
tables=mapApp.ActiveProject.ODTables
tables.RemoveTable("NewTable")
Pleasesendusyourcommentaboutthispage
AttachingObjectData
Addingobjectdatatoadrawingobjectrequires:
Creatinganemptyrecord
Initializingtherecordwithcorrecttypesforthetable
Settingvaluesforeachcolumn
Attachingtheobjectdatabyaddingtherecordtothetable
CreateanemptyrecordusingthestaticmethodObjectData.Record.Create().Thisdoesnotdefineanyfieldsfortherecord.Initializetherecord,whichcreatesfieldsofthecorrecttype,usingTable.InitRecord().
DimrecAsObjectData.Record
rec=ObjectData.Record.Create()
table.InitRecord(rec)
EachItempropertyintherecordisoftypeUtilities.MapValue,whichisageneral-purposeclassforstoringdataofvarianttypes.Tosetanyfield,getareferencetothefieldfromtheRecordobjectusingtheItemproperty.AssignthevaluewithMapValue.Assign().Forexample,ifrecisarecordinatablewherethesecondfieldisoftypeinteger,thefollowingwillassignavalueof10tothefield.
DimvalAsUtilities.MapValue
val=rec(1)
val.Assign(10)
AddtherecordtothetablewithTable.AddRecord()andassociateitwithanobject.ThisrequiresaRecordandeitheranAutoCADDBObjectorObjectIdasparameters.
newTable.AddRecord(rec,objId)
Asingledrawingobjectmayhavemorethanoneobjectdatarecordinagiventable.
Pleasesendusyourcommentaboutthispage
GettingObjectData
Togetallobjectdatarecordsfromasingletableforadrawingobject:
GettheObjectData.Tablesobjectforthedrawing.
Gettheindividualtable.
GettheObjectData.Recordscollectionfortheobject,usingoneoftheGetObjectTableRecords()methods.
Iteratethroughtherecordsinthecollection.
Processthefieldsineachrecord.
ThefollowingexamplewritesthevaluesfromtableforobjIdtotheconsole.
DimfieldDefsAsObjectData.FieldDefinitions=_
table.FieldDefinitions
DimrecsAsObjectData.Records
recs=table.GetObjectTableRecords(0,objId,_
Constants.OpenMode.OpenForRead,True)
If(recs.Count()>0)Then
ForEachrecAsObjectData.RecordInrecs
ForiAsInteger=0Torec.Count()-1
DimvalAsAutodesk.Gis.Map.Utilities.MapValue
val=rec(i)
DimfieldDefAsObjectData.FieldDefinition
fieldDef=fieldDefs(i)
acEditor.WriteMessage(
vbNewLine+fieldDef.Name+":")
SelectCaseval.Type
CaseConstants.DataType.Character
acEditor.WriteMessage(val.StrValue)
CaseConstants.DataType.Integer
acEditor.WriteMessage(val.Int32Value.ToString)
CaseConstants.DataType.Point
acEditor.WriteMessage("point")
CaseConstants.DataType.Real
acEditor.WriteMessage(val.DoubleValue.ToString)
CaseElse
acEditor.WriteMessage("undefined")
EndSelect
Next
Next
EndIf
recs.Dispose()
Processingalltablesforanobjectissimilar.InsteadofcallingTable.GetObjectTableRecords()foranindividualtable,callTables.GetObjectRecords()foralltables.Whenprocessingthefields,besuretotogetthefielddefinitionsfromthecorrecttableforthecurrentrecord.
GettheObjectData.Tablesobjectforthedrawing.
GettheObjectData.Recordscollectionfortheobject,usingoneoftheGetObjectRecords()methods.
Iteratethroughtherecordsinthecollection.
Getthetablenameforthecurrentrecord.
Getthefieldsdefinitionsforthetable.
Processthefieldsineachrecord.
Note Whenyouhavefinishedprocessingtherecords,releaseanyofthedisposableobjectswiththeirDispose()methods.ThisappliestoanyclassesinheritingAutodesk.AutoCAD.Runtime.DisposableWrapper,likeObjectData.Table,ObjectData.Records,orUtilities.MapValue.
Pleasesendusyourcommentaboutthispage
UpdatingandDeletingRecords
Toupdateordeleterecords,theymustbeopenedforwriteaccessinthecalltoTable.GetObjectTableRecords()orTables.GetObjectRecords().
FieldsinarecordareoftypeUtilities.MapValue.Toupdateafield,getareferencetothevaluefromtheRecordobject.AssignanewvalueusingMapValue.Assign()andupdatetherecordusingRecords.UpdateRecord().Thefollowingexamplesetsthevalueofthefirstfieldinarecord:
DimvalAsUtilities.MapValue=rec(0)
val.Assign(19)
recs.UpdateRecord(rec)
Todeletearecord,getanIEnumeratorusingRecords.GetEnumerator().AdvancetheenumeratortotherecordtobedeletedandcallRecords.RemoveRecord().Thefollowingexampledeletesthefirstrecordforanobject.
DimrecsAsObjectData.Records
recs=table.GetObjectTableRecords(0,objId,_
Constants.OpenMode.OpenForWrite,True)
DimieAsIEnumerator
ie=recs.GetEnumerator()
ie.MoveNext()
recs.RemoveRecord()
recs.Dispose()
Pleasesendusyourcommentaboutthispage
DataConnect
Topicsinthissection
OverviewSettingUpVisualStudioCreatingthePlugin
Pleasesendusyourcommentaboutthispage
Overview
TheDataConnectAPIcanbeusedtocreatepluginsfortheDataConnectdialog.UsethistocreatenewconnectionformsforFDOproviders,eitherprovidersthatareinstalledwithAutoCADMap3Doradditionalproviders.
Note TheDataConnectAPIisnotpartoftheGeospatialPlatformAPI.Itis,however,includedinthetechnicalpreviewforthisreleaseofAutoCADMap3D.Forthatreasonitisdocumentedinthisguideinsteadofthe.NETDeveloper’sGuide.
IfacustompluginworkswithaproviderinstalledwithAutoCADMap3D,itreplacestheexistingformfortheprovider.Forexample,acustomformfortheAutodeskOracleprovidercouldlooklikethefollowing.Theoutlinedareaisthecustomform,embeddedintheDataConnectdialog.
ToaddanewoptiontotheDataConnectdialog,completethefollowingsteps:
EnsuretheFDOproviderDLLisinstalledwithAutoCADMap3D.
EnsuretheFDOproviderislistedinproviders.xml.
Createtheplugintousetheprovider.
SavethepluginDLLinthePlugins\DataConnectfolderoftheAutoCADMap3Dinstallation.Ifthefolderdoesnotexist,createit.
providers.xmlislocatedintheFDO\binfolderoftheAutoCADMap3Dinstallation.ItcontainsentriesforeachavailableFDOprovider.
Pleasesendusyourcommentaboutthispage
SettingUpVisualStudio
TocreateaprojectusingtheDataConnectAPI,followtheinstructionsintheAutoCADMap3D.NETDeveloper’sGuide.Addthefollowingreferencestotheproject:
Autodesk.Gis.Plugins.dll
AcMapDataConnectPlugins.dll
TheassembliesarelocatedintheAutoCADMap3Dinstallationfolder.
Pleasesendusyourcommentaboutthispage
CreatingthePlugin
Note Toensurethepluginisloaded,placetheDLLinthePlugins\DataConnectfolderundertheAutoCADMap3Dinstallationfolder.Pluginsinthisfolderthatfollowtheproperstructureareloadedondemand.Thereisnoneedtorunthenetloadcommand.
UsingVisualStudio,createanewproject.AddaUserControltotheproject.ThecontrolwillbeembeddedintheDataConnectdialog.
ThepluginclassmustimplementtheIDataConnectConnectionPlugininterface.ItalsorequiresaDataConnectPluginAttributewiththeFDOprovidername.Theprovidernamemustmatchthenameinproviders.xml.Forexample:
[DataConnectPluginAttribute("Autodesk.Oracle.3.1")]
publicpartialclassSampleProviderConnectUIPlugin
:UserControl
,IDataConnectConnectionPlugin
{
IDataConnectConnectionPluginprovidesthenecessarymethodsforAutoCADMap3Dtointeractwiththecontrol.Itinherits2otherinterfaces:IDataConnectPluginandIPlugin.
TheimplementationforIDataConnectPlugincanbesimple,asfollows.TheIDataConnectPluginHostinterfacecontainsasingleproperty,HostApplication,oftypeobject.Whenattached,itcontainsareferencetothehostapplicationobject,Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication
//IDataConnectPluginimplementation
protectedIDataConnectPluginHost_host;
protectedstring_providerName;
publicvoidAttach(IDataConnectPluginHosthost)
{
_host=host;
}
publicvoidDetach(){_host=null;}
publicIDataConnectPluginHostHost
{
get{return_host;}
}
publicUserControlClientControl
{
get{returnthis;}
}
Similarly,theimplementationforIPluginneedsmethodstogetandsetproperties.Thepropertiesareusedtodescribetheplugin.Theymaybedisplayedtotheuserandshouldbelocalized.TheDependenciespropertyisnotcurrentlyused.
//IPluginimplementation
protectedstringtitle="title";
protectedstringdescription="description";
protectedstringcompany="company";
protectedstringversion="3.0.0";
protectedType[]dependencies;
publicstringTitle
{
get{returntitle;}
set{title=value;}
}
publicstringDescription
{
get{returndescription;}
set{description=value;}
}
publicstringCompany
{
get{returncompany;}
set{company=value;}
}
publicstringVersion
{
get{returnversion;}
set{version=value;}
}
publicType[]Dependencies
{
get{returndependencies;}
}
IDataConnectConnectionPlugincontainsmethodstogetandsettheconnectionparametersfortheFDOprovider,sotheimplementationdependsontherequirementsoftheprovider.Forcompletedetailsaboutthemethods,refertotheAutoCADMap3D.NETAPIReferenceSupplement.Generallythesemethodswillworkwithfieldsonthecustomform.
ThepropertiesofIDataConnectConnectionPluginreturninformationabouttheconnectionparametersfortheprovider.TheseareusedtoopentheFDOconnection.
Property Description
ConnectionParameterNames Alistofparametersfortheprovider.
ConnectionParametersValid Boolean.Trueifthecurrentparametersarevalidfortheprovider.
ProviderName Theprovidername.
ThemethodsofIDataConnectConnectionPlugingetandsetparametervalues:
Methodname Description
GetConnectionParameter() Returnsthecurrentvalueofaconnectionparameter.
SetConnectionParameter() Setsthevalueofaconnectionparameter.Thisshouldupdatetheformfieldfortheparameter.
Initialize() Calledwhenthepluginfirstloads.
SetConnectionParametersToDefaults() Setsallconnectionparameterstodefaultvalues.
Thereisalsoanevent,ParameterValueChanged,whichshouldfirewhenaparametervaluechanges.ThiseventisrequiredsothecontainingformisabletoupdatetheConnectbuttonstatebasedonthevalidityofthecurrentparametervalues.
Pleasesendusyourcommentaboutthispage
Annotation
Topicsinthissection
OverviewAnnotationTemplatesExpressionsinAnnotationsInsertingAnnotationsUpdatingandRefreshingAnnotationsAnnotationOverrides
Pleasesendusyourcommentaboutthispage
Overview
Annotationsprovideawaytolabeldrawingobjects,basedondataassociatedwiththeobjects.Theassociateddatacancomefromvariousplaces,suchasobjectdata,linkeddatabases,orobjectproperties.Forexample,ifadrawingcontainsparcels,andtheparcelshaveobjectdatawiththenameoftheparcelownerorthemostrecentsalepriceoftheparcel,thenthesevaluescouldbeaddedtothemapaspartofanannotation.
Eachannotationisbasedonanannotationtemplate,whichisaspecialblockinthedrawing.Thetemplatedescribestheannotation,andusuallycontainsannotationtextdefiningthevariablecontent.
Anewannotationiscreatedbyinsertingareferencetotheannotationtemplate.Thiscreatesareferencetotheannotationblock,substitutingthepropervaluesintheexpressionfields.
TheclassesforhandlingannotationsaremostlywithintheAnnotationnamespace.Codeinthischapterassumesthefollowing:
ImportsAutodesk.Gis.Map.Annotation
Pleasesendusyourcommentaboutthispage
AnnotationTemplates
Anannotationtemplateisaspecialblockinthedrawing.Itdefinesthefixedandvariablepartsoftheannotation.
Note Formoreinformationaboutblocks,refertotheAutoCADdeveloperdocumentation.
Internally,annotationtemplatesuseaspecialnamingconvention.ThenamesofallblockscontainingannotationtemplatesbeginwithACMAP_ANN_TEMPLATE_.ThisprefixisdefinedintheAnnotations.TemplateNameBlockTableRecordPrefixproperty.
AnnotationAPIcalls,though,usetheannotationnameasitappearsintheUI.Forexample,anannotationtemplatenamedParcelNamewouldbestoredinablocknamedACMAP_ANN_TEMPLATE_ParcelName,butitwouldbecreatedwithacalltoAnnotations.CreateAnnotationTemplate("ParcelName").
TheProjectModel.AnnotationspropertyreturnsanAnnotationsobjectthatcanbeusedformanagingtheannotationsandannotationtemplates.
Attributes
AnAutoCADblockcancontainattributedefinitions,whicharetextentitiesthatcandefineinformationaltextforeachblockreference.
Inanannotationtemplate,attributedefinitionsareusedtodefinethevariablepartsoftheannotation.Forexample,iftheannotationsincludeobjectdata,thenattributedefinitionsintheblocktemplatedefinewhatobjectdatashouldappearandhowitwillbedisplayed.
TheAttributeDefinitionclassinheritstheDBTextclass,whichinheritstheEntityclass.ThesehavepropertiessuchasColorandHeightthatdefinehowtheannotationwillappearinthedrawing.Forexample,tosetthe
textheightforanannotation,settheHeightpropertyoftheattributedefinitionusedfortheannotation.
Note Thepropertiesusedfortheattributedefinitioncanalsobemodifiedusingexpressionstrings.SeeExpressionsinAnnotationsfordetails.
CreatinganAnnotationTemplate
AlthoughanannotationtemplateisaformofAutoCADblock,itmustbecreatedusingtheMapAPIoritwillnotberecognizedproperly.
Startatransaction.
CreatetheannotationtemplateusingAnnotations.CreateAnnotationTemplate().
GetareferencetotheannotationtemplateusingAnnotations.Item().
Ifrequired,setblockpropertiesfortheannotationtemplateusingAnnotationTemplate.SetExpressionString().Forexample,thiscanbeusedtorotatetheblockreferencetomatchtherotationoftheobjectbeingannotated.
Ifrequired,addfixeddrawingobjectstotheannotationtemplate.GettheAutoCADblockidusingtheAnnotationTemplate.BlockDefinitionIdpropertyandadddrawingobjectstothetemplateusingstandardAutoCADAPIcalls.
AddvariableannotationtexttothetemplateusingAnnotationTemplate.CreateAnnotationText().Thiscreatesanattributedefinitionintheblock.
Setthedisplaypropertiesoftheannotationtextbysettingpropertiesfortheattributedefinition.
SettheexpressionstringfortheannotationtextusingAnnotations.SetExpressionString().
Committhetransaction.
Annotations.CreateAnnotationTemplate()createsanemptytemplate.ItreturnsanAutoCADObjectIDthatistheidoftheblocktable
record.GetareferencetotheannotationtemplateobjectusingAnnotations.Item().
DimannotationsAsAnnotation.Annotations=_
activeProj.Annotations
DimtransAsTransaction=Nothing
trans=activeDoc.TransactionManager.StartTransaction()
DimnewTemplateIdAsObjectId=_
annotations.CreateAnnotationTemplate("templateName")
DimnewTemplateAsAnnotation.AnnotationTemplate=_
annotations(newTemplateId)
Ifrequired,setblockpropertiesfortheannotationtemplate.SeeExpressionsinAnnotationsfordetails.
newTemplate.SetExpressionString(_
Annotation.AnnotationExpressionFields.BlockRotation,".ANGLE")
Addobjectstothetemplate.Theycanbenormaldrawingobjectsorannotationtext.
Toaddnormaldrawingobjects,usestandardAutoCADmethods.
DimlineAsNewLine
line.StartPoint=NewGeometry.Point3d(0.0,-0.6,0.0)
line.EndPoint=NewGeometry.Point3d(2.0,-0.6,0.0)
DimblockTableRecAsBlockTableRecord
blockTableRec=newTemplateId.GetObject(OpenMode.ForWrite)
blockTableRec.AppendEntity(line)
trans.AddNewlyCreatedDBObject(line,True)
Toaddannotationtext,createanannotationtextobject.ThisisaspecialtypeofAutoCADattributedefinition.AnnotationTemplate.CreateAnnotationText()returnstheAutoCADObjectIdoftheattributedefinition.OpenthisobjectforwritingandcasttoanAttributeDefinitionobject:
DimexpressionTextIdAsObjectId
expressionTextId=newTemplate.CreateAnnotationText()
DimattDefAsAttributeDefinition
attDef=_
CType(trans.GetObject(expressionTextId,OpenMode.ForWrite),_
AttributeDefinition)
MostofthepropertiesfortheannotationtemplatecanbesetusingtheAttributeDefinitionproperties.Forexample:
attDef.Position=_
NewAutodesk.AutoCAD.Geometry.Point3d(0.0,0.0,0.0)
attDef.Tag="testTag"
attDef.Height=0.5
attDef.VerticalMode=TextVerticalMode.TextVerticalMid
attDef.HorizontalMode=TextHorizontalMode.TextCenter
attDef.AlignmentPoint=
NewAutodesk.AutoCAD.Geometry.Point3d(0.0,0.0,0.0)
TheannotationtextmustbesetusingAnnotations.SetExpressionString().SeeExpressionsinAnnotationsfordetails.
Pleasesendusyourcommentaboutthispage
ExpressionsinAnnotations
Useexpressionstosetthetextorthedisplaypropertiesoftheannotation.Someoftheitemsthatcanuseexpressionsare:
Annotationtext
Textcolor
Textsize
Rotationangle
Positionrelativetothedrawingobjectbeingannotated
Note Propertiesinanattributedefinitioncanbeoverriddenbyannotationexpressions.Forexample,iftheattributedefinitiondefinesthelocationofthetext,theannotationexpressioncouldoverrideit.
AnnotationTemplate.SetExpressionString()setspropertiesfortheentiretemplate.Annotations.SetExpressionString()setspropertiesforannotationtextwithintheblock.
ExpressionsareevaluatedbytheAutoLISPinterpreter,andreturnasinglevalue.Dependingonthepropertybeingset,thevaluecanbenumericorstring.Iftheexpressioncannotbeevaluatedproperlyitdisplaystheattributetagnameinstead.
Note Formoredetailsaboutexpressions,includingalistoffunctionsandvariables,seetheMap3DHelp.IntheReferenceGuidesectionthereisachapterabouttheExpressionEvaluator.
TheenumAnnotation.AnnotationExpressionFieldscontainsthecompletelistoffieldsthatcanuseexpressions.
Inmostcases,expressionsareusedtodefinethetextoftheannotation,buttheycanalsobeusedtodefinethingslikecolor,size,orposition.
Example
Tosettheannotationtextbasedonobjectdata,usethesyntax:fieldname@tablename.Forexample:
ImportsAutodesk.Gis.Map.Annotation
annotations.SetExpressionString(attDef,_
AnnotationExpressionFields.AttributeDefinitionAnnotationString,_
":PARCEL_OWNER@ParcelData")
Pleasesendusyourcommentaboutthispage
InsertingAnnotations
Toinsertanannotation,calloneoftheAnnotationTemplate.InsertReference()methods.TheyallrequireanObjectIdorObjectIdCollectionasparameter,toidentifythedrawingobjectstobeannotated.
Thiscreatesablockreferenceinthedrawing.Itevaluatestheannotationexpressionsandusestheresultstosetthetextorotherpropertiesofthereference.
Aninsertedannotationreferencecanalsohaveoverridesthatchangethedisplayproperties.SeeAnnotationOverridesfordetails.
Pleasesendusyourcommentaboutthispage
UpdatingandRefreshingAnnotations
Onceinserted,annotationreferencesdonotchangeunlesstheyareexplicitlychanged.Forexample,iftheobjectdataforadrawingobjectchanges,anyanotationsthatusetheobjectdatawillstilldisplaytheoriginalvalue.
Therearetwooperationsforrevisingexistingannotationreferences:
Updating
Refreshing
Updatingremovesandrecreatesalltheannotationsthatuseatemplate.Refreshingre-evaluatestheannotationexpressions,butdoesnotremoveout-of-dateannotations.
Toupdateannotations,callAnnotationTemplate.UpdateReferences().
newTemplate.UpdateReferences(True)
Torefreshannotations,callAnnotationTemplate.RefreshReferences().
newTemplate.RefreshReferences(True)
Pleasesendusyourcommentaboutthispage
AnnotationOverrides
Anannotationoverridecanbeappliedwhenanannotationreferenceiscreated.Itchangesselectedpropertiesoftheannotationtemplate.Forexample,anannotationoverridecanchangethecolorortextsizeoftheannotation.
Annotationoverridescanapplytothestaticpropertiesoftheannotation,whicharesetusingtheAttributeDefinitionproperties,orthedynamicproperties,whicharesetusingexpressions.
AnnotationoverridescorrespondtotheInsertOptionsandInsertPropertiesoftheInsertAnnotationdialogintheUI.
Forexample,tooverridethestaticcolor,settheColorOverridepropertyoftheannotationoverride.Tooverrideacolorsetusinganexpression,settheColorExpressionOverrideproperty.
Toapplyanannotationoverride,inserttheannotationusingAnnotationTemplate(ObjectId,AnnotationOverrides).Forexample:
DimannOverridesAsNewAnnotation.AnnotationOverrides
annOverrides.Clear()
DimgreenClrAsAutodesk.AutoCAD.Colors.Color=_
Autodesk.AutoCAD.Colors.Color.FromColorIndex(_
Autodesk.AutoCAD.Colors.ColorMethod.None,3)
annOverrides.ColorOverride=greenClr
annTemplate.InsertReference(objId,annOverrides)
Pleasesendusyourcommentaboutthispage
Events
Topicsinthissection
OverviewEventsintheAPIReferenceListofEvents
Pleasesendusyourcommentaboutthispage
Overview
EventsandeventhandlersprovideawayforapplicationstorespondtochangesintheMapapplication.Forexample,openinganewprojectcanfireaneventhandlertoperformadditionalprocessing.
TheAPIusesstandard.NETmechanismsforhandlingevents.Applicationswantingtohandleeventssubscribetotheevents.Whentheeventisfiredallhandlerssubscribedtothateventarecalled.
Eventhandlersaccepttwoparameters:
Areferencetotheobjectraisingtheevent
Eventarguments
Theclassdefinitionfortheeventargumentsisusuallyspecifictotheeventbeinghandled.
Pleasesendusyourcommentaboutthispage
EventsintheAPIReference
Foreveryevent,theAutoCADMap3DAPIReferencecontainsthefollowing:
Classdefinitionfortheeventarguments.Thenamesoftheseclassesusuallybeginwiththeeventnameandendwith“EventArgs”.InsomecasestheeventusesSystem.EventArgsinsteadofdefininganewclass.
Methodsforaddingandremovingeventhandlers.Thenamesofthesemethodsbeginwith“add_”or“remove_”.Donotcallthesemethodsdirectly.Insteadusethecorrectsyntaxforthelanguage.
Typedefinitionfortheeventhandler.Note Someevents,suchasProjectModel.BeginClose,useSystem.EventHandlerandSystem.EventArgsinsteadofobjectsderivedfromthem.FordetailsrefertotheAPIreferenceortheVisualStudioObjectBrowser.
Forexample,theProjectOpenedeventintheAutodesk.Gis.Mapnamespaceconsistsofthefollowing:
ProjectOpenedEventArgsclass
add_ProjectOpenedmethodintheMapApplicationclass
remove_ProjectOpenedmethodintheMapApplicationclass
ProjectOpenedEventHandlertype
Note TheactualeventnameisnotusedintheAPIreference.Itcanalwaysbeinferredfromthecorrespondingadd_orremove_methods.
Example:VB.NET
TodefineaneventhandlerfortheProjectOpenedevent,createasubroutine:
SubhandleProjectOpened(ByValpSenderAsObject,_
ByValpArgsAsProjectOpenedEventArgs)
'Insertcodetohandleevent
EndSub
Tosubscribetotheevent:
AddHandlermapApp.ProjectOpened,AddressOfhandleProjectOpened
Tounsubscribefromtheevent:
RemoveHandlermapApp.ProjectOpened,AddressOfhandleProjectOpened
Example:C#
TodefineaneventhandlerfortheProjectOpenedevent,createasubroutine:
voidhandleProjectOpened(Objectsender,
ProjectOpenedEventArgsargs)
{
//Insertcodetohandleevent
}
Tosubscribetotheevent:
mapApp.ProjectOpened+=newProjectOpenedEventHandler(
handleProjectOpened);
Tounsubscribefromtheevent:
mapApp.ProjectOpened-=newProjectOpenedEventHandler(
handleProjectOpened);
Pleasesendusyourcommentaboutthispage
ListofEvents
NamespaceAutodesk.Gis.Map
Aliasesclass
Eventname Description
AlliasAdded Firedwhenanewaliasisaddedtotheapplication.Theeventargspassthealiasname.
AliasDeleted Firedwhenanaliasisdeletedfromtheapplication.Theeventargspassthealiasnameandpathofthedeletedalias.
MapApplicationclass
Eventname Description
IntOptionModified Firedwhenoneoftheapplicationoptionsismodified.Theeventargspasstheoptionnameandthenewandoldvaluesoftheoption.
ProjectBeginClose Firedwhenaprojectbeginsthecloseoperation,butbeforetheprojecthasbeenclosed.Theeventargspass
theprojectmodel.
ProjectCreated Firedafteranewprojecthasbeencreated.Theeventargspasstheprojectmodel.
ProjectOpened Firedwhenanexistingprojecthasbeenopened.Theeventargspasstheprojectmodel.
StringOptionModified Firedwhenoneoftheapplicationoptionsismodified.Theeventargspasstheoptionnameandthenewandoldvaluesoftheoption.
UnloadApp Notusedfor.NETapplications.
NamespaceAutodesk.Gis.Map.Classification
ClassificationManagerclass
Eventname Description
FeatureClassDefinitionCreated Firedwhenanewfeatureclassdefinitionhasbeencreated.TheeventargspasstheclassnameandthenameoftheXMLfilecontainingtheclassdefinition.
FeatureClassDefinitionDeleted Firedwhenafeatureclassdefinitionhasbeendeleted.Theeventargspasstheclassnameandthenameof
theXMLfilecontainingtheclassdefinition.
FeatureClassDefinitionModified Firedwhenafeatureclassdefinitionhasbeenmodified.TheeventargspasstheclassnameandthenameoftheXMLfilecontainingtheclassdefinition.
FeatureClassDefinitionRenamed Firedwhenafeatureclassdefinitionhasbeenrenamed.TheeventargspassthenewandoldclassnamesandthenameoftheXMLfilecontainingtheclassdefinition.
FeatureDefinitionFileAttached Firedwhenanewdefinitionfileisattached.Theeventargspassthefilename.
FeatureDefinitionFileModified Firedwhenadefinitionfileismodified.Theeventargspassthefilename.
NamespaceAutodesk.Gis.Map.DisplayManagement
DisplayManagerclass
Eventname Description
CategoryAppended
CategoryModified
CategoryUnappended
MapAppended
MapGoodBye
MapSetCurrentBegin Firedwhenchangingthecurrentdisplaymanagermap,beforethechangeismade.Returns
MapSetCurrentEnd
MapSetCurrentFails
MapUnappended
StyleAppendedToCategory
StyleModified
StyleUnappended
Mapclass
Eventname Description
CurrentScaleModified
DismissStylizationBegin
DismissStylizationCancel
DismissStylizationEnd
ItemAppended
ItemErased
ItemModified
ScaleAdded
ScaleErased
ScaleModified
StyleAppended
StyleErased
StyleReferenceAppended
StyleReferenceErased
StyleReferenceModified
UpdateStylizationBegin
UpdateStylizationCancel
UpdateStylizationEnd
NamespaceAutodesk.Gis.Map.ImportExport
Exporterclass
Eventname Description
ExportRecordError
RecordExported
RecordReadyForExport
Importerclass
Eventname Description
ImportRecordError
RecordImported
RecordReadyForImport
NamespaceAutodesk.Gis.Map.MapBook
BookManagerclass
Eventname Description
MapBookAppended
MapBookErased
MapBookModified
MapBookSetCurrent
MapBookTileModified
MapBookTileWillBeErased
MapBookTreeNodeModified
MapBookWillBeErased
NamespaceAutodesk.Gis.Map.Project
DrawingSetclass
Eventname Description
DrawingActivated
DrawingActivationCancelled
DrawingAttachCancelled
DrawingAttached
DrawingDeactivated
DrawingDetached
DrawingSettingsModified
DrawingToBeActivated
DrawingToBeAttached
ProjectModelclass
Eventname Description
AbortCSChange
AbortSwapId
BeginClose
BeginCSChange
BeginDestroy
BeginOpen
BeginQuery
BeginSave
BeginSaveBack
BeginSwapId
BeginTransform
EndClose
EndCSChange
EndOpen
EndQuery
EndSave
EndSaveBack
EndSwapId
EndTransform
IntOptionModified
StringOptionModified
NamespaceAutodesk.Gis.Map.Query
QueryLibraryclass
Eventname Description
QueryAdded
QueryCategoryAdded
QueryCategoryDeleted
QueryCategoryRenamed
QueryDeleted
QueryModified
QueryRenamed
Pleasesendusyourcommentaboutthispage
DrawingSets
Topicsinthissection
OverviewDriveAliasesAttachingandDetachingDrawings
Pleasesendusyourcommentaboutthispage
Overview
Drawingsetsprovideawayforasinglemaptocombineobjectsfrommultipledrawings.Onedrawing,theprojectdrawing,canattachmultiplesourcedrawings.Thesourcedrawings,inturn,canattachothersourcedrawingstoformatreeofattacheddrawings.
Runningaqueryontheattacheddrawingscopiesselectedobjectsintotheprojectdrawing,wheretheycanbedisplayedandedited.Unlessanobjectfromanattacheddrawinghasbeen“queriedin”itdoesnotappearintheprojectdrawing.SeeQueriesandSaveSetsformoredetails.
Pleasesendusyourcommentaboutthispage
DriveAliases
Attacheddrawingsareoftensharedbetweendifferentusersondifferentcomputers.Becauseofthis,thepathstotheattacheddrawingscanbedifferentforeachuser.Aliaseshelpmanagethesefiles.
Eachaliasmapsanaliasnametoadirectorypath.EachAutoCADMap3Dusercandefinedifferentpathsforthealiases.Thelocationsofattacheddrawingsarealwaysidentifiedusingthealiases,souserscanhavedifferentpathstotheatttacheddrawings,aslongasthealiasesarethesame.
TheDriveAliasclassintheAutodesk.Gis.Mapnamespacerepresentsanindividualalias.Ithastwoproperties:NameandPath.
TheAliasespropertyofthemapapplicationreturnsanAliasesobjectformanagingthealiasesinthesession.Aliases.Item()returnsanindividualdrivealias,eitherbyaliasnameorindexnumber.
DimaliasListAsAliases
aliasList=mapApp.Aliases
Aliasesobjectshavemethodsforaddingandremovingaliases,andeventhandlersfordetectingwhenaliaseshavebeenaddedorremoved.
Pleasesendusyourcommentaboutthispage
AttachingandDetachingDrawings
Attachingadrawingaddsittothedrawingsetforaproject.Detachingadrawingremovesitfromthedrawingset.
Toattachadrawing,useDrawingSet.AttachDrawing().Passasinglestringargumentthatcontainsthealiasandthepathtothedrawingtoattach.Theformis:
alias:\filename
Thisreturnsareferencetotheattacheddrawing,anAttachedDrawingobject.
Whenanattacheddrawingisactivated,thefileislockedagainsteditingbyotherapplications.Toremovethelock,butkeepthedrawingattached,callAttachedDrawing.Deactivate().Toreactivatethedrawing,callAttachedDrawing.Activate().
Pleasesendusyourcommentaboutthispage
QueriesandSaveSets
Topicsinthissection
OverviewQueriesQueryLibrariesSaveSets
Pleasesendusyourcommentaboutthispage
Overview
Queriesandsavesetsworkonattacheddrawings.Aquerycopiesdrawingobjectsfromattacheddrawingsintotheprojectdrawing.Onceintheprojectdrawing,theobjectscanbeeditedlikeanyotherdrawingobject.
Asavesetisalistofobjectsintheprojectdrawingthataretobeupdatedinattacheddrawings.Thesavesetcancontain:
objectsthathavebeenmodifiedintheprojectdrawingthatshouldalsobemodifiedintheattacheddrawings
objectsthathavebeendeletedfromtheprojectdrawingandshouldbedeletedfromtheattacheddrawings
newobjectsthathavebeenaddedtotheprojectdrawingthatshouldalsobeaddedtoanattacheddrawing
Objectsthathavebeenqueriedintotheprojectdrawingarenotaddedtothesavesetautomatically.
Pleasesendusyourcommentaboutthispage
Queries
Aqueryisatreestructurecontainingbranches(QueryBranchobjects)andconditions(DataCondition,LocationCondition,PropertyCondition,andSqlConditionobjects).AlloftheseobjectsaresubclassedfromQueryUnit.
Tocreateaquery,callProjectModel.CreateQuery().
query=activeProj.CreateQuery()
ThisreturnsanemptyQueryModelobject.
Asimplequerycanhavearootbranchwithasinglecondition.Morecomplexqueriescombinebranchesandconditions.
Thecriteriathatthequeryusestoselectobjectsareexpressedinqueryconditions.Therearefourtypesofqueryconditions.
DescriptionLocationConditions Basedonthelocation
ofobjectsrelativetoaboundary.Thereareseveralboundarytypes.SeeLocationBoundariesbelow.
PropertyConditions BasedonaparticularAutoCADproperty.
DataConditions Basedonobjectdata.ToqueryobjectdatasetthequerytypetoDataIrd.Toqueryobjectclassessetthe
querytypetoDataFeature.
SQLConditions BasedondataaboutdrawingobjectsthatisstoredinexternaldatabasetablesandisspecifiedbytheWHEREclauseofaSQLquery.
LocationBoundaries
Thereareseveraltypesoflocationboundaries.TheyareallrepresentedbydescendentsoftheLocationBoundaryclass,asillustratedinthefollowingdiagram.
ExecutingQueries
Tobuildaquery
1. CreatethequeryusingProjectModel.CreateQuery().
2. CreateoneormorequeryconditionsusingtheconstructorsforDataCondition,LocationCondition,PropertyCondition,andSqlCondition.
3. CreateoneormorequerybranchesusingtheconstructorforQueryBranch.
4. BuildthequerytreebyappendingqueryconditionsandbranchesusingQueryBranch.AppendOperand().
5. CreatethequerydefinitionbypassingtherootquerybranchtoQueryModel.Define().
6. Optionally,savethequerydefinitioninanexternalfileorquerylibrary.
Toexecuteaquery
1. Youmaywanttosetthemode,enableordisablepropertyalteration,orcreateareporttemplateforthequery.
2. CallQueryModel.Run()toexecutethequeryagainstallattacheddrawings.CallQueryModel.Execute()toexecutethequeryforaparticulardrawingset.
Thequerymodedeterminesiftheobjectsfromtheattacheddrawingsaredisplayedasaprevieworclonedintotheprojectdrawing.QueryModel.Execute()returnsalistofobjectsthathavebeenqueriedin.
Pleasesendusyourcommentaboutthispage
QueryLibraries
Querylibrariesprovideawaytosaveandre-usequeries.Thequeriescanbesavedinternallyintheprojectfileorexternally.Eachprojecthasitsownlibrary,availablewithProjectModel.QueryCategories.
Librariesaredividedintocategories,whereeachcategoryisacontainerforsavedqueries.ThesavedqueriesarerepresentedbyQueryAttributeobjects.
Toaddaquerytothelibrary,firstaddacategorythenaddthequery.
DimqueryLibAsQuery.QueryLibrary=activeProject.QueryCategories
DimqueryCatAsQuery.QueryCategory
queryCat=queryLib.AddCategory("catName")
queryCat.AddQuery("queryName","querydescription",queryObj)
Tosaveaquerytoanexternalfile,callQueryModel.Save().
Pleasesendusyourcommentaboutthispage
SaveSets
Eachprojecthasasaveset,whichmanagesalistofobjectidstobeupdatedinattacheddrawings.
Objectsarenotaddedtothesavesetautomatically.ItisuptotheapplicationtoaddobjectsusingSaveSet.AddObjects().
Tosaveobjectsbacktoanattacheddrawing,callAttachedDrawing.CloneBack(),AttachedDrawing.CloneBackArea(),orAttachedDrawing.CloneBackLayer().
Pleasesendusyourcommentaboutthispage
Classification
Topicsinthissection
OverviewManagingFeatureDefinitionFilesCreatingFeatureClassDefinitionsClassifyingObjects
Pleasesendusyourcommentaboutthispage
Overview
Objectclassificationisawayoftaggingdrawingobjectswithanobjectclassname.Thiscanhelporganizetheobjectsinthedrawing,andenforcedrawingstandards.
Note Forhistoricalreasons,theAPIusesthetermsfeatureandfeatureclassforobjectclassification.ThesearedifferentfromFDOfeaturesandfeatureclasses.Itisimportantnottoconfusethetwo.
Pleasesendusyourcommentaboutthispage
ManagingFeatureDefinitionFiles
FeatureclassdefinitionsarestoredinXMLfiles,externaltothedrawingfile.Beforedefinitionsfromafilecanbeused,thefilemustbeattachedtoadrawing.Therecanonlybeoneattachedfeaturedefinitionfileactiveatonetimeforagivenproject.
Note IntheUI,featuredefinitionfilesarecalledobjectclassdefinitionfiles.
CreatingFeatureDefinitionFiles
Tocreateafeaturedefinitionfile:
GettheclassificationmanagerobjectfortheprojectusingProjectModel.ClassificationManager.
CreatethenewfileusingClassificationManager.CreateFeatureDefinitionFile()
NotethatthecurrentusermusthaveadministrativeprivilegesintheMapsession.Tocheck,testClassificationManager.CanCurrentUserAlterSchema.
DimclassMgrAsClassification.ClassificationManager
classMgr=activeProj.ClassificationManager
If(classMgr.CanCurrentUserAlterSchema)Then
classMgr.CreateFeatureDefinitionFile(filename)
Else
'Error
EndIf
AttachingandDetachingFeatureDefinitionFiles
Toattachafeaturedefinitionfile,callClassificationManager.AttachFeatureDefinitionFile().
Todetachthecurrentfile,call
CreatingFeatureClassDefinitions
Featureclassdefinitionsarecomposedofpropertiesthatdefinehowclassifiedobjectswillappear.Eachfeatureclassdefinitioncanonlybeusedwithcertaintypesofdrawingobjects.
Tocreateafeatureclassdefinition,startwithadrawingobjecttouseasatemplate.GetthepropertiesofthedrawingobjectusingClassificationManager.GetProperties().Thecurrentvaluesofthedrawingobjectbecomethedefaultpropertyvalues.
Determinethelistofobjecttypesthatthefeatureclassdefinitioncanbeusedwith.ThislistcanbeexpressedasastringcollectionoracollectionofAutoCADRXClassobjects.CreatetheemptyfeatureclassdefinitionusingClassificationManager.CreateFeatureClassDefinition().SetadrawingobjecttypetouseforcreatingnewinstancesoftheclassusingFeatureClassDefinition.SetCreateMethod().
DimclassMgrAsClassification.ClassificationManager
DimnewDefAsClassification.FeatureClassDefinition
classMgr=activeProj.ClassificationManager
DimtransAsTransaction=Nothing
DimobjAsDBObject=Nothing
DimclsAsRXClass=Nothing
Try
trans=_
MdiActiveDocument.TransactionManager.StartTransaction()
obj=trans.GetObject(objId,OpenMode.ForRead)
cls=obj.GetRXClass()
trans.Commit()
Finally
trans.Dispose()
EndTry
DimentTypeAsSystem.String=System.String.Copy(cls.Name)
DimentTypesColAsStringCollection=NewStringCollection()
entTypesCol.Add(entType)
newDef=classMgr.CreateFeatureClassDefinition(_
defName,Nothing,entTypesCol,Nothing,False)
newDef.SetCreateMethod(entType,"")
UsetheFeatureClassPropertyCollectionasaninitialsetofpropertiesforthefeatureclassdefinition.Modifyitasneededbysettingrangeanddefaultvaluesforthepropertiesinthecollection.CreateanewFeatureClassPropertyCollectionwiththeupdatedproperties.Savethefeaturedefinitionfile.
DimclassPropAsClassification.FeatureClassProperty
DimpropCollectionAs_
Classification.FeatureClassPropertyCollection
propCollection=_
NewClassification.FeatureClassPropertyCollection
classMgr.GetProperties(classPropCollection,Nothing,objId)
ForEachclassPropInclassPropCollection
'Modifythepropertyifnecessary
newDef.AddProperty(classProp)
Next
classMgr.SaveCurrentFeatureDefinitionFile()
Pleasesendusyourcommentaboutthispage
ClassifyingObjects
Toclassifyadrawingobject,callClassificationManager.Classify().Thistagstheobjectwiththenameofthefeaturedefinitionfileandthefeatureclassname.Ifthefeaturedefinitionfileisdetached,theclassificationtagremains.
Asingleobjectmaybeclassifiedmorethanonce,byusingfeatureclassesfromdifferentfeaturedefinitionfiles.Togetalistofallclassificationsforanobject,callClassificationManager.GetAllTags().
Tounclassifyanobject,callClassificationManager.Unclassify().
Togetalistofallobjectsinadrawingthathavenotbeenclassified,callClassificationManager.GetUnclassifiedEntities().Theresultofthiscanbeusedtofindandclassifymissingobjects.
Pleasesendusyourcommentaboutthispage
Overview
Filtersprovideasimplemechanismforselectingdrawingobjectsthatmeetcertaincriteria.IntheAutoCADMap3DUI,abasicfiltercanbeusedtoselectdrawingobjectsforanexportoperation.
Abasicfilterhasoptionsforfilteringbasedoncombinationsoflayernames,objectclassification,andblocknames.Customfilterscanfilterbasedonothercriteria.BothtypesarebasedontheFilters.ObjectFilterclass.
AnObjectFilterGroupcancombinemultiplefiltersintoasinglefilteroperation.
ObjectsforworkingwithfiltersareintheAutodesk.Gis.Map.Filtersnamespace.
Pleasesendusyourcommentaboutthispage
BasicFilters
TheFilterObjects()methodforanyfiltertakesalistofdrawingobjectstobefilteredandreturnsalistofdrawingobjectsthatmeetthefilteringcriteria.
Tocreateabasicfilter,calltheconstructorwithalistoflayernames,featureclassnames,andblocknames.Separatemultiplevalueswithcommas.Anasterisk(“*”)wildcardselectsallobjectsmatchingthecriterion.
DimnewFilterAsAutodesk.Gis.Map.Filters.BasicFilter
newFilter=NewAutodesk.Gis.Map.Filters.BasicFilter
("Parcels,Lots","*","*"))
Torunafilter,callitsFilterObjects()methodwiththeoutputandinputObjectIdCollectionobjects.
Pleasesendusyourcommentaboutthispage
CustomFilters
Customfilterscanimplementadditionalfilteringcapabilities.Tocreateacustomfilter,defineanewclassbasedontheObjectFilterclass.Ataminimum,thecustomfiltermustdefineaFilterObjects()method.Itcandefineanyothermethodsneededforcreatingandmodifyingthefilter.
Pleasesendusyourcommentaboutthispage
Overview
TheAutoCADMap3Dapplicationmaintainslistsofavailableimportandexportformats.ItisnotpossibletomodifytheselistsusingtheAPI.TheapplicationImporterandExporterclassescanimportandexportdatausingtheseformats.
Anyimportorexportprocedurerequiresthefollowing:
Selectingtheexternalfileformatandlocation
Mappingattributedatafromtheexternalfiletoobjectdata
Settinganynecessarydriveroptions
Importingorexporting
Theparticularoptionswillvarydependingonthetypeofdatabeingimportedorexported,buttheoverallprocedureisthesame.
Pleasesendusyourcommentaboutthispage
Importing
Theimportprocedurebringsinobjectsfromexternalfilesandcreatesnewdrawingobjects.Someexternalfileshaveasinglelayer,whileothershavemorethanone.
Tostartanimportprocess,gettheImporterobjectfortheapplicationandinitializeitwiththeimportformatnameandthelocationofthefileorfilestoimport.Forexample::
myImporter.Init("SHP",fileName)
Thissetsuptheavailablelayersfortheimport.Iteratethroughthelayers.Foreachlayer,determineifobjectsfromthelayerwillbeimported.SetInputLayer.ImportFromInputLayerOn.
Anyattributedataattachedtoobjectsinthelayerscanbebroughtintothedrawingasobjectdata.Eachattributeinthesourcefilecorrespondstoacolumnintheinputlayer.Thesecolumnscanbemappedtofieldsinobjectdatatables.
Tomapinputcolumns,settheobjectdatatablenameusingInputLayer.SetDataMapping().Theniteratethrougheachcolumn,settingthemappingforthecolumnusingColumn.SetColumnDataMapping().
Differentimportdriverswillhavedifferentoptions.ThedefaultoptionsarestoredinMapImport.ini.Tomodifytheoptions,gettheoptionsusingImporter.DriverOptions().Thisreturnsaname-valuecollection.ModifytheoptionsinthecollectionandcallImporter.SetDriverOptions().
Somedriversalsohaveanoptionsdialog.Forthosedrivers,callImporter.InvokeDriverOptionsDialog()tohavetheusersettheoptions.
Whenallthemappingsanddriveroptionshavebeensetupproperly,callImporter.Import().ThisreturnsanImportResultsobject,whichcontainsdetailsoftheimport.
ImportEvents
TheRecordReadyForImporteventhandlercanbeusedtocontrolwhichrecordsareimported.Thehandlerisfiredforeveryrecord,beforetheimporthasbeencompleted.Tostoptheimportforarecord,setRecordReadyForImportEventArgs.ContinueImporttofalse.
Pleasesendusyourcommentaboutthispage
Exporting
Exportingissimilartoimporting,withsomesmalldifferences.
Toselectwhichdrawingobjectsshouldbeexported,callExporter.SetSelectionSet().Toexportalldrawingobjects,setExporter.ExportAlltotrue.Tofilterthelistofobjects,settheExporter.FeatureClassFilterorExporter.LayerFilterproperties.
TheExporterobjectdoesnothaveapropertycorrespondingtoInputLayer.ThemappingsforattributedataaresetusingExporter.SetExportDataMappings().ThisrequiresanExpressionTargetCollectionparameterasinput.
ItemsinanExpressionTargetCollectionobjectarename-valuepairs,wherethenamecorrespondstoanobjectdataexpressionandthevalueistheattributenameintheexportedfile.FordetailsaboutobjectdataexpressionsseeExpressionsinAnnotationsortheMap3DHelp.
ExportEvents
TheRecordReadyForExporteventhandlerissimilartoRecordReadyForImport.Tostoptheexportofarecord,setRecordReadyForExport.ContinueExporttofalse.
Pleasesendusyourcommentaboutthispage
Topology
Topicsinthissection
OverviewDrawingCleanupCreatingTopologiesNodeTopologyNetworkTopologyPolygonTopology
Pleasesendusyourcommentaboutthispage
Overview
Anetworktopologycontainsasetofedgesorlinks.Eachlinkhasanodeateachend.Multiplelinkscanintersectatasinglenode.
Apolygontopologyrepresentsanareacoverage.
Topologiesdescriberelationshipsbetweendrawingobjects.Therearethreetypesoftopology:
Node,alsocalledpoint
Network
Polygon
Anodetopologycontainsasetofpoints.
Anetworktopologycontainsasetofedgesorlinks.Eachlinkhasanodeateachend.Multiplelinkscanintersectatasinglenode.
Apolygontopologyrepresentsanareacoverage.Thebordersofpolygonsarerepresentedbyedges.Thepolygonsinapolygontopologycannotoverlap,butadjacentpolygonsshareedges.
Eachobjectinthetopology(node,link,orpolygoncentroid)hasanIDnumberthatisuniquewithinthetopology.
Note Thetopologyisrelatedtodrawingobjects,butitisstoredindependently.Itispossibletohaveatopologywherethenodesdonotcorrespondtodrawingobjects.
Internally,therelationshipbetweendrawingobjectsandtopologiesisimplementedusingobjectdatatables.Foratopologynamedtopol_name,thefollowingtablesareused:
TMPCNTR_topol_name
TPMDESC_topol_name
TPMID_topol_name
TPMLINK_topol_name
TPMNODE_topol_name
TPMDESCandTPMIDarenotattachedtoanydrawingobjects.Theyareusedtostoreinformationaboutthetopologyitself.TPMDESCcontainstheparametersusedtocreatethetopology,suchastopologytype,colors,andlayernames.TPMIDcontainsasinglevalueforthelastidassignedforthetopology.
TPMNODEdataisattachedtonodesinthetopology.EachnodehasanIDandaresistancevalue.
TPMLINKdataisattachedtolinksbetweennodes.FornetworktopologiesthelinkhasvaluesfortheID,startandendnode,directionofthelink,andresistancevaluesfortraversingthelinkineachdirection.Forpolygontopologiesthelinkalsohasvaluesforthepolygonsoneithersideofthelink.
TPMCNTRdataisattachedtothecentroidsofpolygonsinapolygontopology.EachcentroidhasvaluesfortheID,area,perimeter,andnumberoflinksthatformtheedgesofthepolygon.
Inmostcases,applicationsdonotneedtomanagetheobjectdatadirectly.ThetopologyAPIcallsperformallthenecessaryupdates.Anapplicationneedingtoknowwhichtopologieshavebeendefinedinthedrawing,however,shouldchecktheobjectdatatablesfornamesbeginningwith“TMPDESC_”.
Pleasesendusyourcommentaboutthispage
DrawingCleanup
Drawingcleanupisessentialforpolygonandnetworktopologies.Itensuresthattheobjectsinthetopologycanbeconnectedproperly.Formoredetailsaboutthevarioustypesofcleanupactions,refertotheUIdocumentation.
Adrawingcleanupoperationinvolvescombiningoneormorecleanupactions.Eachactionisidentifiedbyanactionnumber.Manyoftheactionshaveadditionalsettings.
Action Description Settings
1 EraseShortObjects
CLEAN_TOL
2 BreakCrossingObjects
4 ExtendUndershoots
CLEAN_TOL??breaktarget
8 DeleteDuplicates
CLEAN_TOLINCLUDE_LINEAROBJSINCLUDE_POINTSINCLUDE_BLOCKSINCLUDE_TEXTINCLUDE_MTEXTINCLUDE_ROTATIONINCLUDE_ZVALUES
16 SnapClustered
CLEAN_TOLINCLUDE_POINTS
Nodes INCLUDE_BLOCKSSNAP_TO_NODE
32 DissolvePseudoNodes
64 EraseDanglingObjects
CLEAN_TOL
128 SimplifyObjects
CLEAN_TOL???createarcs
256 ZeroLengthObjects
512 ApparentIntersection
CLEAN_TOL
1024 WeedPolylines
WEED_DISTANCEWEED_ANGLEWEED_SUPPLEMENT_DISTANCEWEED_SUPPLEMENT_BULGE
Thesameclass,Topology.Variable,isusedforbothactionsandsettings.Tocreateadrawingcleanupaction,createasettingsvariableandsetitsvalues:
DimtoleranceValAsNewDatabaseServices.TypedValue_
(Autodesk.AutoCAD.DatabaseServices.DxfCode.Real,25.5)
DimtoleranceSettingAsNewDatabaseServices.ResultBuffer
toleranceSetting.Add(toleranceVal)
DimblocksValAsNewDatabaseServices.TypedValue_
(Autodesk.AutoCAD.DatabaseServices.DxfCode.Int16,1)
DimblocksSettingAsNewDatabaseServices.ResultBuffer
blocksSetting.Add(blocksVal)
DimsettingsAsNewTopology.Variable
settings.Set("CLEAN_TOL",toleranceSetting)
settings.Set("INCLUDE_BLOCKS",blocksSetting)
Createanactionvariableandaddtheactionanditssettings:
DimactionAsNewTopology.Variable
action.InsertActionToList(-1,8,settings)
Iftheoperationwillincludemorethanoneaction,repeattheprocessandinsertmoreactionsandtheircorrespondingsettingsintothesameactionvariable.
Toperformthecleanup,createaTopologyCleanobjectandinitializeitwiththeactionvariableandasetofdrawingobjectstoclean.
DimcleanObjAsNewTopology.TopologyClean
cleanObj.Init(action,Nothing)
Eachindividualactionintheactionvariableisacleanupgroup.Startthecleanupandgothroughthegroupsuntilallactionshavebeencompleted.CommitthechangesusingTopologyClean.End().
cleanObj.Start()
cleanObj.GroupNext()
DoWhileNotcleanObj.Completed
cleanObj.GroupFix()
cleanObj.GroupNext()
Loop
cleanObj.End()
Forfinercontrolovertheobjectsbeingcleaned,stepthroughtheerrorsinagroupusingTopologyClean.ErrorCur().Fixorignoreeachoneindividually.SetTopologyClean.ErrorPointtochangethelocationforthefix.
Tosaveaprofileforlateruse,callVariable.SaveProfile()usinganactionvariableobject.Toreloadtheprofile,callVariable.LoadProfile().
Pleasesendusyourcommentaboutthispage
CreatingTopologies
Tocreateanewtopology,gettheTopologiesobjectfortheproject.Selectthedrawingobjectstoincludeinthetopology.CallTopologies.Create().GetareferencetothenewlycreatedtopologyusingTopologies.Item(),whichtakesastringparameter.
Onceatopologyhasbeencreated,itmustbeopenedusingTopologyModel.Open().Whenthetopologyisnolongerneeded,closeitwithTopologyModel.Close().
Pleasesendusyourcommentaboutthispage
NodeTopology
Anodetopologyrepresentsagroupofrelatedpoints.Nodetopologiesareoftenusedaspartofnetworkorpolygontopologies,torepresenttheendpointsofthelinksinthetopology.
TopologyModel.GetNodes()returnsthecollectionofnodes.Foreachnode,Node.Entityreturnstheassociateddrawingobject.Ifthenodedoesnothaveadrawingobjectassociatedwithit,Node.EntitythrowsaMapException.
Note DonotupdateitemsinaNodeCollectionobjectusingmethodslikeAdd(),Insert(),andRemove().Instead,calltheappropriatemethodsfortheTopologyModelobject,likeAddPointObject().
CallNodeCollection.Dispose()whentheobjectisnolongerneeded.
Pleasesendusyourcommentaboutthispage
NetworkTopology
Anetworktopologyrepresentsagroupofrelatednodesandtheconnectionsbetweenthenodes.Theconnectionsbetweennodesarelinksoredgesinthetopology.
Eachfulledgeiscomposedoftwohalfedges,representingtravelinoppositedirectionsbetweenthenodes.Eachhalfedgecanhaveitsownresistancevalue,whichisusedincertaintypesofnetworkanalysis.
TopologyModel.GetFullEdges()returnsthecollectionoffulledges.Foreachedge,FullEdge.Entityreturnstheassociateddrawingobject.Iftheedgedoesnothaveadrawingobjectassociatedwithit,FullEdge.EntitythrowsaMapException.
FullEdge.GetHalfEdgereturnsahalfedge,ineithertheforwardorbackwarddirection.
Pleasesendusyourcommentaboutthispage
PolygonTopology
Apolygontopologyrepresentsanareacoverage,withpolygonsinsidetheareaboundedbyedges.Anypolygoninthetopologymustbeentirelyenclosedwithinitsedges.
Eachpolygonmusthaveacentroid.
TopologyModel.GetPolygons()returnsthecollectionofpolygons.Foreachedge,FullEdge.Entityreturnstheassociateddrawingobject.Iftheedgedoesnothaveadrawingobjectassociatedwithit,FullEdge.EntitythrowsaMapException.
Pleasesendusyourcommentaboutthispage
DisplayManager
Topicsinthissection
OverviewElementsDataSourceDescriptorsStyle
Pleasesendusyourcommentaboutthispage
Overview
DisplayManagerprovidesawaytoorganizeandstylelayersinAutoCADMap3D.
Note TheDisplayManagerAPIonlymanageslayersthatcontaindrawingobjects.TomanagelayerscontainingFDOdatausetheGeospatialPlatformAPI.SeetheGeospatialPlatformDeveloper’sGuideandtheGeospatialPlatformAPIReferencefordetails.
Eachprojecthasitsownmapmanager,whichisrepresentedbyaDisplayManagement.MapManagerobject.Togetthemapmanagerforaproject,performthefollowingsteps:
trans=activeDoc.TransactionManager.StartTransaction()
DimmanagerIdAsObjectId
DimmanagerAsMapManager=Nothing
managerId=DisplayManager.Create(activeProject).MapManagerId(_
activeProject,True)
manager=trans.GetObject(managerId,OpenMode.ForRead)
Asingleprojectcancontainmultiplemaps.MapManager.GetEnumerator()returnsanenumeratorthatstepsthroughthemapsintheproject.ThepropertiesMapManager.CurrentMapIdandMapManager.Currentgetorsetthecurrentmap.
Amap(DisplayManagement.Mapobject)issub-classedfromDisplayManagement.Group,whichrepresentsanygroupofelementsinDisplayManager.Mapscancontainlayersandmoregroups.
Pleasesendusyourcommentaboutthispage
Elements
DisplayManagerelementsrepresentthedifferentlayersinthemap.Elementscanbeofthefollowingtypes,allsubclassedfromDisplayManagement.Element:
DisplayManagement.BaseElement
DisplayManagement.LayerElement
DisplayManagement.AttachedDwgsQueryElement
DisplayManagement.TopologyElement
DisplayManagement.TopologyQueryElement
DisplayManagement.FeatureElement
DisplayManagement.RasterElement
Thefollowingiteratesthroughtheelementsinamap:
DimiteratorAsIEnumerator=currentMap.NewIterator(True,True)
DimelementTypeAsType=GetType(DisplayManagement.Element)
DimgroupTypeAsType=GetType(DisplayManagement.Group)
DoWhile(iterator.MoveNext())
DimitemIdAsObjectId=iterator.Current
DimthisItemAsObject=_
trans.GetObject(itemId,OpenMode.ForRead)
If(thisItem.GetType().Equals(elementType)Or_
thisItem.GetType().IsSubclassOf(elementType))Then
DimmapElementAsItem=thisItem
'Processelement(layer)
ElseIf(thisItem.GetType().Equals(groupType))Then
DimthisGroupAsDisplayManagement.Group=thisItem
'Processgroup
Else
'NotaDisplayManagerobject,probablycontainsFDOdata
EndIf
Loop
TheBaseElementlayerrepresentstheMapBase.
LayerElementobjectsdisplaydrawingobjectsfromanAutoCADlayer.
AttachedDwgsQueryElementobjectsrepresentlayerscontainingdataqueriedinfromattacheddrawings.
TopologyElementobjectsrepresentDisplayManagerlayersthatcontaintopologyfromthecurrentdrawing.TopologyQueryElementobjectsrepresentlayersthatcontaintopologyqueriedfromattacheddrawings.
FeatureElementobjectsrepresentlayersthatcontainclassifieddrawingobjects.
RasterElementobjectsarenotgenerallyused.Instead,useFDOdatawiththeGeospatialPlatformAPI.
Pleasesendusyourcommentaboutthispage
DataSourceDescriptors
DisplayManagement.Elementhastwopropertiestodescribethedatasourcefortheelement:
AcquisitionCriteriaString
AcquisitionCriteria
AcquisitionCriteriaStringcontainsastringrepresentationofthedatasource,asdescribedinthefollowingtable:
Elementtype AcquisitionCriteriaStringvalue
LayerElement AutoCADlayername
FeatureElement Objectclassificationclassname
TopologyElement Topologyname
AttachedDwgsQueryElement
TopologyQueryElement
AcquisitionCriteriaisoftypeDisplayManagement.DataSourceDescriptor.Itcontainsadditionaldataaboutthesource.Eachelementtypehasacorrespondingdatasourcedescriptortype,subclassedfromDataSourceDescriptor.Forexample,theAcquisitionCriteriapropertyforaLayerElementisoftypeLayerDataSourceDescriptor.
ForLayerElement,FeatureElement,andTopologyElement,AcquisitionCriteria.AcquisitionStatementisthesameasAcquisitionCriteriaString.
AttachedDwgsQueryDataSourceDescriptorandTopologyQueryDataSourceDescriptordefineadditionalmethodsandproperties,asdescribedinthefollowingtable.
Methodorproperty Description
GetDrawingList() Getsthelistofattacheddrawingsusedinthequery
SetDrawingList() Setsthelistofattacheddrawingsusedinthequery
Query Aresultbuffercontainingthequerydefinition,fromtheQueryModel.FileOutproperty
TopologyName ForTopologyQueryDataSourceDescriptoronly,thetopologynameusedinthequery
Toaddanewelement,createtheelementanditsassociateddatasourcedescriptor,thenaddittothemap.ThefollowingexampleaddsaLayerElementthatreferencesanAutoCADlayernamed“Layer1”.Forotherelementtypes,createtheappropriatedatasourcedescriptor.
DimactiveProjectAsProject.ProjectModel=_
HostMapApplicationServices.Application.ActiveProject
DimdocsAsDocumentCollection=Application.DocumentManager
DimactiveDocAsDocument=docs.MdiActiveDocument
DimtransAsTransaction=Nothing
Try
trans=activeDoc.TransactionManager.StartTransaction()
'GettheObjectIdforthecurrentMap
DimmanagerIdAsObjectId
managerId=_
DisplayManager.Create(activeProject).MapManagerId(_
activeProject,True)
DimmanagerAsMapManager=trans.GetObject(managerId,_
OpenMode.ForRead)
DimcurrentMapId=manager.CurrentMapId
DimcurrentMapAsMap=trans.GetObject(currentMapId,_
OpenMode.ForWrite)
'CreatetheLayerelementandsetits
name
DimelementAsLayerElement=LayerElement.Create()
element.Name="NewLayer"
'CreatetheLayerDescriptor
DimdescriptorAsLayerDataSourceDescriptor=Nothing
descriptor=LayerDataSourceDescriptor.Create()
descriptor.AcquisitionStatement="Layer1"
'NowAddthenewelementtothecurrent
Map
DimiteratorAsIEnumerator=_
currentMap.NewIterator(True,True)
DimelementIdAsObjectId=_
currentMap.AddItem(element,iterator)
trans.AddNewlyCreatedDBObject(element,True)
element=trans.GetObject(elementId,OpenMode.ForWrite)
element.AcquisitionCriteria=descriptor
trans.Commit()
trans=Nothing
CatcheAsAutodesk.AutoCAD.Runtime.Exception
'Handleexception
Finally
IfNottransIsNothingThen
trans.Abort()
trans=Nothing
EndIf
EndTry
Pleasesendusyourcommentaboutthispage
Style
DisplayManagerelementscanhavestyleassociatedwiththem.
DisplayManagement.Styleisthebaseclassforallthestyleclasses.ItisbasedonAutoCAD.DatabaseServices.DBObject,soitmustbemanagedusingAutoCADtransactions.Theavailablestyleclassesare:
DefaultStyle
EntityStyle
StylizationEntityAnnotationStyle
StylizationEntityHatchStyle
StylizationEntityTextStyle
RasterStyle
ThematicStyle
Element.AddStyle()createsareferencefromtheelementtothestyleobjectinthedatabase.Multipleelementscanrefertothesamestyleobject.
Tocreateanewstyle,callitsCreate()method.Settheappropriatepropertiesforthestyletype.Savethestyleinthedatabaseandaddittoanelement.Forexample,thefollowingcreatesanewentitystyleandassignsittoalayerelement:
Try
trans=activeDoc.TransactionManager.StartTransaction()
'Opentheelementforwrite,sothestylecanbeadded
DimlayerAsElement=trans.GetObject(layerId,_
OpenMode.ForWrite)
'Pass0.0forthecurrentscale
DimstyleRefIteratorAsStyleReferenceIterator=_
layer.GetStyleReferenceIterator(0.0,True,True)
'Addthestyle
DimstyleEntityAsEntityStyle=EntityStyle.Create()
'Setstyleproperties
DimcolorAsAutodesk.AutoCAD.Colors.Color=_
color.FromColorIndex(_
Autodesk.AutoCAD.Colors.ColorMethod.None,5)
styleEntity.Color=color
styleEntity.Name=styleName
DimidAsObjectId
id=layer.AddStyle(styleEntity,styleRefIterator)
trans.AddNewlyCreatedDBObject(styleEntity,True)
trans.Commit()
trans=Nothing
CatcheAsSystem.Exception
'Processexception
Finally
IfNottransIsNothingThen
trans.Abort()
trans=Nothing
EndIf
EndTry
Pleasesendusyourcommentaboutthispage
MapBook
Topicsinthissection
OverviewMapBookTemplatesCreatingaMapBook
Pleasesendusyourcommentaboutthispage
Overview
AMapBookisawaytodividealargemapintosmallertiles,bycreatingaseparatelayoutforeachtile.
EachprojecthasitsownMapBookmanager.CallMapApplication.GetBookManager()togetthebookmanagerforadatabase.
AMapBookrequiresatemplatefilethatdefinesthelayoutforeachsheetinthebook.
Pleasesendusyourcommentaboutthispage
MapBookTemplates
AMapBooktemplateisanAutoCADtemplate(.dwt)filewithsomespecialcharacteristics.
Thetemplatefilemustdefineatleastonelayout.Thelayoutcancontainviewportsforthefollowingpurposes:
Mapview,whichdisplaysthemapfortheareacoveredbyaparticularsheet
Keyview,whichdisplaysasmallimageoftheentiremap,outliningtheareacoveredbythemapsheet
Maplegend,whichdisplaysthemaplegend
Thelayoutcanalsocontainspecialblocksthatshowlinkstoadjacentmapsheets.WithinAutoCADMap3DoraDWFfile,thelinkscanbeusedtojumpdirectlytoanadjacentsheet.
Thelayoutcanalsocontainatitleblock.
Toidentifyobjectsinthetemplateasanyofthespecialviewsorblocks,callthestaticfunctionMapBook.SheetTemplate.MarkElement()withtheobjectidandelementtype.Forexample,tomarkanobjectasthemapview,call
MapBook.SheetTemplate.MarkElement(objId,_
MapBook.TemplateElementType.MapView)
AdjacentMapSheets
ThearrowspointingtoadjacentmapsheetsareAutoCADblockreferences.Eachblockcanhaveanattributethatdefinesthedirectionofthearrowandcreatesalinktotheadjacentsheet.
Tocreateanarrowtoanadjacentmapsheet,placeablockreferenceofthe
desiredshapeandorientationintothemap.TheblockreferenceshouldhaveanattributenamedTAG.Setthetextstringoftheattributetoanexpressionthatdefinestheadjacentsheet.Thisexpressionisoftheform:
%<\AcSmSheet.direction>%
wheredirectionisoneofthefollowing:
Top
Bottom
Right
Left
TopRight
TopLeft
BottomRight
BottomLeft
Pleasesendusyourcommentaboutthispage