0% found this document useful (0 votes)
7 views

asta3Tutorials

Uploaded by

vishal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

asta3Tutorials

Uploaded by

vishal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

ASTA 3 Tutorials

© 1997-2002 ASTA Technology Group Inc


ASTA SkyWire

Wireless Enabled Web Services and Collaborative Tools

by ASTA Technology Group

ASTA Skywire supports cross platform clients and server to


allow for developers to create fast, reliable and secure
applications that run over any network.
ASTA 3 Tutorials

© 1997-2002 ASTA Technology Group Inc

All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or
mechanical, including photocopying, recording, taping, or information storage and retrieval systems - without the
written permission of the publisher.

Products that are referred to in this document may be either trademarks and/or registered trademarks of the
respective owners. The publisher and the author make no claim to these trademarks.

While every precaution has been taken in the preparation of this document, the publisher and the author assume no
responsibility for errors or omissions, or for damages resulting from the use of information contained in this document
or from the use of programs and source code that may accompany it. In no event shall the publisher and the author be
liable for any loss of profit or any other commercial damage caused or alleged to have been caused directly or
indirectly by this document.

Printed: March 2004 in Boise, Idaho USA

Special thanks to:

All the ASTA users around the world in over 80 countries. Great
users make great products!
I ASTA 3 Tutorials

Table of Contents
Foreword 1

Part I ASTA 3 Help Tutorials 3


1 New User Jump
...................................................................................................................................
Start 4
No Code Thin Client
... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ................ 4
No Code Updates
... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ................ 5
Almost No Code
... ...
Transactions
.... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ................ 6
2 DataSets- In Memory
................................................................................................................................... 7
Master Detail ... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ................ 7
Indexes ... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ................ 9
Create Fields ... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ................ 9
Add a Calculated
... .... ... ....Field
... .... ....
at ...
runtime
.... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 10
3 Client Side SQL
................................................................................................................................... 10
Aggregates . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 12
AutoInc Refetches
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 13
CachedUpdates
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 13
Constraints . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 14
Indexes . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 14
MasterDetail . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 14
PacketFetches. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 15
Sorting . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 16
SuitCase . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 17
Transactions . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 17
4 Messaging and
...................................................................................................................................
File Transfer 17
Instant Messaging
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 18
CodedParamList . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 21
CodedDBParamList
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 22
PackingUpData . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 22
DataSetParamList
... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 23
DataSetPackup
... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 23
Large FileTransfer
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 24
Standard ... Messaging
.... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 24
Server to ...Client
.... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 25
Client to Server
... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 27
RemoteDirectory. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 29
5 Server side Techniques
................................................................................................................................... 29
Provider Text. ...
file
....Updater
... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 29
ServerMethod. ...Param
.... ... ....Example
... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 31
Threaded Server
. ... ....with
... ....No
... ....Database
.... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 32
6 Feature Testers
................................................................................................................................... 34
DataSetQA . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 34
ProviderTester
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 36
ServerMethodTester
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 37
SQLDemo and . ...Http
.... ... Tunneling
.... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 38
SQLExplorer . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 39
7 Authentication
...................................................................................................................................
and Security 40
Login . ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 40

© 1997-2002 ASTA Technology Group Inc


Contents II

SkyWire Emulator
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 42
StatelessAuthentication
. ... .... ... .... ... ....
and .... Cookies
... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 44
Set Up ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 45
ClientSide... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 45
Client Side... Discussion
.... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 46
ServerSide ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 47
Server Side... ....
Discussion
... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 48
DatabaseSetup
... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 48
Blocking Example
... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 48
8 Protocols and
...................................................................................................................................
Firewalls 49
9 Database Servers
................................................................................................................................... 50
DatabaseServers.ADO
. ... .... ... .... ... .... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... .... .... ... .... ... .... ... .... ... ............... 50

Index 0

© 1997-2002 ASTA Technology Group Inc


1 Foreword

ASTA Hitchhiker's guide to the wireless


universe
Run over any TCP/IP connection and be able to disguise yourself as http at anytime.

Have a middleware server that supports ASP and Peer to Peer.

Be aware that the most precious resource is bandwidth.

Provide XML Support.

Provide Compression Options out of respect for #2.

Support Web Services on both client and servers.

Provide Encryption Options to be able to operate securely.

There shall be no administration required (Zero Admin rule).

Authenticate at the server by username and password and be able to uniquely identify
remote devices.

Once a client app is deployed it should be able to update itself automatically and
efficiently.

Be able to work connected and disconnected with sync technology to bridge those
states.

Work with the most popular Development tools.

Work with any Database, on any Platform and provide a way to move data between any
database and any device.

Have a component architecture so that the same techniques can be used cross
platform

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Tutorials

Part

I
3 ASTA 3 Tutorials

1 ASTA 3 Help Tutorials

Welcome to the ASTA 3 Help Tutorials. These are documented tutorials that included new user jump
start, to file sends to server techniques with non-database servers showing how to use Providers and
ServerMethods. A Current version of these tutorials can always be found on line

There are also additional ASTA Code examples available for download. These consist of over 100
code examples we have sent to ASTA users over the years. We plan to take each one of these and
document it and move it into these formal ASTA Help tutorials. Contact ASTA if you require an
example and we will try to supply you what you need.

Source for ASTA database servers are available for download. These tutorials reference the
Asta3ADOServer.

This help file has links that jump to the ASTA main help file which you should have installed. A current
version
ASTA 3 Help is always available for download in windows Help format or a PDF.

Some of these tutorials include their own servers, others use standard ASTA servers to run.

You can view the tutorials in several groups.

New User Jump Start Get going fast with fetching Data over the internet
AstaDataSets In memory Datasets
AstaClientDataSets In Memory DataSets that communciate with a remote
server. These tutorials require an ASTA Server to be
running
Messaging ParamList Messaging and File Transfer Examples
Server Side Techniques Shows how to use TAstaProviders and ASTA Server
Methods using the TAstaBusiness Objects Manager
to implement "Business Logic" on the Middle Tier
Feature Tests Shows some examples of how to take inventory of
ASTA server components from remote clients with
ServerMethod Testers, Provider Testers, SQL Demo
clients and the AstaSQLExplorer
Authentication Shows demos of how to secure ASTA servers and
use the Authentication routines available from ASTA
clients including tcp/ip and
http stateless authentication.
Protocols and firewalls ASTA clients can run tcp/ip, http with winInet or in
blocking mode. This demo shows how to try everyone
and switch back and forth between protocols.

Note: Delphi 6 contains a new property on PageControls that Delphi 5 does not have. We have tried to
make sure that we don't save any forms with page controls with Delphi 6 but if you get a Property not
found error, just ignore it and save the form and the demo will run fine.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 4

1.1 New User Jump Start


For new ASTA users we suggest you start with running pre-compiled Servers. There are several ASTA
servers available for you to run like the Asta3ADOServer.exe, Asta3BDEServer.exe,
Asta3IBobjectsServer.exe and about 28 others!

These starter tutorials use ClientSideSQL. For experienced N Tier Users we still suggest you run an
existing compiled ASTA server and get a feel for ClientSideSQL running over the Internet. You can
move all your "Business Logic" to the Middle Tier with ASTA quite easily using TAstaProviders and
ServerMethods using the TAstaBusinessObjects Manager. Jump to the
Server Side Technique tutorials to see how easy coding a server can be.

NoCodeThin Client Write a thin client datbase application with no code


No Code Updates Write a thin client datbase application with no code
that handles updates also
Almost No Code Transactions We need one line of code to call ApplyUpdates so
changes will be fired in a transaction in one server
round trip

1.1.1 No Code Thin Client


Requires
Any ASTA database server to be running.

Description
This is our traditional ASTA starting tutorial to show how easy it is to write a thin client
application that runs over the internet with no code.

1. Start an ASTA Server.


2. Drop an AstaClientSocket on a Form
3. Drop an AstaClientDataSet on a form.
4. Drop a DataSource and Grid on the form and hook them up so the grid will show
when the dataset populates.
5. With the AstaClientDataSet write some SQL like Select * from Customers.
6. Set the AstaClientDataSet.Active property to true and you will see data populate in
the grid and on the ASTA server you will see the client request.
7. Run the program. You have just written a program that will run over the internet
with no code.

Comments
When writing any client server application, you should adhere to good "Client Server
Manners" which means that you should 'Only Fetch What you need When you need it".
This means that for the most part you should not be writing SQL like Select * from
MyTable but to limit the number of fields and also to add a where clause to limit the
amount of data coming over the wire.

© 1997-2002 ASTA Technology Group Inc


5 ASTA 3 Tutorials

1.1.2 No Code Updates


Requires
Any ASTA database server to be running.

Description
ASTA was designed so you only need write Select SQL, either on the client with ClientSide SQL or on
the Server with TAstaProviders and Servermethods. ASTA can generate all update, insert and delete
SQL for your application.

Starting with the NoCodeThin Client demo, set the EditMode property of the AstaClientDataSet to
AfterPost. To do this you will need to make sure you set the UpdateTableName property and the Prime
Key Fields. Below is the Design time EditMode property Editor from the AstaClientDataSet.

Note: This example is shows data from an Interbase Server and Afterpost EditMode will not use a
transaction. So for true client/server databases we recommend using Transactions for all SQL posting
changes to remote servers. For that you do need to write one line of code to call ApplyUpdates, which
is illustrated in the one line of code used in the AlmostNOCodeTransactions tutorial.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 6

1.1.3 Almost No Code Transactions


Requires
Any ASTA database server to be running.

Description
This builds on the No Code Thin Client and No Code Updates examples. With Client
Server Databases Transactions are always recommended. So write some Select SQL and
click on the TAstaClientDataSet.Editmode property to change the UpdateMethod to
Cached Updates.

