Improve company productivity with a Business Account.Sign Up

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 571
  • Last Modified:


how can i take form results from asp page to delphi?

I will increase points as i gain

  • 2
1 Solution
Read this. It details the basics of ASP under Delphi and covers outputting data, editing data, and getting data back

The Neil =:)

Using COM and Delphi with ASP

The following document aims to outline the development of COM objects (under Delphi) that deal with ASP pages. To keep this explanation as simple and clear as possible, the document will deal with a simple system that displays data from a TStringList, allows the user to edit it, and retrieves the data back from the form. There will then be three further sections detailing how to extract server information, some notes about sessions, and an example of how ASP/Delphi/COM can work in the real world.

NOTE: We?re trying to create ASP pages and it?s worth noting that the more complex the ASP page, the slower it will be, so try to keep as much processing in the COM object rather than placing this complexity into the ASP.

Create the COM

As with all COM objects in Delphi, create the ActiveX Library and then create an Active Server Object (called ASP_TestObject for our example). This will create two vitally important methods automatically: OnStartPage and OnEndPage.

These two methods are ideal for creating and destroying our data variables, initialising the system etc. as they are run when the COM object is created and when it is destroyed. At the moment they?ll look something like:

procedure TASP_TestObject.OnStartPage(CONST AScriptingContext: IUnknown): HResult;
  inherited OnStartPage(AScriptingContext);

procedure TASP_TestObject.OnEndPage;
  inherited OnEndPage;

Looking slightly higher up the code will reveal the ?magic? that enables Delphi to communicate with ASP. ASPTLB in the USES list is a bit of a giveaway and it?s this that is doing the hard work for us. To look at it directly (and you?ll need to sooner or later) head to c:\program files\borland\delphi 5\source\rtl\win.

Register your ActiveX Server and that?s the basic COM object defined and ready to go. From here on in, we?re simply adding the functions that we want rather than those that are needed.

Displaying Some Data

Of course, we need to declare something to store our data in and our declaration for the stringlist needs to be placed in the PROTECTED section of the Object definition (remember to add the CLASSES unit to the USES list). At this stage, this will look something like:

  TASP_TestObject = class(TASPObject, IASPTest1Obj)
    stlSample_Data: TStringList;
    procedure OnEndPage; safecall;
    procedure OnStartPage(const AScriptingContext: IUnknown); safecall;

We can use the OnStartPage and OnEndPage routines to handle creating and destroying our stringlist at the correct times (i.e. when the systems starts and when it ends).

The stringlist is just a common or garden object and we can create and destroy it in the usual way so just add the code to the OnStartPage and OnEndPage routines. As this is going to be a really simple system, we can also put some dummy data into it at this point, which makes our OnPageStart routine:

procedure TASP_TestObject.OnStartPage(const AScriptingContext: IUnknown);
  iCnt : INTEGER;
  inherited OnStartPage(AScriptingContext);

  stlSample_Data := TStringList.Create;

  FOR iCnt := 1 TO 10
    stlSample_Data.Add('Test Data ' + IntToStr(iCnt));

We now need a way to display the data BUT it also has to be available to the outside world. Flick back to the TLB editor dialog and open up the INTERFACE branch of the tree. We only need a display routine at the moment but we?ll define all three routines (display, edit, and validate) at once to save time later. Open the Interface branch of the tree in the Type Library Editor dialog, and click the New Method speed button (the green arrow). Create three new methods and call them DISPLAY, EDITOR, and VALIDATE. Refresh the implementation (using the Refresh Implementation speed button) to get the new methods defined in our PAS file and then we?re ready to start doing something interesting.

What we need to do is create a simple HTML script that simply displays the contents of our stringlist and has a button that allows us to edit it.

procedure TASP_TestObject.Display;
  iCnt : INTEGER;
  //Define the form tag, and define WHERE we?ll goto if the user wants to edit the data
  Response.Write('<FORM NAME="ASP Test-Display" Action="Editor.asp?ActionType=0" Method="POST">');

  //Create a quick title
  Response.Write('<P> Test Data (Text) </P>');        //This is the universal Delphi mechanism for outputting a command to ASP ? this example will output the command ?<P> Test Data (Text) </P>? (which will get interpreted (by the user?s browser) to mean a paragraph containing the text ?Test Data (Text)?) but ANY output can be done in this fashion

  //Output the data itself (One item per line as pure text)
  FOR iCnt := 0 TO (stlSample_Data.Count - 1)
    Response.Write(stlSample_Data[iCnt] + ' <BR>');   //Output the data itself

  //Create the button
  Response.Write('<INPUT TYPE=SUBMIT VALUE="Edit">'); //Although we?re defining a button, we still use the same Delphi output mechanism, just with a different HTML command

  //Close the form tag

