2004. május 5., szerda

Code Insight


Problem/Question/Abstract:

Code Insight

Answer:

Here's a list of the new features in Delphi 3 which are collected under the name 'Code Insight':
Code Insight
Shortcut
Cancel Key
Extra
Code Completion
Ctrl Space
Esc
Can be sorted using right click in popup list.
Incremental search, up and down arrow, home and end keys for navigation.
Respects the visibility of the declared members of the class.
Code Parameters
Ctrl-Shift-Space
Esc

Argument Value List
Ctrl Space

Can be sorted using right click in popup list.
Must be specifically requested.
Displays constants, functions, and variables that are consistent with the argument required by the expression.
Code Templates
Ctrl J

if you type the short cut for the template and then Ctrl J you can skip the popup window.

The Code templates are stored in a ASCII file delphi32.dci which is stored in the Delphi\Bin Folder if you want to enter your templates in manually.

2004. május 4., kedd

How to load a DLL from a resource file and save it to disk


Problem/Question/Abstract:

Is it possible to copy a DLL into my own executable using the IDE only for exporting it after in my program? For example, I create an executable Test.exe and in the IDE I want to attach a resource that contains the DLL. And when my program is running I can export this resource to put a file on my hard disk. Is there a way to do that?

Answer:

Create a file called "mydllres.rc". Edit it and insert the line MYDLL RT_RCDATA "Mydll.dll". Then call the Borland compiler for resouces (you may need to adjust the paths) with BRCC32 mydllres.rc .

This will produce a output file called mydllres.res. Under the implementation header in the main unit add the following: {$R mydllres.res}. This will add the resource to the project.

The following procedure will save it to a file:

procedure savedll;
var
  myres: TResourceStream;
begin
  myres := TResourceStream.Create(hInstance, PChar('MYDLL'), RT_RCDATA);
  myres.SaveToFile(ExtractFilepath(Application.exename) + 'mydll.dll');
  myres.destroy;
end;

2004. május 3., hétfő

Add Interfaces to a List


Problem/Question/Abstract:

It's more efficient to control Interfaces in a List and ask with QueryInterface() which objects support an Interface

Answer:

First we need some Interfaces (the same goes also in Kylix, pure Interfaces are independent from COM, it's a feature of ObjectPascal):

type
  IKiss = interface(IUnknown)
    ['{19A231B1-269F-45A2-85F1-6D8A629CC53F}']
    procedure kiss; stdcall;
  end;

  ISpeak = interface(IUnknown)
    ['{B7F6F015-88A6-47AC-9176-87B6E313962D}']
    procedure sayHello; stdcall;
  end;

Second the interfaces must be implemented:

TDog = class(TInterfacedObject, ISpeak)
public
  procedure sayHello; stdcall;
end;

TFrench = class(TInterfacedObject, ISpeak, IKiss)
public
  procedure kiss; stdcall;
  procedure sayHello; stdcall;
end;

TEnglish = class(TInterfacedObject, ISpeak)
public
  procedure sayHello; stdcall;
end;

e.g. the dog with

procedure TDog.sayHello;
begin
  showmessage('dog is barking wauwau');
end;

Now we add the instances of the interface in the list, using the defined type TInterfaceList so we are able to ask with QueryInterface if an object supports an Interface, in our example if a dog as an object can kiss or just sayhello:

procedure TForm1.btnCollectClick(Sender: TObject);
var
  collection: TInterfaceList;
  i: Integer;
  aObjspeak: ISpeak;
  aObjKiss: IKiss;
begin
  collection := TinterfaceList.create;
  try
    with collection do
    begin
      add(TEnglish.create);
      add(TFrench.create);
      add(TDog.create);
    end;
    for i := 0 to collection.count - 1 do
    begin
      aObjSpeak := collection[i] as ISpeak; //TFrench, TEnglish, TDog
      if aObjSpeak <> nil then
        aObjSpeak.sayHello;
      collection[i].queryInterface(IKiss, aObjKiss); //only TFrench
      if aObjKiss <> nil then
        aObjKiss.kiss;
    end;
  finally
    collection.free;
  end;
end;

2004. május 2., vasárnap

RGB and HSV conversions


Problem/Question/Abstract:

Sometimes it is best to deal with colors as HSV rather than RGB. The artical explains a little bit what HSV is and includes source for converting between the two.

Answer:

HSV is Hue, Saturation, and Value.

HSV:

Hard to explain without a picture so you will have to use your imagination...

Hue:

Draw a circle in your head, the circle is 0 to 360 degrees (or 359 :-) ).  On the outer edge of the circle, place a red dot at 0 degrees, a green dot at 120 degrees and a blue dot at 240 degrees.  Those are the main points.  The other points between these 3 colors are interpolated... for example yellow is between red and green at 60 degrees (equal red + green = yellow), cyan is between green and blue at 180 degrees, magenta is between blue and red at 300 degrees.  Then between yellow and red is another and you keep breaking it down until your circle is full.  The outer edge from 0 to 360 degrees is the hue.

Saturation:

The center of the circle is white.  The color blends with the other colors to white as you go from the outside of the circle to the center.  The outer egde is saturation of 1 and the center is 0 (white).

Value:

Value is simply the intensity of the color.

You already know RGB I assume since you are a programmer.

I played around with my digital camera and took a picture of my brown computer chair.  I created an algorithm that turned my chair green.  It was easy with HSV, I simply used photoshop to see what the hue was of the chair.  Then I rotated the hue so that the chair was in the green range.  Boom, the chair was green.

Here they are:

http://www.eggcentric.com/eimages/greenchair.jpg
http://www.eggcentric.com/eimages/brownchair.jpg

Here is the source of procedures to convert between RGB and HSV and back again.  You can also download it from the link.

unit RGBHSV;
{
  William Egge, public@eggcentric.com
  http://www.eggcentric.com

  This unit converts between RGB and HSV color models.

  procedure HSVToRGB(const H, S, V: Single; out R, G, B: Single);
    in
    H = Hue.  Range is from 0..1.  0.5 = 180 degrees, 1 = 360. or H < 0 for gray
    S = Satration.  Range is 0..1 where 0 is white and 1 is no saturation.
    V = Value.  Range is 0..255

    out
    R = 0..255
    G = 0..255
    B = 0..255

    If H < 0 then the result is a gray value R=V, G=V, B=V

  procedure RGBToHSV(const R, G, B: Single; out H, S, V: Single);
    in
    R = 0..255
    G = 0..255
    B = 0..255

    out
    H = Hue. -1 for grey scale or range 0..1.  0..1 represents 0..360 degrees
    S = Saturation. Range = 0..1. 0 = white, 1 = no saturation.
    V = Value or intensity. Range 0..255
}

interface
uses
  Math;

procedure HSVToRGB(const H, S, V: Single; out R, G, B: Single);
procedure RGBToHSV(const R, G, B: Single; out H, S, V: Single);

implementation

procedure HSVToRGB(const H, S, V: Single; out R, G, B: Single);
const
  SectionSize = 60 / 360;
var
  Section: Single;
  SectionIndex: Integer;
  f: single;
  p, q, t: Single;
begin
  if H < 0 then
  begin
    R := V;
    G := R;
    B := R;
  end
  else
  begin
    Section := H / SectionSize;
    SectionIndex := Floor(Section);
    f := Section - SectionIndex;
    p := V * (1 - S);
    q := V * (1 - S * f);
    t := V * (1 - S * (1 - f));
    case SectionIndex of
      0:
        begin
          R := V;
          G := t;
          B := p;
        end;
      1:
        begin
          R := q;
          G := V;
          B := p;
        end;
      2:
        begin
          R := p;
          G := V;
          B := t;
        end;
      3:
        begin
          R := p;
          G := q;
          B := V;
        end;
      4:
        begin
          R := t;
          G := p;
          B := V;
        end;
    else
      R := V;
      G := p;
      B := q;
    end;
  end;
end;

procedure RGBToHSV(const R, G, B: Single; out H, S, V: Single);
var
  RGB: array[0..2] of Single;
  MinIndex, MaxIndex: Integer;
  Range: Single;
