Autodesk Official latest. NET Tutorial (iii) (vb.net edition)

Source: Internet
Author: User
Tags commit constructor exception handling finally block garbage collection join
Tutorial Chapter 3rd Database Basics:  Create our own Employee Objects   Open LAB3 folders under LAB3 Engineering files, or then LAB2 code. In this chapter, we will create an ' Employee object ' (including a circle, an ellipse, and a multiline text object) that belongs to a custom Employeeblock ' block that resides in the ' Employeelayer ' layer, when inserting this block in the model space, the ' employeelayer ' layer will have a block index of the block. The code in each step of this chapter can be run so that you can better understand the functionality of each part of the code completion. The first step will briefly explain how to create a circle in the model space.  <!--[If!vml]--><!--[endif]-->  This chapter focuses on the basics of accessing databases in AutoCAD. The main content includes transaction processing (Transaction), Object IDs (ObjectId), symbol tables (symbol tables, such as block table blocktable and Layer table layertable), and object references. Some of the other objects used, such as colour color, three-dimensional point Point3D and three-dimensional vector vector3d, are related to each step, but the emphasis should be on the database. 1)     Create a command named ' Create ' that calls the function Createemployee (). This function is used to create a circle with a radius of 2.0 at the (10,10,0) point of the Model Space (Modelspace):  <commandmethod ("CREATE") > _public function Createemployee () ' First declare the object we want to use Dim circle as Circle ' This is the circle Dim btr As Blocktablerecord We want to add to the model space to join the circle, we must open the model space Dim bt As B Locktable ' to open the model space, we have to access it through the Block table (blocktable)    ' We use an object named ' Transaction ' to encapsulate the operation of the database in the function Dim trans as transaction  ' uses TransactionManager's StartTransaction () member to start the transaction trans = HoStapplicationservices.workingdatabase (). Transactionmanager.starttransaction () ' Now create a circle ... Take a closer look at these parameters--note the static members of the ' new ' and Vector3D that created the Point3D object zaxiscircle = new Circle (new Point3D (0), Vector3d.zaxis, 2.0)   ' We need to get block tables and model space objects ' Note that we are using transactional members GetObject to get their BT = trans. GetObject (HostApplicationServices.WorkingDatabase.BlockTableId, Openmode.forread) ' Now, We have declared a Objectid object to represent the model space block table record ... Dim Btrid as ObjectId = Bt. Item (BTR. Modelspace) ' Use this Objectid object to get the Block table Record Object-Note we are opening it to write to BTR = trans. GetObject (Btrid, openmode.forwrite)   ' now uses BTR object to join the circle BTR. Appendentity (Circle) trans. Addnewlycreateddbobject (Circle, True) ' and determine the transaction processing know to join the circle!  trans.commit () ' Once this is done, we commit the transaction so that the changes made above are saved ... trans. Dispose () ' ... The transaction is then destroyed because we have completed the relevant operations (the transaction is not a database-resident object and can be destroyed) end function  Please read the structure of the code block above, and you can find out the relevant details by commenting. Note: To compile the code, you must import the Autodesk.AutoCAD.DatabaseServices and Autodesk.AutoCAD.Geometry namespaces   Run the function to see if it works. A white circle with a radius of 2.0 at (10,10,0) should be created in the graph. &NBSP;2)     We can reduce the amount of code input, which can be done by declaring a database variable instead of HOSTAPPLICATIONSERVICES.WORkingdatabase to implement:       Dim db as Database = Hostapplicationservices.workingdatabase ()   Use this variable instead of the Hostapplicationservices.workingdatabase () that appears in the code. &NBSP;&NBSP;3)     Note: bt. Item (BTR. Modelspace) is used to get the objectid of the Model Space block table record. We can also do the same thing with blocktable attributes: &NBSP;BT (BTR. Modelspace)   The above method makes the code easier and leaner (changing the relevant code as follows):              bt = trans. GetObject (db. Blocktableid, openmode.forread)             BTR = trans. GetObject (BT (BTR). Modelspace) (openmode.forwrite)  4)     in the above code, we do not use any exception handling, and exception handling is correct. NET application is very important. We have to develop a good habit of using exception handling, so let's add try-catch-finally to this function. &NBSP;5)     in order to make the code compact, we can put the declarations and initialization of many variables in the same statement. Now, your code should look like this:  <commandmethod ("CREATE") > _public Function createemployee () Dim db as Database = Hostapplicationservices.workingdatabase () Dim trans as Transaction = db. Transactionmanager.starttransaction () Trydim Circle as Circle = new Circle (new Point3D (0), Vector3d.zaxis, 2.0)  dim bt as Blocktable = trans. GetObject (db. Blocktableid, Openmode.forread) Dim BTR as Blocktablerecord = trans. GetObject (BT (BTR). Modelspace), Openmode.forwrite)  btr. Appendentity (Circle) trans. Addnewlycreateddbobject (Circle, True)  trans. Commit () Catchmsgbox ("Error adding Entities") Finallytrans.dispose () End tryend function  Run your code to test ... The above catch block displays only an error message. The actual cleanup work is done in the finally block. The reason for this is that if Dispose () is invoked before the transaction is committed (commit), the transaction is destroyed. We think if the trans. If any errors occur before commit (), you should destroy the transaction (because the commit will never be invoked). If a commit () is invoked before Dispose (), that is, no error occurs, the transaction is submitted to the database. Therefore, based on the above analysis, the catch block is not necessarily necessary because it is used only to notify the user that an error has occurred in the program. It will be removed in the following code. 6     Now let's add the rest of the employee: examples of ellipses and multiline text. Now let's add the remainder to the employee: an instance of the ellipse and multiline text.        Multi-line text entity:            The    center point should be the same as the centre of the circle: &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;         (recommended: Create a Point3D variable named ' Center ' with a value of 10,10,0 to represent the center point)                the contents of multiple lines of text can be your name.        ellipse (Hint: You can take a look at the ellipse constructor)                normal vectors should be along the z-axis (see Vector3D type)                Spindle set to Vector3D (3,0,0) (hint: Don't forget to use new)                radius ratio set to 0.5               Ellipses must also be closed (i.e., the start and end points must be the same) run your code to test ... You should be able to generate multiple lines of text for a circle, an ellipse, and a central point in 10,10,0. Note: The try-catch-finally block structure in the. NET API associated with the transaction object should be an anomaly observer. We actually instantiate objects in a try block, but they are not explicitly destroyed. Problems can arise when an exception occurs, especially when the observer notices that we are actually using encapsulated unmanaged objects! Remember, the garbage collection mechanism reclaims memory when resources are no longer in use. The garbage collection mechanism occasionally calls the Dispose () method of the encapsulated class to delete the unmanaged object. It is also important to note that the way that Dispose () acts on the encapsulated unmanaged class object depends on whether the object is a database-resident object. Dispose () that is called by a non-database-resident object deletes the unmanaged object, while the Dispose () of the object call by the database resides simply closes itChildren 7          Next let's create a new function that creates an AutoCAD layer with a color yellow, named "Employeelayer." This function should check whether this layer already exists, but regardless of whether this layer exists, the function should return to the "Employeelayer" Objectid. The following is the code for this function:    public function Createlayer () as objectid        Dim layerid As ObjectId ' it returns the value of the function         Dim db As Database = hostapplicationservices.workingdatabase        Dim trans as Transaction = db. Transactionmanager.starttransaction ()         ' first get the layer table ......         Dim lt as layertable = trans. GetObject (db. Layertableid, openmode.forwrite)          ' check employeelayer layer for presence ......         If Lt. Has ("Employeelayer") then            layerId = Lt. Item ("Employeelayer")         else             ' If the Employeelayer layer does not exist, create it              Dim ltr as Layertablerecord = New Layertablerecord ()              Ltr. Name = "Employeelayer"//Set the layer's names             Layerid = Lt. ADD (LTR)             trans. Addnewlycreateddbobject (LTR, True)         end if         trans.commit ()         trans. Dispose ()         return layerid    end function  Do you think the basic structure of this function is similar to the code that joins entities in the model space? The way to access a database is to use transactions to get database objects, to add entities to the symbol table (where the model space is also one of the symbol tables), and then let the transaction know. 8     Add exception handling in this function, as in the Createemployee function. &NBSP;9)     Next, change the color of the new layer. Here is the code snippet for implementation, please add it to your code: &NBSP;LTR. Color = CoLor. Fromcolorindex (Colormethod.byaci, 2)   NOTE: Colormethod.byaci can let us use the AutoCAD ACI color Index ... Here is 2 (for yellow). &NBSP;10)    go back to Createemployee () and add the code that sets up the several entities created above to the Employeelayer layer. Declares a variable of type objectid, assigning it a value with the return value of the Createlayer function. Use the Layerid property of each entity (text, circle, and Ellipse) to set their layer. For example: text. Layerid = empid  Run code to see if the "Employeelayer" layer has been created, all created entities are on this layer (should appear yellow)  11)    now set different colors for each entity. You can use the ColorIndex property (ColorIndex property to represent the color of AutoCAD)         circle is red -1        ellipse is green -3       text is yellow -2  run code to see if the color of the entity is set value, even if these entities are in the " Employeelayer "on the layer. &NBSP;12)    Next, we will create a separate block in the AutoCAD database and insert it into the block table instead of the model space.   First change the name of the Createemployee function to Createemployeedefinition (). Add the following code to create a separate block:  dim mybtr as Blocktablerecord = New Blocktablerecord () mybtr.name = "Employeeblock" Dim Mybtrid as Ob Jectid = Bt. ADD (MYBTR) trans. Addnewlycreateddbobject (MYBTR, True)  13)    Now, make a little change to the code that adds the entity to the model space (instead of adding blocks to the block table, remember to open the block table before joining).   Run the code now and then use INSERT the command to check if the block can be inserted correctly. &NBSP;14)    Finally, we want to create a block index in the model space that represents an instance of the block created above. This step is reserved for you to practise.   Below is the most basic step you will follow:       <!--[if!supportlists]-->a]                    <!--[endif]--> Create a new function named Createemployee  <!--[if!SUPPORTLISTS]--&GT;B]                    <!--[endif]--> to move the command attribute "CREATE" to Createemployee ()  <!--[if!supportlists]-->c)                    <!--[endif]--> modifies createemployeedefintion () to return the objectid of the newly created block "Employeeblock". Please refer to Createlayer () for the steps of the operation.  <!--[if!supportlists]-->d)                    <!--[endif]--> You need to modify createemployeedefintion () to see if "employeeblock" blocks are already included in the Block table. If the block is included, it returns theObjectId (procedure is the same as Createlayer ()). Tip: Move the ' BT ' statement to the top of the try block, using blocktable. Has () method, move other code to else statement:try                 ' Get Blocktable object                 Dim BT As Blocktable = trans. GetObject (db. Blocktableid, Openmode.forwrite)                  If (BT. Has ("Employeeblock")) then                 Newbtrid = BT ("Employeeblock") ' already exists ... There's no need to create it! else   ... <!--[if!supportlists]-->e)                    <!--[endif]--> in the newly created Createemployee () function to create a new Blockreference object and add it to the model space. Hint: We can use the code in Createemployeedefinition () that references the model space, which is not needed here <!--[if!supportlists]-->f)                    <!--[endif]--> calls the Createemployeedefinition () function in Createemployee, Causes the Blocktablerecord () of the Blockreference object generated above to point to the createemployeedefinition () function. Tip: Refer to the Blockreference constructor.    Additional questions: Let's take a look at the operation of the code and execute the command to generate a Employeeblock block index, and you'll see it being inserted into 20,20,0 instead of 10,10,0. Why? If you know why, then how do you get the block index plugged into the correct point? When you view a block index with the list command, it tells you that it is at level 0 (or at the current level when the command is running). Why? How do I make the Block index always located at the Employeelayer level?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.