17
Delphi 8 The following tutorials have been created in order to provide Borland Delphi 8 Architect customers with a step-by-step approach to how Borland Enterprise Core Obects !ECO" wor#s$ The tutorials% beginning with Tutorial &% should ease customers into the concepts of EC O and model-driven applications and advance to more complicated features and capabilitie s$ 'lease chec# bac# for more tutorial updates to this page$ Tutorial &( Creating your first ECO application Tutorial )( *or#ing with Associations Tutorial +( ,sing Borland Enterprise Core Obects !ECO." with Databases Tutorial 1 Creating your first ECO application By Anthony /ichardson Abstract - This article demonstrates building a simple application using the Borland® Enterprise Core Objects (ECO)™ technology in Borland® Delphi™  Architect Introduction What is Modeling The E!a"ple Application #uilding the Application CoreClasses$nit%pas ContactManagerEco&pace%pas #uilding an ECO Model Creating the Model Adding a $ser Interface  'unning the Application (ersisting the data Auto )or"s Conclusion About the Author Delphi 8 Architect ECO Tutor ial 'roect Introduction Enterprise Core Obects !ECO". is a development and runtime framewor# for 0odel Driven D evelopment$ The traditiona l process of transforming re1uirements to a computer understand able view of the problem may involve the design of databases% applications% and interfaces each with its own way of representing the business logic$ ECO applies Obect Oriented fle2ibility and design to the business and persistence layers of your application ma#ing design and development easier $ 3t is worth spending time on this upfront because this is a huge part of the productivity enhancement you will e2perience when using the ECO architectur e$ What is Modeling 3 have mentioned 0odel Driven Development% but what is a model4 A model is a description or view of something$ 5i#e a model aircraft is a miniature representation of a real aircraft% a software model is a representat ion of the problem domain in which the software will run$ 3t is possible to generate many different models for a particular software proect$ 'opular software engineering methodologies describe models and activities at various stages of the software development lifecycle$ 0odels also simplify communication between developers% users and other sta#eholder s$ By creating the various types of models you can describe a comple2 software system in a series of progressively more detailed set of views into the problem domain$ The problem with using models% in this way% is that% by the time you have increasingly refined a model to the point that it is completely unambiguous and e2ecutable% it no longer is recogni6able as a description of the original problem$ By the time we have converted a description of the problem progressively from te2t description to source code and database schemas% only a developer !and the compiler" can understand it$ The problem with this is the transformation from business understanding to compiler understanding has to happen each time we modify the code$ And when we loo# at code written by others we need to convert it the other way% from source code to business logic$ ECO provides a way to remove the need to manually perform a lot of the transformation$ ECO allows the developer to model a problem in a way that more closely represents the business logic% and is still unambiguous and e2ecutable$ This is often referred to as raising the level of abstraction$ By doing this% the ability to change and understand comple2 software is made easier and less e2pensive$ *hen we create models in ECO the classes we model are often referred to as B usiness Classes or Domain Classes$ At runtime we refer to these as Business Obects or Domain Obects$ The reason we use these names is because the classes directly represent entities in the problem domain of the business$ 7or e2ample% in a ,niversity enrollment application we may model the business classes tudent% Teacher and ubect$ The E!a"ple Application This tutorial will build a simple address boo# application that saves its data to an 905 file$ The basic needs for our application are( &tore contact infor"ation for people% &tore contact infor"ation for co"panies% *e are going to implement the following ,nified 0odeling 5anguage. model for our address boo# application(

Delphi 8 Tutorial

Embed Size (px)

Citation preview

Page 1: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 1/17

Delphi 8

The following tutorials have been created in order to provide Borland Delphi 8 Architect customers with a step-by-step approach to how Borland Enterprise CoreObects !ECO" wor#s$ The tutorials% beginning with Tutorial &% should ease customers into the concepts of ECO and model-driven applications and advance to morecomplicated features and capabilities$ 'lease chec# bac# for more tutorial updates to this page$

