DirectoryEntry does not retreiving empty properties and ignore RefreshCache() requested properties

132 Views Asked by At

could you please help me understand why my code isn't work properly:

    _domainService = new DomainServices(AdUserName, AdUserPass,AdUserDN);

    using UserPrincipal user = UserPrincipal.FindByIdentity(_domainService.CurrentGlobalContext, IdentityType.SamAccountName, "MyUserName");
    DirectoryEntry? directoryEntry = user.GetUnderlyingObject() as DirectoryEntry;

    var propList = adUser.BuildPropertiesList().ToArray<string>();
    
    directoryEntry!.RefreshCache(propList);

The code above returns me always 35 properties, whereas my list of properties uploaded to the RefreshCache method is only 27 and besides that thouse 35 doesn't have thouse I was identified ib my propList variable. I checked tons of posts here and tried dozens of solutions but it seems it is just simply ignored whatever i put in RefreshCache method. even if UsePropertyCache is true it is not working as i need. I did even tried to pull only one prop directoryEntry.RefreshCache(new string[] { "mobile" }); but as a result I get 35 properties and non of them was "mobile" ...

Appreciate your help in advance, Best regards, Maks.

1

There are 1 best solutions below

3
Max Zaikin On

Well, as i find out, this wasn't a problem at all.

  1. RefreshCache will return you only thouse properties which has been initialized with value.

  2. If you would like to discover all possible properties that exists in directory entry use following snippet:

    public List<string> AllAvailableProperties(DirectoryEntry de)
    {
        List<string> properties = new List<string>();
        de.RefreshCache(new string[] { "allowedAttributes" });
           
        foreach (string s in de.Properties["allowedAttributes"])
        {
            properties.Add(s);
        }
        return properties;
    }

Note code snippet has been borrowed from How to get ALL available properties for a DirectoryEntry. I did refactor it a bit as proposed solution isn't working in VS 2022, unfortunatelly I wasn't able to place my comment in original subject as my repuitation < 50

  1. So if for instance you would like to initialize mobile phone property then do follwoing:
    using UserPrincipal user = UserPrincipal.FindByIdentity(_domainService.CurrentGlobalContext, IdentityType.SamAccountName, "UserName");
    DirectoryEntry? directoryEntry = user.GetUnderlyingObject() as DirectoryEntry;
    directoryEntry!.Properties["mobile"].Value = "phone-number";
    directoryEntry!.CommitChanges();

That's all, Hope this will be helpfull for you and could save some time.