public Int32 getNextUID()
        {
            checkConnection();

            Int32 id = 0;

            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            mySearcher.Filter = "(|(objectClass=user))";
            SearchResultCollection resultSet = mySearcher.FindAll();

            foreach (SearchResult result in resultSet)
            {
                DirectoryEntry user = result.GetDirectoryEntry();
                if (user.Properties["uidnumber"].Value != null)
                {
                    String foo = user.Properties["uidnumber"].Value.ToString();
                    String username = user.Properties["uid"].Value.ToString();
                    int thisID;
                    Int32.TryParse(foo, out thisID);
                    if (thisID > id){
                        id = thisID;
                    }

                }

            }

            mySearcher.Dispose();

            return (id != 0) ? (id + 1) : 0;
        }
Exemple #2
0
        public static Task Test()
        {
            return Task.Run(() => {
                string strServerDNS = "ldap.hp.com:389";
                string strSearchBaseDN = "ou=Email,ou=Services,o=hp.com";
                string strLDAPPath;
                strLDAPPath = "LDAP://" + strServerDNS + "/" + strSearchBaseDN;
                DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, null, null, AuthenticationTypes.Anonymous);
                DirectorySearcher searcher = new DirectorySearcher(objDirEntry);
                SearchResult result = null;

                searcher.Filter = "[email protected]";
                searcher.PropertiesToLoad.Add("ntUserDomainId");

                searcher.ClientTimeout = TimeSpan.FromSeconds(20);
                try
                {
                    result = searcher.FindOne();

                }
                catch (Exception ex)
                {

                }

                finally
                {
                    searcher.Dispose();
                }

            });
        }
Exemple #3
0
        public static List<string> GetComputers()
        {
            List<string> ComputerNames = new List<string>();

            DirectoryEntry entry = new DirectoryEntry("LDAP://transnetwork.local/OU=Phoenix-DC,DC=transnetwork,DC=local");
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            mySearcher.Filter = ("(objectClass=computer)"); //se buscan solamente objetos de ltipo computadora / server
            mySearcher.SizeLimit = int.MaxValue;
            mySearcher.PageSize = int.MaxValue;

            foreach (SearchResult resEnt in mySearcher.FindAll())
            {

                //"CN=SGSVG007DC"
                string ComputerName = resEnt.GetDirectoryEntry().Name;
                if (ComputerName.StartsWith("CN="))
                    ComputerName = ComputerName.Remove(0, "CN=".Length);
                ComputerNames.Add(ComputerName);
            }

            mySearcher.Dispose();
            entry.Dispose();
             // Console.ReadLine();
            return ComputerNames;
        }
Exemple #4
0
        /// <summary>
        /// Retrieves the user information.
        /// </summary>
        /// <param name="userNameToRetrieveFrom">The user name to retrieve from.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public LdapUserInfo RetrieveUserInformation(string userNameToRetrieveFrom)
        {
            System.DirectoryServices.DirectorySearcher ldapSearcher = new System.DirectoryServices.DirectorySearcher();
            System.DirectoryServices.SearchResult      ldapResult   = default(System.DirectoryServices.SearchResult);

            string filter = "(&(objectClass=user)(SAMAccountName=" + userNameToRetrieveFrom + "))";


            System.DirectoryServices.DirectoryEntry ldap = default(System.DirectoryServices.DirectoryEntry);

            try
            {
                if (LdapLogonUserName == null)
                {
                    ldap = new System.DirectoryServices.DirectoryEntry("LDAP://" + DomainName);
                }
                else
                {
                    ldap = new System.DirectoryServices.DirectoryEntry("LDAP://" + DomainName, LdapLogonUserName, LdapLogonPassword);
                }
            }
            catch (Exception e)
            {
                Util.Log.Trace(e.ToString());
                throw new CruiseControlException("Problem connecting to LDAP service", e);
            }

            ldapSearcher.SearchRoot  = ldap;
            ldapSearcher.SearchScope = SearchScope.Subtree;

            ldapSearcher.PropertiesToLoad.Add(LdapFieldMailAddress);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldSurName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldCommonName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldGivenName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldDisplayName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldMailNickName);

            ldapSearcher.Filter = filter;
            ldapResult          = ldapSearcher.FindOne();
            ldapSearcher.Dispose();

            LdapUserInfo result = new LdapUserInfo();

            if ((ldapResult != null))
            {
                result.CommonName   = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldCommonName].Value;
                result.DisplayName  = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldDisplayName].Value;
                result.GivenName    = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldGivenName].Value;
                result.MailAddress  = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldMailAddress].Value;
                result.MailNickName = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldMailNickName].Value;
                result.Name         = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldName].Value;
                result.SurName      = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldSurName].Value;
            }

            return(result);
        }
