Exemple #1
0
		/// <summary>
		/// This method will return a list of objects representing all records in the table.
		/// </summary>
		///
		/// <returns>list of objects of class ADUser in the form of object of ADUserCollection </returns>
		public ADUserCollection SelectAll()
		{
			ADUserCollection aDUserCollection = new ADUserCollection();
			foreach (POS.DataLayer.ADUser _aDUser in POS.DataLayer.ADUserBase.SelectAll())
			{
				_aDUserWCF = new ADUser();
				
				_aDUserWCF.UserID = _aDUser.UserID;
				_aDUserWCF.UserFullName = _aDUser.UserFullName;
				_aDUserWCF.UserName = _aDUser.UserName;
				_aDUserWCF.Password = _aDUser.Password;
				_aDUserWCF.GroupID = _aDUser.GroupID;
				_aDUserWCF.Email = _aDUser.Email;
				_aDUserWCF.Address = _aDUser.Address;
				_aDUserWCF.Phone = _aDUser.Phone;
				_aDUserWCF.Mobile = _aDUser.Mobile;
				
				aDUserCollection.Add(_aDUserWCF);
			}
			return aDUserCollection;
		}
Exemple #2
0
        /// <summary>
        /// This method will get row(s) from the database using the value of the field specified
        /// along with the details of the child table.
        /// </summary>
        ///
        /// <param name="pk" type="ADGroupPrimaryKey">Primary Key information based on which data is to be fetched.</param>
        ///
        /// <returns>object of class ADUserCollection</returns>
        public ADUserCollection SelectAllByForeignKeyGroupID(ADGroupPrimaryKey pk)
        {
            ADUserCollection aDUserCollection = new ADUserCollection();

            foreach (POS.DataLayer.ADUser _aDUser in POS.DataLayer.ADUserBase.SelectAllByForeignKeyGroupID(new POS.DataLayer.ADGroupPrimaryKey(pk.GroupID)))
            {
                _aDUserWCF              = new ADUser();
                _aDUserWCF.UserID       = _aDUser.UserID;
                _aDUserWCF.UserFullName = _aDUser.UserFullName;
                _aDUserWCF.UserName     = _aDUser.UserName;
                _aDUserWCF.Password     = _aDUser.Password;
                _aDUserWCF.GroupID      = _aDUser.GroupID;
                _aDUserWCF.Email        = _aDUser.Email;
                _aDUserWCF.Address      = _aDUser.Address;
                _aDUserWCF.Phone        = _aDUser.Phone;
                _aDUserWCF.Mobile       = _aDUser.Mobile;

                aDUserCollection.Add(_aDUserWCF);
            }
            return(aDUserCollection);
        }
Exemple #3
0
        /// <summary>
        /// This method will return a list of objects representing the specified number of entries from the specified record number in the table
        /// using the value of the field specified
        /// </summary>
        ///
        /// <param name="field" type="string">Field of the class ADUser</param>
        /// <param name="fieldValue" type="object">Value for the field specified.</param>
        /// <param name="fieldValue2" type="object">Value for the field specified.</param>
        /// <param name="typeOperation" type="TypeOperation">Operator that is used if fieldValue2=null or fieldValue2="".</param>
        /// <param name="orderByStatement" type="string">The field value to number.</param>
        /// <param name="pageSize" type="int">Number of records returned.</param>
        /// <param name="skipPages" type="int">The number of missing pages.</param>
        ///
        /// <returns>List of object of class ADUser in the form of an object of class ADUserCollection</returns>
        public ADUserCollection SelectByFieldPaged(string field, object fieldValue, object fieldValue2, TypeOperation typeOperation, int pageSize, int skipPages, string orderByStatement)
        {
            ADUserCollection aDUserCollection = new ADUserCollection();

            foreach (POS.DataLayer.ADUser _aDUser in POS.DataLayer.ADUserBase.SelectByFieldPaged(field, fieldValue, fieldValue2, typeOperation, pageSize, skipPages, orderByStatement))
            {
                _aDUserWCF = new ADUser();

                _aDUserWCF.UserID       = _aDUser.UserID;
                _aDUserWCF.UserFullName = _aDUser.UserFullName;
                _aDUserWCF.UserName     = _aDUser.UserName;
                _aDUserWCF.Password     = _aDUser.Password;
                _aDUserWCF.GroupID      = _aDUser.GroupID;
                _aDUserWCF.Email        = _aDUser.Email;
                _aDUserWCF.Address      = _aDUser.Address;
                _aDUserWCF.Phone        = _aDUser.Phone;
                _aDUserWCF.Mobile       = _aDUser.Mobile;

                aDUserCollection.Add(_aDUserWCF);
            }
            return(aDUserCollection);
        }
