0

I have a UserGroup table which stores the GroupID and the associated UserName. Currently the users exists inside the active directory, so i do not have a Users table. But before assigning any user to the UserGroup table i want to check if the user already defined inside Active Directory or not. so i find writing a validation object inside my UserGroup Model object a good approach so i wrote the following insdie my USerGroup Partial class :-

List<DomainContext> results = new List<DomainContext>();
using (var context = new PrincipalContext(ContextType.Domain, "WIN-SPDEV"))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
   var searchResults = searcher.FindAll();
   foreach (Principal p in searchResults)
   {
     //not sure what to write here !!!
}}
yield return new ValidationResult("UserName does not exsists.");}

But i am not sure how i can implement the uniqueness checking !!!

2 Answers 2

1

Try:

using (var context = new PrincipalContext(ContextType.Domain, "WIN-SPDEV"))
{
    UserPrincipal user = UserPrincipal.FindByIdentity(context, searchedUserName);
    if (user != null)
    {
        //user found
    }
}
2
  • thanks a lot it worked well , but it is a bad practice to call Active Directory inside Model classes ?
    – user2583498
    Commented Jul 16, 2013 at 13:54
  • You can create a custom validation attribute, and call Active Directory inside that.
    – ataravati
    Commented Jul 16, 2013 at 14:18
1

Please try this code:

var searchResults = searcher.FindAll();
foreach (Principal p in searchResults)
{
  if(p.SamAccountName == User.Identity.Name)
  {
      //your in!
  }
}
1
  • i do not want to compare the current login user!!!. i am working with an intranet web application, so the current login user will always be inside AD !!!
    – user2583498
    Commented Jul 16, 2013 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.