unit ESSensorDialog;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls, Buttons, xmldom, XMLIntf, msxmldom, XMLDoc;

type
  TesSensors = class(TForm)
    Edit1: TEdit;
    Label1: TLabel;
    SpeedButton1: TSpeedButton;
    Label2: TLabel;
    ComboBox1: TComboBox;
    Button1: TButton;
    Button2: TButton;
    Bevel1: TBevel;
    XML: TXMLDocument;
    OpenDialog1: TOpenDialog;
    procedure SpeedButton1Click(Sender: TObject);
    procedure Edit1Change(Sender: TObject);
  private
    { Private declarations }
  public
    Function Execute(Filename: String; Var Value: String): Boolean;
  end;

  function IsFileInUse(FileName: TFileName): Boolean;

var
  esSensors: TesSensors;

implementation

{$R *.dfm}

function IsFileInUse(FileName: TFileName): Boolean;
var
  HFileRes: HFILE;
begin
  Result := False;
  if not FileExists(FileName) then Exit;
  HFileRes := CreateFile(PChar(FileName),
                         GENERIC_READ or GENERIC_WRITE,
                         0,
                         nil,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         0);
  Result := (HFileRes = INVALID_HANDLE_VALUE);
  if not Result then
    CloseHandle(HFileRes);
end;

{ TesSensors }

function TesSensors.Execute(Filename: String; var Value: String): Boolean;
Var
 I: Integer;
begin
 Edit1.Text := Filename;
 Edit1Change(self);
 For I := 0 to combobox1.Items.Count - 1 do begin
  if uppercase(combobox1.items[I]) = uppercase(Value) then begin
   Combobox1.ItemIndex := I;
  end;
 end;
 Result := showmodal = mrOK;
 If Result then begin
  If Combobox1.ItemIndex > -1 then begin
   Value := combobox1.Items[Combobox1.itemIndex];
  end;
 end;
end;

procedure TesSensors.SpeedButton1Click(Sender: TObject);
begin
 Opendialog1.FileName := Edit1.text;
 If not opendialog1.execute then exit;
 Edit1.Text := Opendialog1.filename;
end;

procedure TesSensors.Edit1Change(Sender: TObject);
Var
 I: Integer;
 Root: IXMLNode;
begin
 combobox1.Enabled := false;
 Button1.Enabled := false;
 combobox1.Clear;
 If not fileexists(edit1.text) then begin
  combobox1.Items.add('File not found');
  combobox1.ItemIndex := 0;
  exit;
 end;
 Repeat
  Sleep(100);
 until not IsFileInUse(Edit1.text);
 XML.XML.LoadFromFile(edit1.text);
 Try
  XML.Active := true;
 except
  combobox1.Items.Add('Not a valid XML file');
  combobox1.ItemIndex := 0;
  exit;
 end;
 Root := XML.ChildNodes['root'];
 If root = nil then begin
  XML.Active := false;
  combobox1.Items.Add('Unable to find root node');
  combobox1.ItemIndex := 0;
  exit;
 end;
 For I := 0 to Root.ChildNodes.Count - 1 do begin
  Combobox1.Items.Add(root.ChildNodes[I].NodeName);
 end;
 XML.Active := false;
 combobox1.ItemIndex := 0;
 combobox1.Enabled := true;
 Button1.Enabled := true;
end;

end.
