Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coinitialize has not been called error message

I am in the process of coding a console application that will create a firewall exception for my main app called Client.exe which uploads a few documents to our servers via FTP. I borrowed RRUZ code from Delphi 7 Windows Vista/7 Firewall Exception Network Locations my code looks like this:

program ChangeFW;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  ComObj;

var
  ExecName: string;

procedure AddExceptionToFirewall(Const Caption, Executable: String);
const
NET_FW_PROFILE2_DOMAIN  = 1;
NET_FW_PROFILE2_PRIVATE = 2;
NET_FW_PROFILE2_PUBLIC  = 4;

NET_FW_IP_PROTOCOL_TCP = 6;
NET_FW_ACTION_ALLOW    = 1;
var
  fwPolicy2      : OleVariant;
  RulesObject    : OleVariant;
  Profile        : Integer;
  NewRule        : OleVariant;
begin
  Profile             := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC;
  fwPolicy2           := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject         := fwPolicy2.Rules;
  NewRule             := CreateOleObject('HNetCfg.FWRule');
  NewRule.Name        := Caption;
  NewRule.Description := Caption;
  NewRule.Applicationname := Executable;
  NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
  NewRule.Enabled := TRUE;
  NewRule.Profiles := Profile;
  NewRule.Action := NET_FW_ACTION_ALLOW;
  RulesObject.Add(NewRule);
end;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    ExecName := GetCurrentDir + '\' + 'Client.exe';
    AddExceptionToFirewall('SIP Inventory',ExecName);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

When I execute the application I get the following error message: EOIeSysError: Coinitialize has not been called, ProgID: “HNetCfg.FwPolicy2” Any idea what I am doing wrong? Could you please point me in the right direction? Thank you so very much.

like image 792
Cor4Ever Avatar asked Dec 08 '22 15:12

Cor4Ever


1 Answers

If you want to use COM - objects you will have to call CoInitialize with corresponding CoUninitialize.

In a usual application this will be already done.
As far as your program is a console program you will have to call it on your own.

.....
CoInitialize(nil);
try
  try
    { TODO -oUser -cConsole Main : Insert code here }
    ExecName := GetCurrentDir + '\' + 'Client.exe';
    AddExceptionToFirewall('SIP Inventory',ExecName);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
finally
  CoUninitialize;
end;
.....
like image 165
bummi Avatar answered Jan 04 '23 05:01

bummi