begin
  RGB[0] := R;
  RGB[1] := G;
  RGB[2] := B;

  MinIndex := 0;
  if G < R then
    MinIndex := 1;

  if B < RGB[MinIndex] then
    MinIndex := 2;

  MaxIndex := 0;
  if G > R then
    MaxIndex := 1;

  if B > RGB[MaxIndex] then
    MaxIndex := 2;

  Range := RGB[MaxIndex] - RGB[MinIndex];

  // Check for a gray level
  if Range = 0 then
  begin
    H := -1; // Can't determine on greys, so set to -1
    S := 0; // Gray is at the center;
    V := R; // could choose R, G, or B because they are all the same value.
  end
  else
  begin
    case MaxIndex of
      0: H := (G - B) / Range;
      1: H := 2 + (B - R) / Range;
      2: H := 4 + (R - G) / Range;
    end;
    S := Range / RGB[MaxIndex];
    V := RGB[MaxIndex];
    H := H * (1 / 6);
    if H < 0 then
      H := 1 + H;
  end;
end;

end.


Component Download: http://www.eggcentric.com/download/rgbhsv.zip

2004. május 1., szombat

Insert text at bookmark positions of a Word document


Problem/Question/Abstract:

How to insert text at bookmark positions of a Word document

Answer:

procedure WordBookInsert(v: OleVariant; sgoto, sdata: string);
begin
  try
    {make sure we have passed a word.application level variant}
    if not varisempty(v) then
    begin
      V.Selection.goto(What := wdGoToBookmark, Name := sgoto);
      V.Selection.TypeText(Text := SDATA);
    end;
  except
    {trap OLE errors and display message if it fails}
    on E: sysutils.exception do
    begin
      showmessage(e.message);
    end;
  end;
end;

2004. április 30., péntek

Using Microsoft Index Server from Delphi


Problem/Question/Abstract:

Many people has asked how to search inside an index server from Microsoft in order to show the results like a normal dataset. Here's how this can be done and some considerations on the use & misuse of this technology

Answer:

What is Index Server

Index Server is the web-based solution choosen by Microsoft to give its IIS server the ability to search and retrieve documents; as it is concieved for use with ASP pages, it is strongly based on COM technology and in its latest release has been fully integrated also with the ADO technology.

First Steps

I will demonstrate how to leverage on ADO in order to search the directories of the default catalog of the main website; to search another catalog you will just change an option.
First of all you should get the Microsoft primer on Index Server at:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnindex/html/msdn_is-intro.asp

With this link you wil lfind the explanation necessary to use the index server; using it is anyway easy.
To start it just go inside the Microsoft Management Console (MMC) and open inside it the services; the Microsoft Index Server Service is listed here, just right click to view the contextual menu and choose from it the "Start" option; if you want you can have it start automatically on every boot, just choose the properties of the listed item and choose "Auto Start" from the combo box.
You can have more than 1 catalog to search within; top add new catalogues you should open the MMC for IIS and work from it, but remember that this works only with Nt4/W2K server, not workstation, as in Nt4/W2K wkst only 1 web site is allowed.
BTW: The default catalog is named "WEB".

ADO integration

Let's get our feet wet... We will build a form with a text field and a db grid in which you will see the results of your search, just like using a normal database like access or sql server
First of all open a brand new Delphi Project; add a ADQuery & ADOConncetion couple on the form, together with a Datasource and a DBGrid. You will also need a button and a Edit component.
After these veru first steps, double click on the connectionstring property of the ADOCOnnection1 component; it will open the standard box; from the list of OLEDB Providers you should find (if your ADO is up to date) choose:
"Microsoft OleDb Provider for Indexing Services"; with a double click you will have access to the advanced options, which are already setted correctly; if you want to change the catalogue, just modify the text in the "data source" field. Click on "Test connection", everything should work.

Connect together as usual the components:

Adoquery1 -> Adoconnection1
Datasource1 -> Adoquery1
DBGRID1 -> Datasource1

I suggest of course to keep Adoconnection1.loginprompt := False and to open the connection asap (I made this at design time).

and then double click on th Button you already placed on the form in the first step; the event handler is as follows, just copy and paste:

var
  tmp: string;
begin
  if ADOQuery2.active then
    ADOQuery2.close;
  tmp := 'Select DocTitle, path, rank, size, Vpath, write FROM scope() WHERE
         CONTAINS(''' + edit1.text + ''') > 0 ORDER by FileName';
  ADOQuery2.sql.text := tmp;
  ADOQuery2.Open;
end;

now you have finished: just run the application and type "note" inside the text field, it should show you 3/4 records inside the dbgrid, with the records showing the file names, path etc etc.

Pros & Cons

PROS

You can integrate searched made on Index server and other data repositories like Access files... this can be very useful for sites based upon dynamic page creation technology.
Zero administration
Perfect for ASP objects made in Delphi and for CGIs

CONS

First of all there is a bug in the ADOQuery implementation by Borland, changing the SQL property of the ADOQUERY may result in error messages at design time; it is a confirmed bug, anyway everything works perfectly on runtime. So don't worry for this; maybe a patch will be given to Delphi user, otherwise you can try other ways (Using native ADO as COM objects resolve the problem)
Second: Index Server is tigtly integrated with IIS so you can search only web catalogues, not particular directories of you file system.


Component Download: http://www.dreamscapeitalia.com/download/delphi_index_server.zip

2004. április 29., csütörtök

Sending Raw IP Packets


Problem/Question/Abstract:

How can I send raw IP Packets?

Answer:

This example just showes how to send an UDP packet with customized (spoofed) source ip+port.

Using raw sockets you can SEND raw packets over the internet containing whatever you like.

Keep in mind:

This only works under Window 2000.

You can SEND raw packets. You can NOT RECEIVE raw packets.

You must be Administrator to run this.

This unit requires a form containing a button and a memo.


Usage:

Before you run your program, you must change the SrcIP+SrcPort+ DestIP+DestPort to suitable values!

If you don't understand what this source does: Don't use it.

unit main;

interface

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

const
  SrcIP = '123.123.123.1';
  SrcPort = 1234;
  DestIP = '123.123.123.2';
  DestPort = 4321;

  Max_Message = 4068;
  Max_Packet = 4096;

type

  TPacketBuffer = array[0..Max_Packet - 1] of byte;

  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure SendIt;
  end;

  // IP Header
type
  T_IP_Header = record
    ip_verlen: Byte;
    ip_tos: Byte;
    ip_totallength: Word;
    ip_id: Word;
    ip_offset: Word;
    ip_ttl: Byte;
    ip_protocol: Byte;
    ip_checksum: Word;
    ip_srcaddr: LongWord;
    ip_destaddr: LongWord;
  end;

  // UDP Header
type
  T_UDP_Header = record
    src_portno: Word;
    dst_portno: Word;
    udp_length: Word;
    udp_checksum: Word;
  end;

  // Some Winsock 2 type declarations
  u_char = Char;
  u_short = Word;
  u_int = Integer;
  u_long = Longint;

  SunB = packed record
    s_b1, s_b2, s_b3, s_b4: u_char;
  end;
  SunW = packed record
    s_w1, s_w2: u_short;
  end;
  in_addr = record
    case integer of
      0: (S_un_b: SunB);
      1: (S_un_w: SunW);
      2: (S_addr: u_long);
  end;
  TInAddr = in_addr;
  Sockaddr_in = record
    case Integer of
      0: (sin_family: u_short;
        sin_port: u_short;
        sin_addr: TInAddr;
        sin_zero: array[0..7] of Char);
      1: (sa_family: u_short;
        sa_data: array[0..13] of Char)
  end;
  TSockAddr = Sockaddr_in;
  TSocket = u_int;

const
  WSADESCRIPTION_LEN = 256;
  WSASYS_STATUS_LEN = 128;

type
  PWSAData = ^TWSAData;
  WSAData = record // !!! also WSDATA
    wVersion: Word;
    wHighVersion: Word;
    szDescription: array[0..WSADESCRIPTION_LEN] of Char;
    szSystemStatus: array[0..WSASYS_STATUS_LEN] of Char;
    iMaxSockets: Word;
    iMaxUdpDg: Word;
    lpVendorInfo: PChar;
  end;
  TWSAData = WSAData;

  // Define some winsock 2 functions
