Solved

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

Posted on 2014-04-01
2
558 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 500 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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
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…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

710 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