After some inserts, edits or deletes then just write this one line of code

procedure TForm1.Button1Click(Sender: TObject);


begin
AstaClientDataSet1.ApplyUpdates(usmServerTransation);
end;

Here is what happens next:

1. Generate SQL for all insert, updates and deletes


2. Transport it to the server.
3. Start a Transaction on the server.
4. Exec Each line of SQL Generated
5. Rollback the Transaction if any Fail and raise an Exception on the client

© 1997-2002 ASTA Technology Group Inc


7 ASTA 3 Tutorials

6. Commit if there were no exceptions raised by the Database


7. Return to the Client and Clear out the OldValuesDataSet.

1.2 DataSets- In Memory


TAstaDataSets

Create Fields at runtime


Indexes
Master Detail

1.2.1 Master Detail


Shows how to use masterDetail with an in memoryDataset and to flip back and forth
between master/detail support with setting and clearing the master fields property.

AstaClientDataSets typically implement master/detail using a Parameterized Query on


the Detail DataSet. As the master rows are changed new queries are sent to the server.
ASTA also provides a way to query all the detail for all the master rows and to use a local
filter to implement master detail. There are helper calls to toggle back and forth between
"connected" master/detail and disconnected Master/Detail.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 8

procedure TForm1.ButtonClick(Sender: TObject);


begin
with DetailDataSet do
if Button.tag=0 then begin
SetToDisconnectedMasterDetail( 'Select * from orders order by orderno','CustNo');
Button.Tag:= 1;
Button.Caption:= 'Set to run Master Detail from Server';
end else begin
SetToConnectedMasterDetail( 'SELECT * From ORDERS where Custno=:CustomerNumber');
Button.Caption:= 'Set to run Master Detail Locally';
Button.Tag:= 0;
end;
end;

© 1997-2002 ASTA Technology Group Inc


9 ASTA 3 Tutorials

1.2.2 Indexes
TAstaDataSets support indexes so you can use the standard Delphi TTable calls like SetRange and
FindKey. Additionally, any calls to Locate will use an existing Index so that lookups are optimized.

The Index Tutorial shows examples of using TAstaDataSet index methods.

if an index is addedwith no fieldname it will index on the bookmark. To addindexes with


code shortcuts use

procedure AddIndexFields(TheIndexName: String;Const FieldNames:Array of String;Const


Descending:Array of Boolean);
procedure AddIndex(FieldName:String;Descending:Boolean);

Below shows code to add indexes the traditional way.

AstaDataSet1.Active := True;
Listbox1.items.Add('<not sorted>');
with AstaDataSet1 do begin
Indexes.Clear;
with Indexes.Add do begin
Name := 'Country' ;
Fields:='Country' ;
Active := True;
Listbox1.items.Add(Name);
end;
with Indexes.Add do begin
Name := 'Branch' ;
Fields:='branch' ;
Active := True;
Listbox1.items.Add(Name);
end;
with Indexes.Add do begin
Name := 'Sequence';
Fields := 'Sequence';
Options := [ioUnique];
Active := True;
Listbox1.items.Add(Name);
end;
with Indexes.Add do begin
Name := 'Transaction_Id' ;
Fields := 'Transaction_Id' ;
Active := True;
Listbox1.items.Add(Name);
end;
end;

end;

1.2.3 Create Fields


Description

AstaDataSets are in memory Datasets that can be configured to use any Delphi type of DataType by
using the FieldsDefine property at design time or at runtime. CreateFields shows how to use the
FastFieldDefine call to add fields and also to add Calculated Fields at runtime .

FastFieldsDefine

To add fields at runtime use FastFieldsDefine. If the Dataset was created and fields are being added
the first time, you do not have to call NukeAllFieldInfo but if you are re-suing the DataSet call
NukeAllFieldInfo to clear out all field information.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 10

with AstaDataSet1 do
begin
close;
nukeallFieldInfo; //only needed if you are going to recreate it again
FastFieldDefine( 'Name', ftstring, 25);
FastFieldDefine(FormatDatetime( 'tt', now), ftinteger, 0);
FastFieldDefine( 'Date', ftdatetime, 0);
FastFieldDefine( 'Age', ftinteger, 0);
Open;
end;

1.2.3.1 Add a Calculated Field at runtime

Description

When you right mouse from design time in Delphi on a Dataset you are presented with
the fields editor and can create PersistentFields at design time. when you want to do the
same at runtime, you need to make the fields persisent. Below is an example of using the
MimicTableandMakeFieldsPersistent method from AstaFieldandStream.pas to accomplish
this.

var
CalcField: TStringField;
begin
with AstaDataSet1 do begin
close;
NukeAllFieldInfo;
with FieldDefs do
begin
Add('Test', ftString, 25, false);
Add('Name', ftstring, 25, True);
Add('Date', ftDateTime, 0, False);
Add('Age', ftinteger, 0, False);
Open;
end;
if not CalcFieldCheckBox.Checked then exit;
//this next call is like right mouse at design time and adding fields
MimicTableAndMakeFieldsPersistant(AstaDataSet1, False);
CalcField := TStringField.Create(self);
CalcField.FieldKind := fkCalculated;
CalcField.Size := 20;
CalcField.FieldName := 'CALC';
CalcField.DataSet := AstaDataSet1;
AstaDataSet1.Open;
end;
end;

1.3 Client Side SQL


AstaClientdatasets descend from TAstaDataSets and are in memory DataSets that
communicate with remote servers via the TAstaClientSocket.These tutorials show how to
use the various methods and properties of the AstaClientDataSet.

Aggregates
Cached Updates
Constraints
Indexes
Master Detail
Packet Fetches
Sorting
SuitCase

© 1997-2002 ASTA Technology Group Inc


11 ASTA 3 Tutorials

Transactions

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 12

1.3.1 Aggregates
Requires

Asta3BDEServer to be running

Description
Use Aggregates to define aggregates that summarize the data in the client dataset.
Aggregates is a collection of TAstaAggregate objects, each of which defines a formula for
calculating an aggregate value from a group of records in the client dataset. The
individual aggregates can summarize all the records in the client dataset or subgroups of
records that have the same value on a set of fields. Aggregates that summarize a
subgroup of records are associated with indexes, and can only be used when the
associated index is current.

This example shows how to define an Aggregate called GrpCnt.

procedure TForm1.FormCreate(Sender: TObject);


begin
with AstaClientDataSet1 do begin
Indexes.Clear;
with Indexes.Add do begin
Name := 'BMK';
Active := True;
end;
with Indexes.Add do begin
Name := 'Company' ;
Fields := 'Company';
Options := [ioDescending, ioUnique, ioNatural];
Active := True;
end;
with Indexes.Add do begin
Name := 'TaxRate' ;
Fields := 'TaxRate';
Active := True;
end;
with Indexes.Add do begin
Name := 'CustNo' ;
Fields := 'CustNo';
Options := [ioUnique];
Active := True;
end;
with Indexes.Add do begin
Name := 'State';
Fields := 'State';
Options := [];
Active := True;
end;
end;
AstaClientDataSet1.IndexName := 'State';
with AstaClientDataSet1 do begin
Aggregates.Clear;
with Aggregates.Add do begin
Name := 'GrpCnt' ;
AggKind := akCount;
IndexName := 'State';
Level := 1;
Active := True;
end;
end;
LoadIndexes;
ListBox1.ItemIndex := 1;
ListBox1Click(nil);
LoadAggs;
ListBox2.ItemIndex := 0;
ListBox2Click(nil);
end;

© 1997-2002 ASTA Technology Group Inc


13 ASTA 3 Tutorials

1.3.2 AutoInc Refetches


Requires

This requires an ASTA Database server and the demo works with ADO with sql server or access or
BDE and Paradox. It includes a create table script in order to simulate the AutoIncrement. With
Interbase a generator would need to be defined along with an Insert Trigger.

Description
When you utilize ASTA's ability to automatically generate SQL, ASTA generates SQL for all the fields
including your database's auto increment fields, but the auto increment field must not appear in Update
or Insert statements, those values must be assigned by the database itself. Specifying the auto
increment field in the AstaClientDataSet's AutoIncrementField property allows you to overcome this
problem. When you specify the AutoIncrement field, ASTA does not include that field when it generates
Update or Insert statements. The proper SQL is generated for the remaining fields and the database
correctly assigns the auto increment value. If there are other fields that you do NOT want ASTA to
include in Insert or Update statements, mark them as read only.

This demo creates a table called AutoInctest

1.3.3 CachedUpdates
Requires

AstaBDEServer to be running

Description
ASTA was designed so that you only need write Select SQL and not have to write SQL for inserts,
updates or deletes as ASTA will generate SQL for you. This way you only have to worry about
populating DataSets by using either ClientSide SQL, TAstaProviders or ServerMethods with the
TAstaBusinessObjectsManager.

Cached Updates are the recommend way to post changes to remote ASTA servers. When you run this
demo, just edit a couple of rows and you will see the OldValuesDataSet that the AstaClientDataSet
creates internally. By tracking changes, the AstaClientDataSet can support RevertRecord and
CancelUpdates.

In normal client server programming, to post changes to a server you start a transaction, ExecSQL and
then Commit or Rollback as appropriate. When AstaClientDataSets you need only set the EditMode to
Cached and then call ApplyUpdates(usmServerTransation) and ASTA will generate all the SQL for
you, go to the server, Start a transction and Commit or Rollback as appropriate. All in one server round
trip.

In order to see the actual AstaClientDataSet.OldValuesDataSet, you merely need to set up a grid and
DataSource and set it at runtime in the AstaClientDataSet.AfterPost event.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 14

