| Platform SDK: Active Directory, ADSI, and Directory Services |
The following code fragments contain a function that returns the distinguished name of the specified naming context (defined in the enumerated type NAMING_CONTEXT) using serverless binding and rootDSE.
Function GetNamingContext(ByVal sPropertyName As String) As String
Dim IADsRootDSE As IADs
GetNamingContext = ""
Set IADsRootDSE = GetObject("LDAP://rootDSE")
GetNamingContext = IADsRootDSE.Get(sPropertyName)
Set IADsRootDSE = Nothing
End Function
typedef enum
{
NC_CURRENT_DOMAIN = 0x0,
NC_ROOT_OF_DOMAIN_TREE,
NC_SCHEMA,
NC_CONFIG
} NAMING_CONTEXT;
HRESULT GetNamingContextDN(
NAMING_CONTEXT namingcontext,
LPOLESTR *ppDNString
)
{
LPOLESTR pszDSPath = L"LDAP://rootDSE";
LPOLESTR pszProperty = NULL;
HRESULT hr = S_OK;
VARIANT var;
IADs *pObj = NULL;
//Get the rootDSE.
hr = ADsGetObject(pszDSPath,
IID_IADs,
(void**)&pObj);
if (SUCCEEDED(hr))
{
//String to specify property to get based on namingcontext.
switch (namingcontext)
{
//Ask for DN of root of domain tree that contains the current domain.
case NC_ROOT_OF_DOMAIN_TREE:
pszProperty = L"rootDomainNamingContext";
break;
//Ask for DN of schema container in the current domain.
case NC_SCHEMA:
pszProperty = L"schemaNamingContext";
break;
//Ask for DN of config container in the current domain.
case NC_CONFIG:
pszProperty = L"configurationNamingContext";
break;
//Ask for DN for current domain.
case NC_CURRENT_DOMAIN:
default:
pszProperty = L"defaultNamingContext";
break;
}
//Get the DN from the specified property of rootDSE.
if (pszProperty)
{
hr = pObj->Get(pszProperty,&var);
if (SUCCEEDED(hr))
{
*ppDNString = (OLECHAR *)CoTaskMemAlloc (sizeof(OLECHAR)*(wcslen(var.bstrVal)+1));
if (*ppDNString)
wcscpy(*ppDNString, var.bstrVal);
}
}
}
// Clean up
if (pObj)
pObj->Release();
VariantClear(&var);
return hr;
//The caller needs to call CoTaskMemFree on ppDNString.
}