Archive

Author Archive

[EMBARCADERO – DELPHI] – How to access REST Services using TRESTClient, TRESTRequest and TRESTResponse components

25 February 2018 1 comment

This demo shows how to access REST Services using TRESTClient, TRESTRequest and TRESTResponse components.

In the examples, some REST Services provided by: IEX TradingeBayOpenWeatherMap, The Wall Street Journal, and Wikipedia.

 

Here are the links for more datails and how to get the corrisponding Api Keys, if nedded:

***

… and here is the whole .dpr to download:  RestApiDemo.zip

***

// *****************************************************************************
//   Unit    : Main.pas (Main.fmx)
//   Project : RestApiDemo.dpr
//   Remarks : How to use RESTClient, RESTRequest, RESTResponse components
//   IDE     : Embarcadero - Delphi 10 
//   ...
// *****************************************************************************
unit Main;

interface
uses
  System.SysUtils, System.Types, System.UITypes, System.Classes,
  System.Variants, System.DateUtils,System.SyncObjs, System.Math,
  System. Generics.Collections,
  System.Rtti, System.Bindings.Outputs,

  System.JSON,
  System.JSON.Builders, System.JSON.Readers,

  FMX.Types, FMX.Forms, FMX.Dialogs, FMX.Layouts,
  FMX.Objects, FMX.ListBox, FMX.Ani, FMX.Gestures, FMX.StdCtrls,
  FMX.DateTimeCtrls, FMX.Graphics,
  FMX.Media, FMX.ScrollBox, FMX.Memo, FMX.Calendar, FMX.Edit,
  FMX.Controls, FMX.Controls.Presentation,
  FMX.TreeView, FMX.TabControl,

  REST.Utils,
  REST.Types,
  REST.Client,
  REST.Response.Adapter,
  REST.Authenticator.Simple,
  REST.Authenticator.Basic,
  REST.Authenticator.OAuth, IPPeerClient, Data.Bind.Components;

type
  TFMain = class(TForm)
    StyleBook2: TStyleBook;
    Layout_Form: TLayout;
    Layout_Main: TLayout;
    Rectangle27: TRectangle;
    Layout_Top_Header: TLayout;
    Layout_Header: TLayout;
    Layout_Title: TLayout;
    LTITLE: TLabel;
    ToolbarHolder: TLayout;
    ToolbarPopup: TPopup;
    ToolbarPopupAnimation: TFloatAnimation;
    ToolBar: TToolBar;
    ToolbarCloseButton: TButton;
    Layout_Top_Line: TLayout;
    Top_Line: TRectangle;
    Layout_Description: TLayout;
    LDESCRIPTION: TLabel;
    LTEXT_1: TLabel;
    Layout_Providers: TLayout;
    Layout_Choose_Provider: TLayout;
    Provider_List: TListBox;
    ListBoxItem1: TListBoxItem;
    ListBoxItem2: TListBoxItem;
    ListBoxItem3: TListBoxItem;
    ListBoxItem4: TListBoxItem;
    Layout_Snoopy: TLayout;
    Image1: TImage;
    Layout_Callout_Text: TLayout;
    CalloutRectangle1: TCalloutRectangle;
    Label2: TLabel;
    Label3: TLabel;
    LTEXT_2: TLabel;
    Label1: TLabel;
    Memo: TMemo;
    Layout_Response: TLayout;
    Layout_Header_Response: TLayout;
    LABEL_HEADER_RESPONSE: TLabel;
    Label6: TLabel;
    LABEL_TEXT_REQUEST: TLabel;
    Layout_Top_Header_Response: TLayout;
    Layout_Request: TLayout;
    Layout8: TLayout;
    Layout9: TLayout;
    Layout_Execute_Button: TLayout;
    Layout_Provider_List: TLayout;
    Layout_List_Examples: TLayout;
    Layout_Callout: TLayout;
    Layout_Header_List_Examples: TLayout;
    LABEL_HEADER_EXAMPLES: TLabel;
    Tab_List_Examples: TTabControl;
    Tab_Item_1_IEXTrading: TTabItem;
    Tab_Item_2_eBay: TTabItem;
    Tab_Item_3_WeatherMap: TTabItem;
    Tab_Item_4_WallStreetJournal: TTabItem;
    BTN_BACKGROUND: TRectangle;
    BTN_LABEL: TLabel;
    BTN_EXECUTE: TLayout;
    Layout_Header_Response_Container: TLayout;
    Layout_Memo: TLayout;
    Layout_Examples_Container: TLayout;
    Layout1: TLayout;
    Label4: TLabel;
    List_Examples_WeatherMap: TListBox;
    ListBoxItem_3_1: TListBoxItem;
    Layout10: TLayout;
    Rectangle4: TRectangle;
    Layout11: TLayout;
    LABEL_EXAMPLE_3_1: TLabel;
    BTN_BORDER: TRectangle;
    Layout_Label_Response: TLayout;
    LABEL_RESPONSE: TLabel;
    List_Examples_IEXTrading: TListBox;
    ListBoxItem_1_1: TListBoxItem;
    Layout12: TLayout;
    Rectangle5: TRectangle;
    Layout13: TLayout;
    LABEL_EXAMPLE_1_1: TLabel;
    ListBoxItem_1_2: TListBoxItem;
    Layout14: TLayout;
    Rectangle6: TRectangle;
    Layout15: TLayout;
    LABEL_EXAMPLE_1_2: TLabel;
    ListBoxItem5: TListBoxItem;
    Tab_Item_5_WordPress: TTabItem;
    List_Examples_Wikipedia: TListBox;
    ListBoxItem6: TListBoxItem;
    Layout16: TLayout;
    Rectangle7: TRectangle;
    Layout17: TLayout;
    LABEL_EXAMPLE_5_1: TLabel;
    List_Examples_WallStreetJournal: TListBox;
    ListBoxItem_4_1: TListBoxItem;
    Layout2: TLayout;
    Rectangle1: TRectangle;
    Layout3: TLayout;
    LABEL_EXAMPLE_4_1: TLabel;
    ListBoxItem_4_2: TListBoxItem;
    Layout4: TLayout;
    Rectangle2: TRectangle;
    Layout5: TLayout;
    LABEL_EXAMPLE_4_2: TLabel;
    ListBoxItem_4_3: TListBoxItem;
    Layout6: TLayout;
    Rectangle3: TRectangle;
    Layout7: TLayout;
    LABEL_EXAMPLE_4_3: TLabel;
    List_Examples_EBay: TListBox;
    ListBoxItem_2_1: TListBoxItem;
    Layout18: TLayout;
    Rectangle8: TRectangle;
    Layout19: TLayout;
    LABEL_EXAMPLE_2_1: TLabel;
    Layout20: TLayout;
    LABEL_MSG: TLabel;

    // ... FORM EVENTS
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
                          Shift: TShiftState; X, Y: Single);
    procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo;
                          var Handled: Boolean);
    procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
                          Shift: TShiftState);

    // ... CLICK ON PROVIDER LIST
    procedure Provider_List_Click(Sender: TObject);

    // ... CLICK ON LIST OF EXAMPLES
    procedure List_Of_Examples_Click(Sender: TObject);

    // ... IEX TRADING REST API SERVICES
    procedure IEXTrading_Prepare_Request();
    procedure IEXTrading_Display_Response();

    // ... E-BAY REST API SERVICES
    procedure EBay_Prepare_Request();
    procedure EBay_Display_Response();

    // ... WEATHER MAP REST API SERVICES
    procedure Weather_Prepare_Request();
    procedure Weather_Display_Response();

    // ... WALL STREET JORNAL API REST SERVICES
    procedure WallStreetJournal_Prepare_Request();
    procedure WallStreetJournal_Display_Response();

    // ... WIKIPEDIA REST API SERVICES
    procedure Wikipedia_Prepare_Request();
    procedure Wikipedia_Display_Response();

    // ...
    procedure HideListOfExamples();
    procedure ShowListOfExamples();

    procedure ShowHeaderResponse();
    procedure HideHeaderResponse();

    // ... PARSE JSON OBJECT
    procedure parseJSONObject( p_jsonValue     : TJSONValue;
                               p_jsonString    : TJSONString;
                               p_jsonPairEnum  : TJSONPairEnumerator;
                               p_jsonArrayEnum : TJSONArrayEnumerator );

    procedure BTN_EXECUTEClick(Sender: TObject);
    procedure BTN_EXECUTEMouseEnter(Sender: TObject);
    procedure BTN_EXECUTEMouseLeave(Sender: TObject);

    procedure ToolbarCloseButtonClick(Sender: TObject);
    procedure MainLayoutMouseUp(Sender: TObject; Button: TMouseButton;
                                Shift: TShiftState; X, Y: Single);
    
  private
    // ... PRIVATE DECLARATIONS
    FGestureOrigin      : TPointF;
    FGestureInProgress  : Boolean;
    procedure ShowToolbar(AShow: Boolean);
  public
    // ... PUBLIC DECLARATIONS
  end;

var
    FMain           : TFMain;

    RESTClient      : TRESTClient;
    RESTRequest     : TRESTRequest;
    RESTResponse    : TRESTResponse;

    // ... CURRENT PROVIDER, LIST OF EXAMPLE, ID EXAMPLE
    IdProvider      : Integer;
    IdListOfExample : TListBox;
    IdExample       : Integer;

implementation
{$R *.fmx}

// *****************************************************************************
//   EVENT : FormCreate()
//           ON FORM CREATE
// *****************************************************************************
procedure TFMain.FormCreate(Sender: TObject);
begin
    // ... CREATE REST COMPONENTS:

    // ... REST Client
    RESTClient              := TRESTClient.Create(nil);

    // ... REST Request
    RESTRequest             := TRESTRequest.Create(nil);

    // ... REST Response
    RESTResponse            := TRESTResponse.Create(nil);

    // ... BIND RESTClient AND REST Response TO REST Request
    RESTRequest.Client      := RESTClient;
    RESTRequest.Response    := RESTResponse;
end;
// .............................................................................

// *****************************************************************************
//   EVENT : FormShow()
//           ON FORM SHOW
// *****************************************************************************
procedure TFMain.FormShow(Sender: TObject);
begin
    // ... HIDE LIST OF EXAMPLES
    HideListOfExamples();

    // ... HIDE HEADER RESPONSE
    HideHeaderResponse();
end;
// .............................................................................

// *****************************************************************************
//   EVENT : Provider_List_Click()
//           CLICK ON PROVIDER LIST
// *****************************************************************************
procedure TFMain.Provider_List_Click(Sender: TObject);
var
    __iItem : Integer;
begin
    // ... GET SELECTED PROVIDER
    __iItem     := Provider_List.ItemIndex;

    // ...  SAVE SELECTED PROVIDER
    idProvider  := ( __iItem + 1 );

    case idProvider of
     1 : begin
            // ... IEX TRADING - REST SERVICES
            LABEL_HEADER_EXAMPLES.Text := '> IEX Trading REST Services';
            // ... ASSIGN THE CORRESPONDING TListBox
            IdListOfExample            := List_Examples_IEXTrading;
         end;
     2 : begin
            // ... e-BAY - REST SERVICES
            LABEL_HEADER_EXAMPLES.Text := '> E-Bay REST Services';
            IdListOfExample            := List_Examples_EBay;
         end;
     3 : begin
            // ... WEATHER MAP - REST SERVICES
            LABEL_HEADER_EXAMPLES.Text := '> Weather Map REST Services';
            IdListOfExample            := List_Examples_WeatherMap;
         end;
     4 : begin
            // ... THE WALL STREET JURNAL - REST SERVICES
            LABEL_HEADER_EXAMPLES.Text := '> The Wall Street Journal REST Services';
            IdListOfExample            := List_Examples_WallStreetJournal;
         end;
     5 : begin
            // ... WIKIPEDIA - REST SERVICES
            LABEL_HEADER_EXAMPLES.Text := '> Wikipedia REST Services:';
            IdListOfExample            := List_Examples_Wikipedia;
         end;
    end;

    // ... SHOW THE LIST OF EXAMPLES
    ShowListOfExamples();

    // ... HIDE HEADER RESPONSE
    HideHeaderResponse();
end;
// .............................................................................

// *****************************************************************************
//   EVENT : List_Of_Examples_Click()
//           CLICK ON LIST OF EXAMPLES
// *****************************************************************************
procedure TFMain.List_Of_Examples_Click(Sender: TObject);
var
    __iItem       : Integer;
