2
votes

I am using Delphi XE6, & datasnap, and I am trying to pass an Object (TDataObj) with some fields to a datasnap server method and the strangest error is occuring. My server method will crash on a TStringStream creation if my data object I pass in NOT nil.

//client side

procedure TForm8.btnGetDataClick(Sender: TObject);
var
  DataObj: TDataObj;
  S: TStream;
begin
  //create an object
  DataObj := TDataObj.Create;
  DataObj.Id:= 1;
  DataObj.Name := 'DataObj1';
  DataObj.ExportType := 'PDF';
  //pass the obj to server method to retrieve data stream back
  try
    S := ClientModule1.ServerMethods1Client.GetData(DataObj);
    S.Seek(0, soFromBeginning);
    ClientDataSet1.LoadFromStream(S);
    ClientDataSet1.Open;
  finally
  end;
end;

//Server Side method

function TServerMethods1.getData(const DataObj: TDataObj): TStream;
var
  r: String;
  SS: TStringStream;
begin
  //create a stream using JSON from getSessionJSON method
  SS := TStringStream.Create(getSessionJSON(DataObj)); //returns json
  try
    try
      r := ServerContainer1.idHttp1.Post
        ('MyUrlHere', SS);
      //do something else here
    except
      on e: exception do
      begin
        ShowMessage(e.Message);
        exit;
      end;
    end;
  finally
    SS.Free;
  end; 
end;

//get Json

function TServerMethods1.getSessionJSON(const DataObj: TDataObj): String;
var
  ParamsJSONObj, SessionJSONObj: TJSONObject;
begin
  ParamsJSONObj := TJSONObject.Create;
  ParamsJSONObj.AddPair(TJSONPair.Create('ID', DataObj.Id));
  ParamsJSONObj.AddPair(TJSONPair.Create('Name', DataObj.Name));
  ParamsJSONObj.AddPair(TJSONPair.Create('ExportType', DataObj.ExportType));
  SessionJSONObj := TJSONObject.Create;
  SessionJSONObj.AddPair(TJSONPair.Create('DataParams', ParamsJSONObj));
  result := SessionJSONObj.toString;
end;

However, on the client side, if I pass in a nil object

 S := ClientModule1.ServerMethods1Client.GetData(nil);

and then fill in the values in the get Json on the server side

 ParamsJSONObj.AddPair(TJSONPair.Create('ID', '1'));
  ParamsJSONObj.AddPair(TJSONPair.Create('Name', 'DataObj1'));
  ParamsJSONObj.AddPair(TJSONPair.Create('ExportType', 'pdf'));

it works, but , if I pass in the actual data object (dataObj) instead of nil

it crashes on the server side here

  SS := TStringStream.Create(getSessionJSON(DataObj)); 

whether I call getSessionJSON or not

If I place in any string

SS := TStringStream.Create('THis is a random test');

if the DataObj is not nil, the values in dataObj are there, but the

SS := TStringStream.Create will throw a runtime error

Hope this is understandable? dataObj, makes the call above crash if dataObj is NOT nil

Any help would be greatly appreciated

1

1 Answers

2
votes

Turned out to be an encoding issue which was solved using

 S := getSessionJSON(DataObj);
  SS := TStringStream.Create(r, TEncoding.ASCII);