How To…Edit Templates as Text

Question

“How do I manually edit report templates stored in my database as text files?”

Solution

Stream the templates from thier BLOB field using the GetFieldAsStream routine of the DataPipeline.

Use the built-in Delphi routines ObjectBinaryToText and ObjectTextToBinary to load and save each template to and from text.

Once the template has been edited, use the SetFieldFromStream routine of the Datapipeline to write the template information back to the database.

See the example below on how this can be done

Download: EditTemplatesAsText.zip

Sample Delphi code:

{------------------------------------------------------------------------------}
{ TForm1.LoadTemplate }

procedure TForm1.LoadTemplate(aItemIndex: Integer);
var
  liItemID: Integer;
  lBinaryStream: TMemoryStream;
  lTextStream: TMemoryStream;
begin

  {get the item id for the selected item}
  liItemID := Integer(lbxItems.Items.Objects[aItemIndex]);

  {locate the record to edit}
  if not plItem.Locate('ItemID', liItemID, []) then
    raise Exception.Create('Unable to locate selected report');


  lBinaryStream := TMemoryStream.Create;
  lTextStream := TMemoryStream.Create;

  try

    {read the binary stream from the database}
    plItem.GetFieldAsStream('Template', lBinaryStream);

    lBinaryStream.Position := 0;

    {convert the binary stream to text}
    ObjectBinaryToText(lBinaryStream, lTextStream);

    lTextStream.Position := 0;

    {load the text stream to the memo control}
    memo1.Lines.LoadFromStream(lTextStream);


  finally
    lBinaryStream.Free;
    lTextStream.Free;
  end;


end;

{------------------------------------------------------------------------------}
{ TForm1.SaveTemplate }

procedure TForm1.SaveTemplate;
var
  lBinaryStream: TMemoryStream;
  lTextStream: TMemoryStream;
  lWriter: TWriter;
begin

  lBinaryStream := TMemoryStream.Create;
  lTextStream := TMemoryStream.Create;

  try

    {load the text stream to the memo control}
    memo1.Lines.SaveToStream(lTextStream);

    lTextStream.Position := 0;

    {convert the binary stream to text}
    ObjectTextToBinary(lTextStream, lBinaryStream);

    lBinaryStream.Seek(0,soFromEnd);
    lWriter := TWriter.Create(lBinaryStream, 1024);

    try
      lWriter.Root := Self;
      lWriter.WriteListEnd;
    finally
      lWriter.Free;
    end;

    lBinaryStream.Position := 0;

    plItem.Edit;

    {load the binary stream from the database}
    plItem.SetFieldFromStream('Template', lBinaryStream);

    plItem.Post;

  finally
    lBinaryStream.Free;
    lTextStream.Free;
  end;

end;