2004. június 30., szerda

Distributing the BDE with your application


Problem/Question/Abstract:

What are the essential files to ship with an application that uses the BDE?

Answer:

Delphi allows you to generate a nice tight executable file (.EXE), but if you have created a database application you must include the files that make up the Borland Database Engine as well. The table below shows the files that are mandatory when delivering a database application with Delphi.

File Name
Description
IDAPI01.DLL
IDBAT01.DLL
IDQRY01.DLL
IDASCI01.DLL
IDPDX01.DLL
IDDBAS01.DLL
IDR10009.DLL
ILD01.DLL
IDODBC01.DLL
ODBC.New
ODBCINST.NEW
TUTILITY.DLL
BDECFG.EXE
BDECFG.HLP  
IDAPI.CFG
BDE API DLL
BDE Batch Utilities DLL
BDE Query DLL
BDE ASCII Driver DLL
BDE Paradox Driver DLL
BDE dBASE Driver DLL
BDE Resources DLL
Language Driver DLL
BDE ODBC Socket DLL
Microsoft ODBC Driver Manager DLL V2.0
Microsoft ODBC Driver Installation DLL V2.0
BDE Table Repair Utility DLL  
BDE Configuration Utility DLL
BDE Configuration Utility Help
BDE Configuation File (settings)

        
To assist the user, Delphi ships with an install program for exporting the appropriate files that you want deliver to your clients. Also, installation programs such as InnoSetup and InstallShield can automatically include the relevant files in their setup programs.

InnoSetup is my program installation program of choice, and it is FREE! For more information or to download a copy visit Jordan Russell's site at http:// www.jrsoftware.org

Finally a tip on using the setup CAB file that ships with the BDE to install the relevant files can be found in DKB, article title "Installing BDE from BDEINST.CAB"

2004. június 29., kedd

Combobox instead inplace editor in TStringGrid


Problem/Question/Abstract:

How can I use a combobox as inplace editor in standard TStringGrid?

Answer:

I wrote a small app which demonstrates how you can use the some combobox instead standard inplace editor in TStringGrid component.

Also in this app you can view how change font and/or alignment for some cells.

The form contents as text:

object frmMain: TfrmMain
  Left = 200
    Top = 108
    Width = 510
    Height = 382
    Caption = 'Example: TStringGrid advanced using'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -11
    Font.Name = 'MS Sans Serif'
    Font.Style = []
    OnCreate = FormCreate
    PixelsPerInch = 96
    TextHeight = 13
    object StringGrid1: TStringGrid
    Left = 24
      Top = 152
      Width = 457
      Height = 161
      ColCount = 2
      DefaultColWidth = 200
      DefaultRowHeight = 21
      RowCount = 9
      TabOrder = 0
      OnDrawCell = StringGrid1DrawCell
      OnSelectCell = StringGrid1SelectCell
      ColWidths = (
      118
      296)
  end
  object cbInplaceComboBox: TComboBox
    Left = 32
      Top = 320
      Width = 145
      Height = 21
      Style = csDropDownList
      ItemHeight = 13
      Items.Strings = (
      '1 value'
      '2 value'
      '3 value'
      '4 value'
      '5 value'
      '6 value'
      '7 value'
      '8 value'
      '9 value')
      TabOrder = 1
      OnChange = cbInplaceComboBoxChange
  end
  object btnClose: TButton
    Left = 416
      Top = 320
      Width = 75
      Height = 25
      Cancel = True
      Caption = '&Close'
      default = True
      TabOrder = 2
      OnClick = btnCloseClick
  end
  object MemoDescription: TMemo
    Left = 24
      Top = 8
      Width = 457
      Height = 129
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clNavy
      Font.Height = -11
      Font.Name = 'MS Sans Serif'
      Font.Style = [fsBold]
      Lines.Strings = (
      'In this sample I shows how you can:'
      ' '
      '1. change the inplace editor for second column'
      '    from standard inplace editor to user TComboBox component'
      ' '
      '   view the next procedures:'
      '      - TfrmMain.FormCreate'
      '      - TfrmMain.CMDialogKey'
      '      - TfrmMain.cbInplaceComboBoxChange'
      '      - TfrmMain.StringGrid1SelectCell'
      '  '
      '2. draw the cell values with different fonts'
      ' '
      '   view the next procedure:'
      '      - TfrmMain.StringGrid1DrawCell'
      ' '
      '3. change alignment for cells'
      ' '
      '   view the next procedure:'
      '      - TfrmMain.StringGrid1DrawCell')
      ParentFont = False
      ScrollBars = ssVertical
      TabOrder = 3
  end
