コード例 #1
0
        private SearchResultCollection GetUsers()
        {
            DirectoryEntry    myLdapConnection = null;
            DirectorySearcher search           = null;

            try {
                myLdapConnection         = new DirectoryEntry(PrefC.GetString(PrefName.DomainLoginPath));
                search                   = new DirectorySearcher(myLdapConnection);
                search.PageSize          = 10_000;     //When PageSize is not set, it limits results to 1000. With PageSize set, that limit is ignored.
                search.Filter            = "(&(objectClass=user)(objectCategory=person))";
                search.Sort.PropertyName = _fields[0]; //by default sort results by the first field
                for (int i = 0; i < _fields.Length; i++)
                {
                    search.PropertiesToLoad.Add(_fields[i]);
                }
                return(search.FindAll());
            }
            catch (Exception ex) {
                MessageBox.Show(Lan.g(this, "An error occurred fetching domain users: ") + " " + ex.Message);
                return(null);
            }
            finally {
                myLdapConnection?.Dispose();
                search?.Dispose();
            }
        }
コード例 #2
0
        //_________________________________________________________________________________________________________
        //_________________________________________________________________________________________________________
        public bool DeleteEntry(string cn)
        {
            if (Row["Writable"].ToString().ToLower() != "yes")
            {
                if (Row["Writable"].ToString().ToLower() == "ask")
                {
                    if (MessageBox.Show("Content will be modified. \nAre you sure?", "ALERT", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            Dictionary <string, Dictionary <string, string> > salida = new Dictionary <string, Dictionary <string, string> >();
            DirectorySearcher oDs = new DirectorySearcher(rootDE);

            oDs.SearchScope = SearchScope.Subtree;
            oDs.PageSize    = 1000;
            oDs.Filter      = "(cn=" + cn + ")";
            oDs.PropertiesToLoad.Add("distinguishedName");
            oDs.PropertiesToLoad.Add("+");
            SearchResultCollection results = oDs.FindAll();

            if (results.Count > 1)
            {
                MessageBox.Show("There are " + results.Count + " objects with the same CN [" + cn + "]. It is not possible in LAB. Firstly you have to delete one of them manually.", "ALERT", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                oDs.Dispose();
                return(false);
            }
            foreach (SearchResult r in results)
            {
                string         resultDN = r.Properties["distinguishedName"][0].ToString();
                DirectoryEntry de       = LoadEntry(resultDN);
                DirectoryEntry dp       = de.Parent;
                try { dp.Children.Remove(de); }
                catch (Exception ex) { LogHelper.Msg(ex.Message); }
            }
            oDs.Dispose();
            return(true);
        }
コード例 #3
0
        private List <DirectoryEntry> Search(DirectoryEntry root, string filter, SearchScope scope)
        {
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }
            using (HostingEnvironment.Impersonate())
            {
                DirectorySearcher          directorySearcher = null;
                IEnumerable <SearchResult> result            = null;
                List <DirectoryEntry>      list = new List <DirectoryEntry>();
                try
                {
                    // create directory searcher

                    directorySearcher = new DirectorySearcher(root);
                    // PageSize = 1000 for receiving all (more then default 1000) results
                    directorySearcher.PageSize        = 1000;
                    directorySearcher.SearchScope     = scope;
                    directorySearcher.ReferralChasing = ReferralChasingOption.All;

                    if (!String.IsNullOrEmpty(filter))
                    {
                        directorySearcher.Filter = filter;
                    }

                    //search
                    result = SafeFindAll(directorySearcher);

                    //enumerating

                    foreach (SearchResult entry in result)
                    {
                        list.Add(entry.GetDirectoryEntry());
                    }
                }
                catch (ArgumentException e)
                {
                    log.InfoFormat("Wrong filter. {0}", e);
                    throw new ArgumentException(e.Message);
                }
                catch (Exception e)
                {
                    log.ErrorFormat("Internal error {0}", e);
                }
                finally
                {
                    if (directorySearcher != null)
                    {
                        directorySearcher.Dispose();
                    }
                }
                return(list);
            }
        }
コード例 #4
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);
          }
      }
コード例 #5
0
ファイル: Program.cs プロジェクト: Rafael-Evan/MilanCorp.API
        static void Main(string[] args)
        {
            var userName = "******";
            var password = "******";

            //active directory properties attribute names
            string propUsername  = "******";
            string propFirstName = "givenName";
            string propLastName  = "sn";
            string propMail      = "mail";

            using (DirectoryEntry entry = new DirectoryEntry("LDAP://192.168.0.200/DC=milan,DC=local", "milan" + "\\" + userName, password))
            {
                using (DirectorySearcher searcher = new DirectorySearcher(entry))
                {
                    searcher.Filter = String.Format("({0}={1})", SAMAccountNameAttribute, userName);
                    searcher.PropertiesToLoad.Add(propUsername);
                    searcher.PropertiesToLoad.Add(propFirstName);
                    searcher.PropertiesToLoad.Add(propLastName);
                    searcher.PropertiesToLoad.Add(propMail);

                    //Set Search Options
                    searcher.SearchScope = SearchScope.Subtree;
                    searcher.SearchRoot.AuthenticationType = AuthenticationTypes.Secure;
                    searcher.PageSize = 100;

                    var result = searcher.FindOne();
                    {
                        //get poperties and write them to the console
                        if (result.Properties.Contains(propUsername) && result.Properties.Contains(propMail))
                        {
                            Console.WriteLine("Full Name: " + result.Properties[propFirstName][0]);
                            Console.WriteLine("User Name: " + result.Properties[propUsername][0]);
                            Console.WriteLine("Email: " + result.Properties[propMail][0]);
                        }
                    }
                    //release resources
                    searcher.Dispose();
                    searcher.Dispose();
                }
            }
        }
コード例 #6
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_searcher != null)
         {
             _searcher.Dispose();
             _searcher = null;
         }
     }
 }