begin
    // ... GET ITEM INDEX
    __iItem         := IdListOfExample.ItemIndex;

    // ... SAVE SELECTED EXAMPLE
    idExample       := ( __iItem + 1 );

    // ... DISPLAY HEADER RESPONSE
    ShowHeaderResponse();

    // ... PREPARE REQUESTS
    case idProvider of
    1 : begin
            // ... IEX TRADING - REST REQUEST
            IEXTrading_Prepare_Request();
        end;
    2 : begin
            // ... e-BAY - REST REQUEST
            EBAY_Prepare_Request();
        end;
    3 : begin
            // ... WEATHER MAP - REST REQUEST
            Weather_Prepare_Request();
        end;
    4 : begin
            // ... THE WALL STREET JURNAL - REST REQUEST
            WallStreetJournal_Prepare_Request();
        end;
    5 : begin
            // ... WIKIPEDIA - REST REQUEST
            Wikipedia_Prepare_Request();
        end;
    end;
end;
// .............................................................................

// *****************************************************************************
//   EVENT : BTN_EXECUTEClick()
//           CLICK ON EXECUTE BUTTON
// *****************************************************************************
procedure TFMain.BTN_EXECUTEClick(Sender: TObject);
begin
    // ... CLEAR RESPONSE
    LABEL_RESPONSE.Visible := True;
    Memo.lines.Clear;
    Memo.Lines.Add('... wait, please :)');
    Application.ProcessMessages;

    // ... !!! EXECUTE REQUEST !!!
    RESTRequest.Execute;

    case idProvider of
    1 : begin
            // ... IEX TRADING - RESPONSE
            IEXTrading_Display_Response();
        end;
    2 : begin
            // ... e-BAY - RESPONSE
            EBAY_Display_Response();
        end;
    3 : begin
            // ... WEATHER MAP - RESPONSE
            Weather_Display_Response();
        end;
    4 : begin
            // ... THE WALL STREET JOURNAL - RESPONSE
            WallStreetJournal_Display_Response();
        end;
    5 : begin
            // ... WORDPRESS - RESPONSE
            Wikipedia_Display_Response();
        end;
    end;
end;
// .............................................................................


// ... >>> IEX TRADING REQUEST

// *****************************************************************************
//   PRECEDURE : IEXTrading_Prepare_Request()
//               PREPARE THE REQUEST
// *****************************************************************************
procedure TFMain.IEXTrading_Prepare_Request();
var
    __searchSymbol : String;
begin

    // ... IEX TRADING - SERVICES ABOUT TRADING AND STOCKS EXCHANGE:
    // ... http://iextrading.com
    // ... https://iextrading.com/developer/docs/

    // ... !!! NO API KEY !!!
    // ... All Data are provided for free by IEX.

    // ... Example 1. - QUOTES FOR THE TOP 10 SYMBOLS
    //     https://ws-api.iextrading.com/1.0/stock/market/list/mostactive

    // ... Example 2. - QUOTE FOR A SYMBOL
    //     https://ws-api.iextrading.com/1.0/tops?symbols=FB';

    // ... CLEAR PARAMTERS LIST
    RESTRequest.Params.Clear;

    case idExample of
    1 : begin
            // ... Example 1. - QUOTES FOR THE TOP SYMBOLS
            RESTClient.BaseURL  := 'https://ws-api.iextrading.com/1.0/stock/market/list/mostactive';
        end;
    2 : begin
            // ... Example 2. - QUOTE FOR A SYMBOL

            // ... quote for symbol 'FB' = FaceBook
            __searchSymbol      := 'FB';

            RESTClient.BaseURL  := 'https://ws-api.iextrading.com/1.0/stock';
            RESTClient.BaseURL  := RESTClient.BaseURL + __searchSymbol;
            RESTClient.BaseURL  := RESTClient.BaseURL + '/quote';
        end;
    end;
end;
// .............................................................................

// *****************************************************************************
//   PRECEDURE : IEXTrading_Display_Response()
//               PARSE AND DISPLAY RESPONSE
// *****************************************************************************
procedure TFMain.IEXTrading_Display_Response();
var
    __jsonValue     : TJSONValue;
    __symbols       : TJSONArray;
    __symbol        : TJSONObject;
    __pairInfo      : TJSONValue;
    __nSymbols      : Integer;
    __i             : Integer;
begin

    // ... >> GET RESPONSE TYPE
    Memo.Lines.Add('** RESPONSE TYPE : ' + RESTResponse.ContentType);
    Memo.Lines.Add( '=================================================');

    // ... >> DISPLAY THE WHOLE CONTENT
    // Memo.Lines.Add( RESTResponse.Content );
    // Memo.Lines.Add( '=================================================');
    // Memo.Lines.Add( '');

    // ... >> PARSE & DISPLAY ALL PROPERTIES

    // ... GET RESPONSE VALUE
    __jsonValue     := RESTResponse.JSONValue;

    parseJSONObject( __jsonValue, nil, nil, nil );
    Memo.Lines.Add( '=================================================');
    Memo.Lines.Add( '');


    // ... >> OR ITERATE ON OBJECT AND GET PROPERTIES

    // ... ALL SYMBOLS RETURNED ARE ITEMS OF AN ARRAY
    if ( __jsonValue is TJSONArray ) then begin

        // ... GET ARRAY
        __symbols   :=  TJSONArray( __jsonValue );

        // ... READ MAX THE TOP 10 SYMBOLS
        __nSymbols  := __symbols.Count;
        if ( __nSymbols > 10 ) then __nSymbols := 10;

        __i := 0;
        while ( __i < __nSymbols ) do begin // ... GET i-th SYMBOL __symbol := TJSONObject( __symbols.Items[ __i ] ); Memo.Lines.Add( '>> ' + 'SYMBOL[' + Inttostr( __i + 1) + ']: ');

            // ... CONTENT OF i-th SYMBOL
            // Memo.Lines.Add( __symbol.ToString );

            __pairInfo := __symbol.GetValue('symbol');
            Memo.Lines.Add( '- SYMBOL       : ' + __pairInfo.Value);
            __pairInfo := __symbol.GetValue('companyName');
            Memo.Lines.Add( '- COMPANY      : ' + __pairInfo.Value);
            // __pairInfo := __symbol.GetValue('latestPrice');
            Memo.Lines.Add( '- LATEST PRICE : ' + __pairInfo.Value);
            // ... etc..

            Memo.Lines.Add( '=================================================');
            __i := __i + 1;
        end
    end
    else begin
        Memo.Lines.Add( '... SYMBOL NOT FOUND!');
        Memo.Lines.Add( '=================================================');
    end;
end;
// .............................................................................

// .............................................................................
// .............................................................................
// .............................................................................

// ... >>> E-BAY REST REQUEST

// *****************************************************************************
//   PRECEDURE : EBAY_Prepare_Request()
//               PREPARE THE REQUEST
// *****************************************************************************
procedure TFMain.EBAY_Prepare_Request();
var
    __securityAppName   : String;
    __searchSymbol      : String;
    __globalID          : String;

begin

    // ... E-BAY REST SERVICES
    //     https://go.developer.ebay.com/

    // ... USER GUIDE:
    //     http://developer.ebay.com/Devzone/finding/Concepts/FindingAPIGuide.html

    // ... API REFERENCE:
    //     http://developer.ebay.com/Devzone/finding/CallRef/index.html

    // ... !!!E-BAY REST API NEEDS API KEY!!!

    // ... !!!GET YOUR APPLICATION KEY!!! (free)

    // ... AND ASSIGN TO SECURITY APPLICATION NAME
    // __securityAppName := '<your App ID (Client ID)>';

    // ... CLEAR PARAMTERS LIST
    RESTRequest.Params.Clear;

    case idExample of
    1 : begin
            // ... Example 1. FIND ITEMS BY KEYWORDS='...'
            __searchSymbol      := 'iPhone';
            __globalID          := 'EBAY-US';

            RESTClient.BaseURL  := 'https://svcs.ebay.com/services/search/FindingService/v1';

            RESTRequest.Params.AddItem;
            RESTRequest.Params[0].name     := 'SECURITY-APPNAME';
            RESTRequest.Params[0].value    := __securityAppName;

            RESTRequest.Params.AddItem;
            RESTRequest.Params[1].name     := 'OPERATION-NAME';
            RESTRequest.Params[1].value    := 'findItemsByKeywords';

            RESTRequest.Params.AddItem;
            RESTRequest.Params[2].name     := 'SERVICE-VERSION';
            RESTRequest.Params[2].value    := '1.0.0';

            RESTRequest.Params.AddItem;
            RESTRequest.Params[3].name     := 'RESPONSE-DATA-FORMAT';
            RESTRequest.Params[3].value    := 'json';

            RESTRequest.Params.AddItem;
            RESTRequest.Params[4].name     := 'keywords';
            RESTRequest.Params[4].value    := __searchSymbol;

            RESTRequest.Params.AddItem;
            RESTRequest.Params[5].name     := 'paginationInput.entriesPerPage';
            RESTRequest.Params[5].value    := '6';

            RESTRequest.Params.AddItem;
            RESTRequest.Params[6].name     := 'GLOBAL-ID';
            RESTRequest.Params[6].value    := __globalID;

            RESTRequest.Params.AddItem;
            RESTRequest.Params[7].name     := 'siteid';
            RESTRequest.Params[7].value    := '0';
        end;
    end;
end;
// .............................................................................

// *****************************************************************************
//   PRECEDURE : EBAY_Display_Response()
//               PARSE AND DISPLAY RESPONSE
// *****************************************************************************
procedure TFMain.EBAY_Display_Response();
var
    __jsonValue     : TJSONValue;
    __jsonObject    : TJSONObject;

    __responseArray : TJSONArray;
    __itemsObj      : TJSONObject;

    __searchResult  : TJSONArray;
    __resultObj     : TJSONObject;

    __fieldObj      : TJSONValue;
    __fieldArray    : TJSONArray;

    __nItems        : Integer;
    __i             : Integer;

    __items         : TJSONArray;
    __item          : TJSONObject;

    __category      : TJSONObject;
begin

    // ... >> GET RESPONSE TYPE
    Memo.Lines.Add('** RESPONSE TYPE : ' + RESTResponse.ContentType);
    Memo.Lines.Add( '=================================================');

    // ... >> DISPLAY THE WHOLE CONTENT
    // Memo.Lines.Add( RESTResponse.Content );
    // Memo.Lines.Add( '=================================================');
    // Memo.Lines.Add( '');

    // ... >> PARSE & DISPLAY ALL PROPERTIES

    // ... GET RESPONSE VALUE
    __jsonValue     := RESTResponse.JSONValue;

    parseJSONObject( __jsonValue, nil, nil, nil );
    Memo.Lines.Add( '=================================================');
    Memo.Lines.Add( '');


    // ... >> OR ITERATE ON OBJECT AND GET PROPERTIES
    __jsonObject    := TJSONObject( __jsonValue );

    __responseArray := TJSONArray( __jsonObject.GetValue('findItemsByKeywordsResponse'));
    __itemsObj      := TJSONObject( __responseArray.Items[0] );

    __searchResult  := TJSONArray( __itemsObj.GetValue('searchResult') );
    __resultObj     := TJSONObject( __searchResult.Items[0] );

    // ... COUNT
    __fieldObj      := __resultObj.GetValue('@count');
    __nItems        := strtoint( __fieldObj.Value );
    Memo.Lines.Add( 'N. ITEMS   : ' + __fieldObj.Value );

    // ... GET ALL ITEMS
    __items         := TJSONArray(__resultObj.GetValue('item'));

    __i := 0;
    while ( __i < __nItems ) do begin // ... GET i-th ITEM __item := TJSONObject( __items.Items[ __i ] ); // ... GET ITEM PROPERTIES __fieldArray := TJSONArray( __item.GetValue('itemId') ); Memo.Lines.Add( '- ITEM ID : ' + __fieldArray.Items[0].Value ); __fieldArray := TJSONArray( __item.GetValue('title') ); Memo.Lines.Add( '- TITLE : ' + __fieldArray.Items[0].Value ); // ... CATEGORY __fieldArray := TJSONArray( __item.GetValue('primaryCategory') ); __category := TJSONObject( __fieldArray.Items[0] ); Memo.Lines.Add( '- CATEGORY' ); __fieldArray := TJSONArray( __category.GetValue('categoryId')); Memo.Lines.Add( ' > ID     : ' + __fieldArray.Items[0].Value );
        __fieldArray    := TJSONArray(__category.GetValue('categoryName'));
        Memo.Lines.Add( '  > NAME   : ' + __fieldArray.Items[0].Value );

        // ... etc..

        Memo.Lines.Add( '=================================================');
        __i := __i + 1;
    end;
end;
// .............................................................................

// .............................................................................
// .............................................................................
// .............................................................................

// ... >>> WEATHER REST REQUEST

// *****************************************************************************
//   PRECEDURE : Weather_Prepare_Request()
//               PREPARE THE REQUEST
// *****************************************************************************
procedure TFMain.Weather_Prepare_Request();
var
    __apiKey : String;