end

The pas - file for same form:

unit Main;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, Grids;

type
  TfrmMain = class(TForm)
    StringGrid1: TStringGrid;
    cbInplaceComboBox: TComboBox;
    btnClose: TButton;
    MemoDescription: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure cbInplaceComboBoxChange(Sender: TObject);
    procedure StringGrid1SelectCell(Sender: TObject; Col, Row: Integer;
      var CanSelect: Boolean);
    procedure StringGrid1DrawCell(Sender: TObject; Col, Row: Integer;
      Rect: TRect; State: TGridDrawState);
    procedure btnCloseClick(Sender: TObject);
  private
    { Private declarations }
    procedure CMDialogKey(var msg: TCMDialogKey); message CM_DIALOGKEY;
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.DFM}

procedure TfrmMain.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  StringGrid1.DefaultRowHeight := cbInplaceComboBox.Height;
  cbInplaceComboBox.Visible := False;

  StringGrid1.Cells[0, 0] := 'Row No';
  StringGrid1.Cells[1, 0] := 'Values (from Combobox)';
  for i := 1 to StringGrid1.RowCount - 1 do
    StringGrid1.Cells[0, i] := IntToStr(i);
end;

procedure TfrmMain.CMDialogKey(var msg: TCMDialogKey);
begin
  if (ActiveControl = cbInplaceComboBox) then
  begin
    if (msg.CharCode = VK_TAB) then
    begin
      //set focus back to the grid and pass the tab key to it
      cbInplaceComboBox.SetFocus;
      cbInplaceComboBox.Perform(WM_KEYDOWN, msg.CharCode, msg.KeyData);
      // swallow this message
      msg.result := 1;
      Exit;
    end;
  end;

  inherited;
end;

procedure TfrmMain.cbInplaceComboBoxChange(Sender: TObject);
var
  intRow: Integer;
begin
  inherited;

  {Get the ComboBox selection and place in the grid}
  with cbInplaceComboBox do
  begin
    intRow := StringGrid1.Row;
    if (StringGrid1.Col = 2) then
      StringGrid1.Cells[2, intRow] := Items[ItemIndex]
    else
      StringGrid1.Cells[StringGrid1.Col, intRow] := Items[ItemIndex];
    Visible := False;
  end;
  StringGrid1.SetFocus;
end;

procedure TfrmMain.StringGrid1SelectCell(Sender: TObject; Col, Row: Integer;
  var CanSelect: Boolean);
var
  R: TRect;
begin
  if ((Col = 1) and (Row <> 0)) then
  begin
    {Size and position the combo box to fit the cell}
    R := StringGrid1.CellRect(Col, Row);
    R.Left := R.Left + StringGrid1.Left;
    R.Right := R.Right + StringGrid1.Left;
    R.Top := R.Top + StringGrid1.Top;
    R.Bottom := R.Bottom + StringGrid1.Top;

    {Show the combobox}
    with cbInplaceComboBox do
    begin
      Left := R.Left + 1;
      Top := R.Top + 1;
      Width := (R.Right + 1) - R.Left;
      Height := (R.Bottom + 1) - R.Top;

      ItemIndex := Items.IndexOf(StringGrid1.Cells[Col, Row]);
      Visible := True;
      SetFocus;
    end;
  end;
  CanSelect := True;