コード例 #7
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=" + ADWrapper.FilterOutDomain(userName) + "))";
          deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
          SearchResult rs = deSearch.FindOne();

          deSearch.Dispose();
          return(rs);
      }
コード例 #8
0
        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();
        }
コード例 #9
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            tsLabel.Text = "Поиск...";
            Application.DoEvents();
            lvUsers.Items.Clear();
            try
            {
                String _strfilter = string.Empty;
                switch (Filter)
                {
                case 1: _strfilter = string.Format("(&((objectClass=user)(|(name={0}*)(sAMAccountName={0}*)(mail={0}*)))", tbUser.Text); break;

                case 2: _strfilter = string.Format("(&((objectClass=group)(name={0}*)))", tbUser.Text); break;

                default: _strfilter = string.Format("(&(|(objectClass=user)(objectClass=group))(|(name={0}*)(sAMAccountName={0}*)(mail={0}*)))", tbUser.Text); break;
                }
                DirectorySearcher      DirSearch    = new DirectorySearcher(rootEntry, _strfilter);
                SearchResultCollection SearchResult = DirSearch.FindAll();
                //ArrayList PathArr = new ArrayList();
                foreach (SearchResult SearchRes in SearchResult)
                {
                    ListViewItem lvi = new ListViewItem(SearchRes.GetDirectoryEntry().Properties["name"].Value.ToString());
                    try
                    {
                        lvi.Tag = SearchRes.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString();
                        lvi.SubItems.Add(SearchRes.GetDirectoryEntry().Properties["sAMAccountName"].Value.ToString());
                    }
                    catch { }
                    try
                    {
                        lvi.SubItems.Add(SearchRes.GetDirectoryEntry().Properties["mail"].Value.ToString());
                    }
                    catch
                    {
                        lvi.SubItems.Add("");
                    }
                    try
                    {
                        lvi.SubItems.Add(ConvertSidToString((byte[])SearchRes.GetDirectoryEntry().Properties["objectSid"].Value));
                    }
                    catch {
                        lvi.SubItems.Add("");
                    }
                    //PathArr.Add(SearchRes.GetDirectoryEntry().Path);
                    lvUsers.Items.Add(lvi);
                }
                DirSearch.Dispose();
            }
            catch (Exception ee) {
                MessageBox.Show(ee.Message);
            }
            tsLabel.Text = string.Format("{0} объекта(ов) найдено", lvUsers.Items.Count);
        }