Exemple #5
0
 public static string getDNFromLDAP(string strUID)
 {
     DirectoryEntry entry = new DirectoryEntry("LDAP://rock.temple.edu/ou=temple,dc=tu,dc=temple,dc=edu");
     entry.AuthenticationType = AuthenticationTypes.None;
     DirectorySearcher mySearcher = new DirectorySearcher(entry);
     entry.Close();
     entry.Dispose();
     mySearcher.Filter = "(sAMAccountName=" + strUID + ")";
     SearchResult result = mySearcher.FindOne();
     mySearcher.Dispose();
     int nIndex = result.Path.LastIndexOf("/");
     string strDN = result.Path.Substring((nIndex + 1)).ToString().TrimEnd();
     return strDN;
 }
        public static string GetFullName( string strUserId )
        {
            if( ServerList.Count == 0 )
                LoadServerList();

            string sLDAPPath = string.Format( "LDAP://{0}/DC=XXXX,DC=root01,DC=org", ServerList["XXXX"] );
            string strFullName = "";
            DirectoryEntry objDE = null;
            try
            {
                objDE = new DirectoryEntry(sLDAPPath);

                DirectorySearcher objDS = new DirectorySearcher( objDE );

                // get the LDAP filter string based on selections
                string strFilter = string.Format("(|(&(objectClass=User)(sAMAccountName={0})))", strUserId);
                objDS.Filter = strFilter;
                objDS.ReferralChasing = ReferralChasingOption.None;

                //start searching
                SearchResultCollection objSRC = objDS.FindAll();

                try
                {
                    if (objSRC.Count != 0)
                    {
                        // grab the first search result
                        SearchResult objSR = objSRC[0];

                        string strFirstName = objSR.Properties[ "givenName" ][ 0 ].ToString();
                        string strLastName	= objSR.Properties[ "sn" ][ 0 ].ToString();
                        strFullName			= string.Concat( strLastName, ", ", strFirstName );
                    }
                }
                catch (Exception e)
                {
                    // ignore errors
                }

                objSRC.Dispose();
                objDS.Dispose();
            }
            catch (Exception e)
            {
                // ignore errors
            }

            return strFullName;
        }
        public BindableCollection<IComputer> FindMatchingComputers(string filterName)
        {
            if (!filterName.EndsWith("*") && !filterName.EndsWith("$") && !filterName.EndsWith("%"))
            {
                filterName = filterName += "$";
            }
            if (filterName.EndsWith("%"))
            {
                filterName = filterName.Replace('%', '*');
            }

            string filter = string.Format("(&(objectCategory=Computer)(sAMAccountName={0}))", filterName);
            BindableCollection<IComputer> Matches = new BindableCollection<IComputer>();

            DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}",GetClosestDC()));
            DirectorySearcher ds = new DirectorySearcher(de);
            SearchResultCollection results;
            try
            {
                ds.ReferralChasing = ReferralChasingOption.All;
                ds.SearchScope = SearchScope.Subtree;
                ds.PropertiesToLoad.Add("sAMAccountName");
                ds.Filter = filter;
                results = ds.FindAll();

                if (results.Count > 0)
                {
                    foreach (SearchResult sr in results)
                    {
                        Computer c = new Computer() { Name = sr.Properties["sAMAccountName"][0].ToString().Replace("$", "") };
                        Matches.Add(c);
                    }
                }

                results.Dispose();
            }
            catch
            {
                //ERROR....
            }
            finally
            {
                de.Dispose();
                ds.Dispose();

            }
            return Matches;
        }
		/// <summary>
		/// Search the LDAP store for the entries required using the context specified
		/// </summary>
		/// <param name="adsPath">The adspath that the server will use</param>
		/// <param name="objectClass">The object class to search for</param>
		/// <param name="attrib">The attribute to search on</param>
		/// <param name="attribValue">The value to search for</param>
		/// <returns>The collection of results found.</returns>
		protected SearchResultCollection SearchLdapContext(string adsPath, string objectClass, string attrib, string attribValue)
		{			
			DirectoryEntry root = GetServerContext(adsPath);
			StringBuilder sb = new StringBuilder();
			sb.AppendFormat(m_defaultSearch, objectClass, attrib, attribValue);
			DirectorySearcher ds = new DirectorySearcher(root, sb.ToString());
			if ( m_pageSize > 0 )
				ds.PageSize = m_pageSize;
			ds.SearchScope = SearchScope.Subtree;
			foreach(string prop in m_properties )
				ds.PropertiesToLoad.Add(prop);
			SearchResultCollection src =  ds.FindAll();
			ds.Dispose();
			root.Dispose();
			return src;
		}