function closesocket(s: TSocket): Integer; stdcall;
function socket(af, Struct, protocol: Integer): TSocket; stdcall;
function sendto(s: TSocket; var Buf; len, flags: Integer; var addrto: TSockAddr;
  tolen: Integer): Integer; stdcall; {}
function setsockopt(s: TSocket; level, optname: Integer; optval: PChar;
  optlen: Integer): Integer; stdcall;
function inet_addr(cp: PChar): u_long; stdcall; {PInAddr;} { TInAddr }
function htons(hostshort: u_short): u_short; stdcall;
function WSAGetLastError: Integer; stdcall;
function WSAStartup(wVersionRequired: word; var WSData: TWSAData): Integer; stdcall;
function WSACleanup: Integer; stdcall;

const
  AF_INET = 2; // internetwork: UDP, TCP, etc.

  IP_HDRINCL = 2; // IP Header Include

  SOCK_RAW = 3; // raw-protocol interface

  IPPROTO_IP = 0; // dummy for IP
  IPPROTO_TCP = 6; // tcp
  IPPROTO_UDP = 17; // user datagram protocol
  IPPROTO_RAW = 255; // raw IP packet

  INVALID_SOCKET = TSocket(not (0));
  SOCKET_ERROR = -1;

var
  Form1: TForm1;

implementation

// Import Winsock 2 functions
const
  WinSocket = 'WS2_32.DLL';

function closesocket; external winsocket name 'closesocket';
function socket; external winsocket name 'socket';
function sendto; external winsocket name 'sendto';
function setsockopt; external winsocket name 'setsockopt';
function inet_addr; external winsocket name 'inet_addr';
function htons; external winsocket name 'htons';
function WSAGetLastError; external winsocket name 'WSAGetLastError';
function WSAStartup; external winsocket name 'WSAStartup';
function WSACleanup; external winsocket name 'WSACleanup';

{$R *.DFM}

//
// Function: checksum
//
// Description:
//    This function calculates the 16-bit one's complement sum
//    for the supplied buffer
//

function CheckSum(var Buffer; Size: integer): Word;
type
  TWordArray = array[0..1] of Word;
var
  ChkSum: LongWord;
  i: Integer;
begin
  ChkSum := 0;
  i := 0;
  while Size > 1 do
  begin
    ChkSum := ChkSum + TWordArray(Buffer)[i];
    inc(i);
    Size := Size - SizeOf(Word);
  end;

  if Size = 1 then
    ChkSum := ChkSum + Byte(TWordArray(Buffer)[i]);

  ChkSum := (ChkSum shr 16) + (ChkSum and $FFFF);
  ChkSum := ChkSum + (Chksum shr 16);

  Result := Word(ChkSum);
end;

procedure BuildHeaders(
  FromIP: string;
  iFromPort: Word;
  ToIP: string;
  iToPort: Word;
  StrMessage: string;
  var Buf: TPacketBuffer;
  var remote: TSockAddr;
  var iTotalSize: Word
  );
var
  dwFromIP: LongWord;
  dwToIP: LongWord;

  iIPVersion: Word;
  iIPSize: Word;
  ipHdr: T_IP_Header;
  udpHdr: T_UDP_Header;

  iUdpSize: Word;
  iUdpChecksumSize: Word;
  cksum: Word;

  Ptr: ^Byte;

  procedure IncPtr(Value: Integer);
  begin
    ptr := pointer(integer(ptr) + Value);
  end;

begin
  // Convert ip address'ss

  dwFromIP := inet_Addr(PChar(FromIP));
  dwToIP := inet_Addr(PChar(ToIP));

  // Initalize the IP header
  //
  iTotalSize := sizeof(ipHdr) + sizeof(udpHdr) + length(strMessage);

  iIPVersion := 4;
  iIPSize := sizeof(ipHdr) div sizeof(LongWord);
  //
  // IP version goes in the high order 4 bits of ip_verlen. The
  // IP header length (in 32-bit words) goes in the lower 4 bits.
  //
  ipHdr.ip_verlen := (iIPVersion shl 4) or iIPSize;
  ipHdr.ip_tos := 0; // IP type of service
  ipHdr.ip_totallength := htons(iTotalSize); // Total packet len
  ipHdr.ip_id := 0; // Unique identifier: set to 0
  ipHdr.ip_offset := 0; // Fragment offset field
  ipHdr.ip_ttl := 128; // Time to live
  ipHdr.ip_protocol := $11; // Protocol(UDP)
  ipHdr.ip_checksum := 0; // IP checksum
  ipHdr.ip_srcaddr := dwFromIP; // Source address
  ipHdr.ip_destaddr := dwToIP; // Destination address
  //
  // Initalize the UDP header
  //
  iUdpSize := sizeof(udpHdr) + length(strMessage);

  udpHdr.src_portno := htons(iFromPort);
  udpHdr.dst_portno := htons(iToPort);
  udpHdr.udp_length := htons(iUdpSize);
  udpHdr.udp_checksum := 0;
  //
  // Build the UDP pseudo-header for calculating the UDP checksum.
  // The pseudo-header consists of the 32-bit source IP address,
  // the 32-bit destination IP address, a zero byte, the 8-bit
  // IP protocol field, the 16-bit UDP length, and the UDP
  // header itself along with its data (padded with a 0 if
  // the data is odd length).
  //
  iUdpChecksumSize := 0;

  ptr := @buf[0];
  FillChar(Buf, SizeOf(Buf), 0);

  Move(ipHdr.ip_srcaddr, ptr^, SizeOf(ipHdr.ip_srcaddr));
  IncPtr(SizeOf(ipHdr.ip_srcaddr));

  iUdpChecksumSize := iUdpChecksumSize + sizeof(ipHdr.ip_srcaddr);

  Move(ipHdr.ip_destaddr, ptr^, SizeOf(ipHdr.ip_destaddr));
  IncPtr(SizeOf(ipHdr.ip_destaddr));

  iUdpChecksumSize := iUdpChecksumSize + sizeof(ipHdr.ip_destaddr);

  IncPtr(1);

  Inc(iUdpChecksumSize);

  Move(ipHdr.ip_protocol, ptr^, sizeof(ipHdr.ip_protocol));
  IncPtr(sizeof(ipHdr.ip_protocol));
  iUdpChecksumSize := iUdpChecksumSize + sizeof(ipHdr.ip_protocol);

  Move(udpHdr.udp_length, ptr^, sizeof(udpHdr.udp_length));
  IncPtr(sizeof(udpHdr.udp_length));
  iUdpChecksumSize := iUdpChecksumSize + sizeof(udpHdr.udp_length);

  move(udpHdr, ptr^, sizeof(udpHdr));
  IncPtr(sizeof(udpHdr));
  iUdpChecksumSize := iUdpCheckSumSize + sizeof(udpHdr);

  Move(StrMessage[1], ptr^, Length(strMessage));
  IncPtr(Length(StrMessage));

  iUdpChecksumSize := iUdpChecksumSize + length(strMessage);

  cksum := checksum(buf, iUdpChecksumSize);
  udpHdr.udp_checksum := cksum;

  //
  // Now assemble the IP and UDP headers along with the data
  //  so we can send it
  //
  FillChar(Buf, SizeOf(Buf), 0);
  Ptr := @Buf[0];

  Move(ipHdr, ptr^, SizeOf(ipHdr));
  IncPtr(SizeOf(ipHdr));
  Move(udpHdr, ptr^, SizeOf(udpHdr));
  IncPtr(SizeOf(udpHdr));
  Move(StrMessage[1], ptr^, length(StrMessage));

  // Apparently, this SOCKADDR_IN structure makes no difference.
  // Whatever we put as the destination IP addr in the IP header
  // is what goes. Specifying a different destination in remote
  // will be ignored.
  //
  remote.sin_family := AF_INET;
  remote.sin_port := htons(iToPort);
  remote.sin_addr.s_addr := dwToIP;