1.3.4 Constraints
Requires
AstaBDEServer to be running

Description
Using ASTA Expressions you can define:

Custom/Imported constraints for each TField (field level)


These constraints will fire each time, when a new value is assigned to a TField. If a constraint is
violated, an exception will be raised and no update to the TField will happen.

Custom/Imported constraints for TAstaDataSet


Constraints (record level). These constraints will fire each time, when a TDataSet.Post will occur. If the
constraint is viloated, then no Post will happen.

DefaultExpression for each TField


This expression will be evaluated when a new record is created (Insert / Append) and the result will be
assigned to TField.

Calculated field using DefaultExpression


The TField value will be calculated using this expression.

Expression language is the same as it is described in Delphi Help topic TClientDataSet.Filter

This demo works with DBDEMOS:Orders table. There are:


- a few record level constraints
- a few field level constraints
- a calculated by expression field AmountNotPaid

1.3.5 Indexes
Requires

AstaBDEServer to be running

Description

AstaClientDataSets support Indexes and Aggregates as they descend from the full featured
TAstaDataSet This tutorial shows how to use indexes with the TAstaClientDataSet that is the same
way it use used with the TAstaDataset example.

1.3.6 MasterDetail
Requires

AstaBDEServer to be running

Description
In order to use Master/detail with AstaClientDataSets the Detail DataSet needs to use a
Parameterized query. After setting the Parameter DataType you then need to use the
MasterFields/MasterSource property editor to hook to the master DataSet.

© 1997-2002 ASTA Technology Group Inc


15 ASTA 3 Tutorials

At runtime, a as the master row changes, a new paramterized query is sent to the server
by the detail dataset. ASTA also supports disconnected Master/Detail which allows for a
filter to be used by the Detail DataSet.

There may be times where you do not want to go to the server for every master row
change but want to support master detail locally. This requires the SQL on the detail
dataset to fetch all the rows for all the masters in the master Query. Caution is urged
when using this technique in not bring to many rows over the wire.

1.3.7 PacketFetches
Requires

Asta3ADOServer to be running

Description
ASTA Servers support 4 threading models with SmartThreading being the new recommended
Threading model that gives you all the features you will ever need. Sometimes each user needs their
own Database connection so they can use their Database UserName and Password. But this won't be
as scalable as pooling Sessions. Sometimes you also may want to open a very large DataSet set and
bring over "packets" of rows and to do this each user will need their own Persistent Database
Connection.

ASTA SmartThreading gives you the benefit of Pooling Database sessions but also allows any user to
toggle back and forth between their own Database session the pooled Session. Ideal for admins who
need access to a specific database on the server.

Client Side
This demo shows how to connect to the Asta3ADOServer. If the Username is "PersistentSession" the
server will connect the client to their own Database Session and bring results over 2 rows at a time.

procedure TForm1.FormCreate(Sender: TObject);


begin
Astaclientsocket1.userName:= 'PersistentSessions' ;
end;

As a user scrolls through the grid, the server will get the next packets and stream them to the client.
The demo also has a button that shows how to set the Session to Pooled and back to Persistent.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 16

Server Side
The server checks the username in the OnAssignPersistentSession event and if it matches
creates a datamodule solely for that client. It is there you can use the TAdoConnection to
set any Database params or connect string you desire.

procedure TServerDM.ServerSocketAssignPersistentSession(Sender: TObject;


TheClient: TUserRecord; UserName, Password: String;
var PersistentDataModule: TComponent; var Verified: Boolean);
begin
if comparetext(UserName,'PersistentSessions' )=0 then begin
PersistentDataModule:=TAstaDataModule.Create( nil);
with TAstaDataModule(PersistentDataModule) do begin
AdoConnection.ConnectionString:=FDatabasePlugin.DatabaseConnectionString;
AdoConnection.Connected:=True;
Verified:=True;
end;
end
end;

Below is a snippet of the Server Log that shows the Intial Select from the client and the
threads launched to bring over the next packets
Select SQL SELECT * From Customers
->63.224.240.86:2198
Thread 469 ended for dataset id 1 ->63.224.240.86:2198
Thread 484 launched for dataset id 1 ->63.224.240.86:2198
Thread 484 ended for dataset id 1 ->63.224.240.86:2198
Thread 471 launched for dataset id 2 ->63.224.240.86:2198

1.3.8 Sorting
Requires

AstaBDEServer to be running

Description
AstaDatasets support indexes but there maybe times when you don't want to define

© 1997-2002 ASTA Technology Group Inc


17 ASTA 3 Tutorials

indexes and just do quick sorts. This demo shows how to use SortDataSetbyFieldName
and SortDataSetbyFieldNames.

procedure TForm1.GridTitleClick(Column: TColumn);


