CodeThings

Things i discover during my everyday life of trying build some decent code.

I have my own consulting company, Eqa, in which a assist companies in developing web applications based on various microsoft.net technologies.

Tuesday, April 08, 2008

System.DirectoryServices.AccountManagement namespace

The AccountManagement namespace is part of the .Net 3.5 framework, and provides an easy way to access and modify directory services.

I used to have my own ADHelper library that encapsulated the methods in System.DirectoryServices namespace.

Recently, i had to find out if a user was member of a specified group. This was possible, but it took a lot of lines of code. With the AccountManagement namespace it can be done in a few lines:


    static void Main()

    {

       UserPrincipal user = UserPrincipal.Current;

       if (user == null && !IsMemberOf(user, Settings.Default.EditorRole))

       {

         // user is found

       }

    }

 

    static bool IsMemberOf(UserPrincipal user, string roleName)

    {

        bool result = false;

        if (user != null)

        {

            PrincipalSearchResult groups = user.GetGroups();

            if (groups != null)

            {

                foreach (Principal principal in groups)

                {

                    if (principal.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase))

                    {

                        result = true;

                        break;

                    }

                }

            }

        }

        return result;

    } 

1 comments:

Dennis said...

Thanks for the code sample. This was very useful in understanding and putting into practice the AD integration in .Net.
Marc Sirois
Ottawa, Canada