Write Key/Value Data Entries to Object Table

Write Key/Value Data Entries to Object Table

tristan.jonas8XAAW
Advocate Advocate
430 Views
1 Reply
Message 1 of 2

Write Key/Value Data Entries to Object Table

tristan.jonas8XAAW
Advocate
Advocate

Hi all,

 

So I feel like I've seen multiple ways to accomplish this but I haven't gotten any of them to work. Basically all I want is to be able to click an object (Mtext, Polyline, Block, Multiline, you name it) and then add a Key string and a Value string of my choosing, that can be read either at the bottom of the properties window as I've usually seen, or accessible through another function that can read through the object data table.

The success stories I've seen has been written in C# and while that's usually not been a problem for me, I have been unsuccessful in all my attempts to translate it to VB.NET. 

 

Here is what I have so far:

Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.Gis.Map.ObjectData
Imports HostMapApplicationServices = Autodesk.Gis.Map.HostMapApplicationServices

Public Class ObjectDataCommands
    <CommandMethod("AddTestKeyValue")>
    Public Sub AddTestKeyValue()
        ' Get the current document and editor
        Dim doc As Document = Application.DocumentManager.MdiActiveDocument
        Dim ed As Editor = doc.Editor

        ' Prompt user to select an object
        Dim peResult As PromptEntityResult = ed.GetEntity("Select an object:")
        If peResult.Status <> PromptStatus.OK Then
            ed.WriteMessage(vbLf & "No object selected.")
            Return
        End If

        ' Get object id from the user selection
        Dim selectedObjId As ObjectId = peResult.ObjectId

        ' Get the ObjectData tables from the active project within AutoCAD Map
        Dim odTables As Tables = HostMapApplicationServices.Application.ActiveProject.ODTables

        ' Start a transaction for database operations
        Using trans As Transaction = doc.Database.TransactionManager.StartTransaction()
            ' Attempt to get the corresponding ObjectData table named "Generic"
            Dim odTable As Autodesk.Gis.Map.ObjectData.Table
            Try
                odTable = odTables.Item("Generic")
            Catch ex As System.Exception
                ed.WriteMessage(vbLf & "An error occurred: " & ex.Message)
                Return
            End Try

            ' Create a record or get the existing one to associate data with the selected object
            Dim odRecords As Records = odTable.GetObjectTableRecords(Convert.ToUInt32(0), selectedObjId, OpenMode.ForWrite, False)
            Dim odRecord As Record
            If odRecords.Count > 0 Then
                odRecord = odRecords.Item(0)
            Else
                odRecord = odTable.CreateRecord()
                odTable.InitRecord(odRecord) ' Initialize the record if it's new
                odTable.AddRecord(odRecord, selectedObjId) ' Add the new record
            End If

            ' Add or update the key-value pair
            AddOrUpdateRecord(odTable, odRecord, "TestKey", "TestValue")

            ' Commit the changes to the transaction
            trans.Commit()
        End Using

        ' Confirm successful execution to the user
        ed.WriteMessage(vbLf & "TestKey with TestValue has been successfully added or updated.")
    End Sub

    ' Helper function to add or update a key-value pair in an ObjectData Record
    Private Sub AddOrUpdateRecord(odTable As Table, ByRef record As Record, ByVal key As String, ByVal value As String)
        Dim recordData As Data = record.GetData()

        ' Check if the Record already contains the key
        Dim dataIndex As Integer = recordData.IndexOfKey(key)

        If dataIndex >= 0 Then
            ' If key exists, update the value
            recordData.SetValueAt(dataIndex, value)
        Else
            ' If key does not exist, add the key and value
            recordData.Add(key, value)
        End If
    End Sub
End Class
0 Likes
Accepted solutions (1)
431 Views
1 Reply
Reply (1)
Message 2 of 2

norman.yuan
Mentor
Mentor
Accepted solution

The data you are talking is AutoCAD Map ObjectData, to which you have access to by using AutoCAD MAP's API (either COM API, usually used in VBA, or Map's .NET API, or Map's ObjectARX C++ API). Obviously, your code uses Map's .NET API and you need to have AutoCAD Map or AutoCAD C3D to run your code (e.g. the code would not run with plain AutoCAD).

 

You did not say what issue you have, nor your code is complete (e.g. missing some code for "quick debugging" by simply browsing/reading the code). For example,

 

Record.GetData() is obviously a custom extension method, you need to show the code inside this method for debugging. 

 

If you get the code from somewhere, you need to understand the code/API logic. You may need to look up the sample code in the AutoCAD Map online document, or search the net. The AutoCAD Map ObjectARX SDK (not the AutoCAD ObjectARX SDK!) comes with .NET API code samples in both VB.NET and C#, you can download from Autodesk.

 

I found this document with sample code. While it is for AutoCAD Map 2009, it applies to all later versions, because the MAP API has not been changed in all these years:

 

https://documentation.help/AutoCAD-Map-3D-2008-.NET-API/documentation.pdf 

 

Hope this would get you move forward.

 

Norman Yuan

Drive CAD With Code

EESignature