Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Need help with converting C# AutoCAD code to Visual Basic.

Posted on 2014-04-01
2
Medium Priority
?
572 Views
Last Modified: 2014-04-02
All, Please note the following code found at this link:

http://through-the-interface.typepad.com/through_the_interface/2007/07/updating-a-spec.html

I'm trying to convert this C# code to Visual Basic....

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;


namespace BlockIterator

{

  public class Commands

  {

    [CommandMethod("UA")]

    public void UpdateAttribute()

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Database db = doc.Database;

      Editor ed = doc.Editor;


      // Have the user choose the block and attribute

      // names, and the new attribute value


      PromptResult pr =

        ed.GetString(

          "\nEnter name of block to search for: "

        );

      if (pr.Status != PromptStatus.OK)

        return;

      string blockName = pr.StringResult.ToUpper();


      pr =

        ed.GetString(

          "\nEnter tag of attribute to update: "

        );

      if (pr.Status != PromptStatus.OK)

        return;

      string attbName = pr.StringResult.ToUpper();


      pr =

        ed.GetString(

          "\nEnter new value for attribute: "

        );

      if (pr.Status != PromptStatus.OK)

        return;

      string attbValue = pr.StringResult;


      UpdateAttributesInDatabase(

        db,

        blockName,

        attbName,

        attbValue

      );

    }


    private void UpdateAttributesInDatabase(

      Database db,

      string blockName,

      string attbName,

      string attbValue

    )

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Editor ed = doc.Editor;


      // Get the IDs of the spaces we want to process

      // and simply call a function to process each


      ObjectId msId, psId;

      Transaction tr =

        db.TransactionManager.StartTransaction();

      using (tr)

      {

        BlockTable bt =

          (BlockTable)tr.GetObject(

            db.BlockTableId,

            OpenMode.ForRead

          );

        msId =

          bt[BlockTableRecord.ModelSpace];

        psId =

          bt[BlockTableRecord.PaperSpace];


        // Not needed, but quicker than aborting

        tr.Commit();

      }

      int msCount =

        UpdateAttributesInBlock(

          msId,

          blockName,

          attbName,

          attbValue

        );

      int psCount =

        UpdateAttributesInBlock(

          psId,

          blockName,

          attbName,

          attbValue

        );

      ed.Regen();


      // Display the results


      ed.WriteMessage(

        "\nProcessing file: " + db.Filename

      );

      ed.WriteMessage(

        "\nUpdated {0} instance{1} of " +

        "attribute {2} in the modelspace.",

        msCount,

        msCount == 1 ? "" : "s",

        attbName

      );

      ed.WriteMessage(

        "\nUpdated {0} instance{1} of " +

        "attribute {2} in the default paperspace.",

        psCount,

        psCount == 1 ? "" : "s",

        attbName

      );

    }


    private int UpdateAttributesInBlock(

      ObjectId btrId,

      string blockName,

      string attbName,

      string attbValue

    )

    {

      // Will return the number of attributes modified


      int changedCount = 0;

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Database db = doc.Database;

      Editor ed = doc.Editor;


      Transaction tr =

        doc.TransactionManager.StartTransaction();

      using (tr)

      {

        BlockTableRecord btr =

          (BlockTableRecord)tr.GetObject(

            btrId,

            OpenMode.ForRead

          );


        // Test each entity in the container...


        foreach (ObjectId entId in btr)

        {

          Entity ent =

            tr.GetObject(entId, OpenMode.ForRead)

            as Entity;


          if (ent != null)

          {

            BlockReference br = ent as BlockReference;

            if (br != null)

            {

              BlockTableRecord bd =

                (BlockTableRecord)tr.GetObject(

                  br.BlockTableRecord,

                  OpenMode.ForRead

              );


              // ... to see whether it's a block with

              // the name we're after


              if (bd.Name.ToUpper() == blockName)

              {


                // Check each of the attributes...


                foreach (

                  ObjectId arId in br.AttributeCollection

                )

                {

                  DBObject obj =

                    tr.GetObject(

                      arId,

                      OpenMode.ForRead

                    );

                  AttributeReference ar =

                    obj as AttributeReference;

                  if (ar != null)

                  {

                    // ... to see whether it has

                    // the tag we're after


                    if (ar.Tag.ToUpper() == attbName)

                    {

                      // If so, update the value

                      // and increment the counter


                      ar.UpgradeOpen();

                      ar.TextString = attbValue;

                      ar.DowngradeOpen();

                      changedCount++;

                    }

                  }

                }

              }


              // Recurse for nested blocks

              changedCount +=

                UpdateAttributesInBlock(

                  br.BlockTableRecord,

                  blockName,

                  attbName,

                  attbValue

                );

            }

          }

        }

        tr.Commit();

      }

      return changedCount;

    }

  }

}

Open in new window



Here is what I've got so far but I run into issues with the next couple of For Each statements:

Public Function UpdateAttributesInBlock(ByVal btrID As ObjectId, ByVal blockName As String, ByVal attbName As String, ByVal attbValue As String)


            Dim changedCount As Integer = 0
            Dim doc As Document

            doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim btr As BlockTableRecord
            Dim id As ObjectId = GetBlockTableRecordId(doc.Database, blockName)
            Dim tr As Transaction = doc.TransactionManager.StartTransaction
            Dim ent As Entity


            Using tr

                btr = TryCast(id.GetObject(OpenMode.ForRead), BlockTableRecord)
                For Each id In btr

                    ent = tr.GetObject(entId, OpenMode.ForRead)

                Next

            End Using




        End Function

