The Road to Delphi – a Blog about programming

Delphi – Free Pascal – Oxygene


13 Comments

Detecting Wifi Networks Using Delphi Prism.

The next code uses the Managed Wifi API, The library uses the Native Wifi API, available since Windows Vista and Windows XP SP2 (in a limited fashion, and only after applying a hotfix provided in KB article 918997). Older versions of Windows are not supported.

Before to compile the code you need to download the library from this location. Build the project “ManagedWifi.csproj” and then add the reference to the source code listed below.
namespace DelphiPrismWifidetection;
//Author : Rodrigo Ruz. 2009-09-29
//Shine Your crazy Diamond.

interface

uses
NativeWifi,//You must add the reference to the library ManagedWifi.dll
System.Text;

type
  ConsoleApp = class
  private
    class method GetStringForSSID(ssid : Wlan.Dot11Ssid ) : string;
    class method GetStringFornumberOfBssids (numberOfBssids : Int32 ) : string;
  public
    class method Main;
  end;

implementation

class method ConsoleApp.GetStringForSSID(ssid : Wlan.Dot11Ssid ) : string;
begin
    Result:= Encoding.ASCII.GetString( ssid.SSID, 0, Int32( ssid.SSIDLength) );
end;

class method ConsoleApp.GetStringFornumberOfBssids (numberOfBssids : Int32 ) : string;
begin
  case numberOfBssids of
  1: Result:='infrastructure';
  2: Result:='independent';
  3: Result:='any';
  else
  Result:='Unknow';
  end; // case
end;

class method ConsoleApp.Main;
begin
            var client : WlanClient  := new WlanClient();
            for each  wlanIface in client.Interfaces  do
            begin
                var networks : Array of  Wlan.WlanAvailableNetwork  := wlanIface.GetAvailableNetworkList(NativeWifi.Wlan.WlanGetAvailableNetworkFlags.IncludeAllAdhocProfiles);
                for each  network in networks  do
                begin
                    // for more info goto http://msdn.microsoft.com/en-us/library/ms707403%28VS.85%29.aspx
                    Console.WriteLine( "┌---------------------------------------------------------------¬");
                    Console.WriteLine( "|Network Detected      {0,-40} |", GetStringForSSID(network.dot11Ssid));
                    Console.WriteLine( "├---------------------------------------------------------------┤");
                    Console.WriteLine( "| CipherAlgorithm      {0,-40} |", network.dot11DefaultCipherAlgorithm.ToString());
                    Console.WriteLine( "| DefaultAuthAlgorithm {0,-40} |", network.dot11DefaultAuthAlgorithm.ToString());
                    Console.WriteLine( "| dot11Ssid            {0,-40} |", network.dot11Ssid.ToString());
                    Console.WriteLine( "| networkConnectable   {0,-40} |", network.networkConnectable.ToString());
                    if not network.networkConnectable then
                    Console.WriteLine( "| NotConnectableReason {0,-40} |", network.wlanNotConnectableReason.ToString());
                    Console.WriteLine( "| morePhyTypes         {0,-40} |", network.morePhyTypes.ToString());
                    Console.WriteLine( "| (BSS) network type   {0,-40} |", GetStringFornumberOfBssids(network.numberOfBssids));
                    Console.WriteLine( "| profileName          {0,-40} |", network.profileName.ToString());
                    Console.WriteLine( "| securityEnabled      {0,-40} |", network.securityEnabled.ToString());
                    Console.WriteLine( "| wlanSignalQuality    {0,-40} |", network.wlanSignalQuality.ToString());
                    Console.WriteLine( "└---------------------------------------------------------------┘");
                end;

            end;
            Console.ReadLine();
end;

end.

and the result is

Update

Download the full source code from here

Bye.


1 Comment

The Return of TurboPower.

Nick Hodges has posted on his blog which is the new project Administrator (tpfsadmin) of the TurboPower Components. This is great news, hopefully the components are updated to the latest versions of Delphi.

Here is the complete list of project TurboPower

