GithubHelp home page GithubHelp logo

rruz / delphi-wmi-class-generator Goto Github PK

View Code? Open in Web Editor NEW
57.0 8.0 21.0 8.42 MB

Creates Object Pascal classes to access the WMI

Home Page: https://theroadtodelphi.wordpress.com/

Pascal 99.34% Inno Setup 0.04% PHP 0.62%
wmi delphi

delphi-wmi-class-generator's Introduction

The Delphi Wmi Class Generator is a application which creates full documented Object Pascal classes to access the WMI (Windows Management Instrumentation).

Features

  • The code generated is compatible Delphi 7, 2005, BDS/Turbo 2006 and RAD Studio 2007-2010, XE-XE7 and the Free Pascal Compiler 2.2.4 (win32)

  • Create full documented classes compatible with the help insight feature, available since Delphi 2005.

Note : the language of the description of the methods, parameters and properties depends on of the language of the windows where you generate the units.

  • Create helper functions to retrieve the description of the returned values for the properties and functions.

Limitations

The application generate ready to use code in a 99% approx. of the cases, however some WMI classes exposes meta-data in a incorrect format or the structure of the meta-data is not compatible with the algorithm used to create the object pascal code, in such cases you must patch the code manually.

On this page you can find the classes with problems. another option is download the generated patched classes directly from the repository,

Internals

The tool extract and parse the meta-data (properties, methods, qualifiers, valid values and descriptions) stored in the WMI class, to recreate a Object Pascal compatible class.

Each Object pascal class generated by the application descend from the base class TWmiClass, this class encapsulate the access to the wmi, convert the values (OleVariant) returned by the calling class to native types, and store in a internal collection (buffer) the values of the properties and the address of the instances.

the TWmiClass class can be compiled in two modes.

Using the Microsoft WMI Scripting V1.2 Library

This wrapper (WbemScripting_TLB) is generated by the delphi compiler, this option improve the initial access to the WMI (this option is not compatible with FPC). if you use this mode you must include ion your projects the WbemScripting_TLB unit.

Using late-binding

This option is useful when you need generate small exe files. the performance is a little bit more slow in the initial execution.

To choose between these 2 modes you must comment or uncomment in the uWmiDelphiClass unit the following line

{$DEFINE WbemScripting_TLB}

Usage

In the main window of the application you must select the namespace and class to generate (by default all the classes of the WMI namespace are selected) and press the "Generate units" button, then the tool will be create a folder in the location of the exe with the name of the namespace and inside of this folder will be created a test console project, a copy of the uWmiDelphiClass.pas file and the selected classes. Each class is stored in a separate unit with the name formed by "u" letter plus the name of the Wmi class, example the unit name for the Win32_BIOS class will be uWin32_BIOS.pas.

Demos

In the source repository you can find a set of demos of the usage of the generated classes.

check this very simple console application, which uses the Win32_BaseBoard WMI class.

program TestWin32_BaseBoard;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  uWin32_BaseBoard in '..\..\root_CIMV2\uWin32_BaseBoard.pas', 
  uWmiDelphiClass in '..\..\uWmiDelphiClass.pas'; //the base class

procedure TestBaseBoard;
var
  BaseBoard : TWin32_BaseBoard;
begin
  BaseBoard:=TWin32_BaseBoard.Create;
  try
    Writeln('Base Board Info');
    Writeln('---------------');
    Writeln('Manufacturer '+BaseBoard.Manufacturer);
    Writeln('Model        '+BaseBoard.Model);
    Writeln('SKU          '+BaseBoard.SKU);
    Writeln('SerialNumber '+BaseBoard.SerialNumber);
    Writeln('PartNumber   '+BaseBoard.PartNumber);
    Writeln('Tag          '+BaseBoard.Tag);
    Readln;
  finally
    BaseBoard.Free;
  end;
end;

begin
  try
    TestBaseBoard;
  except
    on E:Exception do
    begin
      Writeln(E.Classname, ': ', E.Message);
      Readln;
    end;
  end;
end.

This tool was compiled using Delphi XE.

Sample source code

Source code sample created by the application for the Win32_Share WMI class.


/// <summary>
/// Unit generated using the Delphi Wmi class generator tool, Copyright Rodrigo Ruz V. 2010
/// Application version 0.1.0.113
/// WMI version 7600.16385
/// Creation Date 23-12-2010 22:39:55
/// Namespace root\CIMV2 Class Win32_Share
/// MSDN info about this class http://msdn2.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/Win32_Share.asp
/// </summary>

{$IFDEF FPC}
 {$MODE DELPHI} {$H+}
 {$DEFINE OLD_DELPHI}
{$ENDIF}