コード例 #10
0
        public UserModel GetUserDetails(string username)
        {
            string filter = $"(&(objectClass=user)(sAMAccountName={username}))";//$ puts allows to use username syntax

            Console.WriteLine($"Searching {username}");

            DirectoryEntry directory = new DirectoryEntry("LDAP://DC=ryhma1,DC=local", _adminLogin.Username, _adminLogin.Password);//LDAP polku

            directory.AuthenticationType = AuthenticationTypes.Secure;

            DirectorySearcher searcher = new DirectorySearcher(directory, filter);

            searcher.SearchScope = SearchScope.Subtree;    //from what level of the branches are we looking from

            var            result    = searcher.FindOne(); //put result if found
            DirectoryEntry de        = null;
            UserModel      userModel = new UserModel();

            if (null != result)
            {
                de = result.GetDirectoryEntry();

                userModel.Osoite       = (de.Properties["StreetAddress"].Value ?? "Not found").ToString();
                userModel.Email        = (de.Properties["mail"].Value ?? "Not found").ToString();
                userModel.EmployeeType = (de.Properties["employeeType"].Value ?? "Not found").ToString();
                userModel.Nimi         = (de.Properties["givenName"].Value ?? "Not found").ToString();
                userModel.Sukunimi     = (de.Properties["sn"].Value ?? "Not found").ToString();
                userModel.Username     = de.Properties["sAMAccountName"].Value.ToString();



                // ViewBag.data = result.Path;

                /*
                 * foreach (var item in de.Properties.PropertyNames)
                 * {
                 *   //Console.Write($"\n{item}");
                 *   //ViewBag.data += $"\n{item}";
                 *   data += $"\n{item}";
                 *   foreach (var val in de.Properties[item.ToString()])
                 *   {
                 *       // Console.Write($"\n{val}");
                 *       //ViewBag.data += $"\n{val}";
                 *       data += $"\n{val}";
                 *   }
                 * }
                 */
            }

            searcher.Dispose();
            directory.Dispose();
            return(userModel);
        }
