Using the Delphi Edition Components in IntraWeb Applications


IntraWeb applications serve many users at once, and each user session can process requests on a different thread. A component instance must therefore never be shared between sessions (e.g., by declaring it as a global variable), since one session could change its properties or call its methods while another session is using it.

The simplest approach is to create the component at runtime in the procedure that uses it, assign any event handlers in code, and free it when the operation is complete. Each request then works with its own instance.

uses
  ServerController, ipwhttp;

procedure TIWForm1.IWButton1Click(Sender: TObject);
var
  http: TipwHTTP;
begin
  http := TipwHTTP.Create(nil);
  try
    http.OnStatus := HTTPStatus;
    http.Get('https://www.example.com/');
    WebApplication.ShowMessage(http.TransferredData);
  finally
    http.Free;
  end;
end;

procedure TIWForm1.HTTPStatus(Sender: TObject; const HTTPVersion: String;
  StatusCode: Integer; const Description: String);
begin
  // Handle the status line returned by the server.
end;

The event handler must be a method of an object (such as the form) with the same signature as the event. The declaration of each event type (e.g., TStatusEvent for the OnStatus event) can be found in the unit of the component.

Keeping an Instance for the Session

When the same instance must be used across several requests (e.g., to keep a connection to a server open while the user works), create it in the user session object instead, and free it when the session ends. In a standard IntraWeb application, the user session is the TIWUserSession class in the UserSessionUnit unit, which is created once for each session. In the example below, the ipwftp unit must be added to the uses clause of UserSessionUnit.

type
  TIWUserSession = class(TIWUserSessionBase)
    procedure IWUserSessionBaseCreate(Sender: TObject);
    procedure IWUserSessionBaseDestroy(Sender: TObject);
  public
    FTP: TipwFTP;
  end;

procedure TIWUserSession.IWUserSessionBaseCreate(Sender: TObject);
begin
  FTP := TipwFTP.Create(nil);
end;

procedure TIWUserSession.IWUserSessionBaseDestroy(Sender: TObject);
begin
  FTP.Free;
end;

The instance can then be accessed from the forms of the session through the UserSession function of the ServerController unit (e.g., UserSession.FTP). Since an instance in the user session belongs to a single session, it is not shared with other users.

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.