Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrincipalSearchResult<T> with PrincipalSearcher FindAll, why does T have to be Principal and not UserPrincipal

I'm just curious:

List<string> ADUsers = new List<string>();
using (PrincipalContext principle_context = new PrincipalContext(ContextType.Domain, "MYDOMAIN"))
using (UserPrincipal user_principal = new UserPrincipal(principle_context) { Enabled = true, Name = "*", EmailAddress = "*" })
using (PrincipalSearcher user_searcher = new PrincipalSearcher(user_principal))
using (PrincipalSearchResult<Principal> results = user_searcher.FindAll())
{
    foreach (Principal p in results)
    {
        ADUsers.Add(p.Name + " " + ((UserPrincipal)p).EmailAddress);
    }
}

...is there a way to avoid having to cast my results here? I wanted to do something like:

using (PrincipalSearchResult<UserPrincipal> results = user_searcher.FindAll())

...so that my search result would be of the type I needed it, but it seems the FindAll method only allows using the <Principal> type. Is there a better way?

Thank you.

like image 278
Mike Avatar asked Dec 20 '22 09:12

Mike


2 Answers

Actually foreach will cast the enumerated values for you so you could do this

foreach (UserPrincipal p in results)
{
    ADUsers.Add(p.Name + " " + p.EmailAddress);
}

assuming that Name is defined within UserPrincipal as well as Principal.

like image 161
juharr Avatar answered Dec 21 '22 23:12

juharr


You could try adding a Cast. Change

PrincipalSearchResult<Principal> results = user_searcher.FindAll()

to

var results = user_searcher.FindAll().Cast<UserPrincipal>()
like image 44
MikeH Avatar answered Dec 21 '22 23:12

MikeH