Exemple #9
0
        public static Task GetUserInfo(Dictionary<string,string> Filter,Dictionary<string, ResultPropertyValueCollection> ResultFormat)
        {
            return Task.Run(() => {
                string strServerDNS = "ldap.hp.com:389";
                string strSearchBaseDN = "ou=People,o=hp.com";
                string strLDAPPath;
                strLDAPPath = "LDAP://" + strServerDNS + "/" + strSearchBaseDN;
                DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, null, null, AuthenticationTypes.Anonymous);
                DirectorySearcher searcher = new DirectorySearcher(objDirEntry);
                SearchResult result = null;

                searcher.Filter = "[email protected]";

                foreach(var returnVal in ResultFormat)
                {
                    searcher.PropertiesToLoad.Add(returnVal.Key);
                }
                searcher.ClientTimeout = TimeSpan.FromSeconds(20);
                try
                {
                    result = searcher.FindOne();
                    for(int i = 0;i<ResultFormat.Count;i++)
                    {
                        string key = ResultFormat.ElementAt(i).Key;
                        ResultFormat[key] = result.Properties[key];
                    }

                }
                catch(Exception ex)
                {

                }

                finally
                {
                    searcher.Dispose();
                }

            });
        }
Exemple #10
0
        public static void AddUserToGroup(string UserName, string GroupName)
        {
            DirectoryEntry rootEntry = GetDirectoryObject("/" + GetLDAPDomain());
            DirectorySearcher Mysearcher = new DirectorySearcher(rootEntry);
            Mysearcher.SearchRoot = rootEntry;
            Mysearcher.Filter = "(&(objectCategory=group)(CN=" + GroupName + "))";
            SearchResult result = Mysearcher.FindOne();
            DirectoryEntry g = result.GetDirectoryEntry();
            Mysearcher.Filter = "(&(objectCategory=user)(SAMAccountName=" + UserName + "))";
            result = Mysearcher.FindOne();
            DirectoryEntry user = result.GetDirectoryEntry();
            g.Invoke("Add", new Object[] { user.Path });
            g.CommitChanges();

            g.Close();
            g.Dispose();

            user.Close();
            user.Dispose();

            Mysearcher.Dispose();
            rootEntry.Close();
            rootEntry.Dispose();
        }