end;

procedure TfrmMain.StringGrid1DrawCell(Sender: TObject; Col, Row: Integer;
  Rect: TRect; State: TGridDrawState);
const
  AlignFlags: array[TAlignment] of Integer =
  (DT_LEFT or DT_VCENTER or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX,
    DT_RIGHT or DT_VCENTER or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX,
    DT_CENTER or DT_VCENTER or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX);
var
  s: string;
begin
  inherited;

  with Rect do
  begin
    Left := Left + 2;
    Top := Top + 2;
    Right := Right - 5
  end;

  s := StringGrid1.Cells[Col, Row];

  if (Row = 0) and (Col < StringGrid1.ColCount) then
  begin
    StringGrid1.Canvas.Font.Style := StringGrid1.Canvas.Font.Style + [fsBold];
    StringGrid1.Canvas.Brush.Color := StringGrid1.FixedColor;
    StringGrid1.Canvas.FillRect(Rect);

    DrawText(StringGrid1.Canvas.Handle,
      PChar(s), Length(s),
      Rect, AlignFlags[taCenter]);
  end
  else if (Col = 0) and (Row > 0) and (Row < StringGrid1.RowCount) then
  begin
    StringGrid1.Canvas.FillRect(Rect);
    DrawText(StringGrid1.Canvas.Handle,
      PChar(s), Length(s),
      Rect, AlignFlags[taRightJustify]);
  end;
end;

procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
  Close
end;

end.


Component Download: http://www.geocities.com/mshkolnik/FAQ/strgrid.zip

2004. június 28., hétfő

How to get and set the volume on a wave device


Problem/Question/Abstract:

How to get and set the volume on a wave device

Answer:

Here are a couple of functions for getting/ setting the volume on the default wave device:


uses
  mmsystem;

function GetWaveVolume: DWord;
var
  Woc: TWAVEOUTCAPS;
  Volume: DWord;
begin
  if WaveOutGetDevCaps(WAVE_MAPPER, @Woc, sizeof(Woc)) = MMSYSERR_NOERROR then
    if Woc.dwSupport and WAVECAPS_VOLUME = WAVECAPS_VOLUME then
    begin
      WaveOutGetVolume(WAVE_MAPPER, @Volume);
      Result := Volume;
    end;
end;

procedure SetWaveVolume(const AVolume: DWord);
var
  Woc: TWAVEOUTCAPS;
begin
  if WaveOutGetDevCaps(WAVE_MAPPER, @Woc, sizeof(Woc)) = MMSYSERR_NOERROR then
    if Woc.dwSupport and WAVECAPS_VOLUME = WAVECAPS_VOLUME then
      WaveOutSetVolume(WAVE_MAPPER, AVolume);
end;


Here's how they might be used:


procedure TForm1.Button2Click(Sender: TObject);
var
  LeftVolume: Word;
  RightVolume: Word;
begin
  LeftVolume := StrToInt(Edit1.Text);
  RightVolume := StrToInt(Edit2.Text);
  SetWaveVolume(MakeLong(LeftVolume, RightVolume));
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  Caption := IntToStr(GetWaveVolume);
end;

2004. június 27., vasárnap

Form with custom caption bar


Problem/Question/Abstract:

How to remove system caption bar (title bar) or replace it by my own?

Answer:

Below you can find the source code of a unit that performs the task (note that it is not a form). All you need is to inherit your form from TDPCCForm instead of TForm. Property CaptionControl is accessible at run time and defines the control (TGraphicControl) which acts as a caption bar. Usually you assign CaptionControl once in OnCreate event handler of you form, but nothing prevents you from further changes of CaptionControl at run time. If you leave CaptionControl unassigned, the form will have no caption functionality at all.

unit DPCCForms;

interface

uses
  Windows, Messages, Classes, Controls, Forms;