Tutorial &( Creating your first ECO application

Tutorial )( *or#ing with Associations

Tutorial +( ,sing Borland Enterprise Core Obects !ECO." with Databases

Tutorial 1

Creating your first ECO applicationBy Anthony /ichardson

Abstract - This article demonstrates building a simple application using the Borland® Enterprise Core Objects (ECO)™ technology in Borland® Delphi™ Architect

• Introduction 

• What is Modeling 

• The E!a"ple Application 

• #uilding the Application

• CoreClasses$nit%pas 

• ContactManagerEco&pace%pas 

• #uilding an ECO Model 

• Creating the Model 

• Adding a $ser Interface 

• 'unning the Application 

• (ersisting the data 

• Auto )or"s

• Conclusion 

• About the Author

Delphi 8 Architect ECO Tutorial 'roect

IntroductionEnterprise Core Obects !ECO". is a development and runtime framewor# for 0odel Driven Development$ The traditional process of transforming re1uirements to acomputer understandable view of the problem may involve the design of databases% applications% and interfaces each with its own way of representing the businesslogic$ ECO applies Obect Oriented fle2ibility and design to the business and persistence layers of your application ma#ing design and development easier$ 3t is worthspending time on this upfront because this is a huge part of the productivity enhancement you will e2perience when using the ECO architecture$

What is Modeling3 have mentioned 0odel Driven Development% but what is a model4 A model is a description or view of something$ 5i#e a model aircraft is a miniature representationof a real aircraft% a software model is a representation of the problem domain in which the software will run$ 3t is possible to generate many different models for aparticular software proect$ 'opular software engineering methodologies describe models and activities at various stages of the software development lifecycle$0odels also simplify communication between developers% users and other sta#eholders$ By creating the various types of models you can describe a comple2software system in a series of progressively more detailed set of views into the problem domain$

The problem with using models% in this way% is that% by the time you have increasingly refined a model to the point that it is completely unambiguous and e2ecutable%it no longer is recogni6able as a description of the original problem$ By the time we have converted a description of the problem progressively from te2t description tosource code and database schemas% only a developer !and the compiler" can understand it$ The problem with this is the transformation from business understandingto compiler understanding has to happen each time we modify the code$ And when we loo# at code written by others we need to convert it the other way% fromsource code to business logic$

ECO provides a way to remove the need to manually perform a lot of the transformation$ ECO allows the developer to model a problem in a way that more closelyrepresents the business logic% and is still unambiguous and e2ecutable$ This is often referred to as raising the level of abstraction$ By doing this% the ability to changeand understand comple2 software is made easier and less e2pensive$

*hen we create models in ECO the classes we model are often referred to as Business Classes or Domain Classes$ At runtime we refer to these as BusinessObects or Domain Obects$ The reason we use these names is because the classes directly represent entities in the problem domain of the business$ 7or e2ample%in a ,niversity enrollment application we may model the business classes tudent% Teacher and ubect$

The E!a"ple ApplicationThis tutorial will build a simple address boo# application that saves its data to an 905 file$ The basic needs for our application are(

• &tore contact infor"ation for people%

• &tore contact infor"ation for co"panies%

*e are going to implement the following ,nified 0odeling 5anguage. model for our address boo# application(

Page 2: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 2/17

3f you are not familiar with ,05% the diagram shows three classes% represented by the rectangles$ The class :Contact: although not mar#ed in the above diagram% isan abstract class$ The lines with the arrowheads indicate that both the :Company: and :person: classes descend from the :Contact: class$ The model shows thefollowing business rules(

• A Contact has a na"e* address and phone nu"ber%

• A Contact "ust be either a person or a Co"pany%

7or this e2ample 3 could have implemented the model using one class and a simple Boolean flag to indicate if the contact was a person$ 3 chose the above modelbecause in the ne2t tutorial we will e2tend the model and 3 also wanted this tutorial to demonstrate the basic generali6ation relationship$

#uilding the Application

• &elect +Other+ fro" the +)ile,e.+ "enu%

• )ro" the +e. Ite"s+ dialog* select +Delphi for %et (ro/ects+ and then +ECO Windo.s )or"s Application+% press the +O0+ button%

• The e. Application Dialog is displayed% Enter the na"e of the application% )or this e!a"ple use the na"e +ContactManager+ press the +O0+

button%

Borland Delphi creates a bare ECO application$ The ;'roect 0anager; !<iew='roect 0anager" shows the automatically generated files$ There are two files that aredifferent from a normal Delphi Application$ These are Contact0anagerEcopace$pas and CoreClasses,nit$pas$

Page 3: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 3/17

CoreClasses$nit%pasThis file contains an empty ;,05 pac#age;$ This is where the classes for our ECO application will be created by default$ 3t is possible to create multiple pac#ages%however% this tutorial will only use the default pac#age$

ContactManagerEco&pace%pasThis contains the ;Ecopace; for your application$ An Ecopace contains the obects of the application at runtime$ 3t provides the lin# between the obects and thepersistence mechanism !905 or /DB0"$ The Ecopace can be 1ueried using OC5 to retrieve obects from the Ecopace$

7rom the Borland Delphi help file(

;An ECO pace is a container of obects$ At runtime% the ECO pace contains actual instances of the classes in your model$ 3t is helpful tothin# of the ECO pace as an actual instance of a model% much li#e an obect is an instance of a class$ The obects contained in the ECOpace retain the domain properties !attributes and operations" and relationships defined in the model$

 As a container of obects% an ECO pace is both a cache% and a transactional conte2t$ *ithin the ECO pace% another component called apersistence mapper is used as the conduit between the persistence layer !either an /DB0 or 905 file"% and the instances of the classesdefined in the model$ *hen you configure an ECO pace using the 3DE% you will select those ,05 pac#ages in your model that you wish topersist in the ECO pace$;

#uilding an ECO ModelECO uses a subset of the ,nified 0odeling 5anguage !,05" as its modeling language$ The specific parts are the Class Diagram and Obect Constraint 5anguage!OC5"$

Creating the Model

7rom the ;0odel <iew; double-clic# the ;CoreClasses; diagram item$ This will open the modeling surface editor$ *hen this opens% the ;Tool palette; changes tocontain the tools for generating our model$

Begin by creating a new class$ >ou can do this one of three ways$

1% &elect the +Class+ tool in the +Tool palette+ and clic the "odeling surface%2% 'ight clic the "odeling surface and select Add,Class fro" the pop-up "enu%3% 'ight clic the "odeling surface and select +Add e. Ite"%%%+ fro" the pop-up "enu% &elect the Class Te"plate and press O0%

Once the class is created% ensure it is selected so the properties of the class are visible in the ;Obect 3nspector; elect the name property to ;Contact; and the Abstract property to ;True; Borland Delphi 8 will create a corresponding Delphi abstract class called Contact$

Page 4: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 4/17

/ight-clic# the class and select ;Add=Attribute;$ elect the attribute in the class with the mouse and the ;Obect 3nspector; will display the properties for the attribute$et this attribute:s name to ;full?ame; and type to ;tring;$

 Add the string attribute:s address and phone to the Contact class$ Add the class: person and Company to the model$ 5eave the abstract property false as these willbe the concrete classes we create instances of$

*e now need to create a generali6ation relationship between the person class and the Contact class$ A generali6ation relationship specifies that person is a type ofContact% and inherits all the attributes and operations of Contact$

To create this relationship select the ;@enerali6ation3mplementation; tool and select the person class and drag to the Contact class$

Create the same generali6ation relationship for the Company Class$ The completed model is below$

Page 5: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 5/17

3t is interesting to ta#e a loo# at the ;0odel <iew; now that we have added some classes$ The 0odel view shows the two models in the ECO Application$ TheDomain 0odel is the model we have ust created% the 3mplementation 0odel is auto generated by ECO$ The 3mplementation 0odel is created as Delphi classes$

The code generated by ECO shows the large amount of implementation detail that ECO ta#es care of for the developer$ This code allows for managing lists of eachdomain class% enumerator classes% adapter and all the management code for maintaining the obects within a running application$ ?ormally% the developer isresponsible for this code and it 1uic#ly turns a readable model from being a clear representation of the problem% into a mass of comple2 structures and architecturalelements unrelated to the real problem$

Adding a $ser Interface?ow that a model has been created% it is necessary to add a simple @,3 to e2plore the runtime behaviour of ECO$

OTE4 At this point in the e!ercise it is i"portant that you co"pile your application%

ECO needs to have the model compiled so the @,3 designer can display the model information$ The runtime system of ECO relies on the interrogation of the classesusing $?et /eflection$ 7or /eflection to wor# you must compile the application$

,sing the ;Tool palette; add the follow controls to the *in7orm$pas form$

• Category4 Windo.s5 )or"s add 2 #uttons%

• Category4 Data Controls add 3 Data6rids%

• Category4 Enterprise Core Ob/ects add 3 E!pression7andles%

et the following properties(

Type: Button  Name: btnAddPerson Type: Button  Name: btnAddCompany Type: ExpressionHandle  Name: ehContacts  Root: rhRoot  Expression: Contact.allinstances Type: ExpressionHandle  Name: ehPersons  Root: rhRoot  Expression: person.allinstances Type: ExpressionHandle  Name: ehCompanies  Root: rhRoot  Expression: Company.allinstances Type: Datarid  Name: d!Contacts  Data"ource: ehContacts

Page 6: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 6/17

 Type: Datarid  Name: d!Persons  Data"ource: ehpersons Type: Datarid  Name: d!Companies  Data"ource: ehCompany 

Enter the following code for the buttons OnClic# event code(

procedure T#in$orm.btnAddPerson%Clic&'sender: "ystem.(b)ect*e: "ystem.E+entAr!s,*

be!in

  Person.Create'Eco"pace,*end*

procedure T#in$orm.BtnAddCompany%Clic&'sender: "ystem.(b)ect*  e: "ystem.E+entAr!s,*be!in  Company.Create'Eco"pace,*end*

The /eferenceandle component% which was placed on the form by the ECO Application wi6ard% provides the lin# between the Ecopace and the *in 7orm$ A/eferencetandle can be set to reference a specific obect in an ECO pace or the entire ECO pace$ This is how the /eferenceandle is being used in thise2ample$ 3t is important to set the reference handle to use the ECO pace we have ust defined in our model% set the following parameter for the rh/oot component$

 Eco"paceType - Contactana!erEco"pace.TContactana!erEco"pace

The E2pressionandle is lin#ed to another handle% either an E2pressionandle or a /eferencehandle% and evaluates an OC5 e2pression to provide a resultingobect% collection or value$ 3t is possible to daisy chain E2pressionandles where each handle evaluates its result from the results of the previous handle$

'unning the Application/un the application and create some persons and Companies$

Page 7: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 7/17

The grid set to show ;person$allinstances; shows only the persons created$ The grid set to show ;Company$allinstances; show only the Companies created$ The gridset to show ;Contact$allinstances; shows both the 'ersons and the Companies$

(ersisting the Data An application li#e in this e2ample would generally be re1uired to save the entered data between each invocation$ *ith ECO there are two basic persistencemethods supported$ aving to a 905 file or saving to a /DB0$ 7or this e2ample an 905 file will be used% as it:s simpler to configure$

7rom the ;proect 0anager; double clic# Contact0anagerEcopace$pas to call up its Design Editor$ 7rom the ;Tool palette; select the :persistence0apper905; tooland drop it on the designer$ et the following properties(

Type: persistenceapper/01  $ileName: data.xml Type: Eco"pace  persistenceapper: persistenceapper/01

On the *in7orm$pas form add a new button$ ?ame it ;btnave; and set the te2t to ;ave;$ Add the following code to btnave OnClic# event handler$

procedure T#in$orm.btn"a+e%Clic&'sender: "ystem.(b)ect*  e: "ystem.E+entAr!s,*be!in  Eco"pace.2pdateDatabase*

end*

?ow when you run the application the data you enter will be saved to the data$2ml file each time you press the ;ave; button$

3t:s worth noting that there was no re1uirement within the model to specify information relating to how the data was going to be saved$ owever% this is possible ifre1uired$

Page 8: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 8/17

Auto )or"sECO supports the automatic generation of forms for editing your ECO Obects at runtime$ The default ECO enabled *in 7orm includes a ECOAuto7ormscomponent$ This component e2tends the data aware controls on your form to support double-clic# activation of the obects auto form$ et the auto form property ofall three grids to true$

 At runtime you can activate the auto form by double clic#ing the fi2ed column of any grid$

ConclusionECO offers a way to develop applications where the developer spends more time coding the business logic and less time on architectural coding$ This allows for thecode to be clearer and reduces the cost of change$ ECO provides a distinct separation between presentation% logic% and persistence$ This reduces the effect

changes have on an application$

Tutorial 2

Woring .ith Associations 

By Anthony /ichardson

Abstract - This article demonstrates accessing Borland® Enterprise Core Objects (ECO™) objects in code !ia handles" implementing relationships andusing master#detail style user inter$aces 

• Introduction 

• $sing the CurrencyManager7andle

• Adding a relationship 

• The relationship at .or 

• Conclusion 

• About the Author  

Delphi 8 Architect ECO Tutorial ) 

Page 9: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 9/17

Introduction 

3n Tutorial & !Borland Delphi. Architect ECO. Tutorial &"% a simple contact manager application was described and constructed$ That application will form thebasis for this tutorial$

$sing the CurrencyManager7andle3n Tutorial &% E2pressionandles were used to provide lists of the core obects in the ECOpace$. These lists were then connected to grids to display theinformation$ *hen it is necessary to determine which item in a list a user has selected% in an ECO application% you use a Currency0anagerandle$

The Currency0anagerandle is a component in the Enterprise Core Obects section of the toolbo2$ 3t will trac# the current selected item in a list$ On the *in 7orm of the application from tutorial &% place a Currency0anagerandle and another button as per the following figure$

et the following properties$

Type: Button  Name: btnDeleteContact  Text: Delete

Type: Currencyana!erHandle  Name: cmhContact  RootHandle: ehContact  Bindin!Context: d!Contact

3n the Clic# event handler for the Delete button place the following code

procedure T#in$orm.btnDelete%Clic&'sender: "ystem.(b)ect* e: "ystem.E+entAr!s,*+ar  "electedContact: Contact*be!in  i3 cmhContact.Element.As(b)ect is Contact then  be!in  "electedContact :- Contact'cmhContact.Element.As(b)ect,*  "electedContact.As4(b)ect.Delete*  end*end*

/un the application$ *hen you press the delete button% the currently selected contact in the contact datagrid is deleted$ Ta#e a closer loo# at the code in thebtnDeleteClic# method$

i3 cmhContact.Element.As(b)ect is Contact thenbe!in  ...

Page 10: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 10/17

end*

The conditional 37 statement accesses the Element property of the Currency0anagerandle$ The Currency0anagerandle$Element property is a reference to thecurrently selected item in the list$ The result is an 3Element$

The 3Element interface is the lowest common denominator for all possible obects that can be referenced by a handle$ All ECO obects% collections% and attributesmust implement 3Element$ The AsObect method of 3Element returns the Obect that is currently implementing the 3Element instance$

3n the above e2ample% the Obect:s class is being compared to the class Contact$ This is done using the 3 operator to ensure the Currency0anagerandle isreferring to an obect of the correct type$

"electedContact :- Contact'cmhContact.Element.As(b)ect,*

The remaining code is using a local variable of type Contact to hold a reference to the obect referred to by cmbContact$Element$AsObect$ The obect is being castas Contact because the previous 37 statement ensures only obects of class Contact will be e2ecuted by this code$

"electedContact.As4(b)ect.Delete*

 All classes generated by ECO implement the 3Obect interface$ 3Obect gives you access to manipulate the obect:s state in the ECO pace$ pecifically% the abovecode calls the Delete method to remove the obect from the ECO pace$ *hy not use the Destroy or Dispose methods4 imply because by calling Delete% the obecthas all its relationships deleted and is removed from the list of normally accessible obects$ owever% the obect has to stay in memory until the ne2t save operation%so ECO #nows to remove it from the database$ ,nli#e normal obects% which only have the one state !created"% ECO obects need to maintain their state while inmemory and while they e2ist in the database$

OTE4 eer call Destroy or Dispose on an ECO-controlled ob/ect9 al.ays use Delete to re"oe ob/ects you no longer re:uire%

Adding a relationship,p until now the application has been very basic$ owever% one of the most important aspects of ECO is its ability to manage relationships between obects$ ,singthe model surface% draw an association from 'erson to Company$

et the following properties$

Type: AssociationName: Employment

  End1.ultiplicity: 5..6

  End1.Name: employees  End7.Name: employer

This association allows our contact manager application to record the relationship of a company and its employees$ This simple process of drawing the associationhas resulted in ECO generating all the code to manage the relationship from both ends$ *hen you assign a company as an employer for a person% ECO will ensurethat the 'erson is automatically added to the employee collection for that company$ top and thin# about this$ ECO now handles all referential integrity aspects ofyour application:s relationships% both in memory and in the database$ A fair amount of architectural coding of a non-ECO application has ust been eliminated$ Theintelligent runtime systems in ECO will handle relationship navigation% caching% retrieval% and persistence$

0ultiplicity is the measure of the number of :connections: at the association end-point$ There are four basic options(

8 5..1: 9ero or one connection.8 1..1: ust ha+e one and only one connection.8 5..6: 9ero or many connections.

8 1..6: (ne or many connections.

The relationship at .orTo see how the relationship wor#s% it is necessary to modify the user interface$ The following steps will change the e2isting E2pressionandle% for the datagriddisplaying 'erson obects% to only display employees of the currently selected Company in the company datagrid$ Also% the button used to create new 'erson obectswill be changed to automatically add the new 'erson to the employee list of the currently selected company$ Because the model has been modified% it is necessaryto compile the application so the changes can be accessed by the @,3 controls at design time$

Page 11: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 11/17

OTE4 At this point in the e!ercise it is i"portant that you co"pile your application%

 Add a Currency0anagerandle for trac#ing the selected company$

Type: Currencyana!erHandle  Name: cmhCompany  RootHandle: ehCompanyBindin!Context: d!Company

?ow modify the OC5 e2pression and root handle used for defining the person list$

Type: ExpressionHandle  Name: ehPerson  RootHandle: cmhCompanyExpression: sel3.employees

Changing the root handle for eh'erson to reference the new cmhCompany handle causes the handle to evaluate its e2pression against the currently selectedCompany$ This is called chaining e2pressions$ Each e2pression evaluates against the result of the previous e2pression$ This is an e2tremely powerful capability ofECO$ The e2pression ;employees; causes the eh'erson handle to now contain a list of all employees of the selected Company$ The ECO runtime systemautomatically handles retrieving the obects from the database without developers needing to concern themselves with how the data is retrieved$ This simplifies thecode dramatically for comple2 applications$

Before running the application% we need a way to create the association between a 'erson and a Company at runtime$ To do this% change the Clic# event for thebtn'erson button to the following code(

procedure T#in$orm.btnAddPerson%Clic&'sender: "ystem.(b)ect* e: "ystem.E+entAr!s,*+ar  NeEmployee: Person*  "electedCompany: Company*be!in  i3 cmhCompany.Element.As(b)ect is Company then  be!in  "electedCompany :- Company'cmhCompany.Element.As(b)ect,*

  NeEmployee :- Person.Create'Eco"pace,*  NeEmployee.employer :- "electedCompany*  end*end*

The code used to e2tract the selected Company is similar to the code used earlier$ The code used to assign the relationship in the Clic# event is the interesting part$

  NeEmployee.employer :- "electedCompany*

The process of using relationships in ECO is as simple as assigning the Company obect to the employer relationship of the 'erson obect$ ;o what4 That:s howDelphi handles all class relationships%; you may say$ E2cept in ECO% the relationship is bi-directional$ ?ot only has the Company been assigned to the'erson$employer role% the 'erson has been added to the Company$Employees role$ This relationship is enforced and maintained by the ECO runtime system$

 Alternatively% the following code could have been used$ The result is ust the same% however the association is completed in code from the other end$ The highlightedline shows the changed code$

procedure T#in$orm.btnAddPerson%Clic&'sender: "ystem.(b)ect* e: "ystem.E+entAr!s,*

+ar  NeEmployee: Person*  "electedCompany: Company*be!in  i3 cmhCompany.Element.As(b)ect is Company then  be!in  "electedCompany :- Company'cmhCompany.Element.As(b)ect,*

  NeEmployee :- Person.Create'Eco"pace,*  "electedCompany.employees.Add'NeEmployee,*  end*end*

/un the application% select a company and add a 'erson% select another company and add more 'erson obects$ As you change between Company obects you willsee the 'erson data grid change to show only the employees for that company$

ConclusionThe ECO runtime system provides an incredibly powerful system for managing obects$ 7rom managing obect lifecycles to relationships% and OC5 evaluations% theburden on developers to provide this functionality is removed$ This allows developers to concentrate on developing business solutions rather than architecturalframewor#s$

Page 12: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 12/17

Tutorial 3

$sing #orland5 Enterprise Core Ob/ects ;ECO<= .ith DatabasesBy Anthony /ichardson

 Abstract - This article demonstrates connecting a Borland® Enterprise Core Objects (ECO™) application to a %elational Database &anagement 'ystem(%DB&') and managing changes to the object space

• Introduction 

• $sing ECO .ith databases 

• Modifying the application to use Microsoft &>? &erer 2@@@ 

• Creating a blan database 

• I"proing the database application 

• Woring .ith transactions 

• I"ple"enting Ob/ect &pace transactions 

• &eparating the Ob/ect &pace and Database Transactions 

• Analying the &>? created by ECO 

• Conclusion 

Borland Delphi. 8 Architect ECO Tutorial + 'roect

Introduction

3n tutorial ) a simple contact manager application was described and constructed$ That application will form the basis for this tutorial$

3n the previous tutorial% the application had been persisting data to an 905 file$ Although this is fine for the simple applications used in the tutorials% it is hardly arobust data storage solution for enterprise applications$ 7or that reason% included with Delphi is support for Borland Data 'roviders for ADO$?ET with high-performance% seamlessly ;switchable; remote enterprise providers for Borland 3nterBase% Oraclei%. 3B0 DB)% and 0icrosoft 5 erver. )FFF$

ECO applications access databases using persistence mapper components$ These components act as bridge between the ECO pace and specific data accesscomponents of the 0icrosoft $?ET 7ramewor#$

$sing ECO .ith databasesECO is natively designed to use /DB0 as its primary choice of obect storage$ ECO handles the generation of the database schema% storage% and retrieval ofapplication data% as well as maintaining database integrity by using transactions$

This tutorial focuses on converting the previous tutorial application from using an 905 file to using a database$ Then% this tutorial e2amines how to manage thechanges to obects and update the database$

Modifying the application to use Microsoft &>? &erer 2@@@3n Delphi% open the Contact 0anager application from the previous tutorial$ ,sing the 'roect 0anager% open the Contact0anagerEcopace$pas file and ensure thatthe ;Design; tab is selected in the editor$ The  persistenceMapperXML1 component should be visible on the design surface of the ECO pace$

Delete the  persistenceMapperXML component and place a  persistenceMapperSqlServer  component% from the Enterprise Core Component category% on the designsurface$ Add a sqlConnection component from the Data Controls category$

Page 13: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 13/17

et the following parameters(

Type: persistenceapper";l"er+er

  Name: persistenceapper";l"er+er1  Connection: s;lConnection1 Type: s;lConnection  Name: s;lConnection1  Connection"trin!: 4nitial Catalo!-Contactana!er*Data "ource-localhost*4nte!rated"ecurity-""P4* Type: Contactana!erEco"pace  Persistenceapper: persistenceapper";l"er+er1

?OTE( Don:t forget to set the ECO paces 'ersistence0apper property to the new persistence mapper component$ Access this by clic#ing in the blan# area of thedesign surface$

This completes the re1uired programming changes necessary to change the application from using a 905 file to using 0icrosoft 5 erver$

The connection string ;4nitial Catalo!-Contactana!er*Data "ource-localhost*4nte!rated"ecurity-""P4* ; instructs ECO to connect to the database ;Contact0anager; on 0icrosoft 5 erver running on the local machine$ owever% because

the database ;Contact0anager; does not e2ist% it must be created$

Creating a blan databaseECO can generate the database schema for the application% but it re1uires a blan# database to which to connect$ ,sing 5 erver Enterprise 0anager% connect toyour local server% and create a new database called ;Contact0anager;$ !The tutorial assumes you are running 0icrosoft 5 erver on the same machine asDelphi$ 3f this is not the case% you must modify the connection string as appropriate"$

Page 14: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 14/17

On the bottom left corner of the design surface for the ECO pace% there is a Create Database button$ Clic# this button$ A dialog bo2 appears showing a list of tablesthat must be deleted andor recreated$ This list will be empty for the first schema generation$ Clic# OG to proceed with the schema generation$ 3f the databasecontains any data% that data will be lost$

The Delphi message window indicates the result of the process$

3f you run the application% it will now save and retrieve data from the 0 5 erver$

I"proing the database application>ou might have noticed that the current application cannot cancel changes that have been made$ Although we would li#e to thin# that users never ma#e data-entryerrors or change their minds% the reality is that the ability to cancel changes is an e2pected feature of database applications$

To facilitate this new functionality a main menu must be added to the application and the current save action moved to the menu$ Add a 0ain 0enu component to the*in7orm$

Page 15: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 15/17

,se the in-place menu editor to add the following menu items(

Type: "ystem.#indos.$orms.enu4tem  Name: mnuDatabase  Text: Database

Type: "ystem.#indos.$orms.enu4tem  Name: mnu"a+eChan!es  Text: "a+e Chan!es

Type: "ystem.#indos.$orms.enu4tem  Name: mnuCancelChan!es  Text: Cancel Chan!es

Type: "ystem.#indos.$orms.enu4tem  Name: mnuDi+ider1  Text: <

Type: "ystem.#indos.$orms.enu4tem  Name: mnuenerate"chema  Text: enerate "chema

Create the following ;Clic#; events for each menu item$

procedure T#in$orm.mnu"a+eChan!es%Clic&'sender: "ystem.(b)ect*e: "ystem.E+entAr!s,*

be!in  == "a+e all chan!es in the ob)ectspace  == to the database  Eco"pace.2pdateDatabase*end*

This is the same code as the previous save method$

procedure T#in$orm.mnuCancelChan!es%Clic&'sender: "ystem.(b)ect*e: "ystem.E+entAr!s,*

be!in  == 0oop throu!h all chan!es to the Eco"pace and  == undo the chan!e.  hile Eco"pace.2ndo"er+ice.2ndo0ist.Count > 5 do  be!in  Eco"pace.2ndo"er+ice.2ndo0atest*  end*end*

Page 16: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 16/17

The menuCancelChangesClic#!" event adds support to discard changes that have occurred in the obect space$ 3t is possible in ECO to create multiple chec#points for undo operations and the above method ensures that all changes since the last database update are undone$ ,ndo will be covered in more detail in futurearticles !although it is not difficult to wor# out by loo#ing at the 3,ndoervice interface"$

3t is also possible to generate the database schema using code$ Add the following method to the Contact0anagerEcopace class in Ecopace$cs

procedure TContactana!erEco"pace.enerate"chema*be!in  sel3.persistenceapper";l"er+er1.CreateDataBase"chema*end*

Enter the following code in the clic# event handler for the ;@enerate chema; menu item$

procedure T#in$orm.mnuenerate"chema%Clic&'sender: "ystem.(b)ect* e:"ystem.E+entAr!s,*+ar  "a+ed"tate: Boolean*be!in  "a+ed"tate :- Eco"pace.Acti+e*  i3 "a+ed"tate then  be!in  == All chan!es must be sa+ed be3ore  == closin! Eco"pace.  Eco"pace.2pdateDatabase*  Eco"pace.Acti+e :- 3alse*  end*  == enerate the database schema  Eco"pace.enerate"chema*  == Restore the acti+e state o3 the Eco"pace  Eco"pace.Acti+e :- "a+ed"tate*end*

'ressing this menu item causes ECO to regenerate the database schema% which destroys all data saved in the database$

/emove the ave button and its event handler% as they are no longer re1uired$ The menu item ust created now performs this duty$

3f you run the application% you will see that it is possible to cancel any pending changes% reverting the application state to what is was after the last database update$

The conversion is now complete$ The application uses 0icrosoft 5 erver )FFF as its storage mechanism instead of 905 files$ *hen the application runs it willconnect to 0icrosoft 5 erver and store and retrieve all data from the ;Contact0anager; database$ ECO automatically converts the OC5 e2pressions to 5%eliminating the need for the developer to #eep changing between the problem domain model and the relational database storage format of the application:s data$

Woring .ith transactions

*hen you call Eco"pace.2pdateDatabase % ECO starts a database transaction% sends one or more 5 re1uests to the server% and then commits

the transaction$ 3f an error occurs during the transaction% the ECO pace reflects the state of the application before the ,pdateDatabase operationH that is% theunsaved changes will still e2ist and still re1uire saving$

This level of transaction support might not be sufficient for your needs$ 7ortunately% support for transactions in ECO e2tends beyond updates to the database$ ECOprovides its own mechanism for encapsulating changes that occur within the ECO pace$ These transactions are native ECO transactionsH however% during adatabase update% ECO also wraps all database changes within a database transaction$

I"ple"enting Ob/ect &pace transactions

3mplementing transactions in an ECO pace is simpleH there are only three method calls$

42ndo"er+ice."tartTransaction*42ndo"er+ice.CommitTransaction*42ndo"er+ice.Rollbac&Transaction*

3f you are familiar with how database transactions wor#% then the operation of the above methods will be obvious$ ,se "tartTransaction* to begin a

transaction$ ECO specifically trac#s all changes made to the obect space from the start of transaction until a transaction is completed$ A transaction can be

completed in one of two ways$ By calling CommitTransaction*  all the trac#ed changes will be applied to the obect space as a single undoable event$ 3f 

Rollbac&Transaction*  is called% then all the changes since the start of the transaction will be lost% and the obect space reverts to how it was before

the transaction started$

3t is important to use transactions in a way consistent with how Borland designed them$ Transactions are designed to be short lived and should be used in a mannersimilar to the following code$

Eco"pace.2ndo"er+ice."tartTransaction*try  == Code that does stu33 here  Eco"pace.2ndo"er+ice.CommitTransaction*

Page 17: Delphi 8 Tutorial

8/10/2019 Delphi 8 Tutorial

http://slidepdf.com/reader/full/delphi-8-tutorial 17/17

except  Eco"pace.2ndo"er+ice.Rollbac&Transaction*  raise*end*

ECO will raise an e2ception if you call commit or rollbac# without a transaction active$

The transaction A'3 specifically does not include a method to chec# whether a transaction is active or not$ This is by designH the state of a transaction should beimplicit in the code$ The above e2ample is li#e thatH #eeping the transaction methods calls together in an e2ception-handling framewor# implicitly controls thetransaction state$

3n the previous paragraphs the ground rules for using transactions were laid out$ Geep them short-lived and #eep the state implicit by the design of the code$ To #eepthem short-lived means that the duration of the transaction must be relatively discernable from the code$ To achieve both goals generally re1uires ensuring that nouser interactions occur while a transaction is active$ Although ECO can handle user interactions during an active transaction% there are reasons to avoid them$

*hen a transaction is active% the undo mechanism of ECO is not used$ This is an all- or-nothing approach to obect space changes$ 3f you commit a transaction% allchanges are applied$ Conversely% if you roll bac# a transaction% all changes within the transaction are lost$ >ou cannot undo individual changes within a transaction$3n fact% when you ma#e changes outside of a transaction% ECO creates a small transaction for each of those changes$ The result is that when you do bul# obectspace changes% many transactions are being started and committed$ 3f the bul# update is placed within a single transaction% these smaller transactions will not occur%and ECO will perform changes to the obect space much faster$

TI(4 When perfor"ing bul changes to the ob/ect space* use transaction to speed up the ti"e it taes to apply the changes%

&eparating the Ob/ect &pace and database transactions*hen you call ;Commit Transaction;% the transaction is committed to the ECO pace only$ Calling ;Cancel Changes; will rollbac# any changes that occurred in thetransaction% even if the transaction is committed$

 At first this seems strange% but it is done for a reason$ The concepts of the ECO pace and data storage are two separate concerns$ Transactions concernthemselves purely with the obect space and persistence operations concern themselves only with the database$ The separation is necessary because transactionswor# on all ECO obects% even transient obects$ ECO applications have no specific re1uirement to even use a database$

Analying the &>? created by ECO As mentioned% all update operations to the database are wrapped in database transactions$ 3t is possible to monitor all operations the ECO application performs onthe database by using the 5 profiler application included with 0icrosoft 5 erver$ The lin# to the 'rofiler application is in the 0icrosoft 5 erver folder of thestart menu$

The following screen shot shows a save of a new person obect to the database$ The analy6er application shows the transaction and 5 commands re1uired toperform the update$

ConclusionThe layered architecture of ECO ma#es it simple to change the storage mechanism used to persist data$ The layered architecture also provides a separation ofconcerns between changes made to the obect space and changes made to the database data$

About the Author  Anthony /ichardson is the director of <iewpoint !A" 'ty 5td$ Anthony has many years of e2perience wor#ing with Borland 0DA technologies$ Anthony:s contactdetails are available at http(www$viewpointsa$com$