Solved

ASP

Posted on 2001-07-09
5
555 Views
Last Modified: 2010-04-06
how can i take form results from asp page to delphi?

I will increase points as i gain

Thanks.
0
Comment
Question by:yarasakol
  • 2
5 Comments
 
LVL 5

Accepted Solution

by:
TheNeil earned 20 total points
Comment Utility
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;
begin
  inherited OnStartPage(AScriptingContext);
end;

procedure TASP_TestObject.OnEndPage;
begin
  inherited OnEndPage;
end;

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:

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

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);
VAR
  iCnt : INTEGER;
begin
  inherited OnStartPage(AScriptingContext);

  stlSample_Data := TStringList.Create;

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

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;
VAR
  iCnt : INTEGER;
begin
  //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)
  DO
    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
  Response.Write('</FORM>');
end;

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")
   DelphiASPObj.Display
%>

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.

E.g.
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")
   DelphiASPObj.Editor
%>

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;
VAR
  iCnt : INTEGER;
begin
  //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)
  DO
    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">');
  Response.Write('</FORM>');
end;


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;
VAR
  iCnt : INTEGER;
begin
  //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)
  DO
    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)
  DO
    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">');
  Response.Write('</FORM>');
end;


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.

VAR
  Server_Data : IRequestDictionary;
  ?
begin
  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
  ?
end;

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 http://www.aspalliance.com/juan/browscap.zip).

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_Name
Server_Port
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_Addr
Remote_Host
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).


Sessions

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:

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

0
 

Expert Comment

by:systemop
Comment Utility
TheNeil this document is nearly ununderstandable. Can you explain it a little understanable? i really need it i think also yarasakol
0
 
LVL 5

Expert Comment

by:TheNeil
Comment Utility
Systemop,

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 =:)
0
 
LVL 26

Expert Comment

by:Russell Libby
Comment Utility
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.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Thank you,
Russell

EE Cleanup Volunteer
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the…
Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now