Q: How to get user details from Active Directory?
A: This example gets NT user name and domain name. Then it opens particular AD object and reads user information.
Code:void ReadActiveDirectory() { IEnumVARIANT *pEnum = NULL; IADsContainer *pCont = NULL; IADs *pADs = NULL; IDispatch *pDisp = NULL; IADsUser *pUser = NULL; VARIANT var; VariantInit(&var); BSTR bstr, user_ADsPath; ULONG lFetch; HRESULT hr; Text username, domainname; CoInitialize(NULL); //Read NT user name memset (username, 0, sizeof (username)); unsigned long len = sizeof (username); ::GetUserName (username, &len); //Read NT domain name memset (domainname, 0, sizeof (domainname)); len = sizeof (domainname); ::GetComputerNameEx(ComputerNameDnsDomain, domainname, &len); char *ch = strchr(domainname, '.'); if(ch) *ch = 0; //Form the AD domain path Text pathName; strcpy(pathName, "WinNT://"); strcat(pathName, domainname); CStringW str(pathName); // Bind to ADs namespace hr = ADsOpenObject(str, NULL,NULL,ADS_READONLY_SERVER,IID_IADsContainer, (void**) &pCont); if ( !SUCCEEDED(hr) || !pCont ) return FALSE; //Create an enumerator object in the container hr = ADsBuildEnumerator(pCont, &pEnum); // Now enumerate through all providers while(hr == S_OK) { hr = ADsEnumerateNext(pEnum, 1, &var, &lFetch); if (lFetch == 1) { pDisp = V_DISPATCH(&var); if(!pDisp) continue; pDisp->QueryInterface(IID_IADsUser, (void**)&pUser); pDisp->Release(); pDisp = NULL; if(!pUser) continue; hr = pUser->get_Class(&bstr); if ( !SUCCEEDED(hr) ) continue; if(CComBSTR("User") != CComBSTR(bstr)) continue; hr = pUser->get_Name(&bstr); if ( !SUCCEEDED(hr) ) continue; if(CComBSTR(username) == CComBSTR(bstr)) { pUser->get_ADsPath(&user_ADsPath); hr = pUser->get_FullName(&bstr); if ( SUCCEEDED(hr) ) full_name.SetAttr ((pchar)CString(bstr).GetString()); break; } pUser->Release(); pUser = NULL; SysFreeString(bstr); } } //Release the enumerator. if (pEnum != NULL) { ADsFreeEnumerator(pEnum); pEnum = NULL; } //Release the container. if (pCont != NULL) { pCont->Release (); pCont = NULL; } }


Reply With Quote
Bookmarks