Solved

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

Posted on 2014-04-01
2
540 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
2 Comments
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

744 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now