Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Mastering UML with Rational Rose 2002.pdf
Скачиваний:
137
Добавлен:
02.05.2014
Размер:
9.68 Mб
Скачать

Chapter 15: Visual Basic Code Generation and Reverse Engineering

Private Function RemovePassenger(PassengerID As int) As boolean

End Function

'##ModelId=3A818EBF03B7

Public Function AddPassenger(PassengerID As int) As boolean

End Function

'##ModelId=3A818EC9007C

Public Function CancelFlight() As Boolean

End Function

'##ModelId=3A818F8303D7 Private Sub Class_Initialize()

End Sub

'##ModelId=3A818F84034C Private Sub Class_Terminate()

End Sub

Generated Code

In the following sections, we'll take a look at the Visual Basic code generated for a class, an attribute, an operation, and for the different types of relationships between classes. In each of these sections, we include some sample code to give you an idea of what will be generated from your Rose model.

Rose uses the information in the specifications of the model elements when generating code. For example, it will look at the different specifications for a class (visibility, attributes, operations, and so on) when generating code for the class.

Let's begin by looking at the code generated for a typical class.

Classes

A class in the Rose model will be implemented as a class in Visual Basic. The type of class that is generated depends on the stereotype you assign the class in Rose. The default Visual Basic stereotype is Class Module. Classes with this stereotype will be implemented as a class module in Visual Basic. In our example, we have a Flight class:

509

Chapter 15: Visual Basic Code Generation and Reverse Engineering

The following is the code generated for the Flight class:

Option Explicit

'##ModelId=395EA80B0088 Private FlightNumber As Integer

'##ModelId=395EA87C01A3 Private DepartureDate As Date

'##ModelId=395EA880036C

Private mDepartureCity As String

'##ModelId=395EA884028B

Private DestinationCity As String

'##ModelId=395EA88D0176

Public Function AddPassenger(PassengerID As Integer) As Boolean

End Function

'##ModelId=395EA8970383

Public Function RemovePassenger(PassengerID As Integer) As Boolean

End Function

'##ModelId=395EA8A1008E

Public Function CancelFlight() As Integer

End Function

'##ModelId=395EB1D202F5

Public Property Get DepartureCity() As String DepartureCity = mDepartureCity

End Property

'##ModelId=395EB2CA0201

Public Property Let DepartureCity(ByVal vNewValue As String)

mDepartureCity = vNewValue End Property

Notice that Rose generated all of the attributes, their data types, and their visibility; the operations with their parameters, data types, visibility, and return types; and the Get and Let operations for DepartureCity.

510

Chapter 15: Visual Basic Code Generation and Reverse Engineering

The Get and Let methods were created because we set the option to create them using the Model Assistant. While Rose generates just the method headers for any operations you've added, it will generate the actual code for Get and Let operations. This saves the programmers from the tedious task of generating and coding Get and Let operations for all of the attributes.

The Option Explicit line is included because the OptionExplicit class property for this class was set to True.

The ModelId lines were created to help synchronize Rose and Visual Basic during round−trip engineering. This feature allows you to change a method name, for example, in the Rose model or in the code, and still be able to synchronize the model with the code.

Warning Be careful not to change the ModelId numbers in the code.

Much of the information in your Rose model will be used directly when generating code. For example, the attributes, operations, relationships, and class name will directly affect the code generated for each class. Other model properties, such as the documentation entered for the class, will not directly affect the code. These properties are created as comments in the generated code.

Table 15.6 lists properties of a class, and notes which of these properties will directly affect the code generated.

The Flight class has a stereotype of Class Module. Let's look at what is generated for some of the other stereotypes. Note that while many different types of classes can be generated in Visual Basic, the Visual Basic add−in will not generate parameterized classes.

Table 15.6: Effect of Class Properties on Generated Code

Property

Effect on Code

Name

Name in model will become class name

Type

Directly affects the type of class created

Stereotype

Directly affects the type of module file created (Class Module, MDI Form,

 

etc.)

Export Control

Does not affect generation

Documentation

Generated as a comment

Cardinality

Does not affect generation

Space

Does not affect generation

Persistence

Does not affect Visual Basic code generation, but does affect whether DDL

 

can be generated for the class

Concurrency

Does not affect generation

Abstract

Does not affect generation

Formal Arguments

Formal arguments are included in the code for a parameterized class

Operations

Generated in code

Attributes

Generated in code

Relationships

Generated in code

511

Chapter 15: Visual Basic Code Generation and Reverse Engineering

Form

The Form stereotype will create a Visual Basic form. Attributes become properties of the form. Operations become methods of the form.

Rose can generate the default Visual Basic methods—such as the Initialize, Load, and Unload methods—for the form. To decide which methods to generate, open the Model Assistant for the class and select the appropriate method(s) on the left side of the window.

