Docstoc

.NET programming for Civil Engin

Document Sample
.NET programming for Civil Engin Powered By Docstoc
					.NET programming for Civil Engineers and
Surveyors
Strahimir Antoljak, P.E. – Langan Engineering & Environmental Services



CP405-2       This class covers introductory programming for civil engineers and surveyors who want to
              venture into the world of customization with VB.NET. You will learn the prerequisites needed to
              start programming in .NET, and how to create AutoCAD Civil 3D objects such as COGO
              points, surfaces, alignments, profiles, and more.




About the Speaker:
In addition to 15 years of international experience in several civil engineering disciplines, Strah has a broad
CAD/GIS and computer-programming background. Previously a teacher of engineering graphics with
AutoCAD at Rutgers University, Strah currently participates in the advanced engineering design, CAD
management, and database aspects within his company, in addition to providing CAD support, in-house CAD
training sessions, and custom-applications programming. santoljak@langan.com
What Is .NET?
“Microsoft .NET is the Microsoft strategy for connecting systems, information, and devices through
Web services so people can collaborate and communicate more effectively. .NET technology is
integrated throughout Microsoft products, providing the capability to quickly build, deploy, manage, and
use connected, security-enhanced solutions through the use of Web services.”
Source: http://www.microsoft.com/net/basics_faq.mspx#EWB)

“... .NET-connected solutions enable businesses to integrate their systems more rapidly and in a more
agile manner and help them realize the promise of information anytime, anywhere, on any device.”
Source: http://www.microsoft.com/net/basics.mspx, February 1, 2005.

.NET introduces a notion of managed code. “In Microsoft Windows terminology, managed code is
computer program code that executes under the management of Microsoft's Common Language
Runtime (CLR) virtual machine, or another similar virtual machine. It is contrasted with unmanaged
code, which is executed directly by the computer's Central Processing Unit (CPU). The benefits of
managed code include programmer convenience and enhanced security guarantees.

The programming language used to create the program determines whether or not it will run as managed
code. Microsoft's most common languages for creating managed code are C# and Visual Basic .NET.

While the term was popularized by Microsoft in its description of programs executed by the Microsoft
CLR, it can be used to describe code intended for any virtual machine execution environment. Thus, for
example, the Java programming language can also be described as one that creates managed code,
which in this case is executed by the Java Virtual Machine.”
Source: Wikipedia http://en.wikipedia.org/wiki/Managed_code



Prerequisites to program in .NET

Notepad and Windows Operating System (OS). In theory, for programming in .NET you need not
buy any software besides Windows Operation System (OS). A bare Notepad and a compiler that comes
with free .NET Framework Software Development Kit (SDK) could serve you as a development
environment. Of course, using Notepad for .NET programming is a bit of dramatization. No sane person
would venture into such a project.

Microsoft Visual Basic.NET (VB.NET) Express Edition. If you want to keep your sanity and be
relatively comfortable programming in .NET, you would use an interactive development environment such
as VB.NET Express. The VB.NET Express edition offers productivity that is ideal for first-time or casual
Windows programming. The bright side of VB.NET Express edition is its price tag — free. You can
download it at http://msdn2.microsoft.com/en-us/express/aa974184.aspx. As usual, however, even
something free comes at a price and for VB.NET Express that price is the lack of some important
functionality that a programmer expects to have. Disabled debugging mode is the most significant lack
of functionality in VB.NET Express. In addition to the free VB.NET Express edition, you can acquire the
relatively inexpensive VB.NET Standard edition but this software also has debugging mode enabled.




                                                                                                      2/25
Microsoft Visual Studio (VS). For greater comfort and productivity you may want to consider
Microsoft Visual Studio. Different editions are available but VS Standard edition is quite sufficient and not
too expensive. It costs between $250 and $300.
Microsoft Visual Studio 2005 (Standard Edition) is a comprehensive, high-productivity professional
development environment for building high-performance, multi-tier applications for Windows, Web, and
common consumer mobile devices. Intended for individual developers and software development teams
to build departmental client-server Windows applications and Web sites, Visual Studio 2005 provides a
wide range of tools that streamline and enhance development processes.
Included in the Microsoft Visual Studio 2005 Standard Edition are Microsoft Visual Basic, Microsoft Visual
C#, Visual C++, and Microsoft Visual J# programming languages; tools for building Windows and Web
solutions; SmartPhone and Pocket PC development tools; and tools for visually designing databases,
queries, and stored procedures.
You may consider using different versions of VS for different versions of AutoCAD, and
consequently AutoCAD Civil 3D.
Strictly speaking, specific Visual Studio versions (and editions) are not necessary for using the managed
Application Programming Interfaces (APIs) for the respective versions of AutoCAD, and that is one of the
advantages of .NET — no need for a specific compiler version, as ObjectARX/C++ requires. However, for
consistency it is suggested to maintain the parity with the version needed to build ObjectARX/C++
applications to work with AutoCAD.
Thus with AutoCAD Civil 3D 2008 you would use Microsoft Visual Studio 2005 (Version 8.0) or
Microsoft Visual Basic 2005.
As for managed code, VS 2005 is suggested for AutoCAD 2008 and AutoCAD 2007 (and required for
unmanaged API; ObjectARX/C++), but AutoCAD 2006 will work just fine with either VS 2005 or VS 2003.
This does not automatically mean that AutoCAD 2006 and AutoCAD 2007 .NET plug-in are
interchangeable if both are written in VS 2005. You will have to re-reference the managed libraries found
in the AutoCAD application directory and recompile to get the plug-in (code) written for AutoCAD 2006 to
run in AutoCAD 2007. In addition, you might need to fix fragments of code.
VS 2003 or VS 2002 is suggested for managed code and earlier versions of AutoCAD, and is required for
unmanaged code and earlier versions of AutoCAD.