unit uWin32_Share;

interface

uses
 Classes,
 Activex,
 Variants,
 ComObj,
 uWmiDelphiClass;

type
{$IFDEF FPC}
  Cardinal=Longint;
  Int64=Integer;
  Word=Longint;
{$ENDIF}
{$IFNDEF FPC}
  {$IF CompilerVersion <= 15}
    {$DEFINE OLD_DELPHI}
  {$IFEND}
{$ENDIF}
  {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
  /// <summary>
  /// The Win32_Share class represents a shared resource on a Win32 system. This may be a disk drive, printer, interprocess communication, or other shareable device.
  /// Example: C:\PUBLIC.
  /// </summary>
  {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
  TWin32_Share=class(TWmiClass)
  private
    FAccessMask                         : Cardinal;
    FAllowMaximum                       : Boolean;
    FCaption                            : String;
    FDescription                        : String;
    FInstallDate                        : TDateTime;
    FMaximumAllowed                     : Cardinal;
    FName                               : String;
    FPath                               : String;
    FStatus                             : String;
    FType                               : Cardinal;
  public
   constructor Create(LoadWmiData : boolean=True); overload;
   destructor Destroy;Override;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// This property has been deprecated in favour of the GetAccessMask method of this 
   /// class due to the expense of calling GetEffectiveRightsFromAcl. The value will 
   /// be set to NULL
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property AccessMask : Cardinal read FAccessMask;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The AllowMaximum property indicates whether the number of concurrent users for this resource has been limited.
   /// Values: TRUE or FALSE. A value of TRUE indicates the number of concurrent users of this resource has not been limited and the value in the MaximumAllowed property is ignored.
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property AllowMaximum : Boolean read FAllowMaximum;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The Caption property is a short textual description (one-line string) of the 
   /// object.
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property Caption : String read FCaption;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The Description property provides a textual description of the object. 
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property Description : String read FDescription;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The InstallDate property is datetime value indicating when the object was 
   /// installed. A lack of a value does not indicate that the object is not installed.
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property InstallDate : TDateTime read FInstallDate;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The MaximumAllowed property indicates the limit on the maximum number of users allowed to use this resource concurrently. The value is only valid if the AllowMaximum member set to FALSE 
   /// Example: 10.
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property MaximumAllowed : Cardinal read FMaximumAllowed;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The Name property indicates the alias given to a path set up as a share on a  Win32 system.
   /// Example: public.
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property Name : String read FName;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The Path property indicates the local path of the Win32 share.
   /// Example: C:\Program Files
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property Path : String read FPath;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The Status property is a string indicating the current status of the object. 
   /// Various operational and non-operational statuses can be defined. Operational 
   /// statuses are "OK", "Degraded" and "Pred Fail". "Pred Fail" indicates that an 
   /// element may be functioning properly but predicting a failure in the near 
   /// future. An example is a SMART-enabled hard drive. Non-operational statuses can 
   /// also be specified. These are "Error", "Starting", "Stopping" and "Service". The 
   /// latter, "Service", could apply during mirror-resilvering of a disk, reload of a 
   /// user permissions list, or other administrative work. Not all such work is on-
   /// line, yet the managed element is neither "OK" nor in one of the other states.
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property Status : String read FStatus;
   {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
   /// <summary>
   /// The Type property specifies the type of resource being shared. Types include 
   /// disk drives, print queues, interprocess communications (IPC), and general 
   /// devices.
   /// </summary>
   {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
   property {$IFDEF OLD_DELPHI}_Type{$ELSE}&Type{$ENDIF} : Cardinal read FType;
   function Create(const Access : OleVariant;const Description : String;const MaximumAllowed : Cardinal;const Name : String;const Password : String;const Path : String;const {$IFDEF OLD_DELPHI}_Type{$ELSE}&Type{$ENDIF} : Cardinal): Integer;overload;
   function SetShareInfo(const Access : OleVariant;const Description : String;const MaximumAllowed : Cardinal): Integer;
   function GetAccessMask: Integer;
   function Delete: Integer;
   procedure SetCollectionIndex(Index : Integer); override;
  end;


  {$IFDEF UNDEF}{$REGION 'Documentation'}{$ENDIF}
  /// <summary>
  /// Return the description for the value of the property TWin32_Share.Type
  /// </summary>
  {$IFDEF UNDEF}{$ENDREGION}{$ENDIF}
  function GetTypeAsString(const APropValue:Cardinal) : string;

implementation


function GetTypeAsString(const APropValue:Cardinal) : string;
begin
Result:='';
  case APropValue of
    0 : Result:='Disk Drive';
    1 : Result:='Print Queue';
    2 : Result:='Device';
    3 : Result:='IPC';
    2147483648 : Result:='Disk Drive Admin';
    2147483649 : Result:='Print Queue Admin';
    2147483650 : Result:='Device Admin';
    2147483651 : Result:='IPC Admin';
  end;
end;

{TWin32_Share}

constructor TWin32_Share.Create(LoadWmiData : boolean=True);
begin
  inherited Create(LoadWmiData,'root\CIMV2','Win32_Share');
end;

destructor TWin32_Share.Destroy;
begin
  inherited;
end;

procedure TWin32_Share.SetCollectionIndex(Index : Integer);
begin
  if (Index>=0) and (Index<=FWmiCollection.Count-1) and (FWmiCollectionIndex<>Index) then
  begin
    FWmiCollectionIndex:=Index;
    FAccessMask          := VarCardinalNull(inherited Value['AccessMask']);
    FAllowMaximum        := VarBoolNull(inherited Value['AllowMaximum']);
    FCaption             := VarStrNull(inherited Value['Caption']);
    FDescription         := VarStrNull(inherited Value['Description']);
    FInstallDate         := VarDateTimeNull(inherited Value['InstallDate']);
    FMaximumAllowed      := VarCardinalNull(inherited Value['MaximumAllowed']);
    FName                := VarStrNull(inherited Value['Name']);
    FPath                := VarStrNull(inherited Value['Path']);
    FStatus              := VarStrNull(inherited Value['Status']);
    FType                := VarCardinalNull(inherited Value['Type']);
  end;
end;


//static, OutParams=1, InParams>0
function TWin32_Share.Create(const Access : OleVariant;const Description : String;const MaximumAllowed : Cardinal;const Name : String;const Password : String;const Path : String;const {$IFDEF OLD_DELPHI}_Type{$ELSE}&Type{$ENDIF} : Cardinal): Integer;
var
  objInParams                : OleVariant;
  objOutParams               : OleVariant;
begin
  objInParams                 := GetInstanceOf.Methods_.Item('Create').InParameters.SpawnInstance_();
  objInParams.Properties_.Item('Access').Value  := Access;
  objInParams.Properties_.Item('Description').Value  := Description;
  objInParams.Properties_.Item('MaximumAllowed').Value  := MaximumAllowed;
  objInParams.Properties_.Item('Name').Value  := Name;
  objInParams.Properties_.Item('Password').Value  := Password;
  objInParams.Properties_.Item('Path').Value  := Path;
  objInParams.Properties_.Item('Type').Value  := {$IFDEF OLD_DELPHI}_Type{$ELSE}&Type{$ENDIF};
  objOutParams                := WMIService.ExecMethod(WmiClass, 'Create', objInParams, 0, GetNullValue);
  Result := VarIntegerNull(objOutParams.ReturnValue);
end;


//not static, OutParams=1, InParams>0
function TWin32_Share.SetShareInfo(const Access : OleVariant;const Description : String;const MaximumAllowed : Cardinal): Integer;
var
  ReturnValue : OleVariant;
begin
  ReturnValue := GetInstanceOf.SetShareInfo(Access,Description,MaximumAllowed);
  Result      := VarIntegerNull(ReturnValue);
end;


//not static, OutParams=1, InParams=0
function TWin32_Share.GetAccessMask: integer;
var
  ReturnValue : OleVariant;
begin
  ReturnValue := GetInstanceOf.GetAccessMask;
  Result      := VarIntegerNull(ReturnValue);
end;

//not static, OutParams=1, InParams=0
function TWin32_Share.Delete: integer;
var
  ReturnValue : OleVariant;
begin
  ReturnValue := GetInstanceOf.Delete;
  Result      := VarIntegerNull(ReturnValue);
end;
end.

Looking for the installer? Check the Release Area

delphi-wmi-class-generator's People

Contributors

rruz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

delphi-wmi-class-generator's Issues

Help...usage?

Hi

Just playing around and trying to work out how to call and use

In my program, I have delclared the uses and so on and started with :

var
PhysDiskSet : TSystemConfig_V2_PhyDisk;
tmpVal1 : widestring;
begin;
PhysDiskSet := TSystemConfig_V2_PhyDisk.Create;
PhysDiskSet.SetCollectionIndex(0); \ I assume 0 is for PhysicalDisk0, 1 for PhysicalDisk 2 etc?
tmpVal1 := IntToStr(PhysDiskSet.PartitionCount);
ShowMessage(tmpVal1);

Zero is always returned. Tried the same with SectorsPerTrack and a few others. Always returns zero. So I am obviously not using the class correctly? Can you explain or give a demo of how to call the procedures in uSystemConfig_V2_PhyDisk.pas?

Several identifiers not found in uWmiDelphiClass.pas

RRUZ
Just tried out the Object Pascal WMI Class Generator for use with Lazarus and Freepascal. Absolutely amazing stuff!! Really very impressed with it - many thanks for sharing it.

I have an issue that I am not sure if the problem is me or the code. I am trying to use the generated units with Lazarus 1.4.0 and FPC 2.6.4 on Windows 7 Pro, 64-bit.

I am trying to use the units 'SystemConfig_V2_PhyDisk' and 'SystemConfig_V2_LogDisk'. I have created the units using the generator and copied the pas files for them, and the uWmiDelphiClass.pas file, to my project folder.

When I try TSystemConfig_V2_PhyDisk.Create in my project and compile, the compiler reports some problems:

uWmiDelphiClass.pas(1163,26) Error: Identifier not found "FWMIService" which is:

{$IFDEF FPC}
WQL := Format('SELECT * FROM %s',[FWmiClass]);
objWbemObjectSet := FWMIService.ExecQuery( WQL,'WQL',0);
oEnum := IUnknown(objWbemObjectSet._NewEnum) as IEnumVariant;
{$ELSE}

untitled

FMIService is first defined on line 97 as part of an IFDEF for WbemScripting_TLB and are greyed out and then again on line 101 as an OLEVariant, and is not greyed out. If I comment out the IFDEF it then cannot find ISWbemLocator. That is first defined on line 194 and is also greyed out as a result of the IFDEF {$IFDEF WbemScripting_TLB} .

I might be wrong but I think one or two of the declaratiosn needed for FPC need to be moved to the FPC IFDEF delcarations? But I know you know what you're doing so I suspect I need to do something different? Or is this an error with the units?

Could you direct me as to how to fix properly without me moving things about in an almost random fashion!?

LoadWmiData; does not exist

D10.2.3
Trying to compile your demo
procedure TFrmMain.Refresh;
begin
FWin32_Process.LoadWmiData;
FillListProcesses(FWin32_Process);

FWin32_Service.LoadWmiData;
FillListServices(FWin32_Service);
end;

LoadWmiData; does not exist

Possibility to share the WMI connection between the objects generated by the tool [Feature Request]

What steps will reproduce the problem?
- Create the units with WMI Class Generator (eg. uWin32_OperatingSystem, 
uWin32_LocalTime)
- Trying to retrieve from remote PC the WMIdata using:

  objWMIOperatingSystem := TWin32_OperatingSystem.Create(false);
  objWMILocalTime := TWin32_LocalTime.Create(false);

  objWMIOperatingSystem.WmiServer := sWMIremotePC;
  objWMIOperatingSystem.WmiUser := sWMIuser;
  objWMIOperatingSystem.WmiPass := sWMIpass;
  objWMIOperatingSystem.LoadWmiData;

  objWMILocalTime.WmiServer := sWMIRemotePC;
  objWMILocalTime.WmiUser := sWMIuser;
  objWMILocalTime.WmiPass := sWMIpass;
  objWMILocalTime.LoadWmiData;


What is the expected output? What do you see instead?
- When I call .LoadWmiData it takes long to retrieve the information at both 
calls, because the WMI connection are not shared between the objects. Sharing 
the WMI connection, the second information should retrieve much faster because 
I would be already authenticated at remote PC. 

What version of the product are you using? On what operating system?
Delphi XE, Windows 7 (x86)


Original issue reported on code.google.com by [email protected] on 19 Mar 2011 at 3:03

A few suggested changes for uWmiDelphiClass.pas

So get this to compile on Lazarus 1.4.0 and FPC 2.6.4 I had to change a few lines of uWmiDelphiClass.pas:

101 moved
{$IFDEF WMI_LateBinding}
FSWbemLocator : OleVariant;
//FWMIService : OleVariant; // commented out and moved:
to line 104:
{$IFDEF FPC}
FWMIService : OleVariant;

Line 192:
{$IFDEF WMI_LateBinding}
property SWbemLocator : OleVariant read FSWbemLocator;
property WMIService : OleVariant read FWMIService; // moved to an FPC IFEDF
to
{$IFDEF WMI_LateBinding}
property SWbemLocator : OleVariant read FSWbemLocator;
//property WMIService : OleVariant read FWMIService;
{$IFDEF FPC}
property WMIService : OleVariant read FWMIService;
{$ENDIF}

1169 from
objWbemObjectSet : = FWMIService.ExecQuery( WQL,'WQL',0);
to
objWbemObjectSet := WmiConnection.FWMIService.ExecQuery( WQL,'WQL',0);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.