begin
AstaclientDataSet1.SortDataSetByFieldName(Column.FieldName, RadioGroup1.ItemIndex= 1);
(*******************
To sort multiple fields use
procedure SortDataSetByFieldNames( const FieldNames: array of string; const Descending:
array of Boolean);
(********************)

end;

procedure TForm1.Button1Click(Sender: TObject);


begin
AstaclientDataSet1.SortDataSetByFieldNames([ 'ContactTitle','ContactName' ],[false,True]);

end;

1.3.9 SuitCase
Requires

AstaBDEServer to be running

Description
ASTA supports a disconnected user or "suitCase" model. This tutorial shows you how to
connect to a server, fetch data, save it to a file, empty the dataset, load it from a file, do
edits and connect back to a server to post updates.

1.3.10 Transactions
Requires

AstaBDEServer to be running

Description
Shows a simple example of calling ApplyUpdates with EditMode set to Cached. Use the
EditMode property editor to configure the UpdateTablename and Primekey fields.

1.4 Messaging and File Transfer


ASTA has a very flexible and easy to use messaging layer. For Database Application Developers,
using Messaging to add features to Database applications opens up a world of possibilities as server
"push" and peer to peer messaging can add many features never before deemed possible or so easy
to business applications.

ASTA ParamList messaging is the recommended way to transfer any kind of data and AstaParamLists
are available across just about all platforms with Java and C++ libraries for Win32, Linux, Palm and
WinCE. To send very large files between client and server use the ASTA File Transfer routines that
allow for large streams to be sent in configurable "chunks"

ParamList Messaging
ParamList Messaging with Threaded Database Support

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 18

Packing Up Data
File Transfer Techniques
Instant Messaging

Messaging examples come with both servers and clients and the servers are not database servers. To
create an AstaServer to test or use with messaging and no database threading, you just need to make
sure you have coded and assigned an Application.OnException event so that exceptions are not raised
in dialogs on the server.

Below is an example.
procedure TForm1.AstaException(Sender: TObject; E: Exception);
begin
//log the message on production servers either don't log to a UI control
//or clear it every now and again!
memo1.lines.add(E.Message);
end;

procedure TForm1.FormCreate(Sender: TObject);


begin
//all ASTA servers need to supply an Application Exception Handler
application.OnException := AstaException;
astaserversocket1.active := True;
end;

1.4.1 Instant Messaging


ASTA 3 provides a full Instant Messaging API to not only easily create full featured
Instant Messaging applications but to support Disconnected Messaging with the
AstaMQManager. Below is a screen shot of the client part of the Instant Messsing Tutorial.
When the Client connects to the server it will retrieve a list of users not only currently
connected to the server but a full list of all users. Messages can be send to users that are
NOT connected. When they connect, they pick up their waiting Messages.

This tutorial includes a full featured Instant Messgaing server and client that suports
advanced features like disconnected messaging and messaging to user defined groups.
Future Tutorials will go into more detail as to the internals of the ASTA IM API. Adding IM
to an ASTA server is accomplished with one line of code, which involves instantiating the
TAstaIMServerBlackBox Object, whose source is included in the tutorial. The idea is that
collaborative abilities are very important in the Internet Second Wave and ASTA users
should be able to add collaborative features very easily to their existing ASTA servers.

ServerSide
Below is a screen shot of the ASTA IM Server from this tutorial.

© 1997-2002 ASTA Technology Group Inc


19 ASTA 3 Tutorials

Client Side
ASTA supports sending messages to "Named" users. Below is the code that gets executed
on a double click from the grid. Teh AstaClientSocket actually has an IMDataSet property
that will get populated with users when a client connects to an IM enabled server. In this
case Fields[0] or the UserName field is being used to send an Instant Message. Event
attachments can be sent.

procedure TfrmIMClientMain.DBGrid1DblClick(Sender: TObject);


var
MsgForm: TfrmTypeMessage;
begin
ConnectionAndUsercheck;
MsgForm := TfrmTypeMessage.Create(self);
try
MsgForm.ShowModal;
if MsgForm.ModalResult = mrOk then
SendInstantMessage(AstaClient,AstaClient.ImDataset.Fields[ 0].AsString,MsgForm.MsgMemo.line
s.text,'');
outmemo.lines.add( 'To
'+AstaClient.ImDataset.Fields[ 0].AsString+':'+MsgForm.MsgMemo.lines.text);
finally
FreeAndNil(MsgForm);
end;
end;

Below is a screen shot of the client. Notice the options to Delete waiting Messings,
broadcast, and define and broadcast to groups.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 20

© 1997-2002 ASTA Technology Group Inc


21 ASTA 3 Tutorials

1.4.2 CodedParamList
This tutorial includes a client and a server.

Server Side

The server is coded to handle 2 events:OnCodedParamlist and OnOutCodedParamList.

procedure TForm1.AstaServerSocket1OutCodedParamList(Sender: TObject;


ClientSocket: TCustomWinSocket; MsgID: Integer; InParams,
OutParams: TAstaParamList);
begin
/// Just need to fill up the OutParams for anything going back to the client
memo1.lines.add( 'incoming from SendGetCodedParamList:'+InParams.AsDisplayText);
OutParams.fastadd( 'Server','Server running at
'+GetThePcsIPAddress+ ':'+IntToStr(AstaServerSocket1.Port));

end;

procedure TForm1.AstaServerSocket1CodedParamList(Sender: TObject;


ClientSocket: TCustomWinSocket; MsgID: Integer; Params: TAstaParamList);
begin
memo1.lines.add( 'incoming from SendCodedParamList:' +Params.AsDisplayText);
end;

Client Side

This client example shows how to use SendCodedParamList and SendGetCodedParamList.


It loads up a text file into a memo and also sends it as a stream, just for example
purposes to show how flexible the AstaParamLists are.

procedure TForm1.BitBtn1Click(Sender: TObject);


var
Params, RetParams: TAstaParamList;
begin
if not OpenDialog1.Execute then Exit;
Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
Params := TastaParamList.Create;
try
Params.FastAdd(OpenDialog1.FileName + ' File Size of ' + IntToStr(Length(memo1.Text)));
Params.FastAdd(Now); // accepts TDateTime but Params[1] can be used as Params[1].AsString
or Params[1].AsDateTime
Params.FastAdd(Memo1.Text); // text is a string representation of a TStringList
Params.FastAdd(OpenDialog1.FileName, ''); //here we are adding it as a stream
//use any way you want
params[params.count- 1].LoadFromFile(OpenDialog1.fileName);
if SendGetCheckBox.Checked then begin
try
RetParams := AstaClientSocket1.SendGetCodedParamList( 15, Params);
//SendGetCodedParams sends the Params to the Server and waits for a return result from
the
//server. The Server must coded the OnOutCodedParamList and fill the OutParams
//which gets received as the Function Result of SendGetCodedParamList
if (RetParams <> nil) and (RetParams.Count > 0) then
showmessage( 'Returned From the server server ' + #13 + RetParams[0].AsString);
finally
RetParams.free;
end
end else AstaClientSocket1.SendCodedParamList( 15, Params);
finally
Params.Free;
end;
end;

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 22

1.4.3 CodedDBParamList
Requires

Asta3ADOServer to be running since this is a Database Messaging routine.

Description
ASTA messaging has been used in more and more ways over the years and ASTA 3 introduces a fast
and easy way to use ASTA messaging with the new call of SendGetCodedDBParamList. This allows
you to use Asta message calls that will check out a database session on the server and execute your
server side code in a thread.

Client side
=======

procedure TForm1.Button1Click(Sender: TObject);


var
pout,PIn:TAstaParamList;
i:Integer;
begin
pout:=TAstaParamList.create;
pin:=cs.SendGetCodedDBParamList( 1000,POut);
try
for i:=0 to pin.count-1 do
memo1.lines.add(pin[i].Name+':'+pin[i].AsString);
finally
pout.free;
pin.free;
end;
end;

Server side
=======
This new event is available which will be called in a thread with a datamodule handed off to you with
any and all of your database components. You can also create and destroy DB components on the fly.

Just Grab the incoming Params and fill up the OutParams and they will be transported back to the
client in a thread. if an exception occurs it will be raised at the client. or you can raise it yourself on the
server to be transported back to the client.

procedure TServerDM.ServerSocketOutCodedDBParamList(Sender: TObject;


ClientSocket: TCustomWinSocket; DBDataModule: TComponent; MsgID: Integer;
InParams, OutParams: TAstaParamList);
begin
with dbDataModule as TAstaDataModule do begin
query.sql.text:= 'select * from customers';
query.Open;
OutParams.FastAdd('Count',Query.Recordcount);
end;
end;

1.4.4 PackingUpData
ASTA Paramlist messaging provides an easy to use and efficient transport to send any
type of information over any network. Sometimes, you may want to transport some
complicated data. These tutorials show some techniques that may help.

© 1997-2002 ASTA Technology Group Inc


23 ASTA 3 Tutorials

DataSets Packed in ParamList


DataSet Packup

1.4.4.1 DataSetParamList

Requires

This demo uses the BDE but you can substitute any TDataset/database component.

Description
This demo shows how to add DataSets to AstaparamLists.

The following code adds the SQL as defined on the form as the ParamName and then copies the Data
from a TQuery by using the AsDataSet Call of the TAstaParamItem.

procedure TForm1.BitBtn1Click(Sender: TObject);


var
i: Integer;
begin
FparamList.Clear;
ListBox1.Items.Clear;
for i := 0 to memo1.lines.count - 1 do begin
Query1.Close;
Query1.Sql.text := 'Select * from ' + memo1.lines[i];
Query1.Open;
ListBox1.items.add( 'Select * from ' + memo1.lines[i]);
FParamList.FastAdd( 'Select * from ' + memo1.lines[i]);
FParamList[FParamList.Count - 1].AsDataSet := Query1
end;
ExtractButton.Visible := FParamList.Count > 0;
end;

This code uses the TAstaParamItem.AsDataSet property to get the DataSet from any ParamItem.

NOTE : You are responsible for freeing any DataSet returned from the AstaParamItem.AsDataSet call
as a TAstaDataSet is actually created in this call.

procedure TForm1.ExtractButtonClick(Sender: TObject);


begin
if ListBox1.ItemIndex < 0 then raise Exception.Create('highlight a query!');
DataSource2.DataSet.Free;
DataSource2.DataSet := FParamList[ListBox1.ItemIndex].AsDataSet;
end;

1.4.4.2 DataSetPackup

Requires

This demo uses the bde but you can substitute any TDataset/database component.

Description
This demo shows how to clone a dataSet to an AstaDataSet (In Memory) and then store
it in a blob or memo field of another DataSet and then to extract it.

The two calls used are

function CloneDataSetToString(D: TDataSet): string;


function StringToDataSet(const S: string): TAstaDataSet;

This code shows the packup:

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 24

procedure TForm1.BitBtn1Click(Sender: TObject);


var
i:Integer;
begin
TableTransportDataSet.Empty;
for i:=0 to memo1.lines.count-1 do begin
Query1.Close;
Query1.Sql.text:= 'Select * from '+memo1.lines[i];
Query1.Open;
TableTransportDataSet.Append;
TableTransportDataSet.FieldByName( 'TableName').AsString:=memo1.lines[i];
TableTransportDataSet.FieldbyName( 'Data').AsString:=CloneDataSetToString(Query1);
TableTransportDataSet.post;
end;
ExtractButton.Visible:=TableTransportDataSet.recordcount> 0;
end;

And this code shows how to use it.

procedure TForm1.ExtractButtonClick(Sender: TObject);


begin
DataSource2.DataSet.Free;
DataSource2.DataSet:=StringToDataSet(TableTransportDataSet.FieldByName( 'Data').AsString);
end;

1.4.5 Large FileTransfer


AstaParamlist messaging is easy to use and efficient but sometimes you may want to
transfer very large files and don't want your Database server to be overwhelmed with file
transfer requests. Of course you can always use FTP which WAS designed for file transfer
and using your ASTA server to manage the files you want with ASTA messaging is a very
efficient way to transfer files.

ASTA does offer an alternative with routines that can transfer files from server to client or
client to server in configurable "chunks" or block sizes. With ASTA messaging typically
files are loaded in TMemoryStreams, in the ASTA segmented file support calls, a
TFileStream is used on both client and and server to use as little memory as possible.

Server to Client
Client to Server
Param List Large File Transfer

1.4.5.1 Standard Messaging

This example shows how to send the Client.exe itself to and from the server using several
ASTA messaging techniques and also showing a progress bar when a file is requested
from the server.

Server Side

procedure TForm1.AstaServerSocket1OutCodedParamList(Sender: TObject;


ClientSocket: TCustomWinSocket; MsgID: Integer; InParams,
OutParams: TAstaParamList);
var
FileName:String;
begin
case msgid of
2000: begin
FileName:=InParams[0].AsString;
memo1.lines.add(FileName);
OutParams.FastAdd(Filename, '');

© 1997-2002 ASTA Technology Group Inc


25 ASTA 3 Tutorials

OutParams[0].loadFromFile(FileName);
end;
end;
end;

Client Side

Procedure TForm2.BitBtn2Click(Sender: TObject);


var
pout, PIn: TAstaParamList;
begin
Pout := TAstaParamList.Create;
pout.FastAdd(Edit1.text);
try
pin := AstaclientSocket1.SendGetCodedParamList( 2000, Pout);
memo1.lines.clear;
if pin.count > 0 then begin //found it
memo1.lines.add( 'File Received of '+IntToStr(Length(pin[ 0].AsString))+' bytes');
end;
finally
pin.Free;
Pout.free
end;
end;

1.4.5.2 Server to Client

Requires
This demo includes both a server and a client.

Description
ASTA messaging allows any type of data to be transfered but sometimes there are very
large files that you want to transfer. ASTA supports the transfer of files from servers to
clients in a thread in configurable "chunks"

Client Side
The shot below shows the ASTA client demo that asks for the AstaBDESErver.exe to be
streamed over in 50K "chunks". There is an event that fires on the client when each
chunk is received from the server.

procedure TForm1.FileSegmentReceive(Sender: TObject; const FileName: string; CurrentSize,


Totalsize, FileSize: Integer);
begin
//when currentsize and totalsize and fillfilereceived are all -1
//the file has been saved to disk
if FileSize=FullFileReceived then begin //-1 then begin
memo1.lines.add(FileName + ' save to file ');
exit;
end;
ProgressBar.Max := FileSize;
ProgressBar.Position := Totalsize;
memo1.lines.add(FileName + ' chunk ' + IntToStr(CurrentSize) + ' received ' +
IntToStr(TotalSize) + ' filesize ' + IntToStr(FileSize));
if TotalSize = FileSize then memo1.lines.add(FileName + ' completed.');
end;

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 26

Server Side
Below is the log of the server sending over the file in a thread to the client. The server
code is pretty trivial in that it must handle the request to Queue up the file for transport

procedure TForm1.ServerSocketCodedParamList(Sender: TObject;


ClientSocket: TCustomWinSocket; MsgID: Integer; Params: TAstaParamList);
var
i: Integer;
begin
for i := 0 to Params.count - 1 do
memo1.lines.add(InttoStr(msgid) + ':' + params[i].Name + ':' + Params[i].AsString);
case msgid of
1000 : ServerSocket.AddFileToTransportQueueParams( 'QueueSend',Params,ClientSocket);
end;
end;

And then the request to sent all the files requested.

procedure TForm1.ServerSocketCodedMessage(Sender: TObject;


ClientSocket: TCustomWinSocket; MsgID: Integer; Msg: string);
begin
case msgid of
1000 : Serversocket.FileQueueList.Transmit( 'QueueSend');
end;
end;

© 1997-2002 ASTA Technology Group Inc


27 ASTA 3 Tutorials

1.4.5.3 Client to Server

With this demo, any file or file masks of files can be transferred from the client to the
server in configurable chunks. Below is a screen shot of the server log showing all the
AstaIO*.pas files being transfered with one file of code.

AstaServerFileSegment.pas implements a TAstaServerFileReceivelist component.

FServerFileList:=TAstaServerFileReceiveList.Create(ServerSocket);

The code on the server is mostly to visually show the files coming in and being saved. To
add support on the server to support client to server file transfer you just need to add a
couple of lines to the AstaServerSocket.onCodedParamList event.

procedure TForm1.ServerSocketCodedParamList(Sender: TObject;


ClientSocket: TCustomWinSocket; MsgID: Integer; Params: TAstaParamList);
begin
Case Msgid of
1001:FServerFileList.SetupFile(ClientSocket,Params);
1002:FServerFileList.AddToFile(ClientSocket,Params);
end;
end;

The Client Side code shows how to send one file or a file mask of files to the server very
efficiently.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 28

Below is a shot from the server log showing the actually sizes and more info as files come
in.

© 1997-2002 ASTA Technology Group Inc


29 ASTA 3 Tutorials

1.4.6 RemoteDirectory
Declaration

Description

1.5 Server side Techniques


In the N Tier Architecture it is common practise to put the "Business Logic" on the middle
tier or ASTA server. These demos show a couple of techniques for using TAstaProviders
and ServerMethods via the TAstaBusinessObjectsManager.

Provider and ServerMethod Text File Updater Shows a non-database example, with a server and a cli
of how to "query" directories on the server via a
ServerMethod using the TAstaBusinessObjectsManager
to "update" text files using AstaClientDatasets and
TAstaProviders
Threaded Server Method Server This examples shows a threaded server that handles an
memory DataSet but has no real Database. The client w
send
Server Method Parameter Example Includes a non-database server with servermethods and
shows how to return params from a servermethod. The
example actually can stream down the server EXE itself
a Param to the AstaclientDataSet

1.5.1 Provider Text file Updater


This samples includes both a server and a client. The server is not a database server but
uses an Servermethod, using the TAstaBusinessObjectsManager, to return a list of text
files from a Parameter defined on the serverMethod. It also uses a Provider to allow for
the text file to be updated.

This example shows a simple of example of putting the "Business Logic" on the middle
tier. There is no real database but we can use ASTA to feed data to remote clients by
populating in memory DataSets on the server and intercepting applyupdates calls to write
files back to disk rather than applying SQL to a Database.

Server Side
Since this server will use ASTA Server side components and not use messaging or
ClientSide SQL, the Datamodules and forms used on the server must be registered. The
call to TAastaServerSocket.RegisterDataModule "takes inventory" of existing Providers
and ServerMethods

procedure TForm1.FormCreate(Sender: TObject);


begin
Application.OnException:=AstaException;
ServerSocket.RegisterDataModule(Self);
ServerSocket.RegisterDataModule(ServerDM);
ServerSocket.Active:=True;
end;

The ServerDataModule defines one ServerMethod that has a String Param of "FileMask".

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 30

From the client, an AstaClientDataSet will point to the Servermethod and send a file
mask to the server which will then execute the following code to use the Delphi Directory
Find Routines to find all files matching the FileMask and optionally Load the file itself. The
FileDataSet is an AstaDataset, an In memory DataSet with the fields already defined. The
Servermethod will append the Dataset.

procedure TServerDM.AstaBusinessObjectManager1Actions0Action(
Sender: TObject; ADataSet: TDataSet; ClientParams: TAstaParamList);
var
FSearchRec:TSearchRec;
begin
FileDataSet.open;
FileDataSet.Empty;
if sysutils.FindFirst(ClientParams.ParamByName( 'FileMask').AsString, 0, FSearchRec) = 0 then
repeat
with FileDataSet do begin
Append;
FieldByName( 'FileName').AsString := ExtractFileName(FSearchRec. Name);
FieldByName( 'Size').AsInteger := FSearchRec.Size;
FieldByName( 'TimeStamp').AsDateTime := FileDatetoDateTime(FSearchRec.Time);
FieldByName( 'Path').AsString := ExtractFilePath(expandFileName(FSearchRec. Name));
if ClientParams.ParamByName( 'LoadFiles').AsBoolean then
TBlobField(FieldbyName( 'File')).LoadFromfile(ExtractFilePath(ClientParams.ParamByName
('FileMask').AsString)+FSearchRec.Name );
Post;
end;
until sysutils.findnext(FSearchRec) <> 0;
if FileDataSet.RecordCount> 0 then FileDataSet.First;
end;

Client Side
The Client has an AstaClientDataSet but it does not use sql but points to the
TAstaProvider on the server. If the user wants to bring the full text file over along with
the Filename,Size, Timestamp etc they just click on a check box and set the 'LoadFiles'
param.

procedure TForm2.Button1Click(Sender: TObject);


begin
with AstaClientDataSet1 do begin
ParamByName('LoadFiles').AsBoolean:=LoadFilesCheckBox.Checked;
ParamByName('FileMask').AsString:=FileMaskEdit.Text;
//ASTA wont' bring over blob or memo fields unless you explictly ask for them
// in this case it's a blob field so we set SQLOptions.soFetchBlobs to true
if LoadFilesCheckBox.Checked then
SQLOptions:=[soFetchBlobs]
else SQLOptions:=[];
Close;
Open;
end;
end;

If we has the LoadFilesCheckBox.checked, the actually Text file is streamed over as part
fo the DataSet "File" field. Now that the AstaClientDataSet is populated the text file
shows in a DBMemo and we can edit the actual text file. To post it to the server, we just
call

with AstaClientDataSet1 do
ApplyUpdates(usmServerTransaction);

And 2 Datasets sent to the server that represent the current rows and "original" rows. On
the TAstaProvider on the server we cannot use SQL since we are just editing a text file
and there is no database. Here is the code on the server that will handle the updates. On
the TAstaProvider there is an OnBeforeUpdate event that has a VAR Handled: Boolean

© 1997-2002 ASTA Technology Group Inc


31 ASTA 3 Tutorials

that can be set if you don't want ASTA to generate SQL, which of course is not going to
work so well in this case with no database on the server.

procedure TServerDM.TextFileProviderBeforeUpdate(Sender: TObject;


ClientSocket: TCustomWinSocket; ExecQuery: TComponent;
OriginalValueDataSet, CurrentValueDataSet, ServerValueDataSet: TDataSet;
var Handled: Boolean);
Function FullFileName:String;
begin
with CurrentValueDataSet do
result:=FieldByName( 'Path').AsString+Fieldbyname('FileName').AsString;
AstaBusinessObjectManager1.actions[ 0].serverSocket.recordServerActivity(ClientSocket
,result);
end;
begin
handled:=True;
with CurrentValueDataSet do
if fileExists(FullFileName) then
TBlobfield(FieldByname('File')).SaveToFile(FullfileName);
end;

1.5.2 ServerMethod Param Example


This samples includes both a server and a client. The server is not a database server but
uses an Servermethod, using the TAstaBusinessObjectsManager. There are 2 Methods
Defined: one called TestMethod and the other called GetFile, neither of which return a
result set but only return params. ServerMethods that return no result sets will be able,
in future ASTA 3 builds, to be published as SOAP Services by just setting the
TAstaActionItem.SoapService:Boolean to true.

Method 1 : TestMethod

TestMethod defines 3 params.

IntputParam : ftSmallInt, ptinput


OutputParam : ftSmallInt,ptoutput
TimeStamp : ftDateTime,ptputput

In the OnActionEvent of the TAstaActionItem here is the code that receives the
InputParam from the client and just sets the output Param. The ClientParams :
TAstaParamList comes in from a remote TAstaclientDatset.

procedure TServerDM.AstaBusinessObjectManager1Actions0Action(
Sender: TObject; ADataSet: TDataSet; ClientParams: TAstaParamList);
begin
ClientParams.ParamByName( 'OutputParam').AsInteger :=
ClientParams.ParamByName( 'InputParam' ).AsInteger - 100;
ClientParams.ParamByName( 'TimeStamp').AsDateTime := now;
end;

Here is the Client Side Code using an AstaClientDataSet with a ServerMethod pointed to
TestMethod.

procedure TForm1.ReOpenClick(Sender: TObject);


begin
with AstaclientDataset1 do begin

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 32

ParambyName( 'InputParam').AsInteger:=StrtoInt(Edit1.text);
refiresql;//this does a disable control/close/open/enable controls
end;
end;

Method 2 : GetFile

GetFile defines 2 params.

FileName : ftstring, ptinput


File : ftblob, ptoutput

In the OnActionEvent of the TAstaActionItem here is the code that receives the
InputParam from the client which in this case is just a filename. If that file is found on
the server it is streamed back in the output Param otherwise an exception is raised which
will propogate back to the client.

procedure TServerDM.AstaBusinessObjectManager1Actions1Action(
Sender: TObject; ADataSet: TDataSet; ClientParams: TAstaParamList);
begin
if fileExists(ClientParams.ParamByName( 'FileName').AsString) then
ClientParams.ParambyName( 'File').LoadFromFile(ClientParams.ParamByName( 'FileName').AsStrin
g)
else raise Exception.create(ClientParams.ParamByName( 'FileName').AsString + ' does not
exist');
end;

Calling ServerMethods at runtime


The demo also has an example of calling servermethods at runtime. When the
serverMethod name is set, the params are fetched from the server so you don't need to
create the params. This happens at design time also when an AstaClientDataSet is set to
use a Provider or ServerMethod. For performance purposes you can cache all the Param
info for Providers and ServerMethods so there is no need for a trip to the server.

procedure TForm1.Button2Click(Sender: TObject);


var
acd: TAstaClientDataSet;
begin
acd := TAstaClientDataSet.Create( nil);
try
acd.AstaClientSocket := AstaClientSocket1;
Acd.ServerMethod := 'ServerDM.GetFile' ;
acd.ParamByName( 'FileName').AsString := FileEdit.Text;
acd.Open;
showmessage( 'File Size is ' + IntToStr(Length(acd.ParambyName( 'File').AsString)));
finally
acd.free;
end;
end;

1.5.3 Threaded Server with No Database


This samples includes both a server and a client. The server is not a database server but
uses an Servermethod, using the TAstaBusinessObjectsManager. This Server is threaded
so you can see the minimum required to thread Servermethods with ASTA servers. There
is no real database but instead there is a servermethod that defines a Parameter named
"RecordsToCreate" so the client determines how many rows to create on the server. An in
memory DataSet, the TAstaDataSet is used on the serverMethod which supplies the

© 1997-2002 ASTA Technology Group Inc


33 ASTA 3 Tutorials

result set streamed down to the AstaClientdataSet.

When the server starts up, any form used on the server needs to be registered so that
ASTA can inventory the server side components. This is done by calling the
AstaServerSocket.RegisterDataModule method. Then CreateSessionsforDBThreads is
called, ThreadedDBSupplySession is called Database Sessions number of times to create
a "pool" of DataModules. Typically the main DataModule is a DataBase DataModule with
some kind of Database Connection Component like a TADOConnection or
TDatabase/TSession pair. When a user connects to an ASTA server no threads are
required. When any request for a datbase process is made, a "session" is checked out of
the thread Pool, the work is done in a thread, and the Session is returned to the Pool as
early as possible. To scale servers, get resources late and release them early. ASTA does
all this for you if you just set a couple of properties and code some events.

Threading the Server


ASTA Database servers already come thread ready but since this is not a database server
there are a couple
of steps you need to do to thread the server.

1. Set the AstaServerSocket.ThreadingModel to tmSmartThreading


2. Set the AstaServerSocket.DatabaseSessions:integer to a value greater than zero.
3. Code the AstaServerSocket.ThreadedDBSupplySession Event.
4. Code the AstaServerSocket.ThreadedDBSupplyQuery event.
5. Call the AstaServerSocket.CreateSessionsForDBThreads method to set up the
Database Session Pool.

Here is the code from the server that sets the server up for threading.

procedure TForm1.FormCreate(Sender: TObject);


begin
Application.OnException:=AstaException;
ServerSocket.RegisterDataModule(Self);
ServerSocket.RegisterDataModule(ServerDM);
ServerSocket.Active:=True;
ServerSocket.CreateSessionsForDBThreads(True);
end;

Server Method : DataSetRows


A ServerMethod is defined using a TAstaBusinessObjectsmanager. On this server there
are 2 TAstaBusinessObjectsManagers to show you that you can use as many as you wish
and you can also use as many DataModules as you need on the server also. The server
defines one Param caled RecordsToCreate that is an Input Param and of type Integer.

The code below opens and Empties the TestDataset:TastaDataSet and then just loops
through and adds as many rows as defined on the client incoming Param.

Note: When populating your own DataSet, ASTA will not call FIRST on the server for
performance considerations. so if you are populating your own in memory DataSet
remember to call First.

procedure TServerDM.AstaBusinessObjectManager2Actions0Action(
Sender: TObject; ADataSet: TDataSet; ClientParams: TAstaParamList);
var
LoopCounter,Total: Integer;

begin

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 34

TestdatASet.Open;
if testDataSet.RecordCount> 0 then
TestDataSet.Empty;
total:=ClientParams.ParamByName( 'RecordsToCreate').AsInteger;
with TestDataSet do
for LoopCounter := 1 to Total do
begin
Append;
FieldByName( 'StringField').AsString := 'This is a test field index : ' +
IntToStr(LoopCounter);
FieldByName( 'IntegerField').AsInteger := LoopCounter;
Post;
end;
TestDataSet.First;
end;

Client Side
On the client side, there is an AstaClientDataSet with the serverMethod set to the
DataSetRows ServerMethod on the server. The Only thing required is that you set the
AstaClientDataSet.Params and then close and open the DataSet. The params will go to
the server, check out a datamodule, execute in a thread, and call the server method
OnActionEvent.

procedure TForm1.Button1Click(Sender: TObject);


begin
with RowDataSet do begin
Params[0].AsInteger:=StrToIntDef(Edit3.Text, 25);
RefireSQL;
end;
end;

1.6 Feature Testers


These tutorials also can be used to test and adminster remote servers. It's not a bad idea
to compile them and install them in the Delphi IDE until Tools Option in order to fire SQL
against any remote server, see all your ServerMethods or providers on remote servers or
see everything you want with the AstaSQLExplorer. Remember these are all ASTA thin
client apps that can be used against any remote server.

DataSet QA
Provider Tester
ServerMethod Tester
SQL Demo and http Tunneling
SQL Explorer

1.6.1 DataSetQA
We've included one of our QA tests in the ASTA 3 tutorials to show how ASTA properly
handles all datatypes. There are projects for Delphi 5 and Delphi 6 with all Delphi 6
datatypes tested. Included in this demo, for the TAstaClientDataSet testing is a paradox
file AstaQA_ClientDS.DB. We will be extending this test to include create table scripts for
other servers. For now it requires the Asta3BDEServer with the AstaQA_ClientsDS.db file
available.

© 1997-2002 ASTA Technology Group Inc


35 ASTA 3 Tutorials

Note: In the test above you are seeing a problem from the BDE/Paradox driver in handling BCD fields. It allows
to transfer to the BDE ftBCD and ftFmtBCD parameters, but it does not handle such data types correctly
(Paradox driver) and no error is raised. After a call of INSERT, ftBCD and ftFmtBCD columns have nulls. ASTA
is correctly delivering the Params. Each Delphi 3rd Party Database used on ASTA servers must be able to
handle all Data types correctly in parameterized queries. If you are seeing any problems with any DataTypes
check the AstaServerSocket.OnServerQuerySetParams Event which is responsible for transfering Params from
the incoming TAstaParamLists coming from the client. Contact ASTA with any questions of course in making
sure all datatypes are supported with whatever ASTA server you choose to use.

Below is the server log of SQL Generated during a test.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 36

1.6.2 ProviderTester
Business Logic can be implemented on the middle tier with ASTA by using the
TAstaBusinessObjectsManager component or TAstaProviders. The
AstaProviderTesterTester shows all the providers running on a remote ASTA server, the
params for those providers and allows the params to be set and a result set requested.

The result set can be edited and ApplyUpdates called to post the changes to the server.

© 1997-2002 ASTA Technology Group Inc


37 ASTA 3 Tutorials

1.6.3 ServerMethodTester
Business Logic can be implemented on the middle tier with ASTA by using the
TAstaBusinessObjectsManager component. The AstaBusinessObjectsTester shows a
couple of techniques that can be used with server methods

This client can be run against any ASTA server and will show all the available
ServerMethods and the params for any given servermethod. Params can be set and
ServerMethods Executed.

When an AstaClientDataSet has it's servermethod property changed, either at runtime or


design time it will bring back param information for the method choosen. This param
information can come from the server or can be cached on the client to avoid extra server
round trips. The AstaclientSocket has a CachedMetata property that allows you to cache
param and other info (like provider primekey info) for TAstaProviders and ServerMethods.
It is recommended that this be set to smFetchOnValidate.

Showing Available Server Methods


The TAstaClientDataSet has a MetaDataRequest propety that allows for many kinds of
information to be streamed over from remote ASTA servers in a DataSet. In this case this

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 38

property is set to mdBusinessObjects and will bring back a list of servemethods.

Show the Params for any ServerMethod


A Technique is show to get ParamInfo for each Param.

Executing any Servermethod


ServerMethods can be assigned and executed at runtime and this example show how to
do that. There is also an example of showing how an exception is raised if a
servermethod name assigned does not exist on the remote server.

Below is a shot of the ServerMethod Tester running against


one of the ASTA tutorial servers.

1.6.4 SQLDemo and Http Tunneling


The AstaSQLDemo allows you to connect to any ASTA server and get a list of table
names, field info for each table and to SQL Select and Exec Queries. It also shows how to
execSQL in a transaction. It is invaluable to test SQL against your database so it is

© 1997-2002 ASTA Technology Group Inc


39 ASTA 3 Tutorials

recommended you keep a compiled version around and even add it to the Options Menu
choice in Delphi so you can run it at any time.

Additionally, it can be set to work with tcp/ip or http with a menu choice that allows you
to set a web server, the location of Astahttp.dll and the location of the ASTA server.

1.6.5 SQLExplorer
The AstaSQLExplorer allows you to browse server side components and metadata information from
your database. It will handle multple Datasources if your server supports them. The source is a good
source for ASTA techniques in fetch server side inforamation. Of course it will run against any of the
over 30 ASTA servers available using Delphi 3rd party Database Components.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 40

1.7 Authentication and Security

Login
Skywire Emulator
Stateless Authentication

1.7.1 Login
Requires

This tutorial comes with a server and a client.

Description
ASTA supports authentication via a Username and Password that are properties of the
ASTA ClientSocket. The ASTA help file explains the login process in detail. This tutorial
shows how to authenticate remote clients.

Server Side

© 1997-2002 ASTA Technology Group Inc


41 ASTA 3 Tutorials

The Server is very simple in that it contains the minimum required to run an ASTA
server: provide an Application .OnException event so that no Dialogs show in any
exceptions, code the TAstaServerSocket.OnShowServerMessage to enable logging and
then code the TAstaServerSocket.OnClientAuthenticate Event.

procedure TForm1.FormCreate(Sender: TObject);


begin
application.OnException := AstaException;
astaserversocket1.active := True;
end;

procedure TForm1.AstaServerSocket1ShowServerMessage(Sender: TObject;


Msg: string);
begin
memo1.lines.add(msg);
end;

The TUserRecord is part of the TAstaServerSocket.UserList and contains an Extra


AstaParamlist named ParamList that can be used to hold any kind of information you
want to track for each client. The ClientSocket has a public property of
ClientSocketParams :TAstaParamList that you can fill with any data that will be transfered
to the server and be available in the TUserRecord.ParamList. The OnClientAuthenticate
Event presents a ClientParamList:TAstaParamList that you can fill and it will be returned
to the AstaClientSocket in the OnLoginParamsEvent.

The important piece is setting the Var LoginVerified:Boolean to true to authenticate the
Client.

procedure TForm1.AstaServerSocket1ClientAuthenticate(Sender: TObject;


Client: TUserRecord; TheUserName, ThePassword, TheAppName: string;
ClientParamList: TAstaParamList; var LoginVerified: Boolean;
var PersistentSession: TComponent);
begin
if comparetext(TheUserName, 'Disconnect' ) = 0 then begin
Loginverified := False;
exit;
end;
LoginVerified := True;
memo1.lines.add(Client.AppVersion);
end;

Client Side
In the FormCreate, the TAstaClientSocket.ClientSocketParams , public property, is getting
appended the date time that will send to the server when the client logs in and will be
transferred to the TUserRecord.ParamList.

The TAstaClientSocket.AutoLoginDlg is set to LtLoginNoDlg which will send the


UserName,Password, ApplicationName and ClientSocketParams to the ASTA server and
present it in the TAstaServerSocket.OnClientAuthenticate event

procedure TForm1.FormCreate(Sender: TObject);


begin
//the Astaclientsocket has a ClientSocketParams:TAstaParamList that will flow to the
//remote server on Login and become part of the AstaServerSocket.UserList.ParamList
Astaclientsocket1.ClientSocketParams.FastAdd( 'Client Form Created at ', now);
end;

Below is the TAstaClientSocket.OnLoginParamAttempt Event that contains the


ClientVerified:Boolean and any Params sent from the
TAstaServerSocket.OnClientAuthenticate event.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 42

procedure TForm1.AstaClientSocket1LoginParamsAttempt(Sender: TObject;


ClientVerified: Boolean; ServerParams: TAstaParamList);
var
i: integer;
begin
if ClientVerified then memo1.lines.add( 'Login verified')
else memo1.lines.add( 'Login Not Verified');
for i := 0 to ServerParams.Count - 1 do
memo1.lines.add(ServerParams[i]. Name + ':' + ServerParams[i].AsString);
end;

1.7.2 SkyWire Emulator


Background

ASTA "SkyWire" refers to non-VCL ASTA clients. ASTA supports a large array of non VCL
clients which is part of the ASTA Safari Kit and Unlimited ASTA 3 licenses. A List of
available clients, including those for Palm, Wince, Java, C#, Win32 via COM for VB and
others is available from the AstaWireless Site. which is targetted to the non-delphi world.

Description
The SkyWire Emulator was designed to show the types of calls available from remote SkyWire clients,
but from a Delphi Client included in the demo. The Emulator includes a Server and Client and includes
ways to visual set the server to secure it, change usernames and passwords and to test encryption.

There is an in memory TAstaDataSet used on the server to add UserNames and


Passwords and the client must match the server settings. See the Security discussion in
the ASTA help for an overview of Security Options and also the Authentication discussion
to review the events that fire during authentication. Note RSA and AES options are only
available to users in the US and Canada. RSA is only available in special source editions
of ASTA. ASTA is applying for a US Government license to be able to export AES and RSA
encryption.

Server

© 1997-2002 ASTA Technology Group Inc


43 ASTA 3 Tutorials

Client
The Client allows for username and password to be set along with encryption options. The
tab represent delphi versions of routines available from the SkyWire API for non-VCL
clients. As you see ASTA clients can do just about anything they can do in Delphi but in
Palm,Wince, Java and even on embedded chips!

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 44

1.7.3 StatelessAuthentication and Cookies

This tutorial server and client to show how authentication can be done with ASTA and
HTTP stateless clients. When clients run stateless, they maintain state or stay connected
to the ASTA server. Normal tcp/ip ASTA clients maintain state and are represented on the
server in the TAstaServerSocket.UserList is a list of TUserRecords which include a pointer
to the ClientSocket: TCustomWinSocket. Remote Clients are first authenticated on the
server before they can process any data. The Login Tutorial and SkyWire Emulator show
an examples of this.

Stateless clients must carry with them, some kind of authentication packet on each trip
to the server. ASTA supports this by sending the TAstaClientSocket.UserName /Password
to the server in the first packet sent to the server and then returning a "Cookie:Cardinal"
value that is then pre-fixed to each subsequent packet to the server so that no further
UserName/Password authentication is required.

ASTA supports stateless HTTP clients that can masquerade as HTTP clients that appear
just like a browser client to any firewall. In order to accomplish this, ASTA provides an
ISAPI dll that must be setup on a Internet Server, like Microsoft Information Server (IIS)
or equivalent. ASTA Client messages are wrapped with HTTP headers and are sent
through the WebServer via AstaHTTP.dll and pass through to the ASTA Server which
processes it and passes it back through IIS to the ASTA client which strips off the HTTP
header and processes it as a normal message.

This tutorial includes a non-database server and a stateless ASTA client and requires a
WEB Server.

© 1997-2002 ASTA Technology Group Inc


45 ASTA 3 Tutorials

Setup the Web Server and ASTA Server


Server Side Discussion
Client Side Discussion

If you are using ASTA clients inside an ISAPI DLL where there is no Windows Message
Pump, the AstaClientSocket must be set to blocking mode which means it will run
stateless also. The same concept of stateless authentication can be used in this mode.

Example using Blocking Sockets

1.7.3.1 Set Up

Asta stateless support via HTTP requires a web server to run like Microsoft IIS (internet
Information Server). Another good choice for testing is the Omini Web Server available
from www.omnicron.ca.

1. Start the WebServer.


2. Copy AstaHttp.dll into a directory that has the rights to execute an ISAPI dll. For IIS
the default is the scripts directory.
3. Compile and Run the AstaHttpTestServer.
4. Configure the AstaclientSocket in the AstaHttpTestClient.

1.7.3.2 ClientSide

This example shows how to setup an stateless client running http that communicates
through a WebServer running Astahttp.dll. In formcreate, the UserName and password is
set and then the AstaClientSocket.WebServerCheck is called in order to setup the client
to run stateless http.
procedure TForm2.FormCreate(Sender: TObject);
begin
Caption := AstaVersion;
ClientSocket.UserName := 'ASTA';
ClientSocket.Password := 'Thin is In';
Clientsocket.WebServerCheck;
end;

The TAstaClientSocket.WebServer property is set to configure the client to communicate


with a remote ASTA server through an Internet Server running AstaHttp.dll. Below is an
image of the object inspector of the AstaclientSocket that shows the WebServer sub
property. Note that the AddCookie:Boolean property is set to true. That is all that is
required to add stateless authentication to an ASTA client. Also not that WinInet is set to
true which uses the Microsoft WinInet.dll to communicate with a Web Server via HTTP.
WinInet will use any proxy or firewall settings used by Internet Explorer and even
supports SSL so it is the recommended way of guaranteeing access through any firewall
that Internet Explorer can traverse also.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 46

1.7.3.3 Client Side Discussion

In order to suport StatelssAuthentication, when the


TAstaClientSocket.WebServer.AddCookie:Boolean is set to true here is what happens
when a the client accesses the server in any way

· The normal ASTA message format adds a datastructure to send the UserName and
Password if there has not been a Cookie retrieved from the server before. This value
can be accessed as the TAstaClientSocket.Cookie:Integer.
· The AstaclientSocket.OnStatelessPacket event is fired if you want to get in the middle
of the process. You can customize the packet on the client and the server but this is
not required nor recommended unless you have a special situation.

procedure TForm2.ClientSocketStatelessPacketEvent(Sender: TObject;


var TheData: string; Packup: Boolean);
begin
if Packup then
memo1.Lines.add( 'Cookie going to Server ' +
IntToStr(TAstaClientSocket(Sender).Cookie))
else memo1.Lines.add( 'Cookie coming from Server ' +
IntToStr(TAStaClientSocket(Sender).Cookie))
end;

· The Server receives the packet and unpacks it passing the UserName and Password
through the TAstaServerSocket.OnClientAuthenticate Event as a normal login. There
you can authenticate your client as normal. IF the client is authenticated a Cookie is
created by the AstaServerSocket and returned to the client. This cookie is then used
on subsequent calls to the server without requiring the username or password to be
resent to the server. If there is a problem, and the
TAstaClientSocket.SQLErrorHandling bit of seRouteCookieErrorsToLogin is set to true,
the TAstaClientsocket.OnLoginParamsEvent is fired as under normal stateless access
and you can tell the user they have not been authenticated and take appropriate
action like to ask for the UserName and Password again.

© 1997-2002 ASTA Technology Group Inc


47 ASTA 3 Tutorials

Below is a screen shot of the client with the cookie values showing as zero on the first
trip to the server and then coming back as 11917813.

1.7.3.4 ServerSide

Server Side
The AstaServerSocket has an AddCookie property which is of type
TAstaServerCookieOption.

TAstaServerCookieOption = (coNoCookie, coStatelessUserList, coUserCoded);

In order to tunnel via HTTP, ASTA binary messages are wrapped using the
HTTP format so that they can be disguised as normal browser traffic in order to traverse
any client firewall. When cookies are used, additional authentication information is
included in the ASTA messaging format. In the first message to the server, the Username
and password

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 48

Value Meaning
coNoCookie No cookie information

coStatelessUserList A binary tree is used to


authenticate clients and
maintain cookie information. The
AstaServerSocket has a property of
StatelessUserList of type
TAstaStatelessUserList.

coUserCoded The user is responsible for


implementing their own cookie
mechanism. in the Cookies tutorial
the AstaMessageQueue Manager is
used for this.

In the tutorial, the AddCookie property is set to coStatelessUserlist. Since HTTP is a


stateless protocol, there is no real user list for normal ASTA TCP/IP clients. When users
connect, they will provide username and password information so that the server can
authenticate them (this
happens in the AstaServerSocket.OnClientAuthenticate event). A "Cookie" or Cardinal
value will be returned to the client that can be used in future accesss of the server. This
allows for a fast/efficient way to authenticate remote clients on each connect to the
server.

1.7.3.5 Server Side Discussion

Declaration

Description

1.7.3.6 DatabaseSetup

Declaration

Description

1.7.3.7 Blocking Example

© 1997-2002 ASTA Technology Group Inc


49 ASTA 3 Tutorials

1.8 Protocols and Firewalls


Requires
This demo requires any ASTA database server running in Pooled to SmartThreading. Note to test http
you can also run the AstaSQLDemo and click on the protocol menu option.

Description
ASTA clients can connect to servers using various protocols

1. tcp/ip- this is the normal mode used with ASTA and the most efficient
2. http via WinInet- If there are any firewall issues on the client you can use stateless
http to use the Microsoft supplied WinInet.dll to get through any firewall that
Internet Explorer can. Requires a Web Server with Astahttp.dll deployed in the
Scripts Directory.
3. blocking- if you are writing an Isapi DLL or are using one of the new hot RAD WEB
tools like EWF or IntraWeb use ASTA blocking calls

The AstaClientSocket.WebServer property allows you to set up the AstaClientSocket to


use a WebServer along with Astahttp.dll

The image belows shows the demo and the options available. ASTA has easy to use
properties and methods to toggle between tcp/ip, http and blocking calls.

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 50

1.9 Database Servers


The ASTA help file goes into detail about the structure of ASTA servers. These tutorials will contain
some comments about individual servers and some screen shots.

The Asta3ADOServer is a very popular server since it can connect to Access or MS SQL Server or any
ODBC DataSource. It current has code on the server to show some extended ASTA features used in
some tutorials found in the ASTA code example download.

Below is a screen shot of the ASTA ADO Server.

Source for ASTA database servers are available for download and
a binary of the Asta3ADOServer can also be downloaded.

AstaServers can be installed as an NT Service by using


Asta3ADOServer.exe /install

1.9.1 DatabaseServers.ADO
The Asta3ADOServer is a very popular server and can connect to MS SQL Server, Access
Fox Pro or any ODBC DataSource.

This server has some code on it that is used in some examples that you will want to
remove when using the server in product.

© 1997-2002 ASTA Technology Group Inc


51 ASTA 3 Tutorials

The unit SocketDM.pas used in the Asta3ADOServer has some events that have been
coded that are for demonstration purposes only.

The following code is used in the Packets Fetches Tutorial to show how to use
SmartThreading and PersistentSessions. In the tutorial a client uses a UserName of
PersistentSessions to signify that it wants it's own connection to the Database.

procedure TServerDM.ServerSocketAssignPersistentSession(Sender: TObject;


TheClient: TUserRecord; UserName, Password: String;
var PersistentDataModule: TComponent; var Verified: Boolean);
begin
if comparetext(UserName,'PersistentSessions' )=0 then begin
PersistentDataModule:=TAstaDataModule.Create( nil);
with TAstaDataModule(PersistentDataModule) do begin
AdoConnection.ConnectionString:=FDatabasePlugin.DatabaseConnectionString;
AdoConnection.Connected:=True;
FPersistentCheck:=UserName+ ' Persistent ';// to show that
//this user has this datamodule only
Verified:=True;
end;
end
end;

The code below is used for a response to a TAstaClientSocket.SendGetCodedParamList


call on the client to show how to return the server time.

procedure TServerDM.ServerSocketOutCodedParamList(Sender: TObject;


ClientSocket: TCustomWinSocket; MsgID: Integer; InParams,
OutParams: TAstaParamList);
begin
outParams.FastAdd( 'ServerTime',Now);
end;

This code shows how you could use the TAstaServerSocket.OnCheckOutSession Event.

procedure TServerDM.ServerSocketCheckOutSession(Sender: TObject;


At: TAstaThread; ClientSocket: TCustomWinSocket; Session: TComponent);
begin
with TAstaDataModule(Session) do
ServerSocket.RecordServerActivity(ClientSocket, 'Check out for '+FPersistentCheck);
end;

The following code insures that certain socket errors are not shown in the server log.

procedure TServerDM.ServerSocketClientError(Sender: TObject;


Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
//we can ignore these
if (ErrorCode=10053) or (ErrorCode=10054) then ErrorCode:=0;
end;

If you want to Support Palm or WinCE Clients the TAstaPdaServerPlugin.OnPdaParamList


is where the action is

procedure TServerDM.PdaServerPluginPDAParamList(Sender: TObject;


TheClient: TUserRecord; MsgID: Integer; P: TAstaParamList);
var
Error:Integer;
Handled:Boolean;

begin

© 1997-2002 ASTA Technology Group Inc


ASTA 3 Help Tutorials 52

error:=PdaServerPlugin.DatabasePlugin.ProcessPdaMessages(TheClient,Msgid,P,Handled);
if not Handled then begin
// you better do something here!!!
//if handled is true, ASTA will return it to the client
//this supports our SkyWire API like ServerTime, Tablesnames etc
end;
end;

This code is where you Authenticate Clients .

procedure TServerDM.ServerSocketClientAuthenticate(Sender: TObject;


Client: TUserRecord; UName, Password, AppName: String;
ClientParamList: TAstaParamList; var LoginVerified: Boolean;
var PersistentSession: TComponent);
begin
if Client.DatabaseSession<> nil then
ClientParamList.FastAdd( 'Database',TAstaDataModule(Client.DatabaseSession).AdoConnection.Co
nnectionString)
else ClientParamList.FastAdd( 'Database','Pooled '+FDatabasePlugin.DatabaseConnectionString);
LoginVerified:=True;
end;

Here is an advanced call to thread a Database messaging call to do a manual Provider


broadcast, an advanced ASTA feature.
procedure TServerDM.ServerSocketCodedParamList(Sender: TObject;
ClientSocket: TCustomWinSocket; MsgID: Integer; Params: TAstaParamList);
begin

//this is just an example of how to call a broadcast manually


Case Msgid of
5000:Serversocket.ThreadedDBUtilityEvent(ClientSocket,ttDataModule,ManualBroadcastDemo,Param
s);
end;
end;

procedure TServerDM.ManualBroadcastDemo(Sender: TObject; ServerSocket: TServerSocket;


ClientSocket: TcustomWinSocket;
AQuery:TComponent;Params: TAstaParamList);
var
d:TAstaDataSet;
begin
with TAstaDataModule(AQuery) do begin //we asked for a ttDataModule
try
CustomerQuery.Close;
CustomerQuery.Open;
d:=CreateDeltaDataSetPrimative(CustomerQuery,true);
try
d.DataTransfer(CustomerQuery,True,False);

d.first;
while d.recordCount>5 do
d.delete;
d.first;
while not d.eof do begin
d.edit;
D.FieldByName( 'astachange').AsInteger:=ord(dtedit);
d.fieldbyName( 'CompanyName').AsString:= 'ASTA Technology Group';
//changing all the fields for this one for the broadcast
d.post;
d.next;
end;
d.first;
TAstaServerSocket(ServerSocket).ManualBroadCastProviderchanges( 'AstaDataModule.CustomerProvi
der','',d);
finally
d.free;
end;
except

© 1997-2002 ASTA Technology Group Inc


53 ASTA 3 Tutorials

TAstaServerSocket(ServerSocket).SendAsyncExceptionUserRecord(TAstaThread(Sender).ThreadedClien
t, 1000,Exception(exceptObject). Message);
end;
end;
end;

© 1997-2002 ASTA Technology Group Inc


54

Endnotes 2... (after index)

© 1997-2002 ASTA Technology Group Inc

You might also like