Extras And Goodies
To get started with writing .NET applications (plug-ins) for AutoCAD Civil 3D 2008 you need VS.NET
2005 or VB.NET 2005, and AutoCAD Civil 3D 2008. That is all. However, extras can make customization
easier, so here are few of them:

1. ObjectARX Software Development Kit (SDK). Free download at www.objectarx.com.
The ObjectARX programming environment provides object-oriented C++, C# and VB .NET application
programming interfaces for developers to use, customize, and extend AutoCAD software and AutoCAD-
based products like AutoCAD Civil 3D 2008.




                                                                                                         3/25
You can download ObjectARX SDK for AutoCAD 2008, AutoCAD 2007, AutoCAD 2006, and AutoCAD
2005. ObjectARX for AutoCAD 2008 is available in 32-bit and 64-bit versions. You may want to check out
the ObjectARX version you plan on using, depending on your software and hardware setup/requirements.
The two most important benefits to a VB.NET developer from ObjectARX SDK are samples and
AppWizard. Good samples (\samples\dotNet\ folder), documentation, and help files for the ObjectARX
SDK show how to use various features of the managed API to AutoCAD. The second benefit is the
AutoCAD Managed VB Project Application template that is installed by ArxWizard. The template
shows when you ask Visual Studio 2005 to create a new project and simplifies setting up an AutoCAD
customization program. The ArxWizard can be found in the utils\ObjARXWiz\ArxWizard.msi folder of the
kit. The only problem I encountered with this VB.NET template is that I could not install it on VB.NET
2005 Express edition. However, it will install on VS 2005 .




2. The AutoCAD VB.NET Application template comes with a VB.NET Programming for AutoCAD
Customization book, http://www.vbcad.com/showabook.asp?BOOKID=5
The book is a great VB.NET reference and it includes a DVD with the AutoCAD VB.NET Application
template. The template can be a big help if you decide to start with the free VB.NET Express edition and
postpone purchase of VS.NET. If you install this VB.NET template, you can not only use it with the
VB.NET Express edition, but you can debug your code in VB.NET Express! However, as the author
states, “it is possible that Microsoft could ‘disable’ our little work-around and Visual Studio 2005 would
need to be purchased.”




                                                                                                      4/25
3. Civil 3D 2008 Basic vb.net template. Free download at www.CivilDev.com
As you will see later, AutoCAD Civil 3D requires a lot of references and this VB.NET template simplifies
the process of setting up an AutoCAD Civil 3D customization program. It runs either on the VB.NET
Express edition or VS, and enables debugging in VB.NET Expression. The sample code supplied in the
accompanying dataset for this class was written using this VB.NET template.




Side note: If you cannot debug an add-in in 2006, check the 'acad.exe.config' file. Usually the debugging issue occurs because
AutoCAD 2006 is set to only use v1.x of the .NET framework. Commenting-out this line will let it use the most recent version
installed on your machine (v2.x) and will let you debug in VS 2005.
Source: http://discussion.autodesk.com/thread.jspa?threadID=517693