TurboPower Async Professional
Async Professional is a comprehensive communications toolkit for Borland Delphi, C++Builder, & ActiveX environments. It provides direct access to serial ports, TAPI, and the Microsoft Speech API. It supports faxing, terminal emulation, VOIP, & more.

TurboPower Orpheus
Orpheus is an award-winning UI toolkit for Borland Delphi & C++Builder. It contains over 120 components covering everything from data entry to calendars and clocks. Other noteworthy components include an Object Inspector, LookOut bar, & report views.

TurboPower FlashFiler
FlashFiler is a client-server database for Borland Delphi & C++Builder. It features a component-based architecture & the server engine can be embedded in your applications. FlashFiler is easy to configure, performs well, & includes SQL support.

TurboPower Internet Professional
Internet Professional is a set of VCL components providing Internet connectivity for Borland Delphi & C++Builder. iPRO includes POP3, SMTP, NNTP, FTP, HTTP, Instant Messaging, & HTML viewer components, as well as components for low-level socket access.

TurboPower Abbrevia
Abbrevia is a compression toolkit for Embarcadero Delphi, C++Builder, & Kylix. It supports PKZIP 4, Microsoft CAB, TAR, & gzip formats & the creation of self-extracting archives. It includes visual components that simplify the manipulation of ZIP files.

TurboPower SysTools
SysTools is a library of utility routines & classes for Borland Delphi, C++Builder, & environments that support COM. It includes 1-D & 2-D bar codes, sorting, money routines, logging, high-precision math, a run-time math expression analyzer, & much more.

TurboPower LockBox
LockBox is a cross-platform toolkit for data encryption. It contains routines & components for use with Borland Delphi, C++Builder, & Kylix. It provides support for Blowfish, RSA, MD5, SHA-1, DES, triple- DES, Rijndael, & digital signing of messages.

TurboPower OnGuard
OnGuard is a library to create demo versions of your Borland Delphi & C++Builder applications. Create demo versions that are time-limited, feature-limited, limited to a certain number of uses, or limited to a certain # of concurrent network users.

TurboPower Essentials
Essentials contains 13 native VCL controls for Borland Delphi & C++Builder. The controls include drop-down calendars & calculators, roll-up dialogs, 3-D labels, tiled backgrounds, scrolling messages, menu buttons, and more.

TurboPower OfficePartner
OfficePartner is the easy way to integrate your projects with Microsoft Office, the worlds leading business productivity software. With OfficePartner you can access COM services in Microsoft Office with easy to use VCL components.

TurboPower Visual PlanIt
Visual PlanIt is a set of synchronized, data-aware components for adding time, task, & contact management capabilities to applications written in Borland Delphi & C++Builder. Get that Outlook look & feel without the hassle.

TurboPower ShellShock
ShellShock provides a set of components that let you customize applications with the functionality available in the Windows Shell & Windows Explorer, all without writing code. The components are written in native VCL for Borland Delphi & C++Builder.

TurboPower B-Tree Filer
B-Tree Filer is a fast library of file-based database routines for Borland Turbo Pascal & Delphi. B-Tree Filer supports stand-alone programs or those running on Microsoft-compatible networks including Novell Netware.

TurboPower XML Partner
XMLPartner helps add the power of XML to Borland Delphi, C++ Builder, and Kylix projects through native, easy to use VCL and CLX components. These powerful components simplify the process of creating, modifying, and parsing XML data documents.

TurboPower Async Professional CLX
Async Professional CLX is a comprehensive communications toolkit for Borland Kylix. It provides direct access to serial ports, and supports terminal emulation, file transfer protocols, & much more.

TurboPower String Resource Manager
The TurboPower String Resource Manger is a tool for building string resource libraries in Borland Delphi. It prevents string resource clashes and simplifies the translation of the string resources.

TurboPower SysTools for Kylix
SysTools for Kylix is a library of utility routines & algorithms for Borland Kylix. Among other things, it supports 1-Dimensional bar codes, date time and string routines, sorting, a regular expression engine, & a run-time math expression analyzer.

TurboPower OnGuard CLX
A port of TurboPower OnGuard to CLX and Linux platform.

