0

I want to create a method which accepts two arguments; First being the username, and the second being the name of the Active Directory property to return... The method exists in a separate class (SharedMethods.cs) and works fine if you define the property name locally in the method, however I can't workout how to pass this in from the second argument.

Here is the method:

public static string GetADUserProperty(string sUser, string sProperty)
{    
        PrincipalContext Domain = new PrincipalContext(ContextType.Domain);
        UserPrincipal User = UserPrincipal.FindByIdentity(Domain, sUser);

        var Property = Enum.Parse<UserPrincipal>(sProperty, true);

        return User != null ? Property : null;
}

And the code that is calling it is as follows;

sDisplayName = SharedMethods.GetADUserProperty(sUsername, "DisplayName");

Currently Enum.Parse is throwing the following error:

The non-generic method 'system.enum.parse(system.type, string, bool)' cannot be used with type arguments

I can get it to work by removing the Enum.Parse, and manually specifying the property to retrieve as such:

public static string GetADUserProperty(string sUser, string sProperty)
{
        PrincipalContext Domain = new PrincipalContext(ContextType.Domain);
        UserPrincipal User = UserPrincipal.FindByIdentity(Domain, sUser);

        return User != null ? User.DisplayName : null;
}

Pretty sure I'm missing something obvious, thanks in advance for everyone's time.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jamesmealing
  • 19
  • 2
  • 8

2 Answers2

0

If you want to get the value of a property dynamically based on the property name, you will need to use reflection.

Please take a look at this answer: Get property value from string using reflection in C#

Community
  • 1
  • 1
Svein Fidjestøl
  • 3,106
  • 2
  • 24
  • 40
0

Because UserPrincipal is not an enum this will be hard but as Svein suggest it is possible with reflections.

public static string GetAdUserProperty(string sUser, string sProperty)
{
    var domain = new PrincipalContext(ContextType.Domain);
    var user = UserPrincipal.FindByIdentity(domain, sUser);

    var property = GetPropValue(user, sProperty);

    return (string) (user != null ? property : null);
}

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}
Piazzolla
  • 423
  • 5
  • 10
  • Thanks Piazzolla, exactly what I was looking for, the example particularly was extremely useful as I was struggling a little to get my head around reflection as per Svein's suggestion. – jamesmealing Nov 03 '14 at 12:50