4. AutoCAD Civil 3D API resources.

     •    Free webcast at http://www.adskconsulting.com/adn/cs/api_course_sched.php?col=Language
          This webcast provides an overview of the AutoCAD Civil 3D Automation API and it helps
          participants understand the concepts, functions and capabilities of the latest version of the
          AutoCAD Civil 3D API. Although the code shown is VB(6) or VBA, it can be easily migrated to
          VB.NET.
     •    The AutoCAD Civil 3D Developer Help includes three documentation components found in the
          Help folder of the AutoCAD Civil 3D 2008 installation folder, and source code samples:
               o    ActiveX API Reference (civilauto-reference.chm)
               o    Developer's Guide (Civil3DDevelopersGuide.chm)
               o    CustomDraw C++ API Reference (civildraw-reference.chm)
               o    Source Code Samples: The Civil 3D API subdirectory contains samples in VB, VBA, C++,
                    C# and VB.NET. Considering that AutoCAD Civil 3D is built on the top of AutoCAD, you
                    can take advantage of all the AutoCAD source code samples for ActiveX (COM
                    Automation), VB/VBA, Visual Lisp, and .NET that are included with the installation of
                    AutoCAD Civil 3D software in the Samples directory.
     •    Autodesk’s Civil 3D related Discussion Groups:
          http://discussion.autodesk.com/index2.jspa?categoryID=17
     •    Augi forums www.augi.com




                                                                                                                             5/25
    •   Through the Interface at http://through-the-interface.typepad.com/
    •   Autodesk University classes – for example class CP405-2 :)
    •   Autodesk Developers Network http://adn.autodesk.com. This requires membership.


5. Visual Studio 2005 Tools for Applications Software Development Kit (SDK).
http://www.microsoft.com/downloads/details.aspx?FamilyID=7c2ea8ae-e051-449a-9051-
3a351bf27b7f&DisplayLang=en
While you cannot take advantage of Visual Studio Tools for Applications (VSTA) at present time, keep
this notion handy. It should not come as a big surprise that VSTA will be incorporated in future versions of
AutoCAD and AutoCAD Civil 3D in the way that VBA and VLips are today. The good thing about it is that
whatever you learn about VB.NET today will only be easier in VSTA tomorrow, much like VB developers
can quickly dive into Visual Basic for Applications (VBA) programming.
Here is the official Microsoft description:
“Visual Studio Tools for Applications (VSTA) leverages the productivity of Visual Studio and the power of
the .NET Framework, accelerating customization development while providing new levels of security and
control.
With the familiar Visual Studio development environment, VSTA enables Visual Basic and Visual C#
developers to easily build managed customizations for both COM (Component Object Model) and .NET
applications. Sharing a common toolset with Visual Studio, VSTA provides a wealth of design-time
features, a robust programming model, and seamless promotion of VSTA projects to full Visual Studio.
The VSTA SDK includes integration tools, samples, and documentation to help you get started with
VSTA.”




To learn more about ActiveX and COM, and their comparison with .NET visit:
ActiveX, COM, and DCOM:
http://sern.ucalgary.ca/Courses/CPSC/547/W2000/webnotes/COM/COM.html
COM: Component Object Model Technologies:
http://www.microsoft.com/com/default.mspx
ActiveX and COM:
http://zone.ni.com/devzone/cda/tut/p/id/2981




                                                                                                       6/25
AutoCAD Civil 3D 2008
Autodesk Civil 3D is a powerful civil engineering tool incorporating a dynamic engineering model that
allows elements to be automatically updated in response to changes in your design. Using Autodesk Civil
3D as a platform, you can take advantage of industry-standard development tools and technologies when
building applications.

AutoCAD Civil 3D 2008 API now supports the creation of alignments outside of sites. New objects and
methods have also been added to the Pipe and Corridors APIs. These improvements extend the
functionality and flexibility of the AutoCAD Civil 3D 2008 API.

The most significant enhancement, however, is the introduction of .NET subassemblies. The default
subassemblies included with AutoCAD Civil 3D are now created using the .NET framework. To maintain
backward compatibility, however, VBA subassemblies are also supported and a utility to convert VBA
subassemblies to .NET is included in the product.

Using the ActiveX (COM Automation) interface in AutoCAD Civil 3D software, you can build applications
with a variety of programming technologies and environments including MSVC++, VB, Delphi, and Java.

A separate, lightweight C++ API is provided for overriding the graphical display of AutoCAD Civil 3D
objects so that developers can customize the drawing and display of these objects.
(See civildraw-reference.chm in the Civil 3D installation folder).

AutoCAD Civil 3D provides .NET Interop assemblies that expose the ActiveX interfaces so they
can be programmed using .NET technologies such as VB.NET, managed C++, and C#.

Although AutoCAD Civil 3D does not expose an ObjectARX API, applications built with the AutoCAD
ObjectARX SDK or the AutoCAD Map ObjectARX SDK will run within AutoCAD Civil 3D.

Extensive application development documentation for the ActiveX (COM Automation) API is built
into the AutoCAD Civil 3D Help system. The Help System also contains information on C++ and
.NET application development.

For more visit: http://usa.autodesk.com/adsk/servlet/index?siteID=123112&id=8007696




                                                                                                       7/25
AutoCAD Civil 3D Object Model
AutoCAD Civil 3D provides .NET interops that expose the ActiveX
interfaces so that they can be programmed using .NET technologies, such
as VB.NET, managed C++, and C#.