TurboPower Object Professional
Object Professional is a library of over 2000 methods and procedures for writing sophisticated DOS text mode applications with Turbo Pascal 5.5, 6.0, 7.0, or Borland Pascal 7.

Bye.


Leave a comment

Enumerating All Network resources using Delphi Prism.

The next code uses the windows library mrp.dll (mpr.dll is a module containing functions used to handle communication between the Windows operating system and the installed network providers) and call these functions :

  • WNetOpenEnum (starts an enumeration of network resources or existing connections)
namespace DelphiPrismNetworkScan;
//Author : Rodrigo Ruz. 2009-09-28
//Shine Your crazy Diamond.

interface

uses
System,
System.Runtime.InteropServices;

type
        RESOURCE_SCOPE_NET= enum
        (
        RESOURCE_CONNECTED  = $00000001,
        RESOURCE_GLOBALNET  = $00000002,
        RESOURCE_REMEMBERED = $00000003,
        RESOURCE_RECENT     = $00000004,
        RESOURCE_CONTEXT    = $00000005
        );

        RESOURCE_TYPE_NET = enum
        (
        RESOURCETYPE_ANY      = $00000000,
        RESOURCETYPE_DISK     = $00000001,
        RESOURCETYPE_PRINT    = $00000002,
        RESOURCETYPE_RESERVED = $00000008
        );

        RESOURCE_USAGE_NET = enum
        (
        RESOURCEUSAGE_CONNECTABLE   =$00000001,
        RESOURCEUSAGE_CONTAINER     =$00000002,
        RESOURCEUSAGE_NOLOCALDEVICE =$00000004,
        RESOURCEUSAGE_SIBLING       =$00000008,
        RESOURCEUSAGE_ATTACHED      =$00000010,
        RESOURCEUSAGE_ALL           =(RESOURCEUSAGE_CONNECTABLE OR RESOURCEUSAGE_CONTAINER OR RESOURCEUSAGE_ATTACHED)
        );

        RESOURCE_DISPLAYTYPE_NET = enum
        (
          RESOURCEDISPLAYTYPE_GENERIC       = $00000000,
          RESOURCEDISPLAYTYPE_DOMAIN        = $00000001,
          RESOURCEDISPLAYTYPE_SERVER        = $00000002,
          RESOURCEDISPLAYTYPE_SHARE         = $00000003,
          RESOURCEDISPLAYTYPE_FILE          = $00000004,
          RESOURCEDISPLAYTYPE_GROUP         = $00000005,
          RESOURCEDISPLAYTYPE_NETWORK       = $00000006,
          RESOURCEDISPLAYTYPE_ROOT          = $00000007,
          RESOURCEDISPLAYTYPE_SHAREADMIN    = $00000008,
          RESOURCEDISPLAYTYPE_DIRECTORY     = $00000009,
          RESOURCEDISPLAYTYPE_TREE          = $0000000A,
          RESOURCEDISPLAYTYPE_NDSCONTAINER  = $0000000B
        );

  NETRESOURCE  = public record
    var     dwScope         : RESOURCE_SCOPE_NET;
    var     dwType          : RESOURCE_TYPE_NET;
    var     dwDisplayType   : RESOURCE_DISPLAYTYPE_NET;
    var     dwUsage         : RESOURCE_USAGE_NET;
    var     [MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPTStr)]  lpLocalName : String;
    var     [MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPTStr)]  lpRemoteName: String;
    var     [MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPTStr)]  lpComment   : String;
    var     [MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPTStr)]  lpProvider  : String;
  end;

  ConsoleApp = class
  public
        [DllImport("mpr.dll", CharSet:=CharSet.Auto)]
        class method WNetEnumResource(hEnum: IntPtr; var lpcCount: Integer; lpBuffer: IntPtr; var lpBufferSize: Integer): Integer;external;
        [DllImport("mpr.dll", CharSet:=CharSet.Auto)]
        class method WNetOpenEnum( dwScope: RESOURCE_SCOPE_NET; dwType: RESOURCE_TYPE_NET; dwUsage: RESOURCE_USAGE_NET; [MarshalAs(UnmanagedType.AsAny)]  [&In()]  lpNetResource: Object; out lphEnum: IntPtr): Integer;external;
        [DllImport("mpr.dll", CharSet:=CharSet.Auto)]
        class method WNetCloseEnum(hEnum: IntPtr): Integer;external;
        class method InitScan(Dummy: Object);
        class method Main;
  end;