begin

    // ... THE WEATHER MAP ORG PROVIDES MANY REST SERVICES ABOUT
    //     CURRENT WEATHER AND FORECAST DATA:
    // ... http://openweathermap.org/api

    // ... THE WEATHER MAP REST SERVICES NEEDS API KEY!

    // ... !!!GET YOUR API KEY!!! (free)
    __apiKey := '<your Api Key>';

    // ... Example 1. - CURRENT WEATHER IN A LOCATION
    //     http://openweathermap.org/data/2.5/weather?q=Rome&appid=<your api key>'

    // ... CLEAR PARAMTERS LIST
    RESTRequest.Params.Clear;

    case idExample of
    1 : begin
            // ... Example 1. - CURRENT WEATHER IN A CITY
            RESTClient.BaseURL := 'http://openweathermap.org/data/2.5/weather';

            // ... SET CITY
            RESTRequest.Params.AddItem;
            RESTRequest.Params[0].name     := 'q';
            RESTRequest.Params[0].value    := 'Stockholm';

            // ... SET YOUR API KEY
            RESTRequest.Params.AddItem;
            RESTRequest.Params[1].name     := 'appid';
            RESTRequest.Params[1].value    := __apiKey;
            // .........................................................................
        end;
    end;
end;
// .............................................................................

// *****************************************************************************
//   PRECEDURE : Weather_Display_Response()
//               PARSE AND DISPLAY RESPONSE
// *****************************************************************************
procedure TFMain.Weather_Display_Response();
var
    __jsonValue     : TJSONValue;
    __jsonObject    : TJSONObject;

    __pairInfo      : TJSONValue;
    __main          : TJSONObject;
    __coord         : TJSONObject;
    __sys           : TJSONObject;

    __dateTime      : TDateTime;
    __sunRise       : String;
    __sunSet        : String;
begin

    // ... >> GET RESPONSE TYPE
    Memo.Lines.Add('** RESPONSE TYPE : ' + RESTResponse.ContentType);
    Memo.Lines.Add( '=================================================');

    // ... >> DISPLAY THE WHOLE CONTENT
    // Memo.Lines.Add( RESTResponse.Content );
    // Memo.Lines.Add( '=================================================');
    // Memo.Lines.Add( '');

    // ... >> PARSE & DISPLAY ALL PROPERTIES

    // ... GET RESPONSE VALUE
    __jsonValue     := RESTResponse.JSONValue;

    parseJSONObject( __jsonValue, nil, nil, nil );
    Memo.Lines.Add( '=================================================');
    Memo.Lines.Add( '');


    // ... >> OR ACCESS THE PROPERTIES
    __jsonObject    := TJSONObject( __jsonValue );

    // ... GET RETURN CODE
    __pairInfo      := __jsonObject.GetValue('cod');

    if ( StrToInt( __pairInfo.Value ) <> 200 ) then begin

        Memo.Lines.Add('- Code    : ' + __pairInfo.Value);

        __pairInfo      := __jsonObject.GetValue('message');
        Memo.Lines.Add('- Message : ' + __pairInfo.Value);

        Memo.Lines.Add( '=================================================');
        exit;
    end;

    // ... 200 - OK, GET RESPONSE FIELDS:

    // ... CITY
    __pairInfo      := __jsonObject.GetValue('name');
    Memo.Lines.Add( '- City     : ' + __pairInfo.Value);

    // ... COUNTRY
    __sys           := TJSONObject(__jsonObject.GetValue('sys'));
    __pairInfo      := __sys.GetValue('country');
    Memo.Lines.Add( '- Country  : ' + __pairInfo.Value);

    // ... SUN RISE
    __pairInfo      := __sys.GetValue('sunrise');
    // ... convert date time
    __dateTime      := UnixToDateTime( Strtoint(__pairInfo.Value), false );
    __sunRise       := FormatDateTime('dd/mm/yyy - hh:nn:ss', __dateTime);
    Memo.Lines.Add( '- Sun rise : ' + __sunRise);

    // ... SUN SET
    __pairInfo      := __sys.GetValue('sunset');
    // ... convert date time
    __dateTime      := UnixToDateTime( Strtoint(__pairInfo.Value), false );
    __sunSet        := FormatDateTime('dd/mm/yyy - hh:nn:ss', __dateTime);
    Memo.Lines.Add( '- Sun set  : ' + __sunSet);

    // ... TEMP
    __main          := TJSONObject(__jsonObject.GetValue('main'));
    __pairInfo      := __main.GetValue('temp');
    Memo.Lines.Add( '- Temp     : ' + __pairInfo.Value);

    // ... COORD
    __coord         := TJSONObject(__jsonObject.GetValue('coord'));
    Memo.Lines.Add( '- Coord');
    __pairInfo      := __coord.GetValue('lon');
    Memo.Lines.Add( '  > Lon    : ' + __pairInfo.Value);
    __pairInfo      := __coord.GetValue('lat');
    Memo.Lines.Add( '  > Lat    : ' + __pairInfo.Value);

    // ... etc..

    Memo.Lines.Add( '=================================================');
end;
// .............................................................................

// .............................................................................
// .............................................................................
// .............................................................................

// ... >>> THE WALL STREET JOURNAL REST REQUEST

// *****************************************************************************
//   PRECEDURE : WallStreetJournal_Prepare_Request()
//               PREPARE THE REQUEST
// *****************************************************************************
procedure TFMain.WallStreetJournal_Prepare_Request();
var
    __apiKey : String;
begin
    // ... THE WALL STREET JOURNAL PROVIDES MANY REST API SERVICES:
    //     (Some free for NON-commercial Projects - for Developers)
    // ... https://newsapi.org (WALL STREET JOURNAL)

    // ... !!!GET YOUR API KEY!!!
    __apiKey := '<your Api Key>';

    // ... Example 1. - THE TOP "US" HEADLINES THAT TALK ABOUT BUSINESS
    //     https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=<your api key>'

    // ... Example 2. - ARTICLES OF A SOURCE "bbc-news"
    //     https://newsapi.org/v2/top-headlines?sources=bbc-new&apiKey=<your api key>'

    // ... Example 3. - ARTICLES THAT TALK ABOUT TRUMP
    //     https://newsapi.org/v2/everything?q=trump&apiKey=<your api key>'

    // ... CLEAR PARAMTERS LIST
    RESTRequest.Params.Clear;

    case idExample of
    1 : begin
            // ... Example 1. - THE TOP "US" HEADLINES THAT TALK ABOUT BUSINESS
            RESTClient.BaseURL          := 'https://newsapi.org/v2/top-headlines?';
            RESTRequest.Params.AddItem;
            RESTRequest.Params[0].name  := 'country';
            RESTRequest.Params[0].value := 'us';
            RESTRequest.Params.AddItem;
            RESTRequest.Params[1].name  := 'category';
            RESTRequest.Params[1].value := 'business';
            RESTRequest.Params.AddItem;
            RESTRequest.Params[2].name  := 'apiKey';
            RESTRequest.Params[2].value := __apiKey;
            // .........................................................................
        end;
    2 : begin
            // ... Example 2. - ARTICLES OF A SOURCE "bbc-news"
            RESTClient.BaseURL          := 'https://newsapi.org/v2/top-headlines';
            RESTRequest.Params.AddItem;
            RESTRequest.Params[0].name  := 'sources';
            RESTRequest.Params[0].value := 'bbc-news';
            RESTRequest.Params.AddItem;
            RESTRequest.Params[1].name  := 'apiKey';
            RESTRequest.Params[1].value := __apiKey;
        end;
    3 : begin
            // ... Example 3. - ARTICLES ABOUT ...
            RESTClient.BaseURL          := 'https://newsapi.org/v2/everything?';
            RESTRequest.Params.AddItem;
            RESTRequest.Params[0].name  := 'q';
            RESTRequest.Params[0].value := 'trump';
            RESTRequest.Params.AddItem;
            RESTRequest.Params[1].name  := 'apiKey';
            RESTRequest.Params[1].value := __apiKey;
        end;
    end;
end;
// .............................................................................

// *****************************************************************************
//   PRECEDURE : WallStreetJournal_Display_Response()
//               PARSE AND DISPLAY RESPONSE
// *****************************************************************************
procedure TFMain.WallStreetJournal_Display_Response();
var
    __jsonValue     : TJSONValue;
    __jsonObject    : TJSONObject;

    __pairInfo      : TJSONValue;
    __articles      : TJSONArray;

    __article       : TJSONObject;
    __source        : TJSONObject;

    __nArticles     : Integer;
    __i             : Integer;
begin

    // ... >> GET RESPONSE TYPE
    Memo.Lines.Add('** RESPONSE TYPE : ' + RESTResponse.ContentType);
    Memo.Lines.Add( '=================================================');

    // ... >> DISPLAY THE WHOLE CONTENT
    // Memo.Lines.Add( RESTResponse.Content );
    // Memo.Lines.Add( '=================================================');
    // Memo.Lines.Add( '');

    // ... >> PARSE & DISPLAY ALL PROPERTIES

    // ... GET RESPONSE VALUE
    __jsonValue     := RESTResponse.JSONValue;

    parseJSONObject( __jsonValue, nil, nil, nil );
    Memo.Lines.Add( '=================================================');
    Memo.Lines.Add( '');


    // ... >> OR ITERATE ON OBJECT AND GET PROPERTIES
    __jsonObject    := TJSONObject( __jsonValue );

    __pairInfo  := __jsonObject.GetValue('status');
    Memo.Lines.Add('- STATUS        : ' + __pairInfo.Value);

    // ...

    __pairInfo  := __jsonObject.GetValue('totalResults');
    Memo.Lines.Add('- TOTAL RESULTS : ' + __pairInfo.Value);

    __nArticles := StrToInt(__pairInfo.Value);
    Memo.Lines.Add( '=================================================');

    // ... GET ALL 'ARTICLES' ( JSONArray )
    __articles := TJSONArray(__jsonObject.GetValue('articles'));

    if ( __nArticles > 20 ) then __nArticles := 20;

    // ... READ INFO FROM ALL HEADLINES
    __i := 0;
    while ( __i < __nArticles ) do begin // ... GET i-th ARTICLE __article := TJSONObject( __articles.Items[ __i ] ); if ( __article = nil ) then break; Memo.Lines.Add( '>> ' + 'ARTICLE[' + Inttostr(__i+1) + ']: ');
        Memo.Lines.Add( '.................................................');

        // ... CONTENT OF ARTICLE
        // Memo.Lines.Add( __article.ToString );

        // ... SOURCE
        __source   := TJSONObject(__article.GetValue('source'));

        __pairInfo := __source.GetValue('id');
        Memo.Lines.Add( '- ' + 'ID           : ' + __pairInfo.Value);
        __pairInfo := __source.GetValue('name');
        Memo.Lines.Add( '- ' + 'NAME         : ' + __pairInfo.Value);
        __pairInfo := __article.GetValue('author');
        Memo.Lines.Add( '- ' + 'AUTHOR       : ' + __pairInfo.Value);
        __pairInfo := __article.GetValue('title');
        Memo.Lines.Add( '- ' + 'TITLE        : ' + __pairInfo.Value);
        __pairInfo := __article.GetValue('description');
        Memo.Lines.Add( '- ' + 'DESCRIPTION  : ' + __pairInfo.Value);
        __pairInfo := __article.GetValue('url');
        Memo.Lines.Add( '- ' + 'URL          : ' + __pairInfo.Value);
        __pairInfo := __article.GetValue('publishedAt');
        Memo.Lines.Add( '- ' + 'PUBLISHED AT : ' + __pairInfo.Value);
        // ... etc..

        Memo.Lines.Add( '=================================================');
       __i := __i + 1;
    end;

end;
// .............................................................................

// .............................................................................
// .............................................................................
// .............................................................................

// ... >>> WIKIPEDIA REST REQUEST

// *****************************************************************************
//   PRECEDURE : Wikipedia_Prepare_Request()
//               PREPARE THE REQUEST
// *****************************************************************************
procedure TFMain.Wikipedia_Prepare_Request();
begin

    // ... WIKIPEDIA PROVIDES MANY REST API SERVICES:
    // ... https://en.wikipedia.org/api

    // ... !!!NO API KEY!!!

    // ... Example 1. - SEARCH A TITLE
    // ... https://en.wikipedia.org/api/rest_v1/page/summary/Music

    // ... CLEAR PARAMTERS LIST
    RESTRequest.Params.Clear;

    case idExample of
    1 : begin
            // ... Example 1. - PAGE SUMMARY <TITLE>
            RESTClient.BaseURL := 'https://en.wikipedia.org/api/rest_v1/page/summary/music';
        end;
    end;
end;
// .............................................................................

