sexta-feira, 24 de julho de 2015

ActiveDirectoryUser

using System.DirectoryServices;
using System.Linq;

namespace Lapuinka.Security.ActiveDirectory
{
    public class ActiveDirectoryUser : ActiveDirectoryObject
    {
        private readonly DirectoryEntry _entry;
        private ActiveDirectoryGroup[] _groups;
       
        public string UserName
        {
            get { return (string) _entry.Properties["sAMAccountName"].Value; }
        }

        public string Name
        {
            get { return (string)_entry.Properties["givenName"].Value; }
        }

        public string FullName
        {
            get { return (string) _entry.Properties["name"].Value; }
        }

        public ActiveDirectoryGroup[] Groups
        {
            get
            {
                if (_groups == null && _entry.Properties["memberOf"] != null)
                {
                    try
                    {
                        if (_entry.Properties["memberOf"].Value is object[])
                        {
                            _groups = ((object[])_entry.Properties["memberOf"].Value)
                                .Cast<string>()
                                .Select(g => new ActiveDirectoryGroup(Create(g)))
                                .ToArray();
                        }
                        else if (_entry.Properties["memberOf"].Value is string)
                        {
                            _groups = new[]
                                          {
                                              new ActiveDirectoryGroup(
                                                  Create((string)_entry.Properties["memberOf"].Value))
                                          };
                        }
                    }
                    catch
                    {
                        return new ActiveDirectoryGroup[0];
                    }
                }

                return _groups ?? new ActiveDirectoryGroup[0];
            }
        }
       
        public string Mail
        {
            get { return (string)_entry.Properties["mail"].Value; }
        }

        public ActiveDirectoryUser(DirectoryEntry entry)
        {
            _entry = entry;
        }
    }
}


Postar um comentário