As you select these methods, you will be given the option to change the method visibility (public, friend, or private). You can check the Replace Existing Body check box so that when Rose generates the method, the code you've entered in the Default Body field will be generated:

Using the Template tab of the Model Assistant, you can set the following options:

512

Chapter 15: Visual Basic Code Generation and Reverse Engineering

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

MDI Form

The MDIForm stereotype will create a Visual Basic MDI form. Attributes become properties of the form. Operations become methods of the form.

As with a Form stereotype, Rose can generate many default methods in an MDI form class. Open the Model Assistant for the class and select the methods to generate. Then, enter the method visibility and the code to be generated for that method.

Using the Template tab of the Model Assistant, you can set the following options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

ADO Class

The ADOClass stereotype will create an ADO class in Visual Basic, which will exhibit some persistent behavior. Attributes of the class become properties of the ADO class. Operations become methods of the

513

Chapter 15: Visual Basic Code Generation and Reverse Engineering

ADO class.

In addition, Rose can generate the following properties. Use the Model Assistant to select the properties to generate.

BOF

ConnectionString

EOF

Recordset

mrs (generated by default)

Rose can generate a number of standard methods for the class, including the MoveFirst, MoveLast, MoveNext, MovePrevious, GetAll, and DeleteAll methods. Use the Model Assistant to select the operations to generate.

By default, Rose will generate the Query method, which creates and fills a recordset using a query passed in as a parameter.

The following code is an example of what is generated for an ADO class:

Option Explicit

'Private constant with database connection string. Default from 'template parameter ConnectionString (which defaults to an empty 'string).

'##ModelId=395EC4060255

514

Chapter 15: Visual Basic Code Generation and Reverse Engineering

Private Const ConnectionString As String = ""

'##ModelId=395EC406033B Private mrs As Recordset

'Public Property Get to get a reference to the private ADO 'Recordset (mrs).

'##ModelId=395EC40602A5

Public Property Get Recordset() As Recordset Set Recordset = mrs

End Property

'Private Function to return ADO Recordset from query sent as SQL 'string input parameter. Creates a Connection and a Recordset. 'Connects Recordset to the Connection, queries the database (with 'the SQL string) which fills the recordset with the result. 'Disconnects the Recordset from the Connection and closes the 'Connection. Returns the created, queried and filled Recordset. 'Uses the module level constant ConnectionString as connection 'string on connection. Uses client side cursors on Connection. '##ModelId=395EC40602E1

Private Function Query(ByVal SQL As String) As Recordset Dim aco As Connection

Dim ars As Recordset

' Create objects

Set aco = CreateObject("ADODB.Connection") Set ars = CreateObject("ADODB.Recordset")

'Open Connection aco.CursorLocation = adUseClient

aco.ConnectionString = ConnectionString aco.Open

'Open Recordset

ars.CursorType = adOpenKeyset ars.LockType = adLockBatchOptimistic ars.ActiveConnection = aco

ars.Open SQL

'Return Recordset Set Query = ars

'Disconnect Recordset from Connection Set ars.ActiveConnection = Nothing

'Close Connection

aco.Close End Function

As with other stereotypes, you can set certain code−generation properties using the Template tab of the Model assistant. For an ADO class, the following options are available:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

515

Chapter 15: Visual Basic Code Generation and Reverse Engineering

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

MTSEnabled determines whether or not the class is MTS aware. If this option is set to True, Rose can generate a CreateInstance method and a Get method for the ObjectContext property.

ConnectionString sets the database connection string to be used.

TableName sets the name of the table corresponding to the class.

PrimaryKeyFieldName sets the name of the primary key of the table corresponding to this class.

MTS Class

The MTS Class stereotype is used to model Microsoft Transaction Server (MTS) classes in Rose. Attributes you've defined in Rose become attributes of the class in Visual Basic. Operations you've defined in Rose become methods of the Visual Basic class.

By default, an MTS class is not ADO−enabled. However, you can change this setting by using the Model Assistant:

The following properties and methods are generated by default:

ObjectContext property, which is the current MTS ObjectContext object

516

Chapter 15: Visual Basic Code Generation and Reverse Engineering

CreateInstance, which creates a new instance of an object

SetAbort, which provides rollback functionality

SetComplete, which commits a transaction

The following is an example of the code generated for an MTS class:

Option Explicit

'Private Property Get to return the current ObjectContext object '(assigned to the object by MTS). If the object is not running in 'MTS, the returned value will be Nothing.

'##ModelId=395EC3EA0395

Private Property Get ObjectContext() As ObjectContext ' Return current ObjectContext

Set ObjectContext = GetObjectContext() End Property