Exemple #4
0
        /// <summary>
        /// This method will return a list of objects representing the specified number of entries from the specified record number in the table.
        /// </summary>
        ///
        /// <param name="pageSize" type="int">Number of records returned.</param>
        /// <param name="skipPages" type="int">The number of missing pages.</param>
        /// <param name="orderByStatement" type="string">The field value to number.</param>
        ///
        /// <returns>list of objects of class ADUser in the form of an object of class ADUserCollection </returns>
        public ADUserCollection SelectAllPaged(int?pageSize, int?skipPages, string orderByStatement)
        {
            ADUserCollection aDUserCollection = new ADUserCollection();

            foreach (POS.DataLayer.ADUser _aDUser in POS.DataLayer.ADUserBase.SelectAllPaged(pageSize, skipPages, orderByStatement))
            {
                _aDUserWCF = new ADUser();

                _aDUserWCF.UserID       = _aDUser.UserID;
                _aDUserWCF.UserFullName = _aDUser.UserFullName;
                _aDUserWCF.UserName     = _aDUser.UserName;
                _aDUserWCF.Password     = _aDUser.Password;
                _aDUserWCF.GroupID      = _aDUser.GroupID;
                _aDUserWCF.Email        = _aDUser.Email;
                _aDUserWCF.Address      = _aDUser.Address;
                _aDUserWCF.Phone        = _aDUser.Phone;
                _aDUserWCF.Mobile       = _aDUser.Mobile;

                aDUserCollection.Add(_aDUserWCF);
            }
            return(aDUserCollection);
        }
Exemple #5
0
		/// <summary>
		/// Populates the fields for multiple objects from the columns found in an open reader.
		/// </summary>
		///
		/// <param name="rdr" type="IDataReader">An object that implements the IDataReader interface</param>
		///
		/// <returns>Object of ADUserCollection</returns>
		///
		/// <remarks>
		///
		/// <RevisionHistory>
		/// Author				Date			Description
		/// DLGenerator			3/7/2015 2:37:27 PM		Created function
		/// 
		/// </RevisionHistory>
		///
		/// </remarks>
		///
		internal static ADUserCollection PopulateObjectsFromReaderWithCheckingReader(IDataReader rdr, DatabaseHelper oDatabaseHelper) 
		{

			ADUserCollection list = new ADUserCollection();
			
            if (rdr.Read())
			{
				ADUser obj = new ADUser();
				PopulateObjectFromReader(obj, rdr);
				list.Add(obj);
				while (rdr.Read())
				{
					obj = new ADUser();
					PopulateObjectFromReader(obj, rdr);
					list.Add(obj);
				}
				oDatabaseHelper.Dispose();
				return list;
			}
			else
			{
				oDatabaseHelper.Dispose();
				return null;
			}
			
		}