Exemple #11
0
        /// <summary>
        /// Gets the photo for the user from the thumbnailPhoto attribute in Active Directory
        /// </summary>
        /// <param name="userPrincipalName"></param>
        /// <returns></returns>
        public byte[] GetPhoto(string userPrincipalName)
        {
            DirectoryEntry de = null;
            DirectorySearcher ds = null;

            try
            {
                logger.Debug("Attempting to find photo for " + userPrincipalName);

                de = new DirectoryEntry("LDAP://" + this.domainController, this.username, this.password);
                ds = new DirectorySearcher(de);
                ds.SearchScope = SearchScope.Subtree;
                ds.Filter = string.Format("(&(objectClass=User)(userPrincipalName={0}))", userPrincipalName);

                SearchResult found = ds.FindOne();

                byte[] data = null;
                if (found != null)
                {
                    using (DirectoryEntry u = new DirectoryEntry(found.Path))
                    {
                        if (u.Properties["thumbnailPhoto"].Value != null)
                            data = u.Properties["thumbnailPhoto"].Value as byte[];
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                this.logger.Error("Error getting photto for " + userPrincipalName, ex);
                throw;
            }
            finally
            {
                if (ds != null)
                    ds.Dispose();

                if (de != null)
                    de.Dispose();
            }
        }
Exemple #12
0
        /// <summary>
        /// 根据组名返回用户组
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="groupname"></param>
        /// <returns></returns>
        public static DirectoryEntry GetGroup(DirectoryEntry entry, string groupname)
        {
            if (string.IsNullOrEmpty(groupname))
            {
                return null;
            }
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = "(&(objectClass=group)(name=" + groupname + "))";
            searcher.CacheResults = false;
            searcher.PropertyNamesOnly = true;
            searcher.PropertiesToLoad.Add("cn");
            searcher.PropertiesToLoad.Add("distinguishedName");
            searcher.PropertiesToLoad.Add("Description");
            searcher.PropertiesToLoad.Add("memberOf");

            SearchResult result = searcher.FindOne();
            DirectoryEntry group = null;
            if (result != null)
            {
                group = result.GetDirectoryEntry();
            }
            entry.Dispose();
            searcher.Dispose();
            return group;
        }
        void LDB_Query(object sender, RoutedEventArgs e)
        {
            lbQBUsers.Items.Clear();

            DirectorySearcher ds = new DirectorySearcher();

            ds.SearchRoot = new DirectoryEntry(selectedPath);       // start searching from whatever was selectted
            ds.Filter = (tbFilter.Text.Length > 0) ? String.Format(
                "(|(&(objectCategory=user)(name={0})))", tbFilter.Text) :
                "(|(&(objectCategory=user)(name=*)))";

            ds.PropertiesToLoad.Add("sAMAccountName");
            if (cbEntireSubt.IsChecked == false)
                ds.SearchScope = SearchScope.OneLevel;
            SearchResultCollection src = ds.FindAll();

            try
            {
                int arraySiz = (src.Count) * 2;

                accts = new string[arraySiz];

                int k = 0;

                foreach (SearchResult sr in src)
                {
                    DirectoryEntry de = sr.GetDirectoryEntry();

                    lbQBUsers.Items.Add(de.Name.Substring(3));
                    foreach (String property in ds.PropertiesToLoad)
                    {
                        foreach (Object myCollection in sr.Properties[property])
                        {
                            if (property == "sAMAccountName")
                            {
                                  accts[k++] = de.Name.Substring(3);
                                  accts[k++] = myCollection.ToString();

                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            src.Dispose();
            ds.Dispose();
        }
Exemple #14
0
        ///// <summary>
        ///// Obtiene un usuario sin pasar clave.-
        ///// </summary>
        ///// <param name="userName"></param>
        ///// <returns></returns>
        internal static SearchResult User_Get_Result(string userName, DirectoryEntry root)
        {
            DirectorySearcher deSearch = new DirectorySearcher(root);
            deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + ADHelper.FilterOutDomain(userName) + "))";
            deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            SearchResult rs = deSearch.FindOne();
            deSearch.Dispose();
            return rs;

        }
Exemple #15
0
        private string GetAvailableSamAccountName(string userPrincipalName)
        {
            DirectorySearcher ds = null;

            try
            {
                log.DebugFormat("Attempting to find an available sAMAccountName for {0}.", userPrincipalName);

                // Get the first part of the user principal name
                string upnFirstPart = userPrincipalName.Split('@')[0];
                string sAMAccountName = upnFirstPart;

                de = GetDirectoryEntry();
                ds = new DirectorySearcher(de);
                ds.SearchScope = SearchScope.Subtree;
                ds.Filter = string.Format("(sAMAccountName={0})", upnFirstPart);

                int count = 0;
                while (ds.FindOne() != null)
                {
                    count = count + 1;

                    sAMAccountName = string.Format("{0}{1}", upnFirstPart, count.ToString());

                    ds.Filter = string.Format("(sAMAccountName={0})", sAMAccountName);
                }

                // We found our available sAMAccountName
                return sAMAccountName;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error searching for available SamAccountName for {0}. Exception: {1} ", userPrincipalName, ex.ToString());
                throw;
            }
            finally
            {
                if (ds != null)
                    ds.Dispose();
            }
        }
Exemple #16
0
        private void GetPropertyFromAD(DataTable result)
        {
            string userName = this.Context.User.Identity.Name;

            using (HostingEnvironment.Impersonate())
            {
                DirectoryEntry dirEntry    = new DirectoryEntry(_adEntryPoint);
                string         studentName = "";

                // Trim the domain name
                if (userName.IndexOf("\\") != 0)
                {
                    userName = userName.Substring(userName.LastIndexOf("\\") + 1);
                }

                // We are storing the Children of a Parent in the  property of Active Directory specified
                System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);
                mySearcher.PropertiesToLoad.Add(_adChildAttribute);
                //Set the filter for the current user
                mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + userName + "))";

                ResultPropertyValueCollection myResultPropColl = null;

                try
                {
                    myResultPropColl = mySearcher.FindOne().Properties[_adChildAttribute];
                }
                catch (Exception ex)
                {
                    Debug(ex.ToString());
                    ShowMessage(LoadResource(GenericErrMsg), String.Format(LoadResource("ErrorRetrievingChildren"), ex.ToString()));
                    return;
                }

                //if null an error occured
                if (myResultPropColl == null)
                {
                    ShowMessage(LoadResource(GenericErrMsg));
                    return;
                }
                //if count =0 then no childern
                if (myResultPropColl.Count == 0)
                {
                    ShowMessage(LoadResource("NoChild"));
                }

                // Loop through each found child, and return their Display Name , Image Url and First Name
                foreach (object myCollection in myResultPropColl)
                {
                    string orgStudentName = myCollection.ToString();

                    Debug("{0} in AD attribute", orgStudentName);

                    if (!IsMember(orgStudentName, _studentsSiteURL))
                    {
                        Debug("Not member");
                        continue;
                    }

                    DataRow studentRow = result.NewRow();
                    studentRow[IsSelectedColumnName] = false;

                    studentRow[UserNameColumnName] = orgStudentName;

                    // Trim the domain name
                    if (orgStudentName.IndexOf("\\") != 0)
                    {
                        studentName = orgStudentName.Substring(orgStudentName.LastIndexOf("\\") + 1);
                    }

                    try
                    {
                        //read display name property
                        mySearcher.PropertiesToLoad.Add(DisplayNameColumnName);
                        mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + studentName + "))";

                        System.DirectoryServices.SearchResult SrchRes;
                        SrchRes = mySearcher.FindOne();

                        if (SrchRes != null)
                        {
                            studentRow[DisplayNameColumnName] = SrchRes.Properties[DisplayNameColumnName][0].ToString();
                            string pictureURL = GetStudentImage(studentName);
                            if (pictureURL == null)
                            {
                                System.Uri defaultpic = new Uri(new Uri(Context.Request.Url.ToString()), DefaultPictureURL);
                                pictureURL = defaultpic.OriginalString.ToString();
                            }
                            studentRow[ImageUrlColumnName] = pictureURL;

                            result.Rows.Add(studentRow);
                        }
                        else // No user object found for the attached child
                        {
                            ShowMessage(String.Format(LoadResource("NoChildFound"), studentName));
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(LoadResource(GenericErrMsg), String.Format(LoadResource("ErrorRetrievingChildInfo"), studentName, ex.Message));
                    }
                }

                mySearcher.Dispose();
            }
        }
        internal static string GetObjectDistinguishedName(objectClass objectCls,
            returnType returnValue,
            string objectName,
            string LdapDomain)
        {
            string distinguishedName = string.Empty;
            string connectionPrefix = "LDAP://" + LdapDomain;
            DirectoryEntry entry = Utility.NewDirectoryEntry(connectionPrefix);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            switch (objectCls)
            {
                case objectClass.user:
                    mySearcher.Filter = "(&(objectClass=user)(|(cn=" + objectName + ")(sAMAccountName=" + objectName + ")))";
                    break;
                case objectClass.group:
                    mySearcher.Filter = "(&(objectClass=group)(|(cn=" + objectName + ")(dn=" + objectName + ")))";
                    break;
            }
            SearchResult result = mySearcher.FindOne();

            if (result == null)
            {
                throw new NullReferenceException("unable to locate the distinguishedName for the object " +
                                                    objectName + " in the " + LdapDomain + " domain");
            }
            DirectoryEntry directoryObject = result.GetDirectoryEntry();
            if (returnValue.Equals(returnType.distinguishedName))
            {
                distinguishedName = "LDAP://" + directoryObject.Properties["distinguishedName"].Value;
            }
            if (returnValue.Equals(returnType.ObjectGUID))
            {
                distinguishedName = directoryObject.Guid.ToString();
            }
            entry.Close();
            entry.Dispose();
            mySearcher.Dispose();
            return distinguishedName;
        }
 internal bool checkGroupExists(string groupName)
 {
     checkConnection();
     DirectorySearcher mySearcher = new DirectorySearcher(entry);
     mySearcher.Filter = "(&(objectClass=group)(name=" + groupName + "))";
     SearchResultCollection resultSet = mySearcher.FindAll();
     mySearcher.Dispose();
     return resultSet.Count > 0;
 }
        public string ResolveUsernameToLookupValue(string username, string staffInfoLookupKey)
        {
            if (lookupValuesByUsername.ContainsKey(username))
                return lookupValuesByUsername[username];

            DirectorySearcher search = null;
            string ldapLookupValue = null;
            string ldapLookupKey = null;
            try
            {
                ldapLookupKey = GetLdapLookupKey();

                search = new DirectorySearcher(SearcherEntry)
                            {
                                Filter = "(" + LdapUsernameProperty + "=" + username + ")"
                            };
                search.PropertiesToLoad.Add(ldapLookupKey);

                var result = search.FindOne();

                if (result == null)
                    return null;

                if (!result.Properties.Contains(ldapLookupKey))
                    throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(NoPropertyReturnedFormat, ldapLookupKey, username))) { Name = username };

                if (result.Properties[ldapLookupKey].Count == 0)
                    throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(EmptyPropertyCollectionFormat, ldapLookupKey, username))) { Name = username };

                var resultValue = result.Properties[ldapLookupKey][0];
                if (resultValue is string)
                {
                    ldapLookupValue = (string)resultValue;
                }
                else if (resultValue is byte[])
                {
                    //LDAP can return a few different types. If it's a byte[], it's probably because ldapLookupKey is objectsid.  Convert the byte[] to a SID.
                    var sid = new System.Security.Principal.SecurityIdentifier((byte[]) (resultValue), 0);
                    ldapLookupValue = sid.ToString();
                }
                else
                {
                    throw new InvalidCastException("The type of the Property is " + resultValue.GetType() + " and it needs to be a string or a SID.");
                }

                ldapLookupValue = ldapLookupValue.ToLower();

                lookupValuesByUsername[username] = ldapLookupValue;
            }
            finally
            {
                if (search != null)
                    search.Dispose();
            }

            if (string.IsNullOrEmpty(ldapLookupValue))
                throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(BlankValueReturnedFormat, ldapLookupKey, username))) { Name = username };

            return ldapLookupValue;
        }
Exemple #20
0
        /// <summary>
        /// Verifica si el usuario existe.- 
        /// </summary>
        /// <param name="userName">Nombre de loging de usuario</param>
        /// <returns></returns>
        public bool User_Exists(string userName)
        {

            //create instance fo the direcory searcher
            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);

            //set the search filter
            //deSearch.Filter = "(&(objectClass=user) (cn=" + FilterOutDomain(userName) + "))";
            //deSearch.Filter = string.Format("(&(objectClass=user)(sAMAccountName= {0} ))", FilterOutDomain(userName));
            deSearch.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", userName);
            //find the first instance
            SearchResultCollection results = deSearch.FindAll();

            if (results.Count == 0)
            {
                deSearch.Dispose();
                return false;
            }
            else
            {
                return true;
            }

        }
