128

Scripting EA

Embed Size (px)

DESCRIPTION

Scripting enterprise architect

Citation preview

Page 1: Scripting EA
Page 2: Scripting EA

Scripting Enterprise ArchitectA guided tour to Enterprise Architect’s scriptingcapabilities

Thomas Kilian

This book is for sale at http://leanpub.com/ScriptingEA

This version was published on 2015-12-01

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight toolsand many iterations to get reader feedback, pivot until you have the right book and buildtraction once you do.

©2012 - 2015 Thomas Kilian

Page 3: Scripting EA

Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Copyright and Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.1 Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2. EA’s Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.1 Accessing EA from the Outside . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.3 Package – and View – and Model . . . . . . . . . . . . . . . . . . . . . . . . . . 72.4 Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.5 Connector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.6 Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.7 TaggedValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3. Creating New Things . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.1 Adding a Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.2 Adding a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.3 Adding a Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.4 Adding an Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.5 Adding a Connector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.6 Adding a Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.7 Adding Diagram Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.8 And the Opposite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

4. Advanced Creations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.1 Semi-manual Element Creation/Selection . . . . . . . . . . . . . . . . . . . . . 324.2 Adding a Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334.3 Create Connector for Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . 364.4 Nasty Things . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.5 More Undocumented Stuff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.6 Creating Things from a MDG . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

5. Object Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.1 EaRepository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.2 EaPackage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555.3 EaElement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Page 4: Scripting EA

CONTENTS

5.4 EaAttribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685.5 EaMethod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715.6 EaParameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735.7 EaConnector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745.8 EaDiagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795.9 EaDiagramObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825.10 EaDiagramLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835.11 EaTaggedValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835.12 EaRequirement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865.13 EaConstraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875.14 EaScenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885.15 EaScenarioStep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885.16 EaScenarioExtension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895.17 EaCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905.18 EaKeyValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915.19 Missing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

6. Bits and Pieces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936.1 Ordering of Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936.2 GUID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936.3 Diagram Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936.4 Object Type Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946.5 Element Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946.6 Element Subtypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956.7 RGB Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966.8 Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966.9 Semi-colon Separated List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966.10 Connector StateFlags Property . . . . . . . . . . . . . . . . . . . . . . . . . . . 976.11 Width of Connectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976.12 Diagram Object Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976.13 Connector Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986.14 Run State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986.15 Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 996.16 Enumeration Relation Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 996.17 XML Result String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

7. GUI Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007.1 Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007.2 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1057.3 Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1077.4 Connector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1097.5 Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1137.6 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

8. Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1208.1 Feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1208.2 Inside Enterprise Architect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

Page 5: Scripting EA

CONTENTS

8.3 Sparx Forum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1208.4 Sparx Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1218.5 Geert Bellekens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Page 6: Scripting EA

PrefaceEnterprise Architect¹ (EA) offers a wealth of API functions to support automated manipulationof UML models. For the beginner it is not easy to find a start. It is the intention of this book tohelp you getting a quick and smooth start

The contents of this book is the essence of a continuous work with EA since end 2003. Almostfrom the beginning on I have been playing with EA’s automation. I have fallen into quite somepitfalls. With this book I hope to prevent newcomers from falling into the same pits again.

This book starts with a short introduction that takes you to reasons for scripting. The followingsection about EA’s object model introduces the most important EA objects along with theirattributes. The section about element creation andmanipulation covers basic and a few advancedexamples on how to populate a model with elements. The next section details the previouslyintroduced objects. Attributes and operations are explained with references to GUI screenshotswhere applicable. Bits and pieces as an internal reference section details a couple of attributes.The final section shows screen-shots of many EA dialogues along with a back reference to wherethe single attributes are to be found in the API. So the circle is closed and you can see how GUIand API relate to each other.

I wish you will have fun when learning EA’s API and as much success as I had so far. If you findany errors or you think that something needs to be explained differently just drop me a note².

¹The EA version used to create this book was actually 9.3 (build 930). This book’s version reflects changes from 10.0 (build 1006) and changesfrom 11.0 (build 1103) are currently being integrated. However, most of the references are also valid for earlier versions of EA.

²[email protected]

Page 7: Scripting EA

Copyright and DisclaimerAlso all of the information in this book has been tested by me in many circumstances I can nothold any liability for use of the here presented information³. However, I’d be glad to receive anykind of feedback to correct future updates of this book which you will receive for free in turn.Having said this, all information presented here is subject to change without notice.

The names of actual companies and products mentioned herein may be the trademarks of theirrespective owners.

Important note: Before going into production with your scripts follow these steps.

• Test with a dummy repository• Test with a copy of the production repository• Backup the production (initially and regularly later)• Run and carefully observe on production• If you are doing some conversion task also have a ‘reverse script’ that helps you undocertain steps.

³I really loathe writing such legal blurb since it should be obvious. By the way: German law applies! (Does that change anything?)

Page 8: Scripting EA

1. IntroductionLet me start with a

Question: What’s the best part of EA?Answer: You can script it!

Of course you find a lot of other pros¹, but scripting is definitely the most prominent advantageyou will find in EA. Now you might ask the

Question: Why should I use scripting?Answer: Because you often have repetitive work you want to automate.

That’s a simple answer and probably too simplistic. The following list shows some major tasksyou can tackle with scripting:

• Regular repetitive task: Repetitive would also mean you have to repeat a couple of stepfive to ten times. If that’s it you would probably not start coding a script. But for taskswhich you can foresee to use regularly and which involve say a minimum of 5 steps youmust consider writing a script.

• Importing Data: If the build-in CSV import of EA is not sufficient you have the choicebetween manual import and a script. If it’s only a couple of lines you should take themanual path. But if either the file is larger or you have to do the import on a regular basisyou have no other choice than scripting.

• Consistency checks: Whenever you need to implement complex modeling rules it isnecessary to cross check the model from time to time. A manual approach will certainlyfail as the model complexity soon reaches the limits you can handle manually. So it is agood advice to script your own model checker.

• Code generation: EA has a build-in scripting for code generation. If you have only minorrequirements for code generation you can live with that. But when it’s going to be morecomplex this scripting language soon becomes too restrictive. Doing the same task withyour preferred language will make things much easier.

• Conversion of data: Sometimes you need to change class names, add tagged values ormove elements according to changed modeling rules. A manual conversion often is notfeasible. That’s why you will need scripting.

• Fancy things: Changing the behavior of the tool can support your modeling tasks a lot.Assume that you need to restrict the creation of elements depending on the model context.Or you need to set tagged values in several elements at once when you create, update ordelete an element. In such cases you will find scripting a real benefit!

¹I will not conceal various cons of the product. But with most of them you can live. Just take them as a challenge.

Page 9: Scripting EA

Introduction 2

You see: there are quite a number of reasons why you should consider using scripting in EA. Butthat brings us to the next

Question: Which language shall/can I use?Answer: The one you are familiar with!

Of course the real answer it not that simple, but quite. EA has a build-in scripting machine whichlets you write JScript and Visual Basic. The nice thing here is that you can write scripts on-the-fly.

Before V10 debugging is only possible via print statements. And finding compilationerrors can be a nightmare².

If you are not familiar with these languages and you prefer another one (e.g. Python, Perl, Cxxor whatever) you can do this as well. The only thing you need to find out is how to access theEA object where you can send API messages. You then can use the IDE of your choice to debugyour application.

I can not go into details specific to any IDE or language³. For that reason I will not give languagespecific coding examples but abstract code sequences you need to adapt to the language of yourchoice. The advantage is that you need to think a lot more about what you are doing rather thantaking ready-to-run samples. So in the end you learn more and faster!

1.1 Notation

As the different languages use different syntax I will use the most common dot-notation withC-like syntax elements with curly brackets. As a Visual Basic scripter you need to know that

1 for (<init>; <cond>; <post>) { <statements> }

translates to VB-like

1 <init>

2 while (<cond>) then

3 <statements>

4 <post>

5 wend

The dot-notation is similar for most other languages (Perl and C++ use -> instead of the dot).

²I have not tested the new debugger but what I have seen from a Sparx demo looked promising.³Actually I had chosen Perl as scripting language for myself. Together with the Komodo IDE debugging was real fun. Additionally I had

build a framework to run Perl scripts as add-in from within EA. You can find more information here: http://community.sparxsystems.com/resources/scripts/extending-ea-perl

Page 10: Scripting EA

Introduction 3

Object.attribute

denotes the public attribute of Object.

Object.method(<parms>)

likewise represents the method call methodwith parameters <parms>where the latter is a commaseparated list of object⁴/name-tuples.

More specifically I will use the following notation⁵:

Primitive = ‘bool’ | ‘short’ | ‘long’ | ‘string’;CamelCase = “type-writer string starting with upper case and no spaces”;EAobject = ‘Ea’ CamelCase; (* e.g. EaElement or EaPackage *)Object = ‘Object’ | ‘ActiveX’ | ‘DateTime’ | EAobject;TypeDefinition = Primitive | Object; (* declare attribute type/method result *)VoidTypeDefinition = ‘void’ (* methods declared as void don’t return a value *)| TypeDefinition;Attribute = TypeDefinition ‘ ‘ CamelCase; (* e.g. long ObjectID *)Method = VoidTypeDefinition ‘ ‘ CamelCase ( ParameterList );ParameterList = [Attribute {‘,’ Attribute}]; (* optional comma-separated list *)

For better distinguishability all EA provided objects are prefixed with Ea. In your preferredlanguage you will probably use these names without the prefix or in a dot-format (e.g.EA.Element instead of EaElement).

Further this document makes frequent use of hyper-links taking you to other locations in thisdocument where the according term is defined in more detail.

⁴Actually in most cases a primitive like short or long is supplied.⁵Basically I denote this using EBNF. If you don’t knowwhat this is good for, just skip this information. You will be able to read this document

without it.

Page 11: Scripting EA

2. EA’s Object ModelEA’s object model is quite complex. This book will not¹ cover all the gory details of EA’s API butit will just give you the point from where to start. You should consult the offline help inside EAvia

Help/Help Contents/Contents/Automation/Enterprise Architect Object Model/Reference

There is also an online help page with almost the same contents. But why use network capacity ifyou already have it on yourmachine? The structure is simple if you follow the InterfaceOverviewdirectory or you skip the Enumerations directory. Inside the Repository directory you find theRepository class some way down. We will start with this one in the next section. The Packageclass is found in the same directory in the middle. Likewise you find the Element Class in theElement directory below the Repository directory.More about that later. All the class descriptionsare in tabular format with the attributes listed first. Operations are found further down in asimilar table. Most of this tabular documentation you can find in the Object Details chapter withadditional comments. You will likely need to reference the EA help only for rarely used areaswhich are not detailed in this book.

This section will not go into details of the operations provided by the single classes unless needed.Instead we concentrate on the attributes to get a grip of EA’s repository structure.

In the following examples I simply assume you have the Example EA Model open. Probably youshould have a copy of that as we might clobber it with our experiments.

But let’s start with the basics. The EA runtime object represents a single repository. Once you gothold of this you can create, read, update and delete everything inside the repository. Furthermoreyou can access a couple of complex operations (like exporting packages as XML) from therepository object.

Now, how can you access this magic object? If you are using the build-in scripting engine thenEA offers the predefined object Repository. You can use that without any declaration in any

¹Quite a number of secrets/hidden features are already explained in this book. As it is in the state of being written it is not complete andthus misses still some information. Over time this gap shall be closed so you can use this book not only for learning but also as a reference forthe advanced use of EA.

Page 12: Scripting EA

EA’s Object Model 5

context. That’s really simple and lets jump start you scripting immediately. Just skip the nextchapter if that’s what you want to do.

2.1 Accessing EA from the Outside

So you need to develop your scripts outside EA. This means you need to get hold of the runningEA application or you need to create one. Note that accessing a running EA instance will onlyget hold of the first one launched. I will not discuss the various possibilities including creatingan instance here. You will likely be able to find that out later when it is getting important.

Here are some samples how to get the currently running EA instance from outside EA. The codesnippets do not contain any validity checks. That means, when you run it without an active EAinstance, it will loudly crash.

Eventually you need to link EA’s TLB to your IDE. This is to let it know about EA’s API classes,unless you deal with EA’s API objects as anonymous. The examples in this book do the latter asthe declaration varies between the different languages. If you require object declaration it willgenerally be something like EA.Repository to declare the repository object or EA.Package for apackage object and so on.

C++

1 CLSID clsid;

2 CLSIDFromProgID(L"EA.App", &clsid);

3 IUnknown *pUnk = NULL;

4 IDispatch *pDisp = NULL;

5 HRESULT hr = GetActiveObject(clsid, NULL, (IUnknown**)&pUnk);

6 if(SUCCEEDED(hr)) {

7 hr = pUnk->QueryInterface(IID_IDispatch, (void **)&pDisp);

8 }

These lines were borrowed from a Microsoft page. So I hope it will not be too misleading as Inever have written a single line in C++.

Perl

1 $App = Win32::OLE->GetActiveObject ("EA.App");

2 $Repository = $App->Repository;

Python

Page 13: Scripting EA

EA’s Object Model 6

1 eaApp = win32com.client.Dispatch("EA.App")

2 eaRep = eaApp.Repository

Visual Basic

1 Dim Repository As EA.repository

2 Set EAapp = GetObject(, "EA.App")

3 Set Repository = EAapp.repository

Java

Unfortunately there is nothing equivalent. You need to code it in another language.

2.2 Repository

Now as you got hold of the repository object you can start exploring it a bit.

Let’s print the name of the repository.

print Repository.ConnectionString;

This will output either the file path and name of the EAP

e.g. C:\Documents and Settings\<user>\Desktop\EAExample.eap

or the ODBC connection string depending on the type of repository you are actually using. Nowlet’s take a first look into the repository.

On top level of a repository there is at least a single root node. It is possible to have multiple rootsso this is a Collection. The visible part of the repository we are going to explore first looks like:

EAExample.EAP repository structure

Lets simply retrieve and print the name of the (first and currently only) root package:

Page 14: Scripting EA

EA’s Object Model 7

1 root = Repository.Models.GetAt (0);

2 print root.Name;

This will print the name of the root package Project Models which was created at first² in therepository. You can iterate through all root nodes and print their names. For the example modelthere’s only a single root node. So create a second root on your own and try the iteration.

That’s all you need to know for the beginning. From here the fun begins!

2.3 Package – and View – and Model

Okay, that sounds confusing. But it’s only history. Packages, views and models are almost thesame. They are all packages. Almost. And to make it a bit more confusing: packages are a tupleof package and element.

Actually when you accessed above Models’ first object this did yield an EaPackage object. Forthe root package this is a sole EaPackage object. Most attributes of this top level package are notused since EA restrains this special package a lot. You will also find that the ParentID propertyis zero. This information can be used to find out that a package is a root package. Alternativelyyou may use the IsModel property which yields the same information as boolean value.

Besides its Name a package has a Packages collection like the Repository has Models.

1 view = root.Packages.GetAt (1);

2 print view.Name;

3 print view.Flags;

This prints the name of the second view Modeling Basics in the model (see following picture).

‘Modeling Basics’ and ‘Line Style’ Packages

In the Flags attribute you will find a semi-colon separated list isModel=1;VICON=1;. This tellsyou that the package is actually a view and it’s icon (which you see as different from a regularpackage) corresponds to the values 0..5 according to the Set View Icon from the context menu.

²You should refer to the Ordering section once you are familiar with the details.

Page 15: Scripting EA

EA’s Object Model 8

View Icon

For all views you iterate from the root object you find that their ParentID property is the same.Lets find out where this ParentID leads us:

1 root2 = Repository.GetPackageByID (view.ParentID);

2 print root2.Name;

Correct! It points back to the root package. And by the way you learned that

EaPackage Repository.GetPackageByID(long PackageID)

returns a EaPackage object. The PackageID itself is the primary key for each package class. It isunique per model³.

Let’s go one level deeper.

1 package = view.Packages.GetAt (0);

2 print package.Name;

Now we reached the package Line Styles (see picture above). We will inspect the contents ofthis package in the following sections.

If you are curious you can print out a couple of the attributes for the chosen package Line

Style. However, you will not see any useful information related to package/version control. Ifyou are interested just configure the package as controlled and see what properties change inwhat way.

Package Element

So far we have learned about the EaPackage object as being used for structuring a repository. Buteach package (except the root) has also a corresponding EaElement. Probably the reason for thisconstruct is to have an element (with an ElementID) that can be used to construct connectors.This makes packages quite ambivalent. A sort of Dr. Jekyll and Mr. Hyde.

Here is a list of ambiguous properties which appear in both EaPackage and EaElement:

• Alias: r/o in the EaPackage but if you need to alter it you must use the EaElement.

³If you want to learn more about the underlying data model you should have a look into my book Inside EA.

Page 16: Scripting EA

EA’s Object Model 9

• Connectors: Can be changed in either object.• Created: ditto• Modified: ditto• Name: ditto• Notes: ditto• Version: ditto• Stereotype: r/o in the EaPackage but if you need to alter it you must use the EaElement.