Exemple #6
0
		/// <summary>
		/// Populates the fields for multiple objects from the columns found in an open reader.
		/// </summary>
		///
		/// <param name="rdr" type="IDataReader">An object that implements the IDataReader interface</param>
		///
		/// <returns>Object of ADUserCollection</returns>
		///
		/// <remarks>
		///
		/// <RevisionHistory>
		/// Author				Date			Description
		/// DLGenerator			3/7/2015 2:37:27 PM		Created function
		/// 
		/// </RevisionHistory>
		///
		/// </remarks>
		///
		internal static ADUserCollection PopulateObjectsFromReader(IDataReader rdr) 
		{
			ADUserCollection list = new ADUserCollection();
			
			while (rdr.Read())
			{
				ADUser obj = new ADUser();
				PopulateObjectFromReader(obj,rdr);
				list.Add(obj);
			}
			return list;
			
		}
        private void InitDomainTree()
        {
            if (domainInfo == null)
            {
                return;
            }
            IStrADDomain   = domainInfo.DomainName;
            IStrADPassword = domainInfo.DomainUserPassWord;
            IStrADUser     = domainInfo.DomainUserName;
            if (IStrADDomain == string.Empty || IStrADPassword == string.Empty || IStrADUser == string.Empty)
            {
                return;
            }
            string LDAPInfo = string.Format("{0}:{1}({2}:{3})", CurrentApp.GetLanguageInfo("11011602", "域账号"), IStrADUser, CurrentApp.GetLanguageInfo("11011601", "域名"), IStrADDomain);

            IListADUsers.Clear();
            List <BindItem> listItems = new List <BindItem>();

            IStrADPath = string.Format("LDAP://{0}", IStrADDomain);
            util       = new ADUtility(IStrADPath, IStrADUser, IStrADPassword);
            ClearChildren(mRoot);       //树中会清理掉list里面的部分内容
            mListDomainObjItem.Clear(); //清理剩余的内容
            try
            {
                //获取下面所有的OU
                ADGroupCollection OUs = util.GetAllOrganizationalUnit();
                foreach (ADGroup group in OUs.AllItem)
                {
                    DomainObjectItem doi = new DomainObjectItem();
                    doi.Name      = group.Name;
                    doi.FullName  = group.Name;
                    doi.mGuid     = group.Guid;
                    doi.ObjType   = 111;
                    doi.IsChecked = false;
                    doi.Icon      = "Images/org.ico";

                    DirectoryEntry de = group.MyDirectoryEntry;
                    doi.ParentGuid     = de.Parent.Guid;
                    doi.ParentName     = de.Parent.Name.Substring(3);
                    doi.ParentFullName = doi.ParentName;
                    mListDomainObjItem.Add(doi);
                }
                //获取下面所有用户
                ADUserCollection Users = util.GetAllUsers();
                foreach (ADUser user in Users)
                {
                    //判断用户是否禁用
                    int    ControlCode     = user.UserAccountControl;
                    string UserControlCode = Convert.ToString(ControlCode, 2);
                    UserControlCode = UserControlCode.Substring(UserControlCode.Count() - 2, 1);
                    if (UserControlCode == "1")
                    {
                        continue;
                    }

                    DomainObjectItem doi = new DomainObjectItem();
                    doi.Name     = user.Name.Substring(3).ToLower();
                    doi.FullName = user.AccountName;
                    if (doi.FullName == string.Empty)
                    {
                        doi.FullName = string.Format("{0}@{1}", IStrADDomain.ToLower(), user.AccountFullName.ToLower());
                    }
                    else
                    {
                        List <string> listsp = doi.FullName.Split('@').ToList();
                        if (listsp.Count == 2)
                        {
                            doi.FullName = string.Format("{0}@{1}", IStrADDomain.ToLower(), listsp[0].ToLower());
                        }
                    }
                    doi.mGuid     = user.Guid;
                    doi.ObjType   = 112;
                    doi.IsChecked = false;
                    doi.Icon      = "Images/user.ico";

                    DirectoryEntry de = user.MyDirectoryEntry;
                    doi.ParentGuid     = de.Parent.Guid;
                    doi.ParentName     = de.Parent.Name.Substring(3);
                    doi.ParentFullName = doi.ParentName;
                    mListDomainObjItem.Add(doi);
                }
                //======================================================================
                //获取组织结构distinguishedName
                ADUser Duser = util.GetADUser(IStrADUser);
                //ADGroupCollection groups = Duser.MemberOf;
                object obj          = Duser.GetProperty("distinguishedName");
                string OUCollection = obj.ToString();
                //拆分string,获取dc下的第一个机构
                List <string> OUsName = OUCollection.Split(',').ToList();
                int           count = 0;
                string        OUName = string.Empty; string DName = OUsName[OUsName.Count - 2];
                for (; count < OUsName.Count(); count++)
                {
                    string tempOU = OUsName[count];
                    if (tempOU.Substring(0, 2) == "OU")
                    {
                        OUName = tempOU.Substring(3);
                        DomainObjectItem objItem = new DomainObjectItem();
                        objItem.Name      = OUName;
                        objItem.FullName  = objItem.Name;
                        objItem.ObjType   = 111;
                        objItem.IsChecked = false;
                        objItem.Icon      = "Images/org.ico";
                        mRoot.AddChild(objItem);
                        mListDomainObjItem.Add(objItem);
                        GetChild(objItem);
                        break;
                    }
                }
                if (OUName == string.Empty && count == OUsName.Count)//是域下面的用户,直接获取整个结构树
                {
                    mRoot.Name = DName.Substring(3);
                    GetChild(mRoot);
                }
            }
            catch (Exception ex)
            {
                ShowException(string.Format("Get Users Info From LDAP Fail:{0}", ex.Message));
                CurrentApp.WriteLog(string.Format("Get all AD users fail.\t{0}", ex.Message));
            }
        }