Exemple #21
0
        /// <summary>
        /// Obtiene un usuario por nombre sin tener en cuenta las credenciales del usuario
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        DirectoryEntry Person_Get(string userName)
        {

            DirectoryEntry userDirectoryEntry = null;
            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
            deSearch.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", userName);


            deSearch.CacheResults = false;
            //deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            SearchResult results = deSearch.FindOne();

            //si result no es nulo se puede crear una DirectoryEntry
            if (results != null)
                userDirectoryEntry = new DirectoryEntry(results.Path);


            deSearch.Dispose();
            return userDirectoryEntry;

        }
Exemple #22
0
        /// <summary>
        /// Obtiene un usuario por nombre sin tener en cuenta las credenciales del usuario
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        DirectoryEntry User_Get(string userName)
        {

            DirectoryEntry userDirectoryEntry = null;
            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
         
            deSearch.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))",FilterOutDomain(userName));
            
            //deSearch.Filter = "(&(objectClass=user)(cn=" + FilterOutDomain(userName) + "))";
            
            deSearch.CacheResults = false;
            deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            SearchResult results = deSearch.FindOne();

            //si result no es nulo se puede crear una DirectoryEntry
            if (results != null)
                userDirectoryEntry = new DirectoryEntry(results.Path);


            deSearch.Dispose();
            return userDirectoryEntry;

        }