コード例 #11
0
        /// <summary>
        /// 获取用户帐号列表
        /// </summary>
        /// <param name="find"> 部门 </param>
        /// <returns>用户帐号列表集合</returns>
        public List <ADUserInfo> getADUserInfo_Unit(string find)
        {
            DirectoryEntry    de = new DirectoryEntry(path, Userid, Password);
            DirectorySearcher ds = new DirectorySearcher(de);

            ds.Filter = "(&(objectClass=user))";
            List <ADUserInfo> ls_ADUserInfo = new List <ADUserInfo>();

            try
            {
                foreach (System.DirectoryServices.SearchResult resEnt in ds.FindAll())
                {
                    DirectoryEntry user = resEnt.GetDirectoryEntry();
                    if (user.Properties["Distinguishedname"].Value.ToString().IndexOf(find.Trim()) >= 0)
                    {
                        ADUserInfo aduser = new ADUserInfo();
                        aduser.Co         = user.Properties["Co"].Value != null ? user.Properties["Co"].Value.ToString() : "";
                        aduser.St         = user.Properties["St"].Value != null ? user.Properties["St"].Value.ToString() : "";
                        aduser.L          = user.Properties["L"].Value != null ? user.Properties["L"].Value.ToString() : "";
                        aduser.Company    = user.Properties["Company"].Value != null ? user.Properties["Company"].Value.ToString() : "";
                        aduser.DepartMent = user.Properties["DepartMent"].Value != null ? user.Properties["DepartMent"].Value.ToString() : "";
                        aduser.Physicaldeliveryofficename = user.Properties["Physicaldeliveryofficename"].Value != null ? user.Properties["Physicaldeliveryofficename"].Value.ToString() : "";
                        aduser.Streetaddress = user.Properties["Streetaddress"].Value != null ? user.Properties["Streetaddress"].Value.ToString() : "";
                        aduser.Postalcode    = user.Properties["Postalcode"].Value != null ? user.Properties["Postalcode"].Value.ToString() : "";

                        aduser.Cn                       = user.Properties["Cn"].Value != null ? user.Properties["Cn"].Value.ToString() : "";
                        aduser.Displayname              = user.Properties["Displayname"].Value != null ? user.Properties["Displayname"].Value.ToString() : "";
                        aduser.SAMAccountName           = user.Properties["SAMAccountName"].Value != null ? user.Properties["SAMAccountName"].Value.ToString() : "";
                        aduser.Sn                       = user.Properties["Sn"].Value != null ? user.Properties["Sn"].Value.ToString() : "";
                        aduser.Givenname                = user.Properties["Givenname"].Value != null ? user.Properties["Givenname"].Value.ToString() : "";
                        aduser.Title                    = user.Properties["Title"].Value != null ? user.Properties["Title"].Value.ToString() : "";
                        aduser.Mail                     = user.Properties["Mail"].Value != null ? user.Properties["Mail"].Value.ToString() : "";
                        aduser.TelephoneNumber          = user.Properties["TelephoneNumber"].Value != null ? user.Properties["TelephoneNumber"].Value.ToString() : "";
                        aduser.Mobile                   = user.Properties["Mobile"].Value != null ? user.Properties["Mobile"].Value.ToString() : "";
                        aduser.Facsimiletelephonenumber = user.Properties["Facsimiletelephonenumber"].Value != null ? user.Properties["Facsimiletelephonenumber"].Value.ToString() : "";

                        aduser.Distinguishedname = user.Properties["Distinguishedname"].Value != null ? user.Properties["Distinguishedname"].Value.ToString() : "";

                        ls_ADUserInfo.Add(aduser);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ds.Dispose();
                de.Dispose();
            }
            return(ls_ADUserInfo);
        }
コード例 #12
0
        public User GetADUser(string lanID)
        {
            try
            {
                User users = new User();
                try
                {
                    string pathNameDomain = string.Format("LDAP://{0}", domainServer);

                    var direcotyEntry = new DirectoryEntry(pathNameDomain);


                    var directorySearcher = new DirectorySearcher(direcotyEntry)
                    {
                        Filter = "(&(objectClass=user)(sAMAccountName=" + lanID + "))"
                    };

                    var          searchResults = directorySearcher.FindAll();
                    SearchResult result;
                    if (searchResults != null)
                    {
                        for (int counter = 0; counter < searchResults.Count; counter++)
                        {
                            result = searchResults[counter];
                            if (result.Properties["samaccountname"].Count != 0 && result.Properties["givenname"].Count != 0 &&
                                result.Properties["sn"].Count != 0 && result.Properties["title"].Count != 0 && result.Properties["mail"].Count != 0)
                            {
                                users.UserId   = (String)result.Properties["samaccountname"][0];
                                users.UserName = (String)result.Properties["givenname"][0] + " " + (String)result.Properties["sn"][0];
                            }
                        }
                    }

                    direcotyEntry.Dispose();
                    directorySearcher.Dispose();
                    searchResults.Dispose();
                }
                catch (InvalidOperationException iOe)
                {
                }
                catch (NotSupportedException nSe)
                {
                }
                finally
                {
                }
                return(users);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #13
0
        public MainWindow()
        {
            InitializeComponent();

            List <string> ComputerNames = new List <string>();

            DirectoryEntry    entry      = new DirectoryEntry("LDAP://OU=Moscow,DC=class,DC=mfua,DC=ru");
            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            mySearcher.Filter    = ("(objectClass=computer)");
            mySearcher.SizeLimit = int.MaxValue;
            mySearcher.PageSize  = int.MaxValue;

            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z]+-\d{1,3}-\d{1,4}-\d{1,4}\b$");

            Char delimiter = '-';

            foreach (SearchResult resEnt in mySearcher.FindAll())
            {
                string ComputerName = resEnt.GetDirectoryEntry().Name;

                if (ComputerName.StartsWith("CN=" + curCompName.Split(delimiter)[0] + "-" + curCompName.Split(delimiter)[1] + "-" + curCompName.Split(delimiter)[2]))
                {
                    ComputerName = ComputerName.Remove(0, "CN=".Length);
                }
                if (reg.IsMatch(ComputerName))
                {
                    ComputerNames.Add(ComputerName);
                }
            }

            mySearcher.Dispose();
            entry.Dispose();

            using (System.IO.StreamWriter sw = System.IO.File.CreateText(FILE_SETTINGS))
            {
                sw.WriteLine("<?xml version=\"1.0\"?>");
                sw.WriteLine("<!DOCTYPE italc-config-file>");
                sw.WriteLine("<globalclientconfig version=\"3.0.1\">");
                sw.WriteLine("<body>");
                sw.WriteLine("<classroom name=\"" + curCompName.Split(delimiter)[0] + "-" + curCompName.Split(delimiter)[1] + "-" + curCompName.Split(delimiter)[2] + "\">");

                foreach (var item in ComputerNames)
                {
                    sw.WriteLine("<client mac=\"\" name=\"\" hostname=\"" + item + "\" id=\"\" type=\"1\"/>");
                }

                sw.WriteLine("</classroom>");
                sw.WriteLine("</body>");
                sw.WriteLine("</globalclientconfig>");
            }
            return;
        }
コード例 #14
0
        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);
        }
        /// <summary>
        /// Hàm lấy thông tin các OU trong Domain mà Computer này đang tham gia
        /// </summary>
        /// <returns>
        /// Trả về List chứa các OU
        /// </returns>
        private static List <string> getOU()
        {
            List <string>     list      = new List <string>();
            DirectorySearcher dSearcher = new DirectorySearcher(dEntry);

            dSearcher.Filter = "(&(objectClass=organizationalUnit))";
            foreach (SearchResult result in dSearcher.FindAll())
            {
                list.Add(TextProcessing.getProperty(result, "ou"));
            }
            dSearcher.Dispose();
            return(list);
        }
コード例 #16
0
 public void Dispose()
 {
     if (directory != null)
     {
         directory.Dispose();
         directory = null;
     }
     if (dirSearcher != null)
     {
         dirSearcher.Dispose();
         dirSearcher = null;
     }
 }
コード例 #17
0
 /// <summary>
 /// Disposes of the objects
 /// </summary>
 /// <param name="Disposing">True to dispose of all resources, false only disposes of native resources</param>
 protected virtual void Dispose(bool Disposing)
 {
     if (Entry != null)
     {
         Entry.Close();
         Entry.Dispose();
         Entry = null;
     }
     if (Searcher != null)
     {
         Searcher.Dispose();
         Searcher = null;
     }
 }
コード例 #18
0
ファイル: Ldap.cs プロジェクト: MyDevsWorks/NetCoreLDAPModule
        /// <summary>
        /// Search for items on the LDAP.
        /// </summary>
        /// <param name="distinguished_name">The DN or we want to do our research.</param>
        /// <param name="query">The filter of the search.</param>
        /// <param name="propertiesToLoad">The properties to load objects.</param>
        /// <returns>A dynamic instance list.</returns>
        public IEnumerable <dynamic> Search(string distinguished_name, string query, string[] properties_to_load = null)
        {
            // Setting up the connection to the ldap.
            DirectoryEntry connection = this.Connect(distinguished_name);
            // Research and translation of the result.
            DirectorySearcher     search = properties_to_load == null ? new DirectorySearcher(connection, query) : new DirectorySearcher(connection, query, properties_to_load);
            IEnumerable <dynamic> result = this.TranslateResult(search.FindAll(), properties_to_load);

            // Closing the connections to the server.
            search.Dispose();

            // Return of the results.
            return(result);
        }
コード例 #19
0
        protected virtual void Dispose(bool disposing)
        {
            if (!m_Disposed)
            {
                if (disposing)
                {
                    de.Dispose();
                    deSearch.Dispose();
                }

                // Unmanaged resources are released here.
                m_Disposed = true;
            }
        }
コード例 #20
0
        /// <summary>
        /// 获取组织架构列表
        /// </summary>
        /// <param name="find"> 值 </param>
        /// <param name="mode"> 参数 </param>
        /// <returns>组织架构列表集合</returns>
        public List <ADUnitInfo> getADUnitInfo_Next(string find)
        {
            DirectoryEntry    de = new DirectoryEntry(path, Userid, Password);
            DirectorySearcher ds = new DirectorySearcher(de);

            ds.Filter = "(objectClass=organizationalUnit)";

            List <ADUnitInfo> ls_ADUnitInfo = new List <ADUnitInfo>();
            List <ADUserInfo> ls_ADUserInfo = new List <ADUserInfo>();

            try
            {
                foreach (System.DirectoryServices.SearchResult resEnt in ds.FindAll())
                {
                    DirectoryEntry user = resEnt.GetDirectoryEntry();
                    if (user.Properties["Distinguishedname"].Value.ToString().IndexOf(find) >= 0)
                    {
                        ADUnitInfo aduser = new ADUnitInfo();
                        aduser.Name = user.Properties["Name"].Value != null ? user.Properties["Name"].Value.ToString() : "";
                        aduser.Distinguishedname = user.Properties["Distinguishedname"].Value != null ? user.Properties["Distinguishedname"].Value.ToString() : "";
                        aduser.Objectcategory    = user.Properties["Objectcategory"].Value != null ? user.Properties["Objectcategory"].Value.ToString() : "";
                        aduser.Whencreated       = DateTime.Parse(user.Properties["Whencreated"].Value.ToString());
                        aduser.Whenchanged       = DateTime.Parse(user.Properties["Whenchanged"].Value.ToString());

                        aduser.ADUserInfo = new List <ADUserInfo>();
                        ADUserInfo aduser3 = new ADUserInfo();
                        ls_ADUserInfo = getADUserInfo_Unit(aduser.Distinguishedname.ToString());
                        for (int i = 0; i < ls_ADUserInfo.Count; i++)
                        {
                            aduser3 = ls_ADUserInfo[i];
                            aduser.ADUserInfo.Add(aduser3);
                        }

                        aduser.NextUnit = new List <ADUnitInfo>();

                        ls_ADUnitInfo.Add(aduser);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ds.Dispose();
                de.Dispose();
            }
            return(ls_ADUnitInfo);
        }
        /// <summary>
        /// Hàm lấy thông tin các Groups trong Domain mà Computer này đang tham gia
        /// </summary>
        /// <returns>
        /// Trả về danh sách các Group
        /// </returns>
        private static List <string> getGroup()
        {
            List <string>     list      = new List <string>();
            DirectorySearcher dSearcher = new DirectorySearcher(dEntry);

            dSearcher.Filter = "(&(objectClass=group))";

            foreach (SearchResult sResult in dSearcher.FindAll())
            {
                list.Add(TextProcessing.getProperty(sResult, "cn"));
            }
            dSearcher.Dispose();
            return(list);
        }
コード例 #22
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_currentde != null)
         {
             _currentde.Dispose();
         }
         if (_ds != null)
         {
             _ds.Dispose();
         }
     }
 }