Exemple #8
0
		/// <summary>
		/// This method will return a list of objects representing the specified number of entries from the specified record number in the table 
		/// using the value of the field specified
		/// </summary>
		///
		/// <param name="field" type="string">Field of the class ADUser</param>
		/// <param name="fieldValue" type="object">Value for the field specified.</param>
		/// <param name="fieldValue2" type="object">Value for the field specified.</param>
		/// <param name="typeOperation" type="TypeOperation">Operator that is used if fieldValue2=null or fieldValue2="".</param>
		/// <param name="orderByStatement" type="string">The field value to number.</param>
		/// <param name="pageSize" type="int">Number of records returned.</param>
		/// <param name="skipPages" type="int">The number of missing pages.</param>
		///
		/// <returns>List of object of class ADUser in the form of an object of class ADUserCollection</returns>
		public ADUserCollection SelectByFieldPaged(string field, object fieldValue, object fieldValue2, TypeOperation typeOperation, int pageSize, int skipPages, string orderByStatement)
		{
			ADUserCollection aDUserCollection = new ADUserCollection();
			foreach (POS.DataLayer.ADUser _aDUser in POS.DataLayer.ADUserBase.SelectByFieldPaged(field, fieldValue, fieldValue2, typeOperation, pageSize, skipPages, orderByStatement))
			{
				_aDUserWCF = new ADUser();
				
				_aDUserWCF.UserID = _aDUser.UserID;
				_aDUserWCF.UserFullName = _aDUser.UserFullName;
				_aDUserWCF.UserName = _aDUser.UserName;
				_aDUserWCF.Password = _aDUser.Password;
				_aDUserWCF.GroupID = _aDUser.GroupID;
				_aDUserWCF.Email = _aDUser.Email;
				_aDUserWCF.Address = _aDUser.Address;
				_aDUserWCF.Phone = _aDUser.Phone;
				_aDUserWCF.Mobile = _aDUser.Mobile;
				
				aDUserCollection.Add(_aDUserWCF);
			}
			return aDUserCollection;
		}