// *****************************************************************************
//   PRECEDURE : Wikipedia_Display_Response()
//               PARSE AND DISPLAY RESPONSE
// *****************************************************************************
procedure TFMain.Wikipedia_Display_Response();
var
    __jsonValue     : TJSONValue;
begin
    // ... >> GET RESPONSE TYPE
    Memo.Lines.Add('** RESPONSE TYPE : ' + RESTResponse.ContentType);
    Memo.Lines.Add( '=================================================');

    // ... >> DISPLAY THE WHOLE CONTENT
    // Memo.Lines.Add( RESTResponse.Content );
    // Memo.Lines.Add( '=================================================');
    // Memo.Lines.Add( '');

    // ... >> PARSE & DISPLAY ALL PROPERTIES

    // ... GET RESPONSE VALUE
    __jsonValue     := RESTResponse.JSONValue;

    parseJSONObject( __jsonValue, nil, nil, nil );
    Memo.Lines.Add( '=================================================');
    Memo.Lines.Add( '');

    // ... >> OR ACCESS THE PROPERTIES
    // ... good fun 
end;
// .............................................................................

// .............................................................................
// .............................................................................
// .............................................................................

// *****************************************************************************
//   EVENT : BTN_EXECUTEMouseEnter()
//
// *****************************************************************************
procedure TFMain.BTN_EXECUTEMouseEnter(Sender: TObject);
begin
    BTN_LABEL.Opacity := 1.0;
end;
// .............................................................................

// *****************************************************************************
//   EVENT : BTN_EXECUTEMouseLeave()
//
// *****************************************************************************
procedure TFMain.BTN_EXECUTEMouseLeave(Sender: TObject);
begin
    BTN_LABEL.Opacity := 0.7;
end;
// .............................................................................

// *****************************************************************************
//   PROCEDURE : ShowListOfExamples()
//               SHOW LIST OF EXAMPLES
// *****************************************************************************
procedure TFMain.ShowListOfExamples();
begin
    Tab_List_Examples.TabIndex      := ( idProvider - 1 );
    Layout_List_Examples.Visible    := True;
    LABEL_MSG.Text                  := '';
end;
// .............................................................................

// *****************************************************************************
//   PROCEDURE : HideListOfExamples()
//               HIDE LIST OF EXAMPLES
// *****************************************************************************
procedure TFMain.HideListOfExamples();
begin
    Layout_List_Examples.Visible    := False;
    Tab_List_Examples.TabIndex      := -1;
    LABEL_MSG.Text                  := '';
end;
// .............................................................................

// *****************************************************************************
//   PROCEDURE : ShowHeaderResponse()
//               DISPLAY HEADER RESPONSE
// *****************************************************************************
procedure TFMain.ShowHeaderResponse();
var
    __label       : TLabel;
    __labelName   : String;
begin

    // ... HEADER RESPONSE
    LABEL_HEADER_RESPONSE.Text := LABEL_HEADER_EXAMPLES.Text;

    __labelName := 'LABEL_EXAMPLE'      + '_' +
                   Inttostr(idProvider) + '_' +
                   Inttostr(idExample);

    // ... TEXT REQUEST
    __label :=  TLabel(FindComponent( __labelName ));

    LABEL_TEXT_REQUEST.Text := '';
    if ( __label <> nil ) then begin
       LABEL_TEXT_REQUEST.Text := __label.Text;
    end;
    // ... SHOW
    Layout_Header_Response.Visible  := True;

    // ... CLEAR MEMO RESPONSE
    LABEL_RESPONSE.Visible := False;
    Memo.Lines.Clear;
end;
// .............................................................................

// *****************************************************************************
//   PROCEDURE : HideHeaderResponse()
//               HIDE HEADER RESPONSE
// *****************************************************************************
procedure TFMain.HideHeaderResponse();
begin
    Layout_Header_Response.Visible  := False;
    Memo.Lines.Clear;
end;
// .............................................................................

// *****************************************************************************
//   PROCEDURE : ParseJSONObject() 
//               RECURSIVE PROCEDURE TO PARSE AND DECODE A JSON OBJECT 
// *****************************************************************************
procedure TFMain.parseJSONObject( p_jsonValue     : TJSONValue;
                                  p_jsonString    : TJSONString;
                                  p_jsonPairEnum  : TJSONPairEnumerator;
                                  p_jsonArrayEnum : TJSONArrayEnumerator );
var
    __jsonPairEnum  : TJSONPairEnumerator;
    __jsonArrayEnum : TJSONArrayEnumerator;
    __jsonPair      : TJSONPair;
    __jsonString    : TJSONString;
    __jsonValue     : TJSONValue;
begin

    // ... IS A JSONObject?
    if ( p_jsonValue is TJSONObject ) then begin
        if ( p_jsonString <> nil ) then begin
            Memo.Lines.Add( '> ' + p_jsonString.Value + ' :');
        end;
        __jsonPairEnum := ( p_jsonValue as TJSONObject ).GetEnumerator;
        if ( __jsonPairEnum.MoveNext ) then begin
            __jsonPair      := __jsonPairEnum.Current;
            __jsonString    := __jsonPair.JSONString;
            __jsonValue     := __jsonPair.JSONValue;
             ParseJSONObject( __jsonValue, __jsonString, __jsonPairEnum, p_jsonArrayEnum );
        end;
    end
    // ... IS A JSON ARRAY?
    else if ( p_jsonValue is TJSONArray ) then begin
        if ( p_jsonString <> nil ) then begin
            Memo.Lines.Add( '[] ' + p_jsonString.Value + ' : ');
        end;
        __jsonArrayEnum := (p_jsonValue as TJSONArray).GetEnumerator;
        if ( __jsonArrayEnum.MoveNext ) then begin
            __jsonValue := __jsonArrayEnum.Current;
            ParseJSONObject( __jsonValue, nil, p_jsonPairEnum, __jsonArrayEnum );
        end;
    end
    // ... IS A JSON STRING?
    else if ( p_jsonValue is TJSONString ) then begin
        if ( p_jsonString <> nil ) then begin
           Memo.Lines.Add( '- ' + p_jsonString.Value + ' : ' + p_jsonValue.Value );
        end
        else begin
           Memo.Lines.Add( '= ' + p_jsonValue.Value );
        end;
    end
    // ... IS A JSONNull?
    else if ( p_jsonValue is TJSONNull ) then begin
        if ( p_jsonString <> nil ) then begin
           Memo.Lines.Add( '- ' + p_jsonString.Value + ' : ' + p_jsonValue.Value );
        end
        else begin
           Memo.Lines.Add( '= ' + p_jsonValue.Value );
        end;
    end;
    // ... to complete
    // ... IS A JSONNumber?
    // ... IS A JSONBool?


    // ... MOVE NEXT PROPERTY OF OBJECT
    if ( p_jsonPairEnum <> nil ) then begin
        if ( p_jsonPairEnum.MoveNext ) then begin
            Memo.Lines.Add('.................................................');
            __jsonPair   := p_jsonPairEnum.Current;
            __jsonString := __jsonPair.JSONString;
            __jsonValue  := __jsonPair.JSONValue;
            // ... CALL RECURSIVE
            ParseJSONObject( __jsonValue, __jsonString, p_jsonPairEnum, p_jsonArrayEnum );
        end;
    end;
    // ... MOVE NEXT ITEM OF ARRAY
    if ( p_jsonArrayEnum <> nil ) then begin
        if ( p_jsonArrayEnum.MoveNext ) then begin
            Memo.Lines.Add('=================================================');
            __jsonValue := p_jsonArrayEnum.Current;
           // ... CALL RECURSIVE
           ParseJSONObject( __jsonValue, __jsonString, p_jsonPairEnum, p_jsonArrayEnum );
        end;
    end;
end;
// .............................................................................

// *****************************************************************************
//   EVENT : FormGesture()
//           ON FORM GESTURE
// *****************************************************************************
procedure TFMain.FormGesture(Sender: TObject;
          const EventInfo: TGestureEventInfo; var Handled: Boolean);
var
  DX, DY : Single;
begin
  if EventInfo.GestureID = igiPan then begin
    if (TInteractiveGestureFlag.gfBegin in EventInfo.Flags) and
       ( (Sender = ToolbarPopup) or (EventInfo.Location.Y > (ClientHeight - 100) ) ) then begin
      FGestureOrigin      := EventInfo.Location;
      FGestureInProgress  := True;
    end;

    if FGestureInProgress and (TInteractiveGestureFlag.gfEnd in EventInfo.Flags) then begin
      FGestureInProgress := False;
      DX := EventInfo.Location.X - FGestureOrigin.X;
      DY := EventInfo.Location.Y - FGestureOrigin.Y;
      if (Abs(DY) > Abs(DX)) then begin
        ShowToolbar(DY < 0);
      end;
    end;
  end
end;
// .............................................................................

// *****************************************************************************
//   EVENT : FormKeyDown()
//           ON FORM KEY DOWN
// *****************************************************************************
procedure TFMain.FormKeyDown(Sender: TObject; var Key: Word;
                             var KeyChar: Char; Shift: TShiftState);
begin
    // ... KEY ESCAPE
    if Key = vkEscape then begin
        // ... SHOW TOOLBAR ( ESCAPE BUTTON, ...  )
        ShowToolbar(not ToolbarPopup.IsOpen);
    end;
end;
// .............................................................................

// *****************************************************************************
//   EVENT : FormMouseUp()
//           ON FORM MOUSE UP
// *****************************************************************************
procedure TFMain.FormMouseUp(Sender: TObject; Button: TMouseButton;
                                    Shift: TShiftState; X, Y: Single);
begin
    // ... CLICK MOUSE RIGHT
    if Button = TMouseButton.mbRight then begin
        // ... SHOW TOOLBAR
        ShowToolbar(True)
    end
    else begin
        // ... HIDE TOOLBAR
        ShowToolbar(False);
    end;
end;
// .............................................................................

// *****************************************************************************
//   PROCEDURE : ShowToolbar()
//               SHOW TOOLBAR ... CLOSE BUTTON
// *****************************************************************************
procedure TFMain.ShowToolbar(AShow: Boolean);
begin
    ToolbarPopup.Width                    := ClientWidth;
    ToolbarPopup.PlacementRectangle.Rect  := TRectF.Create(0, ClientHeight-ToolbarPopup.Height, ClientWidth-1, ClientHeight-1);
    ToolbarPopupAnimation.StartValue      := ToolbarPopup.Height;
    ToolbarPopupAnimation.StopValue       := 0;
    ToolbarPopup.IsOpen                   := AShow;
end;
// .............................................................................

// *****************************************************************************
//   PROCEDURE : MainLayoutMouseUp()
//               MOUSE UP
// *****************************************************************************
procedure TFMain.MainLayoutMouseUp(Sender: TObject; Button: TMouseButton;
                                   Shift: TShiftState; X, Y: Single);
begin
    // ... CLICK MOUSE RIGHT
    if Button = TMouseButton.mbRight then begin
        // ... SHOW TOOLBAR
        ShowToolbar(True)
    end
    else begin
        // ... HIDE TOOLBAR
        ShowToolbar(False);
    end;
end;
// .............................................................................

// *****************************************************************************
//   EVENT : ToolbarCloseButtonClick()
//           CLICK ON CLOSE BUTTON
// *****************************************************************************
procedure TFMain.ToolbarCloseButtonClick(Sender: TObject);
begin
    // ... CLOSE FORM!!!
    Close;
end;
// .............................................................................

// ... THE END
end.

 

 

 

 

… relax

Advertisements
Categories: EMBARCADERO - DELPHI

[EMBARCADERO – DELPHI] – Client and Server using TIdTCPServer and TIdTCPClient components

An easy example of a Client and Server using indy components : TIdTCPServer, TIdTCPClientTIdThreadComponent.

Here you can download .dpr files: microserver.zip  –  microclient.zip   

 

// *****************************************************************************
//   File    : UServer.pas
//   Project : MicroServer.dpr
//             Easy example of TCP Server with indy component : TidTCPSever
//
//   see indy doc: http://www.indyproject.org/sockets/docs/index.en.aspx
//
// *****************************************************************************
unit UServer;

interface

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdComponent, Vcl.StdCtrls,
    IdBaseComponent, IdCustomTCPServer, IdTCPServer, Vcl.ExtCtrls;