So we now have a COM object but how do we test it? Obviously it?s not possible to test a COM object from within Delphi so we have to define some ASP files. Delphi will have created a blank .ASP file for us and most of it can be ignored. The important line is:

<% Set DelphiASPObj = Server.CreateObject("Project1.ASP_Test")
   DelphiASPObj.{Insert Method name here}

For our example, replace {Insert Method name here} with Display, so that it ends up looking like:

<% Set DelphiASPObj = Server.CreateObject("Project1.ASP_Test")

Build the COM object, register it if it hasn?t already been done (using either Delphi?s Register ActiveX Server command (on the Run menu), RegSvr32, etc.) and then view your ASP file using Microsoft?s Personal Web Server (setup to point at the correct .ASP file). Personal Web Server (PWS) is a system under Windows NT that allows us to test web pages, ASP files etc. without creating an actual web on an actual server ? in effect, it turns your machine into your own personal web server (hence the name).

Setting up PWS is a relatively simple task but we?ll go through the process just in case. Firstly, install the software and get it running. The icons down the left hand side of the PWS window allow us access to various publishing and editing tools but it?s Main and Advanced that we?re interested in. The Main page shows us where our ?server? is located, and when you enter this URL into your browser when PWS is running, you?ll end up viewing the pages contained in the specified directory. This is all setup for you so there is nothing that needs changing here. The Advanced page is where we need to make a change though. Make sure that Enable Default Document is checked and that the name of the default document corresponds to the name of the ASP file that we intend to test (a good name is Default.ASP). Once that?s set, make sure that your .ASP file actually exists in your PWS path (as specified on the Main page) ? you will need to copy your Delphi created .ASP file across. Then simply try to connect to your ?server? as you would with any other web page.

On the Main page
Home Page: http://develop24
Home Directory: c:\InetPub\wwwroot

On the Advanced page
Default Document: default.asp

As long as the file default.asp exists in c:\InetPub\wwwroot then you will be able to view it by connecting to the URL http://develop24 in your web browser.

Editing the Data

Running the system that we?ve already defined will display our sample data but will cause problems when we hit the button. The edit form is just another page but although we?ll need a new .ASP file, we define the routine for it in our existing Delphi code (assuming you created the method as described above). Create the new .ASP file by simply copying the exiting Delphi created one. The method needs changing to edit it to use the method that you want to call. In our example this would mean:

<% Set DelphiASPObj = Server.CreateObject("Project1.ASP_Test")

Make sure that when you save this new file, that you use the same name as you used in the definition of the Display routine.

NOTE: Although the .ASP file and the name in the FORM tag must match, there does not need to be any connection between the name of your Delphi method and any of the filenames.

For our example, the edit routine needs to display an edit box for each item, and fill them with the current data. Again it?s a lot more HTML rather than Delphi, but the final thing should look something like:

procedure TASP_TestObject.Editor;
  iCnt : INTEGER;
  //Create the form tag and where to go next
  Response.Write('<FORM Name="ASP Test-Editor" Action="Verify.asp" Method="POST">');

  Response.Write('<P> Test Data </P>');

  //We create a new object for each item of data. To ease referencing later on, we?ll name them meaningfully
  FOR iCnt := 0 TO (stlSample_Data.Count - 1 - Info_Lines)
    Response.Write('Data Item ' + IntToStr(iCnt + 1) + ': <INPUT TYPE="TEXT" NAME="DATAEDIT' + IntToStr(iCnt) + '" VALUE="' + stlSample_Data[iCnt] + '"><BR>');  

  Response.Write('<INPUT TYPE=RESET VALUE="Cancel">');
  Response.Write('<INPUT TYPE=SUBMIT VALUE="Submit">');

Getting the Data Back

We can now display the data, and allow the user to edit it, but how do we get the modified values back and actually use them?

Again it?s another .ASP file affair, so create your file and make sure that it?s name matches the name specified in the calling routine (in our example system this would therefore be VERIFY.ASP as that was the name specified in the FORM tag).

After we?ve retrieved our data we can do whatever we want with it but for this example we?ll just display it again as a way of showing that the changes have been registered.