Exemple #9
0
		/// <summary>
		/// This method will return a list of objects representing the specified number of entries from the specified record number in the table.
		/// </summary>
		///
		/// <param name="pageSize" type="int">Number of records returned.</param>
		/// <param name="skipPages" type="int">The number of missing pages.</param>
		/// <param name="orderByStatement" type="string">The field value to number.</param>
		///
		/// <returns>list of objects of class ADUser in the form of an object of class ADUserCollection </returns>
		public ADUserCollection SelectAllPaged(int? pageSize, int? skipPages, string orderByStatement)
		{
			ADUserCollection aDUserCollection = new ADUserCollection();
			foreach (POS.DataLayer.ADUser _aDUser in POS.DataLayer.ADUserBase.SelectAllPaged(pageSize, skipPages, orderByStatement))
			{
				_aDUserWCF = new ADUser();
				
				_aDUserWCF.UserID = _aDUser.UserID;
				_aDUserWCF.UserFullName = _aDUser.UserFullName;
				_aDUserWCF.UserName = _aDUser.UserName;
				_aDUserWCF.Password = _aDUser.Password;
				_aDUserWCF.GroupID = _aDUser.GroupID;
				_aDUserWCF.Email = _aDUser.Email;
				_aDUserWCF.Address = _aDUser.Address;
				_aDUserWCF.Phone = _aDUser.Phone;
				_aDUserWCF.Mobile = _aDUser.Mobile;
				
				aDUserCollection.Add(_aDUserWCF);
			}
			return aDUserCollection;
		}
Exemple #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="role"></param>
        /// <param name="userNamePart"></param>
        /// <returns></returns>
        private static ADUserCollection GetUsersOfRole( Role role, string userNamePart )
        {
            ADUserCollection result = new ADUserCollection();

            if(role != Role.Anonymous)
            {
                ADUserCollection users = new ADUserCollection();
                string groupName = GetADGroupNameByRole( role );
                LdapAuthentication ldap = new LdapAuthentication();
                users = ldap.GetUsersFromGroup( groupName, userNamePart );

                if(role == Role.Admin)
                {
                    // админы принадлежат к группе админов, с ними всё ясно
                    result = users;
                }
                else
                {
                    foreach(ADUser user in users)
                    {
                        if(CheckUserRole( user.Login, role ))
                        {
                            result.Add( user );
                        }
                    }
                }
            }

            return result;
        }
Exemple #11
0
        /// <summary>
        /// Возвращает всех пользователей, начиная с указанной роли до верхушки иерархии.
        /// </summary>
        /// <param name="role">Роль.</param>
        /// <returns>Коллекция пользователей.</returns>
        public static ADUserCollection GetUsersOfRoleHierarchical( Role role )
        {
            ADUserCollection result = new ADUserCollection();

            Role[] roles = (Role[])Enum.GetValues( typeof( Role ) );
            // начинаем с 1, т.к. нулевой у нас аноним
            for(int i = 1; i < roles.Length && roles[i] <= role; i++)
            {
                ADUserCollection tmpRoles = GetUsersOfRole( roles[i] );
                if(tmpRoles.Count > 0)
                {
                    result.AddRange( tmpRoles );
                }
            }

            return result;
        }