'Private Function to create a new instance of another object 'specified as an input parameter (which is a ProgID string). 'This method handles the creation of objects both running in 'and outside of MTS. If there is an ObjectContext object for 'the current object − i.e. it is running in MTS −

'the CreateInstance method of the ObjectContext is called. 'If not, the CreateObject API is called. This is the only 'way you should use to make instances of new objects from 'the class.

'##ModelId=395EC3EA03D1

Private Function CreateInstance(ByVal ProgID As String) As Variant ' Create object (inside MTS or not)

If Not ObjectContext Is Nothing Then

Set CreateInstance = ObjectContext.CreateInstance(ProgID)

Else

Set CreateInstance = CreateObject(ProgID) End If

End Function

'Calls the ObjectContext SetAbort method (if running in MTS) for 'transactional Rollback behavior.

'##ModelId=395EC3EB002F Private Sub SetAbort()

' Set Abort status on current ObjectContext object If Not ObjectContext Is Nothing Then

ObjectContext.SetAbort End If

End Sub

'Calls the ObjectContext SetComplete method (if running in MTS) 'for transactional Commit behavior.

'##ModelId=395EC3EB0057 Private Sub SetComplete()

' Set Complete status on current ObjectContext object If Not ObjectContext Is Nothing Then

ObjectContext.SetComplete End If

End Sub

517

Chapter 15: Visual Basic Code Generation and Reverse Engineering

Using the Template tab of the Model Assistant, you can set the following code−generation options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

ADOEnabled determines whether or not the class is ADO aware. If this option is set to True, Rose can generate GetAll, GetNew, GetOne, Query, Save, and Update operations.

ConnectionString sets the database connection string to be used.

TableName sets the name of the table corresponding to the class.

PrimaryKeyFieldName sets the name of the primary key of the table corresponding to this class.

MTSTransactionMode sets the MTS support level (Not an MTS Object, No Transactions, Requires Transaction, Uses Transaction, or Requires New Transaction).

Module

A Module stereotype becomes a Visual Basic module. Attributes become properties of the module. Operations become methods of the module.

Using the Template tab of the Model Assistant, you can set the following:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

518

Chapter 15: Visual Basic Code Generation and Reverse Engineering

Collection

A Collection stereotype becomes a Visual Basic collection. Attributes become properties of the collection. Operations become methods of the collection. In addition, Rose generates the following methods by default:

Get Count, which returns the number of items in the collection. Rose will code this method for you

Get Item, which returns an item from the collection. Rose will code this method for you

Get Enum, which supports the enumeration of the collection for the For…Each syntax

Add, which adds a new item to the collection

Remove, which removes an item from the collection

Initialize method, which creates an instance of the class in memory

Terminate method, which does any "clean−up" work and removes an instance of the class from memory

You can determine which methods to generate by using the Model Assistant:

519

Chapter 15: Visual Basic Code Generation and Reverse Engineering

The following code is an example of what is created in Visual Basic for a class with a stereotype of Collection:

Option Explicit

'local variable to hold collection '##ModelId=395EC3EC0320

Private mCol As New Collection

'used when retrieving the number of elements in the 'collection. Syntax: Debug.Print x.Count '##ModelId=395EC3EB03BF

Public Property Get Count() As Long Count = mCol.Count

End Property

'used when referencing an element in the collection

'vntIndexKey contains either the Index or Key to the collection, 'this is why it is declared as a Variant

'Syntax: Set foo = x.Item(xyz) or Set foo = x.Item(5) '##ModelId=395EC3EC0009

Public Property Get Item(vntIndexKey As Variant) As Variant Set Item = mCol(vntIndexKey)

End Property

'this property allows you to enumerate 'this collection with the For...Each syntax '##ModelId=395EC3EC006D

Public Property Get NewEnum() As IUnknown Set NewEnum = mCol.[NewEnum]

End Property

'used when adding a new item to the collection 'syntax: x.Add ayz

'##ModelId=395EC3EC00A9

Public Sub Add(Item As Variant, Optional Key As Variant, Optional Before As Variant, Optional After As Variant)

If Len(Key) = 0 Then

520

Chapter 15: Visual Basic Code Generation and Reverse Engineering

mCol.Add Item

Else

mCol.Add Item, Key

End If

End Sub

'used when removing an element from the collection 'vntIndexKey contains either the Index or Key, which is why 'it is declared as a Variant

'Syntax: x.Remove(xyz) '##ModelId=395EC3EC018F

Public Sub Remove(vntIndexKey As Variant) mCol.Remove vntIndexKey

End Sub

'##ModelId=395EC3ED003C Private Sub Class_Initialize()

End Sub

