asta3Tutorials
asta3Tutorials
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.
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
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
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 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
Part
I
3 ASTA 3 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.
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.
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.
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.
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.
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.
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
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.
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;
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.
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;
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;
Aggregates
Cached Updates
Constraints
Indexes
Master Detail
Packet Fetches
Sorting
SuitCase
Transactions
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 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.
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.
1.3.4 Constraints
Requires
AstaBDEServer to be running
Description
Using ASTA Expressions you can define:
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.
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.
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.
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.
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
indexes and just do quick sorts. This demo shows how to use SortDataSetbyFieldName
and SortDataSetbyFieldNames.
end;
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.
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
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;
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.
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.
Below is a screen shot of the client. Notice the options to Delete waiting Messings,
broadcast, and define and broadcast to groups.
1.4.2 CodedParamList
This tutorial includes a client and a server.
Server Side
end;
Client Side
1.4.3 CodedDBParamList
Requires
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
=======
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.
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.
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.
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.
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.
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
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
OutParams[0].loadFromFile(FileName);
end;
end;
end;
Client Side
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.
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
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.
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.
The Client Side code shows how to send one file or a file mask of files to the server very
efficiently.
Below is a shot from the server log showing the actually sizes and more info as files come
in.
1.4.6 RemoteDirectory
Declaration
Description
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
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
The ServerDataModule defines one ServerMethod that has a String Param of "FileMask".
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.
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
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.
Method 1 : TestMethod
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.
ParambyName( 'InputParam').AsInteger:=StrtoInt(Edit1.text);
refiresql;//this does a disable control/close/open/enable controls
end;
end;
Method 2 : GetFile
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;
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.
Here is the code from the server that sets the server up for threading.
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
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.
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.
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.
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.
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.
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.
Login
Skywire Emulator
Stateless Authentication
1.7.1 Login
Requires
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
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.
The important piece is setting the Var LoginVerified:Boolean to true to authenticate the
Client.
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.
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.
Server
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!
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.
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.
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.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 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.
· 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.
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.
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
Value Meaning
coNoCookie No cookie information
Declaration
Description
1.7.3.6 DatabaseSetup
Declaration
Description
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 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.
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.
Source for ASTA database servers are available for download and
a binary of the Asta3ADOServer can also be downloaded.
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.
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.
This code shows how you could use the TAstaServerSocket.OnCheckOutSession Event.
The following code insures that certain socket errors are not shown in the server log.
begin
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;
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
TAstaServerSocket(ServerSocket).SendAsyncExceptionUserRecord(TAstaThread(Sender).ThreadedClien
t, 1000,Exception(exceptObject). Message);
end;
end;
end;