Customizing Geomedia

229
1 Introduction ...................................................................................................................................... 3 Automation Overview ...................................................................................................................... 5 Object-Oriented Programming and OLE.................................................................................... 7 What is COM? ............................................................................................................................ 9 Benefits of OLE ....................................................................................................................... 10 What is Automation? ................................................................................................................ 11 Manipulating Objects ............................................................................................................... 13 Terminology ............................................................................................................................. 16 Driving Excel Automation ....................................................................................................... 19 GeoMedia’s Automation Capabilities ...................................................................................... 22 Approaches to Customization .................................................................................................. 44 Summary................................................................................................................................... 50 Can You Answer These Questions? ......................................................................................... 51 Creating a Custom Application .................................................................................................... 53 Connecting to the GDO Server ................................................................................................ 55 Creating and Manipulating Recordsets .................................................................................... 62 Adding a MapView and Displaying Data ................................................................................ 69 What are Styles? ....................................................................................................................... 75 What is Marginalia? ................................................................................................................. 80 Printing Maps ........................................................................................................................... 83 Creating and Displaying Queries ............................................................................................. 86 Spatial Query Pipe .................................................................................................................... 88 Buffer Zone Pipe ...................................................................................................................... 96 Locating Features ................................................................................................................... 100 Creating a Data View ............................................................................................................. 105 Custom Application Limitations ............................................................................................ 113 Summary................................................................................................................................. 117 Can You Answer These Questions? ....................................................................................... 118 Adding Commands to GeoMedia................................................................................................ 119 GeoMedia’s Command Wizard .............................................................................................. 121

Transcript of Customizing Geomedia

Page 1: Customizing Geomedia

1

Introduction ...................................................................................................................................... 3

Automation Overview...................................................................................................................... 5

Object-Oriented Programming and OLE.................................................................................... 7

What is COM?............................................................................................................................ 9

Benefits of OLE ....................................................................................................................... 10

What is Automation?................................................................................................................ 11

Manipulating Objects ............................................................................................................... 13

Terminology ............................................................................................................................. 16

Driving Excel Automation ....................................................................................................... 19

GeoMedia’s Automation Capabilities...................................................................................... 22

Approaches to Customization .................................................................................................. 44

Summary................................................................................................................................... 50

Can You Answer These Questions?......................................................................................... 51

Creating a Custom Application .................................................................................................... 53

Connecting to the GDO Server ................................................................................................ 55

Creating and Manipulating Recordsets .................................................................................... 62

Adding a MapView and Displaying Data ................................................................................ 69

What are Styles?....................................................................................................................... 75

What is Marginalia? ................................................................................................................. 80

Printing Maps ........................................................................................................................... 83

Creating and Displaying Queries ............................................................................................. 86

Spatial Query Pipe.................................................................................................................... 88

Buffer Zone Pipe ...................................................................................................................... 96

Locating Features ................................................................................................................... 100

Creating a Data View ............................................................................................................. 105

Custom Application Limitations ............................................................................................ 113

Summary................................................................................................................................. 117

Can You Answer These Questions?....................................................................................... 118

Adding Commands to GeoMedia................................................................................................ 119

GeoMedia’s Command Wizard.............................................................................................. 121

Page 2: Customizing Geomedia

2 Fundamentals of GeoMedia Development Part I

Command Types..................................................................................................................... 127

Creating the Command Skeleton............................................................................................ 131

Modal Commands .................................................................................................................. 142

Modeless Commands ............................................................................................................. 154

Summary................................................................................................................................. 169

Can You Answer These Questions?....................................................................................... 171

Appendices .................................................................................................................................... 173

Document Conventions .......................................................................................................... 173

Reference Materials ............................................................................................................... 174

Where to Get Help.................................................................................................................. 175

Lab Exercises ......................................................................................................................... 176

Feature List for Lab 14........................................................................................................... 177

Visual Basic Syntactical Constructs....................................................................................... 181

Visual Basic Notation Conventions ....................................................................................... 186

PowerBuilder Syntactical Differences ................................................................................... 192

Delphi and GeoMedia ............................................................................................................ 194

Automation Overview Diagrams............................................................................................ 195

OriginatingPipe GRecordset vs. GDO GRecordset ............................................................... 196

Programming Caveats ............................................................................................................ 197

Feature Selection Controls ..................................................................................................... 199

Raster Formats........................................................................................................................ 201

GetExtension Method............................................................................................................. 202

ExtendedPropertySet.GetValue Method ................................................................................ 204

Common Interfaces ................................................................................................................ 207

Type Libraries and Objects .................................................................................................... 208

Object Bundles ....................................................................................................................... 216

Collections: Indexing and Object Types ............................................................................... 222

Instructor’s Overheads ........................................................................................................... 229

Page 3: Customizing Geomedia

Introduction3

Introduction

Welcome to GeoMedia™ and the Team GeoMedia developmentworkshop!

GeoMedia

GeoMedia is a universal geographic client that augments standardIntergraph products like MGE and FRAMME as well as providing accessto geographic data in non-Intergraph formats. GeoMedia provides theability to access multiple geographic data sources simultaneously fordisplay, analysis, and presentation. These capabilities allow professionalsof all industries to communicate geographically.

The three fundamental principles of GeoMedia are:

• Data integration and access

GeoMedia lets the user integrate geographic data from multiplevendors and standard data sources. The user can perform analysisagainst multiple data sources without costly translations betweenformats.

• Productivity

By extending Windows standards through Intergraph’s Jupitertechnology, GeoMedia defines new ways of thinking spatially,performing analysis, and communicating geographically.

• Customization

Through OLE Automation, GeoMedia is directly accessible throughautomation clients like Visual Basic. This allows you to eithercustomize or extend the GeoMedia product or to build your ownapplication with GeoMedia components.

Team GeoMedia

Team GeoMedia is a membership program for developers of GeoMedia-based applications as well as for anyone who uses the GeoMedia objectsor product for development, consulting, systems integration, or dataprovision.

Team GeoMedia is designed to develop relationships with leadingindependent software vendors, consultants, systems integrators, industryadvisors, and data producers around the world. By stressing the unique

Page 4: Customizing Geomedia

4 Fundamentals of GeoMedia Development Part I

abilities of each partner, successful cooperative relationships will beformed. Ultimately, this means a better set of products to meet theexpanding needs in the GIS industry. Team GeoMedia membership isalso valuable to any MIS professional developing enhancements for intra-company use of GeoMedia. The program provides an avenue fordistributing valuable technical information to all developers.

If you are not currently a Team GeoMedia member, we encourage you tolearn more about the program through the world wide web athttp://www.ingr.com/geomedia/team_geo.htm. We look forward to asuccessful relationship.

Course Objectives

Over the next three days, the course will provide you with extensiveinformation about the GeoMedia product, the automated objects, andcustom development techniques. While the course will not be able topresent every object and every possible manipulation of that object, it willcover the fundamental operation of most objects as well as the mostcommon operations with those objects.

The course is divided into three sections.

• Automation Overview

• Adding Commands to GeoMedia

• Creating a Custom Application

Each section builds upon the knowledge gained from the prior section.While the material provides you with some background information onautomation and Visual Basic, the intention is NOT to teach you thismaterial. Rather, the focus is on the effective use of GeoMedia’s objects.

The workshop makes extensive use of hands-on lab exercises. The labsare presented in a format that provides hints in the skeleton code to guideyou through the completion of the exercise. A solution set is alsoprovided. All materials including the labs, course text, and presentationslides are included on the floppy disks in your course manual. While wehave presented the material using Microsoft’s Visual Basic as theautomation controller, the GeoMedia objects may be used with any robustautomation controller. PowerBuilder, Delphi, and Visual C++ are verypopular tools.

We hope that you find the information presented here useful in yourapplication development activities. Please complete the courseevaluations provided in your binder so that we may better serve you in thefuture.

Page 5: Customizing Geomedia

5

Automation Overview

Introduction

The term “automation” will be used frequently and in many differentcontexts. This section will introduce many of the terms used inautomation programming. The automation model for GeoMedia will beanalyzed and the mechanisms for customizing GeoMedia will bepresented. The lab exercises will reinforce the OLE Automation concepts.

Topics

1. Object-oriented programming and OLE

2. What is COM?

3. Benefits of OLE

4. What is Automation?

5. Manipulating Objects

6. Terminology

7. Driving Excel Automation

8. GeoMedia’s Automation Capabilities

9. Approaches to Customization

Objectives

At the end of this section, you will be able to do the following:

1. Define common programming terms

2. Navigate the GeoMedia automation model

3. Describe the three techniques for customizing GeoMedia

Demonstrations

• Introduction to GeoMedia

• Driving Excel through Automation

Page 6: Customizing Geomedia

6 Fundamentals of GeoMedia Development Part I

Labs

• Navigating the GeoMedia Automation Model

Page 7: Customizing Geomedia

Automation Overview 7

Object-Oriented Programming and OLEAs we look at GeoMedia customization, the terms object and automationwill be pervasive. The term object surfaced in conjunction with object-oriented programming techniques. While object-oriented paradigms haveexisted for many years, they are receiving considerable emphasis intoday’s software development environments. An object-oriented systemfocuses on an organization of software that encapsulates data structuresand behavior into discrete components or objects. So, in GeoMedia, asoftware component that provides an encapsulated set of functionality istermed an object.

Automation is the process of communicating with these software objectsas part of creating applications. Before we look at how we useautomation, we need to first review some history of the present daysoftware architecture. Much of the broader focus on object-orientedprogramming started through the introduction of OLE. In its initial form,OLE meant Object Linking and Embedding. In this context, OLE enabledyou to create objects (files, applications) and build relationships betweenthem. For instance, you could include an Excel spreadsheet inside a Worddocument and double click on it to start Excel. OLE, in its current form,enables the following techniques.

• Integration of components (objects)

• Independence of language through a binary standard

• Abstraction of interfaces to components (objects)

More specifically, OLE includes three distinct elements: compounddocuments, automation, and OLE controls. A compound document is adocument that contains, along with native data, one or more objects thatwere created in other applications. Additionally, it exhibits the behaviorsof in-place activation and drag-and-drop. OLE Automation can be definedas one application exposing objects to be programmatically manipulatedby another application. For example, Microsoft Excel can exposespreadsheet and chart objects that can be manipulated by a programwritten using Visual Basic. Or, Intergraph’s GeoMedia can expose mapviews and pipes that can be manipulated by a program using Visual Basicor Visual C++.

Finally, OLE controls embody many of the OLE technologies, includingCOM, connectable objects, compound documents, property pages, OLEAutomation, and object persistence. A control or widget is a softwarecomponent that is usually visible to the user — a button, a listbox, acheckbox — and is used to provide the building blocks for creating userinterfaces in applications. A custom control is one built by a user to

Page 8: Customizing Geomedia

8 Fundamentals of GeoMedia Development Part I

address a specific problem encountered in the workflow.

Obviously, these topics require a much deeper analysis for you to becomeproficient in their effective use and development. However, byintroducing these concepts, you can see where GeoMedia customizationfits into the bigger picture of today’s software architecture. Our primaryfocus for the workshop is the automation aspect of OLE technologies.

Page 9: Customizing Geomedia

Automation Overview 9

What is COM?Although not integral to our objectives for customizing GeoMedia, a briefsummary of Microsoft’s Component Object Model (COM) is worthwhile.GeoMedia’s architecture is founded upon this model. Understanding thebasic principles is useful even if you never create a programmable object.

OLE is built upon COM. COM defines and implements mechanisms thatenable software components (objects, controls, applications, and services)to interact. That is, COM defines a communications protocol for softwarecomponents. COM describes manipulating interfaces, reporting status,and the use of the system registry to resolve universally unique identifiers.COM also defines the interaction of objects within or betweenapplications.

Interfaces are integral to the implementation of COM. A COM interface isa specification for interaction between COM objects. Consider theinterface as a contract between a producer and consumer that defines theintent and behavior of the software. An interface is comprised of a list ofsemantically related functions (or methods) for the COM object. Once aninterface is defined, it cannot change. That is, the contract cannot bebroken. This contract protects you as an application developer fromchanges to the software you depend on in your application.

