Active Directory Programming has become necessary now a days because Active Directory is now been considered as a standard across all organizations. In an active directory structure the objects like computers, users, groups etc., are treated as object nodes with their own properties and collections. This article explains how to use the Active Directory Programming concept to enumerate the users in a local computer.
This Active Directory programming sample uses the objects IADsContainer and IADsUser and functions like ADsGetObject, ADsBuildEnumerator and ADsEnumerateNext.
Active Directory programming – Important interfaces and functions:
IADsContainer:
This Active directory programming interface can be used like a container to hold the other objects. For example this can be used to query the list of users and hold it. This can then be used with enumeration functions to enumerate the objects queried.
IADsUser:
This IADsUser active directory programming interface is used to hold the properties of a user of a domain or a local computer.
ADsGetObject:
This is used to retrieve the object when the right path/ADSI query is specified.
ADsBuildEnumerator and ADsEnumerateNext:
These two Active directory programming functions are used to enumerate the collection of objects inside the container.
Active Directory programming – Sample code to retrieve the list of users:
The following console based application sample can retrieve the users present in the local computer.
#include <comdef.h> #include <Iads.h> #include <Adshlp.h> int main() { HRESULT hr; IADsContainer *pCont = NULL; CoInitialize(NULL); hr = ADsGetObject(L"WinNT://domain/computer", IID_IADsContainer, (void**) &pCont ); if ( !SUCCEEDED(hr) ) { return hr;} _variant_t var; IEnumVARIANTPtr pEnum; ADsBuildEnumerator (pCont,&pEnum); int cnt=0; ULONG ulFetched = 0L; _variant_t vChild; while((SUCCEEDED(ADsEnumerateNext(pEnum, 1, &vChild, &ulFetched)) && ulFetched==1)) { IADsUser* pADs; hr = V_DISPATCH(&vChild)->QueryInterface(IID_IADsUser, (void**)&pADs); if(hr!=S_OK) break; BSTR bstrName; pADs->get_Name(&bstrName); CString csName=bstrName; SysFreeString(bstrName); printf("%sn",csName); pADs->Release(); pADs = NULL; } // Cleanup. if ( pCont ) { pCont->Release(); } CoUninitialize(); }
The ADsGetObject first retrieves the information of the objects present in the computer. Then ADsBuildEnumerator is used to build an enumerator of all the objects. ADsEnumerateNext can be used to traverse through the list till it fails to get a IAdsUser object.
Note: The above program needs to be linked with ActiveDS.lib Adsiid.lib and MFC Libraries.