2

I am trying to retrieve SamAccountName,Surname,GivenName for users within a particular ADGroup using:

        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, adgroup);

        foreach (Principal principal in group.Members)
        {
            samName = principal.SamAccountName;
            surName = principal.SurName;   <-- Intellisense gives error
            givenName = principal.GivenName;   <-- Intellisense gives error
        }

As I step thru the code and add watches in Visual Studio for the above, they display the correct information, but principal.Surname and principal.GivenName give the following error at compile:

'Principal' does not contain a definition for '____' and no extension method can be found

Can someone explain why I can see the information when using codebreaks in the IDE and hover over the principal variable, but cannot access the attribute in the code?

T-Heron
  • 5,385
  • 7
  • 26
  • 52
Keith Clark
  • 609
  • 1
  • 7
  • 19

2 Answers2

2

SurName and GivenName are not public properties of type Principal according to the docs

It looks like you need the UserPrincipal class to expose those properties, see the UserPrincipal documentation

I cannot verify 100% right now, but I think if you change

foreach (Principal principal in group.Members)

to

foreach (UserPrincipal principal in group.Members)

it should work

maccettura
  • 10,514
  • 3
  • 28
  • 35
  • 1
    That did it. Thanks! Crazy that Visual Studio shows it as an attribute while watching the principal variable during run time. – Keith Clark Mar 10 '17 at 19:07
  • 1
    The reason it does that is because the actual type is `UserPrincipal ` but you explicitly defined it as a `Principal`, which means at compile time your code can only access the values Principal has. From the docs you can see that UserPrincipal inherits AuthenticablePrincipal which inherits Principal. – maccettura Mar 10 '17 at 19:09
  • 1
    Ah! Now I know which direction to look in for future issues like this. – Keith Clark Mar 10 '17 at 19:15
0

The Principal class does not have a property Surname or GivenName https://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principal(v=vs.110).aspx

GreatJobBob
  • 271
  • 1
  • 8
  • 1
    I see that in the documentation, but how does Visual Studio IDE show it when watching the principal variable during run time is what I was trying to figure out. Very confusing. – Keith Clark Mar 10 '17 at 19:04
  • 1
    see comment from maccettura, I think that he is correct the Principle class is an abstract class and UserPrinciple derives from it and add the properties that you need – GreatJobBob Mar 10 '17 at 19:10