Open in new window


Please fix the syntax so that I may be able to use and test?
0
Comment
Question by:stephenlecomptejr
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 39971245
Have you tried using one of the online code converters?

e.g.

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.DatabaseServices

Imports Autodesk.AutoCAD.EditorInput

Imports Autodesk.AutoCAD.Runtime


Namespace BlockIterator


	Public Class Commands



		<CommandMethod("UA")> _
		Public Sub UpdateAttribute()



			Dim doc As Document = Application.DocumentManager.MdiActiveDocument

			Dim db As Database = doc.Database

			Dim ed As Editor = doc.Editor


			' Have the user choose the block and attribute

			' names, and the new attribute value





			Dim pr As PromptResult = ed.GetString(vbLf & "Enter name of block to search for: ")

			If pr.Status <> PromptStatus.OK Then

				Return
			End If

			Dim blockName As String = pr.StringResult.ToUpper()





			pr = ed.GetString(vbLf & "Enter tag of attribute to update: ")

			If pr.Status <> PromptStatus.OK Then

				Return
			End If

			Dim attbName As String = pr.StringResult.ToUpper()





			pr = ed.GetString(vbLf & "Enter new value for attribute: ")

			If pr.Status <> PromptStatus.OK Then

				Return
			End If

			Dim attbValue As String = pr.StringResult







			UpdateAttributesInDatabase(db, blockName, attbName, attbValue)

		End Sub






		Private Sub UpdateAttributesInDatabase(db As Database, blockName As String, attbName As String, attbValue As String)




			Dim doc As Document = Application.DocumentManager.MdiActiveDocument

			Dim ed As Editor = doc.Editor


			' Get the IDs of the spaces we want to process

			' and simply call a function to process each


			Dim msId As ObjectId, psId As ObjectId


			Dim tr As Transaction = db.TransactionManager.StartTransaction()

			Using tr






				Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)


				msId = bt(BlockTableRecord.ModelSpace)


				psId = bt(BlockTableRecord.PaperSpace)


				' Not needed, but quicker than aborting


				tr.Commit()
			End Using







			Dim msCount As Integer = UpdateAttributesInBlock(msId, blockName, attbName, attbValue)







			Dim psCount As Integer = UpdateAttributesInBlock(psId, blockName, attbName, attbValue)

			ed.Regen()


			' Display the results




			ed.WriteMessage(vbLf & "Processing file: " & Convert.ToString(db.Filename))







			ed.WriteMessage(vbLf & "Updated {0} instance{1} of " & "attribute {2} in the modelspace.", msCount, If(msCount = 1, "", "s"), attbName)







			ed.WriteMessage(vbLf & "Updated {0} instance{1} of " & "attribute {2} in the default paperspace.", psCount, If(psCount = 1, "", "s"), attbName)

		End Sub






		Private Function UpdateAttributesInBlock(btrId As ObjectId, blockName As String, attbName As String, attbValue As String) As Integer



			' Will return the number of attributes modified


			Dim changedCount As Integer = 0


			Dim doc As Document = Application.DocumentManager.MdiActiveDocument

			Dim db As Database = doc.Database

			Dim ed As Editor = doc.Editor



			Dim tr As Transaction = doc.TransactionManager.StartTransaction()

			Using tr






				Dim btr As BlockTableRecord = DirectCast(tr.GetObject(btrId, OpenMode.ForRead), BlockTableRecord)


				' Test each entity in the container...


				For Each entId As ObjectId In btr




					Dim ent As Entity = TryCast(tr.GetObject(entId, OpenMode.ForRead), Entity)


					If ent IsNot Nothing Then


						Dim br As BlockReference = TryCast(ent, BlockReference)

						If br IsNot Nothing Then






							Dim bd As BlockTableRecord = DirectCast(tr.GetObject(br.BlockTableRecord, OpenMode.ForRead), BlockTableRecord)


							' ... to see whether it's a block with

							' the name we're after


							If bd.Name.ToUpper() = blockName Then



								' Check each of the attributes...



								For Each arId As ObjectId In br.AttributeCollection







									Dim obj As DBObject = tr.GetObject(arId, OpenMode.ForRead)


									Dim ar As AttributeReference = TryCast(obj, AttributeReference)

									If ar IsNot Nothing Then


										' ... to see whether it has

										' the tag we're after


										If ar.Tag.ToUpper() = attbName Then


											' If so, update the value

											' and increment the counter


											ar.UpgradeOpen()

											ar.TextString = attbValue

											ar.DowngradeOpen()


											changedCount += 1

										End If

									End If

								Next
							End If


							' Recurse for nested blocks








							changedCount += UpdateAttributesInBlock(br.BlockTableRecord, blockName, attbName, attbValue)

						End If

					End If
				Next


				tr.Commit()
			End Using

			Return changedCount

		End Function

	End Class

End Namespace

Open in new window

0
 
LVL 1

Author Closing Comment

by:stephenlecomptejr
ID: 39972733
Hey kaufmed, I did do that same conversion but only did one of the functions.  I guess it works better when all the code is provided.

Thank you for your reply!
0

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question