コード例 #23
0
ファイル: DE.cs プロジェクト: antigoniapower/addrbook
        public static LdapType ObtainRODC()
        {
            DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain);
            string           DCname        = "";

            using (var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext))
                using (var controller = domain.FindDomainController())
                {
                    DCname = controller.Name.Replace("." + controller.Domain.Name, "");
                }
            //MessageBox.Show(DCname);
            //string DCname = Properties.Settings.Default.DC;
            var directoryEntry = new DirectoryEntry();

            directoryEntry.AuthenticationType = AuthenticationTypes.ReadonlyServer;
            var dirSearcher = new DirectorySearcher(directoryEntry);

            try
            {
                dirSearcher.SearchScope = SearchScope.Subtree;
                //MessageBox.Show("Начало поиска");
                dirSearcher.Filter = "(&(&(sAMAccountType=805306369)(name=" + DCname + "*)))";

                SearchResult result1 = dirSearcher.FindOne();
                var          dc      = result1.GetDirectoryEntry();
                if (dc.GetProperty("primaryGroupID") == "516")
                {
                    return(LdapType.Writable);
                    //MessageBox.Show(CurLDAP.ToString());
                }
                else
                {
                    return(LdapType.ReadOnly);
                }

                //MessageBox.Show(dc.Name + '\t' + dc.GetProperty("primaryGroupID"));
                //MessageBox.Show("Конец поиска");
                //НЕ ИСПОЛЬЗУЙ ЭТУ КОНСТРУКЦИЮ!!!

                /*using (DirectoryEntry DC = new DirectoryEntry(result1.Path))
                 * {
                 *  MessageBox.Show(DCname + '\t' + DC.GetProperty("primaryGroupID"));
                 * }*/
            }
            finally
            {
                directoryEntry.Dispose();
                dirSearcher.Dispose();
            }
        }