type
    TFServer = class(TForm)
    
        Title         : TLabel;

        btn_start     : TButton;
        btn_stop      : TButton;
        btn_clear     : TButton;

        clients_connected : TLabel;

        IdTCPServer   : TIdTCPServer;
        Label1        : TLabel;
        Panel1        : TPanel;
        messagesLog   : TMemo;

        procedure FormShow(Sender: TObject);
        
        procedure btn_startClick(Sender: TObject);
        procedure btn_stopClick(Sender: TObject);
        procedure btn_clearClick(Sender: TObject);

        procedure IdTCPServerConnect(AContext: TIdContext);
        procedure IdTCPServerDisconnect(AContext: TIdContext);
        procedure IdTCPServerExecute(AContext: TIdContext);
        procedure IdTCPServerStatus(ASender: TObject; const AStatus: TIdStatus;
                                    const AStatusText: string);

        function  getNow():String;
        procedure broadcastMessage(p_message : string);

        private
            { Private declarations }
            
        public
            { Public declarations }
            
    end;
    // ...

    // ... listening port
    const GUEST_CLIENT_PORT    = 20010;

    var
        FServer     : TFServer;


implementation

{$R *.dfm}

// *****************************************************************************
//   EVENT : onShow()
//           ON FORM SHOW
// *****************************************************************************
procedure TFServer.FormShow(Sender: TObject);
begin
    // ... INITIALIZE:

    // ... clear message log
    messagesLog.Lines.Clear;

    // ... zero to clients connected
    clients_connected.Caption := inttostr(0);

    // ... set buttons
    btn_start.visible := true;
    btn_stop.visible  := false;
end;
// .............................................................................


// *****************************************************************************
//   EVENT : btn_startClick()
//           CLICK ON START BUTTON
// *****************************************************************************
procedure TFServer.btn_startClick(Sender: TObject);
begin
    // ... START SERVER:

    // ... clear the Bindings property ( ... Socket Handles )
    IdTCPServer.Bindings.Clear;
    // ... Bindings is a property of class: TIdSocketHandles;

    // ... add listening ports:

    // ... add a port for connections from guest clients.
    IdTCPServer.Bindings.Add.Port := GUEST_CLIENT_PORT;
    // ... etc..


    // ... ok, Active the Server!
    IdTCPServer.Active  := true;

    // ... hide start button
    btn_start.visible   := false;

    // ... show stop button
    btn_stop.visible    := true;

    // ... message log
    MessagesLog.Lines.add('[SERVER] - ' + getNow() + 'STARTED!');

end;
// .............................................................................


// *****************************************************************************
//   EVENT : btn_stopClick()
//           CLICK ON STOP BUTTON
// *****************************************************************************
procedure TFServer.btn_stopClick(Sender: TObject);
begin

    // ... before stopping the server ... send 'good bye' to all clients connected
    broadcastMessage( 'Goodbye my Clients :)');

    // ... stop server!
    IdTCPServer.Active := false;

    // ... hide stop button
    btn_stop.visible   := false;

    // ... show start button
    btn_start.visible  := true;

    // ... message log
    MessagesLog.Lines.add('[SERVER] - ' + getNow() + 'STOPPED!');

end;
// .............................................................................


// *****************************************************************************
//   EVENT : btn_clearClick()
//           CLICK ON CLEAR BUTTON
// *****************************************************************************
procedure TFServer.btn_clearClick(Sender: TObject);
begin
    //... clear messages log
    MessagesLog.Lines.Clear;
end;
// .............................................................................


// *****************************************************************************
//   EVENT : onConnect()
//           OCCURS ANY TIME A CLIENT IS CONNECTED
// *****************************************************************************
procedure TFServer.IdTCPServerConnect(AContext: TIdContext);
var
    Ip          : string;
    Port        : Integer;
    PeerIP      : string;
    PeerPort    : Integer;

    msgToClient : string;
    typeClient  : string;

begin

    // ... OnConnect is a TIdServerThreadEvent property that represents the event
    //     handler signalled when a new client connection is connected to the server.

    // ... Use OnConnect to perform actions for the client after it is connected
    //     and prior to execution in the OnExecute event handler.

    // ... see indy doc:
    //     http://www.indyproject.org/sockets/docs/index.en.aspx


    // ... getting IP address and Port of Client that connected
    Ip        := AContext.Binding.IP;
    Port      := AContext.Binding.Port;
    PeerIP    := AContext.Binding.PeerIP;
    PeerPort  := AContext.Binding.PeerPort;

    // ... message log ...........................................................

    MessagesLog.Lines.add('[SERVER] - ' + getNow() + 'Client Connected!)');


    MessagesLog.Lines.add('           ' + 'Port='     + IntToStr(Port) + ' '
                                      + '(PeerIP='  + PeerIP + '-'
                                      + 'PeerPort=' + IntToStr(PeerPort) + ')');
    // ...

    // ... update number of clients connected
    try
    clients_connected.Caption := IntToStr(IdTCPServer.Contexts.LockList.Count);
    finally
    IdTCPServer.Contexts.UnlockList;
    end;
    // ...

    // ... CLIENT CONNECTED:
    case Port of
    GUEST_CLIENT_PORT   : begin
                            // ... GUEST CLIENTS
                            typeClient := 'GUEST';
                          end;

                          // ...
    end;


    // ... send the Welcome message to Client connected
    msgToClient := 'Welcome ' + typeClient + ' ' + 'Client :)';
    AContext.Connection.IOHandler.WriteLn( msgToClient );

end;
// .............................................................................


// *****************************************************************************
//   EVENT : onDisconnect()
//           OCCURS ANY TIME A CLIENT IS DISCONNECTED
// *****************************************************************************
procedure TFServer.IdTCPServerDisconnect(AContext: TIdContext);
var
    Ip          : string;
    Port        : Integer;
    PeerIP      : string;
    PeerPort    : Integer;

    // msgToClient : string;
    // typeClient  : string;

begin


    // ... getting IP address and Port of Client that connected
    Ip        := AContext.Binding.IP;
    Port      := AContext.Binding.Port;
    PeerIP    := AContext.Binding.PeerIP;
    PeerPort  := AContext.Binding.PeerPort;

    // ... message log ...........................................................
    MessagesLog.Lines.add('[SERVER] - ' + getNow() + 'Client Disconnected!)!');
    MessagesLog.Lines.add('           ' + 'Port='     + IntToStr(Port) + ' '
                                      + '(PeerIP='  + PeerIP + '-'
                                      + 'PeerPort=' + IntToStr(PeerPort) + ')');
    // ...

    // ... update number of clients connected
    try
        clients_connected.Caption := IntToStr(IdTCPServer.Contexts.LockList.Count-1);
    finally
        IdTCPServer.Contexts.UnlockList;
    end;

end;
// .............................................................................


// *****************************************************************************
//   EVENT : onExecute()
//           ON EXECUTE THREAD CLIENT
// *****************************************************************************
procedure TFServer.IdTCPServerExecute(AContext: TIdContext);
var
    Port          : Integer;
    PeerPort      : Integer;
    PeerIP        : string;

    msgFromClient : string;

    msgToClient   : string;

begin

    // ... OnExecute is a TIdServerThreadEvents event handler used to execute
    //     the task for a client connection to the server.

    // ... received a message from a client

    // ... getting IP address, Port and PeerPort from Client that connected
    Port      := AContext.Binding.Port;
    PeerIP    := AContext.Binding.PeerIP;
    PeerPort  := AContext.Binding.PeerPort;


    // ... get message from client
    msgFromClient := AContext.Connection.IOHandler.ReadLn;

    // ... message log ...........................................................
    messagesLog.Lines.add('[CLIENT] - ' + getNow() + msgFromClient);
    MessagesLog.Lines.add('           ' + 'Port='     + IntToStr(Port) + ' '
                                      + '(PeerIP='  + PeerIP + '-'
                                      + 'PeerPort=' + IntToStr(PeerPort) + ')');

    // ...

    // ... process message (request) from Client

    // ...

    // ... send response to Client
    msgToClient := '... response from server :)';

    AContext.Connection.IOHandler.WriteLn( msgToClient );

end;
// .............................................................................


// *****************************************************************************
//   EVENT : onStatus()
//           ON STATUS CONNECTION
// *****************************************************************************
procedure TFServer.IdTCPServerStatus(ASender: TObject; const AStatus: TIdStatus;
                                     const AStatusText: string);
begin

    // ... OnStatus is a TIdStatusEvent property that represents the event handler
    //     triggered when the current connection state is changed...

    // ... message log
    MessagesLog.Lines.add('[SERVER] - ' + getNow() + AStatusText);
end;
// .............................................................................


// *****************************************************************************
//   FUNCTION : getNow()
//              GET NOW DATE TIME
// *****************************************************************************
function TFServer.getNow() : String;
begin
    Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ': ';
end;
// .............................................................................


// *****************************************************************************
//   PROCEDURE : broadcastMessage()
//               BROADCAST A MESSAGE TO ALL CLIENTS CONNECTED
// *****************************************************************************
procedure TFServer.broadcastMessage( p_message : string );
var
    tmpList      : TList;
    contexClient : TidContext;
    i            : integer;
begin

    // ... send a message to all clients connected

    // ... get context Locklist
    try
        tmpList := IdTCPServer.Contexts.LockList;
    finally
        // ... unlock list of clients!
        IdTCPServer.Contexts.UnlockList;
    end;

    i := 0;
    while ( i < tmpList.Count ) do begin

        // ... get context ( thread of i-client )
        contexClient := tmpList[i];

        // ... send message to client
        contexClient.Connection.IOHandler.WriteLn(p_message);

        // ... next client thread
        i := i + 1;
    end;

end;
// .............................................................................

end.

 

 

 

// *****************************************************************************
//   File    : UClient.pas
//   Project : MicroServer.dpr
//             Easy example of TCP Client with indy component : TidTCPSever
//
//   see indy doc: http://www.indyproject.org/sockets/docs/index.en.aspx
//
// *****************************************************************************
unit UClient;

interface

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent,
    IdComponent, IdTCPConnection, IdTCPClient, IdThreadComponent;

type
    TFClient = class(TForm)

    Label1        : TLabel;
    Label2        : TLabel;

    messageToSend : TMemo;
    messagesLog   : TMemo;

    btn_connect   : TButton;
    btn_disconnect: TButton;
    btn_send      : TButton;

    // ... TIdTCPClient
    IdTCPClient       : TIdTCPClient;

    // ... TIdThreadComponent
    IdThreadComponent : TIdThreadComponent;


    procedure FormShow(Sender: TObject);

    procedure btn_connectClick(Sender: TObject);
    procedure btn_disconnectClick(Sender: TObject);
    procedure btn_sendClick(Sender: TObject);

    procedure IdTCPClientConnected(Sender: TObject);
    procedure IdTCPClientDisconnected(Sender: TObject);

    procedure IdThreadComponentRun(Sender: TIdThreadComponent);

    function  getNow() : String;

    private
        { Private declarations }
    public
        { Public declarations }
    end;

    // ... listening port: GUEST CLIENT
    const GUEST_PORT = 20010;

    var
      FClient     : TFClient;

implementation

{$R *.dfm}


// *****************************************************************************
//   EVENT : onShow()
//           ON SHOW FORM
// *****************************************************************************
procedure TFClient.FormShow(Sender: TObject);
begin

    // ... INITAILIZE

    // ... message to send
    messageToSend.Clear;
    messageToSend.Enabled     := false;

    // ... log
    messagesLog.Clear;

    // ... buttons
    btn_connect.Enabled       := true;
    btn_disconnect.Enabled    := false;
    btn_send.Enabled          := false;

end;
// .............................................................................


// *****************************************************************************
//   EVENT : btn_connectClick()
//           CLICK ON CONNECT BUTTON
// *****************************************************************************
procedure TFClient.btn_connectClick(Sender: TObject);
begin

    // ... try to connect to Server
    try
        IdTCPClient.Connect;

        // ... buttons
        btn_connect.Enabled       := false;
        btn_disconnect.Enabled    := true;
        btn_send.Enabled          := true;

    except
        on E: Exception do begin
            MessagesLog.Lines.add('[CLIENT] - CONNECTION ERROR!' + E.Message );
        end;
    end;

end;
// .............................................................................


// *****************************************************************************
//   EVENT : btn_disconnectClick()
//           CLICK ON DISCONNECT BUTTON
// *****************************************************************************
procedure TFClient.btn_disconnectClick(Sender: TObject);
begin
    // ... is connected ?
    if IdTCPClient.Connected then begin

        // ... disconnect from Server
        IdTCPClient.Disconnect;

        // ... set buttons
        btn_connect.Enabled       := true;
        btn_disconnect.Enabled    := false;
        btn_send.Enabled          := false;

        // ... message to send
        messageToSend.Enabled     := false;
    end;
end;
// .............................................................................


// *****************************************************************************
//   EVENT : onConnected()
//           OCCURS WHEN A CLIENT IS CONNETED
// *****************************************************************************
procedure TFClient.IdTCPClientConnected(Sender: TObject);
begin

    // ... messages log
    MessagesLog.Lines.add('[CLIENT] - ' + getNow() + 'CONNECTED!');

    // ... after connection is ok, run the Thread ... waiting messages 
    //     from server
    IdThreadComponent.Active := true;

    // ... set buttons
    btn_connect.Enabled       := false;
    btn_disconnect.Enabled    := true;
    btn_send.Enabled          := true;

    // ... enable message to send
    messageToSend.Enabled     := true;