procedure TASPTest1Obj.Validate;
  iCnt : INTEGER;
  //Get the data back. NOTE that the item names match the names defined in the previous routine
  FOR iCnt := 0 TO (stlSample_Data.Count - 1)
    stlSample_Data[iCnt] := Request.Form.Item['DATAEDIT' + IntToStr(iCnt)];  //Rather than use the Response interface, we now need to use Request as we are retrieving data rather than outputting it. In this case we?re requesting a particular item (although we?re building a text string for the item name, we can pass a pure text string containing the name of the item that we want)

  //Display the new data. We could do anything at this point but this is simple
  Response.Write('<FORM Name="ASP Test-Verify" Action="">');
  Response.Write('<P> Test Data (Text) </P>');

  FOR iCnt := 0 TO (stlSample_Data.Count - 1)
    Response.Write(stlSample_Data[iCnt] + ' <BR>');

  //We need someway to get off this page so create a button that takes us back to the start
  Response.Write('<INPUT TYPE="Button" VALUE="Ok" OnClick="HTTP://develop24">');

Extracting Other Information

There are actually several methods for retrieving data, the above example accesses the form directly but values can be extracted from the URL address (using QueryString), Cookies, the ClientCertificate (if there is one), and the server variables.

Server information is extremely easy to obtain under ASP but can obviously be extremely useful. Firstly we need to get ALL of the server information back and then extract the things that we want.

  Server_Data : IRequestDictionary;
  Server_Data := Request.ServerVariables;               //We want data back so use Request rather than Response
  sTemp_Str := Server_Data.Get_Item('HTTP_USER_AGENT'); //We now have ALL the data so use the Get_Item method to extract the individual value

The above example extracts the BROWSER that the user is viewing our page(s) on. I?ll digress here as this situation is highly relevant to us. Knowing what type of browser is being used would allow us to provide the very best display possible for any given browser, rather than aiming at the most basic type of display. The actual string returned by this, using this parameter, would be something along the lines of:

Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)

Pretty meaningless and as there are so many browsers out there then it might seem to be useless but help is at hand in the form of the browscap.txt file. This contains a list of browsers and their capabilities but stored in a .INI format which makes extraction totally painless (latest versions of the browscap.txt file are available from

Although there are many properties available, the most useful are
Property      Description
Query_String      Retrieves the section of the ??? in the URL string (NOTE: This is very similar to the QueryString process of data extraction)
Logon_User      Returns the Windows NT account details of the current user
URL      The URL of the current page
HTTP_USER_AGENT      Returns information about the browser being used (see above)
HTTP_CONNECTION      The type of connection being used
HTTP_REFERER      The URL of the page where we came FROM
Server_Software      The name and version of the web server software
Server_Protocol      Protocol name and version based on the software on the server and client side
Server_Port_Secure      Hostname or IP of the server, TCP/IP port, and encryption port (1 indicates that the request is on an encrypted port)
Remote_Ident      The IP Address, hostname, and ident of the host (if it supports RFC931)

As all of these (and all the others) are all extracted in the initial call to Request.ServerVariables, it is simply a case of selecting which property to retrieve when using Get_Item and passing the appropriate property name (see the above example).


Although the Server Variables contain a wealth of information, they do not include everything, but fortunately help is at hand in the form of the session data. This contains information specifically about the current session, but what is a session? Luckily it?s not a complex concept to understand (in fact it?s easy): A session is the time that a user spends in the system, from when he/she first enters until the time that he/she leaves. Within ASP we have the SESSION object that has a several properties and methods that allow us to extract as much information as we need.

Actually accessing the Session is even easier than accessing the Server Variables as the session object is predefined for us by ASPTLB (it?s called Session).

The options available (and useful to us) are
Name            Description
SessionID      Property      Returns the session ID string which is unique to this user
LCID      Property      Returns the locale identifier
Abandon      Procedure      Ends the current session

Potentially the most useful property (for us) is the Session ID, as this allows us to uniquely identify each user within the system and maintain his/her specific data efficiently (and more importantly, correctly). For example:

  sUser_ID : STRING;
  sUser_ID := Session.SessionID;  //Like Response and Request, Server is a standard interface to allow us access to ASP

TheNeil this document is nearly ununderstandable. Can you explain it a little understanable? i really need it i think also yarasakol

What do you mean by ununderstandable? I know that Word has gone and replaced single quotes with question marks (grrr) but it covers how to create ASP objects totally from scratch. It then details how to output data, get data back, edit data etc.

Is there something specific that you're having problems with?

The Neil =:)
Russell LibbySoftware Engineer, Advisory Commented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

To accept TheNeil's comment as answer

Please leave any comments here within the next seven days.
Thank you,

EE Cleanup Volunteer
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now