'##ModelId=395EC3ED0078 Private Sub Class_Terminate()

End Sub

Using the Template tab of the Model Assistant, you can set the following options for the collection:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

CollectionOf defines the class of which the collection is a grouping.

Note When reverse engineering a collection, Rose will create a class with a stereotype of Class Module, not Collection.

User Control

The User Control stereotype will create a Visual Basic user control. Attributes become properties of the user control. Operations become methods of the user control. In addition to the operations you define in Rose, you can generate many default methods for the user control, including Click, Double−Click, KeyDown, Resize, and Show.

Using the Model Assistant, select the method(s) to be generated in Visual Basic for the user control.

521

Chapter 15: Visual Basic Code Generation and Reverse Engineering

On the Template tab, you can set the following options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

Property Page

The PropertyPage stereotype will create a Visual Basic property page. Attributes become properties of the page. Operations become methods of the page. As with many other stereotypes, Rose can generate default methods for you through the Model Assistant:

522

Chapter 15: Visual Basic Code Generation and Reverse Engineering

On the Template tab, you can set the following options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

Data Report

A DataReport−stereotyped class is generated as a Visual Basic data report. Any attributes of the class become properties of the data report. Any operations become methods in the data report. In addition, Rose can generate standard methods for you:

The following is an example of a data report generated from Rose:

523

Chapter 15: Visual Basic Code Generation and Reverse Engineering

On the Template tab of the Model Assistant, you can set the following options for the data report:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

Data Environment

A class with a stereotype of Data Environment will create a DataEnvironment class in Visual Basic. As with other stereotypes, attributes and operations are implemented as properties and methods of the generated class.

When generating a data environment, Rose will add a connection object to the generated class. You can then set up the connection, including the connection type (ODBC, etc.) and data source using Visual Basic.

Rose can also generate Initialize and Terminate methods for the data environment. Use the Model Assistant to set which operations to generate:

524

Chapter 15: Visual Basic Code Generation and Reverse Engineering

On the Template tab of the Model Assistant, you can set the following options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

The following is an example of the data environment created from Rose:

User Connection

The UserConnection stereotype will create a Visual Basic user connection. Attributes become properties of the connection. Operations become methods of the connection. You can set up Rose to generate default

525

Chapter 15: Visual Basic Code Generation and Reverse Engineering

methods through the Model Assistant:

On the Template tab of the Model Assistant, you can set the following options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

Once the user connection has been created, you can use Visual Basic to set the connection details, add queries, and complete the code for the connection.

User Document

A User Document stereotype becomes a Visual Basic user document. Attributes become properties of the user document. Operations become methods of the user document. The Model Assistant will enable you to set the default methods to be generated.

526

Chapter 15: Visual Basic Code Generation and Reverse Engineering

Using the Template tab of the Model Assistant, you can set the following:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

Note You cannot generate a user document that is assigned to a component with a Standard EXE stereotype. Map the user document to another component (ActiveX EXE, for example) before generating code.

Type and Enum

A Type or Enum class must be modeled as a class nested within another class. To do this, open the specification of the nesting class and select the Nested tab. Right−click in the whitespace to add a new nested class, and set the stereotype of the nested class to Type or Enum.

Once you have added the nested class, double−click it to open the nested class specification. Click the Attributes tab to add one or more attributes to the nested class before generating code.

The following is an example of a Type and Enum class generated from Rose:

Option Explicit

'##ModelId=39600F880341 Public Enum VBEnum

'##ModelId=3960106A01BF EnumAttribute = 4

End Enum

'##ModelId=39600FA10206 Public Type VBType

'##ModelId=3960107A0245

527

Chapter 15: Visual Basic Code Generation and Reverse Engineering

TypeAttribute As Boolean

End Type

Add−In Designer

The Add−In Designer stereotype will create a Visual Basic add−in designer. Attributes become properties of the designer, while operations become methods of the designer. You can set up Rose to generate default methods through the Model Assistant:

On the Template tab of the Model Assistant, you can set the following options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

ErrorHandling adds error−handling code to the methods of the class. The default setting is False.

Once the designer has been created, you can use Visual Basic to set the details. The following is an example of an add−in designer created from Rose:

528

Chapter 15: Visual Basic Code Generation and Reverse Engineering

DHTML Page

A class with a stereotype of DHTMLPage will be implemented as a DHTML page in Visual Basic. As with other stereotypes, attributes and operations of the class in Rose become properties and methods of the Visual Basic class.

Using the Model Assistant, you can select the methods to be generated in the code:

On the Template tab of the Model Assistant, you can set the following options:

DebugCode adds debug code to the Initialize and Terminate events. The default setting is False.

Comments adds "Your code goes here…" comments to the methods of the class. The default setting is False.

529