type
  TDPCCForm = class(TForm)
  private
    { Private declarations }
    FCaptionControl: TGraphicControl;
    procedure WMNCHitTest(var AMessage: TWMNCHitTest); message WM_NCHITTEST;
  protected
    procedure CreateParams(var Params: TCreateParams); override;
  public
    { Public declarations }
    property CaptionControl: TGraphicControl
      read FCaptionControl write FCaptionControl default nil;
  end;

  {===============================================================}
implementation

{---------------------------------------------------------------}

procedure TDPCCForm.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  with Params do
  begin
    Style := (Style or WS_POPUP) and (not WS_DLGFRAME);
  end; {with}
end {--TDPCCForm.CreateParams--};

{---------------------------------------------------------------}

procedure TDPCCForm.WMNCHitTest(var AMessage: TWMNCHitTest);
begin
  inherited;
  if ((AMessage.Result = HTCLIENT) and
    Assigned(CaptionControl) and
    PtInRect(CaptionControl.BoundsRect,
    ScreenToClient(Point(AMessage.XPos,
    AMessage.YPos)))) then
  begin
    AMessage.Result := HTCAPTION;
  end; {if}
end; {--TDPCCForm.WMNCHitTest--}

end.

2004. június 26., szombat

Open registered files


Problem/Question/Abstract:

How to open a registered file from Delphi

Answer:

Example:

OpenRegisteredFile('c:\windows\desktop\MyHTML.html');
OpenRegisteredFile('d:\data\MyDocuments\FAQ.doc');
OpenRegisteredFile('c:\mp3z\MyFavMp3.mp3');

uses
  WinTypes, ShellApi;

procedure OpenRegisteredFile(Path: string);
begin
  ShellExecute(0, nil, PChar(Path), nil, nil, SW_NORMAL);
end;

2004. június 25., péntek

How to build sets of letters for the currently selected language


Problem/Question/Abstract:

Is there any way to enumerate the contents of a set? Just now I have a set of char, each char is a lower case character, and need to add the corresponding upper case characters to the set. Any other way than looping through the set range and do an inclusion check each time?

Answer:

No. If you are after building sets of letters for the currently selected language you could do it using API functions like IsCharAlpha and IsCharUpper:


unit Charsets;

interface

type
  TCharSet = set of AnsiChar;

const
  Signs: TCharset = ['-', '+'];
  Numerals: TCharset = ['0'..'9'];
  HexNumerals: TCharset = ['A'..'F', 'a'..'f', '0'..'9'];
  IntegerChars: TCharset = ['0'..'9', '-', '+'];
var
  Letters, LowerCaseLetters, UpperCaseLetters: TCharSet;
  FloatChars, SciFloatChars: TCharset;
  AlphaNum, NonAlphaNum: TCharset;

  { Need to call this again when locale changes.  }
procedure SetupCharsets;

implementation

uses
  Windows, Sysutils;

procedure SetupCharsets;
var
  ch: AnsiChar;
begin
  LowerCaseLetters := [];
  UpperCaseLetters := [];
  AlphaNum := [];
  NonAlphaNum := [];
  for ch := Low(ch) to High(ch) do
  begin
    if IsCharAlpha(ch) then
      if IsCharUpper(ch) then
        Include(UpperCaseLetters, ch)
      else
        Include(LowerCaseLetters, ch);
    if IsCharAlphanumeric(ch) then
      Include(AlphaNum, ch)
    else
      Include(NonAlphaNum, ch);
  end;
  Letters := LowerCaseLetters + UpperCaseLetters;
  FloatChars := IntegerChars;
  Include(FloatChars, DecimalSeparator);
  SciFloatChars := FloatChars + ['e', 'E'];
end;

initialization
  SetupCharsets;

end.

2004. június 24., csütörtök

Speeding up compilation/ linking process


Problem/Question/Abstract:

When minor change in any file and re-run project in Delphi compile and link time is very long.(2 minutes) How can I speed compile and link process?

Answer:

While developing your project I'd suggest you to compile it with runtime packages, then when the time comes, you recompile everything into your EXE again, this will speed it up.
I've also been working with a rather big project and also experienced that kind of problem since my processor is rather out-dated. I'd also suggest you to divide your code ( if your code is not a mixture of every unit in you project ) into packages, this will help you to have a better organization, and will even speed up more you compile time since you'll be compiling only the unit you are willing to debug.
Compiling every unit in your project every time you make a minor change will make you waste a lot of time.
Runtime Packages are a great tool for developing projects.

2004. június 23., szerda

Creating an ActiveX for ASP


Problem/Question/Abstract:

How to create an ActiveX that can be used in Active Server Pages for dynamic content?

Answer:

This article shows you how to create a server-side ActiveX library you can use within ASP (Active Server
Pages). We'll keep it very simple.

CREATING THE ACTIVEX SERVER

First, start Delphi and/or close all current projects. Select File|New and change to the "ActiveX" tab. Select the "ActiveX library" project type. AxtiveX libraries, as this can be used for ASP. They are DLL that are implemented by the Server.CreateObject (VBScript) directive.
An ActiveX library must export 4 routines, allowing it to be un-/registered, export its objects and tell the calling process whether it may be unloaded. These for four functions are provided through the ComServ unit, by Borland. You do not have worry about them.
Next, we will create an "Active Server Object". You find these within the File|New dialog on the "ActiveX" tab, too. You will see a dialog with quite a few options. First we will have to enter CoClass Name. This is the name we will use when accessing the object from within our ASP page. Let's call it "Sample". Now we have to choose the "instancing model" and the "threading model". Choose "Single Instance" and "Apartment" from the drop-down lists. (I will explain these models in another article, later on. Drop me an e-mail if you want me to tell you when.) For "Active Server Type" choose "Object Context", leave the check mark in the "Generate template..." check box and press OK.
Delphi will create a new unit (unit1), an ASP (sample.asp), and a type library (project1_tlb). Let's save these files now. (Choose save all and use the following names: uSample.pas, Sample.asp, First.dpr). Goto to the menu and select View|Type Library. This window shows all the objects with their methods and properties within the type library we create. The root object is named "First" (if you've used the same file names). This is your type library name, it must be unique on the machine it is running. Underneath "First" you see two more entries (ISample and Sample). One is the public dispatch interface declaration where all methods and properties are names, the other is the object name that is used within the applications accessing you ActiveX library.
Select the ISampe entry. In the tool bar you will see a green icon (New Method) and a blue icon (New Property) to its right. These are the two we are going to check out in this article.
First select new method. A new entry ("Method1) will appear underneath the ISample entry. Change its name to ShowTime. Select the "Parameters" tab on the right and add a new parameter to the list. Set its name to "TheTime", the type to "BSTR *". Double-click the modifier with your mouse and select "out" and "retval". The "in" box will be deselected automatically. It is not working with "retval" together. We have declared the Parameter "TheTime" as WideString (ASO does not support Pascal Type Strings) as a Return Value. Close the Box by pressing OK.
Save your project files (!), goto to your editor window and select the uSample unit. Delphi has added the following method, automatically:

function ShowTime: WideString; safecall;

Since the parameter "TheTime" was declared as Return Value, Delphi created a function with the Result Type
WideString. The safecall directive tells the Delphi Compiler to ensure the proper DLL/COM wrapping for the
function.

Fill out the ShowTime function as follows:

function TSample.ShowTime: WideString;
begin
  Result := FormatDateTime(
    '"This function was called on " dddd, mmmm d, yyyy, " at " hh:mm AM/PM',
    Now
    );
end;

That's all for the Delphi code. Save your project and select Run|Register ActiveX Server from your menu. The ActiveX server has to be installed on the machine where it is used. Without Delphi you can do this by calling

regsvr32 "Drive:\Path\FileName.dll"

from the command line. Add the parameter /u to unregister the ActiveX server.

THE ACTIVE SERVER PAGE

Delphi has prepare the Sample.asp file already. we just have to fill in the missing parts.

In our case we have to change the line

   DelphiASPObj.{Insert Method name here}

into

   Response.Write DelphiASPObj.ShowTime

"Response.Write" tells ASP to write the following text (provided by our function) into the current place of our HTML code.

Copy the sample ASP into your web server directory (/test) and call it like:

http://localhost/test/sample.asp.

You should have installed either the MS Internet Information Server (IIS) or MS Personal Web Server (PWS).
Good luck and stay tuned for more.

2004. június 22., kedd

How to apply the Windows Shutdown screen effect to a bitmap


Problem/Question/Abstract:

I would like to apply this "screening" effect to a bitmap. I have tried PatBlt, DrawState, and BitBlt, but I don't know what combination of params I need.

Answer:

Create an 8 x 8 bitmap, where the pixels alternate black and white (as in a checkerboard).

Load that bitmap into the Brush.Bitmap property of whatever Canvas it is that you're trying to modify.

Set the canvas's CopyMode to $00A000C9. (This ANDs the destination with the pattern).

Use CopyRect to draw the canvas onto itself. Example:

var
  Bmp: TBitmap;
begin
  Bmp := TBitmap.Create;
  Bmp.LoadFromFile('brush.bmp');
  with Image1.Picture.Bitmap do
  begin
    Canvas.Brush.Bitmap := Bmp;
    Canvas.CopyMode := $00A000C9;
    Canvas.CopyRect(Rect(0, 0, Width, Height), Canvas, Rect(0, 0, 0, 0));
  end;
  Bmp.Free;
end;

2004. június 21., hétfő

Pulling Digits Out of String to Sum Them


Problem/Question/Abstract:

How do I pull out every second digit from a string and sum them?

Answer:

This is a rather unusual question, but it's not that hard to accomplish.

What must iterate through each character of the string and "grab" the digits whose position is a multiple of two (2). There are a couple of ways to do this, but I took what I felt was the easier route. Since this is more or less a binary problem, setting a Boolean value with each iteration works nicely. Here's the logic:

For all "odd" positions, set Boolean value to False;
For all "even" positions, set Boolean value to True;
If the Boolean value is true, grab that character and add it to a temporary buffer.
Iterate through the buffer, and convert each character to an Integer while adding the converted value to an integer variable.

Here's the code that accomplishes the above:

function AddEvenOrOddChars(S: string; OddOrEven: Boolean): Integer;
var
  I: Integer;
  evn: Boolean;
  buf: string;
begin
  Result := 0;

  {If OddOrEven was passed as True, then the all odd positions
   will be grabbed and summed. If False, then all even positions
   will be grabbed and summed.}
  evn := EvenOdd;

  {First grab the even position characters}
  for I := 1 to Length(S) do
  begin
    if evn then
      buf := buf + S[I];

    {Set boolean to its opposite regardless of its current value.
     If it's currently true, then we've just grabbed a character.
     Setting it to False will make the program skip the next one.}
    evn := not evn;
  end;

  {Now, iterate through the buffer variable to add up the individual
   values}
  for I := 1 to Length(buf) do
    Result := Result + StrToInt(buf[I]);
end;

2004. június 20., vasárnap

Customizing the display of IBObject queries


Problem/Question/Abstract:

Customizing the display of IBObject queries

Answer:

If you use IBObjects for your InterBase client application, you can use the powerful TIB_Cursor and TIB_Query to modify how your query results will look for example in a grid. Take a look at the sample source code below.

Note:
All those settings can be made via the object inspector, but when the SQL property is updated at runtime with a new query, some of these properties seem to get wiped out. Therefore it's better to set them at run-time in code.

begin
  with TIB_Query1 do
  begin
    FieldsVisible.Add('ID=F');
    FieldsVisible.Add('SLNR=T'); { not really necessary }
    FieldsCharCase.Add('LAND=UPPER');
    FieldsDisplayLabel.Add('COMMENTS=Your Comments');
    FieldsDisplayWidth.Add('COMMENTS=200');
  end;
end;

2004. június 19., szombat

Compact an Access database (2)


Problem/Question/Abstract:

How to compact and repair MS Access 2000 (Jet Engine 4) during run time using Delphi 5?

Answer:

Usually the size of MS Access keep growing fast by time because of it&#8217;s internal caching and temporary buffering, which in over whole effect the performance, space required for storing, and backing-up (if needed).  The solution is to compact it from Access menus (Tools &#8211; Database Utilities &#8211; Compact and Repair Database) or to do that from inside your Delphi application.

function CompactAndRepair(sOldMDB: string; sNewMDB: string): Boolean;
const
  sProvider = 'Provider=Microsoft.Jet.OLEDB.4.0;';
var
  oJetEng: JetEngine;
begin
  sOldMDB := sProvider + 'Data Source=' + sOldMDB;
  sNewMDB := sProvider + 'Data Source=' + sNewMDB;

  try
    oJetEng := CoJetEngine.Create;
    oJetEng.CompactDatabase(sOldMDB, sNewMDB);
    oJetEng := nil;
    Result := True;
  except
    oJetEng := nil;
    Result := False;
  end;
end;

Example :

if CompactAndRepair('e:\Old.mdb', 'e:\New.mdb') then
  ShowMessage('Successfully')
else
  ShowMessage('Error&#8230;');

Important Notes:
Include the JRO_TLB unit in your uses clause.
Nobody should use or open the database during compacting.
If the compiler gives you an error on the JRO_TLB unit follow these steps:
Using the Delphi IDE go to Project &#8211; Import Type Library.
Scroll down until you reach &#8220;Microsoft Jet and Replication Objects 2.1 Library&#8221;.
Click on Install button.
Recompile a gain.

2004. június 18., péntek

Shutting down a machine across the network


Problem/Question/Abstract:

How to send a shutdown command in a network?

Answer:

{-----------------------------------------------------------------------------
Unit Name:     formClient
Author:        Stewart Moss

Creation Date: 27 February, 2002 (16:30)
Documentation Date: 27 February, 2002 (16:30)

Version 1.0
-----------------------------------------------------------------------------

Description:

  This is to demonstrate shutting down a machine over the network.

  ** Tobias R. requests the article "How to send a shutdown command in a network?" **

  This is not really what you want. I think you are looking for some kind
  of IPC or RPC command. But this will work. Each machine needs to run
  a copy of this server.

  It uses the standard delphi ServerSocket found in the "ScktComp" unit.

  Create a form (name frmClient) with a TServerSocket on it (name ServerSocket)
  set the Port property of ServerSocket to 5555. Add a TMemo called Memo1.

  It listens on port 5555 using TCP/IP.

  It has a very simple protocol.
  Z = Show message with "Z"
  B = Beep
  S = Shutdown windows

  Run the program.. Then from the command prompt type in
  "telnet localhost 5555". Type in one of the three commands above
  (all in uppercase) and the server will respond.

Copyright 2002 by Stewart Moss. All rights reserved.
-----------------------------------------------------------------------------}

unit formClient;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ScktComp, StdCtrls;

type
  TfrmClient = class(TForm)
    ServerSocket: TServerSocket;
    Memo1: TMemo;
    procedure ServerSocketClientRead(Sender: TObject;
      Socket: TCustomWinSocket);
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmClient: TfrmClient;

implementation

{$R *.DFM}

procedure TfrmClient.ServerSocketClientRead(Sender: TObject;
  Socket: TCustomWinSocket);
var
  Incomming: string;
begin
  // read off the socket
  Incomming := Socket.ReceiveText;

  memo1.Lines.Add(incomming);

  if Incomming = 'S' then // Shutdown Protocol
    ExitWindowsEx(EWX_FORCE or EWX_SHUTDOWN, 0);

  if Incomming = 'B' then // Beep Protocol
    Beep;

  if Incomming = 'Z' then // Z protocol
    showmessage('Z');
end;

procedure TfrmClient.FormCreate(Sender: TObject);
begin
  ServerSocket.Active := true;
end;

procedure TfrmClient.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  ServerSocket.Active := false;
end;

end.

2004. június 17., csütörtök

Simple useful Irc routines for server protocol


Problem/Question/Abstract:

How to implement some elements of the IRC protocol

Answer:

{-----------------------------------------------------------------------------
Unit Name: IrcStructures

Documentation Date: 19/02/02 23:56:45
Release Date: 8/21/2002
Version: 1.0

Compiler directives:

Purpose:

  Quick framework for keeping track of IRC protocol.

  Was written as a base framework for a simple IRC server

History:

          Copyright 2001 by Stewart Moss
          All rights reserved.
-----------------------------------------------------------------------------}

unit IrcStructures;

interface

type
  recNick = record
    Nick, Email: string;
  end;

type
  RecChannel = record
    ChannelName,
      ChannelTopic: string;
    NumberOfPeople: Integer;
    NickCount: Integer;
    Nicks: array[0..99] of recNick;
  end;

var
  ChanCount: Integer;
  Channels: array[0..99] of RecChannel;

function InitializeChannels: Boolean;

function ChanExist(Channel, Nick: string): Boolean;
function AddChannel(Channel, Topic, Nick: string): Boolean;
function FindChannel(Channel, Nick: string): Integer;
function JoinChannel(Channel, Nick: string): string;

function addNick(ChannelNo: Integer; Nick: string): Boolean;
function NickExists(ChannelNo: Integer; Nick: string): Boolean;

implementation

function InitializeChannels: Boolean;
var
  loop2, loop: integer;
begin
  for loop := 0 to 99 do
  begin
    for loop2 := 0 to 99 do
      Channels[Loop].Nicks[Loop2].Nick := '';
  end;
end;

function ChanExist(Channel, Nick: string): Boolean;
var
  loop: integer;
begin
  Result := False;
  for loop := 0 to ChanCount do
  begin
    if Channel = Channels[Loop].ChannelName then
      Result := true;
  end;
end;

function AddChannel(Channel, Topic, Nick: string): Boolean;
begin
  result := false;
  if ChanExist(Channel, Nick) then
    exit;
  inc(ChanCount);
  Channels[ChanCount].ChannelName := Channel;
  Channels[ChanCount].ChannelTopic := Topic;
  Channels[ChanCount].NumberOfPeople := 0;
  Channels[ChanCount].NickCount := 0;
  result := true;
end;

function FindChannel(Channel, Nick: string): Integer;
var
  loop: integer;
begin
  Result := -1;
  for loop := 0 to ChanCount do
  begin
    if Channel = Channels[Loop].ChannelName then
      Result := Loop;
  end;
end;

function NickExists(ChannelNo: Integer; Nick: string): Boolean;
var
  loop: integer;
begin
  Result := false;
  with Channels[ChannelNo] do
  begin
    for loop := 1 to NickCount do
    begin
      if nicks[Loop - 1].Nick = Nick then
        result := true;
    end;
  end;
end;

function addNick(ChannelNo: Integer; Nick: string): Boolean;
begin
  Result := false;
  if NickExists(ChannelNo, Nick) then
    exit;
  with Channels[ChannelNo] do
  begin
    inc(NickCount);
    nicks[NickCount].Nick := Nick;
  end;
  Result := True;
end;

function JoinChannel(Channel, Nick: string): string;
var
  ChanOfs: Integer;
begin
  Result := 'Could not join ' + Channel;
  ChanOfs := FindChannel(Channel, Nick);
  if ChanOfs = -1 then
    exit;
  with Channels[ChanOfs] do
  begin
    if addNick(ChanOfs, Nick) then
      Result := 'Joined ' + Channel;
  end;
end;

end.