Exemple #12
0
        /// <summary>
        /// Возвращает список пользователей, удовлетворяющих фильтру по имени и
        /// по идентификатору роли.
        /// </summary>
        /// <param name="userNamePart">Фильтр по имени.</param>
        /// <param name="roleID">Идентификатор роли (-1 - все роли).</param>
        /// <returns></returns>
        public static ADUserCollection GetUsers(string userNamePart, int roleID)
        {
            ADUserCollection users = new ADUserCollection();
            if (roleID == -1)
            {
                Dictionary<string, ADUser> loadedUsers = new Dictionary<string, ADUser>();

                foreach (Role role in Enum.GetValues(typeof(Role)))
                {
                    if (role == Role.Anonymous) continue;
                    foreach (ADUser user in GetUsersOfRole(role, userNamePart))
                    {
                        if (!loadedUsers.ContainsKey(user.Login))
                        {
                            users.Add(user);
                            loadedUsers.Add(user.Login, user);
                        }
                    }
                }
            }
            else
                users = GetUsersOfRole((Role)roleID, userNamePart);

            return users;
        }
        /// <summary>
        /// Возвращает коллекцию пользователей, входящих в данную группу и удовлетворяющих
        /// указанному фильтру.
        /// </summary>
        /// <param name="groupName">Имя группы</param>
        /// 
        /// <param name="userNamePart">Часть имени пользователя, по которой производится поиск.</param>
        /// <returns></returns>
        public ADUserCollection GetUsersFromGroup(string groupName, string userNamePart )
        {
            if( string.IsNullOrEmpty( userNamePart ) )
                return GetUsersFromGroup(groupName);

            ADUserCollection rawUsers = FindUsers( userNamePart, groupName );
            ADUserCollection usersWithRoles = new ADUserCollection();
            foreach (ADUser user in rawUsers)
                usersWithRoles.Add( new ADUser(user) );

            return usersWithRoles;
        }
        /// <summary>
        /// Возвращает коллекцию пользователей, входящих в данную группу
        /// </summary>
        /// <param name="group_name">Имя группы</param>
        /// <returns></returns>
        public ADUserCollection GetUsersFromGroup(string group_name)
        {
            DirectoryEntry group = new DirectoryEntry(
                string.Format( "LDAP://{1}/{0}", GetGroupDistinguishedName(group_name),
                    System.Configuration.ConfigurationManager.AppSettings["LdapServer"] ),
                LdapUserName, System.Configuration.ConfigurationManager.AppSettings["LdapPassword"] );
            DirectorySearcher search = new DirectorySearcher( group );
            search.SearchScope = SearchScope.Subtree;

            ADUserCollection users = new ADUserCollection();
            try
            {
                foreach( string dn in group.Properties["member"] )
                {
                    DirectoryEntry user = new DirectoryEntry(
                        string.Format( "LDAP://{1}/{0}", dn, System.Configuration.ConfigurationManager.AppSettings["LdapServer"] ),
                        LdapUserName, System.Configuration.ConfigurationManager.AppSettings["LdapPassword"] );
                    users.Add( new ADUser(user) );
                }
            }
            catch( DirectoryServicesCOMException )
            {
                throw new CoreApplicationException(Resources.ResourceManager.GetString("ADException", group_name));
            }
            return users;
        }
        /// <summary>
        /// Ищет пользователей AD по заданной части имени пользователя
        /// </summary>
        /// <param name="namePart">Часть имени/логина пользователя</param>
        /// <param name="groupName">
        /// Имя группы, которой следует ограничить поиск (null - искать во всех группах).
        /// </param>
        /// <returns>Список найденных пользователей</returns>
        public ADUserCollection FindUsers( string namePart, string groupName )
        {
            DirectoryEntry entry = new DirectoryEntry( _path,
                LdapUserName,
                System.Configuration.ConfigurationManager.AppSettings["LdapPassword"] );

            try
            {
                DirectorySearcher search = new DirectorySearcher( entry );
                search.SearchScope = SearchScope.Subtree;
                if (String.IsNullOrEmpty( groupName ))
                {
                    search.Filter = String.Format(
                        "(& ({1})(|(sAMAccountName=*{0}*)(cn=*{0}*)(mail=*{0}*)(description=*{0}*)) (userPrincipalName=*))",
                        namePart, System.Configuration.ConfigurationManager.AppSettings["LdapUserClass"] );
                }
                else
                {
                    search.Filter = String.Format(
                        "(& ({1})(memberof={2})(|(sAMAccountName=*{0}*)(cn=*{0}*)(mail=*{0}*)(description=*{0}*)) (userPrincipalName=*))",
                        namePart, System.Configuration.ConfigurationManager.AppSettings["LdapUserClass"],
                        GetGroupDistinguishedName(groupName) );
                }

                try
                {
                    SearchResultCollection results = search.FindAll();
                    ADUserCollection users = new ADUserCollection();
                    foreach(SearchResult result in results)
                        users.Add( new ADUser( result ) );
                    return users;
                }
                catch(ArgumentException) // случай неправильной строки поиска
                { }
                return new ADUserCollection();
            }
            catch(Exception ex)
            {
                throw new CoreApplicationException(Resources.ResourceManager.GetString("ErrorSearchingUserException"), ex);
            }
        }