.NET interops are programming interface, or means to reach Civil 3D
objects. The objects are grouped in different Object Models. AutoCAD Civil
3D 2008 has four Object Models:

     •    AutoCAD Civil 3D Object Model
     •    AutoCAD Civil 3D Corridor Object Model
     •    AutoCAD Civil 3D Pipe Object Model
     •    AutoCAD Civil 3D Survey Object Model

In this class we are covering objects that are stored in AutoCAD Civil 3D
Object Model, shown in the figure.

Accessing objects in the AutoCAD Civil 3D 2008 Object Model is
accomplished by adding the references in the project's Solution Explorer
window of Visual Studio. Right-click on the References node in the
Solution Explorer and choose Add Reference from the floating menu. In
the Add Reference dialog box, select the COM tab. Select the following
components:

     •    AEC Base 5.5 Application Library
     •    AEC Base 5.5 Object Library
     •    Autodesk Civil Engineering Land 5.0 Object Library
     •    Autodesk Civil Engineering UI Land 5.0 Object Library
     •    AutoCAD 2008 Type Library
     •    AutoCAD/ObjectDBX Common 17.0 Type Library

For accessing Roadway/Corridor objects, you would also reference:

     •    Autodesk Civil Engineering Corridor 5.0 Object Library
     •    Autodesk Civil Engineering UI Corridor 5.0 Object Library

For accessing Pipe objects, you would reference:

     •    Autodesk Civil Engineering Pipe 5.0 Object Library
     •    Autodesk Civil Engineering UI Pipe 5.0 Object Library

For accessing Survey objects, you would reference:

     •    Autodesk Civil Engineering Survey 5.0 Object Library
     •    Autodesk Civil Engineering UI Survey 5.0 Object Library




                                                            8/25
Object Browser
Visual Studio provides a tool called the Object Browser that lets you see the relationships between
objects. You can open the Object Browser from the View menu, or by clicking the Object Browser button
on the main toolbar.




There are three panes: an Objects pane on the left, a Members pane on the upper right, and a
Description pane on the lower right, as shown in the figure above.
In the Objects pane, icons identify hierarchical structures such as .NET Framework and COM
components, namespaces, type libraries, interfaces, enums, and classes. You can expand these
structures to reveal ordered lists of their members. Properties, methods, events, variables, constants, and
other contained items are listed in the Members pane. Details on the item selected in the Objects or
Members pane appear in the Description pane.
The browsing scope can be narrowed to the projects you are developing and the components they
reference, or expanded to include the entire .NET Framework, all COM components installed on your
machine, and all external components that you can access. You can also specify a custom set of folders
to browse. For more information, visit: http://msdn2.microsoft.com/en-us/library/exy1facf(VS.80).aspx .




                                                                                                      9/25
How To Write Code — Hello Class CP405!
You downloaded VB.NET 2005 Express or purchased VB.NET Standard or VS 2005 and you want to
start coding.

Let’s create the simplest VB.NET program “Hello Class CP405” just to see how to get into the coding
environment and how to run that code in AutoCAD and AutoCAD Civil 3D.

VS 2005 and VB.NET 2005 Express edition will be briefly compared.

    1. Start VS 2005. The screen captures are taken on Visual Studio 2005 running on Windows XP.

    2. From the File menu select New > Project...
        The New Project dialog box will be displayed.
    3. In the New Project dialog box, select the applicable VB.NET template.
        The most basic template to use is the Class Library template. Optionally you may use any of the
        aforementioned VB.NET templates depending on whether you installed them. In the screen
        captures below, Civil 3D 2008 Basic template is selected.
    4. At the bottom of the New Project dialog box, enter name and select location. Click the OK button.
        In the figure below VB.NET project is named C3DBasic, and is located on “C:\”.
        Clicking on the OK button in the New Project dialog box will get you to the programming
        environment.




                                                                                                  10/25
If you use the VB.NET 2005 Express Edition.

   1. Start the VB.NET 2005 Express. The screen captures are taken on VB.NET 2005 Express
      running on Windows Vista. Vista is not required. VB.NET 2005 Express runs on Windows XP too.

   2. From the File menu select New > Project...
       The New Project dialog box will be displayed.
   3. In the New Project dialog box select applicable VB.NET template.
       The most basic template to use is the Class Library template. Optionally you may use any of the
       aforementioned templates depending whether you installed them. In the screen captures below,
       Civil 3D 2008 Basic template is selected.
   4. At the bottom of the New Project dialog box, enter name and select location. Click the OK button.
       In the figure below VB.NET project is named C3DBasic, and is located on
       “C:\Strah\AU2007\Code”.
       Clicking on the OK button in the New Project dialog box will get you to the programming
       environment.




                                                                                                 11/25