end;

procedure TForm1.SendIt;
var
  sh: TSocket;
  bOpt: Integer;
  ret: Integer;
  Buf: TPacketBuffer;
  Remote: TSockAddr;
  Local: TSockAddr;
  iTotalSize: Word;
  wsdata: TWSAdata;

begin
  // Startup Winsock 2
  ret := WSAStartup($0002, wsdata);
  if ret <> 0 then
  begin
    memo1.lines.add('WSA Startup failed.');
    exit;
  end;
  with memo1.lines do
  begin
    add('WSA Startup:');
    add('Desc.:  ' + wsData.szDescription);
    add('Status: ' + wsData.szSystemStatus);
  end;

  try
    // Create socket
    sh := Socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
    if (sh = INVALID_SOCKET) then
    begin
      memo1.lines.add('Socket() failed: ' + IntToStr(WSAGetLastError));
      exit;
    end;
    Memo1.lines.add('Socket Handle = ' + IntToStr(sh));

    // Option: Header Include
    bOpt := 1;
    ret := SetSockOpt(sh, IPPROTO_IP, IP_HDRINCL, @bOpt, SizeOf(bOpt));
    if ret = SOCKET_ERROR then
    begin
      Memo1.lines.add('setsockopt(IP_HDRINCL) failed: ' + IntToStr(WSAGetLastError));
      exit;
    end;

    // Build the packet
    BuildHeaders(SrcIP, SrcPort,
      DestIP, DestPort,
      'THIS IS A TEST PACKET',
      Buf, Remote, iTotalSize);

    // Send the packet
    ret := SendTo(sh, buf, iTotalSize, 0, Remote, SizeOf(Remote));
    if ret = SOCKET_ERROR then
      Memo1.Lines.Add('sendto() failed: ' + IntToStr(WSAGetLastError))
    else
      Memo1.Lines.Add('send ' + IntToStr(ret) + ' bytes.');

    // Close socket
    CloseSocket(sh);
  finally
    // Close Winsock 2
    WSACleanup;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  SendIt;
end;

end.

2004. április 28., szerda

Muting and revoicing the audio from your application


Problem/Question/Abstract:

Based on an old article that described the solution for muting the audio during my application, someone asked me to make a similar to be controlled from a Button: here's the solution... easy and fast!

Answer:

WARNING: you must avoid pressing 2 times the mute button or the mixer data will be lost. so I added a boolean condition.

uses
  MMSystem;

{...}

{Global variables}

var
  MyVolume: array[0..10] of LongInt;
  mDevs: Integer;
  IsMute: Boolean;

Create two button:

cmdMute
cmdRevoice

procedure TfrmMain.FormCreate(Sender: TObject);
begin
  IsMute := False;
end;

procedure TfrmMain.cmdMuteClick(Sender: TObject);
var
  I: Integer;
begin
  if (not (IsMute)) then
  begin
    mDevs := auxGetNumDevs;
    for I := 0 to mDevs do
    begin
      auxGetVolume(I, Addr(MyVolume[I]));
      auxSetVolume(I, LongInt(9000) * 65536 + LongInt(9000));
    end;
    IsMute := True;
  end;
end;

procedure TfrmMain.cmdRevoiceClick(Sender: TObject);
var
  I: Integer;
begin
  if (IsMute) then
  begin
    for I := 0 to mDevs do
      auxSetVolute(I, MyVolume[I]);
    IsMute := False;
  end;
end;

2004. április 27., kedd

Get the list of function that an executable file imports


Problem/Question/Abstract:

How to get the list of functions that an executable file imports as well as other information like the dlls from which the program imports these functions.

Answer:

The following program shows how you can get the list of functions imported by the executable file. It consists of two units the first one is the 'structures' unit which is required by the program unit

Here is the code

Structures File

unit structures;

interface
uses Windows, sysutils;
const
  IMAGE_DOS_SIGNATURE = $5A4D; { MZ }
  IMAGE_OS2_SIGNATURE = $454E; { NE }
  IMAGE_OS2_SIGNATURE_LE = $454C; { LE }
  IMAGE_VXD_SIGNATURE = $454C; { LE }
  IMAGE_NT_SIGNATURE = $00004550; { PE00 }

  IMAGE_SIZEOF_SHORT_NAME = 8;
  IMAGE_SIZEOF_SECTION_HEADER = 40;
  IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
  IMAGE_RESOURCE_NAME_IS_STRING = $80000000;
  IMAGE_RESOURCE_DATA_IS_DIRECTORY = $80000000;
  IMAGE_OFFSET_STRIP_HIGH = $7FFFFFFF;
  DIRECTORY_ENTRY_EXPORT = 0; // Export Directory
  IMAGE_DIRECTORY_ENTRY_IMPORT = 1; // Import Directory
  IMAGE_DIRECTORY_ENTRY_RESOURCE = 2; // Resource Directory
  IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3; // Exception Directory
  IMAGE_DIRECTORY_ENTRY_SECURITY = 4; // Security Directory
  IMAGE_DIRECTORY_ENTRY_BASERELOC = 5; // Base Relocation Table
  IMAGE_DIRECTORY_ENTRY_DEBUG = 6; // Debug Directory
  IMAGE_DIRECTORY_ENTRY_COPYRIGHT = 7; // Description String
  IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8; // Machine Value (MIPS GP)
  IMAGE_DIRECTORY_ENTRY_TLS = 9; // TLS Directory
  IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10; // Load Configuration Directory
  IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11; // Bound Import Directory in headers
  IMAGE_DIRECTORY_ENTRY_IAT = 12;

type
  plist_entry = ^LIST_ENTRY;
  LIST_ENTRY = record
    Flink: pLIST_ENTRY;
    Blink: pLIST_ENTRY;
  end;

type
  IMAGE_EXPORT_DIRECTORY = packed record
    Characteristics: DWORD;
    TimeDateStamp: DWORD;
    MajorVersion: WORD;
    MinorVersion: WORD;
    Name: DWORD;
    Base: DWORD;
    NumberOfFunctions: DWORD;
    NumberOfNames: DWORD;
    pAddressOfFunctions: PDWORD;
    pAddressOfNames: PDWORD;
    pAddressOfNameOrdinals: PWORD;
  end;
  PIMAGE_EXPORT_DIRECTORY = ^IMAGE_EXPORT_DIRECTORY;

type
  FPO_DATA = packed record
    ulOffStart: DWORD; // offset 1st byte of function code
    cbProcSize: DWORD; // # bytes in function
    cdwLocals: DWORD; // # bytes in locals/4
    cdwParams: WORD; // # bytes in params/4
    cbProlog: WORD; // # bytes in prolog
    cbRegs: WORD; // # regs saved
    fHasSEH: WORD; // TRUE if SEH in func
    fUseBP: WORD; // TRUE if EBP has been allocated
    reserved: WORD; // reserved for future use
    cbFrame: WORD; // frame type
  end;
  PFPO_DATA = ^FPO_DATA;

type
  IMAGE_FUNCTION_ENTRY = packed record
    StartingAddress: dword;
    EndingAddress: dword;
    EndOfPrologue: dword;
  end;
  PIMAGE_FUNCTION_ENTRY = ^IMAGE_FUNCTION_ENTRY;

