2008. május 1., csütörtök

How to create a random "Tip of the Day" from a Paradox table


Problem/Question/Abstract:

How to create a random "Tip of the Day" from a Paradox table

Answer:

Here's a rather simple example of how to reduce your exe size by randomly retrieving a typical "Tip of the Day" (with associated image) from a table instead of getting it from a resource file. It uses a Paradox table with the following structure:


Number (FieldName)
(Type: Alpha)
Text (FieldName)
(Type: Blob)
Image (FieldName)
(Type: Blob)
1 (Variable I)
RTF
JPG Image
2
RTF
JPG Image
3
RTF
JPG Image




The code should be self-explanatory, but you can also download a little sample project at the bottom of this page if you like. Please note, that there are only four records in the table. The same tip might therefore appear several times in a row when you click on the "Next Tip" button.

Here are the basic steps:

Create a new project and drop a TDataSource, a TTable and a TPanel on the main form. Place a TImage and a TDBRichEdit on the panel. Hook Table1 and DBRichEdit1 to Datasource1 and assign the field "Text" of Table1 to the DBRichEdit control. Finally, set table1.active to true.

Put JPEG into the Uses clause and in the private declarations of the main form, add this procedure ...

private
{Private Declarations}

procedure RandomTip;

... and define it as follows:

procedure TForm1.RandomTip;
var
  Stream1: TBlobStream;
  TipImage: TJPEGImage;
  I: Integer;
begin
  {Random(I) would pick a free random number}
  I := Random(4) + 1;
  {Take the random number, locate it in the field "Number" and jump to the record}
  table1.Locate('Number', I, [loPartialKey]);
  begin
    {Create a blobstream and read the stored jpg image from the blob
                 field into the stream}
    Stream1 := TBlobStream.Create(Table1.FieldByName('Image') as TBlobField, bmRead);
    TipImage := TJPEGImage.create;
    try
      {Load the JPEGImage from the blob stream and assign it to the TImage}
      TipImage.LoadFromStream(Stream1);
      Image1.Picture.Assign(TipImage);
    finally
      Stream1.Free;
      TipImage.Free;
    end;
  end;
end;

To initialize the random number generator, we need to call it (for example) in the OnCreate event handler of Form1. Randomize should only be called once in your application - best done probably in the main units Initialization section.

procedure TForm1.FormCreate(Sender: TObject);
begin
  Randomize; {Call the random number generator}
end;

To fill the Tip of the Day from the table the first time, we call the RandomTip procedure in the OnShow event handler of Form1:

procedure TForm1.FormShow(Sender: TObject);
begin
  RandomTip;
end;

That's all there is to do. Dead easy, isn't it? This simple technique could also be used to display random splash screens or random backgrounds for forms in your program. Just use your imagination ...

Download sample project (32K)

Nincsenek megjegyzések:

Megjegyzés küldése