end;
// .............................................................................


// *****************************************************************************
//   EVENT : onDisconnected()
//           OCCURS WHEN CLIENT IS DISCONNECTED
// *****************************************************************************
procedure TFClient.IdTCPClientDisconnected(Sender: TObject);
begin
    // ... message log
    MessagesLog.Lines.add('[CLIENT] - ' + getNow() + ' : DISCONNECTED!');
end;
// .............................................................................


// *****************************************************************************
//   EVENT : btn_sendClick()
//           CLICK ON SEND BUTTON
// *****************************************************************************
procedure TFClient.btn_sendClick(Sender: TObject);
begin
    // ... send message to Server
    IdTCPClient.IOHandler.WriteLn(messageToSend.Text);
end;
// .............................................................................


// *****************************************************************************
//   EVENT : onRun()
//           OCCURS WHEN THE SERVER SEND A MESSAGE TO CLIENT
// *****************************************************************************
procedure TFClient.IdThreadComponentRun(Sender: TIdThreadComponent);
var
    msgFromServer : string;
begin
    // ... read message from server
    msgFromServer := IdTCPClient.IOHandler.ReadLn();

    // ... messages log
    messagesLog.Lines.add('[SERVER] - ' + getNow() + msgFromServer);
end;
// .............................................................................


// *****************************************************************************
//   FUNCTION : getNow()
//              GET MOW DATE TIME
// *****************************************************************************
function TFClient.getNow() : String;
begin
    Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ': ';
end;
// .............................................................................

end.


… here you can download .dpr files: microserver.zip   –  microclient.zip   

 

 

… relax

 

Categories: EMBARCADERO - DELPHI

[EMBARCADERO – DELPHI] – Split a string with more than one delimiter

28 January 2015 Comments off

Sometimes we need to split a string in tokens delimited by more one delimiter …

… for example, we have a string and we want to split it in tokens delimited by the characters: space, comma, greater than sign, etc.. :


String := 'EXEC SQL
                DECLARE STAFF_LIST CURSOR FOR
                     SELECT EMPID,
                            LNAME,
                            FNAME,
                            SALARY
                       FROM QMT_STAFF
                      WHERE SALARY > 10000
                   ORDER BY EMPID
           END-EXEC.'

… here’s a simple function :

// .............................................................................
//    FUNCTION : SplitStringInTokens
//               SPILT STRING IN TOKENS
//       PARMS : Source          - String to Split
//               DelimiterList   - TStringList of Delimiters
//               TokenList       - TStringList of Tokens
//      RETURN : Count of Tokens
.............................................................................
function TForm1.SplitStringInTokens(const Source: String; const DelimitersList : TStringList; var TokensList : TStringList) : Integer;
var
    SourceString    : String;
    Token           : String;
    Char            : String;
    IndexChar       : Integer;
    IndexDelimiters : Integer;
    FoundDelimiter  : Boolean;
begin

    // ... TRIM STRING
    SourceString := Trim(Source);

    IndexChar := 1;
    Token     := '';
    while ( IndexChar <= Length(SourceString) ) do begin
        // ... GET CURRENT CHAR
        Char := Copy(SourceString, IndexChar, 1);

        // ... CHECK IF THE CHAR IS A DELIMITER (SEARCH IN THE LIST)
        IndexDelimiters := 0;
        FoundDelimiter  := FALSE;
        while (FoundDelimiter = FALSE) and (IndexDelimiters < DelimitersList.Count) do begin
            if (Char = DelimitersList[IndexDelimiters]) then begin
                // ... YES, IT'S A DELIMITER! EXIT
                FoundDelimiter := TRUE;
            end
            else begin
                // ... NO, CONTINUE
                IndexDelimiters := IndexDelimiters + 1;
            end;
        end;

        // ... FOUND A DELIMITER?
        if (FoundDelimiter = TRUE) then begin
            // ... YES, SAVE TOKEN (IF NOT NULL)
            if (Token <> '') then begin
                TokensList.Add(Token);
            end;
            // ... SAVE DELIMITER (IF NOT SPACE)
            if (Char <> ' ') then begin
                TokensList.Add(Char);
            end;
            // ... COPY THE REST OF STRING TO SPLIT
            SourceString := Trim(Copy(SourceString, IndexChar+1, Length(SourceString)));
            Token        := '';
            IndexChar    := 1;
        end
        else begin
            // ... CHAR IS NOT A DELIMITER, ADD CHAR TO TOKEN
            Token := Token + Char;
            // ... INC. INDEX
            IndexChar := IndexChar + 1;
        end;
    end;
    // ... END OF STRING

    // ... ADD LAST TOKEN
    if (Token <> '') then begin
        TokensList.Add(Token);
    end;

    // ... RETURN THE COUNT OF TOKENS
    Result := TokensList.Count;
end;
//..............................................................................

… here’s how to call the function with the arguments :


...
var
    StringToSplit  : String;
    DelimitersList : TStringList;
    TokensList     : TStringList;
    i              : Integer;
begin 

    // ... CREATE THE TOKENS LIST
    TokensList      := TStringList.Create;

    // ... CREATE THE DELIMITERS LIST
    DelimitersList  := TStringList.Create;

    // ... ASSIGN THE STRING TO SPLIT
    StringToSplit   := 'EXEC SQL
                           DECLARE STAFF_LIST CURSOR FOR
                             SELECT EMPID,
                                    LNAME,
                                    FNAME,
                                    SALARY
                               FROM QMT_STAFF
                           ORDER BY EMPID
                        END-EXEC.'

    // ... ADD DELIMITERS TO THE LIST
    DelimitersList.Add(' ');
    DelimitersList.Add(',');
    DelimitersList.Add('>');
    // ... etc..

    // ... CLEAR TOKENS LIST
    TokensList.Clear;

    // ... SPLIT STRING IN TOKENS
    SplitStringInTokens(TextSource, DelimitersList, TokensList);

    // ... SHOW TOKENS LIST
    i := 0;
    While (i < TokensList.Count) do begin
        ShowMessage(TokensList[i]);
        i := i + 1;
    end;    

    // ... end  

 

 

 

… relax

Categories: EMBARCADERO - DELPHI

[AS3] – Come creare un oggetto leggendo il nome della Classe e delle sue proprietà da un file XML.

10 March 2011 Comments off

A volte può esserci l’esigenza di dover generalizzare il processo di creazione degli oggetti, e di conseguenza acquisire i riferimenti delle Classi in maniera dinamica.

La funzione getDefinitionByName() di AS3, presente nel package flash.utils, consente di ottenere un riferimento della Classe, passando, come argomento, il nome della classe ( in formato stringa ).

Una volta acquisito il riferimento alla Classe, l’oggetto potrà essere istanziato utilizzando l’operatore new e la variabile contenente il “reference” della Classe.

// ...
var className         :String;
var classReference    :Class;
var objectReference   :Object;

// ... class name ( string );
// ... nome della Classe ( string )   
className       = flash.display.MovieClip

// ... ottieni il riferimento all'oggetto Class
// ... get Class object reference 
classReference  = Class(getDefinitionByName(className));

// ... crea l'oggetto
// ... create the object
objectReference = classReference(new classReference());

// ... 

 

E’ necessario, comunque, che la Classe venga importata al momento della compilazione del .fla o .as.

Nota : la maggior parte delle classi predefinite di AS3 ( presenti nei pacchetti flash.*) sono importate automaticamente dal compilatore. 

 

Per importare in maniera “esplicita” una Classe ( propria o tra quelle presenti nei pacchetti di AS3 non caricate automaticamente ) basterà dichiarare una variabile di quel tipo ( di quella Classe ). 

// ...
// ... declare a dummy variable of type : myClass
// ... dichiarazione di una variabile del tipo : myClass 
var dummyRef : myClass;
// ...

 

Ciò servirà ad “avvertire” il compilatore che “intendiamo utilizzare quella Classe” e lo “costringerà” ad importare la definizione della Classe.

Nota : la sola indicazione della dichiarativa import myclass non è sufficiente a far importare la Classe, in quanto, il compilatore, per motivi di ottimizzazione, non importerà la Classe fin tanto che non incontrerà almeno una dichiarazione di variabile di quella Classe.

 

Qui di seguito un esempio che mostra come creare un oggetto il cui nome della Classe ed alcune delle sue proprietà sono lette da un file XML.

// ...................................................................
//   NAME : buildForm.fla
//          QUESTO ESEMPIO MOSTRA COME CREARE UN OGGETTO LEGGENDO IL 
//          NOME DELLA CLASSE E LE SUE PROPRIETA' DA UN FILE XML. 
//
//          THIS EXAMPLE SHOWS HOW TO CREATE AN OBJECT READING CLASS 
//          NAME AND ITS PROPERTIES AS STRINGS FROM AN XML FILE 
//
// 
// sample XML file : 
// 
// <?xml version="1.0" encoding="UTF-8"?>
// <form>
//   <editField className="flash.text.TextField" >
//     <type>input</type>
//     <maxChars>200</maxChars>
//     <text>... that was only yesterday</text>
//     <textColor>0x00CC00</textColor> 
//     <background>true</background> 
//     <backgroundColor>0x333333</backgroundColor> 
//     <border>true</border> 
//     <borderColor>0x888888</borderColor> 
//     <width>300</width> 
//     <height>25</height> 
//     <x>100</x> 
//     <y>50</y> 
//   </editField>
// </form>
//
// ...................................................................
var XMLRequest        :URLRequest; 
var XMLLoader         :URLLoader; 
var XMLObejct         :XML; 
var myObject          :XMLList; 

var classReference    :Class;
var className         :String;
var objectReference   :Object;

var propertyClass     :Class;
var propertyObject    :XML;
var propertyName      :String;
var propertyValue     :String;
var booleanValue      :Boolean;


XMLRequest     = new URLRequest(); 
XMLLoader      = new URLLoader(); 
XMLLoader.addEventListener(Event.COMPLETE, XMLLoaded); 

XMLRequest.url = "form.xml";
XMLLoader.load(XMLRequest);

// ... 

// .................................................. 
//  FUNCTION : XMLLoaded - Event.COMPLETE
// .................................................. 
function XMLLoaded(evento:Event):void  
{
    // ... ACQUISIZIONE DELL'XML  
    // ... GET XML  
    XMLObejct = new XML(XMLLoader.data); 

    // ... ACQUISIZONE DEL TAG <editField>	
    // ... GET <editField> TAG 
    myObject = XMLObejct.editField; 
    // ... oppure  
    // ... or   
    // ... ( myObject = XMLObejct.children()[0]; ) 
	
	
    // ... ACQUISIZIONE DELL'ATTRIBUTO className 
    // ... GET className ATTRIBUTE 
    //     ( es. : <editField className="flash.text.TextField" > ) 
    className       = myObject[0].@className; 
	
    // ... SYSOUT 
    trace("className : " + className);
	
    // ... ACQUISIZIONE DELLA CLASSE 
    // ... GET CLASS REFERENCE 
    classReference  = Class(getDefinitionByName(className));
	
    // ... CREAZIONE DELL'OGGETTO 
    // ... CREATE THE OBJECT 
    objectReference = classReference(new classReference());
	
    // ... LETTURA DELLE PROPRIETA' DELL'OGGETTO  
    // ... READ OBJECT'S PROPERTIES 
    for( var i:int = 0; i < myObject.children().length(); i++ )
    {
        // ... ACQUISIZIONE DEL i-esimo TAG ( PROPRIETA' )        		
        // ... GET i-th TAG ( PROPERTY )  
        //     ( es. : <maxChars>200</maxChars> ) 
        propertyObject = myObject.children()[i];
		
        // ... NOME DEL TAG ( NOME DELLA PROPRIETA' )  
        // ... TAG NAME ( PROPERTY NAME )  
        //     ( es. "maxChars" ) 
        propertyName   = propertyObject.name();
	    
        // ... VALORE DELLA PROPRIETA' 
        // ... PROPERTY VALUE 
        //     ( es. : 200 ) 
        propertyValue  = propertyObject;
		
        // ... SYSOUT 
        trace(propertyName + "=" + propertyValue);
		
        // ... ACQUISISCI LA CLASSE DELLA PROPRIETA' 
        // ... GET PROPERTY CLASS 
        propertyClass = Object(objectReference[propertyName]).constructor;
		
        // ... SYSOUT 
        trace("propertyClass : " + propertyClass);
		
        // ... SE LA PROPRIETA' E' DI CLASSE BOOLEAN, DOBBIAMO CONVERTIRE 
        //     LE STRINGHE "true" O "false" IN BOOLEAN. 
        // ... IF PROPERTY CLASS IS BOOLEAN, WE NEED TO CONVERT 
        //     THE STRINGS VALUES "true" OR "false" IN BOOLEAN. 
        if (propertyClass == Boolean) 
        {
            // ... RICHIAMO DELLA FUNZIONE strToBoolean() PRIMA DEL CASTING 
            // ... CALL strToBoolean() FUNCTION BEFORE CASTING			
            booleanValue                  = strToBoolean(propertyValue);

            // ... ASSEGNAZIONE DEL VALORE DELLA PROPRIETA' (boolean)
            // ... ASSIGN PROPERTY VALUE (boolean) 
            objectReference[propertyName] = propertyClass(booleanValue);
        }
        else 
        {
            // ... ASSGNAZIONE DEL VALORE DELLA PROPRIETA' 
            // ... ASSIGN PROPERTY VALUE  
            objectReference[propertyName] = propertyClass(propertyValue);
        }
    }	
	
    // ... AGGIUNGI L'OGGETTO 
    // ... ADD CHILD 
    addChild(classReference(objectReference));

    // ... 
} 
// ...................................................................