Exemple #23
0
        /// <summary>
        /// Checks if a userprincipalname exists
        /// </summary>
        /// <param name="userPrincipalName"></param>
        /// <returns></returns>
        private bool DoesUserPrincipalNameExist(string userPrincipalName)
        {
            DirectoryEntry de = null;
            DirectorySearcher ds = null;

            try
            {
                logger.Debug("Attempting to find out if userprincipalname exists " + userPrincipalName);

                de = new DirectoryEntry("LDAP://" + this.domainController, this.username, this.password);
                ds = new DirectorySearcher(de);
                ds.SearchScope = SearchScope.Subtree;
                ds.Filter = string.Format("(userPrincipalName={0})", userPrincipalName);

                if (ds.FindOne() != null)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                this.logger.Error("Error checking if user exists " + userPrincipalName, ex);

                throw;
            }
            finally
            {
                if (ds != null)
                    ds.Dispose();

                if (de != null)
                    de.Dispose();
            }
        }
Exemple #24
0
        /// <summary>
        /// Obtiene un ADGroup que reprecenta un grupo 
        /// </summary>
        /// <param name="pName"></param>
        /// <returns></returns>
        public ADGroup Group_GetByName(String pName)
        {
            string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "group", pName);

            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
            deSearch.Filter = filter;
            SearchResult result = deSearch.FindOne();
            if (result == null) return null;
            DirectoryEntry directoryEntry = result.GetDirectoryEntry();

            ADGroup wADGroup = new ADGroup(directoryEntry);
            directoryEntry.Close();
            directoryEntry.Dispose();
            deSearch.Dispose();
            return wADGroup;

        }