Once you have created a new VB.NET project, you want to set up debug mode. Keep in mind that debug
mode is only available in VS studio or the purchased version of VB.NET Standard Edition, but it is not
available in VB.NET Express edition — not by default anyway.

    5. In the Solution Explorer, right-click on the project and from the floating menu select Properties at
       the bottom, as shown in the figure below.
        This will bring up a page with multiple tabs, one of which is Debug tab.
    6. Click on the Debug tab and enter or browse to:
       Start external program: C:\Program Files\AutoCAD Civil 3D 2008\acad.exe
       Working directory: C:\Program Files\AutoCAD Civil 3D 2008 as show in the figure below.




This will enable you to step through the code line by line while executing it in AutoCAD Civil 3D, and will
help you track down bugs in your code.




                                                                                                      12/25
Notice that VB.NET 2005 Express edition does not offer you the Start external program setting, see figure
below. This means that you cannot debug your code, which is perhaps crucial functionality when writing
the code.




Remember, if you are using Civil 3D 2008 Basic vb.net template or AutoCAD VB.NET Application
template, as mentioned on page 4 and 5, you will be able to debug even in VB.NET Express edition.




                                                                                                   13/25
Next, you want to add reference libraries to reach AutoCAD and AutoCAD Civil 3D objects as shown on
page 8.

   7. If References node is not visible in the Solution Explorer, then click the Show All Files button as
      shown in figure below — the References node will show. Right-click to the References node and
      select Add Reference... The Add Reference dialog box will pop up.




You need to add two .NET references and six COM references. If .NET references are not visible in
.NET tab, click to the Browse tab and browse to the C:\Program Files\AutoCAD Civil 3D 2008 folder, then
select acdbmgd.dll and acmgd.dll, the two AutoCAD pure NET references. Then from the COM tab, select
remaining 6 Civil 3D references as mentioned on page 8.




                                                                                                    14/25
     8. Next you may want to import some so-called Microsoft and Autodesk Namespaces. This step is
        optional but it does help you with typing less code.
Namespace is a group of classes, structures, interfaces, enumerations, and delegates, organized in a logical hierarchy by function,
that enable you to access the core functionality you need in your applications.
Source: http://www.dotnetinterviewfaqs.com/what-is-namespace-in-microsoft-dot-net.aspx.

Most programmers are too lazy to type, so this is one of the first things they will do to reduce typing.
Importing namespace must be placed before the Class is defined. In this example the Class is called
Public Class AU07ClassCP405.
The following Namespaces are imported
          'Microsoft Namespaces
          Imports System.Runtime.InteropServices
          Imports System.Runtime.InteropServices.Marshal

          'AutoCAD Namespaces - "pure" NET based (thin wrapper around ObjectArx)
          Imports AcadNet = Autodesk.AutoCAD 'equivalent to Imports Autodesk.AutoCAD
          Imports AcadNetRuntime = Autodesk.AutoCAD.Runtime
          Imports AcadNetAppServices = Autodesk.AutoCAD.ApplicationServices
          Imports AcadNetDbServices = Autodesk.AutoCAD.DatabaseServices
          Imports AcadNetDBTransMan = Autodesk.AutoCAD.DatabaseServices.TransactionManager
          Imports AcadNetGeometry = Autodesk.AutoCAD.Geometry
          Imports AcadNetEditorInput = Autodesk.AutoCAD.EditorInput

          'Civil 3D (related) Namespaces - COM based
          Imports AcadCom = Autodesk.AutoCAD.Interop 'equiv. to Imports Autodesk.AutoCAD.Interop
          Imports AcadComCommon = Autodesk.AutoCAD.Interop.Common
          Imports Civil3DCom = Autodesk.AECC.Interop.Land
          Imports Civil3DComUi = Autodesk.AECC.Interop.UiLand

          Public Class AU07ClassCP405


If a certain namespace is imported, you have more direct access to objects within it. For example, when
declaring COGO point (AeccPoint), you need to type the following:
          Dim oPoint As Autodesk.AECC.Interop.Land.AeccPoint

If on the other hand, namespace Autodesk.AECC.Interop.Land has been imported:
          Imports Autodesk.AECC.Interop.Land

Then you can write the short expression:

          Dim oPoint As AeccPoint

You may notice that AutoCAD object can be obtained in two ways; as NET based and COM based. To
resolve Application ambiguities for the two types of AutoCAD objects, we may want to separate and
(re)name the namespaces as:

          Imports AcadNet = Autodesk.AutoCAD
          Imports AcadCom = Autodesk.AutoCAD.Interop


This is because you can program in plain vanilla AutoCAD in pure .NET, or managed code, which is really
a thin layer on top of ObjectARX (C++ based). On the other hand, AutoCAD Civil 3D provides .NET
interops that expose the ActiveX interfaces — COM automation.




                                                                                                                            15/25
    9. Finally, you write the code. Here is the most basic code example, as shown in the figure below.
       This code just shows a message box.