Though the help states that Created and Modified are r/w they actually are not! EAwillnot save any changes to those properties on an Update(). Created remains unchangedand Modified will in any case be set to the time of the Update() call. You will need tobypass the API in order to modify these values (see my [Inside]{#inside} book aboutmethods to do that).

If you need the EaTaggedValues you need to go through the EaElement. It is also possible tocreate attributes and operations for EaPackages via automation. But in that case you end upwith one of Mr. Frankenstein’s creatures.

Now, what do you think would be the back link from this element to its package? Well, it is not(!) the PackageID property value. Assume you have retrieved the Line Styles package elementin package_element shown in above picture. If you issue

1 package = Repository.GetPackageByID (package_element.PackageID);

then package will be Modeling Basics (which is likely not what you would expect). To actuallyget the corresponding package element you can go two ways⁴. The recommended way is usingthe GUID which is the same for the Package and the Package Element:

1 package = Repository.GetPackageByGUIID (package_element.ElementGuid);

The seconds way would be to use

1 package = Repository.GetPackageByID (package_element.MiscData(0));

Actually that would need some casting from string to integer and MiscData is not available insome scripting languages (which would force you to do some even more ugly stuff).

2.4 Element

Having understood the structure of packages we are ready for the next challenge: EaElement.Lets simply retrieve the first element from our current package.

⁴Only Sparx knows why. The first alternative is the easier one but has been revealed later in time.

Page 17: Scripting EA

EA’s Object Model 10

1 element = package.Elements.GetAt (0);

2 print element.Name;

You might be astonished that you got Artifact1 (see picture above) printed. Just stop wonderingfor a moment or read the section about ordering.

If you recall the picture of the project browser above you can identify elements as ‘singularityicons’ like the one for Class1. Diagram icons have ‘multiplicity’ and packages are the usualsuspects. But there are also elements you do not see in the browser: i.e. Boundary, Note, Fork/Joinand Text. You can not see them but they are there. EA creates such elements under the sameconstruct as the diagrams they are first placed in.

If you iterate the elements in the package Line Styles you will also find some of the abovementioned invisible elements.

For the curios ones: try to print a couple of the details for each element.

EaElement objects do have a couple of complex attributes. Namely the important ones are

• Attributes and Operations: Most elements can have (class) attributes and operations likeshown in the following picture. The element Account can be found with the

GUID {A423D28F-63D2-48c2-80B9-18B1930DD467}

Attributes and Operations

• EmbeddedElement: Any elements which are moved into other elements like the in thefollowing picture. You can retrieve the use case element Close Account via

Repository.GetElementByGUID ('{06B5CFF7-6C2C-46cf-B310-14F2BE77D296}')

from the example model. When you look into its EmbeddedElements property you will finda couple of elements.

Actually the EmbeddedElements return a subset of the elements you will get via theElements collection. The ones you will eventually get are indicated in the element types.

Page 18: Scripting EA

EA’s Object Model 11

Embedded Elements

• Diagrams: Likewise diagrams can be ordered underneath an element. If you inspectDiagrams for above Close Account element you will find two diagrams.

Attributes

The EaAttribute retrieved from an EaElement.Attributes EaCollection stores name, type anda couple of other attributes. If you run the following code

1 guid = '{A423D28F-63D2-48c2-80B9-18B1930DD467}';

2 elem2 = Repository.GetElementByGUID (guid);

3 for (i = 0; i < elem2.Attributes.Count; i++) {

4 attr = elem2.Attributes.GetAt (i);

5 print attr.Name;

6 print attr.Type;

7 }

it will print 5 attributes with types String or Boolean. The other details are not too difficult tounderstand. A discussion of the tagged values follows later.

Operations

EA is mixing (I guess for historical reasons) operations and methods. The EaMethod

object actually describes a UML operation. And the UML method is the attributeEaMethod.Behavior. Strange enough, the database got it right and the table is calledt_operation.

Similarly to attributes the EaMethod objects can be retrieved from EaElement.Methods. But theyare a bit more complex. Once you listed the six operations of above mentioned class Account

Page 19: Scripting EA

EA’s Object Model 12

1 for (i = 0; i < elem2.Methods.Count; i++) {

2 meth = elem2.Methods.GetAt (i);

3 print meth.Name;

4 print meth.ReturnType;

5 }

you can inspect the details. Likely the parameters of operations are of common interest, so wewill look into these next. The tagged values for operations follow later.

Parameters

Luckily the parameters are the final destination when diving into EaElement. Lets simply grabthe one operation with parameters out of above Account class:

1 guid = '{F5B78EAB-8840-4612-BF9A-FFF8D6071C34}';

2 meth = Repository.GetMethodByGUID (guid);

3 for (i = 0; i < meth.Parameters.Count; i++) {

4 param = elem.Parameters.GetAt (i);

5 print param.Name;

6 print param.Type;

7 }

This will print the two parameters. Again the tagged values are discussed later like the detailsfor EaParameter.

2.5 Connector

EaConnectors always connect EaElements. That means if you connect something with a packageyou need to use the Package Element. So the rest is no real wizardry. Let’s find out whichconnections are present for the Artifact1 element we selected last:

1 con = element.Connectors.GetAt (0);

2 print con.Type;

3 print con.Direction;

This will print Association and Undirected. If you inspect the Relationship Window forArtifact1 you actually find two of those connectors. So let’s try to find out which connector wefound and to which element Artifact1 connects through it:

1 client = Repository.GetElementByID (con.ClientID);

2 print client.Name;

Page 20: Scripting EA

EA’s Object Model 13

This will print Artifact2 and actually you can identify this association in the RelationshipsWindow as the first being listed (see following picture). You can iterate through all connectorsto find out which other clients are connected to Artifact1.

Connector in Diagram and Relationship Window

If you just have a connector you can inspect SupplierID to find out from where the connectorstarts. For the recently retrieved connector(s) you will find out that they start at Artifact1(because the ElementID of Artifact1 equals SupplierID of the connector).

There is not too much noteworthy about connectors here. Most of its attributes apply to all kindsof connectors. However, there are sequence messages, state transitions and information flowswhich have a couple of proprietary attributes.

If you ever encountered connectors connecting attributes: they actually are connectorsbetween the containing elements for the attributes. The fact that those connectorsappear to be connected to attributes/operations is coded in the StyleEx attribute ofthe connector. See the details in my book Inside EA.

Unlike elements, connectors don’t have a modification or creation time stamp. If youneed to get that information you have to turn on auditing and foster the audit log.

2.6 Diagram

The Diagram object is just the container for DiagramObjects. It is what you see in the projectbrowser. Let us retrieve a diagram from where we are in the Line Style package:

1 dia = package.Diagrams.GetAt (0);

2 print dia.Name;

3 print dia.Author;

Page 21: Scripting EA

EA’s Object Model 14

This will print the name Line Style (see picture above) and Pat Taylor as author. Just open thediagram properties and you will see that these values are also shown.

Let’s just stick with this simple view of diagram and skip the details to see the real contents ofeach diagram in the following section.

DiagramObject

A DiagramObject is an instance of an element in a diagram, and includes size and displaycharacteristics. So lets have a look at one of those instance elements.

1 dia_obj = diagram.DiagramObjects.GetAt (0);

2 elem_instance = Repository.GetElementByID (dia_obj.ElementID);

3 print elem_instance.Name;

4 print dia_obj.left;

5 print dia_obj.right;

This will print Class1 as the name of the element and its left and right coordinates 36 and 126in the diagram (see the highlighted class in the picture below). If you inspect the Line Style

diagram you see this element at top left (36 pixels from the left boundary and stretching topixel 126). Just print a few more details of each DiagramObject to see how simple each Diagram

represents single EaElement objects.

Diagram Object and Link

DiagramLink

Like DiagramObject these links are instances of EaConnector objects.

Just lets pick the first connector we get hold of in Line Styles:

Page 22: Scripting EA

EA’s Object Model 15

1 dia_link = diagram.DiagramLinks.GetAt (0);

2 con_instance = Repository.GetConnectorByID (dia_link.ConnectorID);

3 client = Repository.GetElementByID (con_instance.ClientID);

4 supplier = Repository.GetElementByID (con_instance.SupplierID);

5 print client.Name;

6 print supplier.Name;

7 print con_instance.Geometry;

This will print Class1, Class2 and the semi-colon separated list

SX=39;SY=1;EX=39;EY=1;EDGE=2;$LLB=;LLT=;LMT=;LMB=;LRT=;LRB=;IRHS=;ILHS=;

Actually this is the auto routing association from Class1 to Class2 you find in the top left partof the Line Styles diagram (see the highlighted connector in the picture above). For the timebeing you can ignore all the details in the Geometry and all the other attributes.

EA help: A DiagramLink is only created once a user modifies a connector in a diagramin some way. Until this condition has been met, default values are used and theDiagramLink is not in use.

This is not completely true. Once you manually place two connected elements on adiagram EA will create a DiagramLink object for each connector showing up. Onlywhen you create diagram objects via automation the link is not created and EA rendersa default appearance for the connector.

2.7 TaggedValue

Tagged values are used to adorn various EA elements with additional information. Basically atag has a name and a value and/or a memo.

Locate the class ejb-jar below and run the following code.

ejb-jar Class Definition

Page 23: Scripting EA

EA’s Object Model 16

1 guid = '{CDE8A0BB-512C-4709-9A87-B34C8DD5E2FF}';

2 elem = Repository.GetElementByGUID (guid);

3 for (i = 0; i < elem.TaggedValues.Count; i++) {

4 tag = elem.TaggedValues.GetAt (i);

5 print tag.Name;

6 print tag.Value;

7 }

This should print the tags and their values like being present in the repository:

ejb-jar Tags Definition

Remember that if you want to retrieve tagged values for a package you need to get the packageelement first. If you like you can try out with the package having the

GUID {84134A2A-18F5-4528-817C-051A0D45A2EE}.

This should print you 13 different tags. You are also encouraged to inspect further details of theEaTaggedValue object.

Let’s go on with tagged values for attributes. Though the GUI shows both in the same window inthe same way the internal representation is based on different objects⁵. For example let us lookat the attribute billingaddress:

billingaddress Attribute Definition

If you run the following code

⁵Actually tagged values are stored in different tables with quite similar formats. More about this in my book Inside EA.

Page 24: Scripting EA

EA’s Object Model 17

1 guid = '{70413628-3FC7-49d8-9BAF-54000B8C8463}';

2 attr = Repository.GetAttributeByGUID (guid);

3 for (i = 0; i < attr.TaggedValues.Count; i++) {

4 tag = attr.TaggedValues.GetAt (i);

5 print tag.Name;

6 print tag.Value;

7 }

you should see the two tagged values defined for that attribute. Check the details in the accordingAttributes section.

For operations the procedure is similar. Locate the loadAccountDetails() operation in theAccount class shown above. Its GUID is {F3FA096D-03D3-40c6-B569-49CB63990AB3}. Printingthe tag (named ea_guid) should be straight forward. Like before the details are found in theOperations section.

We’re not done yet. Three more tagged value variants to come. I will not go into any more detailsas you should now be able to deal with those. Again the details are to be found in the Connector,Role and Parameter sections. Here are some GUIDs to test with:

Connector:{0C52B4EA-4043-4c9f-8ED7-823D745099E3} For this connector you will find a single tagnamed operation_guid. Actually this connector is the sequence message retrieveAc-

countDetails() in the sequence diagram below the use case View Account details.

Operation:{488B75B5-0DB0-4359-B559-E9576E1CEE30}Thiswill print you two different tags (soapActionand style). You can find the operation GetSampleSOAP in the SampleBindingSOAP class.

Role:{93E1880E-7ABB-43ab-AF34-4291439F8F15} You need to pick the EaConnector with thisGUID and its ClientEnd property. For that you will find a single tagged value namedposition.

Page 25: Scripting EA

3. Creating New ThingsManipulating the repository via automation is the real reason for using the API. A mainapplication is the import of mass data. But again, lets start from the top.

Everything that is added to the repository is created via

1 newThing = EaCollection.AddNew ("name", "type");

2 newThing.Update();

where the name is always the name of the new element and type has different meaning dependingon the thing we want to add. Although some AddNew operations do not use the type parameteryou must supply it (with an empty string). Common to all AddNew is that they return either thesuccessfully created new element or a null pointer.

You already know about different EaCollection attributes (e.g. Models, Packages, Elements,etc.). These determine what is added and what the type parameter means. Further these objectscontain a unique number ObjectType (according to above examples 6 for Models, 5 for Packages,4 for Elements, etc.) so you can find out from what class they were created.

For the following code samples I assume that variables contain the value they were onceinitialized with. Unlike in the previous section I can not refer to any GUID as they will bearbitrary for the model you are using.

3.1 Adding a Root

Assuming you have the EAExample.eap as a copy we can simply go on adding a new root here.You are also free to create an empty .EAP.

Just run the following code on your model:

1 root2 = Repository.Models.AddNew ("A New Root", "");

2 root2.Update ();

3 Repository.Models.Refresh ();

You will find a new root with the name A New Root in your repository. The second parameterfor the AddNew is not used, so an empty string is passed.

Now run the script the with the name a new root (the first lower case character is important).As you will notice the first root is added at the very top while the second is below the previouslyexisting root¹. It should look like the following picture.

¹Actually I haven’t tested this with a case insensitive repository. It might turn out that those behave different.

Page 26: Scripting EA

Creating New Things 19

Two New Roots

The reason is simply that EA sorts these elements alphabetically unless a TreePos attribute issupplied. If you need to order the new root elements differently you have to supply the rightTreePos attributes. Delete the two newly created roots and run the following code snippet:

1 root1 = Repository.Models.GetAt (0);

2 root1.TreePos = 1;

3 root1.Update();

4 root2 = Repository.Models.AddNew ("a new root", "");

5 root2.TreePos = 0;

6 root2.Update ();

7 Repository.Models.Refresh ();

8 Repository.RefreshModelView (0);

While the Refresh simply updates the repositories’ Models collection to reflect the new countand contents, the final RefreshModelView will update the browser view so that you should seethe picture below. This is necessary as the sort order is changed which is not directly reflectedby EA. If you don’t invoke that you will not see the correct ordering of the root packages. Unlessyou care for the correct ordering to take immediate effect you usually can simply omit this call.

Ordered New Roots

A funny thing is when you try to add a root package with an empty name string. This is passedto the database where you get a message from the underlying database. Well…

3.2 Adding a View

Similarly to adding a root it is possible to add a new view. Remember that the following codesnippet assumes root1 to contain the newly created root package. Unless you run both codesnippet directly after each other in a common script you need to retrieve the according elementvia

Repository.GetPackageByGUID(guid);

where guid is the string you retrieved via the context menu Copy Reference/Copy Node GUID

to Clipboard....

Alternatively you can use Repository.GetPackageByName(<name>); where <name>

is the appropriate name of the package you are looking for. However, theGetPackageByName has a major drawback as it will deliver an arbitrary package with<name> as package names must not be unique. The Get...ByName also exists for severalother EA objects, but its use is not recommended for the very same reason.

Page 27: Scripting EA

Creating New Things 20

1 view = root1.Packages.AddNew ("A New View", "");

2 view.Flags = 'VICON=4;';

3 view.Update ();

4 root1.Packages.Refresh ();

5 Repository.RefreshModelView (root1.PackageID);

Again, the type parameter is not used. As we create a view (which is a special EaPackage) theview icon must be set. This is done via the Flags attribute. You can set this to any value in therange 0..5 corresponding to the view icon. The final RefreshModelView is a must.

New Package

If you don’t issue this call you will see the views as simple icon packages!

For the ordering the same applies as for above root packages.

3.3 Adding a Package

Adding a package is similar to adding a view, but simpler.

1 package = view.Packages.AddNew ("New Package", "");

2 package.Update ();

3 package.Packages.Refresh ();

4 Repository.RefreshModelView (view.PackageID);

This will result in the following:

New Package

You must not set any view icons, so the Flags remain unchanged.

The value for the Flags is stored even for non-view packages. However, you shouldnot set these for ordinary packages as it might confuse EA.

The ordering is maintained as for root and view packages. Any sub-packages can be addedrecursively.

If you need to set the stereotype of a package it is necessary to do the following.

Page 28: Scripting EA

Creating New Things 21

1 package = view.Packages.AddNew ("New Package", "");

2 package.Update ();

3 package.Element.Stereotype = "stereo";

4 package.Update ();

It is important to call the first Update since it will create the package element. Only thiscan store the stereotype. The one from the package itself is a r/o copy of the element.

3.4 Adding an Element

Adding elements is a bit more complex as we need the type parameter for the first time. Let’sstart adding a class element to a package we have added before.

The GUI prohibits you from creating elements at top level (I guess for historical reasonsas is does not really make sense). Unlike that, the API allows to create elements at rootlevel. However, if you once move those elements into a view you can not move it backto the root level, except for using the API.

1 element = package.Elements.AddNew ("New Class", "Class");

2 element.Update ();

3 package.Elements.Refresh ();

4 Repository.RefreshModelView (package.PackageID);

This adds the class New Class to the package which was created/select beforehand. The type

was set here to Classwhich told EA to actually create a Class element. The valid values are anyof the element type string properties.

New Element

Adding Attributes and Operations

This is pretty much straight forward. The following code snippet will create two attributes anda operation (assuming you can supply a class classifier via its GUID):

Page 29: Scripting EA

Creating New Things 22

1 attribute = element.Attributes.AddNew ("New Attribute", "simple type");

2 attribute.Update();

3

4 classifier = Repository.GetElementByGUID (guid);

5 attribute =

6 element.Attributes.AddNew ("New Classified Attribute", classifier.name);

7 attribute.ClassifierID = classifier.ElementID;

8 attribute.Update();

9

10 method = element.Methods.AddNew ("New Method", "simple return type");

11 method.Update ();

12

13 parameter = method.Parameters.AddNew ("New Parameter", "simple type");

14 parameter->Update();

15 method.Parameters.Refresh();

16

17 Repository.RefreshModelView (package.PackageID);

The first parameter of the Attribute.AddNew takes the name, while the secondwill be transferredto the simple type. If you need a classifier instead of a simple type this is done by supplying theClassifierID with the element’s ElementID. The type name must not necessarily be the same asthat of the classifier.

New Attributes

Adding operations is similar. The second parameter is used for the return type of the operation.The classification of the return type is done like for attributes.

New Operation with Parameters

I guess that adding parameters to the operation is obvious.

Page 30: Scripting EA

Creating New Things 23

Adding a profile-defined attribute or operation

Currently you can not easily create attributes or operations defined in a MDG. You have to codesome work around. Assume you want to create BPMN2.0::Property $p->Update(); I>Though it’srarely used, you can create attributes and operations defined in a MDG be specifying the FQNas second parameter of the AddNew like <profile_id>::<metatype>.

Embedded and Composite Elements

So what about contained/composite elements? Not too difficult at all:

1 element_embedded = element.Elements.AddNew ("New EP", "EntryPoint");

2 element_embedded.Update ();

3 element.Elements.Refresh ();

New Embedded Element

But the real truth is more difficult. Actually you can add the basic element type to either Elementsor EmbeddedElements – it does not matter! EA decides upon the element type to which collectionthe new element is added. In case of the basic element type set they are all created in Elements.But for the embedded element type set EA will retrieve them in both collections.

It’s probably a bit tricky to go through all the different variants but you should take the time toget a feeling how these elements are actually created. Once you managed above code snippetsyou should try that ExceptionHandler can only be created on package level and not on elementlevel. Vice versa check that EntryPoint is not created on package level. Finally try to create aNote element. Name it uniquely and run a model search with that name. You will find it in thesearch but not in the model. The only thing you probably can do with it: delete it in the modelsearch.

Adding further element ingredients

Inside an Element you find a couple of so called Rules. The Requirements are one of them. As aside note you should know that these are not real Requirements as can be found as stand-aloneelements in EA. Instead they should be called Responsibilities.

However, here’s a code snippet which inserts such an EaRequirement object:

Page 31: Scripting EA

Creating New Things 24

1 requirement =

2 element.Requirements.AddNew ("New Requirement", "Functional");

3 requirement.Update ();

4 element.Requirements.Refresh ();

This is pretty much straight-forward. The supplied second parameter in the AddNew representsthe Type of the requirement. When you open the properties of the element it should look like thefollowing picture:

New Requirement

I will not supply an example for the EaConstraint object as this is just the same.

Adding a scenario starts simply like for the above mentioned two collections. Since Scenariosis quite complex this is discussed in a separate chapter.

Finally the Files can be added like Requirements. The supplied type suggested by the GUI isone of

• Local File• Web Address

3.5 Adding a Connector

In order to create a connector between two elements you need to issue the following code lines:

1 connector = element1.Connectors.AddNew ("", "Dependency");

2 connector.SupplierID = element2.ElementID;

3 connector.Update ();

4 element1.Connectors.Refresh();

5 element2.Connectors.Refresh();

This will create an unnamed dependency starting at element1 and ending at element2. TheClientID of the connector is automatically filled with the ElementID of element1. So you justneed to supply the SupplierID. The connector will appear in the Connectors collection of both

Page 32: Scripting EA

Creating New Things 25

element1 and element2. Therefore you must Refresh() both collections if you want to look intothem later in the continuation of your code.

EA sets the direction of the created connector in dependency of

• the connector type and• for Association according to the Options/Links/Association Default setting.

E.g. for Dependency the default is Source -> Destination and for the standard settingsAssociation will be Unspecified. Eventually you can override this property. However, youneed to stick to the valid string values specified for Direction.

To set the role on either side simply supply an appropriate string in the Role property of theClientEnd or SupplierEnd object.

There is actually no relation between roles and attributes. EA just suggests strings inits GUI and does not create a connection. You should be aware of this fact as changingeither does not automatically change the other.

If you need any side of a connector to be a package you must pick the appropriate packageelement. Do not try to place the PackageID in either ClientID or SupplierID.

Like for elements you can create connectors defined in MDGs via FQN in the secondparameter of the AddNew like <profile_id>::<metatype>.

3.6 Adding a Diagram

Much simpler than adding an element is adding a diagram. We start with creating a simple classdiagram:

1 diagram = package.Diagrams.AddNew ("New Diagram", "Class");

2 diagram.Update ();

3 package.Diagrams.Refresh ();

4 Repository.RefreshModelView (package.PackageID);

Like for elements you need to supply the type which is taken from diagram types. When youopen this empty diagram you should see something like in the following picture:

New Diagram

Page 33: Scripting EA

Creating New Things 26

Just as noted for elements you can create a diagram on root level via automation whichis prohibited by the GUI. This is fine (I think) unless youmove the diagram into anotherview or package. Having done so EA will hinder you from moving it back to the rootlevel.

Like for elements you can create diagrams defined in MDGs via FQN in the secondparameter of the AddNew like <profile_id>::<metatype>. E.g. “BPMN2.0::BPEL” willcreate a BPEL diagram defined in the BPMN2.0 MDG.

3.7 Adding Diagram Objects

Basically this is straight forward, but like everywhere there are some obstacles when you aredeeper in the matters. Let us again start with a simple example. Again assuming you have anempty diagram object present we create a class element and place it somewhere on the diagram:

1 dia_obj = diagram.DiagramObjects.AddNew ("l=10;r=110;t=-20;b=-80", "");

2 dia_obj.ElementID = element.ElementID;

3 dia_obj.Update ();

4 Repository.ReloadDiagram (diagram.DiagramID);

After running this snippet you should see the class element placed somewhere top left of thediagram in a landscape format. The AddNew operation takes the coordinates as a first argument(t=Top, b=Bottom, l=Left, r=Right).

In our example the element will appear at position (10|-20) and stretching 100 pixels in width and60 pixels in height. This time we need to augment the created EaDiagramObject with an extraattribute: the ElementID of the EaElement which shall be shown.

So far, so good. Here’s the first curiosity:

You can add an object more than once to a diagram via automation like shown below.When you do so it looks like EA treats those duplicates correctly². But it feels a bitstrange when you create connectors from/to one of those duplicates. They are createdonly once but after re-opening the connector shows up for the clone too. You can hidethe clone connectors via Diagram/Advanced/Visible Relations... selectively. Butthen if you try to move multiple selected elements with the two clones only one ofthem is moved. In the end it looks and feels strange. YMMV

²I remember that former releases of EA reacted very strange when you created such multi-occurrences.

Page 34: Scripting EA

Creating New Things 27

Duplicate element on diagram

The procedure above is the same for all elements. If you add diagram objects to sequencediagrams the single elements are aligned to t=-50; once they are moved manually. Remember:if you add any package to a diagram you have to use the ElementID of the according packageelement.

Another strange observation is when you create such an EaDiagramObject withoutpassing a name holding the coordinates (i.e. an empty string). In that case thecoordinates are some arbitrary large positive numbers. EA renders these always top-left of the diagram in the default size, ignoring the random size values. It looks like EArecognizes them by their positive y-coordinates. When you run an auto-layout positionand size are re-assigned.

Adding special objects

As mentioned for elements in the section above, there are a couple of invisible elements likeText. Here’s a code snippet to add such a text to the current diagram:

1 text = package.Elements.AddNew ("", "Text");

2 text.Notes = "Some text";

3 text.Update ();

4 pos = "l=200;r=300;t=-20;b=-40";

5 dia_obj = diagram.DiagramObjects.AddNew (pos, "");

6 dia_obj.ElementID = text.ElementID;

7 dia_obj.Update ();

8 Repository.ReloadDiagram (diagram.DiagramID);

This will create a Text element in the current package and place it somewhere on top of thediagram (should be a bit right of the previously created class).

Although you don’t see the related object in the project browser, EA will now keep track of it.After you delete it from the diagram it will also be removed from the repository.

All the other invisible elements are treated the same way.

Page 35: Scripting EA

Creating New Things 28

Applying changes to modified diagrams

Assume you have unsaved modifications to the diagram: what will happen if you run abovecode? Just try it:

• Move the previously created text to the middle of the diagram.• Save the diagram.• Move the text to somewhere far off (e.g. top right).• Do not save but run the above script again.

As you will notice, another text element has been added at the desired position. But you alsosee that the old text has been moved back to the first saved position. Why? Because we issueda Repository.ReloadDiagram (diagram.PackageID); in the end. This will undo all diagramchanges and reload the last saved positions (except that the new element is now part of thediagram objects). Imagine you issue such a script after you made tons of changes in a diagram:they all get lost! Unfortunately you can not query whether a diagram has unsaved changes. Soyou should save preventively via

1 repository.SaveDiagram (diagram.DiagramID);

at the start of the script. Eventually you can precede such a script with a confirmation thatdiagram changes must be saved including an option to cancel.

Adding embedded elements

This is actually not tricky, but simply not very comfortable. For the next snippet³ you need adiagram (preferably empty) object, a class element and an embedded port for it.

1 pos = "l=300;r=400;t=-400;b=-470";

2 dia_obj = diagram.DiagramObjects.AddNew (pos, "");

3 dia_obj.ElementID = element.ElementID;

4 dia_obj.Update ();

5 pos = "l=393;r=408;t=-434;b=-449";

6 dia_obj = diagram.DiagramObjects.AddNew (pos, "");

7 dia_obj.ElementID = embedded.ElementID;

8 dia_obj.Update ();

9 Repository.ReloadDiagram (diagram.DiagramID);

Once you ran this code you will see the class somewhere in the middle of the diagram alongwith its port attached at the right side. As I said: simple. The port has width and height of 15pixels. Such it protrudes 7 pixel to the outside and intrudes 7 pixel. One pixel is the border line ofthe element. In our example we placed the port at the right (approximate) middle of the element

³In V10 (up to build 1006) the embedded element is not placed correctly but EA places it somewhere at the side of the embedding class. Thisbug has been fixed with V11 (build 1103).

Page 36: Scripting EA

Creating New Things 29

which has its right border at pixel 400. As a result the left border of the port is at pixel 393 andthe right border at 408. Since the left border of our element is at pixel 300 the according positionsfor the port being attached to the left side would be 293 and 308. To get the port attached tothe bottom the top/bottom of the port coordinates would be -463 and -478 as the bottom of theelements at -470. Of course the left/right position must be somewhere inside the element limits.

Having said this: you can also place a port “somewhere” and assign it an arbitrary size. While thesize is immediately scaled down to the 15 square pixels the position is that what you supplied.The misplaced port will last at that position until it is dragged. This will attach it to the elementwhere it belongs to.

If you place an orphaned port on a diagram you will not see it. It is however selectable(by dragging a grid over the diagram). Then you see just the quick linker but no element.Simply avoid doing such stupid things.

I (currently) leave it open to the reader to endeavor how the dimensions and coordinates of theother embedded elements are calculated.

Adding a partitioned Activity or State

Orthogonality rules – but not everywhere. As far as we have learned each element in a diagramis represented by a diagram object. When you add partitions to Activity or State elements thesecontain information how the element is to be rendered. When you place a partitioned elementon a diagram its height is calculated from the sum of the single partition heights.

So let’s create two partitions in an already existing activity (place this activity on an opendiagram and make it quite narrow to see the effects):

1 part = activity.Partitions.AddNew ("p1", "");

2 part.Size = "90";

3 part = activity.Partitions.AddNew ("p2", "");

4 part.Size = "90";

5 activity.Update ();

Now you should see two partitions with the same height (90 pixel) named p1 and p2. If theactivity was too narrow (as advised) it should now have a height of 180 pixel.

State partitions are treated just the same as Activities.

Adding specific connectors

If you don’t care for the placement of connectors you simply can omit that. For any connectedelements on a diagram EA will render a default connector. But if you want special appearance(like tree style or custom connectors) you need to create an appropriate entry. Also if you wantto hide a connector you must create an EaDiagramLink.

For the moment we will only light the aspect of connector suppression.

Page 37: Scripting EA

Creating New Things 30

1 dia = Repository.GetCurrentDiagram ();

2 con = dia.SelectedConnector ();

3 for (i = 0; i < dia.DiagramLinks.Count; i++) {

4 diagram_link = dia.DiagramLinks.GetAt (i);

5 if (diagram_link.ConnectorID == con.ConnectorID) break;

6 }

7 if (not diagram_link) {

8 diagram_link = diagram.DiagramLinks.AddNew ("", "");

9 (diagram_link.ConnectorID = con.ConnectorID;

10 }

11 diagram_link.IsHidden = 1;

12 diagram_link.Update;

13 dia.DiagramLinks.Refresh ();

14 Repository.ReloadDiagram (dia.DiagramID);

First we need to find a possibly existing EaDiagramLink entry for the connector. Only if this isnot found we create one and bind it to the connector. Finally the IsHidden property is set to trueso the connector will not be rendered on the diagram. The ReloadDiagram will make the changeeffective and hide the connector.

3.8 And the Opposite

Of course there is also a way to remove objects from the repository. Unfortunately there is noDelete operation for any of the above mentioned objects. Instead you have to locate them in theaccording collection where they were placed before and delete them from there. Not a big deal— almost. Take for example the New Attribute from above. To delete that you can execute thefollowing snippet:

1 attributes = element.Attributes;

2 attributes.Delete(0);

Actually there is a second operation DeleteAtwith one more boolean parameter whichmust be supplied but is not used. So it does the same thing as Delete. I don’t knowwhich heavenly spark hit the interface designer but it was definitely a strange one.

The above code will actually delete the attribute from the repository. But it will not be removedfrom

• the collection where we just issued the Delete,• any currently open diagram where it is shown and• the project browser.

To remove it also from the collection you need to call

Page 38: Scripting EA

Creating New Things 31

1 attributes = element.Attributes;

2 attributes.Delete(0);

and to actually tell EA that you currently have delete something and it should update elementsdisplayed on possibly open diagrams you need to call

1 attributes.Refresh();

Again another bright spark. I have no idea why EA needs an extra trigger for that.Maybe you can save some milliseconds when mass-deleting things, but the chance toleave an inconsistent display on not calling this operation is by far greater.

If you are going to remove multiple things from a collection you can do that safely by calling theDelete for the appropriate indexes. However, you should avoid to call Refresh after each deletesince that will likely confuse your iterator.

So the best thing at last. Still the project browser will display the currently deleted attribute. Soyou finally need to call

1 repository.RefreshModelView (element.PackageID);

The funny thing here is that if you have unsaved changes in a diagram from that package youwillbe asked to save that first (thus making most of the above AdviseElementChange superfluous).Most likely you’re better off calling

1 repository.SaveDiagram (diagram.DiagramID);

first instead of relying on the user doing the right thing.

Page 39: Scripting EA

4. Advanced CreationsIf you have worked up to this point you are probably already an advanced EA scripter. Mostlikely you will be able to make your way yourself. But in the end it’s easier with a couple ofrecipes. I will add them in this chapter time by time.

4.1 Semi-manual Element Creation/Selection

Starting from V10 you can use a neat repository operation to create and/or select element withuser interaction. This is especially useful if you need the user to select an element or to create itduring the runtime of a script.

1 filter = "IncludedTypes=Class,Component;StereoType=foo,bar";

2 elementId = Repository.InvokeConstructPicker(filter);

3

4 filter = "IncludedTypes=Class,Component";

5 elementId1 = Repository.InvokeConstructPicker(filter);

When executing the first of the above operations EA will open a dialog box like the following:

Element Selection

The bottom left reflects the passed parameters. Namely Types from IncludeTypes which limitsthe elements to Class and Component. Below the stereotype filter foo,bar is shown.

Executing the second operation will result in almost the same dialog, except that the stereotypefilter will not be present. Therefore other classes/components with other or no stereotype mightappear in the list.

Page 40: Scripting EA

Advanced Creations 33

It is also possible to create an arbitrary number of elements with the Add New button.These are not limited in type or stereotype. However, only the elements passing thefilter will be shown.

Vice versa it is not possible to create a package, though you have included it in theIncludeTypes.

On return elementId will contain the ElementID of the selected element. If the dialog wascanceled by the user this value is zero.

4.2 Adding a Scenario

There are two different ways to create scenarios: as plain text and as structured steps.

A plain text scenario

Let’s start with plain text variant as it’s a bit easier.

1 scenario = element.Scenarios.AddNew ("scenario", "Basic Path");

2 scenario.Notes =

3 Repository.GetFieldFromFormat ("HTML", "<ol><li>one<li>two<ol>");

4 if (!scenario.Update ()) print "Update failed";

The first line will create the scenario. The first parameter is the name of the scenario and thesecond is the type. Here the latter can be an arbitrary string but it is recommended to stick tothe values described¹. You have to note that the name of the scenario must be unique. If you passthe name of an already existing scenario EA will create an object in scenario but then fails inthe Update call. This is probably because you can change the Name property after creating it andEA only checks it for uniqueness when calling the Update in the last line.

The second/third line creates the scenario description. Most likely you would like to see thedescription itself as an ordered list. For this reason the Notes property – which actually containsthe steps – is populated from an HTML string. The picture for this scenario should finally looklike this:

Plain Text Scenario

¹While plain text scenarios are a bit sloppy in this respect it is important for structured scenarios to stick to the default values or somefunctions will not work!

Page 41: Scripting EA

Advanced Creations 34

A structured scenario

The second way is to create a structured scenario. The basics from the plain text scenario applylikewise.

You should not populate the Notes property as it would introduce an ambiguity in thescenario description. Use one operation or the other and do this consequently in yourwhole model. Just to not confuse the readers of your model!

Before proceeding with the following snippet do not forget to delete the previously createdscenario or choose a different name for it.

1 scenario = element.Scenarios.AddNew ("scenario", "Basic Path");

2 s = scenario.Steps.AddNew ("step1", "1");

3 s.Uses = "use";

4 s.State = "state";

5 s.Update();

6 s = scenario.Steps.AddNew ("step2", "0");

7 s.Update();

8 if (!scenario.Update ()) print "Update failed";

It begins with the creation of the (unique) scenario. Now, instead of creating the steps in thenotes, a single step named step1 is created. The name parameter of the AddNew corresponds tothe Action column in the picture below. Unlike the scenario name it must not be unique. Thetype parameter is interpreted to represent the Step icon. A 1 yields an actor and a 0 a systemicon.

The Uses and State properties can be supplied additionally. For some reason the Results

property seems to be ignored by the automation. This is under investigation.

The next AddNew creates the next step. This time with a system icon. This way you can go oncreating all steps of a scenario.

The final step must be to call Update for the scenario. The steps will only be included in thescenario after this final Update! The scenario should now look like this:

Plain Text Scenario

Page 42: Scripting EA

Advanced Creations 35

An alternative path

The following sample creates two scenarios, a basic path scenario and an alternate. Bothscenarios contain a single step. The variable tilEnd decides whether the alternate path endsin a FlowEnd or joins back to the first step in scenario.

1 alt = element.Scenarios.AddNew ("alternate", "Alternate");

2 altS = alt.Steps.AddNew ("alt step1", "1");

3 altS.Update();

4 scenario.Update();

5

6 scenario = element.Scenarios.AddNew ("scenario", "Basic Path");

7 s = scenario.Steps.AddNew ("step1", "1");

8 s.Update();

9 ext = s.Extensions.AddNew ("", alt.ScenarioGUID);

10 if (tilEnd) ext.Join = "";

11 else ext.Join = s.StepGUID;

12 ext.Update();

13 scenario.Update();

The first four lines are simple: they create a scenario like in above examples. Just that it is anAlternate and has only a single step.

The next three lines after the empty line create the Basic Pathwith a single step. So far, so good.Now the next line creates the ScenarioExtension object. The name parameter is irrelevant² andthe type is the GUID of the alternate scenario to which the flow shall go. Note that the alternateis always placed before the corresponding step.

As mentioned, the if-clause controls how the alternate shall continue. If tilEnd is true the Joinproperty is set to blank. That will terminate the flow in a FlowEnd. Else the StepGUID of the stepinto which the alternate shall go is supplied. In this example it’s that very step1 of scenario.

If you have run this code snippet with tilEnd set to false and create an activity diagram fromthe scenario it should look like this:

²The EA help tells that this must be the name of a step in the scenario. But that’s obviously nonsense as the flow always starts at the firststep of an Alternate.

Page 43: Scripting EA

Advanced Creations 36

Alternate Scenario joining step1

4.3 Create Connector for Attributes

Usually connectors just connect elements. But you can ‘tune’ them to connect attributes (oroperations). For the following sample it is assumed that two classes with each having (at least)two attributes are present in class1 and class2.

1 con = class1.Connectors.AddNew ("", "Association");

2 con.SupplierID = class2.ElementID;

3 attr1 = class1.Attributes.GetAt (0);

4 con.StyleEx = "LFSP=" + attr1.AttributeGUID + "R;";

5 con.Update;

6

7 con = class1.Connectors.AddNew ("", "Association");

8 con.SupplierID = class2.ElementID;

9 attr1 = class1.Attributes.GetAt (1);

10 attr2 = class2.Attributes.GetAt (1);

11 con.StyleEx =

12 "LFSP=" + attr1.AttributeGUID + "R;" +

13 "LFEP=" + attr2.AttributeGUID + "L;";

14 con.Update;

The first two lines create a new association from class1 to class2 and the thirds line fetches thefirst attribute of class1. The fourth line connects the association to that attribute. The oppositeside is simply connected³ to class2. Note that I used the plus operator for string concatenation.The contents of StyleEx should look like LFSP={F174CB55-CC04-49aa-A649-EB1489C270AC}R;.This obscure string actually does the magic to tie a connector to an attribute.

The lines up to the next StyleExmanipulation are obvious. This line then will connect the secondattribute of class1 with the second of class2.

I leave it to you to guess how a connection to just class2’s attribute is made.

³For details see my Inside EA book.

Page 44: Scripting EA

Advanced Creations 37

When you display the result in a diagram it should look like this:

Connectors between Attributes

In order to make connections between operations simply use the appropriate MethodGUID insteadof the AttributeGUID.

4.4 Nasty Things

Sometimes you’ll find yourself in a situation where the API does not provide information whichotherwise can be changed via the GUI. A simple example is the Cardinality property. There isno way to read or write it via the API. The way around that gap is EaRepository.Execute.

In order to work with this feature you need quite some insight into the underlying database⁴.However, here comes the code:

1 sql =

2 "UPDATE t_object SET Cardinality='0..1' WHERE ea_guid = '" +

3 guid + "'";

4 Repository.Execute (sql);

Now, the above example is quite simple. The UPDATE statement will change the columnCardinality which actually stores the information you want to change. The WHERE clause herelooks for the ElementGUID of the element which is going to be changed. Instead it is also possibleto use the ElementID to match Object_ID.

The Execute operation only takes UPDATE and DELETE statements (maybe also ALTER but I can’timagine a use case for that). If you want to use SELECT you need to use EaRepository.SQLQuery.

When you are working with EaRepository.Execute you have to consider that thedatabase is even more vulnerable than going through the official API operations. Thatin mind, plan a thorough test of your scripts when using this operation!

4.5 More Undocumented Stuff

There is another undocumented operation of EaRepository called CustomCommand. Of course youwill be on yourself if you run into trouble when using it. But for the real hackers it offers quitesome hidden treasures.

⁴Of course I can recommend my book Inside EA to learn more about these details.

Page 45: Scripting EA

Advanced Creations 38

In order to open some of the property dialogues in EA you can use this operation. To actually dothat it is necessary to get hold of the windows handle of the EA application. Unfortunately I cannot go into details on how to do that. So in the following examples I simply assume that hwndholds the number that represents this special handle.

To distinguish between the different property dialogues the CustomCommand uses an identificationstring (here dlg).

1 xmlres =

2 Respository.CustomCommand(

3 "CFormCommandHelper", "ProcessCommand",

4 "Dlg=" + dlg + ";id=" + id + ";hwnd=" + hwnd);

Depending on dlg the id parameter must be supplied:

dlg id Open dialogue

PKG EaPackage.PackageID Package propertiesELM EaElement.ElementID Element propertiesATT EaAttribute.AttributeID Attributes propertiesOP EaMethod.MethodID Methods propertiesDGM EaDiagram.DiagramID Diagram properties

On return the xmlres contains an xml-formatted string. If any of the parameters is invalid thenres is empty and no dialogue is shown at all. The contents of the xml follows the structure ofthe appropriate element and it is probably not worth while to parse it since this is available viathe standard API anyway.

You don’t have any means of figuring out whether the OK or Cancel button had beenpressed in the dialogue. It might be sufficient to check whether EaElement.Modifiedhas been changed. This is the case if any of the properties in the dialogue was modified.However, an OK without any change would then be the same as a Cancel.

A second use of this operation is to import reference data:

1 xmlres = Respository.CustomCommand("Repository", "ImportRefData", sXML);

The parameter sXML is a string value containing the reference data from a former export.

Likely there are more usages, but they are not revealed yet. I’m happy to add any findings here.

4.6 Creating Things from a MDG

When working with MDGs you will find a couple of different elements, diagrams, connectors,attributes, operations and eventually packages. In order to create one of the above, things get a

Page 46: Scripting EA

Advanced Creations 39

bit more difficult. First off, creation for each of the above mentioned is a bit different. So I’ll justthrow in a few code examples for the BPMN2.0 MDG which comes per default with EA.

In order to create any element from a MDG you need its profile ID. You find that in the secondline of a profile (see code below). This ID is needed to supply the Fully Qualified Name (FQN)of a MDG stereotype

1 <MDG.Technology version="1.0">

2 <Documentation id="ident" .../>

where you take the contents of the id attribute as <profile_id>.

Further you need the <metatype>, which is a way down near a location like the following:

1 <UMLProfile profiletype="uml2">

2 <Documentation id="..." name=.../>

3 <Content>

4 <Stereotypes>

5 <Stereotype name="..." metatype="meta" ...>

Here you need to locate the appropriate metatype attribute. The FQN would then be somethinglike BPMN2.0::Assignment. You can find those values for e.g. the BPMN2.0 profile by openingBPMN20. Technology.xml in the MDGTechnologies folder inside the EA program folder.

It is not possible to create such an element if it applies to more than one UMLtype (that is such elements you would specify in a toolbox as e.g. <profile_-

id>::<metatype>(UML::Class)). According to Sparx this is not yet implemented.

Packages

Like in above example with package stereotypes you need two steps:

1 package = view.Packages.AddNew ("New Package", "");

2 package.Update ();

3 package.Element.Stereotype = "profile_id::stereo";

4 package.Update ();

Once the package is created you can apply the MDG stereotype. To my knowledge there is nopublic technology which comes with a stereotyped package. So I can’t supply a simple example.But I have tested the above with some scratch MDG I’ve created for that purpose.

Elements

Creation of elements is a bit easier than packages and straight forward:

Page 47: Scripting EA

Advanced Creations 40

1 element = package.Elements.AddNew ("New MDG Element", "BPMN2.0::Assignment");

2 element.Update ();

Diagrams

Creating a new diagram is similar. Again you supply the MDG stereotype via the secondparameter of the AddNew operation:

1 element = package.Elements.AddNew ("New MDG Element", "BPMN2.0::Assignment");

2 element.Update ();

Attributes and Operations

Yet another way (we all love EA for its unique interface) is used to create attributes andoperations:

1 attribute = element.Attributes.AddNew ("New Attribute", "");

2 attribute.SterotypeEx = "BPMN2.0::Property";

3 attribute.Update();

Unlike using the second AddNew parameter like for Elements you need to supply StereotypeEx.

Connectors

Once again like elements you can create connectors by supplying the MDG stereotype via thesecond parameter of the AddNew:

1 connector = element1.Connectors.AddNew ("", "BPMN2.0::ConversationLink");

2 connector.SupplierID = element2.ElementID;

3 connector.Update ();

Page 48: Scripting EA

5. Object DetailsThis section is referenced from above sections. You can use it as a quick reference but it containsalso a number of information which is not detailed in EA’s help.

Unless otherwise noted all properties are r/w. Collections are r/o in the way that they can not beset to anything different. However, each collection has operations to alter their contents.

There are two general operations bool Update() and string GetLastError() which are notlisted below as most objects respond to them and their use is quite obvious. If Update returnsfalse you should consider the return value of GetLastError. Note that it is not cleared by alloperations but may reside from an arbitrary previous error. You should only check it after anUpdate or as noted for different operations.

Since a couple of objects do not have specific operations their appropriate section just lists theattributes. Else attributes and operations appear under separate sub-sections.

5.1 EaRepository

Attributes

EaCollection Authors —An EaCollection of EaAuthor objects.

These are defined with Settings/Project Types/People/Authors.

bool BatchAppend —Set this property to true when your automation client has to rapidly insert many elements,operations, attributes and/or operation parameters.

Set to false when work is complete.

This can result in 10- to 20-fold improvement in adding new elements in bulk.

EaCollection Clients —An EaCollection of EaClient objects.

These are defined with Settings/Project Types/People/Clients.

string ConnectionString —The filename/connection string of the current Repository.

This is either a filename (<drive>:\path\to\file.eap) or an ODBC connection string.

If you find a filename you need to do some additional checks. If the size of the file is small(less than 512k Byte) this is a shortcut file, else it is a .EAP. If it is a shortcut file then youhave to read its contents. The first line starts with EAConnectString: followed by the realconnection string (this is only one recursion as it seems). You can forget about the optionalfollowing lines¹ which are commands to EA to do certain actions upon opening EA.

¹I might document these in a future version of this book.

Page 49: Scripting EA

Object Details 42

Detailed information about the construction of connection strings will be found viaGoogle². However, the connection string will contain DBType=<n>; where <n> is one of

0 - MYSQL1 - SQLSVR2 - ADOJET3 - ORACLE4 - POSTGRES5 - ASA7 - OPENEDGE8 - ACCESS2007

EaCollection Datatypes —An EaCollection of EaDatatype objects.

These are defined with Settings/Code Datatypes....

long EAEdition r/o —Returns the current level of core licensed functionality available.

This property returns Corporate when the edition is Business and Software Engineering,Systems Engineering or Ultimate.

Use EAEditionEx to identify which of these extended editions is available.

Valid values are:

• Lite = 0• Desktop = 1• Professional = 2• Corporate = 3• Business = 4• SystemEng = 5• Ultimate = 6

long EAEditionEx r/o —Returns the current level of extended licensed functionality available.

bool EnableCache —EA help: An optimization for pre-loading package objects when dealing with large sets ofautomation objects.

I have not seen any real performance improvement once I tested it. However, I always turnit on.

bool EnableUIUpdates —Set this property to false to improve the performance of changes to the model; forexample, bulk addition of elements to a package. To reveal the changes to the user, callEaRepository.RefreshModelView().

²You may consult http://www.connectionstrings.com/ to see how such a string is constructed.

Page 50: Scripting EA

Object Details 43

bool FlagUpdate —Instructs Enterprise Architect to update the Repository with the LastUpdate property.

string InstanceGUID r/o —The identifier for the Enterprise Architect runtime session.

bool IsSecurityEnabled r/o —Tells whether User Security is enabled for the current repository.

EaCollection Issues —An EaCollection of EaIssue objects.

These are defined with Project/Project Status/Issues³.

string LastUpdate r/o —The identifier for the Enterprise Architect runtime session and the timestamp for when itwas set.

long LibraryVersion r/o —The build number of the Enterprise Architect runtime.

EaCollection Models —An EaCollection of the root packages of the repository.

long ObjectType r/o —Constant value 2 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

string ProjectGUID r/o —A GUID for the project.

EaCollection ProjectRoles —An EaCollection of EaProjectRole objects.

These are defined with Setting/Project Types/People/Roles.

EaCollection PropertyTypes —An EaCollection of EaPropertyType objects.

These are the pre-defined tagged value types defined with the dialog that appears afterclicking the 6th icon in this picture.

EaCollection Resources —An EaCollection of EaResource objects.

These are defined with Setting/Project Types/People/Resources.

EaCollection Stereotypes —An EaCollection of EaStereotype objects.

These stereotypes are defined with Settings/UML Types/Stereotypes.

³Pre V10: View/More Project Tools/Project Information/Issues

Page 51: Scripting EA

Object Details 44

bool SuppressEADialogs —Set this property in the EA_OnPostNewElement or EA_OnPostNewConnector broadcastevents⁴ to control whether Enterprise Architect should suppress showing the defaultProperties dialogs to the user when an element or connector is created.

EaCollection Tasks —An EaCollection of EaTask objects.

These are defined with View/More Project Tools/Project Information/Tasks.

EaCollection Terms —An EaCollection of EaTerm objects.

These are defined with View/More Project Tools/Project Information/Glossary.

Operations

The EA EaRepository object offers a large variety of operations for various purposes. Most ofthem are placed in the according sections below. Only a few are referenced in both. Everythingthat did not fit a special purpose group is placed in the Misc section at the end.

Object Retrieval

These operations are used to retrieve various elements from the currently open repository.

EaAttribute GetAttributeByGUID (string GUID) —Returns an EaAttribute in the repository, located by its GUID.

EaAttribute GetAttributeByID (long ID) —Returns an EaAttribute in the repository, located by its AttributeID being ID.

EaConnector GetConnectorByGUID (string GUID) —Returns an EaConnector in the repository, located by its GUID.

EaConnector GetConnectorByID (long ID) —Returns an EaConnector in the repository, located by its ConnectorID being ID.

long GetContextItem (object Item) —Sets⁵ a pointer to an item in context within Enterprise Architect.

Returns the corresponding EaObjectType.

long GetContextItemType () —Returns the EaObjectType of the item in context within Enterprise Architect. A EaCon-

textItem is defined as an item selected anywhere within the Enterprise Architect GUIincluding:

• An item selected in the Project Browser

⁴Broadcast events are not (yet) covered by this book.⁵Actually I was not able to get this to work. It might be because I’m using a scripting language.

Page 52: Scripting EA

Object Details 45

• An item selected in an open diagram• An item selected in certain dialogs, such as the attribute Properties dialog

The supported EaObjectTypes can be any one of the following values: otElement,otPackage, otDiagram, otAttribute, otMethod and otConnector.

object GetContextObject () —Returns the current context object. This is the same as GetContextItem above but returnsthe object as return parameter instead of a reference parameter value.

diagram GetCurrentDiagram () —Returns a selected EaDiagram object representing the currently open diagram. If nodiagram is visible (e.g. the start page or the search window is displayed) this operationreturns a null pointer.

EaDiagram GetDiagramByGUID (string GUID) —Returns an EaDiagram in the repository, located by its GUID.

EaDiagram GetDiagramByID (long ID) —Returns an EaDiagram in the repository, located by its DiagramID being ID.

EaElement GetElementByGUID (string GUID) —Returns an EaElement in the repository, located by its GUID.

EaElement GetElementByID (long ID) —Returns an EaElement in the repository, located by its ElementID being ID.

EaCollection GetElementsByQuery (string QueryName, string SearchTerm) —An EaCollection of EA objects which represent the result of the search QueryName andsearch term SearchTerm.

E.g. GetElementsByQuery('Simple','Class1')would return a collectionwith one EaEle-ment having the GUID {D3112AB4-5A35-48e2-9D52-C53C87BC5DC6}.

EaCollection GetElementSet (string IDList, long Options) —An EaCollection of EA elements.

• If Options == 0 an empty IDList returns all EaElement objects in the repository.• If Options == 1 the returned collection is empty.• In both cases with a non-empty IDList being a comma-separated list of EaElementIDvalues the EaElement objects matching ElementID is returned.

• If Option == 2 the contents of IDList is regarded to be a query. E.g. a

SELECT * FROM t_object WHERE Name = 'Class1'

will return the one EaElement having the GUID {D3112AB4-5A35-48e2-9D52-C53C87BC5DC6}.

More about SQL statements can be found in my book Inside EA.

EaMethod GetMethodByGUID (string GUID) —Returns a EaMethod in the repository, located by its GUID.

Page 53: Scripting EA

Object Details 46

EaMethod GetMethodByID (long ID) —Returns a EaMethod in the repository, located by its MethodID being ID.

EaPackage GetPackageByGUID (string GUID) —Returns a EaPackage in the repository, located by its GUID.

EaPackage GetPackageByID (long ID) —Returns a EaPackage in the repository, located by its PackageID being ID.

EaCollection GetTreeSelectedElements() —An EaCollection of EA objects currently selected in the Project Browser.

long GetTreeSelectedItem (object SelectedItem) —Sets SelectedItem to the currently selected item in the tree view.

Returns the EaObjectTypewhich is also stored in the ObjectType attribute of the returnedSelectedItem.

To use this function, create a generic object variable and pass this as the parameter.Depending on the return type, cast it to a more specific type.

The object passed back through the parameter can be a EaPackage, EaElement, EaDiagram,EaAttribute or EaMethod object.

long GetTreeSelectedItemType () —Returns the EaObjectType of the object currently selected in the tree. One of otDiagram,otElement, otPackage, otAttribute or otMethod.

Object GetTreeSelectedObject () —The related operation GetTreeSelectedItem() has an output parameter that is inaccessibleby some scripting languages. As an alternative, this operation provides the selected itemthrough the return value.

EaPackage GetTreeSelectedPackage () —Returns the EaPackage object in which the currently selected tree view object is contained.

void RunModelSearch (string QueryName, string SearchTerm, string SearchOptions,

string SearchData)— Runs the search QueryNamewith search term SearchTerm, display-ing the results in Enterprise Architect’s Model Search window.

• SearchOptions is currently not being used.• SearchData enables you to supply a list of results in the form of XML, which isappended onto the result list in Enterprise Architect. This parameter is notmandatoryso pass in an empty string to run the search as per normal. Also note that thisparameter does not work with some scripting languages.

string SQLQuery (string SQL) —Returns an XML formatted string value of the recordset returned by the query SQL.

More about SQL statements can be found in my book Inside EA.

Page 54: Scripting EA

Object Details 47

View

These operations are used to manipulate views or visible elements in the GUI.

void ActivateDiagram (long DiagramID) —Activates the already open EaDiagram with its DiagramID matching ID (i.e. make it theactive tab).

void ActivateTab (string Name) —Activates the open Enterprise Architect tabbed view named Name.

ActiveX AddTab (string TabName, string ProgID) —Adds an ActiveX custom control from ProgID as a tabbed window named TabName.Enterprise Architect creates a control and, if successful, returns its Unknown pointer,which can be used by the caller to manipulate the control.

ActiveX AddWindow (string WindowName, string ProgID) —Adds an ActiveX custom control from ProgID as a windowwith the title WindowName to theAdd-Ins docked window. Enterprise Architect creates a control and, if successful, returnsits Unknown pointer, which can be used by the caller to manipulate the control.

void AdviseConnectorChange (long ConnectorID) —Provides an Add-In or automation client with the ability to advise the Enterprise Architectuser interface that the EaConnector with ID ConnectorID has changed and, if it is visiblein any open diagram, to reload and refresh that connector for the user.

void AdviseElementChange (long ObjectID) —Provides an Add-In or automation client with the ability to advise the Enterprise Architectuser interface that the EaElement with ID ObjectID has changed and, if it is visible in anyopen diagram, to reload and refresh that element for the user.

void ClearOutput (string Name) —Removes all the text from the tab Name in the Output window.

void CloseDiagram (long DiagramID) —Closes the EaDiagram with ID DiagramID in the current list of diagrams that EnterpriseArchitect has open.

void CreateOutputTab (string Name) —Creates the tab Name in the Output window.

void EnsureOutputVisible (string Name) —Ensures that the tab Name in the Output window is visible to the user. The Output windowis made visible if it is hidden.

string IsTabOpen (string TabName) —Checks whether the (case sensitive) tabbed view TabName is open and active. This includesopen diagram windows or custom controls added using EaRepository.AddTab().

Returns: 0 = not visible at all, 1 = not top-most, or 2 = open and active (top-most)

Page 55: Scripting EA

Object Details 48

void OpenDiagram (long ID) —The EaDiagramwith its DiagramIDmatching ID is added to the tabbed list of open diagramsin the main Enterprise Architect view and made visible.

void RefreshModelView (long ID) —Reloads the EaPackage with ID matching PackageID, updating the user interface.

If ID == 0 the entire model will be reloaded.

void RefreshOpenDiagrams (bool FullReload) —Refreshes the diagram contents for all diagrams open in Enterprise Architect.

If FullReload == True each of the diagrams is completely reloaded from the repository.Else only the displayed contents of elements and connectors are refreshed in each diagram⁶.

void ReloadDiagram (long ID) —Reloads the specified EaDiagram with its DiagramID matching ID.

This would commonly be used to refresh a visible diagram after code import/export orother batch process where the diagram requires complete refreshing.

• Calling this operation within a call to EA_OnNotifyContextItemModified is notsupported

void RemoveOutputTab (string Name) —Removes the specified tab Name from the Output window.

bool RemoveWindow (string WindowName) —Removes an Add-In window that matches the specified WindowName‘.

void ShowDynamicHelp (string Topic) —Shows the help as a view pointing to Topic⁷.

void ShowInProjectView (object Item) —Selects the object Item in the Project Browser.

Accepted ObjectTypes are Package, Element, Diagram, Attribute, and Method. An excep-tion is thrown if the object is of an invalid type.

void ShowProfileToolbox (string Technology, string Profile, bool Show) —Shows/hides the contents of Technology or Profile in the Toolbox according to Show.

To show/hide a profile in the Toolbox, specify the profile’s ID value in the Profile

parameter and set the Technology parameter to a null string.

To show/hide a technology in the Toolbox, specify the technology’s ID in the Technologyparameter and set the Profile parameter to a null string.

void ShowWindow (long Show) —Shows or hides Enterprise Architect according to Show.

⁶Which leads to the question what happens to the non-visible diagrams?⁷Honestly I have no idea how to specify such a topic.

Page 56: Scripting EA

Object Details 49

MDG

These operations are used to control MDG Technologies.

void ActivateTechnology (string Name) —Activates an enabled the MDG Technology named Name.

bool ActivateToolbox (string Toolbox, long Options) —Activates the named Toolbox page in the GUI.Returns true if the specified Toolbox page is successfully activated, otherwise returns false.The parameter Options is reserved for future use.

void AddDefinedSearches (string sXML) —Enables you to enter a set of defined searches that last in Enterprise Architect for the lifeof the application. When Enterprise Architect loads again they must be inserted again byyour Add-In.

The sXML is the XML of the defined searches. You can get this XML by performing anexport of the searches from the Manage Searches dialog in Enterprise Architect

void CloseAddins () —Called by automation controllers to ensure that Add-Ins created in .NET do not linger afterall controller references to Enterprise Architect have been cleared.

bool DeleteTechnology (string ID) —Removes the MDG Technology with ID resource from the repository.

Returns true, if the technology is successfully removed from the model. Returns falseotherwise.

• This applies to technologies imported into pre-7.0 versions of Enterprise Architect(imported technologies), not to technologies referenced in version 7.0 and later(referenced technologies)

string GetTechnologyVersion (string ID) —Returns the version of the specified MDG Technology resource ID.

bool ImportTechnology (string Technology) —Installs the MDG Technology resource located in the file Technology into the repository.

Returns True, if the technology is successfully loaded into the model. Otherwise returnsFalse.

• This applies to technologies imported into pre-7.0 versions of Enterprise Architect(imported technologies), not to technologies referenced in version 7.0 and later(referenced technologies).

bool IsTechnologyEnabled (string ID) —Checks whether the technology with ID is enabled in Enterprise Architect.

Returns True if the MDG Technology resource is enabled. Otherwise returns False.

Page 57: Scripting EA

Object Details 50

bool IsTechnologyLoaded (string ID) —Checks whether the technology with ID is loaded into the repository.

Returns True if the MDG Technology resource is loaded into the repository. Otherwisereturns False.

bool SynchProfile (string Profile, string Stereotype) —Synchronizes Tagged Values and constraints of the UML Profile for Stereotype.

Returns True if the synch was successful. Otherwise returns False.

Security

bool ChangeLoginUser (string Name, string Password) —Sets the currently logged on user to be that specified by a Name and Password. This logsthe user into the repository when security is enabled.

If security is not enabled an exception (Security not enabled) is thrown.

string GetCurrentLoginUser (bool GetGUID) —If GetGUID is True, a GUID generated by Enterprise Architect representing the user isreturned. Otherwise or if missing the text as entered in System Users/User Details/Login

is returned.

If security is not enabled an exception (Security not enabled) is thrown.

bool OpenFile2 (string FilePath, string Username, string Password) —See the OpenFile2 operation below.

bool SuppressSecurityDialog —Suppress the login prompt dialog that appears by default when username and passwordparameters passed to OpenFile2 are invalid.

For use by external automation clients only.

Audit

bool ClearAuditLogs (DateTime StartDateTime, DateTime EndDateTime) —Clears all Audit Logs from the model. If StartDateTime and EndDateTime are not null thenonly log items that fall into this period are cleared.

Returns true for success, false for failure.

• This operation cannot be undone. It is strongly advised that you call SaveAuditLogsfirst to backup the logs

• This operation might fail if the user logged into the model does not have the correctaccess permission

bool SaveAuditLogs (string FilePath, DateTime StartDateTime, DateTime EndDateTime)

—Saves the Audit Logs contained within a model to the file FilePath.

Page 58: Scripting EA

Object Details 51

If StartDateTime and EndDateTime are not null then only log items that fall into this periodare saved.

Returns true for success, false for failure.

• This might fail if the user logged into the model does not have the correct accesspermission

Repositories

void CloseFile () —Closes any open repository. The EA instances stays open so a new repository can opened.

bool CreateModel (short CreateType, string FilePath, long ParentWnd) —If CreateType==0 this creates a new .eap model file based on the standard EnterpriseArchitect Base model located at FilePath. If CreateType==1 this create a shortcut .eapbased on a provided SQL connection. Here thewindow handle ParentWnd acts as the parentfor the SQL connection dialog.

Returns true when the new file is created, otherwise returns false.

void Exit() —Shuts down Enterprise Architect immediately. Used by .NET programmers where thegarbage collector does not immediately release all referenced COM objects.

bool OpenFile (string Filename) —This operation opens a repository and returns True if the repository was opened success-fully. Returns False otherwise.

Filename is interpreted in various ways by EA.

• A file name pointing to an .EAP file: This will simply open the repository.• A file name to a shortcut .EAP file: This will open the repository stored in theshortcut.

• A connection string: This will try to connect to the according RDBMS to open therepository. A valid connection string can be obtained from the Open Project dialogvia context Edit Connection String for any stored recent repository.

bool OpenFile2 (string FilePath, string Username, string Password) —This is the same as OpenFile above except that a Username and Password are supplied tolog in a user defined in security.

string RepositoryType r/o —Returns the currently open database/repository type. For Example: JET, MYSQL, SQLSVR

Further Interface Access

DocumentGenerator CreateDocumentGenerator() —Returns a pointer to the EA.DocumentGenerator interface.

Page 59: Scripting EA

Object Details 52

MailInterface GetMailInterface() —Returns an instance of the MailIinterface. Use this interface to automate the process ofcreating and sending model mail messages.

Project GetProjectInterface () —Return a Project interface object (the XML-based automation server for EnterpriseArchitect). Use this interface to work with Enterprise Architect using XML, and also toaccess utility functions for loading diagrams, running reports and so on.

Version Control

void ScanXMIAndReconcile () —Scans the package XMI files associated with each of the project’s controlled packages andrestores any diagram objects or cross-references that are detected as missing from theproject.

This function is useful in team environments where each user maintains their ownprivate copy of the model database (i.e. multiple private EAP files) and model updatesare propagated through the use of controlled packages. It provides no benefit when themodel is hosted in a single shared database that is accessed by all team members.

Each controlled package is comparedwith its associated XMI file and, if the cross-referenceinformation in the model does not match the XMI, Enterprise Architect updates the modelwith the information from the XMI and records the update in the Output window.

You can roll back such updates by right-clicking on the entry in the Output windowand selecting the context menu option Rollback Update (or Rollback Selected Updates ifmultiple entries are selected).

Closing themodel clears the entries in the Output window. An entry in the Output windowis also cleared as and when you roll-back the update for it.

This functionality is invoked automatically as part of the Get All Latest operation.

When working in an environment that uses a Private Model deployment and your modelcontains a significant number of cross-package references, it is recommended that youinvoke this function from time to time, following the re-importation of controlled packages- for example, after using Get Latest to update a number of packages, or after performinga number of package check-outs.

• As a general rule, avoid running this function while you have uncommitted changesin your model

• Generally, you should:– Check-out a number of packages– Invoke ScanXMIAndReconcile– Make your modifications– Commit any outstanding changes before you check-out more packages and runScanXMIAndReconcile again

void VersionControlResynchPkgStatuses (bool ClearSettings) —Synchronizes the version control status of each version controlled package within thecurrent model with the status reported by your version control provider.

Page 60: Scripting EA

Object Details 53

If ClearSettings == True, clear the version control settings from packages that arereported by the version control provider as uncontrolled. Else leave the version controlsettings unchanged for packages reported as uncontrolled

Package Build Scripts

void ExecutePackageBuildScript (long ScriptOptions, string PackageGUID) —Enables you to run the active package build script where ScriptOptionmeans:

1 = Build, 2 = Test, 3 = Run, 4 = Create Workbench Instance, 5 = Debug

If PackageGUID is supplied the run is taken for the EaPackagewith that specific GUID. Elsethe current selection in the Project Browser is taken.

void ImportPackageBuildScripts (string PckGUID, string BuildScriptXML) —Imports the build script BuildScriptXML into the EaPackage with the PackageGUID equalto PckGUID in Enterprise Architect.

The build script XML data have the format that can also be exported fromwithin EnterpriseArchitect

Misc

EADocumentGenerator CreateDocumentGenerator —Returns a pointer to the EADocumentGenerator⁸ interface.

string CustomCommand (string ClassName, string MethodName, string Parameters) —This undocumented internal operation can be used for a variety of things.

• Synchronize tagged values but that has been replaced by dedicated operations.• Import reference data (see sample below):

1 Repository.CustomCommand ("Repository", "ImportRefData", <xml>);

where <xml> is the xml data which you can find in the exported reference data files.• Open property dialogues (see section above).• A lot of other fancy things unfortunately not uncovered yet.

UndocumentedAs already mentioned this is not an official API operation. So use it on your own risk.

string Execute (string SQL) —Executes a non-SELECT SQL (i.e. INSERT, UPDATE, DELETE) on the underlying database.It is used to perform any dirty manipulation of the repository. Note that the SQL is passeddirectly to the underlying database without any pre-processing. That means, you have totake precautions to supply a correct SQL string. Usually you will deal with at most twodifferent formats: MS Access for the .EAP files and the dialect for your RDBMS. So incase you need to differentiate SQL strings it is necessary to check the used repository viaEaRepository.ConnectionString.

⁸This is new with V10 of EA and will be described in one of the next releases of this book.

Page 61: Scripting EA

Object Details 54

UndocumentedYes, this is an undocumented and therefore unsupported operation. Simply forgetasking Sparx support if you clobbered your repository with this operation. However,it’s your ejection seat when nothing else helps.

string GetCounts () —Returns a set of counts from a number of tables within the base Enterprise Architectrepository. These can be used to determine whether records have been added or deletedfrom the tables for which information is retrieved.

string GetFieldFromFormat (string Format, string Text) —Converts the value Text from the Format ‘HTML’, ‘RTF’ or ‘TXT’ to Enterprise Architect’sinternal format.

Use this to convert strings before placing them into arbitrary Note fields of EA’s objects.

string GetFormatFromField (string Format, string Text) —The reverse for the previous operation.

Use this to convert strings from arbitrary Note fields of EA’s objects into the desiredformats.

MailInterface GetMailInterface —Returns an instance of the EAMailIinterface⁹ ; use this interface to automate the processof creating and sending model mail messages.

EaCollection GetReferenceList (string Type) —For each Type a EaCollection of strings corresponding to EaObjectTypes is returned¹⁰.

Valid values for Type are Diagram, Element, Constraint, Requirement, Connector,

Status, Cardinality, Effort, Metric, Scenario, Status and Test.

string InvokeConstructPicker (string ElementFilter) —Invokes the Select <Item> dialog with filters on the object type and, optionally, stereotype.Returns the ElementID of the selected object, or 0 if no object was selected when the dialogwas closed.

ElementFilter specifies which elements or packages are to bemade available for selection.Its format is either IncludedTypes=<types> or IncludedTypes=<types>;StereoType=<stereo>.The first form will filter only the specified element types while the second form willadditionally filter for stereotypes.

<types>:A comma separate list of values listed in section Element Types. Additionally youcan specify Package if you want to select a package.

⁹This is new with V10 of EA and will be described in one of the next releases of this book.¹⁰I have no idea for what you can use this reference. It looks somehow like what can be contained in Type.

Page 62: Scripting EA

Object Details 55

<stereo>:A comma separate list stereotypes.

Do not use leading or trailing spaces between element type or stereotype values.

StereoType and IncludedTypes must be written with the correct case; element typenames are also case sensitive.

string InvokeFileDialog (string FilterString, long Filterindex, long Flags) —Opens the Standard Open Dialog and returns a string on success.

void SaveAllDiagrams () —Saves all changes made in open diagrams.

void SaveDiagram (long ID) —Saves the changes made to the open EaDiagram matching its DiagramID with ID.

void WriteOutput (string Name, string String, long ID) —Writes String to the tab Name in the Output window, and associates the text with an ID¹¹.

5.2 EaPackage

Attributes

string Alias r/o —The Alias property value.

bool BatchLoad —The Batch Load property value.

bool BatchSave —The Batch Save property value.

EaCollection Connectors —An EaCollection of EaConnector objects linked to this package.

DateTime Created —The date when the package was created property value.

EaCollection Diagrams —An EaCollection of diagrams inside the package.

EaElement Element —The EaPackage Element for the package.

¹¹I can’t recall where this ID can be used (e.g. a double click on the text line). So simply supply a constant number.

Page 63: Scripting EA

Object Details 56

EaCollection Elements —An EaCollection of EaElement objects contained in the package. This list is not recursive.That means that elements in sub-packages must be retrieved from those.

string Flags —For view packages this is a semi-colon separated list isModel=1;VICON=1;. This tells youthat the package is actually a view and it’s icon (which you see as different from a regularpackage) corresponds to the values 0..5 according to the Set View Icon from the contextmenu. The Flags property is obviously only used in the context of views.

For version controlled packages you will find something like Recurse=0;VCCFG=<VC>;

where <VC> is the unique ID of the appropriate Version Control provider.

bool IsControlled —The Control Package property value.

bool IsModel —If non-zero this is a root package.

bool IsNamepace —Is the equivalent to the context menu Code Engineering.../Set as Namespace Root.

bool IsProtected —Actually this property is used nowhere in the GUI.

bool IsVersionControlled —Indicates whether the package is configured for Version Control and has a VC system set.

DateTime LastLoadDate —Used in conjunction with version control and tells when the package was loaded fromXML the last time.

DateTime LastSaveDate —Used in conjunction with version control and tells when the package was saved to XMLthe last time.

bool LogXML —The Log Import/Export property value.

DateTime Modified —The date when the package was modified property value. Note that the EA documentationsays this field is read/write. However, it is not possible to modify this field. It isautomatically updated if a change has been made to any of the other attributes.

string Name —The Name property value.

string Notes —The Notes property value.

Page 64: Scripting EA

Object Details 57

long ObjectType r/o —Constant value 5 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

string Owner —The Owner property value.

string PackageGUID r/o —The GUID property property value.

EaRepository.GetPackageByGUID (PackageGUID) will return the very package.

long PackageID —The primary key under which the package is identified in the model. This identifier is validfor the repository only.

EaRepository.GetPackageByID (PackageID) will return the very package.

Collection Packages —An EaCollection of packages contained inside this package. This is used to traverse therepository tree.

long ParentID —The PackageID of this package’s parent. Zero in the case of a root package.

long TreePos —See the section about ordering for details.

string UMLVersion —The UML/XMI Type property value.

bool UseDTD —The Use DTD property value.

string Version —The Version ID property value.

string XMLPath —The XMI Filename property value.

Operations

bool ApplyGroupLock (string GroupName) —Applies a group lock for GroupName to the element object on behalf of the current user.

Throws an exception if the operation fails; use GetLastError() to retrieve error information.

bool ApplyUserLock () —Applies a user lock to the element object for the current user.

Throws an exception if the operation fails; use GetLastError() to retrieve error information.

Page 65: Scripting EA

Object Details 58

EaPackage Clone —Inserts a copy of the package into the same parent as the original package and returns thenewly-created package.

LDISPATCH FindObject (string DottedID) —Returns a package, element, attribute or operation matching the parameter DottedID,being a string in the form object.object.object where object is replaced by the name ofa package, element attribute or operation, e.g. MyNamespace.Class1, CStudent.m_Name,MathClass.DoubleIt(int).

If the DottedID is not found, NIL is returned; use GetLastError() to retrieve errorinformation.

bool ReleaseUserLock () —–Releases a group lock or user lock from this package object.

Returns true if the operation is successful; returns false if the operation is unsuccessful.Use GetLastError() to retrieve error information.

void SetReadOnly (bool ReadOnly, bool IncludeSubPkgs) —Sets a Package Flag to mark a package conditionally as read only.

If ReadOnly == false, any Read Only flag is removed from the package. Else a Read Onlyflag is applied to the package.

IncludeSubPkgs indicates whether to set/reset the Read Only flag on just the objectpackage (== false), or on the object package and all of the nested sub-packages that itcontains (== true).

If Project Security is enabled, the user must have Configure Packages permission to usethis operation. If you are prevented from editing the package, you are also prevented fromsetting the flag.

Throws an exception if the operation fails due to the user not having Configure Packagespermission; use GetLastError() to retrieve error information.

When working with version controlled packages, the Read Only flag can be applied topackages whether they are checked-in or checked-out.

void VersionControlAdd (string Cfg, string XML, string Comment, bool Keep) —Places the package under version control. Cfg is the name corresponding to the UniqueID of the version control configuration to use. XML is the name of the XML file to use forthis package; this filename is relative to the Working Copy folder specified for the Config.Comment is the log message that is added to the version controlled file’s history (whereapplicable). Keep specifies whether to keep the package checked-out.

Throws an exception if the operation fails; use GetLastError() to retrieve error informa-tion.

It is recommended that the package be saved using Update() before calling VersionCon-trolAdd(), so that any outstanding changes are not lost.

void VersionControlCheckin (string Comment) —Perform checkin of the version controlled package (also see VersionControlCheckinEx,

Page 66: Scripting EA

Object Details 59

below). Comment is the log message that is added to the version controlled file’s history(where applicable).

Throws an exception if the operation fails; use GetLastError() to retrieve error informa-tion.

void VersionControlCheckinEx (string Comment, bool PreserveCrossPkgRefs) —Perform checkin of the version controlled package. Comment is the logmessage that is addedto the version controlled file’s history (where applicable). PreserveCrossPkgRefs indicateswhether to preserve or discard pre-existing Cross Package References when checking-in; this parameter overrides the setting in the Options dialog, XML Specifications page.Unsatisfied cross package references are preserved or discarded according to this setting,without prompting the user.

Throws an exception if the operation fails; use GetLastError() to retrieve error informa-tion.

void VersionControlCheckout (string Comment) —Perform checkout of the version controlled package. Comment is the log message that isadded to the version controlled file’s history (where applicable).

Throws an exception if the operation fails; use GetLastError() to retrieve error informa-tion.

When working in an environment that uses a Private Model deployment and your modelcontains a significant number of cross-package references, it is recommended that youinvoke the EaRepository.ScanXMIAndReconcile() operation (see below) from time totime, following the re-importation of controlled packages - for example, after usingVersionControlGetLatest() below to update a number of packages, or after performinga number of package check-outs.

void VersionControlGetLatest (bool ForceImport) —Updates the local working copy of the package file associated with the object package,before re-importing the package data from the package file. If ForceImport == false,the package data that exists in the model is accepted as being up-to-date and no attemptis made to re-import data from the package file. Else Enterprise Architect re-imports thepackage from the package file regardless.

When working in an environment that uses a Private Model deployment and your modelcontains a significant number of cross-package references, it is recommended that youinvoke the EaRepository.ScanXMIAndReconcile() operation from time to time, followingthe re-importation of controlled packages — for example, after using VersionControlGet-Latest()‘ to update a number of packages, or after performing a number of package check-outs.

long VersionControlGetStatus () —Returns the version control status of the package, as recorded in the current EnterpriseArchitect project database.

Throws an exception if the operation fails; use GetLastError() to retrieve error informa-tion.

Page 67: Scripting EA

Object Details 60

Return value maps to the following enumerated type:

1 enum EnumCheckOutStatus

2 {

3 csUncontrolled = 0,

4 csCheckedIn,

5 csCheckedOutToThisUser,

6 csReadOnlyVersion,

7 csCheckedOutToAnotherUser,

8 csOfflineCheckedIn,

9 csCheckedOutOfflineByUser,

10 csCheckedOutOfflineByOther,

11 csDeleted

12 };

where

csUncontrolled —Either unable to communicate with the version control provider associated with thepackage or the package file is unknown to the provider.

csCheckedIn —The package is not checked-out to anybody in the current project database.

csCheckedOutToThisUser —The package is marked as checked-out to the current user, in the current projectdatabase.

csReadOnlyVersion —Package is marked as read-only; an earlier revision of the package has been retrievedfrom version control.

csCheckedOutToAnotherUser —The package is marked as checked-out in the current project database, by a user otherthan the current user.

csOfflineCheckedIn —The package is not checked-out to anybody in the current project database; however,the version control configuration associated with the package was unable to connectto the VC server.

csCheckedOutOfflineByUser —Indicates that the package was ‘checked out’ in this database, by this user, whilstdisconnected from version control.

csCheckedOutOfflineByOther —Indicates that the package was checked out in this project database, by another user,whilst disconnected from version control.

csDeleted —The package file has been deleted from version control.

Page 68: Scripting EA

Object Details 61

void VersionControlPutLatest (string CheckInComment) —Perform a checkin of the version controlled package, whilst keeping the package checked-out. Comment is the log message that is added to the version controlled file’s history (whereapplicable).

Throws an exception if the operation fails; use GetLastError() to retrieve error informa-tion.

When a package that was previously marked as Checked Out Offline, is successfully ‘Put’(checked-in) to version control, that package’s flags are updated to clear the Checked OutOffline indicator.

void VersionControlRemove () —Removes version control from the package.

Throws an exception if the operation fails; use GetLastError() to retrieve error informa-tion.

void VersionControlResynchPkgStatus(bool ClearSettings) —Synchronizes the version control status of the single object package recorded in yourcurrent model with the package status reported by your version control provider. IfClearSettings == true, the version control settings are cleared from the package. Elsethe version control settings remain unchanged.

5.3 EaElement

Attributes

There are a number of properties which only have meaning with specific elements or in specificcircumstances.

bool Abstract —The Abstract property value.

string ActionFlags —EA help: A structure to hold flags concerned with Action semantics.

I have no idea where this is used in the GUI.

string Alias —The Alias property value.

long AssociationClassConnectorID r/o —If the element is an AssociationClass, this contains the EaConnector.ConnectorID of therespective Association connector.

Collection Attributes —An EaCollection of EaAttribute objects for the current element.

Page 69: Scripting EA

Object Details 62

Collection AttributesEx —Like Attributes but including inherited attributes.

string Author —The Author property value.

EaCollection BaseClasses —An EaCollection of EaElement objects representing the Base Classes for this element.

Derived from the elements to which this element points via a generalization connector.

long ClassifierID —EaElement.ElementID of the classifier for this element (if not zero). Only valid for instancetype elements (such as Object or Sequence).

string ClassifierName —For convenience the EaElement.Name property of the classifying element.

string ClassifierType —For convenience the EaElement.Type property of the classifying element.

string Complexity —The Complexity property value. Valid values are: 1 for Easy, 2 for Medium, 3 for Difficult.

EaDiagram CompositeDiagram —If the element is composite, returns its associated EaDiagram; otherwise returns null.

EaCollection Connectors —Returns a EaCollection containing the EaConnector objects to other elements.

Note that this collection list incoming and outgoing connectors.

EaCollection Constraints —An EaCollection of EaConstraint. See also the Constraints property values.

EaCollection ConstraintsEx —Like Constraints but includes also objects from inherited classes.

DateTime Created —The date when the element was created property value.

EaCollection CustomProperties —An EaCollection of EaKeyValue objects.

The collection of advanced properties differs depending on element type. For example, anAction and an Activity have different advanced properties.

Currently only editable from the user interface. EA will crash if you try to add somethingto this collection.

EaCollection Diagrams —An EaCollection of EaDiagram objects inside the element.

Page 70: Scripting EA

Object Details 63

string Difficulty —The Difficulty property (Requirements-like elements only).

Valid values are: Low, Medium, High.

EaCollection Efforts —An EaCollection of EaEffort objects inside the element.

string ElementGUID —The GUID property value of the element.

EaRepository.GetElementByGUID (ElementGUID) will return the very element.

long ElementID —The primary key under which the element is identified in the model. This identifier is validfor the repository only.

EaRepository.GetElementByID (ElementID) will return the very element.

EaCollection Elements —An EaCollection of EaElement objects contained in the element. This list is not recursive.That means that elements in sub-elements must be retrieved from those.

EaCollection EmbeddedElements —An EaCollection of embedded EaElement objects contained in the element. This list isalso not recursive.

string EventFlags —Semi-colon separated attribute list with links into the Risk/Metrics/etc. tables

string ExtensionPoints —Optional extension points for a Use Case as a comma-separated list.

Editable via diagram context Advanced/Edit Extension Points....

EaCollection Files —An EaCollection of Files objects.

string GenFile —The Filename property value. The file associated with this element for code generationand synchronization purposes; can include macro expansion tags for local conversion tofull path.

string Genlinks —Links to other Classes discovered at code reversing time; Parents and Implements connec-tors only.

Not found in the GUI directly.

string GenType —The Language property value. Note that this value does not appear unless it is defined asProduct in the Language Datatypes

Page 71: Scripting EA

Object Details 64

string Header1 —The Import(s)/Header(s) property value (first box).

string Header2 —The Import(s)/Header(s) property value (second box).

bool IsActive —The Is Active property value.

bool IsComposite —Indicates whether the element is composite (via context menu Advanced/Make Composite)or not.

bool IsLeaf —The Is Leaf property value.

bool IsNew —bool value indicating whether the element is new or not.

I have no idea where this is used in the GUI.

bool IsSpec —The Is Specification property value.

EaCollection Issues —An EaCollection of EaIssue objects.

bool Locked —Indicates if the element has been locked against further change. This attribute is onlyevaluated set when security is enabled.

string MetaType —The element’s domain-specific meta type, as defined by an applied stereotype from anMDG Technology.

EaCollection Methods —An EaCollection of EaMethod objects.

EaCollection MethodsEx —Same as Methods but additional includes inherited operations.

EaCollection Metrics —An EaCollection of EaMetrics objects.

string MiscData —This property returns the t_object.PDatax columns (see my book Inside EA). For somescripting languages these values are not supplied so you need to query the database directlyinstead.

Page 72: Scripting EA

Object Details 65

DateTime Modified —The date when the element was modified property value. Note that the EA documentationsays this field is read/write. However, it is not possible to modify this field. It isautomatically updated if a change has been made to any of the other attributes.

string Multiplicity —The Multiplicity property value.

string Name —The Name property value.

string Notes —The Notes property value.

long ObjectType r/o —Constant value 4 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long PackageID —The PackageID of the EaPackage containing this element.

long ParentID —If this element is a child of another, used to set or retrieve the EaElementID of the otherelement; if not, contains 0.

EaCollection Partitions —An EaCollection of EaPartition objects.

Only valid for elements that support partitions, such as Activities and States. Defined withAdvanced/Set Concurrent Substates....

string Persistence —The Persistence property value.

string Phase —The Phase property value.

string Priority —The Priority property value. Valid values are: Low, Medium and High.

EaCollection Properties —An EaCollection of EaProperty objects. See also the Properties property.

The properties are purposely undocumented because of their obscure nature and becausethey are subject to change as progressive enhancements are made to them.

long PropertyType —The EaElement.ElementID of a Type associated with this element; only valid for Port andPart elements.

Page 73: Scripting EA

Object Details 66

EaCollection Realizes —An EaCollection of Interface (elements) realized by this element for convenience. It isalso possible to retrieve these via the Connectors property.

EaCollection Requirements —An EaCollection of EaRequirement objects. See also the Requirements property.

EaCollection RequirementsEx —Same as Requirements but including requirements of inherited classes.

EaCollection Resources —An EaCollection of EaResource objects.

EaCollection Risks —An EaCollection of EaRisk objects.

string RunState —A run state which represents the values defined via Advanced/Set Run State....

EaCollection Scenarios

The Scenarios property returned as EaCollection.

EaCollection StateTransitions —An EaCollection of EaStateTransitions objects. Applies in particular to Timing ele-ments.

string Status —The Status property value.

string Stereotype —The Stereotype property value.

string StereotypeEx —All the applied stereotypes of the element in a comma-separated list.

string StyleEx —Advanced style settings; reserved for the use of Sparx Systems.

long Subtype —A numeric SubType that qualifies the Type of the main element.

string Tablespace —Associated tablespace for a Table element.

string Tag —The Keywords property value.

EaCollection TaggedValues —An EaCollection of EaTaggedValue objects.

EaCollection TaggedValuesEx —Same as TaggedValues but including tagged values of inherited classes.

Page 74: Scripting EA

Object Details 67

long TreePos —See the section about ordering for details.

EaCollection Tests —An EaCollection of EaTest objects.

string Type —The Type value. Can be one of the element type property string values.

string Version —The Version property value.

bool Visibility —The Scope property value.

Operations

bool ApplyGroupLock (string GroupName) —Applies a group lock for GroupName to the element object, for the specified group, on behalfof the current user.

Throws an exception if the operation fails; use GetLastError() to retrieve error information.

bool ApplyUserLock () —Applies a user lock to the element object for the current user.

Throws an exception if the operation fails; use GetLastError() to retrieve error information.

bool CreateAssociationClass (long ConnectorID) —Makes this element an AssociationClass of the Association with the provided ConnectorIDof the relevant EaConnector. The return value indicates whether the function succeededin converting the element to an AssociationClass.

AssociationClasses are created only where:

• The current element is valid• The current element is a Class• The current element is not already an AssociationClass• The specified connector exists• The specified connector is an Association• The specified connector is not already in an AssociationClass pair• The current element is not at either end of the specified connector

string GetLinkedDocument () —Returns a string value containing the element’s linked document contents, in RTF format.

If the element contains no linked document, an empty string is returned.

string GetRelationSet (short Type) —Returns a string containing a comma-separated list of EaElement.ElementIDs of directlyand indirectly related elements based on the given Type.

Page 75: Scripting EA

Object Details 68

Recurses using the same relation type on all elements it finds, retrieving all dependenciesand sub-dependencies of the current element. For example, Object1 depends on Object2,which depends on Object3, therefore this operation returns Object2 and Object3.

To obtain only the direct relationships of the element, use the Connectors collectioninstead.

string GetStereotypeList () —EA help:Returns a comma-separated list of stereotypes allied to this element.

This returns the same contents as the StereotypeEx attribute.

bool IsAssociationClass —Returns whether or not the current element is an AssociationClass.

bool LoadLinkedDocument (string Filename) —Loads the RTF document from the specified Filename into the element’s linked document.

void Refresh () —Refreshes the element features in the Project Browser.

Usually called after adding or deleting attributes or operations, when the user interface isrequired to be updated as well.

bool ReleaseUserLock () —Releases a user lock or group lock on the element object.

Throws an exception if the operation fails; use GetLastError() to retrieve error information.

bool SaveLinkedDocument (string Filename) —Saves the linked document for this element to the specified Filename.

void SetAppearance (long Scope, long Item, long Value) —Sets the visual appearance of the element. Scopemust be set fixed to 1. The Value is appliedto the Item

0 – Background color, 1 – Font Color, 2 – Border Color and 3 – Border Width.

To set appearance for the element in a selected diagram only, see EaDiagramObject.Style.

bool UnlinkFromAssociation —Performs the opposite of CreateAssociationClass().

5.4 EaAttribute

bool AllowDuplicates —The Allow Duplicates property value.

If the attribute represents a database column this, when set, represents the Not Null option.

string AttributeGUID —The GUID property value of the attribute.

EaRepository.GetAttributeByGUID (AttributeGUID) will return the very attribute.

Page 76: Scripting EA

Object Details 69

long AttributeID —The primary key under which the attribute is identified in the model. This identifier isvalid for the repository only.

EaRepository.GetAttributeByID (AttributeID) will return the very attribute.

ClassifierID —EaElement.ElementID of the classifier for this element (if not zero).

string Container —The Container property value.

Containment —The Containment property value.

Valid values: Not Specified, By Reference or By Value.

Collection Constraints —An EaCollection of EaAttributeConstraint objects.

Default —The Initial Value property value.

bool IsCollection —The Attribute is a Collection property value. If the attribute represents a database columnthis, when set, represents a Foreign Key.

IsConst —The Const property value.

IsDerived —The Derived property value.

IsOrdered —The OrderedMultiplicity property value. If the attribute represents a database column this,when set, represents a Primary Key.

IsStatic —The Static property value. If the attribute represents a database column this, when set,represents the Unique option.

Length —The Length property value.

LowerBound —The Lower bound property value.

string Name —The Name property value.

Notes —The Notes property value.

Page 77: Scripting EA

Object Details 70

long ObjectType r/o —Constant value 23 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long ParentID —EaElement.ElementID of the element this attribute is part of.

long Pos —The position of the attribute in the Class attribute list as ordered in the GUI.

string Precision —The Precision property value.

string Scale —The Scale property value.

string Stereotype —The Stereotype property value.

string StereotypeEx —Provides all the applied stereotypes of the attribute, in a comma-separated list.

Style —The Alias¹² property value.

StyleEx —EA help: Advanced style settings, reserved for the use of Sparx Systems.

If you define an attribute for a≪enumeration≫ classes this contains something like

IsLiteral=1;volatile=0;

reflecting the Is Literal property.

Collection TaggedValues —An EaCollection of TaggedValue objects.

Collection TaggedValuesEx —Same as TaggedValues but includes inherited tags too.

Type —The Type property value. If ClassifierID is not zero this is the name of the accordingclassifier.

UpperBound —The Upper bound property value.

Visibility —The Scope property value.

¹²sic!

Page 78: Scripting EA

Object Details 71

5.5 EaMethod

bool Abstract —The Abstract property value.

string Behavior —The Behavior property value.

DeprecationIn earlier releases of Enterprise Architect this attribute had the UK/Australian spelling‘Behaviour’; this is still present for backwards compatibility, but please now use the‘Behavior’ attribute for consistency.

long ClassifierID —EaElement.ElementID of the classifier for the return type.

string Code —The Initial Code property value.

string Concurrency —The Concurrency property value.

bool IsConst —The Const property value.

bool IsLeaf —A flag to indicate if the operation is Leaf (cannot be overridden).

I have no idea where this flag appears in the GUI.

bool IsPure —The Pure property value.

bool IsQuery —The Is Query property value.

bool IsRoot —A flag to indicate if the operation is Root.

I have no idea where this flag appears in the GUI. Obviously it is only used withtransformation. The database column it t_object.IsRoot.

bool IsStatic —The Static property value.

bool IsSynchronized —The Synchronized property value.

Page 79: Scripting EA

Object Details 72

string MethodGUID r/o —The GUID property value of the operation.

EaRepository.GetMethodByGUID (MethodGUID) will return the very operation.

long MethodID r/o —The primary key under which the operation is identified in the model. This identifier isvalid for the repository only.

EaRepository.GetMethodByID (MethodID) will return the very operation.

string Name —The Name property value.

string Notes —The Notes property value.

long ObjectType —Constant value 24 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

EaCollection Parameters —An EaCollection of EaParameter objects.

long ParentID —EaElement.ElementID of the element this operation is part of.

long Pos —The position of the operation in the Class operation list as ordered in the GUI.

EaCollection PostConditions —An EaCollection of EaPostCondition objects.

EaCollection PreConditions —An EaCollection of EaPreCondition objects.

bool ReturnIsArray —The Return Array property value.

string ReturnType —The Return Type property value.

string StateFlags —EA help: Some flags as applied to methods in State elements.

I have no idea where these flags are used in the GUI.

string Stereotype —The Stereotype property value.

string StereotypeEx —Provides all the applied stereotypes of the attribute, in a comma-separated list.

Page 80: Scripting EA

Object Details 73

string Style —The Alias¹³ property value.

string StyleEx —Advanced style settings, reserved for the use of Sparx Systems.

Eventually contains ShowBeh=1;.

EaCollection TaggedValues —An EaCollection of TaggedValue objects.

string Throws —Exception information.

I have no idea where these flags are used in the GUI.

string Visibility —The Scope property value.

5.6 EaParameter

string Alias —The Alias property value.

long ClassifierID —EaElement.ElementID of the classifier for the parameter or zero if not defined.

string Default —The Default property value.

bool IsConst —The Fixed Value property value.

string Kind —The Direction property value.

Values: in, inout, out or return.

string Name —The Name property value.

string Notes —The Notes property value.

long ObjectType r/o —Constant value 25 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long OperationID —EaMethod.MethodID of the operation this parameter is part of.

¹³No, sick!

Page 81: Scripting EA

Object Details 74

string ParameterGUID —The GUID property value of the parameter.

There is no getter in the Repository to retrieve a parameter.

long Position —The position of the parameter in the parameter list as ordered in the GUI.

string Stereotype —The Stereotype property value.

string StereotypeEx —Provides all the applied stereotypes of the parameter, in a comma-separated list.

string Style —EA help: Some style information.

Well, at least it’s not the Alias. But what is it?

string StyleEx —Advanced style settings, reserved for the use of Sparx Systems.

EaCollection TaggedValues —An EaCollection of TaggedValue objects.

string Type —The Type property value.

5.7 EaConnector

string Alias —The Alias property value.

EaConnectorEnd ClientEnd r/o —An EaConnectorEnd object holding information about the client properties. The objectitself is immutable, but you can supply its properties for an Update.

long ClientID —The EaElement.ElementID indicating the target of the connector.

long Color —A numeric RGB value for the connector default color.

string ConnectorGUID r/o —The GUID of the connector.

EaRepository.GetConnectorByGUID (ConnectorGUID) will return the very connector.

long ConnectorID —The primary key under which the connector is identified in the model. This identifier isvalid for the repository only.

EaRepository.GetConnectorByID (ConnectorID) will return the very connector.

Page 82: Scripting EA

Object Details 75

EaCollection Constraints —An EaCollection holding information about the constraints of the connector.

EaCollection ConveyedItems —An EaCollection of EaElement objects which are conveyed by the connector. This appliesto Information Flow connectors only.

EaCollection CustomProperties —An EaCollection of custom Properties objects.

long DiagramID —The primary key of the EaDiagramwhere this connector appears. Applies only for sequencemessages.

string Direction —The Direction property value. Possible values are Unspecified, Bi-Directional, Source

-> Destination and Destination -> Source.

long EndPointX —The X-coordinate end of a sequence message.

long EndPointY —Same for Y-end.

string EventFlags —Actually this seems to be always null. EA help: A structure to hold a variety of flagsconcerned with event signaling on messages.

bool IsLeaf —Also this seems to be some kind of heritage.

bool IsRoot —ditto

bool IsSpec —ditto

string MetaType —The connector’s domain-specific meta type, as defined by an applied stereotype from anMDG Technology

string MiscData —Corresponds to the t_connector.PDATAx columns. See my book Inside EA for details.

string Name —The Name property value.

string Notes —The Notes property value.

Page 83: Scripting EA

Object Details 76

long ObjectType r/o —Constant value 7 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

EaCollection Properties —An EaCollection of Properties objects. These appear different for messages. Basicallythese properties are available as key-value pairs.

EA help: The properties are purposely undocumented because of their obscure nature andbecause they are subject to change as progressive enhancements are made to them.

For messages some of these properties mean:

Kind:Callor Signal representing the Kind property.

IsReturn:0 or 1 representing the IsReturn property.

IsAsynch:0 (Synchronous) or 1 (Asynchronous) representing the Synch property.

<arg> is the Argument(s) property and

long RouteStyle —Actually I have no idea what this value means. You can change it and it is different forsome connectors. But it has nothing to do with the connector’s appearance.

long SequenceNo —The sequence in which the connector appears. This only applies for sequence messages.

long StartPointX —See EndPointX above.

long StartPointY —ditto

string StateFlags —For Collaboration connectors: a semi-colon separated list like isReturn=true/false;

reflecting the Message/Control Flow Type/Is Return property Advanced settings forSequence connectors.

string Stereotype —The Stereotype property value.

string StereotypeEx —All the applied stereotypes of the connector in a comma-separated list.

string StyleEx —EA help: Advanced style settings; reserved for the use of Sparx Systems. See also Inside EA.

For messages this contains paramvalues=<arg>;alias=<alias>; where <arg> is theArgument(s) property and <alias> is (a copy of) the Stereotype property.

Page 84: Scripting EA

Object Details 77

string Subtype —EA help: A possible subtype to refine the meaning of the connector.

Contains blank, New or Delete representing the Lifecycle property.

EaConnectorEnd SupplierEnd —See ClientEnd above.

long SupplierID —The EaElement.ElementID indicating the start of the connector.

EaCollection TaggedValues —An EaCollection of TaggedValue objects.

string TransitionAction —The Effect property value.

string TransitionEvent —The Specification property value.

string TransitionGuard —The Guard property value.

Formessages this contains retval=<retval>;params=;paramsDlg=<attr>;retatt=<retatt>;where <retval> is the Return Value property, <attr> the Attributes property and <retatt>the Assign To property.

string Type —The connector type; valid types are held in the t_connectortypes table in the repository.

string VirtualInheritance —The Virtual Inheritance property value.

long Width —Specifies the width of the connector.

EaConnectorEnd

long Aggregation —The type of Aggregation as it applies to this end; valid values are:

0 = None, 1 = Shared, 2 = Composite

string Alias —An optional alias for this connector end.

bool AllowDuplicates —For multiplicities greater than 1, indicates that duplicate entries are possible.

string Cardinality —The cardinality associated with this end.

Page 85: Scripting EA

Object Details 78

string Constraint —A constraint that can be applied to this connector end.

string Containment —The containment type applied to this connector end.

bool Derived —Indicates that the value of this end is derived.

bool DerivedUnion —Indicates the value of this role derived from the union of all roles that subset this.

string End r/o —The end this object applies to - Client or Supplier.

string IsChangeable —Flag indicating whether this end is changeable or not - frozen, addOnly or none.

bool IsNavigable —A flag indicating this end is navigable from the other end.

string Navigable —Indicates whether this role of an association is navigable from the opposite classifier -Navigable, Non-Navigable or Unspecified.

long ObjectType r/o —Constant value 22 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long Ordering —Ordering for this connector end.

bool OwnedByClassifier —Indicates that this Association end corresponds to an attribute on the opposite end of theAssociation.

string Qualifier —A qualifier that can apply to the connector end.

string Role —The connector end role.

string RoleNote —Notes associated with the role of this connector end.

string RoleType —The role type applied to this end of the connector.

string Stereotype —The stereotype applied to this connector end.

Page 86: Scripting EA

Object Details 79

string StereotypeEx —All the applied stereotypes of the connector end in a comma-separated list.

EaCollection TaggedValues —A collection of EaTaggedValue objects with ObjectType == RoleTag.

string Visibility —The Scope associated with this connector end - Public, Private, Protected or Package.

5.8 EaDiagram

Attributes

string Author —The Author property value.

DateTime CreatedDate —The Created property value.

long cx —The width of the diagram (the default is 800). If you increase this value the pan and zoomshows a smaller preview of the diagram.

long cy —Same for the height (default 1100).

string DiagramGUID r/o —The GUID of the diagram.

EaRepository.GetDiagramByGUID (DiagramGUID) will return the very diagram.

long DiagramID —The primary key under which the diagram is identified in the model. This identifier isvalid for the repository only.

EaRepository.GetDiagramByID (DiagramID) will return the very diagram.

EaCollection DiagramLinks —An EaCollection of EaDiagramLink objects.

EaCollection DiagramObjects —An EaCollection of EaDiagramObject objects.

string ExtendedStyle —Corresponds to the t_diagram.PDATA column. See Inside EA for more details.

bool HighlightImports —The Show Namespace property value.

Page 87: Scripting EA

Object Details 80

bool IsLocked —A flag indicating whether this diagram is locked or not. Usually this flag is used inconjunction with security and locking. But you may set this also without security (thisis not possible via a GUI!). If you have set this flag to true the diagram is locked againstaccidental changes. However, the user will see a Lock Diagram in the context menu of thediagram plane. Once you select this, the diagram is unlocked again.

string MetaType —The diagram’s domain-specific meta type, as defined by an MDG Technology.

DateTime ModifiedDate —TheModified property value. Note that the EA documentation says this field is read/write.However, it is not possible to modify this field. It is automatically updated if a change hasbeen made to any of the other attributes.

string Name —The Name property value.

string Notes —The Notes property value.

long ObjectType r/o —Constant value 8 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

string Orientation —The Orientation property value. P for Portrait or L for Landscape.

long PackageID —The identifier of the EaPackage in which the diagram is located.

long ParentID —The identifier of an EaElement if the diagram is placed inside an element. Zero if thediagram is on package level.

long Scale —The zoom scale (the default is 100).

EaConnector SelectedConnector —The currently selected EaConnector on this diagram. Null if there is no currently selecteddiagram. If you change this value to be a connector also present on the diagram EA willselect it.

EaCollection SelectedObjects —Returns a collection representing the currently selected elements on the diagram. You canremove objects from this collection to deselect them, and add elements to the collectionby passing the Object ID as a name to select them.

bool ShowDetails —The Show Diagram Details property value.

Page 88: Scripting EA

Object Details 81

bool ShowPackageContents —The Package Contents property value.

bool ShowPrivate —The Private property value.

bool ShowProtected —The Protected property value.

bool ShowPublic —The Public property value.

string Stereotype —The Stereotype property value.

string StyleEx —Advanced style settings, reserved for the use of Sparx Systems. See also Inside EA.

EaSwimLaneDef SwimlaneDef —An object describing any swimlanes defined for the diagram.

string Type —The type of the diagram.

string Version —The Version property value.

Operations

bool ApplyGroupLock (string GroupName) —Applies a group lock for GroupName to this diagram object, on behalf of the current user.

This throws an exception if the operation fails; use GetLastError() to retrieve errorinformation.

bool ApplyUserLock () —Applies a user lock to this diagram object, for the current user.

This throws an exception if the operation fails; use GetLastError() to retrieve errorinformation.

string ReadStyle (string StyleName) —Returns the current value of StyleName for the diagram.

Valid parameters are

• Show Element Property String• Show Connector Property String• Show Feature Property String

Use GetLastError() to retrieve error information (this will usually only return that youhaven’t used one of the above string values).

Page 89: Scripting EA

Object Details 82

bool ReleaseUserLock () —Releases a group lock or user lock on this diagram object.

Throws an exception if the operation fails; use GetLastError() to retrieve error information.

void ReorderMessages () —Resets the display order of Sequence and Collaboration messages.

This is typically used after inserting or deleting messages in the diagram.

void ShowAsElementList (bool ShowAsList, bool Persist) —Toggles the diagram display between diagram and list format depending on the value ofShowAsList.

Setting Persist is the same as (un-)checkingAlwaysOpen as Element List with ShowAsListvalue.

void WriteStyle (string StyleName, string StyleValue) —Sets the StyleName to StyleValue. Opposite to ReadStyle.

5.9 EaDiagramObject

long Bottom —The bottom (Y)-coordinate of the element.

long DiagramID —The EaDiagram in which the element instance is located.

long ElementID —The identifier of the EaElement represented by this instance.

long InstanceID —The primary key to identify the diagram object in the repository. The repository does nothave a operation to access such an object directly.

long Left —The left (X)-coordinate of the element.

long ObjectType r/o —Constant value 19 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long Right —The right (X)-coordinate of the element.

long Sequence —The sequence position when loading the object into the diagram (this affects its Z order).The Z-order is one-based and the lowest value is in the foreground. EA draws the one withthe highest sequence first and overlays others successively.

Page 90: Scripting EA

Object Details 83

string Style —Used to set the style information for this object. Note that although the recent EAdocumentation forbids reading this value, it actually returns the contents of the accordingdatabase field ObjectStyle.

long Top —The top (Y)-coordinate of the element.

5.10 EaDiagramLink

long ConnectorID —The identifier of the EaConnector represented by this instance.

long DiagramID —The EaDiagram in which the element instance is located.

string Geometry —The geometry of the connector.

long InstanceID —The primary key to identify the diagram link in the repository. The repository does nothave a operation to access such an object directly.

bool IsHidden —A flag to indicate if this item is hidden or not. Analogous to Diagram/Advanced/Visible

Relations...

long ObjectType r/o —Constant value 20 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

string Path —The path of the connector with custom style which has bends. This appears as semi-colonseparated list of X:Y coordinates. E.g. for the next connector following above sample youget a semi-colon separated list 32:-313;123:-284;89:-239; which obviously representsthe three bends you can see in the association Class1-Class2.

string Style —Additional style information like color or thickness.

5.11 EaTaggedValue

The tagged values come in EaCollection objects of various EA objects. The basic object has acouple of attributes described here. Specific attributes are listed in the following sections.

string FQName r/o —The fully-qualified name of the tag. This value is only filled for tags coming from a MDG.

Page 91: Scripting EA

Object Details 84

string Name —The name of the tag.

string Notes —Further descriptive notes about this tag.

If Value attribute is set to <memo>, then Notes should contain the actual Tagged Valuecontent.

long ObjectType r/o —Distinguishes objects referenced through a Dispatch interface. Valid values from EaOb-

jectType appearing here can be

• 12: ElementTag• 34: AttributeTag• 36: MethodTag• 38: ConnectorTag• 41: RoleTag• 56: ParamTag

string Value —The value assigned to this tag.

This field has a 255 character limit. If the value is greater than 255 characters long, set thevalue to <memo> and insert the body of text in the Notes attribute (above).

When reading existing Tagged Values, if Value == <memo> then the developer should readthe actual body of text from the Notes attribute

The following tag variants have GUID named differently to confuse the reader. For these and thealso present and differently name IDs there is not get operation present in EaRepository.

Element

Attributes appearing only for those tags with ObjectType == 12.

long ElementID —The EaElement.ElementID of the associated element.

string PropertyGUID —The GUID of the tag.

long PropertyID r/o —The primary key of the tag.

Page 92: Scripting EA

Object Details 85

Attribute

Attributes appearing only for those tags with ObjectType == 34.

long AttributeID —The EaAttribute.AttributeID of the associated attribute.

string TagGUID —The GUID of the tag.

long TagID r/o —The primary key of the tag.

Method

Attributes appearing only for those tags with ObjectType == 36.

long MethodID —The EaMethod.MethodID of the associated method.

string TagGUID —The GUID of the tag.

long TagID r/o —The primary key of the tag.

Connector

Attributes appearing only for those tags with ObjectType == 38.

long ConnectorID —The EaConnector.ConnectorID of the associated connector.

string TagGUID —The GUID of the tag.

long TagID r/o —The primary key of the tag.

Role

Attributes appearing only for those tags with ObjectType == 41.

string BaseClass —Tells which source is meant.

• ASSOCIATION_SOURCE : source role• ASSOCIATION_TARGET : target role

string ElementGUID —EA help: The GUID of the connector with which this role tag is associated. However, thisappears to be 0.

Page 93: Scripting EA

Object Details 86

Parameter

Attributes appearing only for those tags with ObjectType == 56.

string ElementGUID —The GUID of the parameter with which this tag is associated.

5.12 EaRequirement

A Requirement holds information about the responsibilities of an element in the context of themodel. Requirements are accessed through the EaElement.Requirements EaCollection.

string Difficulty —The estimated difficulty of implementing the requirement.

DateTime LastUpdate —The date the requirement was last updated.

string Name —The requirement itself.

string Notes —Further notes on the requirement.

long ObjectType r/o —Constant value 9 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long ParentID r/o —The EaElement.ElementID of the element to which this requirement applies.

string Priority —The assigned priority of the requirement.

long RequirementID r/o —The primary key under which the requirement is identified in the model.

Since there is not getter available this ID is rather pointless.

string Stability —The estimated stability of the requirement.

This is an indication of the probability of the requirement - or understanding of therequirement - changing. High stability indicates a low probability of the requirementchanging.

string Status —The current status of the requirement.

Page 94: Scripting EA

Object Details 87

string Type —The requirement type.

You can use an arbitrary string. The GUI suggests the following:

• Display• Functional• Performance• Printing• Report• Testing• Validate

5.13 EaConstraint

A Constraint is a condition imposed on an element. Constraints are accessed through theEaElement.Constraints EaCollection.

string Name —The name of the constraint (that is, the constraint).

string Notes —Notes about the constraint.

long ObjectType r/o —Constant value 11 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long ParentID r/o —The EaElement.ElementID of the element to which this constraint applies.

string Status —The current status of the constraint.

string Type —The constraint type.

You can use an arbitrary string. The GUI suggests the following:

• Invariant• Post-condition• Pre-condition• Process• OCL

long Weight —A weighting factor.

Page 95: Scripting EA

Object Details 88

5.14 EaScenario

A Scenario corresponds to a Collaboration or Use Case instance. Each Scenario is a pathof execution through the logic of a Use Case. Scenarios are accessed through the EaEle-

ment.Scenarios EaCollection.

string Name —The Scenario name.

string Notes —A description of the Scenario, usually containing the steps to execute the scenario.

long ObjectType r/o —Constant value 10 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

string ScenarioGUID r/o —The GUID for the Scenario, used to identify the Scenario unambiguously within a model.

EaCollection Steps —An EaCollection of EaScenarioStep‘ objects for this Scenario.

string Type —The scenario type.

You can use an arbitrary string. The GUI suggests the following:

• Basic Path• Alternate• Exception

long Weight —Currently used to position scenarios in the scenario list (that is, List Position). sic!

string XMLContent —A structured field that can contain scenario details in XML format. It is recommended thatyou use the Steps collection to read or modify this field.

5.15 EaScenarioStep

A ScenarioStep is a single step which occurs as part of a Scenario. ScenarioSteps are accessedthrough the EaScenario.Steps EaCollection.

EaCollection Extensions —A collection of EaScenarioExtension objects that specify how the scenario is extendedfrom this step. The arguments to AddNew should match the name and GUID of thealternative scenario being linked to.

Page 96: Scripting EA

Object Details 89

string Level r/o —The number of this Step as shown in the scenario editor. This is derived from the value ofPos.

string Link —The EaElement.ElementGUID of a Use Case that is relevant to this step.

EaElement LinkedElement r/o —The actual element specified by Link, if any.

string Name —The step name.

long ObjectType r/o —Constant value 54 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long Pos —The position of the Step in the Scenario Step list.

string Results —Any results that are given from this step.

string State —A description of the state the system enters when this Step is executed.

string StepGUID r/o —The GUID for the scenario step.

short StepType —Identifies whether this step is being performed by a user or the system.

0: Identify that the step is an action performed by an actor.1: Identify that the step is an action performed by the system.

string Uses —The input and requirements that are relevant to this step.

EaCollection UsesElementList —Indicates that the Structured Specification tab Uses field is a linked element list.

5.16 EaScenarioExtension

string ExtensionGUID r/o —The GUID for this Extension.

string Join —The EaScenario.ScenarioGUID of the step where this Extension rejoins the Scenario.Empty if the scenario runs to an FlowEnd.

Page 97: Scripting EA

Object Details 90

string JoiningStep r/o —The actual step where this Extension rejoins the Scenario, if any.

string Level r/o —The number of this Extension as shown in the scenario editor. This is derived from thevalue of Pos for this object and the owning step.

string Name —EA help: The Extension name. This should match the name of the linked scenario.

However, this property is not present in the debugger and seems not to be used at all.

long ObjectType r/o —Constant value 55 from the EaObjectType enumeration. Distinguishes objects referencedthrough the Dispatch interface.

long Pos —The position of the Extension in the Extensions list.

EaScenario Scenario r/o —The EaScenario that is executed as an alternative path for this Extension.

5.17 EaCollection

This object is used to group a variable number of objects of the same type.

Attributes

short Count r/o —The number of entries in the collection; 0 if empty.

long ObjectType r/o —Value from the EaObjectType enumeration telling which EA objects are contained in thecollection.

Operations

Object AddNew (string Name, string Type) —Adds a new object to the collection.

Note that the interface is the same for all collections; you must provide a Name and Type

argument. What these are used for depends on the actual collection member.

Also note that you must call Update() on the returned object to complete the AddNew. IfUpdate() is not called the object is left in an indeterminate state.

Type can be up to 30 characters long.

Page 98: Scripting EA

Object Details 91

void Delete (short index) —Deletes the item at the selected reference.

Does not the refresh the Count of the collection.

void DeleteAt (short index, bool Refresh) —Deletes the item at the selected index. The second parameter is currently unused. However,it must be supplied.

Actually there seems to be no difference to Delete.

Object GetAt (short Index) —Returns the object at the zero-based Index.

EA help: If the index is out of bounds, an error occurs. Which is actually not the case.It simply returns NULL.

Object GetByName (string Name) —Gets an item in the current collection by Name.

• If the collection does not contain any items, the operation returns a null value.• EA : If the collection contains items, but it was unable to find an object with thespecified name, the method raises an exception. Which is actually not the case. Itsimply returns NULL.

• If multiple elements with the same name exist in the collection you will receive anarbitrary object.

Only supported for the following collections: EaPackage, EaElement, EaDiagram andEaTaggedValue for EaElement.

It is a good idea to write your own wrapper class which has a GetByName() operationimplemented for all collections and handling multiple same names in a collection.

void Refresh () —Refreshes the collection by re-querying the model and reloading the collection. Should becalled after adding a new item or after deleting an item.

5.18 EaKeyValue

As per EA documentation there is no such object. However, quite a number of objects arereturned with these properties.

string Name —The name of the item.

Page 99: Scripting EA

Object Details 92

long ObjectType r/o —Value from the EaObjectType enumeration telling which specific EaKeyValue object ismeant.

Valid values: 42: CustomProperty, 49: Property,

string Value —The value of the item.

5.19 Missing Objects

Not all EA objects are covered here, but only the most important ones. For the beginner this ismore than enough and even the advanced user will rarely have the need to go deeper than theseobjects detailed here. Probably if you are familiar with all these objects the rest will be a walkin the sunshine for you.

Page 100: Scripting EA

6. Bits and Pieces6.1 Ordering of Collections

Youwill find that the ordering of collections does notmatch that you find in EA’s project browser.Most objects have a Pos or a TPos property. Only if this is non-zero it is valid and supersedesthe occurrence in the collection. Also you will find that the browser has some rules to internallygroup packages, diagrams and elements. Further there is a Sort Features Alphabetically

option under Tools/Options/General which interferes. So if you need the same ordering as inthe browser you have to code a bit.

6.2 GUID

A GUID (Global Unique ID) has the general format

{XXXXXXXX-XXXX-xxxx-XXXX-XXXXXXXXXXXX}

where XX is a hex code with upper case chars and xx one with lower case. A GUID in contrast toother object IDs in EA is (as the name suggests) unique¹ all over the world. There are a couple ofGet<what>ByGUID operations available for the Repository class. The <what> can be Package,Element, Attribute, Method and Connector.

There’s a bit of magic in some GUID especially with that of tagged values².

6.3 Diagram Types

The following list of diagram types is available with the default UML profiles:

UseCase, Activity, State Machine, Communication, Sequence, Timing, Inter-

actionOverview, Package, Class, Object, CompositeStructure, Component,

Deployment, Custom, Requirements, Maintenance, Analysis, and DataModeling

You can also provide a diagram from a specific profile by specifying <profile>::<type> where<profile> is the name property of the profile. This can be obtained by opening the profile XMLand searching for the UMLProfile property. The next following Documentation property containsthe name attribute (in the following sample this is DiagramProfileName). Accordingly way downin the profile you find the Stereotype property for the diagram where you choose the name

attribute (here DiagramName).

¹Theoretically this varies over 216∗8 = 2128 ≈ 3 ∗ 1038 which means that you can number amounts of 3 ∗ 10−14 grams (much less thana dust grain) uniquely for the whole earth.

²I have detailed that in my book Inside EA.

Page 101: Scripting EA

Bits and Pieces 94

1 <DiagramProfile>

2 <UMLProfile profiletype="uml2">

3 <Documentation id="3CE77A01-8" name="DiagramProfileName" .../>

4 <Content>

5 <Stereotypes>

6 <Stereotype name="DiagramName" notes=.../>

6.4 Object Type Enumeration

This enumeration is used in most EA objects in the property ObjectType.

None 0 DiagramLink 20 Reference 40Project 1 Resource 21 RoleTag 41Repository 2 ConnectorEnd 22 CustomProperty 42Collection 3 Attribute 23 Partition 43Element 4 Method 24 Transition 44Package 5 Parameter 25 EventProperty 45Model 6 Client 26 EventProperties 46Connector 7 Author 27 PropertyType 47Diagram 8 Datatype 28 Properties 48Requirement 9 Stereotype 29 Property 49Scenario 10 Task 30 SwimlaneDef 50Constraint 11 Term 31 Swimlanes 51TaggedValue 12 ProjectIssues 32 Swimlane 52File 13 AttributeConstraint 33 ModelWatcher 53Effort 14 AttributeTag 34 ScenarioStep 54Metric 15 MethodConstraint 35 ScenarioExtension 55Issue 16 MethodTag 36 ParamTag 56Risk 17 ConnectorConstraint 37 ProjectRole 57Test 18 ConnectorTag 38 DocumentGenerator 58DiagramObject 19 ProjectResource 39 MailInterface 59

6.5 Element Types

The following strings³ can be used to create element via the AddNew operation at any (packageor element) level:

Action, Activity, ActivityParameter, ActivityPartition, ActivityRegion,

Actor, Artifact, Change, Class, Collaboration, Component, Decision,

DeploymentSpecification, DiagramFrame, Entity, Event, GUIElement, In-

teractionFragment, InteractionOccurrence, Interface, InterruptibleAc-

tivityRegion, Issue, Node, Object, Part, Requirement, Screen, Sequence,

State, StateNode and UseCase

³Note that all string values must be used case sensitive and without hyphens.

Page 102: Scripting EA

Bits and Pieces 95

A number of elements are not visible in the project browser:

Association, Boundary, Constraint, EmbeddedElement⁴, InteractionState,

Note, Synchronization and Text

When those are created manually (only by adding them to a diagram) EA takes care of theirfurther life time. They will be deleted when the last reference from a diagram is deleted. Butwhen you create themwithout placement in a diagram theywill lurk around in themodel foreverunseen.

Creation of the Association is further limited to package level. This is also the case for thefollowing types:

ExceptionHandler, ExpansionRegion, Report, TimeLine and UMLDiagram

The final list of element types can only appear as embedded elements. That is EA will list themin the EmbeddedElements collection of EaElement.

Furthermore (and finally) there are two more of the kind but you are only allowed to create theminside an Activity:

EntryPoint, ExitPoint, Port, ProvidedInterface and RequiredInterface

Well, a very last one is Package. You actually can create such a bastard but it does not makesense. EA will kick it out right after you (thought) you saved it. The Package is only valid andautomatically created together with an EaPackage.

It’s probably hard to digest where you are allowed to create what element and whether it appearsin the browser. The best approach is to stick to the first list in the beginning which is quite safe.Later (if needed) you can dive into the other types.

6.6 Element Subtypes

These subtypes occur in EaElement.SubType to refine the Type property.

Event0 = Receiver, 1 = Sender

Class1 = Parameterised, 2 = Instantiated, 3 = Both, 0 = Neither, 17 = Association Class

If 17, because an Association Class has been created through the user interface, Misc-Data(3) contains the ID of the related Association; as MiscData is read-only, you cannotcreate an Association Class through the Automation Interface.

⁴According to the EA help you actually can create an EmbeddedElement. But I haven’t figured out where you can actually do that as allelements refused creation of such an element.

Page 103: Scripting EA

Bits and Pieces 96

Note1 = Note linked to connector, 2 = Constraint linked to connector

StateNode100 = ActivityInitial, 101 = ActivityFinal

Activity0 = Activity, 8 = composite Activity (also set to 8 for other composite elements such as UseCases)

Synchronization0 = Horizontal, 1 = Vertical

EA help: Note that there are many more Types than indicated in the above examples.

6.7 RGB Values

Coloring values in EA have simple RGB values without transparency. Each red, blue and greenvalue can take an intensity from 0 to 255. The RGB itself is calculated by

RGB = (blue * 256 + green) * 256 + red

The default coloring is equal to -1.

6.8 Coordinates

Coordinates in diagrams are specified as Cartesian. The top left of the screen is 0|0. The x-coordinate grows and is positive. The y-coordinate diminishes and is always negative.

6.9 Semi-colon Separated List

Many attributes in EAmake use of semi-colon separated lists. Sometimes this simplymakes sensebut often you will find these being a rucksack for things found on the way. EA has extended itsfunctionality over the years quite a lot. However, the API and the underlying data model⁵ havenot been changed. Thus you will find quite some of these lists. When parsing them you cansimply split by semi-colon. So the last parameter is always an empty string. When you supplysuch a list it is not necessary to terminate with a semi-colon.

Each single parameter has the form <name>=<value>where <name> is the case sensitive parametername and <value> the according setting. It is obvious that <value> can contain any ASCIIcharacter except a semi-colon.

⁵For details see my book Inside EA.

Page 104: Scripting EA

Bits and Pieces 97

6.10 Connector StateFlags Property

Something like the following:

Activation=0;ExtendActivationUp=1;Initiate=0;StartCoregionHead=0;EndCoregionHead=0;

StartCoregionTail=0;EndCoregionTail=0;StopActivation=1;EndActivation=1;

From EaConnector.StateFlags

6.11 Width of Connectors

A numeric value corresponding to the width of a connector. 0 is the default and 1..3 are thickerlines. Interestingly you can also set 4 and 5 via automation resulting in event thicker lines thanyou can achieve manually.

6.12 Diagram Object Style

Changing the style of an element appearing on a diagram can be achieved in two ways: globally(for all diagrams) and as a supersession for a local representation in any diagram. For a globalchange use

EaElement.SetStyle(1, <item>, <value>)

where you need to supply single item/value pairs. These will be taken as default whenever theelement is used in a diagram. To overwrite those attributes in single diagrams you need to set

EaDiagramObject.Style

and supply a string which is formatted like follows.

The Style property contains a semi-colon separated list used for setting the appearance of aDiagramObject. It is set with a string value in the format:

BCol=<c>;BFol=<c>;LCol=<c>;LWth=<n>;UCRect=<b>;

where

BCol = Background ColorBFol = Font ColorLCol = Line ColorLWth = Line WidthUCRect = Use Rectangle Notation

Page 105: Scripting EA

Bits and Pieces 98

<n> is a width, <c> is a RGB and <b> is a switch (0/1) value.

You must not specify all of the parameter values. E.g. if you intend to just set the element colorto red use BCol=255. To set reset the color to the default use BCol=-1.

Rectangle notation can only be changed per diagram, not globally.

6.13 Connector Style

When you inspect the connector style you will eventually find something like

Mode=<mode>;EOID=<xid>;SOID=<xid>;Color=<col>;LWidth=<width>;TREE=<tree>;

a semi-colon separated list of line attributes. The single parameters have the following meaning:

<mode>:

1 = Direct2 = Auto Route3 = Custom8 = Bezier

Do not try to set other numeric values here. A value of 7 makes the connector appear as a strangenote link.

<tree>:

OR = Orthogonal RoundOS = Orthogonal SquareLH = Lateral HorizontalLV = Lateral VerticalV = Tree Style VerticalH = Tree Style Horizontal

<col> is a color value and <width> is a line width numeric value.

I have not the faintest idea what <xid>means. Neither for EOID nor for SOID. The best is to ignorethese values and to not supply them when setting the connector style.

6.14 Run State

@VAR;Variable=s1;Value=state1;Op==;@ENDVAR;@VAR;Variable=...

The structure is quite simple. Each run state appears inside a @VAR; – @ENDVAR; bracket. Thesingle attributes are stored as a key-value pairs.

And what happens if you include a semi-colon in any of the values? Just try it out :-/

Page 106: Scripting EA

Bits and Pieces 99

6.15 Geometry

SX=0;SY=0;EX=0;EY=0;EDGE=3;$LLB=;LLT=;LMT=;LMB=;LRT=;LRB=;IRHS=;ILHS=;

For details see my Inside book.

6.16 Enumeration Relation Set

0 = DependEnd – List of elements that depend on the current element.1 = DependStart – List of elements that the current element depends on.2 = GeneralizeEnd – List of elements that are generalized by the current element.3 = GeneralizeStart – List of elements that the current element generalizes.4 = Parents – List of all parent elements of the current element.5 = RealizeEnd – List of elements that are realized by the current element.6 = RealizeStart – List of elements that the current element realizes.

6.17 XML Result String

Any result from a SQL search is returned as XML. The format is as follows:

1 <?xml version="1.0"?>

2 <EADATA version="1.0" exporter="Enterprise Architect">

3 <Dataset_0>

4 <Data>

5 <Row>

6 <col>value</col>

7 </Row>

8 </Data>

9 </Dataset_0>

10 </EADATA>

The <Row> data appears for each row which was matching the supplied SQL. The single columns<col> match the name of the queried column. If you queried * you will find all the columns ofthe according table (e.g. <Object_ID>, <Object_Type>, <Diagram_ID>, etc. for t_object). Incase you query multiple tables with ambiguous column names these will be prefixed with theaccording table name (e.g. <t_object.ea_guid>).

Page 107: Scripting EA

7. GUI ReferenceIn this chapter you will find most of the property dialogs. Where possible a green frame indicatesthe access via the API. In case of a yellow frame the according field is not addressable with theAPI directly and a bypass through EA’s tables might be needed. In such cases you might need tohave a look into my Inside book.

7.1 Element

Here you find property dialogs that deal with elements. Note that packages also have an elementpart and share information in the same dialog as for pure elements.

Dockable Properties Window

Referenced by EaElement attributesName, Visibility (Scope), Type, Stereotype, Alias, Complexity, Version, Phase, GenType(Language), GenFile (Filename), PackageGUID (GUID; shows Name of package in dialog)Author, Status, Created, Modified, Keywords, ElementGUID (GUID), Abstract, Multi-plicity, IsLeaf, IsSpec (Is Specification), Persistence

For packages the EaPackage attributes for Name, Version, Created and Modified are the same asthe shadow attributes in the according element.

Page 108: Scripting EA

GUI Reference 101

For packages the ElementGUID of the related element is the same as the PackageGUID.

The Is Root flag is only available via t_object.IsRoot.

Though the help tells that Created and Modified are r/w they actually are not. Thefirst will not be changed at all on an Update() and the latter will always be the currenttime stamp. You need to bypass the API in order to modify those values.

General Properties Window

Referenced by EaElement attributesName, Notes, Stereotype, Status, Alias, Tag (Keywords), Author, Complexity, GenType(Language), Version, Phase, PackageID (Package; EaPackage.Name), Created, Modified

Sharing of some properties with EaPackage as mentioned above.

Page 109: Scripting EA

GUI Reference 102

General/Details Properties Window

Referenced by EaElement

Persistence, Scope, Abstract, IsLeaf, IsSpec (Is Specification), IsActive

The Is Root flag is only available via t_object.IsRoot. The Concurrency selection is only avail-able via t_object.Concurrency. The Cardinality value is only available via t_object.Cardinality.

Advanced Properties Window

Referenced by EaElement

Properties

Requirements Properties Window

Referenced by EaElement

Requirements

Page 110: Scripting EA

GUI Reference 103

The returned collection contains EaRequirement elementsName, Notes, Status, Difficulty, Stability, Type, LastUpdate

Constraints Properties Window

Referenced by EaElement

Constraints

The returned collection contains EaConstraint elementsName, Notes, Type, Status

Scenarios/Description Properties Window

Referenced by EaElement

Scenarios

The returned collection contains EaScenario elementsName, Notes, Type

Page 111: Scripting EA

GUI Reference 104

Files Properties Window

Referenced by EaElement

Files

Requirements Properties Window

The following properties window shows up for Requirement, Change and Issue element types.

Referenced by EaElement attributesStereotype (Type), Difficulty, Priority

All other fields are the same as in the General Properties Window.

Page 112: Scripting EA

GUI Reference 105

7.2 Attributes

General Properties Window

Referenced by EaAttribute attributesName, Type, Visibility (Scope), Stereotype, Style (Alias), Default (Initial Value), Con-tainment, IsStatic (Static), SubsettedProperty (Property), IsConst (Const) IsDerived(Derived),IsCollection, Container (Container Type), Notes

The Is Literal field is only hidden in EaAttribute.StyleEx. Transient and isID can be foundin t_xref. See my Inside book.

Multiplicity see below.

Multiplicity Properties Window

Referenced by EaAttribute attributesLowerBond, UpperBond, AllowDuplicates, IsOrdered (Multiplicity is Ordered)

Page 113: Scripting EA

GUI Reference 106

Column/General Properties Window

Referenced by EaAttribute attributesName, Type (Data Type), Length, Scale, IsOrdered (Primary Key), AllowDuplicates (NotNull), Style (Alias), Default (Initial Value), Notes

Column/General Float Properties Window

For Float and some other datatypes the properties pane contains a couple of different values:

Referenced by EaAttribute attributesTaggedValues

This is a collection of EaAttributeTag objects.

Page 114: Scripting EA

GUI Reference 107

7.3 Operations

General Properties Window

Referenced by EaMethod attributesName, Parameters, Return Type, Stereotype, Style (Alias), Notes, Visibility (Scope),Abstract, IsStatic (Static), TaggedValues (name native or whatever advanced propertyis present)

Parameters Properties Window

Referenced by EaParameter attributesName (Parameter), Type, Default (Default Value), Stereotype, Alias, Kind (Direction),IsConst (Fixed Value), Notes

For Multiplicity see Inside EA.

Page 115: Scripting EA

GUI Reference 108

Behavior Properties Window

Referenced by EaMethod attributesBehavior, StyleEx (Show Behavior in Diagram), Code (Initial Code)

Page 116: Scripting EA

GUI Reference 109

7.4 Connector

General Properties Window

Referenced by :

• EaConnector attributes Name, Notes SupplierID (Source), ClientID (Target), Alias, Di-rection, Stereotype,

• EaDiagramLink attributes Style

Advanced Properties Window

Referenced by EaConnector attributesCustomProperties

Constraints Properties Window

Referenced by EaConnector

Constraints

This is a collection of EaAttributeConstraint objects.

Page 117: Scripting EA

GUI Reference 110

Source/Target Properties Window

The properties shown here apply to connector source (Supplier) and target (Client).

Referenced by EaConnector attributesClientEnd, SupplierEnd

Both are of type EaConnectorEnd and use the following mappingCardinality (Multiplicity), Ordered (Ordering), AllowDuplicates, Stereotype, Alias,Visibility (Access), Navigable (Navigability), Aggregation, Visibility(Scope), Con-straint, Qualifier (Qualifiers)

Page 118: Scripting EA

GUI Reference 111

Message Properties Window

Referenced by EaConnector attributesName (Message), TransitionGuard (Parameters), StyleEx (Argument(s)), TransitionGuard(Return Value), TransitionGuard (Assign To), Stereotype, Alias, Properties (Synch,Kind and Is Return), Subtype(Lifecycle), Notes

The Alias also appears in the StyleEx attribute. Condition is only available via t_connec-

tor.Btm_Mid_Label, Constraint via t_conncetor.SourceConstraint/.Top_Start_Label, IsIteration via t_conncetor.SourceCard (if it contains Iteration the flag is checked). ShowInherited Messages will just influence the Operations drop down.

Page 119: Scripting EA

GUI Reference 112

Transition/Constraints Properties Window

Referenced by EaConnector attributesTransitionGuard (Guard), TransitionAction (Effect)

For further fields please refer to my Inside book.

Generalization/General Properties Window

Referenced by EaConnector attributesVirtualInheritance

Page 120: Scripting EA

GUI Reference 113

7.5 Diagram

General Properties Window

Referenced by EaDiagram attributesName, Author, Version, Notes, Stereotype, CreatedDate (Created), ModifiedDate (Modi-fied)

Page 121: Scripting EA

GUI Reference 114

Diagram Properties Window

Referenced by EaDiagram attributesShowDetails (Show Diagram Details), HighlightImports (Show Namespace)

Most of the properties here are coded in t_diagram.PDATA. The Show Page Border property iscoded in t_diagram.ShowBorder. The Always Open as Element List property can be set via theEaDiagram.ShowAsElementList() operation. The Show Connector Property String propertycan be set via the EaDiagram.WriteStyle("Show Connector Property String") operation andread via ReadStyle accordingly.

Page 122: Scripting EA

GUI Reference 115

Page Setup Window

Referenced by EaDiagram

Orientation

Page 123: Scripting EA

GUI Reference 116

Elements Setup Window

Referenced by EaDiagram

ShowPackageContents

The Show Element Property String property can be set via the EaDiagram.WriteStyle("ShowElement Property String") operation and read via ReadStyle accordingly.

Page 124: Scripting EA

GUI Reference 117

Features Setup Window

Referenced by EaDiagram attributesShowPrivate (Private), ShowProtected (Protected), Public(Public)

The Show Element Features String property can be set via the EaDiagram.WriteStyle("ShowElement Features String") operation and read via ReadStyle accordingly.

Connectors Setup Window

Referenced by EaDiagram operationReadStyle (“Show Connector Property String”)

Page 125: Scripting EA

GUI Reference 118

7.6 Miscellaneous

Code Generation Window

Referenced by EaElement attributesGenFile (Path), GenType (Target language), Name (Details), Header1 and Header2 (Im-port(s)/Header(s))

Package Control Window

Referenced by EaPackage attributesIsControlled (Control Package), Flags (Version Control), XMLPath (XMI Filename),

Page 126: Scripting EA

GUI Reference 119

UMLVersion (UML/XMI Type), Version (Version ID), Owner, LastLoadDate, LastSaveDate,UseDTD, LogXML (Log Import/Export), BatchLoad (Batch Import), BatchSave (Batch Export)

Page 127: Scripting EA

8. Further ReadingFinally I would like to add a few links where you will get further help.

8.1 Feedback

Any questions you have are important. So you should ask them. Feedback is important for you,me and of course all the other readers. So you are encouraged to send these to one of the belowlinks:

http://www.sparxsystems.com/cgi-bin/yabb/YaBB.cgi?num=1339698787This thread on Sparx’ forum is a good place to ask questions of common interest. E.g. ifyou are missing certain information or you don’t understand something in this book whichmight be explained in more detail.

http://leanpub.com/ScriptingEAThe page where you bought the book has a small discussion forum enabled. Here you canalso post.

[email protected] can mail me directly if you have specific questions.

8.2 Inside Enterprise Architect

If you got to some in-depth knowledge of EA’s automation you will likely be interested in thedetails about EA’s database. My book Inside Enterprise Architect which is available at http://leanpub.com/InsideEA will give you these details. You’ll be astonished how fast the API reactswhen you write a single SQL statement instead of a clumsy API loop.

8.3 Sparx Forum

Probably not necessary to name this source, but anyway:

http://www.sparxsystems.com/cgi-bin/yabb/YaBB.cgi

When you post your questions here you should select the right forum and only post once. Gettinghelp here is most likely the fastest lane you can find. I also post regularly.

Page 128: Scripting EA

Further Reading 121

8.4 Sparx Community

A not so well known source as Sparx itself does not link this on its forum pages:

http://community.sparxsystems.com

Here you will find a variety of articles and resources around EA.

8.5 Geert Bellekens

Geert has become a kind of institution at Sparx’ forum. He is a regular poster. But beyond thathe also has an excellent blog dealing with ULM in general and Enterprise Architect in particular.Check it out:

http://geertbellekens.wordpress.com

And last but really not the least I like to link Geerts EA navigator source:

http://geertbellekens.wordpress.com/ea-navigator/

This will take you into the wonderful world of EA Add-Ins. Have fun!