Visual C++ Tutorial Code – AddUser

 

AddUser code:

#include <windows.h>
#include <atlbase.h>
#import "pisdkcommon.dll" no_namespace
#import "piTimeServer.dll" no_namespace
#import "pisdk.dll" no_namespace 

// prototypes
bool ParseCommandLine(LPTSTR szCmdLine,_bstr_t & bServerName,
_bstr_t & bUserName, _bstr_t &bGroupName);

main()
{
   LPTSTR szCmd = GetCommandLine();
   _bstr_t bServerName,bUserName,bGroupName;
   if(!ParseCommandLine(szCmd,bServerName,bUserName,bGroupName))
   {
      _tprintf(_T("Usage: AddUser Server User Group\n"));
      return 0;
   }
   CoInitialize(NULL);
   try
   {
      IPISDKPtr pPISDK(__uuidof(PISDK));
      ServersPtr pServers;
      ServerPtr pServer;
      PIUsersPtr pUsers;
      PIUserPtr pUser;
      PIGroupsPtr pGroups;
      PIGroupPtr pGroup;

      pServers = pPISDK->Servers;
      pServer = pServers->Item[bServerName];
      // verify the group exists
      pGroups = pServer->PIGroups;
      pGroup = pGroups->Item[bGroupName];
      // Build a NamedValues collection with the group
      _NamedValuesPtr nvGroups(__uuidof(NamedValues));
      _variant_t vtTemp;
      vtTemp = (long)1; // not used
      nvGroups->Add(bGroupName,&vtTemp);
      // Get the Server's PIUser collection to add the user
      pUsers = pServer->PIUsers;
      _bstr_t bPassword = L"";
      _bstr_t bContext = L"default";
      pUsers->Add(bUserName,(_bstr_t)L"Newly Added User",
      bPassword,nvGroups,bContext);
   }
   catch(_com_error Err)
   {
      _tprintf(_T("Error:%s : 0x%x \n"),(TCHAR *)Err.Description(),Err.Error());
   } 
   CoUninitialize();
   return 0;
}


bool ParseCommandLine(LPTSTR szCmdLine,_bstr_t & bServerName,
                                _bstr_t & bUserName, _bstr_t &bGroupName)
{
   // skip over program directory
   LPTSTR szPtr = _tcstok(szCmdLine,_T(" \n\0")); 
   if(!szPtr)
      return false;
   szPtr = _tcstok(NULL,_T(" \n\0")); 
   if(!szPtr)
      return false;
   bServerName = szPtr;
   szPtr = _tcstok(NULL,_T(" \n\0")); 
   if(!szPtr)
         return false;
   bUserName = szPtr; 
   szPtr = _tcstok(NULL,_T("\n\0")); 
   if(!szPtr)
      return false;
   bGroupName = szPtr; 
   return true;
}

Enabling Operational Intelligence