コード例 #24
0
ファイル: ADHelp.cs プロジェクト: windygu/CommonClass
        /// <summary>
        /// 获得帐户Acc的Path
        /// </summary>
        /// <param name="sAcc">Acc</param>
        /// <returns>错误就是empty</returns>
        public static string GetAccPath(string sAcc)
        {
            DirectoryEntry    de       = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);

            deSearch.Filter      = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAcc + "))";
            deSearch.SearchScope = SearchScope.Subtree;
            try
            {
                SearchResult result = deSearch.FindOne();
                string       Apath  = result.Path;
                result = null;
                deSearch.Dispose();
                de.Dispose();
                return(Apath);
            }
            catch (Exception)
            {
                deSearch.Dispose();
                de.Dispose();
                return(string.Empty);
            }
        }
コード例 #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();
                }
            }
        }
コード例 #26
0
ファイル: ADHelper.cs プロジェクト: binCodeCW/IOT
 /// <summary>
 /// 释放资源
 /// </summary>
 public void Dispose()
 {
     if (Entry != null)
     {
         Entry.Close();
         Entry.Dispose();
         Entry = null;
     }
     if (Searcher != null)
     {
         Searcher.Dispose();
         Searcher = null;
     }
 }
コード例 #27
0
        public ActiveDirectoryUser GetUserById(string Id)
        {
            var            username       = ConfigurationManager.AppSettings["ADusername"].ToString();
            var            password       = ConfigurationManager.AppSettings["ADpassword"].ToString();
            DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://hmhc.local");

            DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);

            try
            {
                var adUser = new ActiveDirectoryUser();
                directorySearcher.Filter = "(&(objectClass=user)(objectCategory=Person)(userPrincipalName=" + Id + "@hmhc.local))";
                directorySearcher.PropertiesToLoad.Add("mail");
                directorySearcher.PropertiesToLoad.Add("cn");
                directorySearcher.PropertiesToLoad.Add("userPrincipalName");
                SearchResult searchResult = directorySearcher.FindOne();
                if (searchResult == null)
                {
                    adUser = null;
                }
                else
                {
                    adUser.Id          = searchResult.Properties["userPrincipalName"][0].ToString().Split('@')[0];
                    adUser.Description = searchResult.Properties["cn"][0].ToString();
                    adUser.Email       = searchResult.Properties["mail"][0].ToString();
                }
                directoryEntry.Close();
                directorySearcher.Dispose();
                return(adUser);
            }
            catch (Exception)
            {
                directoryEntry.Close();
                directorySearcher.Dispose();
                return(null);
            }
        }