// ...................................................................
//   FUNCTION : strToBoolean() 
//              CONVERTE LE STRINGHE "true" O "false" IN BOOLEAN 
//              CONVERTS THE STRINGS "true" OR "false" INTO BOOLEAN 
// ...................................................................
function strToBoolean(p_string:String):Boolean
{
    var retValue:Boolean;
	
    retValue = false;
    if (p_string == "true" ) 
    { 
        retValue = true;
    }
    return retValue;
}
// ...................................................................

// ... END 
Categories: ACTIONSCRIPT 3.0

[DB2] – I Tipi di Dati del DB2

28 August 2009 Comments off

La Tabella seguente mostra i tipi di Dati del DB2 e le corrispondenti clausole PICTURE e USAGE in COBOL

Tipo DB2 PICTURE USAGE Descrizione
CHAR(n) PIC X(n) DISPLAY Caratteri a lunghezza Fissa (EBCDIC). Fino ad un massimo di 254 bytes di caratteri alfanumerici. In COBOL è definito come PIC X(n), dove n è il numero di caratteri della colonna.
es. : 01  COD-CLI  PIC X(10).
VARCHAR(n) PIC X(n) DISPLAY Caratteri a lunghezza variabile (EBCDIC). Un numero variabile di caratteri alfanumerici. Il numero di bytes di caratteri è memorizzato in una Halfword (mezzavoce).
es. : 01 NOTE.
49 NOTE-LUNG  PIC S9(4) COMP.
49 NOTE-TXT     PIC X(2000).
SMALLINT PIC S9(4) COMP o
COMP-4
Un valore intero (Halfword). Valori compresi tra -32.768 e +32.767. Definito in COBOL come PIC S9(4) COMP.
es. : 01 CTR-RIGA    PIC S9(4) COMP. 
INTEGER PIC S9(9) COMP o
COMP-4
Un valore intero (Fullword). Valori compresi tra -2.147.485.648 e +2.147.485.648. Definito in COBOL come PIC S9(9) COMP.
es. : 01 CTR-OPE     PIC S9(4) COMP.
DECIMAL(n,d) PIC S9(i)V9(d) COMP-3 Packed Decimal. Contiene valori decimali (il segno della virgola è implicito). Il valore n indica il numero complessivo di cifre e d quante di quelle sono a destra del segno decimale.
es. : 01 TOT-FATT    PIC S9(7).V99 COMP-3.
L’esempio è la corrispondente dichiarazione di una variabile HOST per una COLONNA definita come : DECIMAL(9,2).
DATE PIC X(10) DISPLAY Una stringa di 10 caratteri. La struttura interna è nella forma : yyyy-mm-dd.
es. : 01 DATA-FATT     PIC X(10).
TIME PIC X(8) DISPLAY Una stringa di 8 caratteri (hh.mm.ss).
es. : 01 ORA-INIZIO     PIC X(8).
TIMESTAMP PIC X(26) DISPLAY Una stringa di 26 caratteri. La struttura interna è : yyyy-mm-dd-hh.mm.ss.mmmmmm
es. : 01 DATA-ORA-INIZIO     PIC X(26)
GRAPHIC PIC G(n) DISPLAY-1 Una Stringa grafica a lunghezza fissa che contiene n word (double-byte) di caratteri. Il valore n deve essere  maggiore di 0 e minore di 128.
VARGRAPHIC PIC G(n) DISPLAY-1 Una Stringa grafica a lunghezza variabile. Il valore massimo della lunghezza, n, deve essere maggiore di 0 e minore di un numero che dipende dalla taglia della pagina del table space. La lunghezza massima è di 16.352.
FLOAT No COMP-1 o
COMP-2
Floating Point (singola o doppia precisione). Singola precisione per n minore di 22, doppia precisione se n è compreso tra 22 e 53. La corrispondente dichiarazione COBOL non include la clausola PIC. Va indicato COMP-1 per la singola precisione, COMP-2 per la doppia precisione.
es. : 01 VALORE-SP  COMP-1.
01 VALORE-DP  COMP-2.
Categories: DB2 - SQL

[AS3] – Invio e ricezione Array tra FLASH e PHP

17 May 2009 Comments off
Questo esempio mostra come inviare un’Array da FLASH ad uno script PHP e ricevere dallo script PHP un altro Array.
 
Un modo elementare :
Un Array di nomi viene ‘impacchettato’ in un unica stringa con il metodo : join() della Classe String ( tutti gli elementi dell’Array sono concatenati utilizzando un delimitatore ), quindi inviato allo script PHP.

Lo script PHP riceve la stringa, la ‘esplode’ con la funzione : explode() e riottiene l’Array originale.
L’Array (originale) ottenuto è copiato in un nuovo Array e rispedito all’SWF chiamante.
 
 

 

 

// ...............................................................
//   NAME : flashToPhp.fla
//          QUESTO ESEMPIO MOSTRA COME INVIARE E RICEVERE UN ARRAY
//          TRA FLASH ED UNO SCRIPT PHP
// ...............................................................

import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;

var richiestaPHP  :URLRequest;
var caricatorePHP :URLLoader;
var varsToPHP     :URLVariables;
var arrayNomi     :Array;

// ... CREAZIONE OGGETTO RICHIESTA DI ESECUZIONE DELLO SCRIPT PHP
richiestaPHP        = new URLRequest("PhpToFLASH_02.php");

// ... CREAZIONE OGGETTO CARICATORE SCRIPT PHP
caricatorePHP       = new URLLoader(richiestaPHP);
// ... CREAZIONE OGGETTO URLVariables PER L'INVIO DELLE VARIABILI
//     ALLO SCRIPT PHP
varsToPHP           = new URLVariables();

// ... IMPOSTAZIONE METODO PASSAGGIO VARIABILI ALLO SCRIPT (GET | POST)
richiestaPHP.method = URLRequestMethod.POST;
// ... FORMATO IN CUI SI DESIDERA RICEVERE I DATI DALLO SCRIPT PHP :

// ... in formato VARIABLES
//     i dati ricevuti sono costituiti da un oggetto :URLVariables
//     che contiene le variabili con codifica URL
caricatorePHP.dataFormat = URLLoaderDataFormat.VARIABLES;

// ... ALTRI FORMATI IN CUI POSSONO ESSERE RICEVUTI I DATI DALLO SCRIPT :
//
//     - in fomato TEXT ( URLLoaderDataFormat.TEXT )
//       i dati sono costituiti da una stringa contenente il testo
//
//     - in formato BINARY ( URLLoaderDataFormat.BINARY )
//       i dati sono costituiti da un oggetto ByteArray

// ... CREAZIONE DELL'ARRAY DA INVIARE ALLO SCRIPT PHP
arrayNomi = new Array();

// ... INIZIALIZZAZIONE
arrayNomi.push('giulio');
arrayNomi.push('alina');
arrayNomi.push('carlo');
arrayNomi.push('anna');

// ...

// ... COMPONENETI PRESENTI SULLO STAGE (per il test) :

// ... UN BUTTON PER L'AVVIO DEL CARICAMENTO DELLO SCRIPT PHP
btn_invia.addEventListener(MouseEvent.CLICK, onClickInvia);

// ... UN CAMPO TextField (multiline) CHE CONTERRA' L'ARRAY
//     RICEVUTO DALLO SCRIPT PHP
kmessaggi.text = "";
// ...

// ...............................................................
//  FUNCTION : onClickInvia() - MouseEvent.CLICK
//             AVVIO CARICAMENTO ED ESECUZIONE DELLO SCRIPT PHP
// ...............................................................
function onClickInvia(evento:MouseEvent):void
{
// ... AVVIO DELLO SCRIPT PHP

// ... 'impacchetta' GLI ELEMENTI DELL'ARRAY IN UN'UNICA
//     STRING, UTILIZZANDO COME DELIMITATORE IL CARATTERE "|"
var stringNomi = arrayNomi.join("|");

// ... DOPO LA join(), L'ARRAY DIVENBTA UN'INICA STRING
// stringNomi = 'giulio|alina|carlo|anna';

// ... ASSEGNAZIONE DELLA VARIABILI DA INVIARE COME PROPRIETA'
//     DELL'OGGETTO URLVariables
varsToPHP.nomi = stringNomi;

// ... AGGIUNTA DELL'ASCOLTATORE EVENTO : OPEN
//     per sapere quando il caricamento dello script PHP è iniziato
caricatorePHP.addEventListener(Event.OPEN, onOpenScript);

// ... AGGIUNTA DELL'ASCOLTATORE EVENTO : PROGRESS
//     per sapere che lo script è in fase di caricamento ed esecuzione
caricatorePHP.addEventListener(ProgressEvent.PROGRESS, onProgressScript);

// ... AGGIUNTA DELL'ASCOLTATORE EVENTO : COMPLETE
//     per sapere quando lo script PHP termina ed i dati saranno dati
//     ricevuti.
caricatorePHP.addEventListener(Event.COMPLETE, onCompleteScript);

// ... AGGIUNTA DELL'ASCOLTATORE EVENTO : IO_ERROR
//     per gestire eventuali errori durante il caricamento o esecuzione
//     dello script PHP.
caricatorePHP.addEventListener(IOErrorEvent.IO_ERROR, onErrorScript);

// ... ASSEGNAZIONE DELL'OGGETTO URLVariables ALLA PROPRIETA' .data
//     DELL'OGGETTO URLRequest ( invio dei dati )
richiestaPHP.data = varsToPHP;

// ... AVVIA LA RICHIESTA DI CARICAMENTO ED ESECUZIONE DELLO SCRIPT PHP
caricatorePHP.load(richiestaPHP);

// ...
}
// ...............................................................

// ...............................................................
//  FUNCTION : onOpenScript() - Event.OPEN
//             NOTIFICATO ALL'AVVIO DEL CARICAMENTO DELLO SCRIPT
// ...............................................................
function onOpenScript(evento:Event):void
{
// ... IL CARICAMENTO ED ESECUZIONE DELLO SCRIPT PHP
//     ( SUL SERVER ) E' AVVIATO
kmessaggi.text = '... avvio caricamento Script PHP';
}
// ...............................................................

// ...............................................................
//  FUNCTION : onProgressScript() - ProgressEvent.PROGRESS
//             EVENTO NOTIFICATO DURANTE IL CARICAMENTO
//             ED ESECUZIONE DELLO SCRIPT PHP
// ...............................................................
function onProgressScript(evento:ProgressEvent):void
{
// ... LO SCRIPT PHP E' IN ESECUZIONE ( SUL SERVER )
kmessaggi.text = '... attendere prego!';
}
// ...............................................................

// ...............................................................
//  FUNCTION : onComplteScript()
//             EVENTO NOTIFICATO AL COMPLETAMENTO DELL'ESECUZIONE
//             DELLO SCRIPT PHP
// ...............................................................
function onComplteScript(evento:Event):void
{
// ... LO SCRIPT PHP E' STATO CARICATO ED ESEQUITO, ED I DATI
//     SONO STATI RICEVUTI ...

// ... CREAZIONE DI UN OGGETTO URLVariables, PASSANDO AL
//     COSTRUTTORE I DATI RICEVUTI DALLO SCRIPT PHP
var varsFromPHP = new URLVariables(evento.target.data);

// ... DICHIARAZIONE DI UNA VARIABILE STRING IN CUI COPIARE
//     LA VARIABILE RICEVUTA DALLO SCRIPT PHP
var stringMessaggi:String;

// ... CREAZIONE DI UN NUOVO ARRAY
var arrayMessaggi :Array = new Array();

// ... ACQUISIZIONE DELLA VARIABILE RICEVUTA
stringMessaggi = varsFromPHP.messaggi;
// ... NOTA : il nome della proprietà messaggi è quello
//            indicato nell'echo dello script PHP

// ... 'spacchetta' LA STRINGA IN ELEMENTI DELL'ARRAY
arrayMessaggi  = stringMessaggi.split("|");

// ... VISUALIZZA GLI ELEMENTI DELL'ARRAY
kmessaggi.text = "";
for (var i=0; i < arrayMessaggi.length; i++)
{
kmessaggi.appendText(arrayMessaggi[i] + "\n");
};

// ... RIMUOVI GLI ASCOLTATORI
caricatorePHP.removeEventListener(Event.OPEN, onOpenScript);
caricatorePHP.removeEventListener(ProgressEvent.PROGRESS, onProgressScript);
caricatorePHP.removeEventListener(Event.COMPLETE, onCompleteScript);
caricatorePHP.removeEventListener(IOErrorEvent.IO_ERROR, onErrorScript);
}
// ...............................................................