implementation

class method ConsoleApp.InitScan(Dummy: Object);
  var
  iRet     : Integer;
  ptrHandle: IntPtr  := new IntPtr();
  entries  : Integer;
  buffer   : Integer := 16384;
  nr       : NETRESOURCE;
  ptrBuffer: IntPtr:=Marshal.AllocHGlobal(buffer);
begin
try
    //Init the enumeration , you can change the paremeters to filter.
    iRet := WNetOpenEnum(RESOURCE_SCOPE_NET.RESOURCE_GLOBALNET, RESOURCE_TYPE_NET.RESOURCETYPE_ANY, RESOURCE_USAGE_NET.RESOURCEUSAGE_ALL, Dummy, out ptrHandle);
    if iRet <> 0 then
    begin
      exit;
    end;

        while true do //infinite loop
        Begin
                entries := -1;
                buffer  := 16384;
                iRet    := WNetEnumResource(ptrHandle, var entries, ptrBuffer, var buffer); //Load the next resource

                if ((iRet <> 0)) OR ((entries < 1)) then //if fails or non exist any entries then exit
                begin
                Break;
                end;

            var ptr: Int32 := ptrBuffer.ToInt32();
            var i  : Int32 :=0;
            while i< entries do
            Begin
                nr := NETRESOURCE(Marshal.PtrToStructure(new IntPtr(ptr), typeOf(NETRESOURCE)));
                if RESOURCE_USAGE_NET.RESOURCEUSAGE_CONTAINER = (nr.dwUsage and RESOURCE_USAGE_NET.RESOURCEUSAGE_CONTAINER) then //if is a contanier the function scan the resource again.
                begin
                  InitScan(nr); //recursive call to the function
                end;

                ptr :=ptr+ Marshal.SizeOf( nr );
                Console.WriteLine("{0}", nr.dwDisplayType.ToString());
                Console.WriteLine(" Type       ={0}", nr.dwType.ToString());
                Console.WriteLine(" Usage      ={0}", nr.dwUsage.ToString());
                Console.WriteLine(" Scope      ={0}", nr.dwScope.ToString());
                Console.WriteLine(" LocalName  ={0}", nr.lpLocalName);
                Console.WriteLine(" RemoteName ={0}", nr.lpRemoteName);
                Console.WriteLine(" Description={0}", nr.lpComment);
                Console.WriteLine(" Provider   ={0}", nr.lpProvider);
                Console.WriteLine();

                inc(i);
            End;

        End;

  except
    on e: Exception do
    begin
      Console.WriteLine('Error ** ' + e.Message + ' ** Trace ' + e.StackTrace)
    end;
end;
end;

class method ConsoleApp.Main;
begin
      Console.WriteLine('Scannig Network....Wait a moment , be patient please');
      Console.WriteLine();
      InitScan(nil);
      Console.WriteLine('Scan Network Finish');
      Console.Read();
end;

end.

When you run this code you’ll get something like this

Bye.


2 Comments

Getting the parent process filename of a PID, using Delphi.

uses
  Psapi,
  Windows,
  tlhelp32,
  SysUtils;

function GetParentProcessFileName(PID : DWORD): String;
var                               
  HandleSnapShot      : THandle;
  EntryParentProc     : TProcessEntry32;
  HandleParentProc    : THandle;
  ParentPID           : DWORD;
  ParentProcessFound  : Boolean;
  ParentProcPath      : PChar;