コード例 #28
0
ファイル: Myplanner.cs プロジェクト: rpwillis/mlg
        private string GetUserMail(string userID)
        {
            SearchResultCollection resCol     = null;
            DirectorySearcher      mySearcher = null;

            try
            {
                //strip domain name from the user id
                if (userID.IndexOf("\\") != 0)
                {
                    userID = userID.Substring(userID.LastIndexOf("\\") + 1);
                }

                mySearcher = new DirectorySearcher();
                string PropertyName = "mail";
                mySearcher.PropertiesToLoad.Add(PropertyName);
                mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + userID + "))";
                resCol            = mySearcher.FindAll();

                if (resCol.Count != 1)
                {
                    Page.Response.Write("User Not Found");
                    return("");
                }

                if (resCol[0].Properties[PropertyName] == null)
                {
                    Page.Response.Write("Property mail not found");
                    return("");
                }

                if ((resCol[0].Properties[PropertyName].Count == 1))
                {
                    return(resCol[0].Properties[PropertyName][0].ToString());
                }
                else
                {
                    Page.Response.Write("User has more than 1 mail");
                    return("");
                }
            }

            finally
            {
                resCol.Dispose();
                mySearcher.Dispose();
            }
            //dirEntry.Close();
        }
コード例 #29
0
        /// <summary>
        /// receive from AD list of computers with given name
        /// </summary>
        /// <param name="comuter Name"></param>
        /// <returns>array list whith computers names</returns>
        public ArrayList GetListOfComputers(string comuterName = null)
        {
            DirectoryEntry entry = new DirectoryEntry($"LDAP://{_domainOU}");

            entry.RefreshCache();
            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            ArrayList compList = new ArrayList();

            //search parameters
            //mySearcher.Filter = $"( &(objectClass=computer)(Name=*{comuterName}*)(cn=*{comuterName}*))";

            if (comuterName == null || comuterName == "")
            {
                mySearcher.Filter = $"( &(objectClass=computer))";
            }
            else
            {
                mySearcher.Filter = $"( &(objectClass=computer)(cn=*{comuterName}*))";
            }

            mySearcher.SizeLimit = int.MaxValue;
            mySearcher.PageSize  = int.MaxValue;

            foreach (SearchResult resEnt in mySearcher.FindAll())
            {
                //"CN=SGSVG007DC"
                DirectoryEntry directoryEntry = new DirectoryEntry();
                directoryEntry = resEnt.GetDirectoryEntry();

                //string sAMAccountName = directoryEntry.Properties["sAMAccountName"].Value.ToString();
                if (IsActive(directoryEntry))
                {
                    string ComputerName = directoryEntry.Name;

                    if (ComputerName.StartsWith("CN="))
                    {
                        ComputerName = ComputerName.Remove(0, "CN=".Length);
                    }

                    compList.Add(ComputerName);
                }
            }

            mySearcher.Dispose();
            entry.Dispose();

            return(compList);
        }
コード例 #30
0
        public string BuscarUsuariosAD(Login request)
        {
            DirectoryEntry    searchRoot = null;
            DirectorySearcher searcher   = null;
            DirectoryEntry    userEntry  = null;

            var listUserAD = new List <Usuario>();

            try
            {
                string adminUser        = request.S_Usuario;
                string adminPassword    = request.S_Password;
                string container        = ConfigurationManager.AppSettings["AD_Container"].ToString();
                string domainController = ConfigurationManager.AppSettings["AD_Name"].ToString();

                searchRoot = new DirectoryEntry(String.Format("LDAP://{0}", domainController), adminUser, adminPassword);

                searcher = new DirectorySearcher(searchRoot);

                SearchResult result = searcher.FindOne();
                if (result == null)
                {
                    return("");
                }
                else
                {
                    return(request.S_Usuario);
                }
            }
            catch
            {
                return("");
            }
            finally
            {
                if (userEntry != null)
                {
                    userEntry.Dispose();
                }
                if (searcher != null)
                {
                    searcher.Dispose();
                }
                if (searchRoot != null)
                {
                    searchRoot.Dispose();
                }
            }
        }