// ...............................................................
//  FUNCTION : onErrorScript() - IOErrorEvent.IO_ERROR
//             EVENTO NOTIFICATO IN CASO DI ERRORE DURANTE IL
//             CARICAMENTO DELLO SCRIPT
// ...............................................................
function onErrorScript(evento:IOErrorEvent):void
{
// ... ERRORE DURANTE LA FASE DI CARICAMENTO DELLO SCRIPT
kmessaggi.text = '... errore di caricamento dello script PHP';
}
// ...............................................................

// ... END

 
… lo script PHP

 


<?
// .....................................................
//  NAME : PhpToFLASH_02.php
//         Ricezione ed invio di Array tra FLASH e PHP
// .....................................................

// ... acquisizione delle variabili inviate dall'SWF

// ... la stringa 'impacchettata' contenete l'Array
//     inviato dall'SWF
$stringNomi = $_POST['nomi'];

// ... crea l'Array da ricostruire
$arrayNomi = array();

// ... 'spacchetta' la stringa in elementi dell'Array
$arrayNomi = explode("|", $stringNomi);

// ... l'Array e' stato ricostruito!

// ... crea un nuovo Array, quello che verra' rispedito
//     all'SWF
$arrayMessaggi = array();

// ... copia i nomi presenti nell'Array ricevuto negli
//     elementi del nuovo array, aggiugendo '... hello '
for ($i = 0; $i < sizeof($arrayNomi); $i++)
{
$arrayMessaggi[$i] = '... hello ' . $arrayNomi[$i];
}

// ... 'impacchetta' l'Array in una stringa da rispedire
//     all'SWF
$stringMessaggi = implode("|", $arrayMessaggi);

// ... invia la stringa all'SWF chiamante
echo "messaggi=" . urlencode($stringMessaggi);

// ... la funzione urlencode() effettua l'encoding di
//     una stringa, covertendo la stringa in un formato
//     URL valido (conversione di caratteri speciali).

// ... i caratteri '/', '%', '&', etc..., sono
//     convertiti con il segno % seguito dalla codifica
//     HEX del carattere.

// ... la funzione inversa e' : urldecode()

// ... end of JOB
?>

Categories: ACTIONSCRIPT 3.0

[AS3] – Invio e ricezione Dati tra FLASH e PHP

16 May 2009 Comments off

L’esempio seguente mostra come inviare una variabile ( il contenuto di un TextField ) ad uno script PHP (Server-Side), e ricevere dallo script PHP un messaggio di risposta.

// .........................................................
//     NAME : FlashPhp.fla
//            ESEMPIO MINIMALISTA DI INVIO E RICEZIONE DATI
//            TRA FLASH E PHP
// .........................................................

// ... IMPORT DELLE CLASSI PER IL CARICAMENTO E LO SCAMBIO
//     DEI DATI CON LO SCRIPT PHP
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;

// ... DICHIARAZIONE DELLE VARIABILI RELATIVE AI REFERENCE
//     DEGLI OGGETTI
var phpRequest : URLRequest;
var phpLoader  : URLLoader;
var dataToPHP  : URLVariables;

// ... CREAZIONE DELL'OGGETTO URLRequest PER LA RICHIESTA
//     DI ESECUZIONE DELLO SCRIPT PHP (LATO SERVER)
phpRequest = new URLRequest();

// ... CREAZIONE DELL'OGGETTO URLLoader PER IL CARICAMENTO
//     DELLO SCRIPT PHP (LATO SERVER)
phpLoader  = new URLLoader();

// ... CREAZIONE DELL'OGGETTO URLVariables PER L'INVIO
//     DELLE VARIABILI DA FLASH A PHP
dataToPHP  = new URLVariables();

// ... IMPOSTAZIONE DEL METODO DI PASSAGGIO DELLE VARIABILI
//     (GET | POST)
phpRequest.method = URLRequestMethod.POST;

// ... ASSEGNAZIONE DEL TIPO DI FORMATO IN CUI SI DESIDERA
//     RICEVERE I DATI DALLO SCRIPT PHP :

// ... in formato VARIABLES :
//     (i dati ricevuti sono costituiti da un oggetto URLVariables
//      che contiene le variabili con codifica URL)
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;

// ... altri modi in cui possono essere ricevuti i dati
//     dallo script PHP :

//     - in formato testo (URLLoaderDataFormat.TEXT)
//       i dati sono costituiti da una stringa contenente il testo

//     - in formato binaro (URLLoaderDataFormat.BINARY)
//       i dati sono costituiti da un oggetto di Classe ByteArray

// ***

// ... I COMPONENTI PRESENTI SULLO STAGE (per il test) :

// ... UN TextField PER L'IMMISSIONE DI UN CAMPO DA INVIARE
//     ALLO SCRIPT PHP
nickName.text = "";

// ... UN TextField CHE CONTERRA' IL MESSAGGIO RICEVUTO
//     DALLO SCRIPT PHP
msg.text      = "";

// ... UN Button PER L'AVVIO DEL CARICAMENTO ED ESECUZIONE
//     DELLO SCRIPT PHP (sul server)
btn_Send.addEventListener(MouseEvent.CLICK, onClickSend);

// ...

// .........................................................
//     FUNCTION : onClickSend() - MouseEvent.CLICK
//                AVVIO DEL CARICAMENTO ED ESECUZIONE DELLO
//                SCRIPT PHP SUL SERVER
// .........................................................
function onClickSend(evento:MouseEvent):void
{
    // ... PREPARAZIONE DEI DATI DA INVIARE ALLO SCRIPT PHP

    // ... ASSEGNAZIONE DELLE VARIABILI DA INVIARE
    //     (come proprietà dinamiche dell'oggetto : URLVariables)
    dataToPHP.nickname = nickName.text;
    // ... etc..

    // ... AGGIUNTA DEGLI ASCOLTATORI PER LA GESTIONE DEGLI EVENTI :

    // ... AGGIUNTA DELL'ASCOLTATORE PER LA GESTIONE
    //     DELL'EVENTO : COMPLETE
    //     (la funzione sarà invocata al termine dell'esecuzione
    //      dello script PHP ed eventuali dati, inviati da questi,
    //      saranno pervenuti)
    phpLoader.addEventListener(Event.COMPLETE, onCompleteScript);

    // ... AGGIUNTA DELL'ASCOLTATORE PER LA GESTIONE
    //     DELL'EVENTO : IO_ERROR
    //     (la funzione sarà invocata in caso di errore durante
    //      il caricamento dello script PHP)
    phpLoader.addEventListener(IOErrorEvent.IO_ERROR, onErrorScript);

    // ... AGGIUNTA DELL'ASCOLTATORE PER LA GESTIONE
    //     DELL'EVENTO : OPEN
    //     (la funzione sarà invocata quando il caricamento
    //       dello script PHP e' iniziato)
    phpLoader.addEventListener(Event.OPEN, onOpenScript);

    // ... AGGIUNTA DELL'ASCOLTATORE PER LA GESTIONE
    //     DELL'EVENTO : PROGRESS
    //     (la funzione sarà invocata durante il caricamento
    //      dello script PHP)
    phpLoader.addEventListener(ProgressEvent.PROGRESS, onProgressScript);

    // ... ASSEGNAZIONE DELL'OGGETTO: URLVariables ALLA
    //     PROPRIETA' .data DELL'OGGETTO : URLRequest
    phpRequest.data = dataToPHP;

    // ... ASSEGNAZIONE DELLO SCRIPT PHP ALLA PROPRIETA' .url
    //     DELL'OGGETTO : URLRequest
    phpRequest.url  = "flashPhp.php";

    // ... AVVIO DELLA RICHIESTA DI CARICAMNETO ED ESECUZIONE
    //     DELLO SCRIPT PHP SUL SERVER
    phpLoader.load(phpRequest);

    // ...
}
// .........................................................

// .........................................................
//     FUNCTION : onCompleteScript() - Event.COMPLETE
//                EVENTO NOTOFICATO AL COMPLETAMENTO ED
//                ESECUZIONE DELLO SCRIPT PHP SUL SERVER
// .........................................................
function onCompleteScript(evento:Event):void
{
    var dataFromPHP : URLVariables;
    var msgFromPHP  : String;

    // ... LO SCRIPT PHP E' STATO CARICATO ED ESEGUITO, ED
    //     I DATI SONO STATI RICEVUTI!

    // ... CREAZIONE DI UN OGGETTO : URLVariables IN CUI
    //     ACQUISIRE I DATI RICEVUTI DALLO SCRIPT PHP
    //     (al metodo costruttore viene passato come argomento
    //      la proprietà .data contenente i dati ricevuti)
    dataFromPHP = new URLVariables(evento.target.data);

    // ... ACQUISIZIONE DELLE VARIABILI INVIATE DALLO SCRIPT PHP
    //     (il nome della proprieta' .messaggio e' quello
    //      indicato nell'echo dello script PHP)
    msgFromPHP = dataFromPHP.messaggio;
    // ... etc..

    // ... VISUALIZZAZIONE
    msg.text = String(dataFromPHP.messaggio);
    // ... etc..

    // ... RIMOZIONE DEGLI ASCOLTATORI
    phpLoader.removeEventListener(Event.COMPLETE, onCompleteScript);
    phpLoader.removeEventListener(IOErrorEvent.IO_ERROR, onErrorScript);
    phpLoader.removeEventListener(Event.OPEN, onOpenScript);
    phpLoader.removeEventListener(ProgressEvent.PROGRESS, onProgressScript);
}
// .........................................................

// .........................................................
//     FUNCTION : onErrorScript() - IOErrorEvent.IO_ERROR
//                EVENTO NOTIFICATO IN CASO DI ERRORE DI
//                CARICAMENTO DELLO SCRIPT PHP SUL SERVER
// .........................................................
function onErrorScript(evento:IOErrorEvent):void
{
    // ... SI E' VERIFICATO UN ERRORE DURANTE IL CARICAMENTO
    msg.text = '... errore caricamento Script PHP';
}
// .........................................................

// .........................................................
//     FUNCTION : onOpenScript() - Event.OPEN
//                EVENTO NOTIFICATO ALL'AVVIO DEL CARICAMENTO
//                DELLO SCRIPT PHP SUL SERVER
// .........................................................
function onOpenScript(evento:Event):void
{
    // ... AVVIO RICHIESTA CARICAMENTO ED ESECUZIONE
    //     DELLO SCRIPT PHP SUL SERVER
    msg.text = '... avvio caricamento Script PHP.';
}
// .........................................................

// .........................................................
//     FUNCTION : onProgressScript() - ProgressEvent.PROGRESS
//                EVENTO NOTIFICATO DURANTE I CARICAMENTO
//                DELLO SCRIPT PHP SUL SERVER
// .........................................................
function onProgressScript(evento:ProgressEvent):void
{
    // ... LO SCRIPT E' IN ESECUZIONE SUL SERVER
    msg.text = '... attendere, prego.';
}
// .........................................................

// ... END

… lo script PHP

<?
    // .....................................................
    //  NAME : flashPhp.php
    //         ESEMPIO DI SCAMBIO DATI TRA FLASH E PHP
    // .....................................................

    // ... acquisizione delle variabili inviate dall'SWF

    // ... il nick name
    $nickName   = $_POST['nickname'];
    // ... etc..

    // ... prepara risposta
    $msg        = '... hello ' . $nickName;

    // ... invia messaggio di ritorno all'SWF chiamante
    echo "messaggio=" . urlencode($msg);

    // ... la funzione urlencode() effettua l'encoding di una
    //     stringa, covertendo la stringa in un formato URL
    //     valido (conversione di caratteri speciali).

    // ... i caratteri '/', '%', '&', etc..., sono convertiti
    //     con il segno % seguito dalla codifica HEX del
    //     carattere.
    //     ( la funzione inversa e' : urldecode() )

    // ... end of script
?>

Categories: ACTIONSCRIPT 3.0