Exemple #25
0
        /// <summary>
        /// Find an availble sAMAccountName
        /// It loops and appends a number to the end of a sAMAccountNAme if the original doesn't exist
        /// </summary>
        /// <param name="userPrincipalName"></param>
        /// <returns></returns>
        private string GetAvailableSamAccountName(string userPrincipalName)
        {
            DirectoryEntry de = null;
            DirectorySearcher ds = null;

            try
            {
                logger.Debug("Attempting to find an available sAMAccountName for " + userPrincipalName);

                // Get the first part of the user principal name
                string upnFirstPart = userPrincipalName.Split('@')[0];
                string sAMAccountName = upnFirstPart;

                de = new DirectoryEntry("LDAP://" + this.domainController, this.username, this.password);
                ds = new DirectorySearcher(de);
                ds.SearchScope = SearchScope.Subtree;
                ds.Filter = string.Format("(&(objectClass=User)(sAMAccountName={0}))", upnFirstPart);

                int count = 0;
                while (ds.FindOne() != null)
                {
                    count++;

                    sAMAccountName = string.Format("{0}{1}", upnFirstPart, count.ToString());

                    ds.Filter = string.Format("(&(objectClass=User)(sAMAccountName={0}))", sAMAccountName);
                }

                // We found our available sAMAccountName
                return sAMAccountName;
            }
            catch (Exception ex)
            {
                this.logger.Error("Error retrieving user information " + userPrincipalName, ex);

                throw;
            }
            finally
            {
                if (ds != null)
                    ds.Dispose();

                if (de != null)
                    de.Dispose();
            }
        }
Exemple #26
0
        /// <summary>
        /// Obtiene todo los grupos pertenecientes al dominio.-
        /// </summary>
        public List<ADGroup> Groups_GetAll()
        {
            List<ADGroup> pList = null;


            ADGroup group = null;
            pList = new List<ADGroup>();
            DirectoryEntry wDirectoryEntry = null;
            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
            deSearch.Filter = "(&(objectClass=group))";
            deSearch.Sort.PropertyName = "sAMAccountName";
            deSearch.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;

            try
            {
                foreach (SearchResult result in deSearch.FindAll())
                {
                    wDirectoryEntry = result.GetDirectoryEntry();

                    //GetProperties(wDirectoryEntry, "pQuery");
                    if (wDirectoryEntry.Properties.Contains("sAMAccountName"))
                    {
                        group = new ADGroup(wDirectoryEntry);
                        pList.Add(group);
                    }
                }

                wDirectoryEntry.Close();
                wDirectoryEntry.Dispose();
                deSearch.Dispose();
                return pList;
            }
            catch (Exception ex)
            {
                throw ProcessActiveDirectoryException(ex);
            }

        }
Exemple #27
0
        /// <summary>
        /// Obtiene todo los usuarios pertenecientes al dominio.-
        /// Busca por cn nombre@mail retorna el sAMAccountName ejemplo: moviedo
        /// </summary>
        List<String> User_SearchGroupStringList(String userName)
        {
            DirectoryEntry directoryEntryUser = null;
            List<String> list = null;
            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
            deSearch.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", userName);
            try
            {
                
                SearchResult result = deSearch.FindOne();


                if (result != null)
                {
                    directoryEntryUser = result.GetDirectoryEntry();
                    list = new List<String>();
                    foreach (string grouInfo in directoryEntryUser.Properties["memberOf"])
                    {
                        foreach (string g in GetGroupFromMemberOf(grouInfo))
                        {
                            list.Add(g);
                        }
                    }
                    directoryEntryUser.Close();
                    directoryEntryUser.Dispose();
                }
                deSearch.Dispose();
                return list;
            }
            catch (Exception ex)
            {
                throw ProcessActiveDirectoryException(ex);
            }
        }
Exemple #28
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns>
        /// <see langword="true"/> if the task ran successfully; otherwise <see langword="false"/>.
        /// </returns>
        public override bool Execute()
        {
            try
            {
                _userName = Environment.UserName;
                _domainName = Environment.UserDomainName;

                DirectoryEntry userEntry = null;
                DirectorySearcher searcher = new DirectorySearcher();
                try
                {
                    // Try to retrieve user information from Active Directory if possible.
                    searcher.Filter = string.Format("(SAMAccountName={0})", _userName);
                    userEntry = searcher.FindOne().GetDirectoryEntry();

                    if (userEntry != null)
                    {
                        _firstName = userEntry.Properties["givenName"][0].ToString();
                        _lastName = userEntry.Properties["sn"][0].ToString();
                        _middleInitial = userEntry.Properties["initials"][0].ToString();
                        _email = userEntry.Properties["mail"][0].ToString();
                        _phone = userEntry.Properties["telephoneNumber"][0].ToString();
                    }
                }
                catch
                {
                    Log.LogWarning(Properties.Resources.ActiveDirectoryLookupException, UserNameWithDomain);
                }
                finally
                {
                    searcher.Dispose();
                    if (userEntry != null) { userEntry.Dispose(); }
                }

                return true;
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
                return false;
            }
        }
        public string ResolveLookupValueToUsername(string lookupValue)
        {
            DirectorySearcher search = null;

            try
            {
                var ldapLookupKey = GetLdapLookupKey();

                search = new DirectorySearcher(SearcherEntry)
                {
                    Filter = "(" + ldapLookupKey + "=" + lookupValue + ")"
                };
                search.PropertiesToLoad.Add(LdapUsernameProperty);

                SearchResult result = search.FindOne();

                if (result == null)
					throw new InvalidOperationException(String.Format("Ldap directory returned no results for query: '({0}={1})'", ldapLookupKey, lookupValue));

                // Property names are keyed in lower case by System.DirectoryServices
                string username = (string)result.Properties[LdapUsernameProperty.ToLower()][0];

                if (String.IsNullOrWhiteSpace(username))
					throw new InvalidOperationException(String.Format("Ldap directory returned results for query: '({0}={1})' but the first result value was null or an empty string.", ldapLookupKey, lookupValue));
                
                if (lookupValuesByUsername.ContainsKey(username))
                    lookupValuesByUsername[username] = lookupValue;

                return username;
            }
            finally
            {
                if (search != null)
                    search.Dispose();
            }
        }