In the example above, CmdName is the command you can call from AutoCAD and Public Sub Subroutine
is the subroutine, or sub for short, that will be run when CmdName is typed on the AutoCAD’s command
line and executed.

Optionally you may place breakpoints. This helps debugging. In the programming environment, they
show as brown dots on the side and the line of code at breakpoint is shaded in brown as shown in the
figure above. When you run the code, the program will halt here. This is particularly helpful when you
have a long code and you want to debug only pieces of it so the code will run fast up to the breakpoint
and then, from the breakpoint on, you can step through it line by line, closely analyzing it. To set the
breakpoint, simply click on the side of the programming environment. To remove it, click on it.

As you will see in next step, you run the code by clicking on the icon circled in red in the figure above, or
by pressing the F5 function key on the keyboard.

To step through your code line by line, either from the breakpoint on, or from the very start of code, you
need to press F11 function key. The line of code that is being executed is highlighted in yellow, as
shown in the figure above.

Let’s test the code!




                                                                                                        16/25
How To Run Code
    1. To run the code, you need to press the F5 function key on the keyboard, or click to the Start
       Debugging arrow as show in the previous figure.
If you set Start external program and Working directory in the Debug tab, or if you created project based
on Civil 3D 2008 Basic vb.net template (which automatically sets debug mode for you), then pressing the
F5 function key will start AutoCAD Civil 3D 2008.
Once AutoCAD Civil 3D 2008 is up and running, you need to load the piece of code you wrote to run it.
The code, once compiled, is saved as so-called dynamic-linked library (dll file). For .NET programming in
particular, you will also hear the term .NET assembly interchangeably used for dll file — see figure
below.
    2. At the AutoCAD command prompt, type in NETLOAD and press the Enter key. This will pop the
       Choose .NET Assembly dialog box, as shown below.
The assembly is saved in the Debug subfolder, or Release subfolder, of your VB.NET project. For
example, VB.NET project name in this example is Civil3Dbasic, so the assembly is located in the folder
...\C3DBasic\C3DBasic\bin\Debug\C3DBasic.dll.




                                                                                                   17/25
    3. In the Choose .NET Assembly dialog box, browse to the .NET assembly (dll file) with your code
       and click Open.

        This will load .NET assembly, so you can run the code from within.

    4. At the command prompt type the name of the command defined within the assembly and press
       the Enter key as you would do with any other native AutoCAD command. In our case, the name
       of command is CmdName.

Executing the command will run the code and voilà, a message box with Hello Class CP405 pops up.




Unfortunately there is no NetUnload command (at present) so you will have to start and close AutoCAD
every time when you want to make a change in the code and test it again.

Once you debugged your code and it is ready to use, skip step 1, and netload the .NET assembly (dll)
from the AutoCAD Civil 3D command line, without using VB.NET or VS.




                                                                                                 18/25
Accessing Application and Document Objects
Some generic AutoCAD Civil 3D objects are required most of the time, if not always. It is a good practice
to put such code in a separate files (referred to as class or module), and just call it when needed, rather
than repeatedly writing it as part of different coding subroutines or functions. One classic example of this
case is obtaining application, document and database objects.
Extract from AutoCAD Civil 3D 2008 Developer’s Guide (modified to apply to .NET):
“The root object in the AutoCAD Civil 3D COM hierarchy is the AeccApplication object. It contains information about the main
application window, base AutoCAD objects, and a collection of all open documents. AeccApplication is inherited from the
AutoCAD object AcadApplication.

The AeccApplication object is accessed by first using the GetActiveObject function that obtains a running instance of the
specified object (e.g. AutoCAD) from the Running Object Table (ROT). The GetActiveObject public shared function is member
of Microsoft namespace called System.Runtime.InteropServices.Marshal. This function returns the AutoCAD
AcadApplication object. From this point, use COM Automation to get the desired AutoCAD Civil 3D AeccApplication object.

The application object contains references to all open documents in the AeccApplication.Documents collection and the
AeccApplication.ActiveDocument property. AeccDocument is inherited from the AutoCAD object AcadDocument. See the
AutoCAD ObjectARX documentation for information on all inherited methods and properties.”