begin
  ParentProcessFound := False;
  HandleSnapShot     := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  GetMem(ParentProcPath, MAX_PATH);
  try
    if HandleSnapShot <> INVALID_HANDLE_VALUE then
    begin
      EntryParentProc.dwSize := SizeOf(EntryParentProc);
      if Process32First(HandleSnapShot, EntryParentProc) then
      begin
        repeat
          if EntryParentProc.th32ProcessID = PID then
          begin
            ParentPID  := EntryParentProc.th32ParentProcessID;
            HandleParentProc  := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False,ParentPID);
            ParentProcessFound:= HandleParentProc <> 0;
            if ParentProcessFound then
            begin
                GetModuleFileNameEx(HandleParentProc, 0, PChar(ParentProcPath), MAX_PATH);
                ParentProcPath := PChar(ParentProcPath);
                CloseHandle(HandleParentProc);
            end;
            break;
          end;
        until not Process32Next(HandleSnapShot, EntryParentProc);
      end;
      CloseHandle(HandleSnapShot);
    end;

    if ParentProcessFound then
      Result := ParentProcPath
    else
      Result := '';
  finally
      FreeMem(ParentProcPath);
  end;
end;


Leave a comment

Update 1 for RAD Studio 2010

Embarcadero has just released Update #1 for the Delphi 2010 and C++Builder 2010 personalities of RAD Studio 2010.

RAD Studio 2010 Update 1 includes the following fixes:

  • The product now works properly with All-Access licenses.
  • Several important licensing-related fixes are included that resolve issues with network licensing and ensure that any future updates will work properly.



Leave a comment

Calculate sha1 hash of a file, using Delphi Prism

uses
    System.IO,
    System.Security,
    System.Security.Cryptography;

function CalcSHA1HashCode(oFile:String) : String;
var
sh1Provider : SHA1CryptoServiceProvider;
st          : FileStream;
hash        : Array of Byte;
begin
st := New FileStream(oFile,System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.FileShare.ReadWrite);
try
  sh1Provider:=New SHA1CryptoServiceProvider();
  hash       :=sh1Provider.ComputeHash(st);
  Result     :=Convert.ToBase64String(hash);
finally
   st.Close;
end;
end;


Leave a comment

Using Delphi, how to check if two Bitmaps are the same?

In response to this question I wrote this code.

function IsSameBitmapUsingScanLine(Bitmap1, Bitmap2: TBitmap): Boolean;
var
 i           : Integer;
 ScanBytes   : Integer;
begin
  Result:= (Bitmap1<>nil) and (Bitmap2<>nil);
  if not Result then exit;
  Result:=(bitmap1.Width=bitmap2.Width) and (bitmap1.Height=bitmap2.Height) and (bitmap1.PixelFormat=bitmap2.PixelFormat) ;

  if not Result then exit;

  ScanBytes := Abs(Integer(Bitmap1.Scanline[1]) - Integer(Bitmap1.Scanline[0]));
  for i:=0 to Bitmap1.Height-1 do
  begin
    Result:=CompareMem(Bitmap1.ScanLine[i],Bitmap2.ScanLine[i],ScanBytes);
    if not Result then exit;
  end;

end;


Leave a comment

Detect if an antivirus software is installed in Windows using Delphi Prism

uses
System,
System.Management,
System.Text;

type
  ConsoleApp = class
    private
      class method AntivirusInstalled() : Boolean;
    public
      class method Main;
  end;

implementation

class method ConsoleApp.Main;
begin
  var returnCode : Boolean := AntivirusInstalled();
  Console.WriteLine("Antivirus Installed " + returnCode.ToString());
  Console.WriteLine();
  Console.Read();
end;

class method ConsoleApp.AntivirusInstalled() : Boolean;
begin
   var wmipathstr :string  := "\\" + Environment.MachineName + "\root\SecurityCenter";//since windows vista you must use the SecurityCenter2 namespace
    try
       var searcher  : ManagementObjectSearcher    := New ManagementObjectSearcher(wmipathstr, "SELECT * FROM AntivirusProduct");
       var instances : ManagementObjectCollection  := searcher.Get();
       result:=(instances.Count > 0);
    except on E: Exception do
      begin
        Console.WriteLine(e.Message);
        Result:=False;
      end;
    end;
end;
Follow

Get every new post delivered to your Inbox.

Join 586 other followers