The Component Object Model is the key to OLE’s extensible architecture,providing the foundation on which the rest of OLE is built. COM is abinary standard for component communication. COM is not dependent onWindows NT. Microsoft and other vendors are implementing COMlibraries on other platforms, including Unix and Macintosh. For moreinformation on COM, visit the Microsoft Developer Network (start athttp://www.microsoft.com/). The book Inside OLE 2 by KraigBrockschmidt is a powerful source of information. Refer to the appendixfor publishing information.

Page 10: Customizing Geomedia

10 Fundamentals of GeoMedia Development Part I

Benefits of OLEOLE provides great benefits to both users and developers. OLE’semphasis is on "document-centric" programming rather than “application-centric” programming. That is, the data and data format are independentof the application. Users can manipulate a document (data) with severalapplications without costly conversion processes. Data can also be sharedacross documents. By providing access to data without making a copy ofthe data, the information is better maintained and it simplifies the businessoperations for distribution of information.

The use of OLE objects and interfaces provides developers with the toolsthey need to create flexible applications that can be easily maintained andenhanced. OLE applications can specialize in one area, taking advantageof features implemented in other OLE applications to increase theirusability. This speaks to the adage of using the best tool for the job. Asapplication developers, we no longer are faced with creating all of theneeded functionality. We can utilize other OLE applications to meet ourobjectives. GeoMedia fits into this architecture as an embeddabletechnology.

Although we have not discussed some of the architectural requirements ofOLE and COM, we know that there is a protocol for communicationbetween objects and automation clients or controllers. This protocol is aninterface. All objects support this important interface (IUnknown).Through these interfaces, you can learn at runtime about the capabilitiesof other applications that relate to object services. Support for additionalobjects and interfaces can be added without affecting either the currentapplication or those applications that interact with it. Remember, this isthe contract of COM − once an interface is defined, it cannot be changed.GeoMedia supports this through consistency in the programming contract.

Page 11: Customizing Geomedia

Automation Overview 11

What is Automation?OLE Automation is an industry standard that applications use to exposetheir OLE objects. There are two primary facets of automation: thecontroller and the object. An automation controller is the scripting toolthat enables your program to communicate with the automation objects.Automation controllers include VC++, Visual Basic, PowerBuilder,Developer 2000, and Delphi. Automation objects are the programmablecomponents that support the necessary OLE interfaces. Additionally, anentire application might be an automation object. For example, aspreadsheet application may expose a worksheet, chart, cell, or range ofcells — all as different types of objects. A word processor might exposeobjects such as application, document, paragraph, sentence, bookmark, orselection.

Automation Controller: scripting tool used to create programs thatmanipulate automated objects. Same as automation client.

When an application supports OLE Automation, the objects it exposes canbe accessed by any automation controller (VB, VC++, etc.). You use thescripting tool to manipulate the application’s objects by invoking methodson the object or by getting and setting the object’s properties.

Automation Object: programmable software componentmanipulated by automation controller. Same as automation server.

You might find literature that refers to automation clients and servers. Aclient is equivalent to a controller. A client is a scripting tool or anapplication built with this tool that manipulates automation objects. Aserver is equivalent to an object. An automation server is a softwarecomponent that can be manipulated by any automation client. It exposesprogrammable objects. Exposing programmable objects enables clients to“automate” certain procedures by directly accessing the objects andfunctionality the server makes available.

Supporting automated objects allows you to fine-tune your workflowusing existing applications. You can also create very specializedapplications that utilize the power of other applications. This equates toless development time and less support for you, as well as meeting veryspecific needs for your organization. Through the standardization of theautomation interface, this application can be built in a single generalprogramming language instead of the multiple scripting languages

Page 12: Customizing Geomedia

12 Fundamentals of GeoMedia Development Part I

associated with the various products.

For an automation client to effectively access the automated objects, theclient (controller) must have information about the server’s objects.Within each object, you must have information about the properties andmethods of the object. To achieve this information exchange, the serverwill create a type library which defines each object. The type library alsodescribes the properties of the object including the data type of eachproperty. Finally, the object’s methods are described. The descriptionincludes the return values and the method’s argument list – variable anddata type. In GeoMedia, we have one type library for each DLL andOCX, as well as one for the application’s executable. The type library filehas a .tlb extension. In the case of Visual Basic automation servers, theDLL itself contains the type information. The list of GeoMedia objectsand their corresponding type libraries is presented in the Appendix.

Page 13: Customizing Geomedia

Automation Overview 13

Manipulating ObjectsIn order to be effective in programming automation servers, you mustunderstand how to manipulate the automated objects. We can collectivelyrefer to the attributes of an object as the interface to the object. The firstattribute type is the property. If we think of an object as a structure, aproperty is a member variable. Properties control the characteristics ofobjects like color and weight. A method is the operation associated withthe object. In the object-oriented sense, methods embody the behavior ofthe object. Almost all objects will have both properties and methods.Some objects will also have the third type of attribute — events. An eventis a signal or action that an object responds to. For example, clicking on aradio button on a form will trigger a click event on the radio button object.Controls typically have events.

A member object is a property of one object which is itself another object.For instance, the GeoMedia application object exposes a Documentproperty. The Document property is also an object. The Document isthen a member object of the application object. A dependent object is likea member object but it has a stricter relationship with the containingobject. A dependent object cannot be created independently of thecontaining object. For example, the GField object in GDO is a dependentobject on the GTableDef object. You must use a method on GTableDef tocreate a GField object.

Finally, we need to discuss a special kind of object known as a collection.A collection is an automation object which groups or manages a set ofsimilar objects. A collection object normally has the same name as theobjects it manages — simply distinguished by the plural form. Forexample, Windows is a collection of Window objects; Queries is acollection of Query objects. The objects within a collection may behomogeneous or heterogeneous in nature. The Windows collection isheterogeneous in that it contains DataViewWindow and MapViewWindowobjects. The Queries collection is homogeneous in that it contains onlyQuery objects. It is important to understand the type of collection you aremanipulating as you often process all members of a collection.

Collection: set of related objects

Although a collection object can have its own unique methods andproperties, it must have a Count property and an Item method. The Countproperty indicates the number of objects in the collection. The Itemmethod supports the iteration process:

Page 14: Customizing Geomedia

14 Fundamentals of GeoMedia Development Part I

For i = 1 To objCollection.Count

objX = objCollection.Item(i)

Next I

The standard for new collections is to begin the iteration at one (1). Thisis often referred to as a base 1. However, you will find some collectionsbegin iteration at zero (0). In GeoMedia, all GDO collections are base 0,while the GeoMedia collections are base 1.

Additionally, collections often have these methods:

• Add values or Append object

• Remove index or Delete object

• _NewEnum — hidden method that supports the For Each construct

Objects typically have a default method or property. This defaultmechanism allows you to omit the property or method name and implicitlyretrieve the value or execute the method. For example, the Item method isusually the default for the collection object. In this situation,

objCollection.Item(i)

objCollection(i)

are equivalent statements. In the text control, the Text property is thedefault. Then,

txtControl1.Text

txtControl1

have the same effect of retrieving the value in the text control.

Table 0-1 Object Characteristics

Attribute Description

Property Data member or characteristic

Method Procedure or function which operates on the object

Event Action recognized by an object

Member /Dependent Object

Constituent element of a collection or object

Collection An object which contains a set of similar objects

Another important concept in manipulating objects is the dot ornavigational operator. This is syntactically represented by a period or dot

Page 15: Customizing Geomedia

Automation Overview 15

(‘.’) in Visual Basic. The dot operator provides access to the values of theproperties of the object and initiates the methods on the objects. When anobject contains member objects, you can use the dot operator to traversethe entire object hierarchy. Consider an Application object with aDocument member object. The Document object has several propertiesincluding the Name. Through the use of the dot operator, we can retrievethe name of the Document with:

Application.Document.Name

There is no limit to the depth of the hierarchy that can be traversed.However, code readability will suffer and there is a potential performancepenalty for repeated traversals. Since each dot initiates a request to theautomation server, you should examine your use of this operator. Forinstance, if you are accessing several properties on an object or areprocessing an object within a loop, it is much more effective to either usea With block or introduce an intermediate or temporary variable as aplaceholder. For instance:

Application.Document.Name = ‘Automation Overview’

Application.Document.Date = ‘7/12/97’

Application.Document.Author = ‘John Doe’

is more efficiently written either as:

Set tmpDoc = Application.Document

tmpDoc.Name = ‘Automation Overview’

tmpDoc.Date = ‘7/12/97’

tmpDoc.Author = ‘John Doe’

or:

With Application.Document

.Name = ‘Automation Overview’

.Date = ‘7/12/97’

.Author = ‘John Doe’

End With

Both methods eliminate two navigation steps throughApplication.Document.

Dot / Navigation Operator: mechanism for accessing property valuesor initiating methods of objects.

Page 16: Customizing Geomedia

16 Fundamentals of GeoMedia Development Part I

Terminology

Dim, New, CreateObject

In each automation client (controller), as in any programming language,there must be some mechanism for declaring variables. In Visual Basic,this is accomplished with the Dim statement. The Dim statement is alsoused to declare object variables. For example, Dim objX As Objectestablishes objX as a pointer to any object. This occurs because Object isa generic term that does not indicate the exact type of the object. Sincethis is a pointer, you must set the value of the pointer to an object. Onemechanism for accomplishing this is to set it to a member or dependentobject property of another object:

Dim objDoc As Object

Set objDoc = Application.Document

You may also create an object using the function provided by yourautomation controller where you have a reference to MyApplication’s typelibrary in your project:

Set objDoc = CreateObject(“MyApplication.Document”)

In Visual Basic, you can also achieve the latter functionality with the Newoperator:

Dim objDoc As New Document

In both of the latter examples, you have actually created a new object. Inthe first example, you simply created a reference to (shared) an existingobject.

Not all objects are externally creatable. This rule implies that the Newoperator and the CreateObject function will fail when attempted. You canalso create a variable that references an object’s interface with the Dimstatement. You cannot, however, create an instance of an interface object.We will see how interfaces surface in the GeoMedia model later in theworkshop.

In-Process, Out-of-Process

There are two ways to communicate with an automation server: in-process and out-of-process. An in-process server is created as a DLL, andthe client is either a DLL or an EXE. An out-of-process server is createdas an EXE, and the client is either a DLL or an EXE. The distinguishingdifference between these two types of implementations is that an in-process server shares the same address space as the client. Hence, it can

Page 17: Customizing Geomedia

Automation Overview 17

be significantly faster than an out-of-process server. The out-of-processserver has its own address space. To its advantage though, it can servemultiple clients simultaneously. The significance of these two types ofservers will be important later when we look at how to create customcommands and write independent applications using GeoMedia.

UUID, GUID, CLSID, PROGID

You might wonder how an automation controller keeps track of objects —that is, how does it uniquely identify them? All interfaces and automationobjects are represented by a universally unique identifier (UUID). Thevalue is also known as a globally unique identifier (GUID). A GUID is a128-bit value that is generated by a program and is guaranteed to beunique — globally. The value is generated based on time of day, the date,and a unique number contained in your network card. There are twospecific types of GUIDs: interface identifiers (IID) and class identifiers(CLSID).

Each interface is defined by its own interface identifier (IID). This valueis used to find the correct interface (set of functions) associated with anobject. Once you have the interface, you have access to the methodswithin the interface. Most automation controllers convert from objecttype names to interface identifiers automatically so you will not beexposed to this information directly.

A class identifier is associated with each type of automated object. Theclass identifier is used in creating objects of the given type. As with IIDs,this GUID is used to uniquely define the objects (classes) supported by anautomation server.

Finally, each class has a programmatic identifier (ProgID). This is a stringthat uniquely identifies the object in the registry. An API exists forconverting between the ProgID and the CLSID, and vice versa.Underscores and periods are the only allowable punctuation. The CLSIDfor most GeoMedia objects begin with GeoMedia. and is followed by theclass name. The ProgID is the argument to CreateObject in yourautomation controller. For example, GeoMedia.Application,GeoMedia.Connection, and GeoMedia.ColorSchemes are ProgIDs.Access.GDatabase is the ProgID for the Access GDO server.

Interface

Interfaces are the mechanism by which you communicate with an object.An object may have one or more interface pointers. Recall that aninterface is a set of related functions. Typically, the relationship betweenfunctions in an interface is one of purpose. For example, an object may

Page 18: Customizing Geomedia

18 Fundamentals of GeoMedia Development Part I

have a persistence interface that provides the methods for saving andloading the object. Another interface might be the automation methodsfor the object.

An interface is an abstract C++ class whose definition is stored in a typelibrary. All member functions return an HRESULT — a special type oferror code which indicates success or failure of the member method.Remember that an interface defines a contract which must not changeonce defined. All automation objects will implement at least threeinterfaces: IUnknown, IDispatch, and an automation interface. Severalobjects can implement the same interface. Semantically, the memberfunctions perform the same operations. However, they may implementthat function differently as long as the semantic meaning has not changed.

This diagram provides a visualization of an object and its interfaces. Mostautomated objects will have three interfaces – some of which are acquiredthrough inheritance.

MyAutomatedClass

IUnknown Interface• AddRef• Release• QueryInterface

IDispatch Interface• Invoke• GetIDsOfNames• GetTypeInfoCount• GetTypeInfo

MyAutomatedClass Interface• get_Value1• set_Value1• MyMethod1• MyMethod2

Page 19: Customizing Geomedia

Automation Overview 19

Driving Excel Automation

This section shows an example of OLE automation outside of GeoMedia.The material is provided to emphasize that automation is a standardprogramming technique and not a proprietary approach. The remainder ofthe course material will not be affected by the omission of the section.

Many applications today are automation servers. As such, you can write aprogram to access the objects they expose to use the capabilities of theapplication without interactively operating the application. Such acapability is extremely powerful to an application integrator. The besttools can be used for particular tasks, but the interface to the tools can beencapsulated in a small set of end user programs.

Automated objects are not unique to Intergraph. Many applications fromMicrosoft and other vendors are automation servers. Automation isquickly becoming a common mechanism for extending the capabilities ofan “off the shelf” application to better suit your needs.

This section will use Excel to illustrate some of the automation concepts.Although there is no direct correlation between Excel’s automation andGeoMedia’s, spreadsheets can provide a common ground for introducingthese automation concepts.

As is the case with most automation servers, the root object of thehierarchy is the application object. Traversing an automation hierarchy ismuch like following the steps you would take interactively in using theapplication.

Page 20: Customizing Geomedia

20 Fundamentals of GeoMedia Development Part I

This type of drawing is often used to express the automation model of anapplication. This “automation diagram” shows the objects and theirhierarchical relationship to one another. Each box represents anautomated object. Gray boxes are used to represent a collection objectand the object it contains. In this example,

• Application contains (has a member object) of Workbooks. TheWorkbooks collection contains Workbook objects.

• Workbook object has members Worksheets, DialogSheets, Charts, andModules.

• Worksheets collection contains Worksheet objects.

• Worksheet object has a member object, Range.

• Range contains Areas collection and Border member objects.

There are many other objects within the model for Excel. Each object canbe further traversed until you reach an object which has no member ordependent objects. Each member or dependent object will be indented orstepped below the containing object. You can use the dot operator totraverse the hierarchy. For example, the Range object is accessible asApplication.Workbooks(1).Worksheets(1).Range.

Page 21: Customizing Geomedia

Automation Overview 21

In the automation diagrams, heterogeneous collections are indicated by agray box with a dashed outline rather than a solid outline. Excel refers tothese as metacollections.

Demo 2: Driving Excel through Automation

This demonstration illustrates the nature of automation capabilities.Microsoft’s Excel is an automated application. This enables you tointeract programmatically with the spreadsheet software. Through thisapproach, you can reduce the number of manual steps your users wouldnormally follow in their daily tasks.

In preparation for this demonstration, an Excel macro was created andstored in the personal workbook. Additionally, some data was extractedfrom pole features and stored in a text file (comma-separated value format— .csv).

The automation program is written in Visual Basic. The input to theprogram is the name of the data file. The program then starts Excel andloads the data into the worksheet of a new workbook. The data is selectedand the macro is run. The result of this process is a chart indicating thenumber of poles that need service each month.

Although this is quite trivial alone, it is indicative of the type of controlyou can exert over applications through automation. Automation’sforemost benefit is in automating the end user’s tasks by reducing manualsteps.

The instructions for programming this example and the solution areavailable with the lab materials under ExcelDemo.

Page 22: Customizing Geomedia

22 Fundamentals of GeoMedia Development Part I

GeoMedia’s Automation Capabilities

GeoMedia Concepts

GeoMedia is a viewing and analysis tool for geographic information.GeoMedia lets you integrate data from multiple sources and multipleformats into one map and perform sophisticated queries for spatialanalysis. You can either use GeoMedia as an end-user product or as adevelopment platform to build customized applications.

GeoMedia allows you to do the following:

• Display multiple geographic data types simultaneously withouttranslation. GeoMedia uses coordinate transformations so you canview data from numerous standard data sources as an integrated map.As a product, GeoMedia automates this process and requires only aminimal knowledge of projections and coordinate systems. As acustom application developer, you need to have a working knowledgeof coordinate systems and projections.

• Perform spatial analysis through buffer zones, spatial and attributequeries, and thematic maps.

• Control the contents and appearance of your map window through theinteractive legend, including the display of scanned images.

There are, of course, many more capabilities within GeoMedia.

GeoMedia works in a client / server configuration. GeoMedia is theclient. The data (or warehouse) may reside on the client machine or on aremote machine. The warehouse or database contains the geographic data.All access to a warehouse is performed through a software componentknown as a GDO server. Although GeoMedia only reflects the changes ofa single user, it is a possible to have many GeoMedia clients access thesame warehouse data. The GDO servers are resident on the client systemand access the warehouse on the remote system as needed.

GeoMedia Terminology

GDO

“Geographic Data Objects” (GDO) is an extension to OLE which enablesclients to access geographic data from disparate sources in a predictablemanner. With GDO, we have created a specification for an OLEAutomation server that may be accessed via automation clients such asVisual Basic.

Page 23: Customizing Geomedia

Automation Overview 23

Intergraph participates in Open GIS Consortium (OGC) activities to definean international standard for access to geographic data. The GDOspecification has been presented as that standard.

GDO follows the example of Microsoft’s DAO and RDO technologies fordata access. These have been Microsoft’s OLE Automation object-oriented standards for accessing and manipulating databases. Theseparadigms match the needs of geographic data access quite well; GIS canbe considered a database problem with the additional problems of geodeticcoordinate systems, geometry, and graphics display.

GDO addresses these additional problems with GIS specific interfaces.However, GDO does not take on the responsibility of database technologyinterfaces because many data sources are not true databases. It followsthe paradigm for its familiarity and usefulness, but does not require thesophistication of a database. In this light, GDO specifies the way toaccess data, but does not mandate any of the technology for the replicationof data, backup and recovery, security administration, or multi-user accessthat may be commonly associated with a database.

GRecordset

A GRecordset object contains all database records that meet a specifiedcriterion. All GRecordset objects are constructed using records (rows)and fields (columns). By exposing the geographic data as a GRecordset,we enable data manipulation. GRecordset objects are equivalent tocursors containing data from the database. The cursor is the result ofposing a query to the database. Information about attributes or columns ofa GRecordset is accessed and manipulated via a collection of Gfields,which are akin to columns selected by the query.

Through this common structure clients are able to access and manipulateinformation from a variety of data sources in a standard way.

The terms GRecordset and recordset will be used interchangeably in thismaterial.

NOTE: A recordset is not a collection, although there are similarities. Arecordset is a single object in which the rows are accessed much like anarray using the MoveNext method or by setting the Bookmark property asyou would an array index. If the recordset were a collection, you wouldaccess an individual object for each row.

We will use several terms that are very common in database environmentsthat are synonyms for the GeoMedia terms.

GDO Term Database Other Synonyms

Page 24: Customizing Geomedia

24 Fundamentals of GeoMedia Development Part I

GDatabase Database Warehouse, server

GTableDef Table Feature Class

GField Column Attribute, field

GRecordset Cursor Recordset

Active row (bookmark) Current row Feature instance, row

Legend

The legend is an important part of GeoMedia. It is the display controlcenter for the map window. Unlike a traditional legend that only reflectswhat appears in a map, the GeoMedia legend is interactive, allowing youto dynamically control the map. Through the legend, you control whichfeature classes, queries, thematic maps, labels, and images appear in themap window and how they look.

Pipe

GeoMedia’s architecture includes a concept known as a pipe. The pipephilosophy defines a protocol that allows software components tointerchange data in a common fashion — through GRecordsets. As such,GeoMedia includes several pipe components that create and/or manipulatedata through GRecordset objects.

Pipes are the mechanism by which GeoMedia packages table-relatedfunctionality in a way that fosters the reuse of data and the manipulationof data by specialized software components. Pipes consume one or moreinput GRecordsets and produce one or more output GRecordsets. Theoutput GRecordset of a pipe may have more rows, fewer rows, morefields, or fewer fields than the original input GRecordset. This outputGRecordset can in turn be fed into another pipe which may further processthe data contained in the GRecordset.

Coordinate System

A coordinate system is a way that GIS locations are stored. The amountof data contained in the coordinate system is relative to its accuracy anddetail. A more detailed coordinate system definition provides a moreprecise description of geographic positions.

GeoMedia stores geographic data with reference to one of many possiblecoordinate systems. These coordinate systems provide the mathematicalbasis for relating the features in your study area to their real-worldpositions.

GeoMedia supports two categories of coordinate systems:

Page 25: Customizing Geomedia

Automation Overview 25

• Projected coordinate systems express coordinates as X,Y,h, where Xnormally points east on the plane of the map, and Y points north at thepoint chosen for the origin of the map. The X coordinate is calledeasting; the Y, northing. The h represents height. Projectedcoordinate systems differ in how they represent the curved surface ofthe earth on the flat surface of a map.

• Geographic coordinate systems express coordinates as lon,lat,h, wherelon (longitude) is the angular distance from a zero meridian, lat(latitude) is the angular distance from the equator, and h is height.

GeoMedia interprets coordinates with reference to a geodetic datum,which defines precisely the reference ellipsoid and its position relative tothe surface of the earth. The ellipsoid is the model used to represent theshape of the earth’s surface.

Feature Class

A feature class is a classification of data. In GeoMedia, this maps to atable in the data server. Every data instance is assigned to a feature class.For example, a data set generally consists of several feature classes, suchas roads, bridges, schools, and churches.

Feature

A feature is a geographic entity that is represented on a map by geometryand defined by nongraphic attributes in the database. The definition ofthese attributes and geometry is stored in a feature class. A feature, orinstance, is equivalent to a row in the feature class table.

GeoMedia’s Automation Model

GeoMedia contains many automated objects. The volume of automatedobjects makes GeoMedia both very powerful and very overwhelming. Inorder to better understand the objects, we’ll first review the automationdiagrams.

The first part of the automation model that we will review is the overallapplication structure.

Page 26: Customizing Geomedia

26 Fundamentals of GeoMedia Development Part I

As we look at the document, note the differences in boxes. Thesedifferences provide insight as to the nature of the object.

• Boxes that are dark green represent both a collection and an object.

• Boxes with a heavy border only function within the GeoMediaapplication.

• Boxes that are dark green and have a hatched pattern aremetacollections. Recall that a metacollection is a collection thatcontains more than one type of object.

• Aqua boxes are simply objects.

• Blue boxes are simple objects but are a heterogeneous member object.For example, the legend entry contains a style object property. Thatproperty may be any of the GeoMedia style objects.

The following rules can be applied when you are navigating theautomation diagrams:

Page 27: Customizing Geomedia

Automation Overview 27

• When you encounter a homogeneous collection, add an “s” to theobject name. If the object name ends with a “y”, replace the “y” with“ies” to make the collection name. For example,Application.Document.Connections andApplication.ActiveWindow.MapView.Legend.LegendEntries.

• If you are manipulating an object in the collection, remember to addthe index into the collection. For example,Application.Document.Connections(1).ConnectionName.

• When you encounter a heterogeneous collection, skip the next objectas you continue through the hierarchy. For example,Application.Document.Windows(1).Mapview.Visible

• When you encounter a heterogeneous object, substitute the actualobject in its position and continue your navigation.

Note: These diagrams show objects and their dependent objects. In manycases, the dependent object is represented by its property name. Forexample, the QuerySubFolders collection is the property name on theQueryFolder object. The actual object type is QueryFolders.

This section will briefly review each object. Subsequent sections of theworkshop will provide more detailed information.

Application

Starting from the upper left corner of the diagram, we have the followingmember and dependent objects for the Application:

• Windows − a collection of all the open windows (data or map) withinthe application

• Active Window − the window that has focus. This is either aDataWindow or a MapWindow in the Windows collection.

• PreferenceSet − an object that provides access to the GeoMediapreference information stored in the registry

• UnitsOfMeasure − an object that provides conversion services formeasurement units (e.g., feet, meters)

• Category / Command − the classifications and commands defined byGeoMedia as well as custom commands

• Menubar / MenuItem − the menubars that control the user interfaceand the items within each menu

• Accelerator − the short cut definitions for commands (e.g., F1 for

Page 28: Customizing Geomedia

28 Fundamentals of GeoMedia Development Part I

help)

• Toolbar / ToolBarButton – the toolbars that control the user interfaceand the buttons within each bar

• DockableControl − a GeoMedia window-like container for ActiveXcontrols

• Document — the geoworkspace object

The Document object is the most significant one within this set because itprovides access to all of the data and display capabilities of GeoMedia.While your data is stored in an application (FRAMME, MGE) or adatabase (Access, Oracle SDO), your display definitions, queries, andtransformations are stored in the geoworkspace (document). While datacan be accessed through multiple documents, the definitions stored in theworkspace are unique to that workspace. GeoMedia supports a singledocument interface and does not allow multiple documents to be openedsimultaneously. Because many objects have an inherent association withthe document, you must be sure that you release any references to theseobjects before the document is closed.

Document

Continuing through the diagram, the following objects are associated withthe Document.

• Connections — collection of Connection objects that provide accessto the GDO (Geographic Data Objects) servers and to your data

• Windows — collection of windows open on this document (same asApplication.Windows)

• MasterLegend — a special instance of a legend object that GeoMediauses to assign the default style to recordsets

• Legends — collection of named legend objects

• QueryFolder — this object contains the collection of queryclassifications, each containing a collection of query objects

• SelectedObjects — the set of selected objects within the activedocument enabling the highlighting of the same object in multiplewindows

• CoordSystemsMgr — object governing the definition of projectionsand transformations. This object also provides the default coordinatesystem for each map window.

• SpatialFilters — collection of geometry objects that can be used tolimit the area of interest associated with a connection

Page 29: Customizing Geomedia

Automation Overview 29

• PropertySet − stores miscellaneous user-defined data

• ColorSchemes — collection of color palettes used in unique and rangelegend entries

As we know, the Windows collection is a metacollection in that it containstwo types of objects, MapWindow and DataWindow. The DataWindow issimply a container for the DataView custom control. The DataViewenables you to review the attribute information associated with all of therows in a recordset.

MapWindow

The MapWindow hosts three controls: MapView, NorthArrow, andScaleBar. Each of these controls provides information to assist the user ininterpreting the display of the geographic data.

• NorthArrow — an OLE control that indicates the true north positionrelative to the data displayed and the coordinate system of theMapView

• ScaleBar — an OLE control that indicates the scale of the datadisplayed in the MapView (e.g., 1” paper = 100 ft. ground)

• MapView — an OLE control that displays the geometric definition ofGIS data

The MapView is the key to the display of vector data and images. TheLegend member object defines which recordsets to display and in whatorder. The CoordSystemsMgr member object defines the projection usedto display the data.

• Legend — object which manages the display of data in the MapView

• LegendEntries — collection of legend entries in which each entryholds a recordset object and its associated style for display

• HighlightedObjects — collection of objects that are highlighted in theMapView to help distinguish the elements and make selections

• MapViewSelectedObjects — collection of objects within theMapView that are also in the SelectedObjects collection on theDocument

• CoordSystemsMgr — object governing the definition of projectionsand transformations for this particular MapView

Coordinate Systems

The CoordSystemsMgr is the primary object governing all activitiesassociated with the coordinate system. The CoordSystem member objectdefines characteristics of a particular GIS coordinate system. These

Page 30: Customizing Geomedia

30 Fundamentals of GeoMedia Development Part I

characteristics include the storage resolution and range, as well as ties tothe projection, geographic, geocentric, and paper reference spaces.

• CoordSystem — object which defines a particular GIS coordinatesystem.

• RefSpaceMgr — object which defines a set of reference spaces basedon a common geodetic datum and a set of algorithms for transformingcoordinate points among the members of that local set of referencespaces.

• UnitFormatSpec — stores units and formatting information. Thisobject formats and parses value and point strings representing distanceand coordinates.

• GeogSpace — object which specifies and retrieves the ellipsoid andgeodetic datum used to define the geographic reference space withinthe RefSpaceMgr object.

• PaperSpace — object which controls the nominal paper map scale and

Page 31: Customizing Geomedia

Automation Overview 31

returns and adjusts the projection-to-paper matrix. This matrix is usedinternally by the RefSpaceMgr object to transform points between theprojection and paper space.

• ProjSpace — object specifies and retrieves the projection algorithmused to define the projection reference space within the RefSpaceMgrobject. This object also allows modification of the projectionalgorithm parameter settings.

• AltCoordSystemPaths — a collection of AltCoordSystemPath objectseach of which contains a chain of transformations from theCoordSystem of the current CoordSystemsMgr object to othertransformations.

• LeastSquares − uses least squares mathematics to perform control-point-based registration between two sets of coordinate points

• DatumTransformation − defines a horizontal geodetic datumtransformation model and defines its parameters for thetransformation of coordinates between different geodetic datums

Legend

As you know, the legend controls the display characteristics of the data.The legend contains a collection of legend entries. The order of thelegend entries controls the display priority of the data. A recordset object(GRecordset) is associated with each legend entry. Additionally, a styledefines the visual characteristics of the data associated with the legendentry. Each legend entry object responds to similar properties andmethods. The differences in the types are related to the need for differentdisplay mechanisms for different data types. All geometric recordsets canbe displayed as RecordLegendEntry. Recordsets associated with rasterentries require different display techniques and thus are displayed with theRasterLegendEntry.

Page 32: Customizing Geomedia

32 Fundamentals of GeoMedia Development Part I

• RecordLegendEntry — type of legend entry that displays all geometryin the recordset with the associated style

• RasterLegendEntry — type of legend entry that displays a singleimage from the specified recordset

• RangeLegendEntry — a thematic legend entry that divides the inputrecordset into N ranges based on statistical analysis

• UniqueValueLegendEntry — a thematic legend entry that divides theinput recordset into N sub recordsets by grouping all of the rows fromthe recordset that have the same value for a specified field into a newrecordset

• Style — an object which contains display characteristics like color,weight, and style

• TitleFont, SubtitleFont, HeadingFont — Microsoft font object whichcontrols the font used for text display on the legend

• Range — an object that specifies the display characteristics of thesublegend entry and indicates the ranges of the associated data

Page 33: Customizing Geomedia

Automation Overview 33

• UniqueValue — an object that specifies the display characteristics ofthe sublegend entry and indicates the value associated with this set ofdata

• DisplayedObjects − object type of the HighlightedObjects andMapViewSelectedObjects containing a list of elements to highlight orselect

• RecordsetObject − reference to an entire recordset for highlight orselection purposes

• RecordObject − reference to a single row in a recordset for highlightor selection purposes

• GeometryObject − reference to a single row in a recordset identifiedby a graphic point for highlight or selection purposes

• RasterObject − reference to a single image for highlight or selectionpurposes

GDO

In GeoMedia, most all operations center around data access. GDO is thehub of that access. We use the recordset as the primary medium forcommunication between software components. All data servers supportthe GDO interface for accessing definition information and data.

Page 34: Customizing Geomedia

34 Fundamentals of GeoMedia Development Part I

• GDatabase — object which provides primary access to the data anddefinitions

• GTableDef — object which defines the structure of the data where asingle object defines one feature class or table in the database

• GField — object which defines one column in the database of a giventable

• GIndex — object which indicates the field upon which a table’sdatabase index is created for improving data retrieval

• GRecordset — object containing data from the data server

• GError — object indicating errors that occurred during processing

• GFRMAdminExtension — object containing administrativeinformation for FRAMME servers

• GFRMSeg — object specifying the segment name and number forFRAMME servers

• ExtendedPropertySet — an extension object available onOriginatingPipe based recordsets which provides metadatainformation

Page 35: Customizing Geomedia

Automation Overview 35

• Name — an extension object identifying the associated Query objectfor the recordset

• Notification — an extension object which provides access to methodsneeded to refresh a recordset when the criteria is changed

• Errors − an extension object which provides access to the GErrorscollection of the underlying database

• CoordSystem − an extension object that provides a GRecordset objectcontaining the coordinate system definition for the associatedgeometry field

Geometry and Styles

A GIS system without geometric data is like a fish out of water. GISapplications present and analyze spatial data. The geometry objects arethe visualization of that spatial data. The geometric data storage isdefined by the server. In traditional applications like FRAMME andMGE, the storage was in binary files. In the Access and Oracle SDOservers, the storage is as coordinate values in the relational database.Through GDO, all servers provide the geometric data in a binary (blob)format. To operate more effectively on the blobs, GeoMedia converts thedata from a blob to a geometry object. All of the geometry objects areautomated objects. This simplifies the process of manipulating the objectbecause the manipulation of the binary format is isolated to the geometryobjects and the geometry services – you do not have to create the blobformat.

Most presentations of GIS data would not be very interesting withoutstyles. A style is a definition of the color, weight, and pattern associatedwith an element. We support styles for each classification of geometryobjects. However, most style objects can be applied to any geometryobject.

Page 36: Customizing Geomedia

36 Fundamentals of GeoMedia Development Part I

• GeometryCollection — a set of geometry objects that represent aparticular spatial object

• PointGeometry — an object defining a point

• Origin — X, Y, Z coordinate values

• Vector − I, J, K coordinate values representing a vector in 3D space

• Matrix − a 4 x 4 matrix

• OrientedPointGeometry — an object defining a point with orientation

• TextPointGeometry — an object defining a point that has anassociated text string or label

• LineGeometry — a two-point vector

• PolylineGeometry — a vector defined by an unlimited number ofpoints

• RectangleGeometry — an object defining a rectangle

• PolygonGeometry — an object defining a closed shape (area) with anunlimited number of points

Page 37: Customizing Geomedia

Automation Overview 37

• BoundaryGeometry — a special type of closed shape which mightcontain holes or cut outs within the shape (area)

• Holes — collection of rectangle or polygon geometries that define thecut-outs within a boundary

• RasterGeometry — an object defining the display characteristics andthe bounding polygon for the image

• ArcGeometry − an object representing a circular arc in some plane in3D space

• CompositePolylineGeometry − collection of a geometries that form asingle continuous polyline

• CompositePolygonGeometry − collection of geometries that form asingle continuous closed shape

• AreaStyle — definition of style characteristics for gdbAreal types ofgeometry

• AnyStyle — definition of style characteristics for gdbAnySpatialtypes of geometry

• TextStyle — definition of style characteristics for gdbGraphicsTexttypes of geometry

• LinearStyle — definition of style characteristics for gdbLinear types

Page 38: Customizing Geomedia

38 Fundamentals of GeoMedia Development Part I

of geometry

• BitmapStyle — one of the definitions of style characteristics forgdbPoint types of geometry

• SymbolFontStyle — one of the definitions of style characteristics forgdbPoint types of geometry

• HandleStyle — definition of style characteristics for handlesdisplayed in selected data for edit operations

• PointSymbolStyle − one of the definitions of style characteristics forgdbPoint types of geometry

• PatternedLinearStyle − one of the definitions of style characteristicsfor gdbLinear types of geometry

• PatternedAreaStyle − one of the definitions of style characteristics forgdbAreal types of geometry

Pipes and Services

GeoMedia’s model contains many objects that are not dependent on theapplication object. Many of the objects presented in the previous sections,although navigable from the application, can exist independently of theapplication. In this section, we present a large set of objects that are not inany way dependent on the application object. The Controls groupincludes all of the GeoMedia custom controls. The Services groupincludes software components that accept some set of input, performcalculations, and return a set of answers. The Pipes group containssoftware components that accept some input (possibly includingrecordsets), perform a calculation, and output a new recordset. This is theprimary distinction between pipes and services. Pipes always output arecordset, while services provide discrete answers.

Page 39: Customizing Geomedia

Automation Overview 39

• AttributeFilterPipe — pipe object which filters or reduces arecordset’s number of rows based on an SQL attribute filter

• BufferZonePipe — pipe object that creates new geometry based on thegeometry in the input recordset

• SpatialQueryPipe — pipe object that spatially compares the two inputrecordsets

• CSSTransformPipe — pipe object that performs a coordinatetransformation on the geometry of the input recordset

• OriginatingPipe — special pipe object that creates an initial recordsetadding value to the GDO recordset (Name, ExtendedPropertySet,Notification)

• SortPipe — pipe object that orders the input recordset

• SortKey — object supporting the SortPipe

• CenterPointPipe − pipe object that calculates the center of a geometry

• EquijoinPipe − pipe object that creates a new recordset by joining two

Page 40: Customizing Geomedia

40 Fundamentals of GeoMedia Development Part I

input recordsets

• GraphicsTextPipe − pipe object that creates a text geometry bycalculating the label from attribute values

• MovePipe − pipe object that moves geometry

• SchemaProjectPipe − pipe object that allows fields to be hidden

• SpatialFilterPipe − pipe object that spatial constrains the rows in itsoutput recordset

• StatisticsService — component that statistically analyzes the inputrecordset

• GeometryDigitizeService — object supporting viewing of geometryobjects that are not currently stored in the database (during creation orfor temporary objects)

• GeometryEditService — object that supports geometry edit operations

• GeometryStorageService — component that converts betweengeometry blobs and geometry objects

• ServerTransService — component that provides methods forperforming common coordinate system operations

• RasterPropertiesService — object used for extracting informationfrom an image file and for creating a transformation matrix

• MeasurementService — object calculating the area, length, partiallength, and perimeter of a geometry object

• MetadataService — object which sets and retrieves feature classdefinition information to supplement the GDO GTableDef object

• TableProperty — MetadataService support object

• FieldProperty — MetadataService support object

• SmartLocateService — service object for finding elements within aspecified geometric region

• AutoPanService − service object for automatically adjusting the viewas the cursor nears the map window edge

• OutputTableService − service object for saving recordsets to tables

• SnapService − service object to assist in snapping to geometryelements

• SymbolFileService − service object for loading symbol objects for usein the style definitions

Page 41: Customizing Geomedia

Automation Overview 41

• GMMapView — OLE control which defines the MapView object

• GMDataView — OLE control which defines the DataView object

• GMDefCoordSystem — OLE control which supports the interactivedefinition of a coordinate system

• GMEventControl — OLE control that receives events from theMapView and fires them to your form

• GMFeatureCombobox — OLE control for displaying feature classesand queries on custom forms as a combobox

• GMFeatureListbox — OLE control for displaying feature classes andqueries on custom forms as a listbox

• GMNorthArrow — OLE control which defines the NorthArrow object

• GMScaleBar — OLE control which defines the ScaleBar object

• GMWebBrowser − OLE control which supports the integration of

Page 42: Customizing Geomedia

42 Fundamentals of GeoMedia Development Part I

Internet Explorer

• GMPlacement − OLE control used during feature placement to selecta feature and geometry type

• GMProperties − OLE control used during feature placement andediting to gather attribute values. Use of this control duringdevelopment requires a license of True DBGrid Pro 5.0 from ApexSoftware Corporation. Upgrades are available from the DBGridcomponent provided with Visual Basic 5.0. Visit their web site formore information: http://www.apexsc.com/.

• GMTextPlacement − OLE control used during interactive textplacement

• GMPrecisionCoordinate − OLE control that supports coordinatereadout

• PickQuickDialog − dialog that assists users distinguish multipleelements during a highlight operation

• PageSetup − command object used in independent applications toinitiate the mapview page setup

• Print − command object used in independent applications to initiatethe mapview print operation

• GMFeatureComboboxInput − OLE control that creates a recordset

• GMFeatureListboxInput − OLE control that creates a recordset

• GMQueryStorage − OLE control that stores recordsets in queryfolders

• GMTableStorage − OLE control that outputs a recordset to a GDOtable

• GMLegendEntryOutput − OLE control that creates a legend entry fora recordset

• GMDataWindowOutput − OLE control that displays a recordset in adata window

• GMJoinProperties − OLE control that provides a GUI interface for theEquijoinPipe

• GMLabelProperties − OLE control that provides the GUI forspecifying the label content

• EventServer — object which allows events from multiple mapwindows to funnel into a single event control

Page 43: Customizing Geomedia

Automation Overview 43

• MapViewListeners — object which manages commands that arelistening to events in MapViews

• GeoMathUtilities − a C function library of math functions callable byautomation clients

IMPORTANT: Use the automation help to find more details on each ofthe objects. Initiate Programming Utilities and select GeoMedia ObjectReference. You may also select the help icon from the Visual BasicObject Browser.

Lab 1: Navigating the GeoMedia automation model

In this lab, you will use the automation diagram to find the requestedobjects in the hierarchy. Each lab step will ask you to create a referenceto a particular object or property within the automation model. Theanswer can be a single statement that uses the navigation (dot) operator.You will need to use the automation diagrams presented in this section aswell as the Automation Help and the Visual Basic browser.

Exercise setup:

1. From the GeoMedia program group or from the Start Menu, selectProgramming Utilities. Select GeoMedia Object Reference. Thiswill provide access to all of the help topics.

2. Start Visual Basic and open the project inc:\TGM\Labs\Lab01\src\GeoMediaCommand.vbp. This will provideyou with access to context sensitive help on each object.

3. Open C:\TGM\Labs\Lab01\NavigationLab01.txt with Notepad. UseApplication or gobjGeoApp to refer to the application object for theexercises.

As we will see in the next section, GeoMedia commands are initializedwith two global objects: gobjGeoApp and mobjGeoViewListeners.The former is a pointer to the GeoMedia application object. Thelatter is a pointer to the set of commands actively listening for eventson the map views.

4. Specify the answer in the text file. Use the help to assist you infinding the correct property names. Problems 9 and 10 are extracredit.

Page 44: Customizing Geomedia

44 Fundamentals of GeoMedia Development Part I

Approaches to CustomizationAs with many of Intergraph’s GIS products, customization capabilities area very important aspect of the product. Additionally, many productswhich have traditionally served as “out of the box” applications also allowyou to configure or modify the interface to the product. GeoMedia offersthree mechanisms for customizing the product. The approach tocustomization will depend on your requirements, your level ofprogramming expertise, and the suitability of the standard GeoMediainterface to your needs.

These three approaches can be viewed through the following diagrams.

Commands

GeoMedia.exe

CustomCommandDLLs

ObjectDLLs

Using this technique, GeoMedia is enhanced with command DLLs and theGeoMedia object DLLs. Recall the discussion of in-process and out-of-process execution of software components. In this model, during normaloperation, there is a single process executing so all components are in-process.

Page 45: Customizing Geomedia

Automation Overview 45

Custom Application

Custom.exeObjectDLLs

Using this technique, you build your own executable using GeoMedia’sobjects. There is again only a single process executing.

Driving GeoMedia

GeoMedia.exe

Custom Command DLLs

ObjectDLLs

Custom.exe

ObjectDLLs

In this approach, there are two separate programs executing.

Customizing GeoMedia through menus andcommands

In this approach, you begin with the GeoMedia application. You maycreate a new set of GeoMedia commands that augment the GeoMediacommands or perform tasks in an order more suited to your environment.

Page 46: Customizing Geomedia

46 Fundamentals of GeoMedia Development Part I

We will see how to create commands in the next section of the workshop.

The simplest approach to customization involves only tuning theGeoMedia menus. You may remove menu items that you do not need ordo not want your user to access. The Tools > Customize command canbe used to configure the menus and the keyboard accelerators. Anaccelerator is a keystroke defined by the application to give the user aquick way to perform a task. An accelerator is also known as a short-cutkey. For example, pressing the control key (CTRL) and N is equivalent tothe File > New GeoWorkspace... command selection. You can removemenu items from the menubars. There are three types of menus availablefor modification:

• Map — menubar that displays when a map window is active

• Data — menubar that displays when a data window is active

• None — menubar that displays when no document is open

If you want to remove or reorder commands that exist in all window types,you will need to remove them from each of the menu types.

Menu and accelerator customization is stored in the registry atHKEY_CURRENT_USER\Software\Intergraph\GeoMedia\02.00 underMenus and Keyboard, respectively. Since they are stored in this location,it is possible to have different menu configurations for different types ofusers who might share a single computer. If you are configuring anenvironment for several users, we recommend that you write a commandor application which utilizes the application’s automation model(MenuBar/MenuItem, Accelerator, Category/Command,ToolBar/ToolBarButton) to configure your menus.

If you find that you need more commands than GeoMedia provides, youwill need to write these and add them to the GeoMedia command set. Youwill need to move your custom commands to every machine. They canreside in any directory that you choose. You will need to install eachcommand. This will register the command so that the GeoMediaframework can create it (with CreateObject) and add it to the GeoMediacommand set. The installation syntax is:

“c:\Program Files\GeoMedia\Program\Installusrcmd.exe”MyCommand.dll MyCommand.ini

Substitute the appropriate installation location when accessing theexecutable. If you are not in the directory containing the .dll and .ini files,include the full path. The .ini file is created when the command is createdthrough the GeoMedia Command Wizard. It contains information aboutthe command, its tool tip and status prompt, and the enabling conditionsfor the command. It is possible to create multiple commands in a singleDLL to reduce the number of files that must be delivered.

Page 47: Customizing Geomedia

Automation Overview 47

Note: Installing Sample Commands: If a command is accompanied by aGMSampleXXX.txt file, you can use the Programming Utilities moduleto install the sample command in lieu of installusrcmd.exe.

You will also need to add menu items for your custom commands. If youhave commands that are applicable to all windows, you will need to addthem to each of the menu types.

You can also create custom workspace templates. Through the templates,you can define standard connections, legends, and queries that your userwill utilize on a frequent basis. You can also define the displayedwindows and the status of the legend entries.

The advantages of customizing GeoMedia through command creation andmenu configuration are:

• quicker start up

• availability of all window and document-management functions

• automatic persistence of display environment and options

• incremental expansion of capabilities

• ability to focus development and testing only on additional end-usercapabilities

As you will see when we create a custom application, there is a significantamount of development work associated simply with maintaining theapplication framework. By customizing GeoMedia through commands,you can focus your efforts on end-user functionality.

Note: DLLs generated with PowerBuilder 5.0 cannot be called byexternal applications. The GeoMedia command framework createscommands as in-process OLE servers. Since you cannot do this inPowerBuilder, you will have to create a VB wrapper command that canthen communicate with the PowerBuilder.Application object. Because theapplication will be out-of-process, you need to be sure and create anypersistable GeoMedia objects through the Application.CreateServicemethod. You should also use this method for any objects that arearguments or properties of other objects created with the method.

Custom applications using GeoMedia objects

Another approach to GeoMedia development is to create a customapplication using the GeoMedia objects. In this scenario, you develop

Page 48: Customizing Geomedia

48 Fundamentals of GeoMedia Development Part I

your own framework, including window management, documentmanagement, and persistence. You then utilize the automated objects inyour commands and application processing to perform the desiredanalysis. In this case, you will create an executable and, possibly,supporting DLLs. Your executable and any supporting DLLs you havecreated may utilize GeoMedia DLLs.

This approach is often taken when the end user is granted very littleflexibility in using the product. For example, you may not want to allowthe end user to change the legend configuration that you have defined. InGeoMedia, we do not provide any option for a “read only” legend.

In the automation diagrams, all public GeoMedia objects can be used incustom applications except those that are explicitly associated with theframework (application). These objects are:

Table 0-2

Application Windows ActiveWindow

Category(s) Command(s) MenuBar(s)

MenuItem(s) Accelerator(s) Document

DataWindow MapWindow MasterLegend

SelectedObjects MapViewListeners GMFeatureCombobox

GMFeatureListbox ToolBar(s) ToolBarButton(s)

GMFeatureComboboxInput

GMFeatureListboxInput

GMQueryStorage

GMTableStorage GMLegendEntryOutput

GMDataWindowOutput

All of these objects require some information associated with theapplication or document, therefore they are only creatable within thecontext of the application. That is, GeoMedia must be running for theseobjects to exist.

With a custom application, you are responsible for delivery andregistration of the GeoMedia components that you use. The standardmechanism is to install GeoMedia and then install your application. Thiswill require a full GeoMedia license and provides the user with the abilityto use the full product. You are required to include the GeoMediacopyright information in the delivery of your application. This is usuallyspecified in the application’s Help > About MyApp... command.

Intergraph will discuss opportunities with individuals and third-partydevelopers to purchase object bundles. Please contact the Team

Page 49: Customizing Geomedia

Automation Overview 49

GeoMedia Technical Staff ([email protected]) to discuss such an OEM(Original Equipment Manufacturer) agreement. The object bundles aredivided by sets of functionality that would comprise the application. Forexample, a simple viewing application requires a certain set of objects,while an analysis application would require additional objects. Refer toObject Bundles in the Appendix for the object breakdown.

The advantages of creating a custom application with GeoMediacomponents are:

• ability to strictly control the user workflow

• ability to specify the complete look and feel to match other productsused in your workflow

• reduction in application footprint by eliminating unused components

Note: A custom application is the only logical option for PowerBuilderusers since it does not support other applications calling into its DLLs.

If you have arranged an OEM agreement with Intergraph, you may notinstall the GeoMedia application on the end-user machine. You mustinclude the GeoMedia component installation and registration in yourcustom setup.

Driving GeoMedia

One final option for customizing GeoMedia involves creating a customapplication that runs or drives the GeoMedia application object. In theprior discussion, you used objects from GeoMedia that were NOT relatedto the framework. In this approach, you will create an application (.EXE)and then create the GeoMedia application or attach to an existing instanceof GeoMedia. Hence, two separate executables will be active. This issimilar to the lab exercise in which we wrote a Visual Basic application todrive Excel. You then have access to all of the GeoMedia automationmodels. In this way, you get all of the benefits of the GeoMediaframework, but you are able to restrict access or control the user’sworkflow.

GeoMedia objects should be created using the Application.CreateServicemethod rather than CreateObject directly. This ensures that all objects arecreated within the GeoMedia process and share the same memory space.

Page 50: Customizing Geomedia

50 Fundamentals of GeoMedia Development Part I

SummaryThe primary objective of this section was to familiarize you withautomation capabilities and to prepare you for GeoMedia customization.To this end, we discussed basic object-oriented techniques andOLE/COM. We focused on the topic of automation within the realm ofOLE. You should be able to define these terms:

• Automation client/controller

• Automation server/object

• Object

• Property

• Method

• Collection

• Dot/navigation operator

• GUID, ProgID

• Interface

You should understand these fundamental GeoMedia concepts:

• GDO

• Pipes

• Legend

• Coordinate System

• Features

You should understand an automation diagram and be able to traverse it.Finally, you should understand the options for GeoMedia customization.

The next section will investigate the first customization option: addingGeoMedia commands.

Page 51: Customizing Geomedia

Automation Overview 51

Can You Answer These Questions?1. What is the purpose of Team GeoMedia?

2. What does COM stand for?

3. When you hear the word “Automation”, what two words come tomind?

4. What are the benefits of OLE?

5. What three ways can be used to customize GeoMedia? Give anexample of each.

6. How many legend entry types are there?

7. What is the component hierarchy in GeoMedia from Application toRecordLegendEntry?

8. In your program, you are iterating through the legend and examiningeach entry. How do you know the type of the legend entry?

9. Given the following definition, provide two other ways to create aninstance of the object.

Dim objMD as Object

Set objMD = CreateObject(“GMService.MetadataService”)

Page 52: Customizing Geomedia

52

Page 53: Customizing Geomedia

53

Creating a Custom Application

Introduction

In this section, you will be creating an independent custom applicationusing Visual Basic as the automation controller or client (scriptinglanguage and application) and the GeoMedia objects.

This is a very common approach to customizing GeoMedia. Manycustomers have the requirement to create their own independentapplications using the GeoMedia objects (and perhaps automationobjects from other applications). There are several reasons why this maybe the best approach for your application. One reason is that you arebuilding an application where GeoMedia functionality is only a smallpart of the overall application. It may be easier to create this applicationfrom scratch, and then in the appropriate places call GeoMediafunctionality to perform certain necessary GIS tasks. Another reasonwould be that you want to limit the flexibility and functionality of youruser much more so than you could simply by customizing the existingGeoMedia framework application. It may be that your requirementsdictate a different look and feel of your application than GeoMediaprovides. And, as already mentioned, if one of the requirements is thatyour application be developed using PowerBuilder, this is the mostlogical approach since PowerBuilder does not support other applicationscalling into its DLLs. This section of the workshop discusses thisparticular approach to customizing GeoMedia.

In the first lab of this section, you will add a small amount of code to anexisting Visual Basic project. That first lab will primarily focus onfamiliarizing you with an application which has been built for you — itsframework, menus, windows, and forms. For the remainder of thisworkshop, you will be adding functionality to this same project, each labbuilding upon the previous one. By the end of this section, you willhave built quite a functional application. This Visual Basic project isdesigned to output a single executable which utilizes both Visual Basicobjects and GeoMedia objects contained in their delivered DLLs. It willrun stand-alone — independent of GeoMedia. This means thatGeoMedia is providing the necessary functionality in the background.You are not actually running the GeoMedia product — you never see itsapplication framework running.

While this approach gives you — the application developer — muchmore flexibility, it also means that you have more initial work to do thatis provided for you when you add commands to GeoMedia. Forpurposes of this class, the framework and windows management portionsof the application have already been provided in the lab templates.

Page 54: Customizing Geomedia

54 Fundamentals of GeoMedia Development Part I

Topics

1. Connecting to the GDO Server

2. Creating Recordsets

3. Adding a MapView and Displaying Data

4. Creating and Displaying Queries

5. Creating a Data View

6. Custom Application Limitations

Objectives

At the end of this section, you will be able to do the following.

1. Explain the independent application approach to GeoMediacustomization

2. Use these GeoMedia objects:

GDatabase GRecordset GField

MapView Legend LegendEntries

Style DataView

3. Implement a GeoMedia custom application

Labs

2. Application Framework and Connecting

3. Creating and Manipulating Recordsets

4. Constructing the MapView

5. Optional: Styles

6. Optional: Marginalia

7. Optional: Printing

8. Spatial Query

9. Buffer Zone

10. Locate

11. Optional: Data View

12. Optional: Multi Key Sort

Page 55: Customizing Geomedia

Creating a Custom Application 55

Connecting to the GDO ServerTypically, one of the first actions your application will have to do (orallow the user to do) is make a connection to an existing GIS database— what GeoMedia calls a warehouse. This is accomplished viafunctionality in one of the GDO servers. For example, if you need toconnect to an MGE database, you will be using the MGE GDO server;for Access, the Access GDO server.

GDatabase

GError

GTableDef

GRecordset

GField

GIndex

GField

GField

Specifically, this is accomplished by creating a GDatabase object, andthen calling its OpenDatabase method.

Dim objAccessDbs As GDatabase

Set objAccessDbs = CreateObject (“Access.GDatabase”)

objAccessDbs.OpenDatabase “D:\wherever\myDB.mdb”

Note: When creating a GDatabase object, you will need to use theabove method so that the appropriate GDO server’s GDatabase will becreated. You accomplish this by specifying a particular GDO server asthe prefix of the ProgID passed to CreateObject. The optional VisualBasic syntax for creating an instance of an automation object

Dim objAccessDbs As New GDatabase

will not work.

Page 56: Customizing Geomedia

56 Fundamentals of GeoMedia Development Part I

There are nine different GDO servers. The prefix for the ProgIDs are asfollows.

Server Type Prefix

Access Access

ArcInfo AI

Oracle Spatial Cartridge GW

MGE MGE

FRAMME FRAMME

MGE Segment Manager MGSM

ArcView AV

MGDM MGDM

CAD Server GCAD

Establishing access to the GIS data from the GDatabase object may suityour purposes well. However, you may want to take advantage of someGeoMedia functionality that requires that you actually start creatingobjects at a higher level in GeoMedia’s automation model. Specifically,you may want to use the GeoMedia Connections collection andConnection object. For example, if your application is going to allowmore than one connection, the Connections collection can serve as adynamic data structure for the multiple databases your user might access.Also, if you want to take advantage of the MetadataService or createOriginatingPipe objects, you must use the Connection object.

You can accomplish the same functionality as above with GDatabase bydoing the following with Connections:

Dim objConnections As New Connections

Dim objConnection As Connection

Set objConnection = _objConnections.Add(“D:\wherever\myDB.mdb”)

With objConnection

.Type = "Access.GDatabase"

.Location = “D:\wherever\myDB.mdb”

.Connect

End With

Now, you have the ability to add additional connections in a likemanner, and you can use the services mentioned above.

Page 57: Customizing Geomedia

Creating a Custom Application 57

Debugging Your Application

Interactive debugging within the Visual Basic development environmentis very intuitive. Certain general rules should be applied in thedevelopment of your application for successful development anddebugging. For any functions or procedures that manipulate objects insome way such that they might encounter errors, you should alwaysinclude an error handling clause. Refer to the Err Objectdocumentation in VB help for more information on this construct.Additionally, you should always include Option Explicit in every file inyour project. This forces method and property names as well asargument sequences to be checked during compilation. Finally, usestrong typing wherever possible rather than Object declarations.

You can run your program interactively or compile and execute it.During initial development, you will want to run the program fromwithin the Visual Basic project environment. Open your Visual Basicapplication project. Set any breakpoints needed in the source code.Select the Run > Start (or the Start button). When your applicationcommand is selected, you will break at the locations you set. All normalVisual Basic debugging capabilities are available to you. Alwayscontinue (with the Start command) at the end of your functions andsubroutines.

You can stop debugging at any time to terminate your application.When you have made code corrections, select Run > Start again andrepeat the process.

To avoid causing a crash on exit from the application, be sure andrelease all variables whenever their use is no longer required.

If a part of your command is not suitable for interactive debugging, youwill need to use status prompt messages and/or MsgBox calls todiagnose the cause of your errors. You can use the application status barto display information messages about your command progress. Thiscall is:

MfrmMain.stbMainStatusBar.SimpleText = _

“Step 1 preparation”

This technique is less intrusive than a message box. If you opt formessage box displays, you should consider writing a DebugMsgBoxfunction. For example:

Page 58: Customizing Geomedia

58 Fundamentals of GeoMedia Development Part I

Global Const iCurrentSeverity = 5

Public Function DebugMsgBox( iSeverity As Integer, _

strPrompt As String ) As Long

If iSeverity >= iCurrentSeverity Then

DebugMsgBox = MsgBox strPrompt, _

vbOKOnly + vbExclamation, _

“My Command Title Error”

Else

DebugMsgBox = vbOK

End If

End Function

With this type of function, you can retain your diagnostic informationwithout continual editing of your code while controlling the extent of thedebug information displayed. To turn off diagnostics completely, youcan exit the function immediately.

Lab 2a: Debugging Your Application

1. Start Visual Basic.

2. Open the project for the custom application. This file isc:\TGM\Labs\CustomApp\src\CustomApp.vbp.

3. In the Project Window, under the CustomApp (CustomApp.vbp)folder and Forms subfolder, select mfrmMain (mfrmMain.frm)from the Project Window and select View > Code (or double-clickon mfrmMain (mfrmMain.frm)).

4. Select the MDIForm_Load method, and set a breakpoint on the lineinitializing the bInitDataRecordset variable by depressing thefunction key F9 or through Debug > Toggle Breakpoint. You canalso click the mouse in the gray column to the left of the codewindow.

5. Select the mnuFileOpen_Click method, and set a breakpoint on theOpenDatabase subroutine call.

6. Start your application by selecting the Start button or the Run> Start command.

The debug window -- Immediate -- will appear.

7. The program will stop immediately in the form load subroutine.

8. Step over the initialization statements, either by depressing thefunction key F8 or through Debug > Step Into, and select Startbefore you reach the end of the MDIForm_Load method.

Page 59: Customizing Geomedia

Creating a Custom Application 59

9. Select File > Open. The program will stop again at the call toOpenDatabase. Step into the OpenDatabase subroutine.

10. Step over the statements (using SHIFT+F8 or Debug > Step Over)until you are positioned at the conditional test for the value ofstrFile. You will need to select a warehouse before you can get tothis comparison.

11. In the Debug Window, key in: print strFile.

The debugger will display the current value of strFile. You can alsohold your cursor over the variable name. A little tooltip box willappear containing the value. .

12. Select Start to continue execution of the command.

13. Stop the debug session by selecting the stop button or Run > Endfrom the menu. Exit Visual Basic.

Summary: This section showed you how to establish the debugenvironment for your application and some of the basic operationsavailable for debugging.

Lab 2b: Application Framework and Connecting

In this lab, you will be writing the code behind the File > Open, File >Close, and File > Exit commands on the menu bar in the customapplication. Remember that this application will be modified in all ofthe remaining labs. File > Open will make a connection to an Accessdatabase. File > Close will close the chosen connection. File > Exitwill clean up references and exit the application.

Note: Before you can use GeoMedia objects in a custom application,you need to add its Program directory to your path. You should do thison your lab machines by selecting Start > Settings > Control Panel onthe Windows NT task bar. Now choose System. From theEnvironment tab, select Path in the System Variables: list. Youshould now see Path in the Variable: text box near the bottom of thedialog and your existing path in the Value: text box. Place your cursorin the Value: text box and go to the end of that path. Type in thefollowing value, substituting your appropriate drive and directorystructure:

;C:\Program Files\GeoMedia\Program

Do not place any quotes around this value. Now choose the Set button,and select OK to dismiss the dialog. You will need to reboot yoursystem to ensure that the new value has taken effect.

Page 60: Customizing Geomedia

60 Fundamentals of GeoMedia Development Part I

1. Open the Visual Basic projectC:\TGM\Labs\CustomApp\src\CustomApp.vbp. In the ProjectWindow, under the Modules folder, select modDatabase, and selectView > Code.

2. In Sub OpenDatabase, create a Connection by calling the Addmethod on the global Connections object already created for you—gobjConnections.

This is the function called when you select File > Open. Don’t forgetthat object variables need to be Set in Visual Basic. The argumentto the Add method is the value of the local variable strFile. Theglobal variable, gobjConnections, is declared in modGlobals.bas.

3. Make the actual connection (open the database) by setting the Typeand Location properties of your new connection, and by calling itsConnect method.

The Type property needs to be set to the same string as the ProgIDargument would be if you were creating a GDatabase object—in thiscase “Access.GDatabase”. The Location property is the path to theactual warehouse file, in this case the .mdb. This is the stringreturned by the BrowseForFile function already in your project (itgets it from the Common File Open dialog). When you’re finishedmaking the connection — call the Connect method.

4. In Sub CloseDatabase, populate the lstDatabases List box onfrmDatabase with each of the open connections.

The loop processes every connection in the collection by looking at theCount property. You only want to put open connections in the list,so you will look at the value of the Status property on theConnection object. When you find an open connection, add thename of the connection (ConnectionName) to the listbox. You mayclose the code window when you have completed this step.

Note: All of the form’s controls have been named such that the prefixindicates the type of control. For example, lstSomething is a listbox,txtValue is a textbox, and cboChoices is a combobox.

5. In the Project Window, under the Forms folder, selectfrmDatabase, and select View > Code.

6. In Sub btnOK_Click, find the connection the user has chosen in theConnections collection and close it.

You can iterate over each of the connections in the gobjConnectionscollection. Determine if it is the one the user has chosen bycomparing its ConnectionName property with the item in the listbox the user chose. Close it by calling the Disconnect method onthe connection object. You can close the code view window forfrmDatabase.

Page 61: Customizing Geomedia

Creating a Custom Application 61

7. In the Project Window, under the Forms folder, select mfrmMain,and select View > Code.

8. In Sub MDIForm_Unload, close any open connections, and releasethe global pointer to the Connections collection—gobjConnections.

You will need to reference the global collection (gobjConnections) andthen call the Disconnect method on each item in the collection. Torelease an object variable, set it to Nothing.

9. Now, test your code by running the application, and exercise File >Open, File > Close, and File > Exit from the Main Window.

Choose the Start command from the toolbar or Run menu. In yourapplication’s main window, main menubar, select File > Open. Inthe Common File Open dialog, choose an Access database (e.g., USSample Data.mdb in the Warehouses directory). Select File >Close, and choose the connection you just opened. Try havingmultiple connections open and having more than one to choose fromwhen you close. Select File > Exit.

Summary: In Lab 2, you have created a connection object, added it tothe application’s collection, and connected to the database. Also, inimplementing the close command, you have disconnected from thedatabase. Although we don’t set the Mode property, you will need to dothis for read-only connections. Use the constant gmcModeReadOnlyfor the value. You have also practiced debugging your application

Page 62: Customizing Geomedia

62 Fundamentals of GeoMedia Development Part I

Creating and Manipulating RecordsetsOnce you have connected to a warehouse or database, the primary objectyou will be using to manage the data is a GRecordset (often just calledrecordset). You can create a recordset in one of two ways. The first issimply by calling the OpenRecordset method on a GDatabase object.The second is by creating an OriginatingPipe.

A recordset is a data structure containing graphic and attribute data. It isanalogous to a database cursor. The recordset is important withinGeoMedia as it is the common data unit for communication betweensoftware components.

Creating a Recordset with OpenRecordset

Given a GDatabase object − either one created independently or throughthe Connection object, you can call OpenRecordset to create arecordset. For example:

Dim objRS As GRecordset

Set objRS = objAccessDbs.OpenRecordset (“Parcels”)

This will populate objRS with a GRecordset containing all the parcels inyour database with each parcel represented as a row or record in therecordset. Just supplying a GTableDef name (e.g., “Parcels”) is theequivalent of passing an SQL select statement to select all members ofthe given GTableDef. Therefore, the above statement is equivalent to:

Set objRS = objAccessDbs.OpenRecordset (“SELECT *FROM Parcels”)

You can further refine the results with attribute query criteria, as in:

Set objRS = objAccessDbs.OpenRecordset (“SELECT *FROM Parcels WHERE AssessedValue > 100000”)

Additionally, you can apply a spatial criteria for filtering by using otheroptional arguments to the OpenRecordset method.

There are several additional optional arguments to OpenRecordset.This discussion will address one of those. The second argument toOpenRecordset is optional and determines the type of Recordset created.By default (i.e., if the second argument is not specified), a Dynasetrecordset is created (or by supplying gdbOpenDynaset as this secondargument). The other type is a Snapshot recordset, created by supplyinggdbSnapshot as the second argument.

A dynaset recordset is updateable (if your connection and GDO serverare read/write) and is a “dynamic” view of your data. In other words, theactual field values are gathered from the GDO server on demand, so thatyou will always get the latest data. This is powerful, but can be slowerespecially if the data is coming across a network connection.

Page 63: Customizing Geomedia

Creating a Custom Application 63

A snapshot recordset is a static copy of the data generated at the timeyou called OpenRecordset. It’s a picture or view of the data at the timeyou generated the recordset—it’s not aware of changes made to that dataafter you created the recordset. You cannot add, delete, or edit itsrecords. But, a snapshot is more performant if the dynamic orupdateable aspects of a dynaset are not needed.

Creating a Recordset with OriginatingPipe

As alluded to earlier, the second method for creating a recordset uses anOriginatingPipe. In essence, the same information is provided to theOriginatingPipe object via its properties as is provided to theOpenRecordset method via its arguments. In fact, the OriginatingPipecreates its output recordset by calling OpenRecordset. Then why havea second way of creating a recordset? Pipes add additional functionalityto recordsets including the following.

• Persistence

• Notification

• Metadata access

• Recordset naming

• Errors

• CoordSystem

These additions add significant power to your GeoMedia applications.Except for persistence, all of these additions are available in customapplications.

You create an OriginatingPipe using the CreateOriginatingPipemethod on a Connection. Once created, supply it with the necessaryproperties as criteria for the particular data you want, then reference theOutputRecordset as you would any other recordset.

Dim objOP As OriginatingPipe

gobjConnections(1).CreateOriginatingPipe objOP

objOP.Table = “Parcels”

objOP.Filter = “AssessedValue > 100000”

Dim objRS As GRecordset

Set objRS = objOP.OutputRecordset

Manipulating Records in a Recordset

In the next section, you will learn how to display a recordset on a map,and how to display its attributes in a DataView. But, how do you workwith the records (rows) and fields (columns) of a recordset individually?As mentioned earlier, set notation differs from collection notation. You

Page 64: Customizing Geomedia

64 Fundamentals of GeoMedia Development Part I

iterate over a recordset using the move methods (Move, MoveFirst,MoveLast, MoveNext, and MovePrevious), such that you always havea current record (pointed to by the Bookmark property). You then caniterate over the fields of that record (or jump to a particular field) via therecordset’s GFields collection.

For example, given a recordset, you typically can access each and everyrecord with code similar to the following:

Set objRS = objDB.OpenRecordset (“Parcels”)

If Not (objRS.EOF and objRS.BOF) Then

Do Until objRS.EOF

.

‘ code processing the individual records

.

objRS.MoveNext

Loop

Else

MsgBox (“No Parcels found.”)

End If

Note: In the above code, you are checking for a non-empty recordset byensuring that its EOF and BOF are not both True. The recordset alsohas a RecordCount property. The RecordCount will be greater than 0when the recordset is first opened as long as there is at least one record.This property will return 0 had there been no records satisfying thequery. However, the property cannot be depended upon to return thetotal number of records in a non-empty recordset until either the loopabove finishes processing (i.e., you’ve done a MoveNext through everyrecord) or a MoveLast has been issued on the recordset. Both areexpensive operations just to get the record count, and should not beissued unless the exact count is needed. Otherwise, you can use thisproperty like a boolean property telling you whether the recordset isempty (value of 0) or not (some other value). Or, accomplish the sametest by checking to see if both the BOF and EOF properties are True, inwhich case the recordset is empty.

The BOF property is set to True when the recordset is empty or whenyou’ve done a MovePrevious beyond the first record. EOF is set toTrue when the recordset is empty or when you’ve done a MoveNextbeyond the last record.

Page 65: Customizing Geomedia

Creating a Custom Application 65

IMPORTANT: A common mistake is to forget to put the MoveNext ina loop similar to the one above. In this case you’ve created an infiniteloop.

You can process the fields as you would any other collection using a Forloop if you want to iterate over all of them. For example, in the codeabove, you might want to iterate over each of the fields. Inside the loop,add code as follows:

Dim objField As GField

For Each objField in objRS.GFields

Print #1, objField.Name & “:” & CStr(objField.Value)

Next objField

Note: If this code is inside the recordset loop in the previous example,objRS will successively point to each record or row in the recordset.

Geometry Formats

How does the GDO server expose the geometry of the features beingreturned? In the same way it exposes all the other attributes of thefeature — as a GField object. Each GField object has a Type property.A geometry field will have a Type of gdbSpatial or gdbGraphic. If theType of the field is gdbSpatial or gdbGraphic, then it will also have aSubType property that further defines the geometry type. Valid valuesfor SubType in GeoMedia are shown relative to the geometry types.

Type / SubType Description

gdbSpatial Classification of data such that thecoordinate information is assumedspatially accurate

gdbLinear Geometry which is comprised of a seriesof points

gdbAreal Geometry which is comprised of a seriesof points where the first and last pointare coincident. The area may includeone or more holes.

gdbAnySpatial Geometry which might either containone of each type of geometry (gdbPoint,gdbLinear, gdbAreal) in a collection ormight contain any one of these types in agiven feature class

gdbCoverage Geometry describing an image (raster

Page 66: Customizing Geomedia

66 Fundamentals of GeoMedia Development Part I

data)

gdbPoint Geometry defined by a single point

gdbGraphic Classification of data such that whilecoordinate information is identifiedrelative to the earth, the spatial locationis not significant. This type is usuallyassociated with annotative data likelabels.

gdbSpatial Same as in gdbSpatial.

gdbLinear Same as in gdbSpatial.

gdbAreal Same as in gdbSpatial.

gdbAnySpatial Same as in gdbSpatial.

gdbCoverage Same as in gdbSpatial.

gdbGraphicsText Geometry defined by a point and a textstring.

gdbPoint Same as in gdbSpatial.

The values for the geometry fields are exposed in a binary format oftencalled a BLOB (Binary Large OBject). This format is documented onthe Team GeoMedia web site in the Technical White Paper “GeometrySpecifications.”

The values for these geometry fields are not exposed as Geometryobjects. The GeometryStorageService object provides methods forconverting from this storage format to a Geometry object and vice-versa.

When writing applications that need to read or write these valuesexternal to GDO, it is recommended that you use the Geometry object toabstract your program from the binary format. This will make yourprogram less vulnerable to needing modification should these formatschange in the future.

Lab 3: Creating a Recordset

In this lab, you will be writing the code behind Analyze > RecordsetInformation. You will complete the code in a sub procedure(CreateRecordset) that will display a dialog to the user of all connectionshe has open and all valid tables for him to select from each of thoseconnections. Given his selection, you will then complete the code inanother sub procedure (AnalyzeRecordset) to take that table and displaysome analysis of the recordset generated on that table.

1. Open the Visual Basic projectC:\TGM\Labs\CustomApp\src\CustomApp.vbp. In the ProjectWindow, under the Forms folder, select frmSelectFeature, and

Page 67: Customizing Geomedia

Creating a Custom Application 67

select View > Code.

2. In Sub cboDatabases_Click, get the list of all tables in the activeconnection and populate the lstFeatures list box with those tables.

You could accomplish this by populating the list box with each of theGTableDef.Name values. This would, however, return even thenon-displayable (i.e., metadata) tables. Therefore, it is better tocreate a MetadataService (objMDSrvc) and use its GetTablesmethod to get only displayable tables.

The returned data is stored in vTableList. The data type is Variantwhich simply means any data type may be stored in this argument.In this case, an array of strings is returned. The Visual Basic builtin functions, UBound and LBound, return the upper and lowerbounds of the array dimension.

3. In the Project Window, under the Modules folder, selectmodRecordset, and select View > Code. In Sub CreateRecordset,create a recordset using an OriginatingPipe. The recordset will bebased on the feature the user selected.

Create an OriginatingPipe by calling CreateOriginatingPipe on theconnection returned from GetSelectFeatureInfo. This is store in thevariable objActiveConnection. Set its Table property to the tablename returned from GetSelectFeatureInfo. Assign theOutputRecordset of the OriginatingPipe to the output argument ofCreateRecordset (objRS). The CreateRecordset sub procedure isused in multiple places throughout this application. You will alsosee that this subroutine creates the transformation object for thedata that will be displayed from this recordset. This operation isdiscussed in subsequent exercises.

4. In Sub AnalyzeRecordset, call CreateRecordset to have the usercreate a new recordset.

This is the sub procedure called when you select Analyze > RecordsetInformation Recall that a subroutine calling statement does notrequire parenthesis around the arguments. ObjRS is the argumentto CreateRecordset.

5. Display the name of the feature on frmRecordsetInfo in thetxtFeature Text box.

Use the value of SourceTable on one of the recordset’s fields.

6. For each field in the recordset, display its name in the lstFields Listbox, and tally (keep a running count) each of the types of fields.

You will iterate over the GFields collection. You will examine the Typeproperty on the GField object (objField). Don’t forget to releaseobjField after completing the loop.

7. Display the count of records in the recordset in the txtCount Text

Page 68: Customizing Geomedia

68 Fundamentals of GeoMedia Development Part I

box.

In order to get the correct count of records (rows), you must go to thelast row. However, it is invalid to do this if there are no rows. Firstcheck the EOF and BOF properties on the recordset (objRS).

8. Now, test your code by running the application, and selectingAnalyze > Recordset Information from the Main Window afteryou have opened a connection.

Choose the Start command from the toolbar or Run menu. In yourapplication’s main window, main menubar, select File > Open. Inthe Common File Open dialog, choose an Access database (e.g., USSample Data.mdb in the Warehouses directory). Select Analyze >Recordset Information, and choose a feature to analyze.

Summary: In Lab 3, you used the MetadataService to retrieve the list offeatures available in the warehouse. You created a recordset with theOriginatingPipe. Finally, you accessed the fields within the recordset’sfields collection and you accessed the count of records (rows) within theoutput recordset. Each row is equivalent to a feature instance.

Page 69: Customizing Geomedia

Creating a Custom Application 69

Adding a MapView and Displaying DataThe main distinction between a GRecordset from GDO and a Recordsetfrom DAO is that the GRecordset data is geographic in nature. In otherwords, geometry and world coordinate information are served up suchthat the data has spatial context. This context has little meaning withoutviewing that data spatially or on a map. The MapView OCX suppliedwith GeoMedia gives you that context. The MapView OCX is thecustom control on which you will display the spatial aspect of yourGRecordset. During the next lab exercise, you will learn the mechanicsof adding a MapView to your application.

Additionally, the MapView gives you view manipulation functionality(e.g., zooming, fitting, etc.) as well as giving you the extensions forselecting and highlighting elements, coordinates systems management,and the legend.

MapView

CoordSystemsMgr

Legend

LegendEntries

The Legend is the mechanism by which you will actually display thedata on the MapView. The Legend is a member object of the MapView.In a custom application, you will need to create it and assign theMapView’s Legend property to the one you created, as in:

Dim objLegend As New Legend

Set ocxMapView.Legend = objLegend

Set objLegend = Nothing

LegendEntries is a heterogeneous collection on the Legend that storesinformation on each logical grouping of data displayed on the map. Forour purposes, you will be creating a RecordLegendEntry. Displayingdata on a map is as simple as creating a recordset, creating a style objectto set the data display characteristics, both of which are input intocreating a RecordLegendEntry, and appending that to the Legend.

Coordinate Systems and Transformations

There is one other aspect of displaying data in a map view which youwill need to ensure is properly handled. This involves coordinatesystems and transformations between your data and the map view inwhich you are displaying that data. Every connection will have one ormore coordinate systems (server side). Each map view will have a singlecoordinate system (client side). If you know that all of your data is in

Page 70: Customizing Geomedia

70 Fundamentals of GeoMedia Development Part I

Recordset inCS A

Recordset inCS B

MapView inCS X

Transformfrom A to X

Transformfrom B to X

the same coordinate system and you want it displayed in the samecoordinate system, then you can set the coordinate system on your mapview to be the same as that of your data and you will not need to beconcerned about transformations.

However, in most cases you will want to approach the problem with amore generic solution. GeoMedia provides the tools for you to easilyaccomplish this such that your data may exist in one or more coordinatesystems that are entirely different from the one in which you aredisplaying the data. Once the transformations are properly configured,GeoMedia will do on-the-fly transformation of your data to the propercoordinate system of the map view. The two objects you will use toaccomplish this are the ServerTransService and the CSSTransformPipe.

In a custom application, you will need to create and define theCoordSystemsMgr and CoordSystem for your map view. If you don’texplicitly define the coordinate system, GeoMedia will create a defaultone for you, just by issuing a CreateObject on the CoordSystemsMgr, asin:

ocxMapView.CoordSystemsMgr = CreateObject _(“CoordSystemsMgr”)

Then, to ensure that the data you are displaying in that map view istransformed properly, create a ServerTransService, and define atransformation between your server and map view by calling theCreateSimpleTransFromCSMtoServer method. Then, pass eachrecordset you wish to display through a CSSTransformPipe beforeassigning it to a legend entry’s recordset and calling LoadData. Thiswill transform all the geometries of the recordset such that they will bedisplayed properly on the map view. There is an example of this in theCreateRecordset function of modRecordset in the previous labexercise.

Figure 0-1

The reverse is true, as well. If your application allows the user todigitize some data, you will need to transform it from the map viewcoordinate system back to the server’s coordinate system before youwrite it to the data store.

Page 71: Customizing Geomedia

Creating a Custom Application 71

Lab 4: Constructing the MapView

In this lab, you will complete the code necessary to display data on amapview − the code behind selecting View > Add Feature in yourapplication. You will begin by placing the MapView on a form. Youwill create the default coordinate system and a legend on the MapView.You will write code controlling the display of the legend. Then, youwill complete the code necessary for creating a legend entry anddisplaying that legend entry on the MapView.

1. Open the Visual Basic projectC:\TGM\Labs\CustomApp\src\CustomApp.vbp. In the ProjectWindow, under the Forms folder, select frmMap, and select View> Object.

The form will be opened, and it will contain the Map Window.

2. Delete the existing MapView control by selecting this control on theform and pressing the delete key. (The control already existed in thelab project so that other code referencing it would compile.)Remove the MapView as one of the controls on the toolbox byselecting Project > Components… In the Components dialog onthe Controls tab, uncheck GMMapview OLE Custom Controlmodule, and select OK to dismiss the dialog.

You should see one of the buttons on your toolbox whose ToolTipreads GMMapView disappear.

Now add the MapView back as one of the controls on the toolbox byselecting Project > Components… In the Components dialog onthe Controls tab, check Intergraph GeoMedia Mapview Control2.0, and select OK to dismiss the dialog.

You should see a new button on your toolbox whose ToolTip readsGMMapView.

This reference had to exist in your lab project so that references tothis GMMapView would compile. The purpose of your removingit and replacing it on the toolbox was so that you would understandhow GeoMedia controls are added to the toolbox in your VisualBasic project.

3. Select the GMMapView control on the toolbox by clicking on the

button whose tooltip reads GMMapView . Now when youmove your mouse you will be in control placement mode. On theMap Window of frmMap , click (and hold) the left mouse buttonwith your mouse pointer on the upper-left-most gridmark in the MapWindow. Drag to the lower-right-most gridmark, and release themouse button to complete the placement of the MapView on the

Page 72: Customizing Geomedia

72 Fundamentals of GeoMedia Development Part I

form.

You should see a blank MapView on the Map Window.

4. Name the GMMapView control ocxMapView. Make sure theupper left coordinates of the MapView are 0, 0.

In the Properties window, modify the Name, Top, and Left properties ofthe GMMapView. If the GMMapView is not already the activecontrol, you can make it the active control by either selecting on it inthe Form, or by selecting it from the Properties Window Controlpull-down.

5. In the Project Window, under the Forms folder, select frmMap, andselect View > Code. In Sub Form_Load, create aCoordSystemsMgr, and set the NominalMapScaleDenominator ofthe CoordSystem.RefSpaceMgr.PaperSpace member object in theCoordSystemsMgr. Then, assign the CoordSystemsMgr object tothat property of the ocxMapView.

This will create a default CoordSystem as a member property of theCoordSystemsMgr, giving your map view a “CylindricalEquirectangular” projection and other default coordinate systemparameters that will serve our purposes well in displaying data anddemonstrating “on-the-fly” transformation from the coordinatesystem parameters of your data server or data store.

6. In Sub Form_Load, create a Legend and assign it to that property ofthe map view.

The ProgID for all GeoMedia objects are listed in the Appendix. Thenewly created Legend object must be assigned to the Legendproperty of the ocxMapView.

7. In Sub mnuViewLegend_Click, toggle the display of the Legend onand off.

For displaying the Legend, there is a Visible property whose type isboolean. Since you are toggling the display, if the legend iscurrently displayed (Visible = True), then turn it off. Forcontrolling the check mark on the menu, use the Checked property.MnuViewLegend is the menu item for the Legend Toggle command.

8. Now, test the code you’ve written thus far by running theapplication, and selecting View > Legend from the Main Windowafter you have activated the Map Window.

Choose the Start command from the toolbar or Run menu. In yourapplication’s main window, main menubar, select Window >Activate Map. Select View > Legend, and the Legend shouldappear in your map view. Note that it is empty as we have not addedany legend entries yet. Select View > Legend again, and you shouldsee the legend disappear. You may quit the application by selectingFile > Exit.

Page 73: Customizing Geomedia

Creating a Custom Application 73

Note: In Sub mnuDisplayFeature_Click, notice the structure of thecode already in place for displaying a feature on the map. You arecalling CreateRecordset from the previous lab. Once you’ve created arecordset, it is used as input to the function GetLegendEntry. Giventhe RecordLegendEntry returned from that function, you callDisplayTheLegendEntry to actually display the data on your map view.In the next steps, you will be writing code that provides the keyfunctionality for those two procedures. You can close the code andobject windows of frmMap.

9. In the Project Window, under the Modules folder, select modMap,and select View > Code. Create the RecordLegendEntry that will bereturned by this function.

By assigning a value to the name of the function, you are setting thereturn type from the function.

10. Notice how you can get additional information about the recordsetusing the ExtendedPropertySet object since the recordset wascreated with OriginatingPipe. This functionality is used to get thePrimaryGeometryFieldName. Now similarly, get the recordset’sName property from the extension object and assign its value as thelegend entry’s title.

Remember the GetLegendEntry is a variable of typeRecordLegendEntry. The extended property set object is stored inthe objExt variable. The value of the Name will be used as thelegend entry’s Title.

Note: Similarly, the extended property GeometryType is used to get thegeometry type which is passed to the function GetStyleObject. Thisfunction returns a style (based on the given geometry type) that is thenassigned as the Style property of the RecordLegendEntry. Style objectswill be covered in more detail in a later lab. This function will abstractthat for us during this lab.

11. As we have discussed, a transformation must be established betweeneach coordinate system used by your application. In theCreateRecordset procedure, the ServerTransService is created tocreate a transformation between the projection of the coordinatesystem of the map view and the data being returned from the server.This one method call is all that is needed to accomplish this. Nowthat the transformation has been created, a CSSTransformPipe iscreated to take the input recordset and give an output recordsetwhose geometries have been “transformed” from the server side tothe client side. Take that output recordset from the pipe object andassign it to the legend entry’s Recordset property.

Using the Set keyword, assign the OutputRecordset from the

Page 74: Customizing Geomedia

74 Fundamentals of GeoMedia Development Part I

objCSSPipe to the GetLegendEntry variable.

12. In Sub DisplayTheLegendEntry, the legend entry is checked to besure it is a valid object, and then ValidateSource is called to ensurethat it has a recordset and proper geometry field set. Append thelegend entry to the legend’s LegendEntries collection, and load thedata by calling the LoadData method on the legend entry. If it is thefirst legend entry being loaded on the map view, then do a fit of thedata in the map view.

The Append method has a first argument of a legend entry and then twooptional arguments—BeforeIndex and AfterIndex. It must be calledwithout an index when appending the first Legend Entry. Thesecond and subsequent times Append is called requires using eitherthe BeforeIndex or the AfterIndex argument, but not both. For thisexercise, append the second and subsequent legend entries to the topof the legend (i.e., give them a BeforeIndex of 1). The legend entryto append is stored in objLE. If this is the first legend entry, wewant to call Fit on the map view.

13. Now, test your code by running the application, and selecting View> Add Feature from the Main Window after you have opened aconnection and activated the Map Window.

Choose the Start command from the toolbar or Run menu. In yourapplication’s main window, main menubar, select File > Open. Inthe Common File Open dialog, choose an Access database (e.g., USSample Data.mdb in the Warehouses directory). Select Window >Activate Map. Select View > Add Feature, and choose a feature todisplay. Notice that if you view the legend now (View > Legend),you will see the newly created legend entry.

Summary: In Lab 4, you have placed a map view control on your form.The paper scale of the coordinate system has been adjusted to control thethickness of the lines in the display. The legend entry was created —this involved finding the geometry field using ExtendedPropertySet,creating a default style, and appending the entry to the collection. Acoordinate transformation was established between the server and theview’s coordinate system. Finally, the legend entry was validated andthe data loaded into the geometry cache.

Page 75: Customizing Geomedia

Creating a Custom Application 75

What are Styles?A style is an object that describes how to visualize the geographic data.Typically, the style includes color and weight. A style object is assignedto each legend entry. You can use the same style object on multiplelegend entries.

The simplest approach to defining a style is to create a linear styleobject. You can apply this object to any geometry type. The drawingprocess will then use whatever information that is in the style object thatit can, and apply it to the current geometry. As such, if the geometry isareal, only the edges will display. There will be no associated filling ofthe area. If the geometry is point, only a dot will appear.

There is also an AnyStyle object which has member object properties foreach possible style type. This is most often used for the gdbAnySpatialgeometry type. The display process attempts to use the best fit — mostappropriate — style for the geometry type.

In the linear and area styles, you have both a back and fore color andback and fore width settings. This allows you to draw two lines for eachgeometry. This enables more variation in symbolization. The Color andWidth properties are equivalent to setting the BackColor and BackWidthproperties.

GeoMedia supports the display of point objects with true type fonts aswell as MicroStation symbol font resources. You must define theappropriate registry keys for the location of your resource files. All filespresent in the directories will be available for use. GeoMedia recognizesthree keys which specify directories that contain resource files:HKEY_CURRENT_USER\Software\Intergraph\Applications\GeoMedia\PrefSets\Options-FileLocations\Font1, ...\Font2, and ...\Font3. Thekey’s value must be the full directory path. The directories need not bepart of the GeoMedia installation directory. GeoMedia also supports abitmap style. Additionally, a symbol element may be created fromMicroStation cell libraries or from AutoCAD block files. Use the DefineSymbol File utility to create the .FSM file.

GeoMedia also provides style objects for patterned lines and areas. Youcan combine the symbol element and the line or area styles to create apattern.

In the GeoMedia user interface, style width’s are assigned based onpoints – a standard printer’s measurement. Use the following values todetermine how to calculate the desired point sizes. Remember, the stylewidth is based on the paper scale of the coordinate system. If yourdisplay is greater or smaller than the paper scale, the measurements willnot match point size you specified.

• One point is 1/72 of an inch (0.0139 inches)

Page 76: Customizing Geomedia

76 Fundamentals of GeoMedia Development Part I

• One point is 0.353 millimeters

• When using gmsStyleUnitsPaper, the Width is specified inHIMETRIC units where 100 units is one millimeter (one unit is 0.01millimeters)

• Using the HIMETRIC measurement, 35 units is one point (1/3 of amillimeter)

For example, if you specify 300 units in the Width property, theGeoMedia style dialog will display 9 points. At your defined paperscale, the line will measure 3 mm or 1/8 inches.

If you specify the StyleUnits property as gmsStyleUnitsView, you areindicating that the width reflects the number of pixels to use.

Finally, the StyleUnits property of gmsStyleUnitsPaperAsNonscaling iscalculated like the gmsStyleUnitsPaper setting, but behaves like thegmsStyleUnitsView. This option is referred to as View Independent.That is, the width of the style is calculated from the point or HIMETRICinput, but is a width relative to the screen rather than the ground orgeographic space. Hence, 36 point text would appear as ½ inch on thescreen. Additionally, the width will remain at ½ inch no matter what theview extents. This is contrary to gmsStyleUnitsPaper which gets smalleras you zoom out and larger as you zoom in.

OPTIONAL Lab 5: Creating Specific Style Objects

In this lab, we will expand our legend entry subroutine to assign the stylebased on the geometry type.

Style Object Normally Applied To Covered inLab?

AreaStyle Subtype = gdbAreal Yes

AnyStyle Subtype = gdbAnySpatial Yes

BitmapStyle Subtype = gdbPoint No

HandleStyle Not applicable No

LinearStyle Subtype = gdbLinear No

SymbolFontStyle Subtype = gdbPoint Yes

TextStyle Subtype = gdbGraphicsText Yes

PointSymbolStyle Subtype = gdbPoint No

PatternedLinearStyle Subtype = gdbLinear No

PatternedAreaStyle Subtype = gdbAreal No

Page 77: Customizing Geomedia

Creating a Custom Application 77

In this first section, you will add logic to support gdbPoint andgdbGraphicsText subtypes for the geometry data. For all style objects,you will set the StyleUnits to gmsStyleUnitsPaper. For the Colorproperties, employ a cyclic assignment of color values. Use theQBColor function to convert the nNextColor index value to the RGBvalue.

Section A: Adding Symbols and Text

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select modMap from the Modules list, and select View > Code.

3. Select the (General) object, and select the GetStyleObjectprocedure.

4. Add a case statement for point type geometry. You will need tocreate the SymbolFontStyle object and populate it appropriately.

First, create the object with the GeoMedia.SymbolFontStyle ProgID.Then populate the minimum set of properties: Color, StyleUnits,FontName, Index, and Size. Setting the Color and StyleUnitsproperties are described in the lab introduction. The FontName iseither the name of a true type font or a MicroStation symbol font.The Index is the position in the list of glyphs within a font. This isusually a value between 0 and 255, but will vary by particular font.For this exercise, use “Wingdings” for the FontName and a numberbetween 33 and 200 for the Index. Finally, the Size or width shouldbe set to 300 for a 3 mm size as described in the section overview.

5. Add a case statement for gdbGraphic geometry. Because you knowthe metadata techniques used to retrieve the element type, you knowthat this geometry type represents gdbGraphicsText elements. Youwill need to create the TextStyle object and populate itappropriately.

First, create the object with the GeoMedia.TextStyle ProgID. Thenpopulate the minimum set of properties: Color, StyleUnits, andFont. Setting the Color and StyleUnits properties are described inthe lab introduction. The Font is a Microsoft StdFont object.Create a new StdFont object and assign it to the Font property.Within the StdFont object, you must set the Name and Sizeproperties. Name is the name of the text style like ”Arial” or“Times New Roman”. Size is the number of points to display thetext at. There are other properties you may set like Bold.

6. Save the project, and compile the executable by selecting File >Make customapp.exe.

7. Test the application.

Open a database. Select Window > Activate Map. Select View > Add

Page 78: Customizing Geomedia

78 Fundamentals of GeoMedia Development Part I

Feature, select the Cities feature and select OK. The city pointsshould appear in the style you created. Select View > Add Feature,select the StateNameLabels feature and select OK. The state namesshould appear in the style you created. You may need to adjust thepoint sizes for correct sizing.

Summary: In Lab 5, Section A, you defined symbol font and text styles.This included manipulating the StdFont object.

We can now expand the styles to include gdbAreal and gdbAnySpatial.To display the compound geometry, you will need to connect to theAnySpatial.mdb database.

Section B: Adding Area and AnyStyle

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select modMap from the Modules list, and select View > Code.

3. Select the (General) object, and select the GetStyleObjectprocedure.

4. Add a case statement for gdbAreal geometry. You will need tocreate the AreaStyle object and populate it appropriately.

First, create the object with the GeoMedia.AreaStyle ProgID. Thenpopulate the properties. This style object is divided into two parts.The member object Boundary defines the style of the line boundingthe area. This object is created by default and is a read-onlyproperty. Set the properties of this object as shown in the case forgdbLinear. The remaining properties describe the characteristics ofthe inside of the area (fill). BackColor is the color for the filledarea. FillMode should be set to gmsFillModeStandard. Select anyof the gmsFP constant values for the FillType property. Thisdescribes the hatching pattern to use in the fill area. StyleUnits ispopulated as described in the other sections of the lab. ForeColoris the color of the hatching. HatchSpacing is the number of pixelsbetween hatch lines in the fill pattern. HatchWidth is the number ofpixels for the width of the hatch lines.

5. Add a case statement for gdbAnySpatial geometry. You will need tocreate the AnyStyle object and populate it appropriately. Thisobject simply has member properties which are the simple styletypes that we have already created. You need only create this objectand create one of each of the dependent objects: TextStyle,SymbolFontStyle (for the PointStyle property), LinearStyle, andAreaStyle.

First, create the object with the GeoMedia.AnyStyle ProgID. Thencreate the simple style objects. You can simply copy the code we

Page 79: Customizing Geomedia

Creating a Custom Application 79

used in the other steps for this exercise. You may want to adjustsome of the simple style properties to help differentiate the display.Then populate the properties of the AnyStyle object with thesesimple style objects.

6. Save the project, and compile the executable by selecting File >Make customapp.exe.

7. Test the application.

Open a database. Select Window > Activate Map. Select View > AddFeature, select the States feature, and select OK. The states shouldappear in the style you created. Open another database —AnySpatial.mdb in c:\TGM\Labs\CustomApp. Select View > AddFeature, select the CityFacilities feature, and select OK. A fewAnySpatial features will appear in the style you created. You mayneed to adjust the point sizes for correct sizing. The CityFacilitiesare in the vicinity of Chicago, Illinois.

Summary: In Lab 5, Section B, you defined the area style. Thiscompletes the primitive style types (excluding BitmapStyle andPointSymbolStyle). You also defined the AnyStyle object whichcontains member objects for each of the primitive types.

Page 80: Customizing Geomedia

80 Fundamentals of GeoMedia Development Part I

What is Marginalia?Marginalia is a term used to describe graphics that typically appear inthe margin of a printed map. In GeoMedia, there are currently two ofthese types of objects: NorthArrow and ScaleBar. The NorthArrowindicates the direction of the geographic north pole relative to the data.The NorthArrow is a custom control that can be placed on your form.You must set the MapViewID property of the control to the map view’sDispatch property. This allows the control to retrieve the coordinatesystem information to determine the direction of north.

The ScaleBar reflects the scale of the map. That is, when you use a rulerto measure distances on the map, the scale indicates how much ground iscovered. For example, one inch measured on the paper may represent100 feet or 100 miles depending on your scale. Like the NorthArrow,the ScaleBar is a custom control that can be placed on your form. TheScaleBar also requires that it’s MapViewID property be set to theassociated map view’s Dispatch property. This allows the control toretrieve the coordinate system information to determine the current scaleof the view.

OPTIONAL Lab 6: Marginalia

In this lab, we will add the custom controls to our map view. We willset the necessary properties in the form load operation and turn on theirdisplay.

Section A: North Arrow

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmMap from the Forms list, and select View > Object.

The Map Window form will appear.

3. Delete the existing GMNorthArrow control by selecting thiscontrol on the form and pressing the delete key. From the toolbox,

select the GMNorthArrow control.

The cursor will change to cross or plus sign.

4. Create a rectangle by placing the cursor in the upper right corner ofthe form and dragging to create a 495 x 495 box.

An arrow bitmap will appear. The name of the control will default toGMNorthArrow1.

5. Adjust the properties of the control to set BackTransparent to Truein the Properties Window. This only applies to the printed northarrow and not to the display.

Page 81: Customizing Geomedia

Creating a Custom Application 81

6. Set the BackColor to the color of your map view.

Select the Palette tab in the Properties Window to associate a particularcolor.

7. Select frmMap from the Forms list, and select View > Code.

8. Select the Form object and Load from the procedure list. Add logicto assign the Dispatch pointer of the map view control to theMapViewID property of the north arrow.

Both the GMNorthArrow1 and ocxMapView are properties of frmMap.The code skeleton includes logic for adjusting the control’s positionwithin the map view control.

9. Save and compile the application. Test the application.

Open a database. Select Window > Activate Map. The NorthArrowshould appear at the location you placed the control. The areasurrounding the arrow should be the same color as the map view.

Summary: In Lab 6, Section A, you placed the control on the form andestablished the communication through the map view. Many otherproperties can be configured for the North Arrow.

Section B: Scale Bar

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmMap from the Forms list, and select View > Object.

The Map Window form will appear.

3. Delete the existing GMScaleBar control by selecting this control onthe form and pressing the delete key. From the toolbox, select the

GMScaleBar control.

The cursor will change to cross or plus sign.

4. Create a rectangle by placing the cursor in the upper right corner ofthe form and dragging to create a 3255 x 495 box.

A scale bar will appear. The name of the control will default toGMScaleBar1.

5. Adjust the properties of the control to set BackTransparent to Truein the Properties Window. This only applies to the printed scale barand not to the display.

6. Set the BackColor to the color of your map view.

Select the Palette tab in the Properties Window to associate a particular

Page 82: Customizing Geomedia

82 Fundamentals of GeoMedia Development Part I

color.

7. Select frmMap from the Forms list, and select View > Code.

8. Select the Form object and Load from the procedure list. Add logicto assign the Dispatch pointer of the map view control to theMapViewID property of the scale bar.

Both the GMScaleBar1 and ocxMapView are properties of frmMap.The code skeleton includes logic for adjusting the control’s positionwithin the map view control.

9. Save and compile the application. Test the application.

Open a database. Select Window > Activate Map. Select File > Opento open a database. Select View > Add Feature and display theStates feature. The ScaleBar should appear at the location youplaced the control. The area surrounding the scale bar should bethe same color as the map view. The ScaleBar will adjust to thescale of the data.

Summary: In Lab 6, Section B, you placed the control on the form andestablished the communication through the map view. Many otherproperties can be configured for the ScaleBar.

Page 83: Customizing Geomedia

Creating a Custom Application 83

Printing MapsWhile GeoMedia has numerous commands, it does not provide thecapability to have one command call another. However, two commandshave been enabled — Page Setup and Print — for custom applications.These are the only two commands that can be called by customapplications.

Printing requires two steps. First, you need to establish the Page Setupinformation. The GeoMedia command object PageSetup is used for thispurpose. This task need only be performed once. If this is notinitiated, then defaults for the printer will be used as long as you havecreated valid PreferenceSet and UnitsOfMeasure objects. Theseobjects are GeoMedia objects that may be used in custom applications.

For the second step, you will use the GeoMedia command object Print.This object performs the actual print operation. It is assumed that thework performed by PageSetup is complete, but you can print based ondefaults without calling this command.

Postscript Printing

If you have loaded the appropriate printer drivers, you can print youroutput to a postscript file. From “Map Window Page Setup” on thePrinter tab, select Properties. From Document Properties, selectOptions... Select Encapsulated Postscript File, and specify the filename.

Limitations

The data view cannot be printed outside of GeoMedia. Both commandmethods display dialogs and there is no option to hide their display.Currently, the NorthArrow and ScaleBar do not print in customapplications.

Map Layout in Imagineer

GeoMedia also provides a mechanism for creating more formal maps.This is accomplished by linking or embedded views from the GeoMediaworkspace onto sheets in Imagineer. Imagineer enables you to createsophisticated borders and include other drawings on a single sheet.Refer to the GeoMedia product documentation for more information onthis workflow.

Page 84: Customizing Geomedia

84 Fundamentals of GeoMedia Development Part I

OPTIONAL Lab 7: Printing

For this lab, we will implement the Map > File > Print command forthe map view.

Section A: PageSetup

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmMap from the Forms list, and select View > Code.

3. Select the mnuFilePrint object, and select the Click procedure.

4. Call the PageSetup method on the objPageSetup command object.

The calling sequence for this method is: PageSetup( Dispatch,PreferenceSet, ApplicationName, HelpFileName, UOM) as Longwhere the Dispatch argument is the value of the Dispatch propertyfrom the map view control. The PreferenceSet is the object of typePreferenceSet. In your application, this is declared globally. TheApplicationName is the text string used for the print queue entryname. Any value may be used. The HelpFileName is the text stringindicating the name of the help file used if the help button is selectedon one of the dialogs. Any value may be used Finally, the UOM isan object of type UnitsOfMeasure. The return value is always zero.

1. Save the project, and compile the executable by selecting File >Make customapp.exe.

2. Test the application.

Open a database. Select Window > Activate Map. Select View > AddFeature, select a feature, and select OK. Select File > Print. ThePageSetup dialog should appear. Select OK or Cancel.

Summary: In Lab 7, Section A, you created the preference set objectand UnitsOfMeasure objects. These are used by the page setup todetermine size of the areas. You configured the command to display thisdialog.

Section B: Print

1. Return to the project.

2. Select frmMap from the Forms list, and select View > Code.

3. Select the mnuFilePrint object, and select the Click procedure.

4. Add logic to call the Print method on the print command object.

The calling sequence for this method is: Print( Dispatch,

Page 85: Customizing Geomedia

Creating a Custom Application 85

ApplicationName, PreferenceSet, HelpFileName) as Long whereDispatch is the value of the Dispatch property from the map viewcontrol. ApplicationName is a text string used for the print queueentry name. Any value may be used. PreferenceSet is an object oftype PreferenceSet. Finally, HelpFileName is a text stringindicating the name of the help file used if the help button is selectedon one of the dialogs. Any value may be used.

5. Save the project, and compile the executable by selecting File >Make customapp.exe

6. Test the application.

Open a database. Select Window > Activate Map. Select View > AddFeature, select a feature, and select OK. Select File > Print. ThePageSetup dialog should appear. Select OK or Cancel. The Printdialog should appear. Select OK or Cancel. If a printer isavailable, review your results.

Summary: In Lab 7, Section B, you initiated the print dialog. Again,the map view dispatch is used to establish the location of the map view.This component actually drives the print operation.

Page 86: Customizing Geomedia

86 Fundamentals of GeoMedia Development Part I

Creating and Displaying QueriesA GIS user has two primary tasks: choose data to display and manipulatedata that is already displayed. In this section and the subsequent labexercises, you will examine the first task at length. Through GeoMediaautomation components, you will select and display data that is spatiallyrelated to other data. On a related topic, you will examine GeoMedia’sbuffering functionality − bufferzone. Finally, you will look at selectionof displayed features from the map view, and subsequent review of theattribute data.

You choose data to display either through the selection of a table or theselection of a subset of data from one or more tables. The first is calleda feature class. You implemented this in Lab 3. The latter is commonlyreferred to as a query. Both requests result in the creation of recordsets,but the use of spatial operators in selecting the data subset in the secondmethod allows you to generate an infinitely varied set of results.

The ability to perform sophisticated spatial queries is a key distinction inseparating GeoMedia from ordinary desktop mapping applications anddevelopment platforms. GeoMedia has a comprehensive set of spatialoperators for the programmer, including touch, are within distance of,are contained by, entirely contain, are entirely contained by, overlap,meet and are spatially equal. These spatial operators work on points,lines, and areas. For example, the “contains” operator can find a sewercontained within a parcel. You can also build a pipeline such that youcan find sewers contained in parcels contained within a particularcounty.

GeoMedia allows the user to save a spatial or attribute query as a newQuery object for display in an existing map view or for future use. It isan important distinction to note that GeoMedia does not store the queryresults as a static entity, but stores the query statement and submits itdynamically to the GDO server when it is needed. In other words,GeoMedia stores the question and not the answer for queries andreissues the question at the right time so that the answer will never beout of date.

Queries can be created programmatically in several different ways. Youcan use the OpenRecordset method of the current GDatabase object asdescribed in detail in Lab 2. You can also use the OriginatingPipeand/or the SpatialQueryPipe to create a query that uses a spatial filterand generates a recordset as the query results.

Previously in the section on Creating and Manipulating a Recordsetwe learned how to create a recordset using the OriginatingPipe.Building on this example, suppose you now want to find out what landparcels are located directly next to a specific highway. This can be doneby prompting the user to select the highway which you want to check for

Page 87: Customizing Geomedia

Creating a Custom Application 87

adjacent land. Execute the following code segment:

Dim objOP As OriginatingPipe

gobjConnections(1).CreateOriginatingPipe objOP

objOP.Table = “Parcels”

objOP.SpatialOperator = gdbTouches

Dim vSpatialFilter as Variant

vSpatialFilter = objHiwayTbl.GFields(“Geometry”).Value

objOP.SpatialFilter = vSpatialFilter

objOP.GeometryFieldName = “Geometry”

Dim objRS As GRecordset

Set objRS = objOP.OutputRecordset

In this example, the spatial filter is passed into the OriginatingPipe as ageometry blob which GeoMedia uses along with the spatial operator todetermine which records satisfy the query criteria. Use of theSpatialQueryPipe to execute a similar query will be explained in detailin the next section.

Once the query is created, GeoMedia uses query folders to organizesaved queries and for quick recall of previously saved queries. Queryfolders are a key component in implementing shared recordsets whichhelp eliminate redundant recordsets (i.e., identical queries). Throughthis organization, GeoMedia minimizes both the number of queries andthe amount of time required to execute a query. Refer to Lab 14 formore discussion on the GeoMedia query folder hierarchy.

Because queries are simply recordsets − the common currency used tocommunicate between components in GeoMedia, they are displayed in amap view or data view just like we have done with other recordsets.This means that in order to display a query in a map view you will firsttake the recordset resulting from the query operation, transform it to thecurrent map view coordinate system, assign it to a RecordLegendEntry,add the entry to the legend, and finally execute the ValidateSource andLoadData methods on the legend entry. A query can be displayed in adata view by simply assigning the recordset to a valid data view.

Page 88: Customizing Geomedia

88 Fundamentals of GeoMedia Development Part I

Spatial Query PipeAs we discussed briefly in the introductory section, a pipe is a softwarecomponent that accepts one or more recordsets as input and produces anew recordset based on some analysis. The spatial query pipe performsa spatial (geographic) analysis of the data from the input recordsets. Theresulting recordset will contain one of the following.

• Data from the first recordset that meets the spatial criteria

• Data from the second recordset that meets the spatial criteria

• The derived geometry resulting from the spatial comparison

• A combination of data from one of the recordsets and the derivedgeometry

Spatial Operators

The pipe supports several different spatial operators that control theanalysis. These are described pictorially here. In all cases, the spatialanalysis iterates over each record in the first recordset comparing it toevery record in the second recordset.

point line area

Diagram conventions

The gmsqWithinDistance operator will find all features in the firstrecordset which contain at least one point within the specified distanceof the current record in the second recordset.

Page 89: Customizing Geomedia

Creating a Custom Application 89

gmsqWithinDistance -- “are within distance of”

point 2 is within 20 meters of point 1point 3 is not within 20 meters of point 1

20 meter zone

12

3

1

2

12

1.5 mile zone

3

point 1 and line 2 are within 1.5 miles of line

point 1 and line 2 are not within 15 yards of the

1

1

2

15 yard zone

point 2 and line 3 are not within 1.5 miles of line

point 2, line 1, and line 3 are within 15 yards of the

there is only one area, and it has a hole2

3

point 1and line 3 are in the area’s holethe zone has a hole

Note that:

point 1 is also in the zone’s hole

The gmsqMeet operator will find all features in the first recordset whichshare a single point with the geometry of features in the secondrecordset.

line meets point

point meets line

line 1 meets line 2 area meets point

point meets area

line meets area

area meets line

area meets area

gmsqMeet -- “meet”

line 2 meets line 1

21

The gmsqOverlap operator will find all features in the first recordsetwhich share some portion of geometry with features in the secondrecordset.

Page 90: Customizing Geomedia

90 Fundamentals of GeoMedia Development Part I

gmsqOverlap -- “overlap”

line overlaps point

point overlaps line

line overlaps line area overlaps point

point overlaps area

line overlaps area

area overlaps line

area overlaps area

The gmsqContains operator will find all features in the first recordsetwhich share all portions of the geometry for features in the secondrecordset. In this condition, endpoints are allowed to touch. ThegmsqContainedBy operator will find all features in the secondrecordset that share all portions of the geometry for the features in thefirst recordset. As with gmsqContains, endpoints are allowed to touch.

gmsqContainsgmsqContainedBy -- “are contained by”

line contains point

point c.b. line

line 1 contains line 2

line 2 c.b. line 1

area contains point

point c.b. area

area contains line

line c.b. area

area 1 contains area 2

area 2 c.b. area 1

1

12

2

The gmsqEntirelyContains operator is like gmsqContains however,every point is shared. That is, endpoints cannot overlap. The same istrue for gmsqEntirelyContainedBy and gmsqContainedBy.

gmsqEntirelyContainsgmsqEntirelyContainedBy -- “are entirely contained by"

line e.c. point

point e.c.b. line

line 1 e.c. line 2

line 2 e.c.b. line 1

area e.c. point

point e.c.b. area

area e.c. line

line e.c.b. area

area 1 e.c. area 2

21

area 2 e.c.b. area 1

2

1

The gmsqSpatiallyEqual operator will find all features in the first

Page 91: Customizing Geomedia

Creating a Custom Application 91

recordset that are identical to features in the second recordset.

gmsqSpatiallyEqual -- “are spatially equal”

point spatially equals point line spatially equals line area spatially equals area

note that points can only bespatially equal to other points

note that lines can only be note that areas can only bespatially equal to other lines spatially equal to other areas

The gmsqTouches operator will find all features in the first recordsetwhich have at least one point in common with features in the secondrecordset.

gmsqTouches -- “touch”

All of the preceding examples will be detected by the touches operator. This is an extremely

"catch-all" operator.

Pipe Object Automation

The properties for the pipe are described here.

Property Description

DerivedGeometryFieldName Set this property to include thegeometry object resulting from thespatial comparison. This field namemust be unique.

Distance Applicable only when theSpatialOperator is gmsqWithinDistance.

ErrorCount Populated at the completion of thespatial comparison and indicates howmany geometry values where skippedduring processing. The spatial analysisis completed ignoring these geometriesin its output.

FirstGeometryFieldName Specifies the name of the geometry fieldin the first recordset that will participate

Page 92: Customizing Geomedia

92 Fundamentals of GeoMedia Development Part I

in the spatial analysis.

FirstRecordset The set of data representing the left sideof the expression. That is, for theexpression A overlap B, A is theFirstRecordset.

OutputRecordset The result of the spatial analysis. If youset the ReferenceFirstRecordset flag totrue, the recordset contains the featureinstances from the first recordset thatsatisfy the analysis.

ReferenceFirstRecordset If true, indicates that the attributes ofthe first recordset should be included inthe output recordset.

ReferenceSecondRecordset If true, indicates that the attributes ofthe second recordset should be includedin the output recordset.

SecondGeometryFieldName Specifies the name of the geometry fieldin the second recordset that willparticipate in the spatial analysis.

SecondRecordset The set of data representing the rightside of the expression. That is, for theexpression A overlap B, B is theSecondRecordset.

SpatialOperator A constant that identifies the type ofspatial analysis to perform.

When using the spatial query pipe, you must follow a certain protocol.Both recordsets must contain geometry in the same coordinate system.If necessary, use the CSSTransformPipe to convert one of the inputrecordsets to the coordinate system of the other. When using thegmsqWithinDistance operator, the distance value must be in the sameunit of measure as the input recordsets.

Inverting the comparison will typically not produce the same results.For example, A overlap B will give you the set of features from A thatoverlap B. However, B overlap A will give you the set of features fromB that overlap A.

In this lab, you will create a command to allow the user to perform thespatial analysis between two feature classes. If your applicationmanages queries for data subsets, you could also allow the user tochoose a query and analyze the data subsets.

Lab 8: Spatial Query

This section of the lab will add the logic to display the list of linear

Page 93: Customizing Geomedia

Creating a Custom Application 93

measurements in the combobox.

Section A: Populating Form

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmSpatialQuery from the Forms list, and select View >Code.

3. Select the Form object, and select the Load procedure.

4. Add logic to retrieve the list of linear measurement types fromUnitsOfMeasure object.

First create a UnitsOfMeasure object. Store the result in objUOM.Then execute the GetUnitIDs method to retrieve the list of distanceunit identifiers and store this in the temporary variable objUnitIDs.Iterate through the collection of unit identifiers and use theGetUnitName method to get the name of each unit from theUnitsOfMeasure object. Finally, put the names in the combobox.

5. Set the default distance/unit to 1 m (one meter).

Use the constant igDistanceMeter as an argument to the GetUnitNamemethod on the objUOM variable.

6. Save the project, and compile the executable from File > Makecustomapp.exe.

7. Test the application.

Open a database. Select Window > Activate Map. Select Analyze >Spatial Query. Select the within distance operator to test thedisplay of the list. Cancel the dialog, as the code has not beenfinished yet to process OK.

Summary: In Lab 8, Section A, you retrieved the linear measurementtypes from the UnitsOfMeasure object and displayed them in thecombobox control. You tested the processing of the command to displaythe special within distance controls when that spatial operator isselected.

This section of the lab will create the input recordsets, set up the pipe,and retrieve the output recordset.

Section B: Processing the Request

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmSpatialQuery from the Forms list, and select View >Code.

Page 94: Customizing Geomedia

94 Fundamentals of GeoMedia Development Part I

3. Select the btnOK object, and select the Click procedure.

4. Add a function to check that a feature has been selected in bothtreeview controls on the form. Also, if the spatial operator isgmsqWithinDistance, check that a valid distance has been entered.

Create a boolean function called ValidSpatialInput that checks bothtreeview controls and returns a status of True if the user hasselected a feature in each. The function also return the names of thetwo selected features in sFeature1 and sFeature2. If the result isNot true, you will exit the subroutine.

5. Add logic to retrieve the recordsets associated with the twoselections.

Create an OriginatingPipe recordset using the feature names retrievedin the previous step. Note: In order to get the connection thatcorresponds to the selected feature each connection node in thetreeview control was assigned the correct index in its Tag property.So, get the treeview.SelectedItem.Parent.Tag, convert it to anumber and use it as the index into the gobjConnections collection.

Populate the Table property on the pipe with the sFeature1 andsFeature2 values and store the results in objRS1 and objRS2respectively.

6. Add logic to check for matching coordinate systems. If the systemsare not the same, perform a transformation of one of the recordsets.

Use the GetCSGUID function to retrieve the GUID of each recordsetcreated in the previous step. These are stored in RS1CSGUID andRS2CSGUID. If they are not equal call the functionTransformSpatialRS. This function returns transformed recordsetsthat should be stored in the variables objTransRS1 andobjTransRS2. In this routine, a ServerTransService object iscreated and uses the CreateSimpleTransFromCSMtoServermethod to register the recordset GUID as an alternatetransformation. Then it creates a CSSTransformPipe and transformthe recordset to the map view coordinate system.

In the first part of this if statement, assign the transformed recordsets tothe FirstRecordset and SecondRecordset properties on theSpatialQueryPipe (objSQPipe). In the second part of the ifstatement, use the original recordsets (objRS1 and objRS2).

7. If the operator is gmsqWithinDistance, convert the units to theunits of the recordsets.

Create a UnitsOfMeasure object (objUOM). Get the distance and unitsfrom the form. Convert the distance to meters using theConvertUnitToUnit method. The resulting distance is stored indblNewDist.

8. Display the results of the spatial query in the map view.

Add code identical to that which you did in Lab 4 using the

Page 95: Customizing Geomedia

Creating a Custom Application 95

GetLegendEntry and DisplayTheLegendEntry functions. Onlycreate a legend entry if there are rows in the recordset. This can bedetermined by testing the EOF and BOF properties. The input tothe GetLegendEntry function is objSQRS while the output should bestored in objLE.

9. Save the project, and compile the executable from File > Makecustomapp.exe.

10. Test the application.

Open a database. Select Window > Activate Map. Select Analyze >Spatial Query. Select two features and an operator. Select OK.Processing should complete although you won’t see any displayeddata.

Summary: In Lab 8, Section B, you created the OriginatingPiperecordsets for the selected features. You compared coordinate systemsthrough the CoordSystemGUID values. If they were not the same, youtransformed one recordset to the other coordinate system. If the operatorwas Within Distance, you converted the input value to the units of thedata. You reused your existing functions for creating and displaying alegend entry.

Page 96: Customizing Geomedia

96 Fundamentals of GeoMedia Development Part I

Buffer Zone PipeThis section introduces the BufferzonePipe component. This automationobject is used in GeoMedia to create a specialized query that identifiesan area around a particular feature − commonly known as a buffer zone.This component is typically used to help solve problems involving areasaround features. For example, you might want to analyze a specificdistance around a road to determine the easement extents and determinewhich parcels fall in the buffer zone.

With the BufferzonePipe component, you are able to create bufferzonesaround point and linear features. You may also create bufferzones insideor outside of areal features. The resulting buffers may be multiplestacked or multiple ringed. You may opt to display the generatedbufferzones as either separate area geometries or merged ones. TheBufferzonePipe operates in the same manner as other pipes. You assignthe input recordset along with a series of properties that control how thebufferzones will be created. Then, trigger the actual bufferzoneoperation by requesting the OutputRecordset. In order to view theresults from a BufferZonePipe you must save the recordset to a new orexisting table. This means that you must have a read/write serverconnection when using this component (typically an Access database).Once the table is populated with the records in the OutputRecordset, youcan create a record legend entry for these results and display them in themap view.

Note: The BufferzonePipe does not perform any unit conversionsinternally. This means that it operates correctly only when theInputDistance is in the same units as the geometry field of theInputRecordset. If these two properties are in different units, then youmust convert the InputDistance to be the same units as the geometryfield before requesting the OutputRecordset from the BufferzonePipe.

Buffer Zone Automation

The BufferzonePipe contains the following properties. It has nomethods. Eight of the properties can be assigned programmatically andtwo are output properties.

Property Description

BufferType Defines the shape of the bufferzone:gmbtAreaInside, gmbtAreaOutside,

Page 97: Customizing Geomedia

Creating a Custom Application 97

gmbtLinearButtEnd, gmbtLinearRoundEnd,gmbtLinearSquareEnd, gmbtPoint,gmbtPointRinged, gmbtPointStacked.

DistanceType Defines whether the distance is constant orvaries: gmbdConstant, gmbdVariable.

ErrorCount Number of errors encountered in bufferzoneoperation - typically bad geometry. This isan output value.

InputDistance Distance to buffer around feature ifDistanceType is constant. If DistanceTypeis variable this is name of database fieldthat contains the buffer distance.

InputGeometryFieldName Name of geometry field in the inputrecordset.

InputRecordset Input recordset.

Merge Defines how to merge overlaying buffers:gmbmAll, gmbmNone, gmbmOverlap.

OutputGeometryFieldName Name of geometry field in the outputrecordset.

OutputRecordset Result of bufferzone calculation. This is anoutput.

Tolerance Determines the smoothness of curves andcorners. Default value is 0.01.

Lab 9: Buffer Zone

Section A: Creating a Buffer Zone

In this section of the lab, the custom application will display a bufferzone form upon selecting the Analyze > Buffer Zone map view menuitem. You will select the feature to buffer, enter the distance from thefeature to measure the buffer zone, and choose the units of measure forthat distance. In order to view the buffer zone in the map view, you mustalso select a database and table to store the results in. The outputdatabase must be read/write. The form will automatically default a newoutput table name (e.g., BufferZone1). You can either accept or modifythe name or pick an existing table for the results. Once the OK button isselected, the application will create the BufferzonePipe object, calculatea buffer zone, populate an output table, and display the results in themap view.

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

Page 98: Customizing Geomedia

98 Fundamentals of GeoMedia Development Part I

2. Select frmBuffer.frm from the Forms list, and select View Form.

The Buffer Zone form will appear. All of the controls have been placedon the form already. You will add code to the procedure for the OKbutton to perform the actual bufferzone computation.

3. Double click on the OK button.

The code window will appear with the focus set to the btnOK_Clickfunction.

4. Create the BufferzonePipe object.

Use the objBufferZoneSrvc variable for this object.

5. Select the SetupBZPipe function. Convert the distance and unitstrings from the form’s unit selection to meters.

You will need to create a UnitsOfMeasure object (objUOM), and passthe distance and unit values from the form to theConvertUnitToUnit method to get the distance in meters.

6. Calculate the true projected input distance and assign this to theBufferzonePipe.

First get the scale factor from the coordinate system with theStorageToProjectionScale method. Use this value(dblGeomFactor) as the denominator and the value in Step 5(dblNewDist) as the numerator in the calculation the projecteddistance. Set this property on the BufferzonePipe.

7. Set the BufferType property on the BufferzonePipe.

This will vary based on the geometry type of the feature that is to bebuffered. Use the Object Browser to find the values for theBufferZoneTypeConstants.

8. Set the geometry field properties for both the input and outputtables.

The input geometry field name has already been retrieved and stored instrInputGeometryFieldName.

9. Calculate the buffer zone.

Return to the btnOK_Click function. Set a recordset variable(objBufferZoneRS) equal to the OutputRecordset property of theBufferzonePipe.

10. Create a new table with the name of the bufferzone feature class.

Scroll down to the UpdateOutputTable function. Create aMetadataService object (objMetadataSrvc) and set the connection(objConn) on it. Execute the CreateTableDef method on theassociated database within the connection object.

11. Create an originating pipe object to create a recordset for thebufferzone data.

Page 99: Customizing Geomedia

Creating a Custom Application 99

Scroll to the AddLegendEntry function. Create an OriginatingPipe(objOP) recordset (objRS) of the buffer zone feature class. Thetemplate already includes the logic to create a coordinate transformfor this recordset.

12. Display the buffer zone feature on the map view.

Again, in the AddLegendEntry function, add code similar to that whichyou did in Lab 4 using the GetLegendEntry andDisplayTheLegendEntry functions. The call to GetLegendEntrywill have the input objRS and will populate the variable objLE.

13. Save and compile the application. Test the application.

Open a map view. Select the Analyze > Buffer Zone command. Afterpressing the OK button, you should see the mouse pointer change toan hourglass and after a few seconds the bufferzone feature willdisplay in the map view.

Summary: In Lab 9, you established the pipe input properties from theuser’s selections. The units specified by the user are converted tometers. The database scale is retrieved and is used in the calculation forthe pipe’s input distance. Meters is the common measurement unit forall internal operations within coordinate systems and measurement. Anew database table is created in the warehouse and metadata informationadded for the table. The table is populated from the output recordset ofthe pipe. Once the data is stored, you created an originating piperecordset on the new table. You again reused the GetLegendEntry andDisplayTheLegendEntry functions to complete the command.

Page 100: Customizing Geomedia

100 Fundamentals of GeoMedia Development Part I

Locating FeaturesIn the next lab, we will cover the selection of features in the map viewand iteration through the highlighted objects. You will access therecordset corresponding to the selected feature, and finally display theassociated database record in a form. The following GeoMediacomponents are used in this lab:

• SmartLocateService

• EventServer and EventControl

• LocatedObjectsCollection

• HighlightedObjects

Before beginning the lab, let’s review these automated objects.

SmartLocateService Automation

The SmartLocateService is used to locate features adjacent to a point orwithin a specified region in the map view. It requires a map viewdispatch pointer to indicate which map view the point is coming fromand a point geometry. This point will start the search for features. Youmay also use an areal geometry as input to perform a fence locate. Usingthe Locate method, the SmartLocateService populates a collection objectcalled LocatedObjectsCollection. Here are its properties and method:

Property/Method Description

FenceMode Constant used for fence operations indicatingwhether to look for features strictly inside the fenceor for those intersecting the fence — locFenceInsideor locFenceOverlap. This only applies if the inputgeometry is a rectangle.

PixelTolerance Sets or gets the locate point radius, specified inpixels.

Locate Method that takes as input a geometry, a map viewpointer, and a LocatedObjectsCollection. The latterargument is populated by the method.

Here is an example of how the SmartLocateService is used:

Page 101: Customizing Geomedia

Creating a Custom Application 101

Dim objSmartLocSvrc As New SmartLocateService

objSmartLocSvrc.Locate objPointGeometry, ocxMapVw, _

objLocatedObjects

The third argument is the LocatedObjectsCollection. You must createthis collection prior to calling Locate.

EventControl and EventServer Automation

The input point for SmartLocateService.Locate is typically assignedwhen the user clicks inside the map view indicating where the locateoperation should begin. The EventControl is an OLE control that is usedto capture the mouse click event in the map view. This OCX is onlyused with the map view, and, like the map view control, requires acontainer − typically a VB form. Using the control is easy − you simply“drop” the EventControl on the form at design time and assign it a name(it defaults to EventControl1). Any single container should not havemore than one event control associated with it.

After starting a command that uses the EventControl to detect mouse andkeyboard events, the event control must be told what map view it shouldlisten to. This is done with the AddMapView method. A related objectcalled an EventServer must be instantiated at this point. It acts like atraffic controller for all map view events — as the events are fired itdirects them to the correct EventControl for proper handling. TheEventServer provides the ability to tie more than one map view to asingle event control. As such, you can detect mouse clicks in any mapview with one EventControl. Here is how you would initiate listening totwo map views:

Dim objEvServer As New EventServer

ocxEvCtrl.AddMapView ocxMapVw1.Dispatch, objEvServerocxEvCtrl.AddMapView ocxMapVw2.Dispatch, objEvServer

When working with these two components, it is important to know thatonce a command is started, you must also terminate it correctly. Whenusing the EventControl to listen to mouse and keyboard events, you mustalso execute the RemoveMapView method when the command is done.If you fail to do this, GeoMedia (or your custom application) willcontinue to listen to events causing unexpected results. The EventServerobject does not expose any public automation properties or methods.

LocatedObjectsCollection Automation

As noted above, the LocatedObjectsCollection is populated by theSmartLocateService with all features located near the designated point orfence. It is a heterogeneous collection of DisplayedObjects − either a

Page 102: Customizing Geomedia

102 Fundamentals of GeoMedia Development Part I

RecordsetObject, RecordObject, GeometryObject, or RasterObject. Aswith any collection, you are able to iterate through it to determine whatfeatures are contained within it. Here is an example of retrieving fieldvalues associated with a located feature:

Set objRS = objLocatedObjects.Item(1).Recordset

objRS.Bookmark = objLocatedObjects.Item(1).Bookmark

For Each objFld In objRS.GFields

strResult = objFld.Name & “:” & CStr(objFld.Value)

Next

HighlightedObjects Automation

When using the SmartLocateService, it is important to note that the mapview highlight set and/or select set typically come into play. Onceobjects are located, they can be added to the map view’s highlight set orselect set. Like the LocatedObjectsCollection, the HighlightedObjectscomponent is also a heterogeneous collection of the same fourcomponents associated with a map view (RecordsetObject,RecordObject, GeometryObject or RasterObject). Here is how youwould add a feature from the LocatedObjectsCollection to behighlighted in red in the map view:

ocxMapVw.HighlightedObjects.SetDisplayColor RGB(255,0,0)

ocxMapVw.HighlightedObjects.Add objLocObjects.Item(1)

Here are the properties and method for the collection:

Property/Method Description

Count Number of highlighted objects in the collection.

SetDisplayColor Set the highlight color.

Add Add an item to the collection.

Clear Clear the highlight set.

GetRange Returns the corner points of the minimum boundingrectangle that holds all highlighted features.

IsMember Takes as input a pointer to a feature and returns trueor false indicating if the object is in the collection.

Remove Remove an item from the collection

Page 103: Customizing Geomedia

Creating a Custom Application 103

Lab 10: Locate

This lab selects a feature or features in the map view, and then iteratesthrough the highlighted objects. You will access the recordsetcorresponding to the selected feature, and finally display the associateddatabase record in a form.

Section A: Locating a Feature

In this section, the custom application will prompt you to select a featureafter selecting the Analyze > Attributes item from the map view menu.Before running this command, you must first run the View > AddFeature command so that there are features in the map view to select.The event control will detect when the user has clicked in the map viewand then fire a click event. You will add code in the click method of theevent control to determine what feature is near the click point using theSmartLocateService. This process will retrieve a recordset and access aparticular row. You can then iterate through the recordset’s fields anddisplay the results in a textbox on a simple review form. You willreview the results, select OK to dismiss the dialog, and then terminatethe command.

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmMap.frm. Delete the existing EventControl control byselecting this control on the form and pressing the delete key. Placean EventControl OCX on the map view.

Set the name property on the control to ocxEventControl.

3. Select the Analyze > Attributes menu item.

The code window will appear with the focus set to themnuAnalyzeAttributes_Click function.

4. Set the locate tolerance on the SmartLocateService to five.

The service is referenced by the variable, objSmartLocSvrc.

5. Add the map view and EventServer to the EventControl.

Use the AddMapView method on the EventControl. The first argumentis the ocxMapView.Dispatch pointer.

6. Set the status bar prompt to ask the end user to select a feature.

The property on the status bar is SimpleText.

7. Clear the located and highlighted collections. Populate theLocatedObjectsCollection using the SmartLocateService.

Scroll down to the ocxEventControl_Click function. First, use theClear method on objLocatedObjects. Next, use the Clear methodon the ocxMapView.HighlightedObjects collection. Now, populate

Page 104: Customizing Geomedia

104 Fundamentals of GeoMedia Development Part I

the objPointGeometry’s Origin property with the world coordinatevalues. Then, you will use the Locate method on theSmartLocateService object. Use the Object Browser to check theorder of the arguments.

8. Populate the map view’s HighlightedObjects.

Use the Add method.

9. Get the recordset associated with the highlighted feature.

Remember to set the bookmark after you have assigned the recordsetfrom the LocatedObjectsCollection.

10. Iterate through the recordset’s fields, and display the fields andvalues in the form.

Scroll to the DisplayReviewDialog function. This is listed in the(General) section. Generate a string with the field name and fieldvalue for each field in the recordset. Add the string to the listbox onthe form. You should always check database values for Null beforemanipulating them.

11. Add the code to display the form.

This action is supported by the Show method. The argument value ofone (1) indicates that the dialog is modal.

12. When the user selects the OK button, end the command.

Scroll back to the ocxEventControl_Click function. Remember toexecute the RemoveMapView method on the EventControl and thenclear the two collections. In the Wrapup section of this functionrelease the SmartLocateService, LocatedObjectsCollection, andEventServer objects The variables you will reference areocxEventControl, ocxMapView, and objLocatedObjects.

13. Save and compile the application. Test the application.

Open a map view. Add a feature to the map view. Select the Analyze >Attribute command. Select a feature, and you should see the reviewform display with a database record that corresponds to the selectedfeature.

Summary: In Lab 10, you placed the event control and established thecommunication between the view and the control with the event server.The SmartLocateService and the LocatedObjectsCollection areinstantiated to perform the Locate operation. The feature that is foundfirst is highlighted and its field names and values are displayed in thedialog.

Page 105: Customizing Geomedia

Creating a Custom Application 105

Creating a Data ViewIn this section, you will examine the data view control.

A data view control displays the nongraphic attributes of a specificfeature class or query. That is, the input to the data view control is arecordset. Data views do not display geometry columns, long binarycolumns, or other columns flagged as not displayable within the featureclass metadata. In your application, you will place the control on a form.This is usually referred to as a window of the application.

There is no limit on the number of data views you may include in yourapplication. However, there is no inherent relationship between multipleviews. You will be responsible for any synchronization of the datadisplay. If your recordsets are based on the OriginatingPipe and youappropriately broadcast changes when you edit a recordset, the otherviews will reflect the changes since they listen for notification.However, highlighting a row in one view will not highlight the row inthe other view unless you programmatically initiate it.

The data view supports the following types of manipulation:

• Show or hide columns

• Move selected rows to the top of the window

• Multiple cell selection

• Multiple column selection

• Multiple row selection

• Launching of hypertext attribute values

Hypertext attribute values are determined by the metadata informationassociated with the field. Hypertext is a special text field that containsthe name of a file associated with the record.

The data view supports several mechanisms for selecting data, includingboth mouse and keyboard manipulation. Some of the more commonoperations are:

Mode Key Sequence Result

Cell Left Mouse Click Select a cell

Left Mouse Click Drag Select multiple contiguouscells

Control Left Mouse Click Selects a hypertext cellwithout activating the value

Left / Right Arrow Select the next cell

Shift Left / Right Arrow Select a contiguous block of

Page 106: Customizing Geomedia

106 Fundamentals of GeoMedia Development Part I

cells

Control Left / Right Arrow Select a cell one page left orright

Up / Down Arrow Select the next cell

Shift Up / Down Arrow Select a contiguous block ofcells

Control Up / Down Arrow Select a cell one page up ordown

Home Select the first cell

Shift Home Select all cells between thecurrent cell and the first cell

End Select the last cell

Shift End Select all cells between thecurrent cell and the last cell

Column Left Mouse Click Select a single column

Shift Left Mouse Click Unselect all columns andselect contiguous columns

Control Left Mouse Click Select or unselectdiscontiguous columns

Left / Right Arrow Unselect all active columnsand select the next column

Shift Left / Right Arrow Unselect all active columnsand select contiguouscolumns

Control Left / Right Arrow Adds column selections tothe current set of selectedcolumns

Row Left Mouse Click Single select a row

Shift Left Mouse Click Select contiguous rows

Control Left Mouse Click Select or unselectdiscontiguous rows

Up / Down Arrow Unselect all active rows andselect the next row

Shift Up / Down Arrow Unselect all active rows andselect contiguous rows

Page Up / Down Unselect all active rows andselect the first row in thenext page (rows visiblewithin the data view)

Page 107: Customizing Geomedia

Creating a Custom Application 107

Shift Page Up / Down Unselect all active rows andselect a page of rows

Control Page Up / Down Add rows between thecurrent row and one page upor down to the currentlyselected rows

Home / End Unselect all active rows andselect the top or bottom row

Shift Home / End Unselect all active rows andselect all rows between thecurrent row and the top orbottom

Control Home / End Add rows between thecurrent row and the top orbottom to the currentlyselected rows

Recall that an event is a message sent from a control to the application.The message indicates some change that has occurred that the programmight need to respond to. We have already used the EventControl’sevents to receive mouse and keyboard input through the map view.Unlike the map view, the data view will handle many of the mouse andkeyboard inputs and then notify you through an event of what action hasoccurred. The following events are fired by the data view:

Event Description

DeleteRows Not currently fired. The application should includea command to delete a selected row.

GotFocus Standard control behavior.

LostFocus Standard control behavior. Lost focus is usuallyused to complete any pending action.

NewCell Not currently fired.

SelectCell Fired when one or more cells is selected by theuser. You may control the enabling of menuoptions when this event is fired.

SelectColumn Fired when one or more columns is selected by theuser. Also fired when a cell is selected. You maycontrol the enabling of menu options when thisevent is fired.

SelectRow Fired when one or more rows is selected by the useror when the pointer is set to a particular row. Youmay control the enabling of menu options when thisevent is fired.

Page 108: Customizing Geomedia

108 Fundamentals of GeoMedia Development Part I

UpdateCell Fired after the data content of a row is modified.The dataview will update the active row in thedatabase when the focus changes to a different rowor view. Multiple cells (fields) within the row maybe modified for each UpdateCell event.

Many of the GeoMedia data window commands allow the user to makeselections and then perform a command operation. The command willuse the methods on the control to find out what cells, columns, or rowsare selected. Each selection mode is distinct. That is, you cannot have acombination of items selected - only cells or columns or rows but notcells and columns or columns and rows.

OPTIONAL Lab 11: Data View Construction

This lab covers the basic operation of the data view. You will place thecontrol on your form and allow the user to select a table to display.

Section A: Placing the Control

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmData.frm, and select View Object.

The Data Window form will appear.

3. Delete the existing GMDataView control by selecting this controlon the form and pressing the delete key. From the toolbox, select theGMDataview control.

The cursor will change to cross or plus sign.

4. Create a rectangle by placing the cursor in the upper left corner ofthe form and dragging to the lower right corner.

A white box will appear. The name of the control will default toGMDataview1.

5. Adjust the position of the control to set Top = 0 and Left = 0 in theProperties Window.

6. Select frmData in the Project Window, and select View Code.Select the Form object and the Resize procedure. Add logic toadjust the size of the data view when the form resizes.

Use the ScaleHeight and ScaleWidth properties of the form and assignthem to the control’s properties.

7. Save and compile the application. Test the application.

Open a database. Select Window > Activate Data. Select a feature andselect OK. The form should appear with the data view as a whitesquare. Test resizing the form and notice the adjustment of the data

Page 109: Customizing Geomedia

Creating a Custom Application 109

view control.

Summary: In Lab 11, Section A, you placed the data view control,adjusted its position, and added the logic to automatically resize it.

In this section of the lab, you will display a recordset in the data view.

Section B: Associating the Recordset

1. Return to the Visual Basic project. Select mfrmMain in the ProjectWindow, and select View Code. Select the mnuWindowDataobject, and select the Click procedure.

2. Add logic to associate the recordset with the data view.

Use the SetRecordset method on the control. The inputs to this functionare a database pointer, a caption, and, a recordset. The databasepointer need not be initialized. Use objDB which is defined in thefunction. Use the name of the table as the caption. The name of thetable can be found by looking at the SourceTable property on thefirst field of the recordset. Finally, the recordset, objRS is returnedfrom the CreateRecordset function.

3. Save and compile the application. Test the application

Open a database. Select Window > Activate Data. Select a feature andselect OK. The form should appear displaying the contents of theselected feature.

Summary: In Lab 11, Section B, you created a recordset and associatedit with the data view.

In this section of the lab, you will change the recordset displayed in thedata view.

Section C: Changing the Recordset

1. Return to the Visual Basic project. Select frmData in the ProjectWindow, and select View Code. Select the mnuToolsChangeobject, and select the Click procedure.

2. Add logic to change the recordset associated with the data view.

Again, use the SetRecordset method on the control. The inputs are thesame as in the previous section of the exercise.

3. Select frmMap in the Project Window, and select View Code.Select the mnuWindowData object, and select the Click procedure.

4. Add logic to make sure a recordset is active before showing the datawindow from the active map view.

Page 110: Customizing Geomedia

110 Fundamentals of GeoMedia Development Part I

Again, this is the same logic as implemented in step 2.

5. Save and compile the application. Test the application

Open a database. Select Window > Activate Data. Select a feature andselect OK. The form should appear displaying the contents of theselected feature. Select Tools > Change Contents. Select a featureand select OK. The contents of the view should change to reflect thenew feature class.

Summary: In Lab 11, Section C, you again used the SetRecordsetmethod to implement the Change Contents command.

OPTIONAL Lab 12: Multiple Key Sort

This lab involves a common operation on tabular data − sorting. TheGeoMedia product supports a single key sort operation. The SortPipeobject is used to perform the sorting. The pipe object actually supports amultiple key sort.

Section A: Setting up the Form

1. Open the project, C:\TGM\Labs\CustomApp\src\customapp.vbp.

The project window will appear.

2. Select frmData.frm, and select View Code. Select mnuToolsSortfrom the object list, and select the Click procedure.

The command, Tools > Sort is enabled when the data view is active. Thefunction simply calls SortRecordset.

3. Select modSort.bas from the project window, and select ViewCode.

The file contains the function SortRecordset. The function is fullydefined to display the fields associated with the recordset displayedin the data window.

4. Review the code for retrieving the recordset and adding the fields tothe form.

5. Test the application.

Open a database and display the data window. Select Tools > Sort.Verify that the list of attributes is populated on the left.

Summary: In Lab 12, Section A, you reviewed the logic for populatingthe form with the recordset fields available for sorting.

Page 111: Customizing Geomedia

Creating a Custom Application 111

The remaining section of the lab will create a sort key for each fieldchosen from the left list and moved to the right list. As fields aredropped from the right, the sort key will be removed. Finally, when theOK button is selected, the data view will be updated with the output ofthe sort pipe.

Section B: Setting up the Pipe

1. Return to the Visual Basic project. Select frmSort in the ProjectWindow, and select View Code. Select the btnAdd object, andselect the Click procedure.

2. Add logic to set the name of the field for one of the sort keys and theascending flag value. Append the key to the collection on theSortPipe object.

The pipe has been created in the Form_Load subroutine. objSortPipe isavailable globally within the file. You will need to populate theobjKey variable, setting the SortFieldName to the currently selectedattribute — lstAvailable.List(lstAvailable.ListIndex). Use the valueof optFlag(0).Value to set the SortAscendingFlag. Finally, appendobjKey to the SortKeys collection on objSortPipe.

3. Select the btnClear object and the Click procedure.

4. Add logic to remove the fields selected in the right list from thecollection of keys.

Simply re-create the SortKeys collection on objSortPipe to clear the listof entries. The SortPipe keys collection does not support a removemethod. An alternative implementation is to manage your owncollection of SortKey objects and delete them from this list.

5. Save the project, compile, and test the application.

Open the database, activate the data window, and select Tools > Sort.Test your work by adding several attributes and clearing the sortlist.

Summary: In Lab 12, Section B, you created a SortKey for eachselected field and set the SortAscendingFlag appropriately. You addedlogic to clear the collection of keys in case the user selected them in thewrong order.

Finally, you will see the sorted recordset. The sort is controlled by theorder that the keys are added to the collection. For instance, if you wantan alphabetic list of employees by their last name, you would first addthe LastName field to the collection. Follow this by FirstName andMiddleInitial to get a list sorted first by last name. Within the same lastname, the list is sorted by first names. Finally, when both last and first

Page 112: Customizing Geomedia

112 Fundamentals of GeoMedia Development Part I

name are the same, the data is ordered by the middle initial.

Section C: Updating the Data View

1. Return to the Visual Basic project. Select frmSort in the ProjectWindow, and select View Code. Select the btnOK object, andselect the Click procedure.

2. Add logic to retrieve the recordset from the data view. Use it asinput to objSortPipe.

Use the GetRecordset method on the data view control to populateobjRS. Assign this to objSortPipe.InputRecordset. Use thetemporary variable, objRS, to pass to GetRecordset on the dataview control.

3. Retrieve the output recordset from the pipe, and associate it with thedata view.

Use the SetRecordset method on the data view control. Again, objDB isnothing (no active object assigned to the variable) and the captioncan be derived from the SourceTable of one of the recordset’s fields.To distinguish the sorted recordset, you should concatenate “Sorted” to the table name. Use objSortPipe.OutputRecordset asthe final argument.

4. Save the project, compile, and test the application.

Open the database, activate the data window, and select Tools > Sort. Test your work by adding several attributes and selecting OK.

Summary: In Lab 12, Section C, you established the recordsetassociated with data view as the InputRecordset for the SortPipe. Youthen retrieved the OutputRecordset from the pipe and assigned it to thedata view.

Page 113: Customizing Geomedia

Creating a Custom Application 113

Custom Application LimitationsAs presented in our first section, there are three ways to customizeGeoMedia:

• Custom commands

• Custom application

• Driving GeoMedia

The third section of the workshop will address custom commanddevelopment while this section addressed custom applicationdevelopment. We will not pursue the third option in this workshop.

To determine how you pursue GeoMedia customization, you need toweigh the advantages and disadvantages of each option. While a customapplication allows you better control over the user’s workflow, it doesrequire more development time than the custom command option. Inparticular, a custom application must address these items:

• Persistence of data and settings

• Document and window management functions

• Multiple view synchronization

• Database edit broadcasting

• On-line help

• Application delivery

How much extra time is required for development is entirely dependenton the sophistication of the custom application. Let’s examine thesedevelopment areas in more detail.

Persistence

What is persistence? Persistence is the process of saving data anddefinitions created during an application session. In GeoMedia, thegeoworkspace or document is where this information is saved. Ofcourse, your geographic data is saved, but this is written directly to thedatabase and is not included in this discussion.

What types of items (objects) are saved or persisted? In GeoMedia,many of the objects that are member objects of the application arepersisted. This includes named legends, windows, query folders, andspatial filters. When a window is saved, we also save the position of thewindow, the associated legend (if it’s a map window), and subsequentlythe recordset(s).

Naturally, the inverse of persistence is loading the data and definitions.

Page 114: Customizing Geomedia

114 Fundamentals of GeoMedia Development Part I

This process restores the application state to the condition the user lastviewed.

So, do you need persistence? This choice is determined by yourapplication requirements. None of the GeoMedia objects are persistableoutside of the geoworkspace. As such, you must maintain allinformation necessary to recreate the objects. This information must besaved in some file format you determine, and, when your applicationrestarts, you must recreate the GeoMedia objects with the savedinformation.

Document and Window Management

This area of functionality includes opening and closing of the persistentstores (e.g., the geoworkspace), and the display of map and datawindows. Additionally, you may choose to implement commonoperations like Cascade and Arrange for the window objects.

If your application is written in Visual Basic, you will have to implementmost of this yourself. In Visual C++, the wizard-generated applicationusually includes these types of operations. You will simply need to addthe appropriate GeoMedia objects.

Multiple View Synchronization

As you work with GeoMedia, you will notice that when an object (afeature instance) is selected in one view, the corresponding object isselected in the other views that contain the object. GeoMediacoordinates this through the document’s selected objects collection.When a selection is made, the command (in most cases the Select Tool −northwest arrow) adds the item to the collection. The collection thennotifies all of the views about the selected items. The views in turn scantheir displayed data for a match and select the item if found. Thissystem of notification is unique to GeoMedia and its selected objectscollection.

If you want to simulate similar behavior in your application, you willneed to manage the windows, the selection of data, the broadcast of theselection, and the subsequent data selection in other views. In order toselect the correct objects, you will need to understand how to identifyeach object uniquely. You could simply select the object in all views.However, you usually only want to add a selection when the data isactually displayed. Identification of objects is usually done through keyfields in each object.

While this is very useful behavior for the application, this task representsa significant development effort.

Database Edit Broadcasting

When you modify values in a recordset, the server will create entries

Page 115: Customizing Geomedia

Creating a Custom Application 115

(rows) in the modification tables. These entries indicate which tableshave been modified and the type of modification (add, edit, or delete). Ifyou open the database directly through the GDO interface rather than theconnection object, you can turn off this logging.

For GeoMedia, the process of logging edits and the broadcast enablesthe application to reflect the edit in other windows that contain the samefeatures. Broadcast is the process of reading the modification tables,finding all the recordsets affected by the modification, and notifying(sending a message) to all the objects that are referencing this recordset.Let’s take an example. In a data window, there is a recordset open onthe river table that contains all of the feature instances. One of theattributes is the river depth (RDEPTH). On the legend of a map view isa recordset containing all rivers where RDEPTH < 20. In the datawindow, the user modifies a row (feature) and changes one value ofRDEPTH from 10 to 30. When the broadcast is completed, the mapview will display one less river since the modified row no longer meetsthe criteria of the query.

These capabilities — synchronized displays and automatic resultrecalculations — are quite powerful. To achieve the same affect in yourapplication, you can use one of two approaches. In the first approach,you simply need to use the connection object for database access andcreate all recordsets through the originating pipe object. Then whenyour commands edit data, you must callConnection.BroadcastDatabaseChanges. The other alternative involvesusing GDO directly for the database open and recordset creation. It thenbecomes the application’s responsibility to process the modificationtables, find the recordsets, and recreate the recordset to reflect thechanges. The GDO interface does not support a refresh or requerymethod so you will need to retrieve the data again.

If your application does not allow data edits, then you need not worryabout this. Alternatively, you may deem it acceptable to allow the viewsto lose synchronization. The first alternative to achieving this is quitesimple if considered from the outset of your development.

On-Line Help

GeoMedia includes extensive documentation about the product’sfunction and command processing. While you might still reference thismaterial, it is highly likely that you would write your own help toaccompany the application.

Application Delivery

Whether you add one command or build a complete application, youneed to consider how you will move your software to each user’smachine. If GeoMedia is a prerequisite (as is most often the case), andyou are adding commands, you can create a compressed file, and create aseries of command files to automate registration of the commands. One

Page 116: Customizing Geomedia

116 Fundamentals of GeoMedia Development Part I

command will be the setup command that automates the configuration ofthe GeoMedia menus. You will need to run GeoMedia and your setupcommand on each machine. An alternative to the compressed andcommand files is a setup application. Even with this alternative, youwill need to create and run the setup command.

You can take a similar approach to the installation of a customapplication. In this scenario, you won’t need the setup command.

If you have established the legal OEM agreement with Intergraph toredistribute the GeoMedia object DLLs, you will be responsible for thedelivery and registration of all the necessary files. This includes objectDLLs, type libraries, and OCXs as well as supporting DLLs thatGeoMedia uses. You will need to update the registry with the path tothe DLLs or put your executable in the same directory as the supportingobject DLLs.

Application delivery is a necessary component in your developmentprocess. It is highly advisable that you begin this process early - as soonas you have a working subset of your application. It is imperative thatyou test the installation on a non-development machine. Also, you needto include an uninstall mechanism to remove the software componentsfrom the user’s machine.

Summary

The choice of customization technique is yours to make. Onlydevelopers and companies who have entered into legal OEM agreementswith Intergraph can redistribute GeoMedia DLLs. So, in most cases, youmust install GeoMedia whether you use the product or just the objects.

Although at the outset, a custom application may appear to be thesimplest approach, be sure to consider the long term projectrequirements. You may find that you quickly end up recreatingGeoMedia.

Page 117: Customizing Geomedia

Creating a Custom Application 117

Summary The overall objective of this section was to familiarize you with thecreation of an independent custom application that uses GeoMediaobjects. To this end, you learned how to do the following operations in aVisual Basic application.

• Make a connection to a warehouse through a GDO server

• Create and manipulate recordsets

• Use a MapView control and display data in it

• Customize the display characteristics of your data with styles

• Perform spatial analysis with spatial queries and buffer zones

• Locate your data

• Display the attributes of your data in a data view and sort it

In doing so, you have utilized the following objects:

• Connections, Connection

• GDatabase

• GRecordset, OriginatingPipe

• GFields, GField

• GMMapView

• Legend

• LegendEntries

• RecordLegendEntry

• Styles

• GMNorthArrow

• GMScaleBar

• MetadataService

• SpatialQueryPipe

• BufferZonePipe

• SmartLocateService

• EventServer and EventControl

• LocatedObjectsCollection

• HighlightedObjects

Page 118: Customizing Geomedia

118 Fundamentals of GeoMedia Development Part I

• GMDataView

• SortPipe

Can You Answer These Questions?1. What is notification? What is its significance?

2. What is the component hierarchy of the GDO components?

3. What can you use instead of GDatabase.OpenRecordset? Why?

4. What is persistence?

5. What is the significance of GDO over DAO?

6. What is a ProgID? When is it used? Where is it stored?

7. How do you find the PrimaryGeometryFieldName of a table? Of arecordset?

8. Complete these descriptions in the context of GeoMediaprogramming.

A table is a ???.

A column is a ???.

A row is a ???.

Page 119: Customizing Geomedia

Adding Commands to GeoMedia 119

Adding Commands to GeoMedia

Introduction

The simplest approach to GeoMedia customization involves the additionof commands. By adding commands, you can expand the capabilities ofGeoMedia while focusing solely on the value added code. That is, youneed not implement the mechanics of an application since this frameworkis inherent in GeoMedia.

This section of the workshop will present the types of commands, how tocreate a command, debugging commands, and the creation of modal andmodeless commands.

Topics

1. GeoMedia’s Command Wizard

2. Command Types

3. Creating the Command Skeleton

4. Modal Commands

5. Modeless Commands

Objectives

At the end of this section, you will be able to:

1. Describe the operation of the Command Wizard

2. Describe the types of GeoMedia commands that may be created

3. Describe command stacking and priorities

4. Implement a modal command

5. Implement a modeless command

6. Use the following objects:

EventControl EventServer RectangleGeometry

MapView Legend RecordLegendEntry

PointGeometry LinearStyle GeometryEditService

Query QueryFolder OriginatingPipe

Page 120: Customizing Geomedia

120 Fundamentals of GeoMedia Development Part I

ExtendedPropertySet

MetadataService Connection

CSSTransformPipe GeometryStorageService ServerTransService

Labs

13. Hello GeoMedia!

14. Custom Reports

15. Magnify View

Page 121: Customizing Geomedia

Adding Commands to GeoMedia 121

GeoMedia’s Command WizardGeoMedia’s Command Wizard is a Visual Basic add-in. An add-inautomates common tasks. In this case, the task is the creation of aGeoMedia command. The add-in becomes accessible from the VisualBasic development environment. The term wizard is used to describe apart of a program that guides you through a series of steps to accomplish atask.

Note: If Visual Basic is not installed when you install GeoMedia, youwill need to manually add the wizard to make it accessible from VisualBasic. Run the regwiz.exe from the c:\program files\GeoMedia\wizarddirectory. In Visual Basic, select Add-Ins > Add-In Manager…, andcheck the GeoMedia Command Wizard entry. Select OK .

The Command Wizard creates a Visual Basic project that functions as acommand for GeoMedia and edits or deletes command set information.

Commands are separated from the GeoMedia framework through aninterface. This means that each command is an automated object.Through automation, the application and the command components worktogether. The GeoMedia framework and the individual commands areautomation servers. The framework exposes the application objects tosupport application programmability and customization. The frameworkexpects individual commands to expose an automation interface whichsupports the command’s side of communication with the framework. TheCommand Wizard supplies the automation interface for you. Theinterface includes the following methods. These will be reviewed as wediscuss the types of commands.

Note: While each command is an automated object, you cannot call onecommand from another. Additionally, you cannot call GeoMediacommands from an independent application. The PageSetup and Printcommands are exceptions to this rule.

Property/Method Description

IsDone Indicates whether or not the modeless command hascompleted processing. This property should be set toTrue if the command has completed processing andrequests termination.

Page 122: Customizing Geomedia

122 Fundamentals of GeoMedia Development Part I

Initialize Called when a command server is created. Currently,the server is created only once within a GeoMediasession.

Activate Called to start the command. A modal commandshould show its main form. Modeless commandsshould set their IsDone property to False and connectto their views if they are also view listeners. Thismethod is called multiple times during the commandserver object’s lifetime.

CanDeactivate Called by command manager to determine if thecommand can be deactivated. This method allows thecommand to perform any user interaction necessary tocomplete any pending actions.

CanEnable Called by the framework when custom enabling hasbeen specified. The command logic must determine ifconditions are appropriate for the command toexecute.

CanActivate Called by the framework when custom activation hasbeen specified. Not currently supported?

Deactivate Called to make the command become inactive.

AddView Called when a new map view is opened.

RemoveView Called when a map view is closed.

IgnoreEvents Called when your command is suspended.

RestoreEvents Called when your command is reactivated.

Terminate Called when your command server is about to bedestroyed. This currently occurs when GeoMedia isexiting. Since this occurs after the workspace isclosed, you must release global variables associatedwith the workspace prior to this method.

The wizard begins by asking for the type of operation: add, edit, or deletecommand. A command edit allows you to change the status message, tooltip, and enabling conditions for a command. A delete request removes thecommand from the command set. An addition creates a new commandproject.

The second step of the wizard, Choose Project Location, prompts you tochoose a directory for the command - optionally creating a new directory.It’s a good idea to have a central location for all of your command

Page 123: Customizing Geomedia

Adding Commands to GeoMedia 123

directories, although this is not required.

The third step of the wizard, Choose Command Name, gathers informationabout the command, including the name, the status message, and thetooltip. A status message appears in the application’s main window asyou drag your cursor over the menu item. The tooltip appears as you holdyour cursor over a toolbar button. It is also used as the name of thecommand in the Tools > Customize… command list. The commandname in combination with the Project Name from the previous stepcomprises the ProgID for the command. GeoMedia uses this to create aninstance of your command class.

The fourth step of the wizard, Command Classification, indicates thenature of the command processing. Modal commands generally display adialog that prohibits selection of any item (vector data, menu items) untilthe dialog has been dismissed. Essentially, a modal command hascomplete focus of the application, and nothing else can occur until thecommand completes. Modeless commands may display modeless formsand allow other parts of the application to process while they are active.

Note: Due to limitations in Visual Basic’s OLE Server implementation,you cannot display a modeless dialog in an OLE DLL. Modeless dialogsmust be created in VC++. Alternatively, you can use the DockableControlobject in the GeoMedia framework to host an ActiveX control. VisualBasic 5.0 supports the creation of these controls and they can be used likemodeless dialogs. Refer to the article,mk:@ivt:kb/source/vbwin/q171978.htm, on Microsoft’s DeveloperNetwork. Note that Visual Basic 4.0 did not support any modeless dialogsin OLE DLLs. In Visual Basic 5.0, if the application (EXE) is built withVisual Basic 5.0, modeless dialogs can be created in an OLE DLL.GeoMedia is built with Visual C++ and does not provide the interfacerequired for the communication with the application message looprequired to support modeless VB dialogs.

The fifth step of the wizard, Choose Form Name, requests the name of theform and an indication of desired position. The wizard generates thenecessary code to position the form.

Page 124: Customizing Geomedia

124 Fundamentals of GeoMedia Development Part I

If you specified that the command is modeless, the View Listener step asksif you will listen to events exposed through the map view -- like mouseclicks and keyboard input. The View Listener Requirements step asks forinformation about the type of views you will listen to. Finally, the ViewListener Command Type step determines the classification or priority yourcommand will take. Refer to Command Types for information on theseselections.

The sixth step of the wizard, Command Enabling Conditions, allows youto control when the command is enabled on the menubars. Specificationof the appropriate set of enabling conditions can simplify your command’serror handling. The wizard provides an extensive list of conditions thatcan be checked for. You may select as many conditions as necessary.Some conditions preclude others. For example, if your command requiresthat an element must be in the select set, you need not specify that ageoworkspace must be open since you cannot select an item without anopen workspace. The set of enabling conditions cover aspects ofdataview, queries, connection, windows, and the select set. Additionally,you can specify your own enabling conditions. If you specify customconditions, you must implement the CanEnable method on the commandmanager interface.

The final step, Complete, simply summarizes the activities and indicatesthe files that will be generated. The files are divided into twosubdirectories within your project. When you select Finish, the wizardwill generate the following set of files.

File Purpose / Content

src\GeoMediaCommand.vbp Visual Basic project

src\MyCommand.cls OLE class definition and commandinterface functions

src\modMyCommand.bas Form centering logic and globals

src\frmMyCommand.frm Default form

src\MyCommand.txt Text file which recaps the commandspecification information

bin\MyCommand.ini Specification of command setinformation used when the command isregistered for access by GeoMedia

Once you compile your command, it can be positioned on a GeoMediamenubar and executed. If you need to move the command to another

Page 125: Customizing Geomedia

Adding Commands to GeoMedia 125

machine, you need only take bin\MyCommand.dll andbin\MyCommand.ini. You will need to install the command on the othermachine using the installation program:

“c:\Program Files\GeoMedia\Program\Installusrcmd.exe”MyCommand.dll MyCommand.ini

This program registers the command and updates the command set on theother machine. Because commands are written as OLE servers, they canbe easily reused in other projects. Of course, the ease of reuse is tied tohow well you have generalized your processing and eliminated any data-set-specific dependencies.

Page 126: Customizing Geomedia

126 Fundamentals of GeoMedia Development Part I

This page is intentionally blank.

Page 127: Customizing Geomedia

Adding Commands to GeoMedia 127

Command TypesGeoMedia supports two fundamental classifications of commands: modaland modeless. Modal commands take control of the entire applicationuntil the commands complete their functions. This group includes all ofthe commands that display dialog boxes to collect user input beforeperforming a task (File Open, File Send Mail), all object-action commandswhich are enabled when the required type of object is selected (userinteraction occurs before the command is started), and all commandswhich require no further user interaction after the command is started.These command manager interface methods are applicable to modalcommands:

• Initialize

• CanEnable (if custom enabling specified)

• Activate

• Terminate

Modeless commands briefly take control of the application to create orconnect to windows. These commands consist of two phases: setup(modal) phase and the listening phase. During the setup phase, thesecommands may create new modeless windows or start listening to eventsat existing windows. Modeless commands then return control to theapplication. After the overall application is released to respond to events,these commands are still active. Modeless commands listen for events atthe windows they create or to which they attach. Modeless commandsremain active until they receive an event instructing them to deactivate.

Some modeless commands require the user to interact with GeoMediawhile the form is displayed. Such a form is referred to as modeless. Ifyou need to have the form displayed while you are moving the mouse overthe application window, the form must be modeless. Commands thatrequire modeless forms must be written in Visual C++. A modelesscommand has two phases: setup, which is typically modal in nature, andlistening, during which the command responds to events. In addition tothe methods that modal commands implement in the command managerinterface, all modeless commands also implement:

• Deactivate

If you specify a command as modeless, a further classification processoccurs. If you want your modeless command to receive mouse andkeyboard events, it is a map view listener command. When writing acommand that acts as a map view listener, it is very important that you

Page 128: Customizing Geomedia

128 Fundamentals of GeoMedia Development Part I

understand the calling sequence of the command manager interfacemethods in your command class. Modeless commands that are viewlisteners will implement the remaining command manager interfacemethods:

• AddView

• CanActivate (if custom listening specified)

• CanDeactivate

• RemoveView

• IgnoreEvents

• RestoreEvents

So that GeoMedia can control the simultaneous processing of modelesscommands, modeless commands are classified. Through thisclassification, we establish a command stacking priority.

There are four classifications of map view listeners:

1. Selection

2. Placement / Editing

3. View Change

4. Tracker

A Selection command’s primary purpose is the selection of data elements.In GeoMedia, this is the Select Tool or Northwest Arrow. Only onecommand from this group can be listening to a single map view at a time.It is possible to have different selection commands active if you havemultiple views active and they are listening to only one view.

A Placement / Editing command’s primary purpose is the creation ormodification of data. Only one command from this group may be active.In GeoMedia, Insert Feature and Modify Feature Geometry are examplesof this type.

A View Change / Define Subview command’s purpose is to modify theextents of the view or extract information about the view. In GeoMedia,Print and Snapshot are examples of this type.

For each of the command group types above, the initiation of a newcommand in the same group terminates another command of the sametype, and it will terminate any other type of higher priority if the othercommand allows the termination request. A new command from a higher-priority classification temporarily steals events from the active selectioncommand.

The final group, Tracker, does not participate in the command-stacking

Page 129: Customizing Geomedia

Adding Commands to GeoMedia 129

process. Any number of tracker commands may be active at the sametime. In GeoMedia, the Coordinate Readout and ScaleBar are examplesof tracker commands.

The commands exhibit the following priorities:

Priority Command Type

Highest View Change

Intermediate Placement / Editing

Lowest Selection

Command priority provides the capability to stack commands. Forexample, if you initiate the selection tool (Northwest Arrow in GeoMedia)and then select a placement command, you have suspended the selectiontool command. When you complete the placement command, theselection tool command will resume. In a similar fashion, if you selectzoom in while the placement command is active, the placement operationis temporarily suspended. When you complete the zoom operation, theplacement command will resume.

The tracker commands operate independently of all other command types.That is, they have no effect on and are not affected by the activation ofother commands. For any single view, GeoMedia can have threecommands stacked and any number of tracker commands processing.Initiation of commands defined as modal do not explicitly affect anystacked commands in the modeless groups.

View Listener Hints and Tips

All of the view listener types of commands exhibit the following behavior:

1. When the command class is first created, the Initialize method iscalled. Each time the command is selected, the Activate method iscalled.

2. Since your command can be selected even though it might already berunning, you must handle the reactivation. For example, don’treattach to views that you’re already listening to.

3. You will normally attach to the map view during the Activate methodby calling the Add method on the view listener object.

4. Deactivate is only called during application shut down if yourcommand is currently active.

Page 130: Customizing Geomedia

130 Fundamentals of GeoMedia Development Part I

5. If you support a self termination (i.e., honor the ESC key), then youwill typically call your own Deactivate method. Do not rely onGeoMedia to do this.

6. If another command of lesser or equal priority is selected while yourcommand is active, your CanDeactivate method will be called for eachmap view that is in conflict. If your command returns True for all theCanDeactivate calls, then your RemoveView method will be called foreach conflicting view. When the last map view is taken away fromyour command, then your command should set IsDone to True andreset to its inactive state. Essentially, selecting another command ofequal or lesser priority will cause your command to terminate.

7. If another command of greater priority collides with your command ata map view, then your IgnoreEvents method will be called for eachview in conflict. This essentially suspends your command. When theother command completes, your RestoreEvents method will be calledfor each view in conflict.

8. If your command has requested notification of new views, yourAddView method will be called either if the command is active or if itis ignoring events.

9. When a map view window is closed, the CanDeactivate method willbe called for all commands that are active or ignoring events for thewindow. If any CanDeactivate method returns False, the window willnot be closed and the commands continue processing. If allCanDeactivate calls return True, then RemoveView is called on all thecommands referencing the view.

10. When GeoMedia exits, all map view windows are closed. This will inturn cause all view listener commands to self terminate when their lastview is removed. All remaining commands will have their Deactivatemethod called. Finally, the Terminate method for all loadedcommands will be called.

11. If you have not specified custom enabling or activation rules, thenreturn True for CanEnable and CanActivate. If you have customrules, you will need to examine the condition of the application andreturn True if you can enable or activate. Return False if theconditions are not correct for your command to run successfully.

12. The IsDone property should be set to True when your command isinactive. You are inactive if all operations have been completed andyou are waiting for the next Activate request. Otherwise, return False.

Page 131: Customizing Geomedia

Adding Commands to GeoMedia 131

Creating the Command SkeletonThis section provides you with hands-on experience with the commandwizard and accessing your command in GeoMedia. Each step of thewizard is accumulating information about your command for GeoMedia’scommand set. Once you have completed all of the steps, your commandwill be available for use within GeoMedia.

Object Browser

Since you will be creating commands that utilize GeoMedia’s objects, youneed to be familiar with the object browser in Visual Basic. This tooldisplays the objects and their properties, constants, and methods that areavailable in object (type) libraries. You can also examine your ownproject modules and procedures. The object libraries that are visible inthe browser are controlled by the references you have established in theproject. By default, the GeoMedia Command Wizard includes most of thecomponents’ type libraries associated with GeoMedia, as well as theMapView, DataView, and EventControl custom controls.

Type Library Description Object Types

Intergraph GeoMedia EventControl 2.0

Custom control for receivingmapview events

Intergraph GeoMedia Map ViewControl 2.0

Custom control for displayinggeographic data

Intergraph GeoMedia Framework2.0

GeoMedia application andworkspace objects

Intergraph GDO 2.0 ObjectLibrary

GDatabase objects

Intergraph GeoMediaExtendedPropertySet 2.0

Support for extension objects

Intergraph GeoMedia BasicUtilities 2.0

Geometry definitions

Intergraph GeoMedia ClientSupport 2.0

Connections and services

Intergraph GeoMedia CoordinateSystems 2.0

Coordinate system objects

Intergraph GeoMedia MapViewing 2.0

Legend and style definitions

Page 132: Customizing Geomedia

132 Fundamentals of GeoMedia Development Part I

Intergraph GeoMedia Services 2.0 Metadata constants

Intergraph GeoMedia Services 2.0 Metadata and preference set objects

Intergraph GeoMedia DatabasePipes 2.0

Attribute-based pipe objects

Intergraph GeoMedia GeometryPipes 2.0

Geometry-based pipe objects

Intergraph GeoMedia GeoMath2.0

Math function definitions

Intergraph GeoMedia ThematicDisplay 2.0

Thematic legend entries

Intergraph GeoMedia Raster 2.0 Raster manipulation objects

You may need to add these references:

• Intergraph GeoMedia CAD Server 2.0

• Intergraph GeoMedia Feature Controls 2.0

• Intergraph FRAMME GDO Extension 1.0 Object Library

• Intergraph GeoMedia North Arrow Control 2.0

• Intergraph GeoMedia Scale Bar Control 2.0

• Intergraph GeoMedia Coordinate System Dialog Control 2.0

• Intergraph GeoMedia Data View Control 2.0

• Intergraph GeoMedia Controls 2.0

GeoMedia includes additional DLLs that appear in the browser. However,they contain commands and are not developed for reuse by other software.To add an additional type library, select Tools > References... and thensearch through the list by selecting “I” to find the Intergraph libraries.The browser does not alphabetize the list. Check the appropriate libraryand select OK. To add an additional control, select Tools > CustomControls.... You may get a series of warning messages indicating “Objectserver not correctly registered.” Simply dismiss these dialogs. Check theappropriate control and select OK.

Within the browser, you first select the library of interest. The availableclasses will appear for the library. By selecting a class, you will see theassociated properties and methods. Selection of a method will expose themethod’s signature (call sequence). Within an active method or property,you can select Paste to copy the information to the cursor location within

Page 133: Customizing Geomedia

Adding Commands to GeoMedia 133

your code. If you pasted a method, the resulting code will use namedarguments. Through this technique, you can specify the arguments to themethod in any order. If you do not use named arguments, then thearguments must be in the same order as in the method definition. Youmay also select the help button to activate the automation help file. Thisprovides you with specific information about the selected object, method,or property.

GeoMedia’s Menus and Toolbars

After you compile your command’s DLL, you will associate yourcommand with a menu item within GeoMedia. There are three menus inGeoMedia. The menu that appears depends on the active window. Whenno window is open (i.e., no workspace is open), the window type is none.When a map window is active, the window type is Map. Finally, when adata window is active, the window type is Data. If your command isapplicable to all types of windows, you will need to add it to each menu.To associate a command to a menu, you will use the Tools > Customize...command. This command allows you to add or remove commands. Youmay also add a new section on the menubar.

You may also customize the GeoMedia toolbars. The Tools >Customize... command is also used for this operation.

Lab 13a: Hello GeoMedia!

This lab will create a very simple modal command, attach it to theGeoMedia menus, and run the command. Since the standardprogramming exercise is always “Hello world” for any new language, wewill oblige with “Hello GeoMedia!.”

Section A: Using the Wizard

1. Initiate Visual Basic by selecting the desktop icon or from the Startmenu.

A dialog New Project will appear; select OK

2. Select Add-Ins > GeoMedia Command Wizard... If this menu itemdoes not exist, select Add-Ins > Add-In Manager... and selectGeoMedia Command Wizard. Then reattempt step 2.

The Introduction dialog will appear.

3. Select Create a new project for a command., and select Next >.

The Choose Project Location dialog will appear.

4. Under Project Location:, select c:\TGM\Labs.

Page 134: Customizing Geomedia

134 Fundamentals of GeoMedia Development Part I

5. Under New Subdirectory Name:, enter Lab13. Select Next>.

The Choose Command Name dialog will appear.

6. In Command Name:, specify Hello.

7. In Command Description:, specify Welcome to GeoMedia.

8. In Command Tool Tip:, specify Hello GeoMedia. Select Next >.

The Command Classification dialog will appear.

9. Select Command is Modal. Select Next >.

The Choose Form Name dialog will appear.

10. Select Form is centered in the Intergraph application window. Select Next >.

The Commands Enabling Conditions dialog will appear.

11. Select GeoWorkSpace is open. Select Next >.

The Complete dialog will appear.

12. Select Finish.

You will be prompted to open the new project. Select Yes. You may alsobe prompted to save the initial project. In this case, you may selectNo. In your normal development activities, you may need to specifyYes.

13. Save your project with File > Save Project.

14. Create the server DLL by selecting File > Make Hello.dll...

A dialog will appear asking for the output location.

15. Select C:\TGM\Labs\Lab13\bin. Select OK.

16. Collapse or exit Visual Basic.

Summary: In Section A, you successfully used the command wizard tocreate your Visual Basic command project.

Section B: Adding the Command to GeoMedia

1. Start GeoMedia. Create a new geoworkspace (File > NewGeoWorkspace...). Use the default template.

2. Connect to the sample warehouse. Select Warehouse > NewConnection... and select Access and the Us Sample Data.mdb in thec:\warehouses directory. All of the default options on the wizard are

Page 135: Customizing Geomedia

Adding Commands to GeoMedia 135

acceptable.

3. Save your new workspace so that you may use it in the other labexercises. Select File > Save GeoWorkspace..., and specify anyname you choose. Store it in the c:\geoworkspaces directory.

4. Select Tools > Customize...

The Customize dialog will appear.

5. Select the Custom category from the Categories: list.

The Commands: list will update to reflect all user defined commands.

6. Select the Hello GeoMedia command.

7. Select Help from the Change what menu: list.

8. Select Add, and select Close.

Your command is now associated with the Map window type menu. If youwant the command available for all of the windows, repeat theprocess for each of the Window Type: entries.

9. Select Help > Hello GeoMedia.

The default dialog should appear.

10. Select OK, and select File > Exit to terminate the session.

Summary: In Section B, you successfully added your command to theGeoMedia menus. You are able to run your command. It will display thedefault dialog created by the Command Wizard. You can also create acommand that will configure the GeoMedia menus.

Section C: Updating Code

1. Return to the Visual Basic project for your command.

2. If the Project Explorer window is not already displayed, select View> Project Explorer. Under the folder GeoMediaCommand(GeoMediaCommand.vbp) and under the subfolder Forms, there isthe form frmHello (frmHello.frm); double-click on it.

The default form will appear.

3. Delete all of the controls ( two label controls and one button control ).

Simply select the controls with the mouse, and press the delete key.

4. Display the Properties Window (View > Properties Window). Selectthe Font property, and select the ... button.

Page 136: Customizing Geomedia

136 Fundamentals of GeoMedia Development Part I

The Font dialog will appear.

5. Change the Size: property to 8. Select OK.

By setting the font on the form, all controls placed on the form will inherittheir size and style from the form. In most cases, you will use thesame size font on all controls.

6. Display the Toolbox (View > Toolbox ). Select the label control

button.

The cursor will change to a small cross hair (+).

7. Click and drag to create a rectangular area to hold the text string. Inthe Properties window, select Caption. Key in Hello GeoMedia!

8. Select Font, and select the ... button.

The Font dialog will appear.

9. Change the Size: property to 24. Select OK.

This label will be larger for added emphasis.

10. Select the button control button in the toolbox.

The cursor will change to a small cross hair (+).

11. Click and drag to create a rectangular area for a Close button. In theProperties window, select Caption. Key in Close.

12. In the Properties window, select (Name), which is located at the topof the property list. Key in btnClose.

13. In the Properties window, select Cancel. Select True.

This property controls the dismissal of the form when the ESC key isselected.

14. You may wish to set standards for you control sizes. Most GeoMediabuttons are 350 twips by 1125 twips; if you choose these dimensions,select Height and key in 350, then select Width and key in 1125.

A twip is a screen-independent unit used to ensure that the placement andproportion of screen elements in your screen application are the sameon all display systems. A twip is a unit of screen measurement equalto 1/20 of a printer’s point. There are approximately 1440 twips to alogical inch or 567 twips to a logical centimeter (the length of ascreen item measuring one inch or one centimeter when printed).

15. Double click on the button control.

The code for frmHello will appear.

Page 137: Customizing Geomedia

Adding Commands to GeoMedia 137

16. Delete the definition for Command1_Click (located under the(General) object), since this was the logic for the default button thatwe deleted.

17. Add the code to btnClose_Click to Hide the form.

Notice the declaration Option Explicit at the top of the file, under theobject (General) and the method (Declarations). Be sure to includethis in EVERY code file (.cls, .bas, .frm). This declaration forces acompile time check for declaration of all variables. You can chooseTools > Options (under the Editor tab) and check Require VariableDeclaration to have it automatically included in all the project’s codefiles.

18. Save your project with File > Save Project. Select File > MakeHello.dll...

Save the DLL on top of the one created in Section A; reply Yes to thedialog box asking you if you want to replace the old DLL.

19. Collapse or exit Visual Basic; save the changes toGeoMediaCommand.vbp and frmHello.frm.

20. Start GeoMedia, and open the workspace you created in Section A.

21. Select Help > Hello GeoMedia.

Your command’s dialog should appear.

22. Select Close and select File > Exit to terminate the session.

Summary: In Section C, you made some basic modifications to theVisual Basic project to display your own message. You included the codeto end your command and tested it within the GeoMedia environment.

Debugging GeoMedia Commands

Debugging within the Visual Basic environment is quite powerful andproductive. In most cases, you will be able to debug your GeoMediacommands. However, there are situations in which you will not be able tosuccessfully debug. The problems are related to the discussion of in-process versus out-of-process manipulation of objects. When a commandruns normally in GeoMedia, it is in-process. However, when it is runfrom Visual Basic, it is out-of-process as the Visual Basic executable isalso running and controlling the command server. There are certainoperations on GeoMedia objects that do not function correctly whenexecuted out-of-process. The feature selection control does not functioncorrectly out-of-process. Additionally, modeless commands are very

Page 138: Customizing Geomedia

138 Fundamentals of GeoMedia Development Part I

difficult to interactively step through since the debugger interactionchanges the normal interaction with the command.

Certain general rules should be applied in the development of yourcommands for successful development and debugging. For any functionsor procedures that manipulate objects in some way such that they mightencounter errors, you should always include an error handling clause.Refer to the Err Object documentation in VB help for more information onthis construct. Additionally, you should always include Option Explicitin every file in your project. This forces method and property names aswell as argument sequences to be checked during compilation. Finally,use strong typing wherever possible rather than Object declarations.

For commands that will support interactive debugging, create yourcommand, compile it, and integrate it into the framework menus. Now,open your Visual Basic command project. Set any breakpoints needed inthe source code. Select the Run > Start (or the Start button). Now startGeoMedia. When your command is selected, you will break at thelocations you set. All normal Visual Basic debugging capabilities areavailable to you. Always continue (with the Start command) at the end ofyour functions and subroutines.

NOTE: You will have to exit GeoMedia to exit your debugging session.When you have made code corrections, select Run > Start again andrepeat the process. You do not need to rerun installusrcmd.exe, nor doyou need to reconfigure your menus. If you do not exit GeoMedia, youwill get an error when you attempt to recompile your command DLL.This is because GeoMedia is still holding a reference to the commandDLL in memory.

To avoid causing a GeoMedia crash on exit from the application, be sureand release all variables when the command is completed. Do NOT waitfor the Terminate function to be called. This function is only called onexit of the application. Releasing document and recordset variables at thispoint will result in application crashes.

If your command is not suitable for interactive debugging, you will needto use status prompt messages and/or MsgBox calls to diagnose the causeof your errors. You can use the application status bar to displayinformation messages about your command progress. This call is:

gobjGeoApp.SetStatusBar “Step 1 preparation”, 1

This technique is less intrusive than a message box. If you opt formessage box displays, you should consider writing a DebugMsgBoxfunction. For example:

Page 139: Customizing Geomedia

Adding Commands to GeoMedia 139

Global Const iCurrentSeverity = 5

Public Function DebugMsgBox( iSeverity As Integer, _

strPrompt As String ) As Long

If iSeverity >= iCurrentSeverity Then

DebugMsgBox = MsgBox strPrompt, _

vbOKOnly + vbExclamation, _

“My Command Title Error”

Else

DebugMsgBox = vbOK

End If

End Function

With this type of function, you can retain your diagnostic informationwithout continual editing of your code while controlling the extent of thedebug information displayed. To turn off diagnostics completely, you canexit the function immediately.

Lab 13b: Debugging Commands

1. Start Visual Basic.

2. Open the project for the Hello GeoMedia! lab. This file isc:\TGM\Labs\Lab13\GeoMediaCommand.vbp.

3. In the Project Window, under the GeoMediaCommand(GeoMediaCommand.vbp) folder and Class Modules subfolder,select Hello (Hello.cls) from the Project Window and select View >Code (or double-click on Hello (Hello.cls)).

4. Select the Initialize method, and set a breakpoint on the lineinitializing the command’s application object by depressing thefunction key F9 or through Debug > Toggle Breakpoint.

5. Select the Activate method, and set a breakpoint on the line whichcalls the CenterForm subroutine.

6. Start your command by selecting the Start button or the Run >Start command.

The debug window -- Immediate -- will appear.

7. Start GeoMedia, open the stored workspace, and select yourcommand.

Page 140: Customizing Geomedia

140 Fundamentals of GeoMedia Development Part I

8. Step over the initialization statements, either by depressing thefunction key F8 or through Debug > Step Into, and select Start beforeyou reach the end of the Initialize method.

9. Step into the CenterForm subroutine.

10. Step over the statements (using SHIFT+F8 or Debug > Step Over)until you are positioned at the assignment statement for iMidY.

11. In the Debug Window, key in: print iMidX.

The debugger will display the current value of iMidX.

12. Select Start to continue execution of the command.

13. Dismiss your command by depressing the Close button, exitGeoMedia, and then exit Visual Basic.

Summary: This section showed you how to establish the debugenvironment for commands and some of the basic operations available fordebugging.

Page 141: Customizing Geomedia

Adding Commands to GeoMedia 141

Command Writing Guidelines

While each organization will implement its own development standards,there are a few recommendations that are emphasized here.

• Use Option Explicit within EVERY source code file. This forcesyou to declare all variables and allows the compiler to perform typechecking for you.

• Ensure there is a Release of each object variable corresponding toevery Set. Release of an object is achieved by setting the variable toNothing. Without releasing objects, you degrade memorymanagement within the application.

• Use meaningful variable names. Some naming conventions aresuggested in the appendices.

• Include liberal comments in your source code.

• Minimize the use of global variables.

• Include an error handler in every function and subroutine that mightfail under some circumstance.

Page 142: Customizing Geomedia

142 Fundamentals of GeoMedia Development Part I

Modal CommandsModal commands typically display a dialog to the user. They are mostoften used to gather information from the user prior to processing.Although a modal command can affect other views in GeoMedia, it doesnot receive input from the user outside of the dialog.

Modal commands are much simpler to write than modeless commands.Since modal commands are not considered in the command stacking andpriority, you do not need to program for interrupts or conflicts.

For any modal command, you must implement the following methods onthe command manager interface for the command class.

Method Description

Initialize Stores the application pointer and performs any one-timeset up operations for the command.

Activate Performs the processing of a single command initiation.

Terminate Performs any command clean up, such as releasing theapplication pointer.

The wizard-generated code provides the correct defaults for the remainingmethods.

Lab 14: Custom Reports

In this example, the code you write will allow the end-user to create acustom QueryFolder for storing user-defined reports (queries). Arudimentary interface will be defined to create new queries. Thecommand will also allow the end-user to run the query to add it to theactive window. Finally, the command allows the end-user to delete thequery. The recordset creation will be written to include a spatial filter.

GeoMedia maintains three sets of queries. Each set (QueryFolder)contains Query objects that are associated with GRecordset objects.Because these sets are centrally available, GeoMedia will reuse arecordset rather than creating another one when the criteria for therecordset are the same. This reuse eliminates duplicate queries issued tothe servers, duplicate retrieval of data from the servers, and additionaloverhead for the GRecordset and dependent objects.

Page 143: Customizing Geomedia

Adding Commands to GeoMedia 143

Let’s look at the object hierarchy for the QueryFolders presented in thisdiagram.

While there is a single, unnamed QueryFolder associated with thedocument, there are three subfolders used by GeoMedia. These are:

• Features - contains query objects for recordsets created on full orspatially filtered feature tables

• Images - contains query objects for recordsets created on image tables

• Queries - contains query objects for user defined queries

Now let’s take an alternate approach to viewing these objects.

In this lab, you will create a command that supports the addition of newQueryFolder objects in the collection associated with the document’s baseQueryFolder. The object reference is:gobjGeoApp.Document.QueryFolder.QuerySubFolders(“MyFolder”)

You will also define new Query objects within the Queries collectionassociated with the new QueryFolder. You will use OriginatingPipe tocreate the recordsets, and you will apply the ConnectionFilter to therecordset if it exists.

Page 144: Customizing Geomedia

144 Fundamentals of GeoMedia Development Part I

NOTE: This project includes a .res file. This is a compiled VC++resource file. There are several different types of resources that may bedefined in the VC++ project, including bitmaps, strings, and icons.Resource files are an excellent means of externalizing language-specificdata. This is important if you are building custom components that youwill want to market internationally. Visual Basic supports a number offunctions for reading data from the binary file. There is also some run-time advantage to putting this data into a resource file. The items areloaded on demand rather than at form load time, thereby reducing memorycosts until the data is actually needed. The VC++ project and files areincluded in the resdll and include directories. We will not modify these inthis lab.

You will create a style object for displaying the results of your query. Inthe GeoMedia user interface, style width’s are assigned based on points - astandard printer’s measurement. Use the following values to determinehow to calculate the desired point sizes. Remember, the style width isbased on the paper scale of the coordinate system. If your display isgreater or smaller than the paper scale, the measurements will not matchpoint size you specified.

• One point is 1/72 of an inch (0.0139 inches).

• One point is 0.353 millimeters.

• When using gmsStyleUnitsPaper, the Width is specified inHIMETRIC units where 100 units is one millimeter.

• Using the HIMETRIC measurement, 35 units is one point (1/3 of amillimeter).

For example, if you specify 300 units in the Width property, theGeoMedia dialog will display 9 points. At your defined paper scale, theline will measure 3 mm or 1/8 inches.

Since this lab involves a very user-interactive task, it includes quite a bitof user-interface handling. Most of this handling is included in thecommand skeleton so that the lab can focus on manipulation of theGeoMedia objects.

To familiarize you with the project, this table describes the files and theircontents. Additionally, the last column indicates if you will need tomodify the file contents.

File Description Methods to modify

Page 145: Customizing Geomedia

Adding Commands to GeoMedia 145

frmCustomReports.frm Main form for the command. None

frmNewFolder.frm Form displayed to getinformation about newfolders.

None

frmNewReport.frm Form displayed to getinformation about newreports.

btnOK_Click

CustomReports.cls Wizard-generated commandclass.

None

modCustomReports.bas Wizard-generated functionsand globals.

None

modGlobals.bas Declarations of constants. None

modInitCustom.bas Performs initialization of theCustomReports form.Contains the subroutine tocreate the legend entry.

CreateLegendEntry

modNewReport.bas Performs initialization of theNewReport form. Containsa subroutine for retrievingthe connection filter data.

InitializeNewReport

CustomReports.res Compiled bitmaps, icons. None

Section A: Getting Started

1. Open the project, C:\TGM\Labs\Lab14\src\GeoMediaCommand.vbp.

The project window will appear.

2. Select File > Make CustomReports.dll... to compile the command.Accept ..\bin\CustomReports.dll as the output location. Select Yeswhen prompted to overwrite an existing DLL.

3. Open a command window, and install the command DLL. Issue thecommand - "c:\program files\geomedia\program\installusrcmd.exe"CustomReports.dll CustomReports.ini - from the bin directory of thecommand.

4. Start GeoMedia, and open (or create) a GeoWorkspace.

5. Select Tools > Customize... Select the Menus tab.

6. Select the Map Window type.

Page 146: Customizing Geomedia

146 Fundamentals of GeoMedia Development Part I

7. Select the Custom entry in the Categories list.

8. Select the Custom Reports command from the Commands list.

9. Select &Help entry on the Change what menu list.

10. Select Add.

11. Select the Data Window type.

12. Repeat steps 7 - 10.

13. Select Close.

14. Select and test the command.

Only the New button is enabled initially. Select New and the New Folderform will appear. You can test the creation and deletion of folderswith the code skeleton. Select Close on the Custom Reports formafter you have tested adding and deleting folders. The command willtest for duplication of folder names as well.

15. Exit GeoMedia.

Summary: In Section A, you used the InstallUsrCmd.exe program tomake the custom command available within your GeoMedia environment.This is necessary since you did not run the Command Wizard to create theVisual Basic project. You associated the command to the menus and youcan test some of the basic operations including the creation and deletion offolders.

Connections and Metadata

This section of the lab accesses the connection objects and uses themetadata service to get a list of tables from the warehouse. TheGeoMedia connection object is a generalized mechanism for accessingdifferent warehouses. Each document can have several connections. Theconnections collection is the list manager for the warehouses -- GDOservers.

Metadata is data about data. That is, metadata describes thecharacteristics of your data instances. The feature class definition is aform of metadata. GeoMedia also supports additional metadatainformation that is not part of the GDO table and field definitions. Thecreation, maintenance, and access to the metadata are controlled throughthe metadata service. However, since the metadata is stored in thedatabase for read/write servers, you could maintain this information

Page 147: Customizing Geomedia

Adding Commands to GeoMedia 147

without using the service. In this lab, you will use the metadata service todetermine the primary geometry field. GeoMedia uses the primary fieldextensively to know which gdbSpatial field to use for analysis.

Section B: Initializing the Report Form

1. Select modNewReport under the Modules folder in the ProjectWindow and select View > Code.

2. Select the (General) object and the InitializeNewReport procedure.

3. Implement the logic to add all of the connection names to thecombobox and select (highlight) the first connection from the list.

You will need to iterate over the Document’s Connections collection.Pass the ConnectionName from the connection object as theargument to the AddItem method. Be sure that the connection is openbefore adding it to the list. Setting the ListIndex property to 0 willhighlight the first item in the list.

4. Now for the first connection, display all of the feature tables in thelist. Use the MetadataService to get the list.

Retrieve the first connection object and hold it in the objConn variable.The ProgID for the service is GMService.MetadataService forobjMD. Set the Connection property to the first connection. Use theGetTables method passing 0 and vList as the arguments. Again, useAddItem on the list control to display the names. The vList variablewill actually contain an array of strings. The last entry is the emptystring. UBound and LBound are built-in Visual Basic functions todetermine the number of elements in an array.

5. Save and compile your command.

6. Start GeoMedia, open (or create) a workspace, and test yourcommand.

Iteratively test your command until you are successfully able to displaythe populated New Report form.

7. Exit GeoMedia.

8. Return to the Visual Basic project. Select frmNewReport under theForms folder in the Project Window, and select View > Code.

9. Select the cboConnections object and the Click procedure.

10. Review the code in this section. It is very similar to the section youjust wrote. This will update the table list when the end-user changesthe connection.

Page 148: Customizing Geomedia

148 Fundamentals of GeoMedia Development Part I

Summary: In Section B, you have processed the Connections collectionto populate the list of available connections for only the open connections.You have also used the MetadataService to retrieve the list of features.Although this command supports queries on any feature, you can filter thelist of tables based on geometry type by using the mask argument to theGetTables method.

Filtering Queries and Geometry Transformations

In many cases, you will be accessing very large data sets. Although youneed the ability to view all data simultaneously, you only need to view ageographic subset of that data. GeoMedia and GDO achieve this byproviding a spatial filtering capability. A filter is a geometry that definesan area within the data model. When you create a recordset, you canspecify what geometry to use for filtering, how to compare this geometryto the data in the server (inside, overlap), and which data (field) tocompare against.

As we discussed briefly as we reviewed pipes in GeoMedia, pipes addvalue to GeoMedia through client-side extensions where GeoMedia is theclient. Section C of the lab will use the Name extension to create thequery object. Section D of the lab will use the ExtendedPropertySetextension to retrieve metadata information.

GeoMedia can display geographic data within a number of differentcoordinate systems. Each coordinate system will display the data in aslightly different manner. In some cases, the visible characteristics of thedata may change radically. As a GeoMedia programmer, you need to beaware of when you need to perform transformations of data and values.

Recall that there is a coordinate system associated with the document.This may or may not be the same as the warehouse’s coordinate system.In this case, GeoMedia transforms the data from the server to arepresentation appropriate for the document’s display. Likewise, whenyou digitize in GeoMedia, data is collected in the coordinate system of thedocument. You will need to transform it to the system of the server forstorage of geometry data.

Section C: Creating and Saving the Report

1. Return to the Visual Basic project. Select frmNewReport in theProject Window, and select View > Code.

Page 149: Customizing Geomedia

Adding Commands to GeoMedia 149

2. Select the btnOK object, and select the Click procedure.

3. Get the selected connection, and create an OriginatingPipe object.

Populate the temporary variable, objConn, with the selected connection.Create the OriginatingPipe object and populate the Table and Filterproperties from the values in lstTables and txtFilter. TheOriginatingPipe object is created with the CreateOriginatingPipemethod on the connection object.

4. Call the subroutine DetermineFilter.

This subroutine has already been written. The function signature is CallDetermineFilter( chkFilter.Value, objConn, objOP).. It uses thevalue of the chkFilter control to determine whether or not to assignthe filter to the OriginatingPipe.

5. Retrieve the new recordset from the OriginatingPipe object.

Use the objRS variable to hold the OutputRecordset from objOP.

6. Retrieve the Name extension from the recordset. This returns a queryobject. Populate the query object.

Use the GetExtension method requesting the “Name” object. Set the.Name and .Description properties.

7. Append the query object to the appropriate query subfolder.

Remember that strQueryFolder holds the name of the subfolder that willcontain this query. Use the Append method on the Queries collection.

8. Save and compile your command.

9. Start GeoMedia and test your command. Select Legend > AddFeature Class… Add the States feature. Select Warehouse >Connection Filter… Select Define…

You are prompted to draw a rectangle around some area of data. Doubleclick the mouse to return to the form.

10. Select Close. Select Warehouse > Edit Connection… Click in theConnection Filter Name field. Select a filter for this connection.Select Close. Save your workspace.

11. Test your command.

Test your command until you are successfully able to define a report.Specify an invalid attribute filter (where clause) to ensure that you getan error message.

12. Exit GeoMedia.

13. Return to the Visual Basic project. Select modNewReport under the

Page 150: Customizing Geomedia

150 Fundamentals of GeoMedia Development Part I

Modules folder in the Project Window, and select View > Code.

14. Select the DetermineFilter procedure.

15. Review the code used to apply the spatial filter to the pipe.

The metadata service is used to find the primary geometry field. Sincethe filter is defined in the coordinate system of the document, we willhave to transform it to the server system. We set up thetransformation first. If there is a filter associated with the connectionand the control was selected to apply the filter, then create a copy ofthe filter geometry, convert it to the server’s coordinate system, andassign the result to the originating pipe SpatialFilter property.

Summary: In Section C, you created an OriginatingPipe object based onthe user’s selection of a connection and table and any filter (attribute orspatial) specification. The OriginatingPipe produces an output recordset(internally using GDatabase.OpenRecordset) which provides additionalcapabilities. These capabilities include support for notification of datachanges, access to the metadata for the table, and persistence of therequest within the workspace through the Query object. The sectionalso saves the recordset and query object in the appropriate QueryFolderobject. You can build your own folder hierarchy to manage predefinedqueries in your application. Finally, the command includes the logic toapply the connection filter to restrict the query to a particular geographicarea. You accessed the SpatialFilter object associated with theConnection and converted this geometry to the coordinate systemassociated with the data warehouse.

Displaying Data

As you know, all data is displayed in the map window through the legendentries. In order to visualize and distinguish the different features in yourmodel, you need to assign different styles to each legend entry. This isachieved with the use of one of the style objects. You will create a styleobject and associate it with the legend entry for displaying the results ofyour query. In the GeoMedia user interface, style width’s are assignedbased on points – a standard printer’s measurement. The following valueshelp you determine how to calculate the desired point sizes. Remember,the style width is based on the paper scale of the coordinate system. Ifyour display is greater or smaller than the paper scale, the measurementswill not match the point size you specified.

• One point is 1/72 of an inch (0.0139 inches).

Page 151: Customizing Geomedia

Adding Commands to GeoMedia 151

• One point is 0.353 millimeters.

• When using gmsStyleUnitsPaper orgmsStyleUnitsPaperAsNonscaling, the Width is specified inHIMETRIC units, where 100 units is one millimeter.

• Using the HIMETRIC measurement, 35 units is one point (1/3 of amillimeter).

For example, if you specify 300 units in the Width property, theGeoMedia dialog will display 9 points. At your defined paper scale, theline will measure 3 mm, or 1/8 inches. If you specify gmsStyleUnitsView,the width is the number of pixels. When usinggmsStyleUnitsPaperAsNonscaling, the behavior is the same asgmsStyleUnitsView, but the value is calculated from the point size or theHIMETRIC values. Hence, eighteen points will appear as one quarter(1/4) inch on the screen and will disregard the view extents and thecoordinate system’s paper scale value.

Section D: Running Queries

1. Open the command project. Select frmCustomReports in theProject Window, and select View > Code.

2. Select the btnRun object, and select the Click procedure.

Review the code to add the recordset to the active data view.

3. Select frmCustomReports in the Project Window, and select View> Code.

4. Select the btnRun object, and select the Click procedure.

5. Review the logic to create a legend entry. Also review the logic todisplay the recordset on the map view.

In this method, the CreateLegendEntry subroutine is called and thelegend entry appended to the map view’s legend. Once the legendentry is appended, you will call ValidateSource and LoadData to tellGeoMedia to display the data.

6. Select modInitializeCustom in the Project Window, and selectView > Code.

7. Select the CreateLegendEntry procedure.

8. Implement the logic to create a legend entry and style object. Assignthe style to the legend entry.

Create a linear style object. This style can be used to symbolize all datatypes. Create the legend entry and assign the style to it. Use the

Page 152: Customizing Geomedia

152 Fundamentals of GeoMedia Development Part I

ProgID GeoMedia.RecordLegendEntry to create the legend entryand GeoMedia.LinearStyle, to create the style. UsegmsStyleUnitsPaper for StyleUnits,gmsLinearModeShowBackground for Mode, vbRed for Color, and300 for Width. Set the Title of the legend entry to the input string.Set the Subtitle to the string “Custom Report.”

Extra Credit: Create a default style based on the geometry type.Additionally, rather than defaulting to red, create a cyclic defaultingscheme for the 16 basic colors (0 - 15).

9. Find the primary geometry field for the recordset. Assign this value tothe legend entry.

Use the ExtendedPropertySet extension on the recordset to find thisinformation. Retrieve the extension object with the GetExtensionmethod. From this object, use the GetValue method, requesting thePrimaryGeometryFieldName.

10. Create a transform pipe object to transform the primary geometry inthe recordset. Associate the recordset with the legend entry.

The ProgID for the pipe is GeoMedia.CSSTransformPipe. You will needto populate the InputRecordset with the subroutine’s recordsetargument, the CoordSystemsMgr with the document’s coordinatesystem manager, the InputGeometryFieldName with the nameretrieved in step 9, and the OutputCSGUID with the GUID of theCoordSystem object within the Document.CoordSystemsMgr. Assignthe OutputRecordset to the legend entry.

11. Save and compile your command.

12. Start GeoMedia and test your command.

Test your command until you are successfully able to display therecordset in the map view. Test both an empty legend and one withentries. The new entry should display at the top.

13. Exit GeoMedia.

Summary: In Section D, you implemented logic to display the recordsetin the map view. A style object is created and associated with the legendentry. The GetExtension method is used to access the metadata to findthe primary spatial geometry field. Finally, you transformed the recordsetfrom the coordinate system of the server or warehouse to that of the mapview or client.

Page 153: Customizing Geomedia

Adding Commands to GeoMedia 153

Section E: Editing Queries (Extra Credit)

Extend the capabilities of this command to change the criteria of the queryand to refresh any existing displays of the data.

Page 154: Customizing Geomedia

154 Fundamentals of GeoMedia Development Part I

Modeless CommandsModeless commands are the second type of command available inGeoMedia. Modeless commands differ from modal commands in oneimportant aspect: they do not need to be terminated before you cancontinue working with the rest of the application. While modalcommands take over the application until the dialog is closed and thecommand is completed, modeless commands allow you to shift the focusfrom a dialog or window to a secondary window -- or even to anothercommand. Unlike modal commands, modeless commands remain activeuntil they receive an event that tells them to deactivate.

Modeless commands are not as common as modal commands and are a bitmore complex to develop, but there are situations where they are veryuseful. The Find command in Microsoft Word or Visual Basic is anexample of a modeless command that uses a dialog to collect the user’ssearch criteria, performs the find operation, and allows the user to movearound in the document while the Find command is still active. As aGeoMedia custom command writer, you will find that modelesscommands can be employed to handle a variety of scenarios which wouldbe cumbersome or even impossible to do with modal commands alone.

The advantage of using a modeless command when developing a customcommand in GeoMedia is that it allows user interaction with one of theapplication windows in the middle of the command. For example, youmight want to create a fancy Print Area command that has the user definethe boundary of the target area in a map view and then modify the extentsdynamically, all the while demonstrating what the new settings are in amodeless dialog.

The disadvantages of using a modeless command are that much greatercare must be taken to handle all scenarios and to cleanly deactivate thecommand at the appropriate time. Additionally, you will recall thatVisual Basic OLE servers do not support modeless dialogs. As such, youmust keep this limitation in mind when developing modeless customcommands. If a command uses a modeless dialog that requires user inputon the form (e.g., key-in field), the dialog must be written in VC++.

Types of Modeless Commands

The GeoMedia command wizard creates a VB project with several files init that serve as a skeleton for a custom modeless command. In the ViewListener Command Type step of the command wizard, you are asked to

Page 155: Customizing Geomedia

Adding Commands to GeoMedia 155

select what type of modeless command you want to create. Recall thefour types of modeless commands:

• Select commands -- (e.g., feature selection) only one command fromthis group may be listening to map views at a time. A new listenerfrom this group will terminate any existing listener if termination isallowed by the old listener.

• Placement / Edit commands -- (e.g., place new feature / modify featuregeometry) - only one command from this group may be listening tomap views at a time. A new listener from this group will terminateany existing listener if termination is allowed by the old listener. Thisselection will suspend any command in the Selection group.

• View change / Define sub-view commands -- (e.g., zoom in / printarea or snapshot) - only one command from this group may belistening at a time. A new listener in this group will cause anycommand in the Selection or Placement/Edit groups to temporarilystop listening to events until the command in this group completes.

• Tracker commands -- (e.g., scale bar, north arrow, mouse data pointreadout, etc.) - any number of these commands may be listening at aview. Listeners in this group are not affected by the other groups.

Modeless Command Class Methods

The life cycle of a modeless command is cleanly divided into two phases:set up (modal) phase and listening phase. During the setup phase, thecommand may create new modeless windows and/or start listening toevents at existing windows; then the command returns control to theapplication. After the overall application is released to respond to events,the command is still active and moves into the second phase, where itlistens for events at the windows that it created or attached to until anevent is received that signals it to end.

One of the generated files from the GeoMedia command wizard is acommand class module (.cls file) that consists of the methods listedbelow. Following is a brief summary of these methods:

• Initialize - This is the first method that is called after the command isselected from the menu. This routine is called only once no matterhow many times the command is re-executed. In it, the EventServerobject is created and the form with the EventControl on it is loaded.You can add any code to this method that you want to execute onlythe first time the command is run.

• Activate - This method is executed each time the command is run andis the core of the command “setup” phase mentioned above. First the

Page 156: Customizing Geomedia

156 Fundamentals of GeoMedia Development Part I

IsDone property is set to False; and if your command has an initialmodal dialog that is used to gather user input, it will be displayedhere.

After this dialog is dismissed, the command is registered with the viewlisteners manager. This component enforces the command stackingrules and determines if the command will terminate when anothercommand is started (see previous section). Also in this routine, theEventControl is attached to the EventServer for each map view that itwants to receive events from, registering itself as a listener to the mapview. Each view that is being listened to is added to a privatecollection that is used later.

In this routine you will add any initialization code for the modelesscommand that you need to run each time the command is executed.

• CanActivate - All command servers that are custom map viewlisteners must implement this method. The method is called beforethe Activate method. A custom modeless command is one that is notcategorized in one of the four types of modeless commands describedin the previous section. Normally this simply returns a status of True.

• Deactivate - This is called when a modeless command receives anevent to stop execution. At this time, the IsDone property is set toTrue, all map view listeners are disconnected from the EventServer,and each map view is removed from internal collection. In thismethod you will add code to clear memory of any objects used in theActivate method or objects from the form module.

• AddView - This method is used to register a map view so that youmay begin to listen to events received by the command using theEventControl.

• RemoveView - This method does the inverse of the AddView methodby unregistering a view from the event-listening process.

• IgnoreEvents - If another command is started in the middle of thecurrent modeless command, then this method will be called so that themap view will be temporarily disconnected from the EventControl.This allows the events to be handled correctly by the interruptingcommand.

• RestoreEvents - After an interrupting command is completed, the mapview will be reattached to the EventControl, and it will proceed againlistening to events in that view.

• Terminate - This is called when the command manager is shuttingdown, normally when you select the File > Exit command. As aresult, this method is executed only once in a command life cycle. At

Page 157: Customizing Geomedia

Adding Commands to GeoMedia 157

this time, you will add any extra memory cleanup, especially ofobjects created in the Initialize method.

Lab 15: Magnify View

In this exercise, you will create a modeless command that displays a smallMagnify window with the contents of a portion of the active map windowzoomed in at a smaller scale so as to look bigger. A small square is drawnin the map view centered around the cursor showing the extent of theMagnify window. You are able to move the mouse around the active mapwindow, and the contents of the Magnify window will changeaccordingly. Likewise, you are able to execute any view change command(e.g., zoom in) and the Magnify window will respond appropriately.

The command can be terminated by one of four ways:

• Press the ESC key at any time.

• Cancel the Magnify window by pressing the “x” in the upper rightcorner of the Magnify window.

• Move the cursor into the Magnify window map view area.

• Exit the application.

The GeoMedia components used in this lab are:

Components Type Library

MapView MapviewLib

GeometryEditService PClient

PointGeometry PBasic

RectangleGeometry PBasic

LinearStyle PView

EventControl GMEventControlLib

The command was created with the wizard as a modeless, map viewlistener in the tracker group. The enabling conditions require an activemap view and open connection.

One of the related objects used in the form module of Lab 15 is the

Page 158: Customizing Geomedia

158 Fundamentals of GeoMedia Development Part I

MapViewDispatch pointer, which is used as a variable passed into theevent control methods. It refers to the IDispatch interface on the mapview object. As you may recall from the Automation Overviewdiscussion, interfaces are the means by which you communicate with anobject; and an object may have one or more interface pointers. TheIDispatch interface is a specific interface that all automated objectssupport which allows you to access all the automation methods of thatobject. The IDispatch interface communicates all the public methods andproperties of the object to the automation client.

Another object referenced in this lab is the CommandClass. Eachcommand in GeoMedia is a separate OLE automation server whichsupports one interface - the command interface. The CommandClasspointer refers to this interface, which in this case consists of the methodsdefined in the Magnify.cls file. The CommandClass object is used in thislab so that the methods in the class module can be called from the formmodule.

To familiarize you with the project, this table describes the files and theircontents. Additionally, the last column indicates if you will need tomodify the file contents.

File Description Methods to modify

frmMagnify.frm Main form for the command

(it is hidden)

Form_Load

Form_Unload

EventControl1_KeyUp

EventControl1_MouseMove

SetCmdCls

SetMapViewDispatch

UnsetMapViewDispatch

ResetGeometryEditService

Magnify.cls Wizard generated commandclass

Initialize

Activate

Deactivate

RemoveView

Terminate

modMagnify.bas Wizard generated functionsand globals

None

Page 159: Customizing Geomedia

Adding Commands to GeoMedia 159

In addition to the modeless command class methods discussed above, youwill need to add code to several subroutines in the form module in order tocomplete this lab. There are two routines that are triggered when eventsare received by the EventControl. In the frmMagnify’sEventControl1_KeyUp subroutine you will write code to handle the casewhen the user hits the Esc key. Likewise, in the frmMagnify’sEventControl1_ MouseMove routine you will handle the case when theuser moves the mouse around the map view. The frmMagnify’sForm_Load and frmMagnify.Form_Unload subroutines are executedwhen the command is initialized and terminated, respectively.

Using the generated source code from the command wizard as a startingpoint for developing this command, you only need to add a limitedamount of code in order to complete it. However, care should be taken tocarefully remove any allocated memory by setting any object variable tonothing after you are done using the object. As is true with other customcommand development, failing to clear memory in a modeless commandcan lead to strange behavior and unexpected crashes.

Section A: Creating the Magnify Window

1. Start Visual Basic, opening the command skeleton for the Magnifymodeless command.

The project is located in C:\TGM\Labs\Lab15\src.

2. Select View > Code on the Magnify.cls file under the Class Modulesfolder in the Project Window, and select the Activate method.

3. Create a new window.

You will need to use the NewMapWindow method of the Documentobject. The newly created window will become the ActiveWindow.

4. Give the new window the title “Magnify.”

Use the Caption property on the map (Active) window. This caption willbe used to identify this window in several places later. The constantMAGNIFY_CAPTION is available for use.

5. The command already sets the dimensions of the Magnify window tobe a square window that is 1/3 the size of the smallest dimension ofthe application. The application’s Height and Width properties areused in the calculation and the resulting values are used to set theHeight and Width of the Magnify window.

6. Position the Magnify window in the lower right of the application.

Page 160: Customizing Geomedia

160 Fundamentals of GeoMedia Development Part I

Set the Top and Left properties of the Magnify window. Remember thatthese two properties are relative to the application window (not thescreen) so that 0,0 is the upper-left corner of the application.

You will have to account for the statusbar height (subtracting it from theApplication.Height) in the calculation for the Top as well as theapplication frame’s width (subtracting it from Application.Width) inthe Left calculation. Use the variables, lStatusbarHeight andlFrameWidth, in the calculation.

7. Exit the command if all the views that the MapViewListener islistening to have been removed.

At the end of the RemoveView subroutine, there is a check to see if all theviews have been removed (Count=0). If they have, then add a call toDeactivate in the If - Then clause.

8. Save the project and compile the custom command. Select File >Make Magnify.dll...

9. Register the command. This is necessary since you did not use theCommand Wizard to create the initial command on this machine.

You need to open a command window and move to thec:\TGM\Labs\Lab15\bin directory. Execute the command:

"c:\Program Files\GeoMedia\Program\Installusrcmd.exe" Magnify.dllMagnify.ini Start GeoMedia and add the new Magnify command tothe menus using Tools > Customize…

Follow the steps in Lab 13 to add a custom command to GeoMedia.

10. Run the Magnify command. Confirm that the Magnify windowdisplays in the lower right corner of the application as a squarewindow with the correct caption.

If necessary, modify the calculation for the Top, Left, Height, orWidth properties of the Magnify window, and rerun the commanduntil the new window is sized and position correctly.

Note: Because we have not added code to make the commandreentrant, you may only be able to run it once - the second invocationof the Magnify command may cause a crash.

Page 161: Customizing Geomedia

Adding Commands to GeoMedia 161

Summary: In Section A, in addition to installing the command skeleton,you created a new map window and set its Caption, Height, and Widthproperties. You also established the position of the window in the lowerright corner of the application framework. You successfully associatedthe command to a GeoMedia menu. When you select your command, anew, empty map window will appear. Finally, you triggered the commandto Deactivate when all the views were closed that it was listening to.

Section B: Populating the Magnify Window

1. Return to Visual Basic, and edit the Activate method in Magnify.cls.

2. Create a copy of the legend of the active map view.

Use the Copy method on the Legend object. It is probably easiest to dothis before the Magnify window is created and while the activewindow is still the map window. The active window contains thefeatures we want to magnify. Use the variable objMagnifyLegend tohold the copy.

3. The variable, objMagnifyMapView, has been declared. It will beused throughout the exercise and contains the Magnify map view.

4. Set the legend in the Magnify map view to be the same as the activemap window.

Assign the object, objMagnifyLegend, from Step 2 as the Magnify legend.Note: This must be done after the Magnify window has been created.Use the variable declared in the Step 3 with the Legend property.

5. The command sets the Visible property of the legend to False. Thisturns off the display of the legend in the Magnify window.

6. Loop through the legend entries in the Magnify legend, and load eachentry into the Magnify window.

Create a For loop, and call the LoadData method on each entry.

7. Modify each legend entry in the Magnify window so that the graphicfeatures cannot be selected.

Set the Locatable property on each legend entry in the same loop as Step6.

8. Close the Magnify window.

At the end of the Deactivate method use the Close method on the Magnifymap window. Since the variable objMagnifyView contains a pointerto the mapview control, you will need to traverse to the window

Page 162: Customizing Geomedia

162 Fundamentals of GeoMedia Development Part I

through the Parent property.

9. Compile the command.

10. Test the Magnify command in GeoMedia.

The Magnify window will still be empty at this point. Execute a mouseright click in the Magnify window and check the Legend option. Thelegend should display with the same legend entries as the map view(the one that was active when the Magnify command was started).The legend entries should be loaded, and the legend should lookidentical to the map view legend. If you have not released all of theglobal variables, the command may crash on exit.

Summary: In Section B, you created a copy of the legend from the activemap view and associated it with the Magnify window. You implementedthe logic to display the geometry data with the legend entry LoadDatamethod. You also indicated that none of the data in the Magnify windowcould be located with the mouse by setting the Locatable property toFalse for each legend entry. Finally, you closed the Magnify window.

Section C: Drawing a Square Cursor and Tracking MouseEvents

1. In the Visual Basic project again, use View > Code to edit thefrmMagnify.frm file.

2. The command defines four variables at the top of the form modulethat correspond to:

• a GeometryEditService object (objGeomEditSrvc)

• a RectangleGeometry object (objRectangle)

• a LinearStyle object (objRectangleStyle)

• a PointGeometry object (objPoint)

3. Create the objects in the Form_Load subroutine using theApp.CreateService method.

The App.CreateService directive is used rather than the CreateObjectmethod to instantiate each of these objects because we will be doingsome debugging and we want to create all of the objects in the sameprocess space. See the article in the Programming Caveats section ofthe Appendix for more information on this topic.

Page 163: Customizing Geomedia

Adding Commands to GeoMedia 163

4. Initialize the style of the rectangle to black with a weight of 3.

Do this also in the Form_ Load routine immediately after creating therectangle object. Use the LinearStyle object and set the BackColorand BackWidth properties. Black is defined as a color having a valueof 0.

5. Set the map view on the GeometryEditService object. Use the publicsubroutine (called SetMapViewDispatch) that has one argumentwhich is a map view dispatch pointer.

In this subroutine you will assign the subroutine’s argument holding themap dispatch pointer to the MapView property of theGeometryEditService object.

6. Add code so that each time the command is run, theGeometryEditService has the correct MapView property.

You will now edit the Activate method in the Magnify.cls file and call thesubroutine created in Step 5. Don’t forget to pass the map viewdispatch pointer of the right window (the original active map windowwhen the Magnify command was called).

7. Before drawing the box around the cursor, you need to make sure noother temporary graphics are displayed.

In the form module, edit the MouseMove method of the EventControl.Use the RemoveAllGeometries method on the GeometryEditServiceobject to clear it.

8. The command retrieves the Height and Width of the map windowand stores them in the variables: lx2Win and ly2Win. You will usethese values to calculate the size of the square round the cursor.

9. The command next determines the dimension of the window in worldcoordinates. This calculation converts window coordinates (0,0 beingthe top/left of the window) into world coordinates using theWindowToWorld method on the map view. By determining the sizein world coordinates, you avoid the discrepancies that may occur withdifferent coordinate systems. The smaller dimension is chosen andstored in the variable dblMinWidth. It is important that the width bein world coordinates since you want to use this to determine theextents of the magnify window.

10. Calculate the height and width of the rectangle around the cursor.

Divide the value from the previous step, dblMinWidth, by 10. Assign thisto the Height and Width of the objRectangle.

11. Calculate the origin of the box that will be drawn around the cursor.

Set the origin (use the temporary variable objPoint) of the

Page 164: Customizing Geomedia

164 Fundamentals of GeoMedia Development Part I

RectangleGeometry object (X, Y, Z properties) from Step 2 equal tothe worldX, worldY, and worldZ arguments that are passed to thesubroutine. Modify the values to offset them by 1/2 the width of thesquare so the cursor point is directly in the middle of the box.

12. Draw the box around the cursor.

Use the AppendGeometry method on the GeometryEditService object.You need to pass the rectangle (objRectangle) and the style(objRectangleStyle) objects.

13. Complete the subroutine, ResetGeometryEditService, to empty theGeometryEditService object before exiting.

At the end of frmMagnify module, complete the public subroutine thatremoves all geometries from the GeometryEditService object andsets the MapView property to nothing.

14. Call the subroutine, ResetGeometryEditService, in the Deactivatemethod so that it is executed right before the command exits.

15. Compile the project. and test the Magnify command in GeoMedia.

You should see a dark, square block around the cursor that trackswith any mouse movement and repaints cleanly in the map view. If youhave not released all of the global variables, the command may crashon exit.

Summary: In Section C, you created objects to manage the boxpositioned around the cursor in the view you are magnifying. Thisincluded the GeometryEditService for the dynamic display of thegeometry, the RectangleGeometry, and the LinearStyle for symbolizingthe rectangle. We used the Dispatch property of the map view toestablish the communication link between the view and theGeometryEditService. You managed the size and position of the boxaround the cursor in the MouseMove event. The Height and Width ofthe box (RectangleGeometry) is determined by the size of the windowwhile the position is determined by the cursor location.

Section D: Magnifying Features

1. Return to the VB project. The variable, objMagnifyViewDispatch,at the top of the frmMagnify module represents the map viewdispatch of the Magnify window.

Page 165: Customizing Geomedia

Adding Commands to GeoMedia 165

2. Get the map view dispatch pointer of the Magnify window.

Update the subroutine, SetMapViewDispatch, logic to retrieve thispointer. Create a loop that cycles through the collection of windowsin the application, and look for the one that has the caption“ Magnify.” Use the MAGNIFY_CAPTION constant. Once it isfound then assign its dispatch pointer to the variable defined above instep 1.

Remember that we will use the map view’s Dispatch property to establishcommunication between the map view and other controls.

3. Now you will calculate the extents of the area to magnify. Get theupper left and lower right corners of the RectangleGeometry objectaround the cursor.

In the MouseMove method for the EventControl in frmMagnify, calculatethe six values that correspond to the X, Y, Z coordinates of the twoopposite corners in the square box (upper left and lower right). TheOrigin of the rectangle is the upper left.

4. Draw the graphical features displayed inside the box of the active mapview in the Magnify view in a magnified scale.

Use the ZoomArea method of the Magnify map view dispatch object, andpass it the six points calculated in the previous step.

5. Update the Magnify window.

Call the Refresh method on the Magnify map view.

6. The command includes the appropriate logic to release the map view’sDispatch pointer in the UnsetMapViewDispatch subroutine.

7. Call the cleanup routine (UnsetMapViewDispatch) from theDeactivate method.

Add a line at the end of the Deactivate method of the command class(Magnify.cls) that calls the subroutine created in the previous step.

8. Compile the project.

9. Test the Magnify command in GeoMedia.

You should now see the features from the active map view display inthe Magnify window, only much larger. Move the mouse and differentmagnified elements will display. If you have not released all of theglobal variables, the command may crash on exit.

Page 166: Customizing Geomedia

166 Fundamentals of GeoMedia Development Part I

Summary: In Section D, you utilized the ZoomArea method of the mapview to set the viewing location for the magnify window. The area isdefined by the upper left and lower right corners of the box in the windowyou are magnifying. Logic is also added to release the pointer to the mapview dispatch pointer to ensure correct reference counting.

Section E: Exiting the Command Cleanly

1. Return to the VB project. The command includes a variable in thefrmMagnify module that represents a pointer to the command class --objCmdCls. This will be used to call methods on the command.

2. Assign the command class pointer.

Complete the subroutine, SetCmdCls, in frmMagnify that takes as anargument an Object pointer and assign this to the variable defined inthe previous step.

3. Let the form module know at the start of the command the address ofthe command class.

At the end of the Initialize method of the Magnify.cls file, add a line thatcalls the subroutine, SetCmdCls. Remember, you can pass thevariable Me as the command class pointer.

4. So that the command may be terminated, you will add code to checkto see if the user pressed the “Esc” key.

In the form module, open up the KeyUp method for the EventControl andadd a test for the Esc key (KeyCode = 27). You may also usevbKeyEscape to compare the value. Call the Deactivate method onthe command class object assigned in Step 2 above.

5. Clean up the command class pointer on exit.

Set the variable defined in the first step of this section, objCmdCls, toNothing in the Form_Unload method of the form module.

6. Add the Magnify window to the windows that the EventControl islistening to. This is important, because you will not capture the “Esc“keyin unless you are listening to that window.

In the Activate method of the command class, add a call to AddView andpass it the ActiveWindow, which is now the Magnify window.Remember that AddView is a method on the command class.

7. Add a statusbar message to indicate that ESC is a valid key-in to

Page 167: Customizing Geomedia

Adding Commands to GeoMedia 167

terminate the command.

Modify the Activate method of the command class and use theSetStatusBar method of the application to indicate in the second panethat “ESC” is a way to kill the command.

8. End the Magnify command if you move the cursor into the Magnifywindow.

An error handler section has been defined in the MouseMove method ofthe EventControl before the call to ZoomArea. If there is a problemwith the ZoomArea, then it will fall through to the error handler. Adda call to the Deactivate method of the command class. Whenever youmove the cursor into the Magnify view, an error will be raised byZoomArea and the command will end.

Alternatively, a more deterministic way to handle this situation would beto calculate at the top of the MouseMove method if the cursor is inthe Magnify window by comparing the cursor x,y with the windowcoordinates and from there calling Deactivate if it falls in the window.

9. End the command if you close the Magnify window by selecting the“x” button in the top right corner of the Magnify window. Thecommand defines a private variable in Magnify.cls that is a flagindicating whether or not the window is destroyed by the selection ofthe X on the window bar. This boolean variable, bKillMagWin, willbe used in later steps.

10. Initialize the kill window flag.

Set the variable, bKillMagWin, to False in the Activate method.

1. Set the kill window flag to True if the Magnify window is closed withthe “x” button.

The RemoveView method will be called when the “x” button is selectedand the MapViewListener is removed for that window. Inside the Forloop of this routine add an If statement that checks to see if theMagnify window is the one being removed. You can do this bylooking at the window caption. If it matches, then set the kill flag toTrue.

2. Deactivate the command if the kill window flag is True. This isaccomplished at the end of the RemoveView routine. The Ifstatement checks to see if the kill window flag is True. If it is, then itcalls Deactivate.

3. Do not issue the Close command to the Magnify window if it hasalready been manually closed. In the Deactivate method, this isaccomplished with an If statement before Close method is called.

Page 168: Customizing Geomedia

168 Fundamentals of GeoMedia Development Part I

4. Compile the command.

5. Test the Magnify command in GeoMedia.

You should now have a fully functional, modeless Magnify command.Finally, the command will not cause the application to crash on exit.

Summary: In Section E, you established a reference to the commandclass. This provides access to the command from functions andsubroutines in the DLL but not within the class module. You trapped theESC key to Deactivate the command. The application’s status bar isupdated with a prompt. You added logic to terminate the command whenthe Magnify window is closed.

Page 169: Customizing Geomedia

Adding Commands to GeoMedia 169

SummaryThe overall objective of this section was to familiarize you with thecreation of GeoMedia commands. To this end, you learned the purposeand use of the Command Wizard. You now understand the types ofGeoMedia commands that may be created:

• View change / Subview definition

• Placement / Editing

• Selection

• Tracker

You should be familiar with the command stacking capabilities that allowcommands within different classes to interrupt or pause other commands.You have also successfully implemented three commands. The first oneexercised the command manager and the process of establishing a menuitem for the command. The second command utilized the followingobjects:

• QueryFolder

• Query

• OriginatingPipe

• SpatialFilter

• LinearStyle

• RecordLegendEntry

• GeometryStorageService

• ServerTransService

• CSSTransformPipe

• ExtendedPropertySet

• MetadataService

Finally, the third command utilized the following objects:

• EventControl, EventServer

• GeometryEditService

• RectangleGeometry, PointGeometry

Page 170: Customizing Geomedia

170 Fundamentals of GeoMedia Development Part I

You practiced these techniques in the lab:

• Receiving events

• Terminating modeless commands

• Monitoring selective views

• Temporary geometry construction

• Legend copying

• Creating persistable recordsets

• Manipulating the query folders

• Associating a spatial filter with a recordset

• Coordinate transformation operations

• Retrieving metadata information

• Displaying data in the map view and data view

The next section will utilize the GeoMedia objects in a customapplication. Custom applications are the second approach to GeoMediacustomization.

Page 171: Customizing Geomedia

Adding Commands to GeoMedia 171

Can You Answer These Questions?1. What two types of commands are available in GeoMedia?

2. What restrictions exist for modeless commands?

3. What is the significance of CreateService?

4. What are the two types of collections? Provide a GeoMedia exampleof each.

5. How do you register a command?

6. How do you remove a command?

7. What is a connection filter? Give an example of its benefit and usage.

8. What two components are used in conjunction withCoordSystemsMgr to transform a recordset from the server projectionto the map view’s projection?

9. What is wrong with this?

Set objQuery =gobjGeoApp.QueryFolder.QuerySubFolder(3).Query(4)

Page 172: Customizing Geomedia

172 Fundamentals of GeoMedia Development Part I

Page 173: Customizing Geomedia

173

Appendices

Document Conventions

Keywords

Italics are used in the workshop text to indicate special objects orkeywords.

Definitions

IMPORTANT: Highlights important notes and definitions.

Code Fragments

Indicates a fragment of code

Step by Step Instructions

1. Step one...

System prompts and expected results are shown following thecorresponding step.

2. Step two...

GUI Indicators

Operations or titles of user interface items (GUI) will be indicated inBold.

Page 174: Customizing Geomedia

174 Fundamentals of GeoMedia Development Part I

Reference MaterialsThe following materials have been used as reference materials in thecreation of this workshop.

Microsoft ® Development Library

Copyright © 1992 - 1996 Microsoft Corporation

Inside OLE 2

Copyright © 1995 by Kraig Brockschmidt

ISBN 1-55615-843-2

Microsoft Excel Version 5.0 for Windows NT

Copyright © 1985 - 1994 Microsoft Corporation, On-line Help

GeoMedia ™ Help

GeoMedia ™ Help Topics

Programming with GeoMedia ™

GeoMedia ™ Automation Programming Help

Copyright © 1997 Intergraph Corporation 1997

Team GeoMedia Technical Articles and Samples

http://www.ingr.com/geomedia/team_geo.htm

Visual Basic ® 4 Enterprise Development

Copyright © 1996 by Que ® Corporation

Craig Goren, James Schmelzer, Jeffery Smith

ISBN: 0-7897-0099-9

Object-Oriented Modeling and Design

Copyright © 1991 by Prentice-Hall, Inc.

Page 175: Customizing Geomedia

Appendices 175

James Rumbaugh, Michael Blaha, William Premerlani, Frederick Eddy,William Lorensen

ISBN: 0-13-629841-9

Where to Get HelpQuestions on GeoMedia and GeoMedia customization can be directed toIntergraph support. Our web page provides all the necessary instructionsfor logging worksheets. Access to our knowledge base is also availablefor helping you resolve any problems you might have. The web site is:

http://www.ingr.com/iss/products/mapping/services/support.htm

– or –

http://www.ingr.com/iss/products/mapping/services/GeoMedia.htm

Or, you may call 1-800-633-7248 in the US. For non-US customers,please contact your local Intergraph office.

Page 176: Customizing Geomedia

176 Fundamentals of GeoMedia Development Part I

Lab ExercisesThe lab exercises are intended to reinforce the concepts presented in theworkshop materials. Each lab will start from a skeleton, or template. Thistemplate provides you with hints for writing the proper code for the lab.Additionally, much of the code needed to manipulate the GUI will beincluded in the template.

The Labs directory contains the standard templates. These templatesprovide the code for the exercise, with methods and properties missing asindicated by question marks (??). You need only fill in the missingnames.

The templates can be found on the floppy labeled Fundamentals ofGeoMedia Development Part I Lab Exercises and Solutions, whichaccompanies the workshop materials. Create a root directory, likeC:\TGM. Unzip the templates and solutions to this root directory. Thelabs are defined in the subdirectory Labs, while the solutions are providedin Solutions. Each skeleton is contained in a subdirectory of (e.g.,C:\TGM\Labs\Lab14). Each solution is in a parallel subdirectory ofSolutions (e.g., C:\TGM\Solutions\Lab14).

Page 177: Customizing Geomedia

Appendices 177

Feature List for Lab 14This table provides a list of all the features and their field names andtypes. This information will be used in Lab 14.

Airports POINTID gdbDouble

Airports FEATURID gdbText

Airports FAC_TYPE gdbText

Airports FAC_NAME gdbText

Airports CITY gdbText

Airports COUNTY gdbText

Airports STATE gdbText

Airports STFIPS gdbText

Airports FAA_REGION gdbText

Airports FAC_USE gdbText

Airports JOINT_USE gdbText

Airports OWN_TYPE gdbText

Airports OWN_NAME gdbText

Airports ELEVATION gdbLong

Airports CDB_DIST gdbDouble

Airports RUN_NUM gdbInteger

Airports PAD_NUM gdbInteger

Airports CONG_LVL gdbText

Airports LNG_FLT gdbText

Airports AC_TYPE gdbText

Airports GEOMETRY gdbSpatial

Airports TEXT gdbGraphic

Cities GEOMETRY gdbSpatial

Cities CITY_NAME gdbText

Cities POP gdbDouble

Cities WHPOP gdbDouble

Page 178: Customizing Geomedia

178 Fundamentals of GeoMedia Development Part I

Cities BLKPOP gdbDouble

Cities HISPPOP gdbDouble

Cities ASIANPOP gdbDouble

Cities MEDAGEMAL gdbDouble

Cities MEDAGEFEM gdbDouble

Cities ED_LT_HS gdbDouble

Cities EDHS gdbDouble

Cities EDSOMCOL gdbDouble

Cities EDCOL gdbDouble

Cities EDGRAD gdbDouble

Cities SQMILES gdbDouble

Cities TOTCRIME gdbDouble

Cities AVETEMP gdbDouble

Cities ANNULRAIN gdbDouble

Cities ANNULSNOW gdbDouble

Cities STATE_NAME gdbText

Cities CITY_ID gdbLong

Cities POP_EDU gdbDouble

Counties FIPS gdbText

Counties STATE_NAME gdbText

Counties Geometry gdbSpatial

Counties POP gdbDouble

Counties WHPOP gdbDouble

Counties BLKPOP gdbDouble

Counties HISPPOP gdbDouble

Counties ASIANPOP gdbDouble

Counties MEDAGEMAL gdbDouble

Counties MEDAGEFEM gdbDouble

Counties ED_LT_HS gdbDouble

Page 179: Customizing Geomedia

Appendices 179

Counties EDHS gdbDouble

Counties EDSOMCOL gdbDouble

Counties EDCOL gdbDouble

Counties EDGRAD gdbDouble

Counties SQMILES gdbDouble

Counties TOTCRIME gdbDouble

Counties AVETEMP gdbDouble

Counties ANNULRAIN gdbDouble

Counties ANNULSNOW gdbDouble

Counties COUNTY_ID gdbLong

Counties POP_EDU gdbDouble

Interstates STATE_FIPS gdbInteger

Interstates STATE_NAME gdbText

Interstates SUB_REGION gdbText

Interstates Geometry gdbSpatial

Interstates Id gdbLong

Rivers TYPE gdbInteger

Rivers RIVER_TYPE gdbText

Rivers STATE_FIPS gdbInteger

Rivers STATE_NAME gdbText

Rivers SUB_REGION gdbText

Rivers Geometry gdbSpatial

Rivers Id gdbLong

StateNameLabels ID gdbLong

StateNameLabels LabelColumn gdbGraphic

States FIPS gdbText

States STATE_NAME gdbText

States STAABBRV gdbText

States Geometry gdbSpatial

Page 180: Customizing Geomedia

180 Fundamentals of GeoMedia Development Part I

States POP gdbDouble

States WHPOP gdbDouble

States BLKPOP gdbDouble

States HISPPOP gdbDouble

States ASIANPOP gdbDouble

States MEDAGEMAL gdbDouble

States MEDAGEFEM gdbDouble

States ED_LT_HS gdbDouble

States EDHS gdbDouble

States EDSOMCOL gdbDouble

States EDCOL gdbDouble

States EDGRAD gdbDouble

States SQMILES gdbDouble

States TOTCRIME gdbDouble

States AVETEMP gdbDouble

States ANNULRAIN gdbDouble

States ANNULSNOW gdbDouble

States STATE_ID gdbLong

States POP_EDU gdbDouble

Page 181: Customizing Geomedia

Appendices 181

Visual Basic Syntactical Constructs

Declarative and Assignment Statements

You declare a variable with the following statement.

{Dim | ReDim | Static | Private | Public} variablename [Astype]

You declare an object variable in the same way you declare othervariables. The only differences are the optional New keyword and theclass argument which takes the place of the type.

{Dim | ReDim | Static | Private | Public} variable As [New]class

Arrays are declared and referenced with their subscripts in parentheses.

{Dim | ReDim | Static | Private | Public}arrayname(subscripts) [As type]

Likewise, parentheses are used to numerically index collections.Additionally, most collections allow you to index or address a member ofthe collection by name.

collection("name") -or

collection!name

Determining the type of an object variable may be accomplished in one oftwo ways. An expression of the form

TypeOf objectname Is objecttype

may be used as the condition in decision or loop structures. TheTypeName function may be used in an expression. It returns a stringcontaining the object type.

Dim strObjectType As String

strObjectType = TypeName(objectname)

You assign the value of an expression to a variable or property as:

Page 182: Customizing Geomedia

182 Fundamentals of GeoMedia Development Part I

[Let] varname = expression

Explicit use of the Let keyword is a matter of style, but it is usuallyomitted.

You often need to make several property assignments or perform severaldifferent actions on the same object. You can do this with the Withstatement.

With object.property = expression -and/or-.method(arguments)

.

.

End With

You assign an object to an object variable with the Set statement:

Set variable = object

After you declare an object variable, you must assign an object referenceto the variable before you can use the object’s properties, methods, andevents. You can assign a new object reference in several ways.

• If you declared the variable using the New keyword, Visual Basic willautomatically assign a new object reference the first time you use thevariable.

• You can assign a reference to a new object in a Set statement by usingthe New keyword or CreateObject function.

Set objectvariable = New class -or-

Set objectvariable = CreateObject("progID")

• You can assign a reference to a new or existing object in a Setstatement by using the GetObject function.

When you are finished using an object, clear any variables that referencethe object so the object can be released from memory. To clear an objectvariable, set it to Nothing.

Page 183: Customizing Geomedia

Appendices 183

Set objectvariable = Nothing

Procedural Structures

A Sub procedure is a block of code that can take arguments, perform aseries of statements, and change the value of its arguments.

[Private|Public][Static]Sub procedurename (arguments)[statementblock][Exit Sub][statementblock]

End Sub

You call a Sub procedure as a stand-alone statement in one of two ways:

procedurename arguments -or-

Call procedurename(arguments)

A Function procedure is a block of code that can take arguments, performa series of statements, change the value of its arguments, and can return avalue to the calling procedure.

[Private|Public][Static]Function procedurename(arguments) [As type]

[statementblock][Exit Function][statementblock]

End Function

You call a function by including the function procedure name andarguments on the right side of a statement or expression.

returnvalue = function(arguments)

Decision Structures

Use an If...Then structure to execute one or more statements conditionally.You can use either a single-line syntax or a multiple-line block syntax.

Page 184: Customizing Geomedia

184 Fundamentals of GeoMedia Development Part I

If condition Then statement

If condition Thenstatements

End If

Use an If...Then...Else block to define several blocks of statements, one ofwhich will execute.

If condition1 Then[statementblock-1]

[ElseIf condition2 Then[statementblock-2]] ...

[Else[statementblock-n]]

End If

A Select Case statement provides capability similar to the If...Then...Elsestatement, but it makes code more readable when there are severalchoices.

Select Case testexpression[Case expressionlist1

[statementblock-1]][Case expressionlist2

[statementblock-2]]...

[Case Else[statementblock-n]]

End Select

Loop Structures

Use a Do loop to execute a block of statements an indefinite number oftimes. In the Do While...Loop, the statements execute as long as thecondition is True.

Do While condition[statementblock][Exit Do]

Page 185: Customizing Geomedia

Appendices 185

[statementblock]

Loop

In the Do Until...Loop, the statements execute as long as the condition isFalse.

Do Until condition[statementblock][Exit Do][statementblock]

Loop

When you know you must execute the statements a specific number oftimes, use a For…Next loop which uses a variable called a counter thatincreases or decreases in value during each repetition of the loop.

For counter = start To end [Step increment][statementblock][Exit For][statementblock]

Next [counter]

The arguments counter, start, end, and increment are all numeric.

A For Each...Next loop repeats a group of statements for each element in acollection of objects.

For Each object In collection[statementblock][Exit For][statementblock]

Next object

Page 186: Customizing Geomedia

186 Fundamentals of GeoMedia Development Part I

Visual Basic Notation Conventions

Introductory Remarks

Some of the content below is based on information available throughVisual Basic Books Online and MSDN.

It is convenient for the programmer to be able to determine the data typeof a variable or constant quickly and directly from the name. To this end,programmers use notation conventions; perhaps the most famous is the so-called Hungarian notation convention, developed by Charles Simonyi.

The exact notation convention used within a given Visual Basic programis not as important as that one is used throughout. Typically, the first few(1-4) letters indicate what data type a variable or constant is. This prefixis usually in lower case letters, and the following letter is capitalized in thevariable name. For example, the variable supplied by the GeoMediaCommand Wizard for the GeoMedia application object is named:

gobjGeoApp

Here, “g” refers to the fact that gobjGeoApp is a global variable, and“obj” refers to the fact that gobjGeoApp is an object. An example of aGeoMedia constant is

gmsqTouches

Here “gm” stands for GeoMedia, “sq” for Spatial Query, and “Touches”is the particular spatial operator referred to. The other GeoMedia SpatialQuery constants have similar names, e.g., gmsqEntirelyContains.

Before getting into a discussion of general Visual Basic conventions, wewish to note two characteristics of GeoMedia objects. The first is thatmany times a property of a GeoMedia object corresponds to a GeoMediaobject. For example, the Application object has a property calledDocument which is in fact a Document object. An example of a propertyon a Document object is Name. Thus,

gobjGeoApp.Document.Name

makes good sense, just as

objDocument.Name

does if

objDocument

is a Document object.

Page 187: Customizing Geomedia

Appendices 187

Secondly, we wish to note a convention regarding collections; weillustrate by looking at the Connections collection off of the Documentobject. Generally speaking, collections are named with the plural ofwhatever they are collections of. Thus,

objDocument.Connections

is a Connections object, which is a collection of Connection objects.Thus,

objDocument.Connections(3)

is a Connection object; in fact, it is the third Connection object in theConnections collection of objDocument.

Variable Scope Prefixes

We now begin with an excerpt from Visual Basic Books Online, locatedat:

Start Here

Programmer’s Guide (All Editions)

Visual Basic Coding Conventions

Constant and Variable Naming Conventions

As a project size grows, so does the value of recognizing variable scopequickly. A one-letter scope prefix preceding the type prefix provides thiswithout greatly increasing the size of variable names.

Scope Prefix Example

Global g gstrUserName

Module-level m mblnCalcInProgress

Local to procedure None dblVelocity

A variable has global scope if it is declared Public in a standard module ora form module. A variable has module-level scope if declared Private in astandard module or form module, respectively.

Note Consistency is crucial to productive use of this technique; thesyntax checker in Visual Basic will not catch module-level variables thatbegin with "p."

Page 188: Customizing Geomedia

188 Fundamentals of GeoMedia Development Part I

Suggested Prefixes for Controls

To address naming of controls and DAO objects, we now quote from:

Start Here

Programmer’s Guide (All Editions)

Visual Basic Coding Conventions

Object Naming Conventions

ControlType Prefix Example

3D Panel pnl pnlGroup

Animated button ani aniMailBox

Check box chk chkReadOnly

Combo box cbo cboEnglish

Command button cmd cmdExit

Common dialog dlg dlgFileOpen

Communications com comFax

Control (used within procedureswhen the specific type isunknown)

ctr ctrCurrent

Data control dat datBiblio

Data-bound combo box dbcbo dbcboLanguage

Data-bound grid dbgrd dbgrdQueryResult

Data-bound list box dblst dblstJobType

Directory list box dir dirSource

Drive list box drv drvTarget

File list box fil filSource

Form frm frmEntry

Frame fra fraLanguage

Gauge gau gauStatus

Graph gra graRevenue

Grid grd grdPrices

Page 189: Customizing Geomedia

Appendices 189

Horizontal scroll bar hsb hsbVolume

Image img imgIcon

Key status key keyCaps

Label lbl lblHelpMessage

Line lin linVertical

List box lst lstPolicyCodes

MAPI message mpm mpmSentMessage

MAPI session mps mpsSession

MCI mci mciVideo

MDI child form mdi mdiNote

Menu mnu mnuFileOpen

MS Flex grid msg msgClients

MS Tab mst mstFirst

OLE ole oleWorksheet

Outline out outOrgChart

Pen BEdit bed bedFirstName

Pen HEdit hed hedSignature

Pen ink ink inkMap

Picture pic picVGA

Picture clip clp clpToolbar

Report rpt rptQtr1Earnings

Shape shp shpCircle

Spin spn spnPages

Text box txt txtLastName

Timer tmr tmrAlarm

UpDown upd updDirection

Vertical scroll bar vsb vsbRate

Slider sld sldScale

ImageList ils ilsAllIcons

TreeView tre treOrganization

Page 190: Customizing Geomedia

190 Fundamentals of GeoMedia Development Part I

Toolbar tlb tlbActions

TabStrip tab tabOptions

StatusBar sta staDateTime

ListView lvw lvwHeadings

ProgressBar prg prgLoadFile

RichTextBox rtf rtfReport

Suggested Prefixes for Menus

Applications frequently use many menu controls, making it useful to havea unique set of naming conventions for these controls. Menu controlprefixes should be extended beyond the initial "mnu" label by adding anadditional prefix for each level of nesting, with the final menu caption atthe end of the name string. The following table lists some examples.

Menu caption sequence Menu handler name

File Open mnuFileOpen

File Send Email mnuFileSendEmail

File Send Fax mnuFileSendFax

Format Character mnuFormatCharacter

Help Contents mnuHelpContents

When this naming convention is used, all members of a particular menugroup are listed next to each other in Visual Basic’s Properties window. Inaddition, the menu control names clearly document the menu items towhich they are attached.

Suggested Prefixes for Variables and Function Names

Finally, we discuss prefixes for variables and function names; thesesuggestions are derived from both VB Books Online and MSDN.

Data type Prefixes Example

Boolean bln or b blnFound or bFound

Page 191: Customizing Geomedia

Appendices 191

Byte byt bytRasterData

Collection object col colWidgets

Currency cur or c curRevenue or cRevenue

Date (Time) dtm or dt dtmStart or dtStart

Double dbl or d dblTolerance or dTolerance

Error err errOrderNum

Integer int or i or n intQuantity or iQuantity ornQuantity

Long lng or l lngDistance or lDistance

Object obj objCurrent

Single sng sngAverage

String str or s strFName or sFName

User-defined type udt udtEmployee

Variant vnt or v vntCheckSum or vCheckSum

Page 192: Customizing Geomedia

192 Fundamentals of GeoMedia Development Part I

PowerBuilder Syntactical DifferencesSince most of the examples in the course materials and exercises useVisual Basic syntax, the following table shows some equivalent operationsin PowerBuilder syntax.

Visual Basic PowerBuilder

To declare an automation object:

Dim objLegend As NewLegend

-or-

Dim objLegend As Legend

Set objLegend =CreateObject(“GeoMedia.Legend”)

OLEObject objLegend

objLegend = Create OLEObject

objLegend.ConnectToNewObject(“GeoMedia.Legend”)

To release an object:

Set objLegend = Nothing objLegend.DisconnectObject

Destroy objLegend

PowerBuilder has no default properties, so you must explicitly referenceevery property or method, as in the case of the Item method on acollection. You index an array or collection with [ ] in PowerBuilder asopposed to ( ) in Visual Basic.

Application.Windows(2) Application.Windows.Item[2]

When using custom controls in PowerBuilder, you need to use thekeyword “Object” as the member property of the control beforereferencing any of the control’s properties or methods.

ocxMapView.Legend ocxMapView.Object.Legend

PowerBuilder’s definition of True and False is not exactly the same asVisual Basic’s, so it is safest to use 1 and 0 for True and False,

Page 193: Customizing Geomedia

Appendices 193

respectively.

objLegend.Visible = True

objLegend.Visible = False

objLegend.Visible = 1

objLegend.Visible = 0

Additionally, in PowerBuilder, as in Visual Basic, the dot is thenavigational operator for accessing an object’s properties and methods.

There is no For Each in PowerBuilder; you must use a For loop with acounter or index.

There is no TypeName() or Type Of in PowerBuilder; you must write a VBautomation server that you call from PowerBuilder if you need todetermine the type of an object. You can pass the object and VB can stilldetermine its type.

There is no equivalent concept to a With block in PowerBuilder, so it isimportant to create temporary variables to store deep-nested objects.

In PowerBuilder, you need to use the Ref keyword on return argumentsfrom methods.

Page 194: Customizing Geomedia

194 Fundamentals of GeoMedia Development Part I

Delphi and GeoMediaRefer to the technical note, Developing GeoMedia Applications withDelphi, on the Team GeoMedia web site for hints and tips on usingGeoMedia with Delphi.

Page 195: Customizing Geomedia

Appendices 195

Automation Overview DiagramsIn addition to the standard product documentation, we have prepared aquick reference guide to the automation model for GeoMedia. You canfind this file on the floppy labeled Fundamentals of GeoMediaDevelopment Part I Workshop Materials. The file, GeoMediaAuto.hlp, isa standard Windows help file. Double click on the file to start help. Byclicking on the hot spots within the graphics, you will get a summary ofthe object’s properties and methods.

The file has been copied to c:\TGM\GeoMediaAuto.hlp for access duringthe workshop.

Page 196: Customizing Geomedia

196 Fundamentals of GeoMedia Development Part I

OriginatingPipe GRecordset vs. GDO GRecordsetMost communication of data in GeoMedia is done through the use of aGRecordset object. GRecordset objects can be created in two ways. Theprimary mechanism is through the GDO OpenRecordset method on theGDatabase object. The alternative method is through the use of a pipe. Apipe is a software component that accepts input data in the form of aGRecordset and outputs data in the form of a GRecordset. The interfaceto the object (its method and properties) is exactly the same whethercreated by GDO or through a pipe. Then why are there two mechanisms?Pipe-based recordsets add value to the system. Specifically, they provide

• Persistence

• Notification

• Metadata access

• Recordset naming

• Error access

• CoordSystem access

These additions add significant power to GeoMedia. Except forpersistence, all of these additions are available in custom applications. Toensure full access to all of these capabilities, you should useOriginatingPipe to create all of your recordsets. OriginatingPipe is aspecial pipe which creates a GRecordset just as you would with GDO. Infact, it internally creates a recordset with GDatabase.OpenRecordset.

Page 197: Customizing Geomedia

Appendices 197

Programming Caveats

GeoMedia does not exit cleanly

It is probable that you will encounter situations in which GeoMedia doesnot exit cleanly after running your commands. The executable(GeoMedia.exe) will remain in memory until all references on itsautomation objects are reduced to zero. If you are encountering thissituation, your command is probably holding a global variable referencingone of these objects: GeoMedia.Application, GeoMedia.Document,GeoMedia.MapViewWindow, GeoMedia.DataViewWindow, and anyother object found under the application object in the automation diagram.To correct the situation, you must set the global objects to Nothing. Ingeneral, this should be done as soon as you have completed all operationsusing that object. In all situations, this must be done by the time theexecution of your command’s terminate method is completed.

When is it safe to keep an object reference?

In general, you should reduce or eliminate global variables in yourcommands. Obviously, this is not always possible. However, certainsituations dictate that you release the objects referenced by your globalvariables to avoid intermittent crashes. The only two GeoMedia objectswhich can safely be referenced between command initiations are theapplication object and the map view listeners object. These objects werepassed to the command in the Initialize method and are guaranteed to bevalid until the command is terminated. Although in theory, an object willnot be destroyed until all references are zero, the GeoMedia developmentstaff has diagnosed conditions in which MFC will ignore the referencecounts and destroy the object prematurely. If you then try to referencesuch an object, your command will cause GeoMedia to crash. In general,you should not retain references to any objects under the document objectin the automation hierarchy between initiations of the command.

CreateObject versus CreateService

You will find a method on the application object, CreateService, whichacts like the built-in CreateObject function. In fact, CreateService doesperform the same function as CreateObject - it creates an instance of theobject specified by the ProgID sent as the method’s parameter. Whywould you use one method over the other? The only reason to useApplication.CreateService is to sidestep some problems in marshaling of

Page 198: Customizing Geomedia

198 Fundamentals of GeoMedia Development Part I

data between process boundaries. When will you cross processboundaries? Any time you have two executables running on your systemand you are communicating between them, the data is crossing processboundaries. When GeoMedia is one of the processes, you should useApplication.CreateService to create any GeoMedia objects that will besaved in the GeoMedia workspace. By using this method, GeoMediacreates the object, and the memory is allocated in GeoMedia’s processspace. This allows GeoMedia to correctly persist its data.

NOTE: Marshaling is the packaging and sending of interface method callsacross thread or process boundaries. Essentially, marshaling is thetechnique used to translate data addresses from one process space toanother.

A query in the collection might be invalid or closed

When accessing recordsets within GeoMedia through theQueryFolder.Queries collections, you may encounter recordsets that areinvalid or closed. An invalid recordset is caused by a change to theschema that prevents the server from providing the requested data. Forexample, you may have a query for all Roads where NumLanes >2. If theschema or metadata for Roads has changed such that the attributeNumLanes no longer exists, the recordset is invalid.

To ensure a recordset is open before you access it, the following codeshould be used:

Dim objNotify as Object

Set objNotify = Nothing

On Error Resume Next

Set objNotify = objRecordset.GetExtension(“Notification”)

On Error GoTo AccessFailed

If objNotify Is Nothing Then

‘ assume that the recordset is open and continue

Else

objNotify.Reopen

End If

There is no cost to reopen the recordset if it is already open.

Page 199: Customizing Geomedia

Appendices 199

Feature Selection ControlsThe feature selection controls, GMFeatureListBox andGMFeatureComboBox, are custom controls (OCXs) that present theconnection, feature, and query information in a tree view. If you arecreating GeoMedia commands, you may use these controls. This sectionprovides the documentation necessary to utilize the controls. Bothcontrols operate in a similar fashion. They are not available in customapplications as they require a GeoMedia document as an initializationvalue.

Property/Method Data Type Description

ClearSelectedItem Boolean Clears any selected item in thetree.

ConnectionName String Name of connection selected inthe tree. Not applicable if aquery is selected.

ConnectionsVisible Boolean Indicates whether or notconnections should be displayedin the tree.

Document Document Pointer to the geoworkspacedocument. Must be set beforethe control is displayed. Mustbe released before the commandexits.

FullName Boolean Flag to indicate if the tablenames should be shown asConnection.Table. Onlyapplicable toGMFeatureCombobox.

GeometryTypesVisible Long Mask ofMetadataTableConstants thatcontrols the list of tables byinclusion of the specifiedprimary geometry types. Notapplicable to queries displayedin the tree. To display all tables,specify zero (0) for the mask.

QueriesVisible Boolean Flag to indicate if query objectsshould be included in the tree.

Page 200: Customizing Geomedia

200 Fundamentals of GeoMedia Development Part I

ReadonlyVisible Boolean Flag to indicate if read onlyconnections should be includedin the tree.

Refresh Void Method to force the tree toupdate after you have changedproperties.

SelectedItem String Value of the selected leaf node.

SelectedType Integer One of three constant valuesindicating the nature of theuser’s selection in the tree:gmfcNoSelection,gmfcConnection, or gmfcQuery.

ValidateSelectedItem Boolean Method you must call after youhave specified theConnectionName, SelectedItem,and SelectedType so that thedefault tree entry can behighlighted.

All other properties have the same definition as other controls.

Page 201: Customizing Geomedia

Appendices 201

Raster Formats

General Information

• GeoMedia will support any raster image that has been georeferencedwith Intergraph software using the transformation matrix. InGeoMedia, this type of file is placed using the "By Header" optionand the user must specify a design file so that GeoMedia candetermine the correct working units to apply to the transformationmatrix.

• GeoMedia will support any raster image that has been georeferencedwith the geo_tie_pkt application packet. In GeoMedia, this type offile is placed using the "Georeferenced" option. This is an Intergraphformat.

• GeoMedia will support most common non-georeferenced rasterformats. In GeoMedia, this type of file is placed using the"Interactive" placement option.

Supported Formats

• Intergraph (*.cot *.cit *.crl *.rgb *.rle *.tg4)

• Bitmap (*.bmp)

• TIFF (*.tif)

• In V1.0, placement by header was not supported. It isavailable in V2.0 for industry standard geo_tif_pkt forplacement by header.

• GIF (*.gif)

• IGS (*.rlc *.igs)

• JPeg (*.jpg)

• Hitachi (*.hrf)

• PCX (*.pcx)

• CALS (*.cal)

Page 202: Customizing Geomedia

202 Fundamentals of GeoMedia Development Part I

GetExtension MethodThe GDO specification includes a mechanism on the GDatabase,GRecordset, and GField objects to expose additional capabilitiesassociated with a server. Additionally, GeoMedia provides a series ofclient side extensions. These extensions typically provide additionalcapabilities associated with object.

The syntax for retrieving the extension object is:

dim objExt as Object

set objExt = myObject.GetExtension(“ExtensionName”)

where myObject is a reference to one of the GDO objects. ExtensionNameis replaced by one of the names specified in the following tables. Youmay strongly type the extension object.

GDatabase Extensions

The following extensions may be retrieved.

Extension Name Object Type Returned

FRMAdminExtension GFRMAdminExtension **

**This extension is only applicable to the GDO FRAMME server.

GRecordset Extensions

The following extensions may be retrieved.

Extension Name Object Type Returned

Name Query

Notification Notification

ExtendedPropertySet ExtendedPropertySet

OriginatingPipe OriginatingPipe

SpatialQueryPipe SpatialQueryPipe

AttributeFilterPipe AttributeFilterPipe

CSSTransformPipe CSSTransformPipe

SortPipe SortPipe

Errors GErrors

Page 203: Customizing Geomedia

Appendices 203

CenterPointPipe CenterPointPipe

EquijoinPipe EquijoinPipe

GraphicsTextPipe GraphicsTextPipe

MovePipe MovePipe

SchemaProjectPipe SchemaProjectPipe

SpatialFilterPipe SpatialFilterPipe

GField Extensions

The following extensions may be retrieved.

Extension Name Object Type Returned

ExtendedPropertySet ExtendedPropertySet

CoordSystem GRecordset

Errors GErrors

Page 204: Customizing Geomedia

204 Fundamentals of GeoMedia Development Part I

ExtendedPropertySet.GetValue MethodThe ExtendedPropertySet provides access to the client side metadatainformation about the recordset’s underlying table and fields. Themethod, GetValue, returns the value of the property specified by the inputargument. The input argument corresponds to the names of the fields inthe metadata tables. The available values are specified below.

The syntax for retrieving the value is:

dim strValue as Variant

strValue = objExtendedPropertySet.GetValue(“Property”)

where objExtendedPropertySet is a reference an ExtendedPropertySetobject retrieved through GetExtension from either the GRecordset or theGField objects. Property is replaced by one of the names specified in thefollowing tables.

GRecordset

Property Name Returned Value

Name String containing the name of the tableupon which the recordset is defined.This may be empty if the recordset is notbased directly on a warehouse table.

GeometryType Long integer containing the subtype ofthe geometry field specified by the nextproperty. The values correspond to theGDO geometry types. A special casesituation exists where this value isgdbGraphic. This indicates that thereare no spatial geometries within therecordset.

PrimaryGeometryFieldName String containing the name of thegeometry field that contains the primaryor default gdbSpatial field. This stringwill be empty if the recordset containsno spatial fields.

Description String containing a user description ofthe underlying table.

Page 205: Customizing Geomedia

Appendices 205

GField

Property Name Returned Value

Key Boolean value indicating if this field is theprimary unique key for the recordset. Onlyapplicable to non-geometry fields.

Format String containing information about thetechnique to use to format the value of thefield. Refer to the Technical Paper: MetadataLayout for information on the format values.Only applicable to non-geometry fields.

Type Short integer containing the type of the field.The value is one of the GDO data types. Onlyapplicable to non-geometry fields.

Displayable Boolean value indicating whether or not thefield should be displayed in the Data View orObject Properties dialogs. Only applicable tonon-geometry fields.

Precision Short integer indicating the number of decimalplaces to display for numeric data. Onlyapplicable to non-geometry fields.

Description String containing a user description of theunderlying table.

PrimaryGeometryFlag Boolean value indicating whether or not thisgdbSpatial field is the primary or default field.Only applicable to geometry fields.

GeometryType Long integer corresponding to the SubType ofthe field. The values corresponds to GDOgeometry types. Only applicable to geometryfields.

GCoordSystemGUID String value containing theGCoordSystemGUID associated with the field.Only applicable to geometry fields.

SpatialKeyTableName Gets or set the name (string) of the tablecontaining the geometry field to be indexed.Need only be specified on a table createdwithin a database session. Set operation is onlyapplicable to the GField object of a GTableDefobject. This is extension is currently supported

Page 206: Customizing Geomedia

206 Fundamentals of GeoMedia Development Part I

by the Access server.

SpatialKeyFieldName Gets or sets the name (string) of the spatial keyfield. The set operation is only applicable to aGField object on a GTableDef object. This isextension is currently supported by the Accessserver.

Page 207: Customizing Geomedia

Appendices 207

Common Interfaces

IUnknown

All COM objects will implement this interface. The methods within theinterface are:

• AddRef - adds a references to the object

• Release - releases a reference on the object

• QueryInterface - allows the client to ask if the object supports thespecified interface

IDispatch

All automated objects will implement this interface. The methods withinthe interface are:

• Invoke - provides access to the properties and methods exposed on anobject

• GetIDsOfNames - retrieves the interface IDs for the named member

• GetTypeInfo - retrieves the type information for an object

• GetTypeInfoCount - retrieves the number of type informationinterfaces that an object provides (either 0 or 1).

Page 208: Customizing Geomedia

208 Fundamentals of GeoMedia Development Part I

Type Libraries and ObjectsGeoMedia delivers a number of files containing information about theobjects and their methods and properties. These files can be categorizedinto three groups: OLE controls, GDO, and GeoMedia.

Category Type Library

OLE Controls dataview.tlb

defcoordsystem.tlb

mapview.tlb

ntharrw.tlb

ScaleBar.tlb

gmevent1.ocx (type library not separate from control)

gmfeaturecontrols.tlb

Pcontrol.ocx (type library not separate from controls)

GDO ExtendedPS.tlb

GDO.tlb

GDOFRM.tlb

CADIGDSScanner.tlb

CADODBCScanner.tlb

GCADServer.tlb

GeoMedia GeoMedia.tlb

PAdvLgd.tlb

Pbasic.tlb

PClCmd.tlb

Pclient.tlb

PCmdMgr.tlb

PCSS.tlb

PDBPipe.tlb

PGeoMath.tlb

Page 209: Customizing Geomedia

Appendices 209

Ppipe.tlb

Praster.tlb

PService.dll/tlb

Pview.tlb

Page 210: Customizing Geomedia

210 Fundamentals of GeoMedia Development Part I

The objects and their corresponding type libraries are listed herealphabetically by object name.

Object Type Library ProgID Prefix GeoMediaFramework

*Font Standard OLE Types

Accelerator GeoMedia Not Creatable X

Accelerators GeoMedia Not Creatable X

AltCoordSystemPath PCSS Not Creatable

AltCoordSystemPaths PCSS Not Creatable

AnyStyle PView GeoMedia

Application GeoMedia GeoMedia X

AreaStyle PView GeoMedia

ArcGeometry Pbasic GeoMedia

AttributeFilterPipe PDBPipe GeoMedia

AutoPanService PService GMService

BitmapStyle PView GeoMedia

BoundaryGeometry Pbasic GeoMedia

BufferZonePipe PPipe GeoMedia

BursaWolf PCSS Not Creatable

Categories GeoMedia Not Creatable X

Category GeoMedia Not Creatable X

CenterPointPipe PPipe GeoMedia

ColorScheme PView GeoMedia

ColorSchemes PView GeoMedia

Command GeoMedia Not Creatable X

Commands GeoMedia Not Creatable X

ComplexPolynomial PCSS Not Creatable

CompositePolygonGeometry Pbasic GeoMedia

CompositePolylineGeometry Pbasic GeoMedia

Connection PClient GeoMedia

Connections PClient GeoMedia

CoordSystem PCSS

CoordSystemsMgr PCSS

Page 211: Customizing Geomedia

Appendices 211

CSSTransformPipe PDBPipe GeoMedia

DataWindow GeoMedia Not Creatable X

DatumTransformation PCSS

DisplayedObjects PView GeoMedia

DockableControl GeoMedia Not Creatable X

DockableControls GeoMedia Not Creatable X

DocSelectedObjects PClient GeoMedia X

Document GeoMedia GeoMedia X

EllipsoidStrings PCSS Not Creatable

EquijoinPipe PDBPipe GeoMedia

EventServer PBasic GeoMedia

ExtendedPropertySet PClient Not Creatable

FieldProperty PService GMService

GDatabase GDO Access, AI, GWMGE, FRAMME,

MGSM, AV,MGDM, GCAD

GeodeticDatumStrings PCSS Not Creatable

GeogSpace PCSS Not Creatable

GeometryCollection PBasic GeoMedia

GeometryDigitizeService PClient GeoMedia

GeometryEditService PClient GeoMedia

GeometryObject PView GeoMedia

GeometryStorageService PClient GeoMedia

GError GDO Not Creatable

GErrors GDO Not Creatable

GField GDO Not Creatable

GFields GDO Not Creatable

GFRMAdminExtension GDOFRM Not Creatable

GFRMSeg GDOFRM Not Creatable

GFRMSegs GDOFRM Not Creatable

GIndex GDO Not Creatable

GIndexes GDO Not Creatable

GMDataView DataViewLib Control

GMDefCoordSystem DefCoordSystemLib GeoMedia

Page 212: Customizing Geomedia

212 Fundamentals of GeoMedia Development Part I

GMEventControl GMEventControLib Control

GMFeatureCombobox GMFeatureControlsLib Control

GMFeatureListbox GMFeatureControlsLib Control

GMMapView MapViewLib Control

GMNorthArrow GMNorthArrow Control

GMScaleBar ScaleBarLib Control

GMViewListeners PCmdMgr Not Creatable X

GraphicsTextPipe PService GMService

GRecordset GDO Not Creatable

GRecordsets GDO Not Creatable

GTableDef GDO Not Creatable

GTableDefs GDO Not Creatable

HandleStyle PView GeoMedia

LeastSquares PCSS GeoMedia

Legend PView GeoMedia

LegendEntries PView GeoMedia

Legends PView GeoMedia

LinearModelResidual PCSS Not Creatable

LinearStyle PView GeoMedia

LineGeometry PBasic GeoMedia

Link PCSS Not Creatable

Links PCSS Not Creatable

LocatedObjectsCollection PView GeoMedia

MapWindow GeoMedia Not Creatable X

Matrix Pbasic GeoMedia

MeasurementService PClient GeoMedia

MenuBar GeoMedia Not Creatable X

MenuBars GeoMedia Not Creatable X

MenuItem GeoMedia Not Creatable X

MenuItems GeoMedia Not Creatable X

MetadataService PService GMService

MovePipe PPipe GeoMedia

MultipleRegression PCSS Not Creatable

Page 213: Customizing Geomedia

Appendices 213

NonlinearModelResidual PCSS Not Creatable

Notification PClient Not Creatable

Observation PCSS Not Creatable

Observations PCSS Not Creatable

OrientedPointGeometry PBasic GeoMedia

OriginatingPipe PClient Not Creatable

OutputTableService PService GMService

PaperSpace PCSS Not Creatable

PatternedAreaStyle PView GeoMedia

PatternedLinearStyle PView GeoMedia

PickQuickDialog PService GMService

Point PBasic GeoMedia

PointGeometry PBasic GeoMedia

Points PBasic GeoMedia

PointSymbolStyle PView GeoMedia

PolygonGeometry PBasic GeoMedia

PolylineGeometry PBasic GeoMedia

PreferenceSet PService GMService

ProjAlgorithmStrings PCSS Not Creatable

ProjSpace PCSS Not Creatable

Queries PDBPipe GeoMedia

Query PDBPipe GeoMedia

QueryFolder PDBPipe GeoMedia

QueryFolders PDBPipe GeoMedia

Range PAdvLgd GeoMedia

RangeLegendEntry PAdvLgd GeoMedia

Ranges PAdvLgd GeoMedia

RasterGeometry PRaster GeoMedia

RasterLegendEntry PRaster GeoMedia

RasterObject PRaster Not Creatable

RasterPropertiesService PRaster GeoMedia

RecordLegendEntry PView GeoMedia

RecordObject PView GeoMedia

Page 214: Customizing Geomedia

214 Fundamentals of GeoMedia Development Part I

RecordsetObject PView GeoMedia

RectangleGeometry PBasic GeoMedia

RefSpaceMgr PCSS Not Creatable

SchemaProjectPipe PDBPipe GeoMedia

SecondDegreePolynomial PCSS Not Creatable

ServerTransService PClient GeoMedia

SingleParameterConstraint PCSS Not Creatable

SingleParameterConstraints PCSS Not Creatable

SmartLocateService PBasic GeoMedia

SnapService PClient GeoMedia

SortKey PPipe GeoMedia

SortKeys PPipe GeoMedia

SortPipe PPipe GeoMedia

SpatialFilter PClient GeoMedia

SpatialFilterPipe PDBPipe GeoMedia

SpatialFilters PClient GeoMedia

SpatialQueryPipe PPipe GeoMedia

StandardMolodensky PCSS Not Creatable

StatisticsService PClCmd GeoMedia

Symbol PView Not Creatable

SymbolFileService PView GeoMedia

SymbolFontStyle PView GeoMedia

SymbolNames PView Not Creatable

TableProperty PService GMService

TextPointGeometry PBasic GeoMedia

TextStyle PView GeoMedia

ToolBar GeoMedia Not Creatable X

ToolBarButton GeoMedia Not Creatable X

ToolBarButtons GeoMedia Not Creatable X

ToolBars GeoMedia Not Creatable X

TransLinks PCSS Not Creatable

UniqueValue PAdvLgd GeoMedia

UniqueValueLegendEntry PAdvLgd GeoMedia

Page 215: Customizing Geomedia

Appendices 215

UniqueValues PAdvLgd GeoMedia

UnitFormatSpec PCSS Not Creatable

UnitIDs PCSS Not Creatable

UnitsOfMeasure PCSS

Vector Pbasic GeoMedia

Windows GeoMedia Not Creatable X

Page 216: Customizing Geomedia

216 Fundamentals of GeoMedia Development Part I

Object BundlesIn addition to the standard product offerings, Intergraph will accommodatethe sale of object bundles. That is, you can use a subset of the GeoMediaobjects without installing GeoMedia on each user’s machine. Objectbundle sales must be negotiated as an OEM (Original EquipmentManufacturer) agreement with Intergraph. Please contact the TeamGeoMedia Technical Staff at [email protected] for more information onthe requirements of this program and associated pricing.

The basic object bundles are categorized here.

Object Set Name Description

MapView Map view display complete with smart legend,object locate, north arrow, scale bar, andgeometry objects. Record legend entry isincluded which provides for the display of vectordata, including the supported styles. Requires atleast one data server.

Raster Extends the map view object set with rasterdisplay.

Thematics Extends the map view object set with thematicmap displays for both unique value and rangethematics.

Buffer Zone Extends the map view object set with the abilityto generate, display and store buffer zones.Requires the Access Data Server.

Adv. Analysis Extends the map view object set with the abilityto perform spatial analysis against one or moredata sources.

Edit/Redline Extends the map view object set with the abilityto perform dynamics in the generation of newfeatures. Requires the Access Data Server.

Access Data Server Provides the ability to read and write GIS data inan Access compatible data base. MicrosoftAccess is not required.

MGE Data Server Provides read-only access to MGE databases. AnODBC driver for the relational database used by

Page 217: Customizing Geomedia

Appendices 217

the MGE database is required.

FRAMME Data Server Provides read-only access to a FRAMMEdatabase.

MGSM Data Server Provides read-only access to a MGSM database.

Oracle Data Server(RO)

Provides read-only access to an Oracle databasewith or without SDO. The ability to import datainto Oracle is NOT supported by this object.

ArcInfo Data Server Provides read-only access to ArcInfo coverages.

** As a minimum, you must purchase the MapView set of objects.

Page 218: Customizing Geomedia

218 Fundamentals of GeoMedia Development Part I

The following chart indicates the composition of the above describedobject sets, including objects and type libraries.

OBJECT TYPE LIBRARY OBJECT SETNAME

MAPVIEW

AltCoordSystemPath PCSS MapView

AltCoordSystemPaths PCSS MapView

AnyStyle PView MapView

AreaStyle PView MapView

BitmapStyle PView MapView

BoundaryGeometry PBasic MapView

ColorScheme PView MapView

ColorSchemes PView MapView

CoordSystem PCSS MapView

CoordSystemsMgr PCSS MapView

DisplayedObjects PView MapView

EllipsoidStrings PCSS MapView

EventServer PBasic MapView

GeodeticDatumStrings PCSS MapView

GeogSpace PCSS MapView

GeometryCollection PBasic MapView

GeometryObject PView MapView

GeometryStorageService PClient MapView

GMDefCoordSystem DefCoordSystemlib MapView

GMEventControl GMEventControllib MapView

GMMapView MapViewLib MapView

GMNorthArrow GMNorthArrow MapView

GMScaleBar ScaleBarLib MapView

HandleStyle PView MapView

Legend PView MapView

LegendEntries PView MapView

Legends PView MapView

Linear Style PView MapView

Page 219: Customizing Geomedia

Appendices 219

LineGeometry PBasic MapView

Link PCSS MapView

Links PCSS MapView

LocatedObjectsCollection PView MapView

MeasurementService PClient MapView

OrientedPointGeometry PBasic MapView

PageSetup PClCmd MapView

PaperSpace PCSS MapView

Point PBasic MapView

PointGeometry PBasic MapView

Points PBasic MapView

PolygonGeometry PBasic MapView

PolylineGeometry PBasic MapView

PreferenceSet PService MapView

Print PClCmd MapView

ProjAlgorithmStrings PCSS MapView

ProjSpace PCSS MapView

RecordLegendEntry PView MapView

RecordObject PView MapView

RecordsetObject PView MapView

RectangleGeometry PBasic MapView

RefSpaceMgr PCSS MapView

SmartLocateService PBasic MapView

SymbolFontSytle PView MapView

TextPointGeometry PBasic MapView

TextStyle PView MapView

TransLinks PCSS MapView

UnitFormatSpec PCSS MapView

UnitIDs PCSS MapView

UnitsOfMeasure PCSS MapView

RASTER

RasterGeometry PRaster Raster

RasterLegendEntry PRaster Raster

Page 220: Customizing Geomedia

220 Fundamentals of GeoMedia Development Part I

RasterObject PRaster Raster

RasterPropertiesService PRaster Raster

THEMATICS

Field Property PService Thematics

Range PAdvLgd Thematics

RangeLegendEntry PAdvLgd Thematics

Ranges PAdvLgd Thematics

SortKey PPipe Thematics

SortKeys PPipe Thematics

SortPipe PPipe Thematics

StatisticsService PClCmd Thematics

TableProperty PService Thematics

UniqueValue PAdvLgd Thematics

UniqueValueLegendEntry PAdvLgd Thematics

UniqueValues PAdvLgd Thematics

BUFFERZONE

BufferZonePipe PClCmd BufferZone

ADVANCEDANALYSIS

AttributeFilterPipe PPipe Advanced Analysis

Connection PClient Advanced Analysis

Connections PClient Advanced Analysis

CSSTransformPipe PClient Advanced Analysis

GMDataView DataView Advanced Analysi

GMFeatureCombobox GMFeatureControlsLib Advanced Analysis

GMFeatureListBox GMFeatureControlsLib Advanced Analysis

MetadataService PService Advanced Analysis

Notification PClient Advanced Analysis

OriginatingPipe PClient Advanced Analysis

Queries PClient Advanced Analysis

Query PClient Advanced Analysis

QueryFolder PClient Advanced Analysis

QueryFolders PClient Advanced Analysis

ServerTransService PClient Advanced Analysis

Page 221: Customizing Geomedia

Appendices 221

SpatialQueryPipe PPipe Advanced Analysis

EDIT/REDLINE

GeometryDigitizeService PClient Edit/Redline

GeometryEditService PClient Edit/Redline

Page 222: Customizing Geomedia

222 Fundamentals of GeoMedia Development Part I

Collections: Indexing and Object TypesThis section describes the available collections within GeoMedia. Itidentifies the indexing technique (zero or one relative) and the type ofobjects contained in each collection.

Collection Object Hetero-

geneous

IndexRelativeTo

Accelerators Accelerator No 1

AltCoordSystemPaths AltCoordSystemPath No 1

Categories Category No 1

ColorSchemes ColorScheme No 1

Commands Command No 1

CompositePolygonGeometry LineGeometry, PolylineGeometry,ArcGeometry,CompositePolylineGeometry

Yes 1

CompositePolylineGeometry LineGeometry, PolylineGeometry,ArcGeometry,CompositePolylineGeometry

Yes 1

Connections Connection No 1

DisplayedObjects See HighlightedObjects &MapViewSelectedObjects

Yes 1

DockableControls DockableControl No 1

GeometryCollection GeometryCollection,CompositePolylineGeometry,CompositePolygonGeometry,ArcGeometry, PointGeometry,OrientedPointGeometry,TextPointGeometry, LineGeometry,PolylineGeometry,RectangleGeometery,PolygonGeometry, BoundaryGeometry,RasterGeometry

Yes 1

GErrors Gerror No 0

GFields GField No 0

GFRMSegs GFRMSeg No 0

Gindexes Gindex No 0

Grecordsets GRecordset No 0

GTableDefs GTableDef No 0

Page 223: Customizing Geomedia

Appendices 223

HighlightedObjects GeometryObject, RecordObject,RecordsetObject, RasterObject

Yes 1

Holes RectangleGeometery, PolygonGeometry Yes 1

LegendEntries RecordLegendEntry,RasterLegendEntry, RangeLegendEntry,UniqueValueLegendEntry

Yes 1

Legends Legend No 1

Links Link No 1

LocatedObjectsCollection GeometryObject, RecordsetObject,RasterObject

Yes 1

MapViewSelectedObjects GeometryObject, RecordObject,RecordsetObject, RasterObject

Yes 1

MenuBars MenuBar No 1

MenuItems MenuItem No 1

Observations Observation No 1

Points Point No 1

Queries Query No 1

QueryFolders QueryFolder No 1

Ranges Range No 1

SelectedObjects GeometryObject, RecordObject,RecordsetObject, RasterObject

Yes 1

SortKeys SortKey No 1

SpatialFilters SpatialFilter No 1

ToolBarButtons ToolBarButton No 1

ToolBars ToolBar No 1

TransLinks TransLink No 1

UniqueValues UniqueValue No 1

Windows DataWindow, MapWindow Yes 1

Page 224: Customizing Geomedia

224 Fundamentals of GeoMedia Development Part I

Object Types in Heterogeneous Collections

CompositePolygonGeometry,CompositePolylineGeometry

Contains a mixture of LineGeometry, PolylineGeometry,ArcGeometry, and CompositePolylineGeometry objects. Thiscollection is heterogeneous and indexed relative to 1.

Object Value Returned by TypeName Value of TypeProperty

CompositePolylineGeometry DGMCompositePolylineGeometry CompositePolyline

Geometry

LineGeometry DGMLineGeometry LineGeometry

PolylineGeometry DGMPolylineGeometry PolylineGeometry

ArcGeometry DGMArcGeometry ArcGeometry

GeometryCollection

Contains a mixture of GeometryCollection, PointGeometry,OrientedPointGeometry, TextPointGeometry, LineGeometry,PolylineGeometry, RectangleGeometery, PolygonGeometry,BoundaryGeometry, and RasterGeometry objects. This collection isheterogeneous and indexed relative to 1.

Object Value Returned by TypeName Value of Type Property

ArcGeometry DGMArcGeometry ArcGeometry

CompositePolygonGeometry DGMCompositePolygon

Geometry

CompositePolygon

Geometry

CompositePolylineGeometry DGMCompositePolyline

Geometry

CompositePolyline

Geometry

GeometryCollection DGMGeometryCollection GeometryCollection

PointGeometry DGMPointGeometry PointGeometry

OrientedPointGeometry DGMOrientedPointGeometry OrientedPointGeometry

TextPointGeometry DGMTextPointGeometry TextPointGeometry

LineGeometry DGMLineGeometry LineGeometry

Page 225: Customizing Geomedia

Appendices 225

PolylineGeometry DGMPolylineGeometry PolylineGeometry

RectangleGeometery DGMRectangleGeometry RectangleGeometry

PolygonGeometry DGMPolygonGeometry PolygonGeometry

BoundaryGeometry DGMBoundaryGeometry BoundaryGeometry

RasterGeometry DGMRasterGeometry RasterGeometry

DisplayedObjects, HighlightedObjects,MapViewSelectedObjects

Contains a mixture of GeometryObject, RecordObject,RecordsetObject, and RasterObject objects. This collection isheterogeneous and indexed relative to 1.

Object Value Returned byTypeName

Value of TypeProperty

GeometryObject GeometryObject GeometryObject

RecordObject RecordObject RecordObject

RecordsetObject RecordsetObject RecordsetObject

RasterObject DGMRasterObject RasterObject**

Holes

Contains a mixture of RectangleGeometry and PolygonGeometryobjects. This collection is heterogeneous and indexed relative to 1.

Object Value Returned by TypeName Value of TypeProperty

RectangleGeometery DGMRectangleGeometry RectangleGeometry

PolygonGeometry DGMPolygonGeometry PolygonGeometry

CompositePolygonGeometry DGMCompositePolygonGeometry CompositePolygon

Geometry

Page 226: Customizing Geomedia

226 Fundamentals of GeoMedia Development Part I

LegendEntries

Contains a mixture of RecordLegendEntry, RasterLegendEntry,UniqueValueLegendEntry, and RangeLegendEntry objects. Thiscollection is heterogeneous and indexed relative to 1.

Object Value Returned by TypeName Value of TypeProperty

RecordLegendEntry DGMRecordLegendEntry RecordLegendEntry

RasterLegendEntry DGMRasterLegendEntry RasterLegendEntry

RangeLegendEntry DGMRangeLegendEntry RangeLegendEntry

UniqueValueLegendEntry DGMUniqueValueLegendEntry UniqueValueLegendEntry

LocatedObjectsCollection

Contains a mixture of GeometryObject, RecordsetObject, andRasterObject objects. This collection is heterogeneous and indexedrelative to 1.

Object Value Returned byTypeName

Value of TypeProperty

GeometryObject GeometryObject GeometryObject

RecordsetObject RecordsetObject RecordsetObject

RasterObject DGMRasterObject RasterObject**

SelectedObjects

Contains a mixture of GeometryObject, RecordObject,RecordsetObject, and RasterObject objects. This collection isheterogeneous and indexed relative to 1.

Object Value Returned byTypeName

Value of TypeProperty

GeometryObject GeometryObject GeometryObject

RasterObject DGMRasterObject RasterObject**

RecordObject RecordObject RecordObject

Page 227: Customizing Geomedia

Appendices 227

RecordsetObject RecordsetObject RecordsetObject

Windows

Contains a mixture of DataWindow and MapWindow objects. Thiscollection is heterogeneous and indexed relative to 1.

Object Value Returned byTypeName

Value of TypeProperty

DataWindow Object DataWindow

MapWindow Object MapWindow

** The Type property of a RasterObject currently returns a blank string.A software trouble report (TR) has been logged.

Page 228: Customizing Geomedia

228 Fundamentals of GeoMedia Development Part I

Page 229: Customizing Geomedia

Appendices 229

Instructor’s OverheadsThe following pages provide you with copies of the overheads used duringthe workshop sessions.