Translated into English, this means the following: before you add any Civil 3D object, such as point,
surface, alignment, etc., to the drawing, you need to programmatically grab the AutoCAD Civil 3D
application (object). Once you get it, you will obtain its document (ActiveDocument) and its database
(ActiveDocument.Database) where you can store newly created Civil 3D objects (point, surface,
alignment, etc.)
Obviously, this step will need to be repeated frequently; therefore, I put it in a separate file called
Common.vb. You can see this file in the Solution Explorer once you open the dataset in VS or VB.NET.
Here is the code in Common.vb that demonstrates the process of accessing the AeccApplication,
AeccDocument, and ActiveDocument.Database objects:
               Const ACAD_VER As String = "AutoCAD.Application.17.1"
               Const CIVIL3D_VER As String = "AeccXUiLand.AeccApplication.5.0"

               Public g_oCivil3D As Civil3DComUi.AeccApplication
               Public g_oCivil3DDoc As Civil3DComUi.IAeccDocument
               Public g_oCivil3DDb As Civil3DCom.IAeccDatabase

               ' Get Civil 3D (AeccApplication), Civil 3D document (AeccDocument)
               ' and database (AeccDatabase) objects.
               Public Function Civil3DObtained() As Boolean
                   Dim oAcad As AcadCOM.AcadApplication
                   oAcad = GetActiveObject(ACAD_VER)
                   g_oCivil3D = oAcad.GetInterfaceObject(CIVIL3D_VER)
                   If g_oCivil3D Is Nothing Then
                       MsgBox("Error creating " & CIVIL3D_VER & ", exit.")
                       Return False
                   End If
                   g_oCivil3DDoc = g_oCivil3D.ActiveDocument
                   g_oCivil3DDb = g_oCivil3D.ActiveDocument.Database
                   Return True

              End Function

AeccApplication is represented with a global variable g_oCivil3D, ActiveDocument with
g_oCivil3DDoc, and ActiveDocument.Database with g_oCivil3DDb. A global variable can be used
throughout the entire VB.NET project (scope).




                                                                                                                       19/25
Code in This Class
Sample code developed for this class can be downloaded from AU web page and is saved under the
following name: AU07CP405-2.zip. It was written entirely using the following:

  • VB.NET 2005 Express edition running on Microsoft Vista.
    Vista is not mandatory, and code will run equally on Microsoft Windows XP.

  • VB.NET project is based on Civil 3D 2008 Basic vb.net template (courtesy of www.CivilDev.com).
    This VB.NET template attaches all required references automatically, applies all the Imports
    statements, and enables debugging even in the VB.NET Express edition.

  • Some basic .NET error handling methods are included with the code (e.g. Try - Catch).



To run the code, you will need the following information and files:

  • Password to unlock code: AU07CP405
    Code is supplied as zipped dataset file, which requires a password to unzip.

  • Drawing template that code works best with _AutoCAD Civil 3D (Imperial) NCS Base.dwt.
    This drawing template is supplied with AutoCAD Civil 3D 2008. Code may not run with other drawing
    templates if, for example, some of the hard-coded object styles are missing.

  • Point file: C:\PointsPENZD_CommaDelimit.csv
    File PointsPENZD_CommaDelimit.csv is enclosed in the dataset file AU07CP405-2.zip. Once the
    dataset file is unzipped, move or copy PointsPENZD_CommaDelimit.csv on the C drive top level.

In this handout, only code snippets are presented demonstrating the concepts. The entire code is
supplied in the data set in the form of VB.NET solution. To explore and analyze it, you need to open the
solution with VB.NET 2005 Express or VS 2005 and run it. To open the solution, look for the so-called
solution file C3Dbasic.sln.




                                                                                                    20/25
Creating Civil 3D Point And Point Group
User’s Interface                                                       Programmer’s Interface

                                                            Point and Point Group Object Model




                                                     Essential Code to create Point

                                                     Dim dCoords(0 To 2) As Double
                                                     Dim oPoint As AeccPoint
                                                     Dim oPoints As AeccPoints

                                                     'Get Civil 3D application, document and database
                                                     '(see page 18, and source code for more details)
                                                     If Not Civil3DObtained() Then Exit Sub

                                                     'Get the drawing points
                                                     oPoints = g_oCivil3DDoc.Points

                                                     'Add a point to the drawing's ponits - oPoints
                                                     oPoint = oPoints.Add(dCoords)



                                                     Essential Code to create Point Group

                                                     Dim oPointGroup As AeccPointGroup
                                                     Dim oPointGroups As AeccPointGroups

                                                     'Get the Point Group collection in the drawing
                                                     oPointGroups = g_oCivil3DDoc.PointGroups

                                                     'Create new Point Group
                                                     oPointGroup = oPointGroups.Add(“point group name”)


For the entire code, refer to region Points in the
dataset C3DBasic.




                                                                                            21/25
Creating Civil 3D Surface
User’s Interface                                                          Programmer’s Interface

                                                                              Surface Object Model




                                                     Essential Code to create TIN Surface

                                                     Dim oTinCreationData As AeccTinCreationData
                                                     Dim oTinSurface As AeccTinSurface
                                                     Dim oSurfaces As AeccSurfaces

                                                     'Get Civil 3D application, document and database
                                                     '(see page 18, and source code for more details)
                                                     If Not Civil3DObtained() Then Exit Sub

                                                     'Get the collection of all the surfaces in the
                                                     'document (drawing).
                                                      oSurfaces = g_oCivil3DDoc.Surfaces

                                                     oTinCreationData = New AeccTinCreationData
                                                     'Set oTinCreationData properties such as
                                                     'Name, Style, Layer, Description, etc.

                                                     'Add empty surface container to the surface
                                                     'collection in the Prospector
                                                     oTinSurface = _