type
  PIMAGE_DOS_HEADER = ^IMAGE_DOS_HEADER;
  IMAGE_DOS_HEADER = packed record { DOS .EXE header }
    e_magic: WORD; { Magic number }
    e_cblp: WORD; { Bytes on last page of file }
    e_cp: WORD; { Pages in file }
    e_crlc: WORD; { Relocations }
    e_cparhdr: WORD; { Size of header in paragraphs }
    e_minalloc: WORD; { Minimum extra paragraphs needed }
    e_maxalloc: WORD; { Maximum extra paragraphs needed }
    e_ss: WORD; { Initial (relative) SS value }
    e_sp: WORD; { Initial SP value }
    e_csum: WORD; { Checksum }
    e_ip: WORD; { Initial IP value }
    e_cs: WORD; { Initial (relative) CS value }
    e_lfarlc: WORD; { File address of relocation table }
    e_ovno: WORD; { Overlay number }
    e_res: packed array[0..3] of WORD; { Reserved words }
    e_oemid: WORD; { OEM identifier (for e_oeminfo) }
    e_oeminfo: WORD; { OEM information; e_oemid specific }
    e_res2: packed array[0..9] of WORD; { Reserved words }
    e_lfanew: Longint; { File address of new exe header }
  end;

  PIMAGE_FILE_HEADER = ^IMAGE_FILE_HEADER;
  IMAGE_FILE_HEADER = packed record
    Machine: WORD;
    NumberOfSections: WORD;
    TimeDateStamp: DWORD;
    PointerToSymbolTable: DWORD;
    NumberOfSymbols: DWORD;
    SizeOfOptionalHeader: WORD;
    Characteristics: WORD;
  end;

  PIMAGE_DATA_DIRECTORY = ^IMAGE_DATA_DIRECTORY;
  IMAGE_DATA_DIRECTORY = packed record
    VirtualAddress: DWORD;
    Size: DWORD;
  end;

  PIMAGE_OPTIONAL_HEADER = ^IMAGE_OPTIONAL_HEADER;
  IMAGE_OPTIONAL_HEADER = packed record
    { Standard fields. }
    Magic: WORD;
    MajorLinkerVersion: Byte;
    MinorLinkerVersion: Byte;
    SizeOfCode: DWORD;
    SizeOfInitializedData: DWORD;
    SizeOfUninitializedData: DWORD;
    AddressOfEntryPoint: DWORD;
    BaseOfCode: DWORD;
    BaseOfData: DWORD;
    { NT additional fields. }
    ImageBase: DWORD;
    SectionAlignment: DWORD;
    FileAlignment: DWORD;
    MajorOperatingSystemVersion: WORD;
    MinorOperatingSystemVersion: WORD;
    MajorImageVersion: WORD;
    MinorImageVersion: WORD;
    MajorSubsystemVersion: WORD;
    MinorSubsystemVersion: WORD;
    Reserved1: DWORD;
    SizeOfImage: DWORD;
    SizeOfHeaders: DWORD;
    CheckSum: DWORD;
    Subsystem: WORD;
    DllCharacteristics: WORD;
    SizeOfStackReserve: DWORD;
    SizeOfStackCommit: DWORD;
    SizeOfHeapReserve: DWORD;
    SizeOfHeapCommit: DWORD;
    LoaderFlags: DWORD;
    NumberOfRvaAndSizes: DWORD;
    DataDirectory: packed array[0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of
      IMAGE_DATA_DIRECTORY;
  end;

  PIMAGE_SECTION_HEADER = ^IMAGE_SECTION_HEADER;
  IMAGE_SECTION_HEADER = packed record
    Name: packed array[0..IMAGE_SIZEOF_SHORT_NAME - 1] of Char;
    PhysicalAddress: DWORD; // or VirtualSize (union);
    VirtualAddress: DWORD;
    SizeOfRawData: DWORD;
    PointerToRawData: DWORD;
    PointerToRelocations: DWORD;
    PointerToLinenumbers: DWORD;
    NumberOfRelocations: WORD;
    NumberOfLinenumbers: WORD;
    Characteristics: DWORD;
  end;

  PIMAGE_NT_HEADERS = ^IMAGE_NT_HEADERS;
  IMAGE_NT_HEADERS = packed record
    Signature: DWORD;
    FileHeader: IMAGE_FILE_HEADER;
    OptionalHeader: IMAGE_OPTIONAL_HEADER;
  end;

  PIMAGE_RESOURCE_DIRECTORY = ^IMAGE_RESOURCE_DIRECTORY;
  IMAGE_RESOURCE_DIRECTORY = packed record
    Characteristics: DWORD;
    TimeDateStamp: DWORD;
    MajorVersion: WORD;
    MinorVersion: WORD;
    NumberOfNamedEntries: WORD;
    NumberOfIdEntries: WORD;
  end;

  PIMAGE_RESOURCE_DIRECTORY_ENTRY = ^IMAGE_RESOURCE_DIRECTORY_ENTRY;
  IMAGE_RESOURCE_DIRECTORY_ENTRY = packed record
    Name: DWORD; // Or ID: Word (Union)
    OffsetToData: DWORD;
  end;

  PIMAGE_RESOURCE_DATA_ENTRY = ^IMAGE_RESOURCE_DATA_ENTRY;
  IMAGE_RESOURCE_DATA_ENTRY = packed record
    OffsetToData: DWORD;
    Size: DWORD;
    CodePage: DWORD;
    Reserved: DWORD;
  end;

  PIMAGE_RESOURCE_DIR_STRING_U = ^IMAGE_RESOURCE_DIR_STRING_U;
  IMAGE_RESOURCE_DIR_STRING_U = packed record
    Length: WORD;
    NameString: array[0..0] of WCHAR;
  end;

type
  LOADED_IMAGE = record
    ModuleName: pchar;
    hFile: thandle;
    MappedAddress: pchar;
    FileHeader: PIMAGE_NT_HEADERS;
    LastRvaSection: PIMAGE_SECTION_HEADER;
    NumberOfSections: integer;
    Sections: PIMAGE_SECTION_HEADER;
    Characteristics: integer;
    fSystemImage: boolean;
    fDOSImage: boolean;
    Links: LIST_ENTRY;
    SizeOfImage: integer;
  end;
  PLOADED_IMAGE = ^LOADED_IMAGE;

type
  IMAGE_LOAD_CONFIG_DIRECTORY = packed record
    Characteristics: DWORD;
    TimeDateStamp: DWORD;
    MajorVersion: WORD;
    MinorVersion: WORD;
    GlobalFlagsClear: DWORD;
    GlobalFlagsSet: DWORD;
    CriticalSectionDefaultTimeout: DWORD;
    DeCommitFreeBlockThreshold: DWORD;
    DeCommitTotalFreeThreshold: DWORD;
    LockPrefixTable: Pointer;
    MaximumAllocationSize: DWORD;
    VirtualMemoryThreshold: DWORD;
    ProcessHeapFlags: DWORD;
    ProcessAffinityMask: DWORD;
    Reserved: array[0..2] of DWORD;
  end;
  PIMAGE_LOAD_CONFIG_DIRECTORY = ^IMAGE_LOAD_CONFIG_DIRECTORY;

type
  IMAGE_IMPORT_BY_NAME = packed record
    Hint: WORD;
    Name: DWORD;
  end;
  PIMAGE_IMPORT_BY_NAME = ^IMAGE_IMPORT_BY_NAME;

type
  IMAGE_THUNK_DATA = packed record
    ForwarderString: PBYTE;
    Func: PDWORD;
    Ordinal: DWORD;
    AddressOfData: PIMAGE_IMPORT_BY_NAME;
  end;
  PIMAGE_THUNK_DATA = ^IMAGE_THUNK_DATA;

type
  IMAGE_IMPORT_DESCRIPTOR = packed record
    Characteristics: DWORD;
    TimeDateStamp: DWORD;
    ForwarderChain: DWORD;
    Name: DWORD;
    FirstThunk: DWORD;
  end;
  PIMAGE_IMPORT_DESCRIPTOR = ^IMAGE_IMPORT_DESCRIPTOR;

implementation

end.

Code File

unit p1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    OpenDialog1: TOpenDialog;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    procedure ProcessFile;
  end;

var
  Form1: TForm1;
  h1, hmap: integer;
  bptr: pointer;
  gptr: pbyte;
  ntsign: plongword;
  doshd: PIMAGE_DOS_HEADER;
  pehd: PIMAGE_FILE_HEADER;
  peoptn: PIMAGE_OPTIONAL_HEADER;
  sectionheads: array of PIMAGE_SECTION_HEADER;
  offsetmem: longword;
  idataphysicaladress: pbyte;
  idata: PIMAGE_IMPORT_DESCRIPTOR;
  modulename, functionname: pchar;
  dptr: plongword;
  ord: word;
  pexpdir: PIMAGE_EXPORT_DIRECTORY;
  pexpnames: pdword;
  expfname: pchar;
implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
  processfile;
end;

procedure TForm1.ProcessFile;
var
  i, j: integer;
begin
  if opendialog1.Execute = false then
    exit
  else
    h1 := fileopen(opendialog1.FileName, fmShareDenyNone or fmOpenRead);
  hmap := CreateFileMapping(h1, nil, PAGE_READONLY, 0, 0, nil);
  doshd := PIMAGE_DOS_HEADER(mapviewoffile(hmap, FILE_MAP_READ, 0, 0, 0));
  bptr := doshd;
  memo1.lines.add('DOS Header');
  memo1.Lines.Add(' -e_magic=' + inttostr(doshd.e_magic));
  memo1.Lines.Add(' -e_cblp=' + inttostr(doshd.e_cblp));
  memo1.Lines.Add(' -e_cp=' + inttostr(doshd.e_cp));
  memo1.Lines.Add(' -e_crlc=' + inttostr(doshd.e_crlc));
  memo1.Lines.Add(' -e_cparhdr=' + inttostr(doshd.e_cparhdr));
  memo1.Lines.Add(' -e_minalloc=' + inttostr(doshd.e_minalloc));
  memo1.Lines.Add(' -e_maxalloc=' + inttostr(doshd.e_maxalloc));
  memo1.Lines.Add(' -e_ss=' + inttostr(doshd.e_ss));
  memo1.Lines.Add(' -e_sp=' + inttostr(doshd.e_sp));
  memo1.Lines.Add(' -e_csum=' + inttostr(doshd.e_csum));
  memo1.Lines.Add(' -e_ip=' + inttostr(doshd.e_ip));
  memo1.Lines.Add(' -e_cs=' + inttostr(doshd.e_cs));
  memo1.Lines.Add(' -e_lfarlc=' + inttostr(doshd.e_lfarlc));
  memo1.Lines.Add(' -e_ovno=' + inttostr(doshd.e_ovno));
  memo1.Lines.Add(' -e_oemid=' + inttostr(doshd.e_oemid));
  memo1.Lines.Add(' -e_oeminfo=' + inttostr(doshd.e_oeminfo));
  memo1.Lines.Add(' -e_lfanew=' + inttostr(doshd.e_lfanew));
  gptr := bptr;
  inc(gptr, doshd.e_lfanew);
  ntsign := plongword(gptr);
  if (ntsign^ = IMAGE_NT_SIGNATURE) then
  begin
    memo1.Lines.Add('NT Signature<' + inttostr(IMAGE_NT_SIGNATURE) + '>=' +
      inttostr(ntsign^));
    memo1.Lines.Add('Windows Executable');
    memo1.lines.add('------------------------------------------');
    gptr := bptr;
    inc(gptr, doshd.e_lfanew + 4);
    pehd := PIMAGE_FILE_HEADER(gptr);
    memo1.lines.add('PE Header');
    memo1.Lines.Add(' -Machine=' + inttostr(pehd.Machine));
    memo1.Lines.Add(' -Number of Sections=' + inttostr(pehd.NumberOfSections));
    memo1.Lines.Add(' -TimeDateStamp=' + IntToStr(pehd.TimeDateStamp));
    memo1.Lines.Add(' -PointerToSymbolTable=' + IntToStr(pehd.PointerToSymbolTable));
    memo1.Lines.Add(' -Number of Symbols=' + IntToStr(pehd.NumberOfSymbols));
    memo1.Lines.Add(' -SizeOfOptionalHeader=' + IntToStr(pehd.SizeOfOptionalHeader));
    memo1.Lines.Add(' -Characteristics=' + IntToStr(pehd.Characteristics));
    memo1.lines.add('------------------------------------------');
    gptr := pbyte(pehd);
    inc(gptr, sizeof(IMAGE_FILE_HEADER));
    peoptn := PIMAGE_OPTIONAL_HEADER(gptr);
    memo1.lines.add('PE Optional Header');
    memo1.Lines.Add(' -Magic=' + inttostr(peoptn.Magic));
    memo1.Lines.Add(' -MajorLinkerVersion=' + inttostr(peoptn.MajorLinkerVersion));
    memo1.Lines.Add(' -MinorLinkerVersion=' + inttostr(peoptn.MinorLinkerVersion));
    memo1.Lines.Add(' -SizeOfCode=' + inttostr(peoptn.SizeOfCode));
    memo1.Lines.Add(' -SizeOfInitializedData=' +
      inttostr(peoptn.SizeOfInitializedData));
    memo1.Lines.Add(' -SizeOfUninitializedData=' +
      inttostr(peoptn.SizeOfUninitializedData));
    memo1.Lines.Add(' -AddressOfEntryPoint=' + inttostr(peoptn.AddressOfEntryPoint));
    memo1.Lines.Add(' -BaseOfCode=' + inttostr(peoptn.BaseOfCode));
    memo1.Lines.Add(' -BaseOfData=' + inttostr(peoptn.BaseOfData));
    memo1.Lines.Add(' -ImageBase=' + inttostr(peoptn.ImageBase));
    memo1.Lines.Add(' -SectionAlignment=' + inttostr(peoptn.SectionAlignment));
    memo1.Lines.Add(' -FileAlignment=' + inttostr(peoptn.FileAlignment));
    memo1.Lines.Add(' -MajorOperatingSystemVersion=' +
      inttostr(peoptn.MajorOperatingSystemVersion));
    memo1.Lines.Add(' -MinorOperatingSystemVersion=' +
      inttostr(peoptn.MinorOperatingSystemVersion));
    memo1.Lines.Add(' -MajorImageVersion=' + inttostr(peoptn.MajorImageVersion));
    memo1.Lines.Add(' -MinorImageVersion=' + inttostr(peoptn.MinorImageVersion));
    memo1.Lines.Add(' -MajorSubsystemVersion=' +
      inttostr(peoptn.MajorSubsystemVersion));
    memo1.Lines.Add(' -MinorSubsystemVersion =' +
      inttostr(peoptn.MinorSubsystemVersion));
    memo1.Lines.Add(' -Reserved1 =' + inttostr(peoptn.Reserved1));
    memo1.Lines.Add(' -SizeOfImage =' + inttostr(peoptn.SizeOfImage));
    memo1.Lines.Add(' -SizeOfHeaders =' + inttostr(peoptn.SizeOfHeaders));
    memo1.Lines.Add(' -CheckSum =' + inttostr(peoptn.CheckSum));
    memo1.Lines.Add(' -SubSystem =' + inttostr(peoptn.Subsystem));
    memo1.Lines.Add(' -DllCharacteristics =' + inttostr(peoptn.DllCharacteristics));
    memo1.Lines.Add(' -SizeOfStackReserve =' + inttostr(peoptn.SizeOfStackReserve));
    memo1.Lines.Add(' -SizeOfStackCommit =' + inttostr(peoptn.SizeOfStackCommit));
    memo1.Lines.Add(' -SizeOfHeapReserve =' + inttostr(peoptn.SizeOfHeapReserve));
    memo1.Lines.Add(' -SizeOfHeapCommit =' + inttostr(peoptn.SizeOfHeapCommit));
    memo1.Lines.Add(' -LoaderFlags =' + inttostr(peoptn.LoaderFlags));
    memo1.Lines.Add(' -NumberOfRvaAndSizes =' + inttostr(peoptn.NumberOfRvaAndSizes));
    memo1.lines.add('------------------------------------------');
    setlength(sectionheads, pehd.NumberOfSections);
    for i := 0 to pehd.NumberOfSections - 1 do
    begin
      gptr := pbyte(peoptn);
      inc(gptr, sizeof(IMAGE_OPTIONAL_HEADER) + i * sizeof(IMAGE_SECTION_HEADER));
      sectionheads[i] := PIMAGE_SECTION_HEADER(gptr);
    end;
    if peoptn.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = 0 then
    begin
      memo1.lines.add('No Export Table Present');
      memo1.lines.add('------------------------------------------');
    end
    else
    begin
      memo1.lines.add('Export Table Present');
      for i := pehd.NumberOfSections - 1 downto 0 do
      begin
        if peoptn.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress >=
          sectionheads[i].VirtualAddress then
        begin
          offsetmem := sectionheads[i].PointerToRawData -
            sectionheads[i].VirtualAddress;
          break;
        end;
      end;
      gptr := bptr;
      inc(gptr, offsetmem +
        peoptn.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
      pexpdir := PIMAGE_EXPORT_DIRECTORY(gptr);
      pexpnames := pdword(longint(bptr) +
        integer(PIMAGE_EXPORT_DIRECTORY(gptr).pAddressOfNames));
      for i := 0 to pexpdir.NumberOfNames - 1 do
      begin
        expfname := pchar(integer(bptr) + integer(pexpnames^));
        memo1.lines.add(' -' + expfname);
        inc(pexpnames);
      end;
      memo1.lines.add('------------------------------------------');
    end;
    if peoptn.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = 0 then
      memo1.lines.add('No Import Table Present')
    else
    begin
      memo1.lines.add('Import Table Present');
      for i := pehd.NumberOfSections - 1 downto 0 do
      begin
        if peoptn.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress >=
          sectionheads[i].VirtualAddress then
        begin
          offsetmem := sectionheads[i].PointerToRawData -
            sectionheads[i].VirtualAddress;
          break;
        end;
      end;
      gptr := bptr;
      inc(gptr, offsetmem +
        peoptn.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
      idataphysicaladress := gptr;
      i := 0;
      j := 0;
      while true do
      begin
        gptr := idataphysicaladress;
        inc(gptr, i * sizeof(IMAGE_IMPORT_DESCRIPTOR));
        idata := PIMAGE_IMPORT_DESCRIPTOR(gptr);
        if idata.Name = 0 then
          break;
        gptr := bptr;
        inc(gptr, offsetmem + idata.Name);
        modulename := pchar(gptr);
        memo1.Lines.Add('Module Name:' + modulename);
        while true do
        begin
          if (idata.FirstThunk + j * 4) = 0 then
            break;
          gptr := bptr;
          inc(gptr, offsetmem + idata.FirstThunk + j * 4);
          dptr := plongword(gptr);
          gptr := bptr;
          inc(gptr, offsetmem + dptr^);
          if isbadcodeptr(gptr) then
            break;
          ord := pword(gptr)^;
          inc(gptr, 2);
          functionname := pchar(gptr);
          if isbadcodeptr(functionname) then
            break;
          if functionname = nil then
            break;
          memo1.Lines.Add('  -Ord:' + inttohex(ord, 3) + ' Function Name:' +
            functionname);
          inc(j);
        end;
        inc(i);
      end;
    end;
  end;
  UnmapViewOfFile(bptr);
  closehandle(hmap);
  fileclose(h1);
end;

end.

2004. április 26., hétfő

Handling Winsock errors


Problem/Question/Abstract:

For any of the following exception handling methods to work, the VCL must in some way become aware that an error condition exists. If a call to the Winsock does not return, or does not provide information to the TCustomWinSocket descendant that called it, then there is no mechanism to handle the condition. OnError exception handler.

Answer:

One method for trapping exception conditions in a descendant of TCustomWinSocket is to use an OnError exception handler. This method will only handle a limited set of conditions because the mechanism provided by the Winsock for event notification only reacts to a limited list of conditions.  To be notified of an exception condition within the Winsock, TCustomWinSocket registers user message CM_SocketMessage to be sent to the component, and the CMSocketMessage message handler raises an exception.  The message is registered with the Winsock by an API call to WSASyncSelect. WSASyncSelect is a request for event notification of socket read, writes, connect, close, and accept events.  If the exception condition is not read, write, connect, close or accept, or if the CM_SocketMessage is not sent by the Winsock for any reason, the error handler will not fire.

Usage:

procedure TChatForm.ClientSocketError(Sender: TObject;
  Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
  var ErrorCode: Integer);
const
  ErrorEvents: array[eeGeneral..eeAccept] of string = (
    'eeGeneral',
    'eeSend',
    'eeReceive',
    'eeConnect',
    'eeDisconnect',
    'eeAccept'
    );
begin
  ListBox1.Items.Add('ClientSocketError.   TErrorEvent: ' +
    ErrorEvents[ErrorEvent] + '    ErrorCode: ' + IntToStr(ErrorCode));
  ErrorCode := 0; // don't raise an exception
end;

Definition:

procedure TCustomWinSocket.CMSocketMessage(var Message: TCMSocketMessage);

  function CheckError: Boolean;
  var
    ErrorEvent: TErrorEvent;
    ErrorCode: Integer;
  begin
    if Message.SelectError <> 0 then
    begin
      Result := False;
      ErrorCode := Message.SelectError;
      case Message.SelectEvent of
        FD_CONNECT: ErrorEvent := eeConnect;
        FD_CLOSE: ErrorEvent := eeDisconnect;
        FD_READ: ErrorEvent := eeReceive;
        FD_WRITE: ErrorEvent := eeSend;
        FD_ACCEPT: ErrorEvent := eeAccept;
      else
        ErrorEvent := eeGeneral;
      end;
      Error(Self, ErrorEvent, ErrorCode);
      if ErrorCode <> 0 then
        raise ESocketError.CreateFmt(sASyncSocketError, [ErrorCode]);
    end
    else
      Result := True;
  end;

begin
  with Message do
    if CheckError then
      case SelectEvent of
        FD_CONNECT: Connect(Socket);
        FD_CLOSE: Disconnect(Socket);
        FD_READ: Read(Socket);
        FD_WRITE: Write(Socket);
        FD_ACCEPT: Accept(Socket);
      end;
end;

Object Pascal Exception Handling
You can also wrap a specific call in a try..except block or setting an application level exception handler.  For this to
work, the component must in some way become aware of the exception condition and an exception must be raised for the exception to be trapped here.

Example of Application Exception Handler:

TChatForm = class(TForm)
  {.
  . }
public
  procedure AppException(Sender: TObject; E: Exception);
end;
{.
. }
implementation
{.
. }

procedure TChatForm.AppException(Sender: TObject; E: Exception);
begin
  ListBox1.Items.Add('AppException: ' + E.Message);
end;

procedure TChatForm.FormCreate(Sender: TObject);
begin
  Application.OnException := AppException;
end;

Example of Try..Except block:

with ClientSocket do
try
  Active := True;
except
  on E: Exception do
    ListBox1.Items.Add('Try..except during open: ' + E.Message);
end;
end;

SocketErrorProc
For calls that use the CheckSocketResult function to check the result returned by WSAGetLastError, errors can be handled in a programmer defined function by setting the SocketErrorProc.

Usage:

interface
{.
. }
procedure MySocketError(ErrorCode: Integer);

implementation
{.
. }

procedure MySocketError(ErrorCode: Integer);
begin
  ShowMessage('MySocketError: ' + IntToStr(ErrorCode));
end;

procedure TChatForm.FormCreate(Sender: TObject);
begin
  SocketErrorProc := MySocketError;
end;

Defined:

function CheckSocketResult(ResultCode: Integer; const Op: string):
  Integer;
begin
  if ResultCode <> 0 then
  begin
    Result := WSAGetLastError;
    if Result <> WSAEWOULDBLOCK then
      if Assigned(SocketErrorProc) then
        SocketErrorProc(Result)
      else
        raise ESocketError.CreateFmt(sWindowsSocketError,
          [SysErrorMessage(Result), Result, Op]);
  end
  else
    Result := 0;
end;


Help Text for SocketErrorProc:

Unit ScktComp

SocketErrorProc handles error messages that are received from a Windows socket connection.

threadvar
  SocketErrorProc: procedure(ErrorCode: Integer);

Assign a value to SocketErrorProc to handle error messages from Windows socket API calls before the socket component raises an exception. Setting SocketErrorProc prevents the socket component from raising an exception.  SocketErrorProc is a thread-local variable. It only handles errors that arise from the Windows socket API calls made within a single execution thread.

2004. április 25., vasárnap

Search in MS Word file without MS Word


Problem/Question/Abstract:

How can i Search in MS Word File Without MS Word?

Answer:

You can use follow code in delphi and search in msword file without msword and office :

unit FindText;

interface

function FindTextInFile(const FileName, TextToFind: WideString): boolean;

implementation

uses ComObj, ActiveX, AxCtrls, SysUtils, Classes;

function FindTextInFile(const FileName, TextToFind: WideString): boolean;
var
  Root: IStorage;
  EnumStat: IEnumStatStg;
  Stat: TStatStg;
  iStm: IStream;
  Stream: TOleStream;
  DocTextString: WideString;
begin
  Result := False;

  if not FileExists(FileName) then
    Exit;

  // Check to see if it's a structured storage file
  if StgIsStorageFile(PWideChar(FileName)) <> S_OK then
    Exit;

  // Open the file
  OleCheck(StgOpenStorage(PWideChar(FileName), nil,
    STGM_READ or STGM_SHARE_EXCLUSIVE, nil, 0, Root));

  // Enumerate the storage and stream objects contained within this file
  OleCheck(Root.EnumElements(0, nil, 0, EnumStat));

  // Check all objects in the storage
  while EnumStat.Next(1, Stat, nil) = S_OK do

    // Is it a stream with Word data
    if Stat.pwcsName = 'WordDocument' then

      // Try to get the stream "WordDocument"
      if Succeeded(Root.OpenStream(Stat.pwcsName, nil,
        STGM_READ or STGM_SHARE_EXCLUSIVE, 0, iStm)) then
      begin
        Stream := TOleStream.Create(iStm);
        try
          if Stream.Size > 0 then
          begin
            // Move text data to string variable
            SetLength(DocTextString, Stream.Size);
            Stream.Position := 0;
            Stream.Read(pChar(DocTextString)^, Stream.Size);

            // Find a necessary text
            Result := (Pos(TextToFind, DocTextString) > 0);
          end;
        finally
          Stream.Free;
        end;
        Exit;
      end;
end;

end.

2004. április 24., szombat

Resolution independent applications


Problem/Question/Abstract:

Have you ever wondered how to display your forms and components always the same size no matter what the screen resolution is?

Answer:

You have to modify your project�s DPR file to acomplish that:

// Modify your projects code to achieve resolution independent
// applications. I have found that this trick only works for
// resolutions greater than the resolution you design the forms, for
// example if you design at 800x600 you can use your application at
// a resolution of 1024 x 768 or greater.
// However it won�t run fine at 640x480 (altough, nowadays I don�t
// kwonw many people with thatv resolution, so I think 800X600 is
// fine)

program TestResolution;

uses
  Forms,
  Dialogs,
  Classes,
  TypInfo,
  Windows,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.RES}

const
  //If form is designed in 800 x 600 mode
  ScreenWidth: LongInt = 800;
  ScreenHeight: LongInt = 600;

var
  vi_Counter1, vi_Counter2: Integer;
  NewFormWidth: Integer;

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.CreateForm(TForm2, Form2);
  NewFormWidth := GetSystemMetrics(0);

  with Application do
    for vi_Counter1 := 0 to ComponentCount - 1 do
    begin
      //Find all the Auto-create forms
      if Components[vi_Counter1] is TForm then
        with (Components[vi_Counter1] as TForm) do
        begin
          Scaled := True;
          if screen.Width <> ScreenWidth then
          begin
            Height := longint(Height) * longint(screen.Height) div
              ScreenHeight;
            Width := longint(Width) * longint(screen.Width) div
              ScreenWidth;
            ScaleBy(screen.Width, ScreenWidth);

            //Now Scale the Form�s component�s Font
            for vi_Counter2 := 0 to ControlCount - 1 do
              with Components[vi_Counter2] do
                //Use RTTI information to find for a Font property
                if GetPropInfo(ClassInfo, 'font') <> nil then
                  Font.Size := (NewFormWidth div ScreenWidth)
                    * font.Size;
          end;
        end;
    end;
  Application.Run;
end.

finally some aditional considerations:

You will have to scale every form create on the fly.
Use only TrueType fonts, not Bitmapped fonts to avoid problems.
Don�t set the Form�s Position property to poDesigned, when scalling it could be off the screen.
Don't change the PixelsPerInch property of the form.
Don't crowd controls on the form - leave at least 4 pixels between controls, so that a one pixel change in border  locations (due to scaling) won't show up as ugly overlapping  controls.

2004. április 23., péntek

Overcome a printing glitch in the EPSON 600 series driver


Problem/Question/Abstract:

How to overcome a printing glitch in the EPSON 600 series driver

Answer:

The drivers for the Epson 600-series seem to have a weird problem. If the Printer.Title property is empty (by default) the printer won't do anything. You can't get a single line of text out of the printer. So, to be sure your application prints, put the line:

{ ...}
Printer.Title := 'Some Text';
{ ...}

just before you call Printer.BeginDoc. You can replace the TitleString by any, non-empty, string you like.

2004. április 22., csütörtök

TQuery vs TTable components: why upgrade?


Problem/Question/Abstract:

Using TTable was absoltely normal in a near past, when the data resided locally, but is a common (and great) mistake in a modern, network environment.

Why should I use Query components instead of  Tables? Is the change in the existing projects worth the efforts?

Answer:

Until recently, many programmers were told to use extensively in their programs Table Datasets instead of queries.

In a single user environment, where all the data resides locally, this can be an easy and rapid solution for the basic needs, and most programs  seemed to function perfectly with this approach in the near past.

But a Network Environment is NOT a Single User Environment: let&#8217;s get a brief look to the differences between them.

First of all, data stored in tables shared on a network are often by far bigger then single user&#8217;s ones, as the data in an organization are of course bigger of the data of a single user: for example, I have seen Paradox tables of more then 80 Mbytes, truncated every 6 months because they were to big to be used with the BDE.
The BDE cannot simply manage huge quantities of data with local drivers (Paradox, dBase). The problem in this case is that using tables, you have to load in memory ALL the datas: if you&#8217;re lucky enaugh, and the programs are slow and take dozens of Mbytes of RAM. If you&#8217;re not so lucky, index corruption problems affect your databases many times every day, too, as a consequence of concurrent access on big physical tables.

In a second place, you haven&#8217;t control on the fields you need: think about a catalog.db in which there is also a big BLOB field with a TIFF boxshot of a product inside&#8230; if you use tables, you have to load it in memory even if you don&#8217;t need it, for example if you are an accountant or the CEO and you are interested only in the most important aspects of a catalog (SKU, DESC, PRICE).
Using Table components, which load in memory all the fields, can fill the RAM of the PCs, so it is a great cost for the company, too. BE ADVISED: adding field definitions to the table doesn&#8217;t solve the problem! The fields not defined are anyway loaded in the PC&#8217;s RAM and their datas flow on the network creating a great traffic jam on it!

In a 3rd place: not only you have to load in memory ALL THE FIELDS, even if you don&#8217;t want some of them; you also have to load in memory from a shared network ALL THE ROWS of the table; most middlewares (BDE included) need this even if you try to &#8220;filter&#8221; the table.

Finally: if you have to calculate avarage, min, max values for categories inside a database, you have to build yourself code using a Table component; if you use Query components instead of Tables, you can use the aggregated functions of the Queries, making the server work for you and simplifying radically the development process. Using TQueries, you can make advanced statistics in a snap.

Also, if you use a Database Server like Interbase or MS-SQL, the Server takes charge of filtering the result set, reducing the CPU, Bandwith and RAM requirements of the the client up to the 95% and giving the client program a quicker response to the user&#8217;s actions.

Despite the (little) effort needed to change existing projects, I suggest all the programmers, in particular those with Ttable components in their programmer&#8217;s DNA, to use Queries also in old projects and not only in  newer ones; this is by far the best solution to achieve better performance in your EXEs.

Remember: using Queries can lead to incredible performance gains, both in CPU, Bandwith and Ram occupation on older machines, increasing their productive life and reducing costs, so the great savings achieved are by far worth the (small) effort needed.