コード例 #31
0
    private static SearchResultCollection RetrieveAllNetworkUsersFromLDAP(string sDomainName)
    {
        string sServerName = System.Configuration.ConfigurationManager.AppSettings[sDomainName].ToString();
        string sLDAPPath = "LDAP://" + sServerName + "/DC=" + sDomainName + ",DC=root01,DC=org";

        DirectoryEntry objRootDE = new DirectoryEntry(sLDAPPath, sUID, sPwd, AuthenticationTypes.Secure);
        DirectorySearcher objDS = new DirectorySearcher(objRootDE);

        objDS.Filter = "(|(&(objectClass=User)(givenname=*)(sn=*)))";
        objDS.ReferralChasing = ReferralChasingOption.None;
        objDS.PropertiesToLoad.Add("userAccountControl");
        objDS.PropertiesToLoad.Add("SAMAccountName");

        SearchResultCollection objSRC = null;
        try
        {
            objSRC = objDS.FindAll();
        }
        catch (Exception excpt)
        {
            if (excpt.Message.IndexOf("The server is not operational.") < 0)
                throw;
        }

        objDS.Dispose();
        objRootDE.Close();
        objRootDE.Dispose();
        return objSRC;
    }
コード例 #32
0
    public static DataTable LookForUserInAllDomains(string sLastNameSearch, string sFirstNameSearch)
    {
        if (sUID == "") sUID = null;
        if (sPwd == "") sPwd = null;

        CreateNetworkUserTable();
        objTable.Rows.Clear();

        ////Search in all the domains
        //string ldapdomains = System.Configuration.ConfigurationManager.AppSettings["LDAPDomains"].ToString();
        //string[] Domains = ldapdomains.Split(new char[] { ';' });

        //for (int i = 0; i < Domains.Length; i++)
        //{
        //    string domainName = Domains[i];

        //    objTable = LookForUserInDomain(domainName, sLastNameSearch, sFirstNameSearch);

        //}

        string sFilter = String.Format("(|(&(objectClass=User)(givenname={0})(sn={1})))", sFirstNameSearch, sLastNameSearch);

        // collect inactive users in all the domains
        string[] sDomains = sLDAPDomains.Split(new char[] { ';' });
        for (int i = 0; i < sDomains.Length; i++ )
        {
            string sDomainName = sDomains[ i ];
            string sServerName = System.Configuration.ConfigurationManager.AppSettings[sDomainName].ToString();
            string sLDAPPath = "LDAP://" + sServerName + "/DC=" + sDomainName + ",DC=root01,DC=org";

            DirectoryEntry objRootDE = new DirectoryEntry(sLDAPPath, sUID, sPwd, AuthenticationTypes.Secure);
            DirectorySearcher objDS = new DirectorySearcher(objRootDE);

            objDS.Filter = sFilter;
            objDS.ReferralChasing = ReferralChasingOption.None;
            objDS.PropertiesToLoad.Add("userAccountControl");
            objDS.PropertiesToLoad.Add("SAMAccountName");
            objDS.PropertiesToLoad.Add("givenName");
            objDS.PropertiesToLoad.Add("sn");
            objDS.PropertiesToLoad.Add("TelephoneNumber");
            objDS.PropertiesToLoad.Add("mail");

            SearchResultCollection objSRC = null;
            try
            {
                objSRC = objDS.FindAll();
            }
            catch (Exception excpt)
            {
                if (excpt.Message.IndexOf("The server is not operational.") < 0)
                    throw;
            }

            if (objSRC == null)
                continue;

            foreach (SearchResult objSR in objSRC)
            {
                int iInactiveFlag	= Convert.ToInt32(objSR.Properties["userAccountControl"][0]);
                string sUserId		= objSR.Properties["SAMAccountName"][0].ToString();
                string sFirstName	= objSR.Properties["givenName"][0].ToString();
                string sLastName	= objSR.Properties["sn"][0].ToString();

                string sPhone	= "";
                string sEmail	= "";

                if (objSR.Properties["TelephoneNumber"].Count > 0)
                    sPhone	= objSR.Properties["TelephoneNumber"][0].ToString();

                if( objSR.Properties["mail"].Count > 0 )
                    sEmail	= objSR.Properties["mail"][0].ToString();

                iInactiveFlag = iInactiveFlag & 0x0002;
                if (iInactiveFlag <= 0)
                {
                    // add name, username, phone and email to the table, if active
                    DataRow objRow = objTable.NewRow();

                    objRow["LastName"] = sLastName;
                    objRow["FirstName"] = sFirstName;
                    objRow["Username"] = sUserId;
                    objRow["UserDomain"] = sDomainName;
                    objRow["Phone"] = sPhone;
                    objRow["Email"] = sEmail;

                    objTable.Rows.Add( objRow );

                    continue;
                }
            }

            objSRC.Dispose();
            objDS.Dispose();
            objRootDE.Close();
            objRootDE.Dispose();
        }

        return objTable;
    }