The Road to Delphi

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.


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.


Leave a comment

Calculate the SHA1 hash of a file, using Delphi Prism

The next code show how calculate the SHA1 hash of a file, using Delphi Prism (Oxygene)

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;


1 Comment

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

The next code show how detect if an antivirus software is installed in Windows using Delphi Prism (Oxygene) and the WMI.

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;