Platform SDK: Active Directory, ADSI, and Directory Services

Example Code for Binding to the Users Container

The following C++ code fragment contains a function that binds to the users container and then uses IADsContainer::GetObject to bind to the Administrator user object within the users container:

LPOLESTR szPath = new OLECHAR[MAX_PATH];
VARIANT var;
hr = ADsOpenObject(L"LDAP://rootDSE",
                 NULL,
                 NULL,
                 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
                 IID_IADs,
                 (void**)&pObject);
 
//Get current domain DN.
if (SUCCEEDED(hr))
{
    hr = pObject->Get(L"defaultNamingContext",&var);
    if (SUCCEEDED(hr))
    {
        //Build the WKGUID binding string.
        wcscpy(szPath,L"LDAP://cn=Users,");
        wcscat(szPath,var.bstrVal);
        if (pObject)
          pObject->Release();
        hr = ADsOpenObject(szPath,
                 NULL,
                 NULL,
                 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
                 IID_IADs,
                 (void**)&pObject);
        if (SUCCEEDED(hr))
        {
            hr = pObject->QueryInterface(IID_IADsContainer,(void**)&pContainer);
            if (SUCCEEDED(hr))
            {
                hr = pContainer->GetObject(L"user",L"cn=Administrator",&pDisp);
                if (SUCCEEDED(hr))
                {
                  hr = pDisp->QueryInterface(IID_IADs,(void**)&pChild);
                  if (SUCCEEDED(hr))
                  {
                      hr = pChild->get_ADsPath(&bstr);
                      if (SUCCEEDED(hr))
                      {
                        wprintf (L"ADsPath of child object: %s\n", bstr);
                        FreeADsStr(bstr);
                      }
                  }
                  if (pChild)
                      pChild->Release();
                }
                else
                  wprintf(L"GetObject failed with hr: %x\n",hr);
                if (pDisp)
                    pDisp->Release();
            }
            if (pContainer)
                 pContainer->Release();
        }
        if (pObject)
            pObject->Release();
    }
    VariantClear(&var);
}