Search code examples
c#propertiesmicrosoft-graph-apivisual-studio-2019

Unable to extract sAMAccountName from DirectoryObject using MsGraph - .Net 4.8


I'm running into an odd error extracting some non-default properties from a DirectoryObject and could use some guidance.

I'm using the following to grab the manager for the current user

            GraphServiceClient graphServiceClient = this.GetGraphServiceClient();
            var managerInfo = await graphServiceClient.Me.Manager
                .Request()
                .Select("onPremisesSamAccountName,displayName,jobTitle,userPrincipalName,directreports")
                .GetAsync();

            user.ManagerUpperEmail = GetDirObjPropertyValue(manager, "UserPrincipalName");
            user.ManagerUpperName = GetDirObjPropertyValue(manager, "DisplayName");
            user.ManagerUpperID = GetDirObjPropertyValue(manager, "onPremisesSamAccountName");

and I am able to see ALL of those properties when I view the managerInfo object in VS2019 Inspector (as shown below) but when I try to access it using the following, I get an NullReferenceException in the var3 assignment due to the part shown in var2 returning a null. This DOES NOT happen when running the same code against properties DisplayName and UserPrincipalName

        private string GetDirObjPropertyValue(DirectoryObject dObj, string key)
        {
            var var1 = dObj.GetType();
            var var2 = dObj.GetType().GetProperty(key);
            var var3 = dObj.GetType().GetProperty(key).GetValue(dObj, null);
            return (String) dObj.GetType().GetProperty(key).GetValue(dObj, null);
        }

returning a null in the following. This works perfectly for default properties such as DisplayName and UserPrincipalName.

enter image description here


Solution

  • The property names are case sensitive. You need to use OnPremisesSamAccountName instead of onPremisesSamAccountName.