Exemple #30
0
        /// <summary>
        /// Retorna la lista de usuarios pertenecientes a un determinado grupo
        /// </summary>
        /// <param name="groupName">Nombre del grupo</param>
        /// <returns></returns>
        public List<ADUser> Users_SearchByGroupName(String groupName)
        {

            List<ADUser> userlist = new List<ADUser>();
            ADUser wADUser = null;
            DirectoryEntry directoryEntryUser = null;
            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
            //deSearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";
            deSearch.Filter = string.Format("(&(objectClass=group)(SAMAccountName={0}))", groupName);
            try
            {
               

                SearchResult results = deSearch.FindOne();
                if (results != null)
                {

                    DirectoryEntry deGroup = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);

                    System.DirectoryServices.PropertyCollection pColl = deGroup.Properties;

                    int count = pColl["member"].Count;



                    for (int i = 0; i < count; i++)
                    {

                        string respath = results.Path;

                        string[] pathnavigate = respath.Split("CN".ToCharArray());

                        respath = pathnavigate[0];

                        string objpath = pColl["member"][i].ToString();

                        string path = string.Concat(respath, objpath);

                        directoryEntryUser = new DirectoryEntry(path, LDAPUser, LDAPPassword);

                        wADUser = new ADUser(directoryEntryUser);

                        userlist.Add(wADUser);

                        directoryEntryUser.Close();
                        directoryEntryUser.Dispose();

                    }
                    deGroup.Close();
                    deGroup.Dispose();

                }
                deSearch.Dispose();
                return userlist;

            }

            catch (Exception ex)
            {
                throw ProcessActiveDirectoryException(ex);
            }



        }
Exemple #31
0
        public static List<string> ListOU(string name)
        {
            List<string> ous = new List<string>();
            using (DirectoryEntry root = new DirectoryEntry("LDAP://" + name))
            {
                DirectorySearcher searcher = new DirectorySearcher(root);
                searcher.Filter = "(&(objectClass=organizationalUnit))";
                searcher.SearchScope = SearchScope.Subtree;
                searcher.PropertiesToLoad.Add("distinguishedName");

                var result = searcher.FindAll();
                foreach (SearchResult entry in result)
                {
                    ous.Add(entry.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString());
                }

                result.Dispose();
                searcher.Dispose();
            }
            return ous;
        }
Exemple #32
0
        /// <summary>
        /// Retorna una lista de usuarios cuyo nombre comiense con fname.-
        /// Ejemplo: evel*
        /// </summary>
        /// <param name="fName"></param>
        /// <returns></returns>
        public List<ADUser> Users_Search_StartName(string fName)
        {
            List<ADUser> userlist = new List<ADUser>();
            DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
            deSearch.Asynchronous = true;
            deSearch.CacheResults = true;

            //string filter = string.Format("(givenName={0}*", fName);
            //filter = "(&(objectClass=user)(objectCategory=person)" + filter + ")";


            deSearch.Filter = string.Format("(&(objectClass=user)(objectCategory=person)(givenName={0}*))", fName); 
            try
            {
                SearchResultCollection userCollection = deSearch.FindAll();

                foreach (SearchResult users in userCollection)
                {
                    DirectoryEntry userEntry = new DirectoryEntry(users.Path, LDAPUser, LDAPPassword);
                    userlist.Add(new ADUser(userEntry));
                }
                deSearch.Dispose();
                return userlist;
            }
            catch (Exception ex)
            {
                throw ProcessActiveDirectoryException(ex);
            }
        }