For the entire code refer to region Surface in the   g_oCivil3DDoc.Surfaces.AddTinSurface(oTinCreationData)
dataset C3DBasic.
                                                     'Populate the empty surface container with data:
                                                     'e.g. breaklines, point groups
                                                     oTinSurface.Breaklines.AddStandardBreakline(parameters)
                                                     oTinSurface.PointGroups.Add(oSomePointGroup)


                                                                                               22/25
Creating Civil 3D Alignment
User’s Interface                                                           Programmer’s Interface

                                                                            Alignment Object Model




                                                   Essential Code to create Alignment from polyline on the site:

                                                   Dim   oAlignment As AeccAlignment
                                                   Dim   oAlignments As AeccAlignments
                                                   Dim   oSite As AeccSite
                                                   Dim   oSites As AeccSites

                                                   'Get Civil 3D application, document and database
                                                   '(see page 18, and source code for more details)
                                                   If Not Civil3DObtained() Then Exit Sub

                                                   'Get/create site, see getSite function in the Common.vb
                                                   of the dataset
                                                   oSite = getSite(sSiteName)

                                                   'Get the alignment collection for given site
                                                   oAlignments = oSite.Alignments
                                                   'Add an alignment to the site's alignment collection
                                                   oAlignment = oAlignments.AddFromPolyline(paremeters)
For the entire code refer to region Alignment in
the dataset C3DBasic. In addition to creating
alignment, in the same region you will find code   Essential Code to create siteless Alignment from polyline:
showing how to create alignment style and
                                                   Dim oAlignment As AeccAlignment
alignment labels style.                            Dim oAlignmentsSiteless As AeccAlignmentsSiteless
                                                   oAlignmentsSiteless = g_oCivil3DDoc.AlignmentsSiteless
                                                   oAlignment = _
                                                   oAlignmentsSiteless.AddFromPolyline(paremeters)




                                                                                                  23/25
Creating Civil 3D Profile And Profile View
User’s Interface                                                       Programmer’s Interface

                                                                            Profile Object Model




                                                 Essential Code to create Profile and Profile View

                                                 Dim oProfile As AeccProfile
                                                 Dim oProfiles As AeccProfiles
                                                 Dim oProfileView As AeccProfileView

                                                 'Get Civil 3D application, document and database
                                                 '(see page 18, and source code for more details)
                                                 If Not Civil3DObtained() Then Exit Sub

                                                 'Get the profile collection for the given alignment
                                                 'Remember, the alignment can be on site or siteless
                                                 oProfiles = oAlignment.Profiles


                                                 'Create the profile from surface
                                                 oProfile = oProfiles.AddFromSurface(parameters)

For the entire code refer to region Profile in   'Create the profile view for given profile
                                                 oProfileView = oAlignment.ProfileViews.Add(parameters)
the dataset C3DBasic.




                                                                                              24/25
Visual Studio 2008 and evolution
At this time, it is possible to download Visual Studio 2008 Beta 2. Here is an extract from the Microsoft
Developer Network (MSDN):

“Earlier this year Visual Studio celebrated its tenth anniversary. As we move towards releasing Visual
Studio 2008, let’s take a moment to reflect on the product's evolution.

The first release of Visual Studio in 1997 featured separate IDEs (that required their own installation) for
Visual C++, Visual Basic, J++, and a tool known as InterDev. Visual Studio 6.0 was a dramatic
improvement that marked the birth of Visual Basic 6 and embodied the idea of a set of unified services
across all languages.

With Visual Studio .NET 2002 and Visual Studio .NET 2003, this vision was realized with the .NET
Framework. For the first time an individual developer could write an application in the language of their
choosing while taking advantage of a common set of tools including designers, drag and drop controls,
and IntelliSense. Along with the increase of individual developer productivity was an increase in the size
and complexity of development projects and teams.

Visual Studio 2005 was born to help developers in teams of any size increase collaboration and reduce
development complexity. With each progressive release, Microsoft has reaffirmed its commitment to
empowering the developer by creating a dialogue with the community to help incorporate feedback and
improve the product. Visual Studio 2008 is no exception. With your help we are prepared to deliver on the
commitment to make every software project successful on the Microsoft platform.”
(Source: http://msdn2.microsoft.com/en-us/vstudio/aa700830.aspx)

You may also take a look at the following link:
http://www.velocityreviews.com/forums/t368827-difference-between-vb-2005-and-vbnet.html




                                                                                                       25/25

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:79
posted:4/22/2010
language:English
pages:26