public PropertyCollectionWrapper(PropertyCollection propertyCollection)
        {
            if(propertyCollection == null)
                throw new ArgumentNullException("propertyCollection");

            this._propertyCollection = propertyCollection;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Get the SID string for a given user name
        /// </summary>
        /// <param name="Domain"></param>
        /// <param name="UserName"></param>
        /// <returns>SID string</returns>
        public static string GetSIDFromUserName(String Domain, String UserName)
        {
            string retVal = null;
            string domain = Domain;
            string name   = UserName;

            if (string.IsNullOrEmpty(domain))
            {
                domain = System.Environment.MachineName;
            }

            try
            {
                DirectoryEntry de = new DirectoryEntry("WinNT://" + domain + "/" + name);

                Int64  iBigVal = 5;
                Byte[] bigArr  = BitConverter.GetBytes(iBigVal);
                System.DirectoryServices.PropertyCollection coll = de.Properties;
                object obVal = coll["objectSid"].Value;
                if (null != obVal)
                {
                    retVal = ConvertByteToSidString((Byte[])obVal);
                }
            }
            catch (Exception ex)
            {
                retVal = string.Empty;
                Console.Write(ex.Message);
            }

            return(retVal);
        }
Ejemplo n.º 3
0
        public List <Dictionary <string, object> > GetMemberofGroup(string adspath)
        {
            List <Dictionary <string, object> > groupMemebers = new List <Dictionary <string, object> >();

            try
            {
                DirectoryEntry         ent  = new DirectoryEntry(adspath);
                DirectorySearcher      srch = new DirectorySearcher(ent);
                SearchResultCollection coll = srch.FindAll();
                string USERNAME_FIELD       = !string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_USERNAME_FIELD")) ? AMSCore.WebConfigReadKey("AD_USERNAME_FIELD") : "SAMAccountName";
                foreach (SearchResult rs in coll)
                {
                    ResultPropertyCollection resultPropColl = rs.Properties;
                    foreach (Object memberColl in resultPropColl["member"])
                    {
                        DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
                        System.DirectoryServices.PropertyCollection subgroupProps = gpMemberEntry.Properties;
                        groupMemebers.Add(GetGroupsMember(subgroupProps, new Dictionary <string, object>()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
                //return groupMemebers;
            }
            return(groupMemebers);
        }
Ejemplo n.º 4
0
		private void InitBlock()
		{
			_Properties=null;
			_Entry=null;
			_PropsToLoad=null;
			ispropnull=true;
			_Rproperties=null;
		}
Ejemplo n.º 5
0
        public static string GetUserName(string loginID)
        {
            string RealUserName = string.Empty;
            string userName     = string.Empty;

            if (loginID.Contains("\\"))
            {
                userName = loginID.Split('\\')[1];
            }
            else
            {
                userName = loginID;
            }

            try
            {
                DirectoryEntry    root;
                DirectorySearcher searcher;
                string            m        = ""; // sk05
                string            sEmail   = string.Empty;
                string            bindDN   = "";
                string            bindPass = "";
                string            ldapHost = ConfigurationManager.AppSettings["LDAPHOST"];
                string            ldapPort = ConfigurationManager.AppSettings["LDAPPORT"];
                string            baseDN   = ConfigurationManager.AppSettings["BASEDN"];
                string            ldapPath = ConfigurationManager.AppSettings["LDAPPATH"];

                DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + ldapHost + ":" + ldapPort + "/" + baseDN);
                dEntry.Username           = bindDN;
                dEntry.Password           = bindPass;
                dEntry.AuthenticationType = AuthenticationTypes.FastBind;

                DirectorySearcher dSearch = new DirectorySearcher(dEntry);
                root     = new DirectoryEntry(ldapPath);
                searcher = new DirectorySearcher(root);


                dSearch.Filter = "(&(jnjMSUsername="******"))";

                dSearch.PropertiesToLoad.Add("givenname");
                dSearch.PropertiesToLoad.Add("sn");

                foreach (System.DirectoryServices.SearchResult dResult in dSearch.FindAll())
                {
                    System.DirectoryServices.PropertyCollection pColl = dResult.GetDirectoryEntry().Properties;

                    if (pColl != null && pColl["givenname"].Value != null)
                    {
                        RealUserName = pColl["givenname"].Value.ToString() + " " + pColl["sn"].Value.ToString();
                    }
                }

                dEntry.Close();

                return(RealUserName);
            }
            catch (Exception Ex) { throw Ex; }
        }
Ejemplo n.º 6
0
        private void backgroundProc_DoWork(object sender, DoWorkEventArgs e)
        {
            userEntry = new DirectoryEntry(userDN);
            PrincipalContext context = new PrincipalContext(ContextType.Domain);

            userProp    = userEntry.Properties;
            userPrinc   = UserPrincipal.FindByIdentity(context, IdentityType.DistinguishedName, userProp["distinguishedName"].Value.ToString());
            isPwExpired = BAADTools.isPasswordExpired(userProp["sAMAccountName"].Value.ToString());
        }
    /// <summary>
    /// GetFullName Method: Uses the user login name to get the full name of user by interrogating active directory. Uses active directory name.
    /// </summary>

    public string GetFullName()
    {
        string str;
        string strDomain;
        string strName;

        if (string.IsNullOrEmpty(ActiveDName))
        {
            ActiveDName = @"GMFS\redmondp";
        }

        // Parse the string to check if domain name is present.
        int idx = ActiveDName.IndexOf('\\');

        if (idx == -1)
        {
            idx = ActiveDName.IndexOf('@');
        }

        if (idx != -1)
        {
            strDomain = ActiveDName.Substring(0, idx);
            strName   = ActiveDName.Substring(idx + 1);
        }
        else
        {
            strDomain = Environment.MachineName;
            strName   = ActiveDName;
        }

        try
        {
            var obDirEntry          = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
            PropertyCollection coll = obDirEntry.Properties;

            object obVal = coll["FullName"].Value;

            str = obVal.ToString();


            //below rearranges the name from [last][first] to [first][last]
            string[] Name = str.Split(new char[0]);

            foreach (string order in Name)
            {
                str = Name[1];
                //+" " + Name[0];
            }
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }

        return(str);
    }
Ejemplo n.º 8
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);
          }
      }
        private static string GetSingleStringPropertyCollectionValue(System.DirectoryServices.PropertyCollection props, string name)
        {
            if (!props.Contains(name))
            {
                return(string.Empty);
            }

            PropertyValueCollection pvc = props[name];

            if (pvc == null || pvc.Count == 0)
            {
                return(string.Empty);
            }
            return(pvc[0] as string);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 用户是否属于某个组
        /// </summary>
        /// <param name="accountName">用户登录名称,不包括域名 如:xueqingxia</param>
        /// <param name="groupName">组名 如:英语0901</param>
        /// <returns></returns>
        public static bool UserIsMemberof(string accountName, string groupName)
        {
            DirectoryEntry user = GetDirectoryEntryByAccount(accountName);

            if (user != null)
            {
                System.DirectoryServices.PropertyCollection props = user.Properties;
                PropertyValueCollection values = props["memberOf"];
                foreach (object val in values)
                {
                    if (val.ToString().ToLower().Contains(groupName.ToLower()))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 11
0
        protected string[] GetSchemaProperties(string schemaNamingContext, string objectType)
        {
            string[] data;
            using (DirectoryEntry de = new DirectoryEntry())
            {
                de.Username = username;
                de.Password = password;

                de.Path = "LDAP://" + hostname + "CN=" + objectType + "," + schemaNamingContext;

                DS.PropertyCollection      properties = de.Properties;
                DS.PropertyValueCollection values     = properties["systemMayContain"];

                data = new String[values.Count];
                values.CopyTo(data, 0);
            }
            return(data);
        }
Ejemplo n.º 12
0
        public List <UserProfile> GetUserFromGroup(String groupName)
        {
            List <UserProfile> userlist = new List <UserProfile>();

            try
            {
                using (HostingEnvironment.Impersonate())
                {
                    _directoryEntry = null;
                    DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                    directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";
                    SearchResult results = directorySearch.FindOne();
                    if (results != null)
                    {
                        DirectoryEntry deGroup = new DirectoryEntry(results.Path);
                        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    = respath + objpath;


                            DirectoryEntry user    = new DirectoryEntry(path);
                            UserProfile    userobj = UserProfile.GetUser(user);
                            userlist.Add(userobj);
                            user.Close();
                        }
                    }
                    return(userlist);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <ActiveDirectoryHelper>("GetUserFromGroup Exception: ", ex);
                return(userlist);
            }
        }
Ejemplo n.º 13
0
        static int GetUserAccountControl(DirectoryEntry anEntry)
        {
            //Get AD user account control flag for Kerberos
            int val = 0;

            if (null != anEntry)
            {
                System.DirectoryServices.PropertyCollection collProperties = anEntry.Properties;
                if ((null != collProperties) && (collProperties.Count > 0))
                {
                    object prop = anEntry.Properties["userAccountControl"];
                    if (null != prop && (prop is PropertyValueCollection))
                    {
                        object oVal = ((PropertyValueCollection)prop).Value;
                        //If property doesn't exist, than value is null
                        val = (int)oVal;
                    }
                }
            }
            return(val);
        }
Ejemplo n.º 14
0
        ///// <summary>
        ///// 获取用户的性别
        ///// </summary>
        ///// <param name="accountName">用户登录帐户,不包括域名;如:20053703</param>
        ///// <returns>返回登录用户的性别</returns>
        //public static string GetUserSex(string accountName)
        //{
        //    DirectoryEntry user = GetDirectoryEntryByAccount(accountName);
        //    if (user != null)
        //    {
        //        System.DirectoryServices.PropertyCollection props = user.Properties;
        //        PropertyValueCollection des = props["description"];
        //        if (des.Value != null)
        //        {
        //            string identify = des.Value.ToString().Trim();
        //            string flag;
        //            if (identify.Length == 18)
        //                flag = identify.Substring(16, 1);
        //            else
        //                flag = identify.Substring(14);
        //            if (Convert.ToInt16(flag) % 2 == 0)
        //                return "女";
        //            else
        //                return "男";
        //        }
        //        else
        //            return "";
        //    }
        //    return "";
        //}
        /// <summary>
        /// 获取用户的性别2010-09-07
        /// </summary>
        /// <param name="accountName">用户登录帐户,不包括域名;如:20053703</param>
        /// <returns>返回登录用户的性别</returns>
        public static string GetUserSex(string accountName)
        {
            DirectoryEntry user = GetDirectoryEntryByAccount(accountName);

            if (user != null)
            {
                System.DirectoryServices.PropertyCollection props = user.Properties;
                PropertyValueCollection des = props["description"];
                if (des.Value != null)
                {
                    string identify = des.Value.ToString().Trim();
                    if (identify.Length == 1)
                    {
                        return(identify);
                    }
                    string flag;
                    if (identify.Length == 18)
                    {
                        flag = identify.Substring(16, 1);
                    }
                    else
                    {
                        flag = identify.Substring(14);
                    }
                    if (Convert.ToInt16(flag) % 2 == 0)
                    {
                        return("女");
                    }
                    else
                    {
                        return("男");
                    }
                }
                else
                {
                    return("");
                }
            }
            return("");
        }
Ejemplo n.º 15
0
        public static string GetFullName(string strLogin)
        {
            string str = "";
            string strDomain;
            string strName;

            // Parse the string to check if domain name is present.
            int idx = strLogin.IndexOf('\\');

            if (idx == -1)
            {
                idx = strLogin.IndexOf('@');
            }

            if (idx != -1)
            {
                strDomain = strLogin.Substring(0, idx);
                strName   = strLogin.Substring(idx + 1);
            }
            else
            {
                strDomain = Environment.MachineName;
                strName   = strLogin;
            }

            DirectoryEntry obDirEntry = null;

            try
            {
                obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
                System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
                object obVal = coll["FullName"].Value;
                str = obVal.ToString();
            }
            catch               //(Exception ex)
            {
                str = strLogin; // ex.Message;
            }
            return(str);
        }
Ejemplo n.º 16
0
        public List <ADUserDetail> GetUserFromGroup(String groupName)
        {
            List <ADUserDetail> userlist = new List <ADUserDetail>();

            try
            {
                DirectoryEntry    de = GetRoot();
                DirectorySearcher directorySearch = new DirectorySearcher(de);
                directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";
                SearchResult results = directorySearch.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    = respath + objpath;
                        DirectoryEntry user    = new DirectoryEntry(path, LDAPUser, LDAPPassword);
                        ADUserDetail   userobj = ADUserDetail.GetUser(user);
                        userlist.Add(userobj);
                        user.Close();
                    }
                }
                return(userlist);
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                string err      = ex.Message;
                int    Event_id = 1122;
                EventLog.WriteEntry(InfoHubEventLog.LogSource, err, EventLogEntryType.Warning, Event_id, Category);
                return(userlist);
            }
        }
        /// <summary>
        /// This function will take a DL or Group name and return list of users
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public List <ADUserDetail> GetUserFromGroup(String groupName)
        {
            List <ADUserDetail> userlist = new List <ADUserDetail>();

            try
            {
                _directoryEntry = null;
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";
                SearchResult results = directorySearch.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    = respath + objpath;


                        DirectoryEntry user    = new DirectoryEntry(path); //, LDAPUser, LDAPPassword);
                        ADUserDetail   userobj = ADUserDetail.GetUser(user);
                        userlist.Add(userobj);
                        user.Close();
                    }
                }
                return(userlist);
            }
            catch (Exception ex)
            {
                return(userlist);
            }
        }
Ejemplo n.º 18
0
        public DirectoryEntry(string sLDAPPath)
        {
            this.sLDAPPath     = sLDAPPath;
            propertyCollection = null;
            nativeObject       = null;
            sName           = null;
            children        = null;
            objectSecurity  = null;
            guid            = Guid.Empty;
            parent          = null;
            objectClassType = null;

            SDSUtils.CrackPath(sLDAPPath, out sProtocol, out sServer, out sCNs, out sDCs);

            /*if (sProtocol != null) Console.WriteLine("sProtocol is " + sProtocol);
             * if (sServer != null) Console.WriteLine("sServer is " + sServer);
             * if (sCNs != null) Console.WriteLine("sCNs is " + sCNs);
             * if (sDCs != null) Console.WriteLine("sDCs is " + sDCs); */

            string[] rootDNcom;

            if (sServer != null)
            {
                rootDNcom = sServer.Split('.');

                rootDN = "";

                foreach (string str in rootDNcom)
                {
                    string temp = string.Concat("dc=", str, ",");
                    rootDN = string.Concat(rootDN, temp);
                }

                rootDN = rootDN.Substring(0, rootDN.Length - 1);
            }
            //beacuse rootDN is nothing but collection of all DC's from DN
            if (sDCs != null)
            {
                rootDN = sDCs;
            }

            baseDn = "";

            //sCNs = RootDSE, Configuration, Schema, Domain
            if (sCNs != null && sDCs == null)
            {
                if (sCNs.Equals("RootDSE", StringComparison.InvariantCultureIgnoreCase))
                {
                    baseDn = "";
                }
                else if (sCNs.Equals("Configuration", StringComparison.InvariantCultureIgnoreCase))
                {
                    baseDn = string.Concat("CN=Configuration,", rootDN);
                }
                else if (sCNs.Equals("Schema", StringComparison.InvariantCultureIgnoreCase))
                {
                    baseDn = string.Concat("CN=Schema,", rootDN);
                }
                else if (sCNs.Equals("Domain", StringComparison.InvariantCultureIgnoreCase) ||
                         sCNs.Equals("", StringComparison.InvariantCultureIgnoreCase) ||
                         sCNs.StartsWith("<"))
                {
                    if (rootDN != null)
                    {
                        baseDn = rootDN;
                    }
                }
                else
                {
                    baseDn = string.Concat(sCNs, ",", rootDN);
                }
            }

            if (sCNs != null && sDCs != null)
            {
                baseDn = string.Concat(sCNs, ",", sDCs);
            }

            if (sCNs == null && sDCs != null)
            {
                baseDn = sDCs;
            }

            if (sCNs == null && sDCs == null)
            {
                baseDn = rootDN;
            }

            //assign sName value using the dN of this node
            if (baseDn.Equals("", StringComparison.InvariantCultureIgnoreCase))
            {
                sName = "RootDSE";
            }
            else
            {
                sName = baseDn;
            }
        }
		/// <summary>
		/// Returns entry properties.
		/// </summary>
		/// <param name="forceLoad">Specifies whenever to force the properties load from the server if local property cache is empty.</param>
		/// <returns></returns>
		private PropertyCollection GetProperties(bool forceLoad)
		{
			if (_Properties == null) {
				// load properties into a different collection 
				// to preserve original collection state if exception occurs
				PropertyCollection properties = new PropertyCollection (this);
				if (forceLoad && !Nflag)				
					LoadProperties (properties,null);

				_Properties = properties ;
			}			
			return _Properties;
		}
		private void InitToRootDse(string host,int port)
		{
			if ( host == null )
				host = DefaultHost;
			if ( port < 0 )
				port = DefaultPort;	
		
			LdapUrl rootPath = new LdapUrl (host,port,String.Empty);
			string [] attrs = new string [] {"+","*"};
			DirectoryEntry rootEntry = new DirectoryEntry (rootPath.ToString (),this.Username,this.Password,this.AuthenticationType);
			DirectorySearcher searcher = new DirectorySearcher (rootEntry,null,attrs,SearchScope.Base);

			SearchResult result = searcher.FindOne ();			
			// copy properties from search result
			PropertyCollection pcoll = new PropertyCollection ();
			foreach (string propertyName in result.Properties.PropertyNames) {
				System.Collections.IEnumerator enumerator = result.Properties [propertyName].GetEnumerator ();
				if (enumerator != null)
					while (enumerator.MoveNext ())
						if (String.Compare (propertyName,"ADsPath",true) != 0)
							pcoll [propertyName].Add (enumerator.Current);
			}			
			this.SetProperties (pcoll);
			this._Name = "rootDSE";
		}
		void RefreshEntry()
		{
			_Properties = null;
			_Fdn = null;
			_Name = null;
			_Parent = null;
			_SchemaClassName = null;
			InitEntry();
		}
 public static PropertyCollectionWrapper FromPropertyCollection(PropertyCollection propertyCollection)
 {
     return propertyCollection;
 }
Ejemplo n.º 23
0
        private void CommitEntry()
        {
            PropertyCollection properties = GetProperties(false);

            if (!Nflag)
            {
                System.Collections.ArrayList modList = new System.Collections.ArrayList();
                foreach (string attribute in properties.PropertyNames)
                {
                    LdapAttribute attr = null;
                    if (properties [attribute].Mbit)
                    {
                        switch (properties [attribute].Count)
                        {
                        case 0:
                            attr = new LdapAttribute(attribute, new string [0]);
                            modList.Add(new LdapModification(LdapModification.DELETE, attr));
                            break;

                        case 1:
                            string val = (string)properties [attribute].Value;
                            attr = new LdapAttribute(attribute, val);
                            modList.Add(new LdapModification(LdapModification.REPLACE, attr));
                            break;

                        default:
                            object [] vals     = (object [])properties [attribute].Value;
                            string [] aStrVals = new string [properties [attribute].Count];
                            Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count);
                            attr = new LdapAttribute(attribute, aStrVals);
                            modList.Add(new LdapModification(LdapModification.REPLACE, attr));
                            break;
                        }
                        properties [attribute].Mbit = false;
                    }
                }
                if (modList.Count > 0)
                {
                    LdapModification[] mods = new LdapModification[modList.Count];
                    Type mtype = typeof(LdapModification);
                    mods = (LdapModification[])modList.ToArray(mtype);
                    ModEntry(mods);
                }
            }
            else
            {
                LdapAttributeSet attributeSet = new LdapAttributeSet();
                foreach (string attribute in properties.PropertyNames)
                {
                    if (properties [attribute].Count == 1)
                    {
                        string val = (string)properties [attribute].Value;
                        attributeSet.Add(new LdapAttribute(attribute, val));
                    }
                    else
                    {
                        object[] vals     = (object [])properties [attribute].Value;
                        string[] aStrVals = new string [properties [attribute].Count];
                        Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count);
                        attributeSet.Add(new LdapAttribute(attribute, aStrVals));
                    }
                }
                LdapEntry newEntry = new LdapEntry(Fdn, attributeSet);
                conn.Add(newEntry);
                Nflag = false;
            }
        }
 public void CommitChanges()
 {
     if (this.justCreated)
     {
         try
         {
             this.SetObjectSecurityInCache();
             this.adsObject.SetInfo();
         }
         catch (COMException exception)
         {
             throw COMExceptionHelper.CreateFormattedComException(exception);
         }
         this.justCreated = false;
         this.objectSecurityInitialized = false;
         this.objectSecurityModified = false;
         this.propertyCollection = null;
     }
     else if ((this.useCache || ((this.objectSecurity != null) && this.objectSecurity.IsModified())) && this.Bound)
     {
         try
         {
             this.SetObjectSecurityInCache();
             this.adsObject.SetInfo();
             this.objectSecurityInitialized = false;
             this.objectSecurityModified = false;
         }
         catch (COMException exception2)
         {
             throw COMExceptionHelper.CreateFormattedComException(exception2);
         }
         this.propertyCollection = null;
     }
 }
Ejemplo n.º 25
0
		/// <summary>
		/// Loads the values of the specified properties into the property cache.
		/// </summary>
		/// <param name="propertyNames">An array of the specified properties.</param>
		private void LoadProperties(PropertyCollection properties,string[] propertyNames)
		{
			_inPropertiesLoading = true;
			try	{
				LdapSearchResults lsc=conn.Search (Fdn,LdapConnection.SCOPE_BASE,"objectClass=*",propertyNames,false);
				if (lsc.hasMore ()) {
					LdapEntry nextEntry = lsc.next ();
					string [] lowcasePropertyNames = null;
					int length = 0;
					if (propertyNames != null) {
						length = propertyNames.Length;
						lowcasePropertyNames = new string [length];
						for(int i=0; i < length; i++)
							lowcasePropertyNames [i] = propertyNames [i].ToLower ();
					}
					foreach (LdapAttribute attribute in nextEntry.getAttributeSet ())	{
						string attributeName = attribute.Name;
						if ((propertyNames == null) || (Array.IndexOf (lowcasePropertyNames,attributeName.ToLower ()) != -1)) {
							properties [attributeName].Value = null;
							if (BytesAttributes.Contains (attributeName.ToLower ()))
							{
								var i = 0;
								foreach(var item in attribute.ByteValueArray)
								{
									properties [attributeName].Add(Array.ConvertAll (item, x => (byte)x));
									i++;
								}
							}
							else if (Int32Attributes.Contains (attributeName.ToLower ()))
							{
								foreach(string item in attribute.StringValueArray)
								{
									int i ;
									if (int.TryParse (item, out i)) {
										properties [attributeName].Add(i);
									}
								}
							}
							else if (Int64Attributes.Contains (attributeName.ToLower ()))
							{
								foreach(string item in attribute.StringValueArray)
								{
									long i ;
									if (long.TryParse (item, out i)) {
										properties [attributeName].Add(i);
									}
								}
							}
							else if (BoolAttributes.Contains (attributeName.ToLower ()))
							{
								foreach(string item in attribute.StringValueArray)
								{
									bool i ;
									if (bool.TryParse (item, out i)) {
										properties [attributeName].Add(i);
									}
								}
							}
							else{
								properties [attributeName].AddRange (attribute.StringValueArray);
							}
							properties [attributeName].Mbit=false;
							properties [attributeName].NativeObject = attribute;
						}
					}
				}
			}
			finally {
				_inPropertiesLoading = false;
			}
		}
Ejemplo n.º 26
0
        public static UserDetails GetUserDetails(string loginID)
        {
            UserDetails user     = new UserDetails();
            string      userName = string.Empty;

            if (loginID.Contains("\\"))
            {
                // strip out domain
                userName = loginID.Split('\\')[1];
            }
            else
            {
                userName = loginID;
            }

            /*Code commented on 02/12/2015 by Shekhar. Reason: Now it is out of scope
             * if (userName.ToUpper().Contains("ADMIN_"))
             *  userName = userName.Substring(6);
             */
            try
            {
                DirectoryEntry    root;
                DirectorySearcher searcher;
                string            m        = ""; // sk05
                string            sEmail   = string.Empty;
                string            bindDN   = "";
                string            bindPass = "";
                string            ldapHost = ConfigurationManager.AppSettings["LDAPHOST"]; //CommonUtility.LDAPHOST;
                string            ldapPort = ConfigurationManager.AppSettings["LDAPPORT"]; //CommonUtility.LDAPPORT;
                string            baseDN   = ConfigurationManager.AppSettings["BASEDN"];   //CommonUtility.BASEDN;
                string            ldapPath = ConfigurationManager.AppSettings["LDAPPATH"]; //CommonUtility.LDAPPATH;

                DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + ldapHost + ":" + ldapPort + "/" + baseDN);
                dEntry.Username           = bindDN;
                dEntry.Password           = bindPass;
                dEntry.AuthenticationType = AuthenticationTypes.FastBind;

                DirectorySearcher dSearch = new DirectorySearcher(dEntry);
                root     = new DirectoryEntry(ldapPath);
                searcher = new DirectorySearcher(root);


                dSearch.Filter = "(&(jnjMSUsername="******"))";
                dSearch.PropertiesToLoad.Add("mail");

                dSearch.PropertiesToLoad.Add("givenname");
                dSearch.PropertiesToLoad.Add("sn");

                foreach (System.DirectoryServices.SearchResult dResult in dSearch.FindAll())
                {
                    System.DirectoryServices.PropertyCollection pColl = dResult.GetDirectoryEntry().Properties;

                    if (pColl != null && pColl["mail"].Value != null)
                    {
                        user.UserName      = pColl["givenname"].Value.ToString() + " " + pColl["sn"].Value.ToString();
                        user.UserEmailId   = pColl["mail"].Value.ToString();
                        user.UserWWID      = pColl["uid"].Value.ToString();
                        user.UserFirstName = pColl["givenName"].Value.ToString();
                        user.UserLastName  = pColl["sn"].Value.ToString();
                        user.UserNetworkId = userName;
                        string ManagerStr        = pColl["manager"].Value.ToString();
                        string ManagerNamewithOU = ManagerStr.Split(',')[1];
                        string ManagerWWID       = ManagerNamewithOU.Remove(ManagerNamewithOU.IndexOf("OU="), ("OU=").Length);
                        user.ManagerName = (ManagerStr.Split(',')[0]).Remove((ManagerStr.Split(',')[0]).IndexOf("CN="), ("CN=").Length);
                        user.ManagerWWID = ManagerWWID;

                        dSearch.Filter = "(&(uid=" + ManagerWWID + "))";
                        foreach (System.DirectoryServices.SearchResult dResult1 in dSearch.FindAll())
                        {
                            System.DirectoryServices.PropertyCollection pCol2 = dResult1.GetDirectoryEntry().Properties;

                            user.ManagerEmailId   = pCol2["mail"].Value.ToString();
                            user.ManagerFirstName = pCol2["givenName"].Value.ToString();
                            user.ManagerLastName  = pCol2["sn"].Value.ToString();
                            user.ManagerNetworkId = pCol2["jnjMSUsername"].Value.ToString();
                        }
                    }
                }

                dEntry.Close();
                if (String.IsNullOrEmpty(m))
                {
                    m = userName;
                }
                return(user);
            }
            catch (Exception Ex) { throw Ex; }
        }
Ejemplo n.º 27
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator.ValuesEnumerator"]/*' />
 ///<internalonly/>
 public ValuesEnumerator(PropertyCollection propCollection)
 {
     this.propCollection = propCollection;
 }
Ejemplo n.º 28
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysEnumerator.KeysEnumerator"]/*' />
 ///<internalonly/>
 public KeysEnumerator(PropertyCollection collection)
     : base(collection)
 {
 }
Ejemplo n.º 29
0
        private void DoSearch()
        {
            InitBlock();
            String[] attrs = new String[PropertiesToLoad.Count];
            PropertiesToLoad.CopyTo(attrs, 0);

            LdapSearchConstraints cons = _conn.SearchConstraints;

            if (SizeLimit > 0)
            {
                cons.MaxResults = SizeLimit;
            }
            if (ServerTimeLimit != DefaultTimeSpan)
            {
                cons.ServerTimeLimit = (int)ServerTimeLimit.TotalSeconds;
            }

            int connScope = LdapConnection.SCOPE_SUB;

            switch (_SearchScope)
            {
            case SearchScope.Base:
                connScope = LdapConnection.SCOPE_BASE;
                break;

            case SearchScope.OneLevel:
                connScope = LdapConnection.SCOPE_ONE;
                break;

            case SearchScope.Subtree:
                connScope = LdapConnection.SCOPE_SUB;
                break;

            default:
                connScope = LdapConnection.SCOPE_SUB;
                break;
            }
            LdapSearchResults lsc = _conn.Search(SearchRoot.Fdn,
                                                 connScope,
                                                 Filter,
                                                 attrs,
                                                 PropertyNamesOnly, cons);

            while (lsc.hasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.next();
                }
                catch (LdapException e)
                {
                    switch (e.ResultCode)
                    {
                    // in case of this return codes exception should not be thrown
                    case LdapException.SIZE_LIMIT_EXCEEDED:
                    case LdapException.TIME_LIMIT_EXCEEDED:
                    case LdapException.REFERRAL:
                        continue;

                    default:
                        throw e;
                    }
                }
                DirectoryEntry     de    = new DirectoryEntry(_conn);
                PropertyCollection pcoll = new PropertyCollection();
//				de.SetProperties();
                de.Path = DirectoryEntry.GetLdapUrlString(_Host, _Port, nextEntry.DN);
                LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                if (ienum != null)
                {
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        pcoll[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].Mbit=false;
                    }
                }
                if (!pcoll.Contains("ADsPath"))
                {
                    pcoll["ADsPath"].Add(de.Path);
                }
//				_SrchColl.Add(new SearchResult(de,PropertiesToLoad));
                _SrchColl.Add(new SearchResult(de, pcoll));
            }
            return;
        }
Ejemplo n.º 30
0
        public DirectoryEntry(string sLDAPPath)
        {
            this.sLDAPPath = sLDAPPath;
            propertyCollection = null;
            nativeObject = null;
            sName = null;
            children = null;
            objectSecurity = null;
            guid = Guid.Empty;
            parent = null;
            objectClassType = null;

            SDSUtils.CrackPath(sLDAPPath, out sProtocol, out sServer, out sCNs, out sDCs);

            /*if (sProtocol != null) Console.WriteLine("sProtocol is " + sProtocol);
            if (sServer != null) Console.WriteLine("sServer is " + sServer);
            if (sCNs != null) Console.WriteLine("sCNs is " + sCNs);
            if (sDCs != null) Console.WriteLine("sDCs is " + sDCs); */

            string[] rootDNcom;

            if (sServer != null)
            {
                rootDNcom = sServer.Split('.');

                rootDN = "";

                foreach (string str in rootDNcom)
                {
                    string temp = string.Concat("dc=", str, ",");
                    rootDN = string.Concat(rootDN, temp);
                }

                rootDN = rootDN.Substring(0, rootDN.Length - 1);
            }
            //beacuse rootDN is nothing but collection of all DC's from DN
            if (sDCs != null)
                rootDN = sDCs;

            baseDn = "";

            //sCNs = RootDSE, Configuration, Schema, Domain
            if (sCNs != null && sDCs == null)
            {
                if (sCNs.Equals("RootDSE", StringComparison.InvariantCultureIgnoreCase))
                    baseDn = "";
                else if (sCNs.Equals("Configuration", StringComparison.InvariantCultureIgnoreCase))
                    baseDn = string.Concat("CN=Configuration,", rootDN);
                else if (sCNs.Equals("Schema", StringComparison.InvariantCultureIgnoreCase))
                    baseDn = string.Concat("CN=Schema,", rootDN);
                else if (sCNs.Equals("Domain", StringComparison.InvariantCultureIgnoreCase) ||
                 sCNs.Equals("", StringComparison.InvariantCultureIgnoreCase) ||
                 sCNs.StartsWith("<"))
                {
                    if (rootDN != null)
                        baseDn = rootDN;
                }
                else baseDn = string.Concat(sCNs, ",", rootDN);

            }

            if (sCNs != null && sDCs != null)
                baseDn = string.Concat(sCNs, ",", sDCs);

            if (sCNs == null && sDCs != null)
                baseDn = sDCs;

            if (sCNs == null && sDCs == null)
                baseDn = rootDN;

            //assign sName value using the dN of this node
            if (baseDn.Equals("", StringComparison.InvariantCultureIgnoreCase))
                sName = "RootDSE";
            else
                sName = baseDn;
        }
Ejemplo n.º 31
0
		internal SearchResult(DirectoryEntry entry, PropertyCollection props)
		{
			InitBlock();
			_Entry = entry;
			_Path = entry.Path;
			_Rproperties = props;
		}
 internal void CommitIfNotCaching()
 {
     if ((!this.justCreated && !this.useCache) && this.Bound)
     {
         new DirectoryServicesPermission(PermissionState.Unrestricted).Demand();
         try
         {
             this.SetObjectSecurityInCache();
             this.adsObject.SetInfo();
             this.objectSecurityInitialized = false;
             this.objectSecurityModified = false;
         }
         catch (COMException exception)
         {
             throw COMExceptionHelper.CreateFormattedComException(exception);
         }
         this.propertyCollection = null;
     }
 }
Ejemplo n.º 33
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysCollection.KeysCollection"]/*' />
 ///<internalonly/>
 public KeysCollection(PropertyCollection props)
     : base(props)
 {
 }
 public void RefreshCache()
 {
     this.Bind();
     try
     {
         this.adsObject.GetInfo();
     }
     catch (COMException exception)
     {
         throw COMExceptionHelper.CreateFormattedComException(exception);
     }
     this.cacheFilled = true;
     this.propertyCollection = null;
     this.objectSecurityInitialized = false;
     this.objectSecurityModified = false;
 }
Ejemplo n.º 35
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.ValuesCollection"]/*' />
 ///<internalonly/>
 public ValuesCollection(PropertyCollection props)
 {
     this.props = props;
 }
Ejemplo n.º 36
0
        /// <summary>
        /// This method will return all users for the specified group in a dataset
        /// </summary>
        /// <param name="GroupName"></param>
        /// <returns></returns>
        public static DataSet GetUsersForGroup(string GroupName)
        {
            DataSet        dsUser = new DataSet();
            DirectoryEntry de     = GetDirectoryObject();

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

            //set the search filter
            deSearch.SearchRoot = de;
            //deSearch.PropertiesToLoad.Add("cn");
            deSearch.Filter = "(&(objectClass=group)(cn=" + GroupName + "))";

            //get the group result
            SearchResult results = deSearch.FindOne();

            //Create a new table object within the dataset
            DataTable tbUser = dsUser.Tables.Add("Users");

            tbUser.Columns.Add("UserName");
            tbUser.Columns.Add("DisplayName");
            tbUser.Columns.Add("EMailAddress");

            //Create default row
            DataRow rwDefaultUser = tbUser.NewRow();

            rwDefaultUser ["UserName"]     = "******";
            rwDefaultUser ["DisplayName"]  = "(Not Specified)";
            rwDefaultUser ["EMailAddress"] = "(Not Specified)";
            tbUser.Rows.Add(rwDefaultUser);

            //if the group is valid, then continue, otherwise return a blank dataset
            if (results != null)
            {
                //create a link to the group object, so we can get the list of members
                //within the group
                DirectoryEntry deGroup = new DirectoryEntry(results.Path, ADAdminUser, ADAdminPassword, AuthenticationTypes.Secure);
                //assign a property collection
                System.DirectoryServices.PropertyCollection pcoll = deGroup.Properties;
                int n = pcoll["member"].Count;

                //if there are members fo the group, then get the details and assign to the table
                for (int l = 0; l < n; l++)
                {
                    //create a link to the user object sot hat the FirstName, LastName and SUername can be gotten
                    DirectoryEntry deUser = new DirectoryEntry(ADFullPath + "/" + pcoll["member"][l].ToString(), ADAdminUser, ADAdminPassword, AuthenticationTypes.Secure);

                    //set a new empty row
                    DataRow rwUser = tbUser.NewRow();

                    //populate the column
                    rwUser["UserName"]     = GetProperty(deUser, "cn");
                    rwUser["DisplayName"]  = GetProperty(deUser, "givenName") + " " + GetProperty(deUser, "sn");
                    rwUser["EMailAddress"] = GetProperty(deUser, "mail");
                    //append the row to the table of the dataset
                    tbUser.Rows.Add(rwUser);

                    //close the directory entry object
                    deUser.Close();
                }
                de.Close();
                deGroup.Close();
            }


            return(dsUser);
        }
Ejemplo n.º 37
0
		private void DoSearch()
		{
			InitBlock();
			String[] attrs= new String[PropertiesToLoad.Count];
			PropertiesToLoad.CopyTo(attrs,0);
			
			LdapSearchConstraints cons = _conn.SearchConstraints;
			if (SizeLimit > 0) {
				cons.MaxResults = SizeLimit;
			}
			if (ServerTimeLimit != DefaultTimeSpan) {
				cons.ServerTimeLimit = (int)ServerTimeLimit.TotalSeconds;
			}

			int connScope = LdapConnection.SCOPE_SUB;
			switch (_SearchScope)
			{
			case SearchScope.Base:
			  connScope = LdapConnection.SCOPE_BASE;
			  break;

			case SearchScope.OneLevel:
			  connScope = LdapConnection.SCOPE_ONE;
			  break;

			case SearchScope.Subtree:
			  connScope = LdapConnection.SCOPE_SUB;
			  break;

			default:
			  connScope = LdapConnection.SCOPE_SUB;
			  break;
			}
			LdapSearchResults lsc=_conn.Search(	SearchRoot.Fdn,
												connScope,
												Filter,
												attrs,
												PropertyNamesOnly,cons);

			while(lsc.hasMore())						
			{
				LdapEntry nextEntry = null;
				try 							
				{
					nextEntry = lsc.next();
				}
				catch(LdapException e) 							
				{
					switch (e.ResultCode) {
						// in case of this return codes exception should not be thrown
						case LdapException.SIZE_LIMIT_EXCEEDED:
						case LdapException.TIME_LIMIT_EXCEEDED:
						case LdapException.REFERRAL:
							continue;
						default :
							throw e;
					}
				}
				DirectoryEntry de = new DirectoryEntry(_conn);
				PropertyCollection pcoll = new PropertyCollection();
//				de.SetProperties();
				de.Path = DirectoryEntry.GetLdapUrlString(_Host,_Port,nextEntry.DN); 
				LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
				System.Collections.IEnumerator ienum=attributeSet.GetEnumerator();
				if(ienum!=null)							
				{
					while(ienum.MoveNext())				
					{
						LdapAttribute attribute=(LdapAttribute)ienum.Current;
						string attributeName = attribute.Name;
						pcoll[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].AddRange(attribute.StringValueArray);
//						de.Properties[attributeName].Mbit=false;
					}
				}
				if (!pcoll.Contains("ADsPath")) {
					pcoll["ADsPath"].Add(de.Path);
				}
//				_SrchColl.Add(new SearchResult(de,PropertiesToLoad));
				_SrchColl.Add(new SearchResult(de,pcoll));
			}
			return;
		}
Ejemplo n.º 38
0
        /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.RefreshCache"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Loads the property values for this directory entry into
        ///       the property cache.
        ///    </para>
        /// </devdoc>
        public void RefreshCache()
        {
            Bind();
            try
            {
                _adsObject.GetInfo();
            }
            catch (COMException e)
            {
                throw COMExceptionHelper.CreateFormattedComException(e);
            }

            _cacheFilled = true;
            // we need to refresh that properties table.
            _propertyCollection = null;

            // need to refresh the objectSecurity property
            _objectSecurityInitialized = false;
            _objectSecurityModified = false;
        }
		/// <summary>
		/// Loads the values of the specified properties into the property cache.
		/// </summary>
		public void RefreshCache ()
		{
			// note that GetProperties must be called with false, elswere infinite loop will be caused
			PropertyCollection properties = new PropertyCollection ();
			LoadProperties(properties, null);
			SetProperties (properties);
		}
Ejemplo n.º 40
0
        /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.CommitChanges"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Saves any
        ///       changes to the entry in the directory store.
        ///    </para>
        /// </devdoc>
        public void CommitChanges()
        {
            if (_justCreated)
            {
                // Note: Permissions Demand is not necessary here, because entry has already been created with appr. permissions. 
                // Write changes regardless of Caching mode to finish construction of a new entry.
                try
                {
                    //
                    // Write the security descriptor to the cache
                    //
                    SetObjectSecurityInCache();

                    _adsObject.SetInfo();
                }
                catch (COMException e)
                {
                    throw COMExceptionHelper.CreateFormattedComException(e);
                }
                _justCreated = false;
                _objectSecurityInitialized = false;
                _objectSecurityModified = false;

                // we need to refresh that properties table.
                _propertyCollection = null;
                return;
            }
            if (!_useCache)
            {
                // unless we have modified the existing security descriptor (in-place) through ObjectSecurity property
                // there is nothing to do
                if ((_objectSecurity == null) || (!_objectSecurity.IsModified()))
                {
                    return;
                }
            }

            if (!Bound)
                return;

            try
            {
                //
                // Write the security descriptor to the cache
                //
                SetObjectSecurityInCache();
                _adsObject.SetInfo();
                _objectSecurityInitialized = false;
                _objectSecurityModified = false;
            }
            catch (COMException e)
            {
                throw COMExceptionHelper.CreateFormattedComException(e);
            }
            // we need to refresh that properties table.
            _propertyCollection = null;
        }
		private void SetProperties(PropertyCollection pcoll)
		{
			_Properties = pcoll;
		}
Ejemplo n.º 42
0
        public static DataSet GetGroupUsers(string domain, string userName, string password, string group)
        {
            DataSet groupMemebers = new DataSet();

            groupMemebers.Locale = CultureInfo.InvariantCulture;

            try
            {
                string            strPath = "LDAP://" + domain;
                DirectoryEntry    ent     = new DirectoryEntry(strPath, userName, password, AuthenticationTypes.Secure);
                DirectorySearcher srch    = new DirectorySearcher(ent);
                srch.Filter   = "(cn=" + group + ")";
                srch.PageSize = 1000;

                SearchResultCollection coll = srch.FindAll();
                foreach (SearchResult rs in coll)
                {
                    if (groupMemebers.Tables.Count == 0)
                    {
                        groupMemebers.Tables.Add();
                        groupMemebers.Tables[0].Columns.Add("USER_ID", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("DOMAIN", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("FIRST_NAME", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("LAST_NAME", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("EMAIL", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("RESIDENCE_ADDRESS", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("COMPANY", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("STATE", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("COUNTRY", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("PHONE", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("EXTENSION", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("FAX", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("DEPARTMENT", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("USER_NAME", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("CN", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("DISPLAY_NAME", typeof(string));
                        groupMemebers.Tables[0].Columns.Add("FULL_NAME", typeof(string));
                    }
                    ResultPropertyCollection resultPropColl = rs.Properties;

                    foreach (Object memberColl in resultPropColl["member"])
                    {
                        try
                        {
                            DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
                            System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;

                            string UserID           = userProps["sAMAccountName"].Value as string;
                            string firstName        = userProps["givenName"].Value as string;
                            string lastName         = userProps["sn"].Value as string;
                            string email            = userProps["mail"].Value as string;
                            string residenceAddress = userProps["homePostalAddress"].Value as string;
                            string company          = userProps["company"].Value as string;
                            string state            = userProps["st"].Value as string;
                            string country          = userProps["co"].Value as string;
                            string phone            = userProps["telephoneNumber"].Value as string;
                            string extension        = userProps["otherTelephone"].Value as string;
                            string fax         = userProps["facsimileTelephoneNumber"].Value as string;
                            string department  = userProps["department"].Value as string;
                            string UserName    = userProps["name"].Value as string;
                            string commonName  = userProps["cn"].Value as string;
                            string displayName = userProps["displayName"].Value as string;
                            string fullName    = userProps["fullName"].Value as string;

                            if (null != UserID)
                            {
                                groupMemebers.Tables[0].Rows.Add(UserID, domain, firstName, lastName, email, residenceAddress, company, state, country, phone, extension, fax, displayName, commonName, displayName, fullName, department);
                            }
                        }
                        catch (Exception ex)
                        {
                            string error = ex.Message;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
                throw;
            }
            return(groupMemebers);
        }
		/// <summary>
		/// Loads the values of the specified properties into the property cache.
		/// </summary>
		/// <param name="propertyNames">An array of the specified properties.</param>
		private void LoadProperties(PropertyCollection properties,string[] propertyNames)
		{
			_inPropertiesLoading = true;
			try	{
				LdapSearchResults lsc=conn.Search (Fdn,LdapConnection.SCOPE_BASE,"objectClass=*",propertyNames,false);
				if (lsc.hasMore ()) {
					LdapEntry nextEntry = lsc.next ();
					string [] lowcasePropertyNames = null;
					int length = 0;
					if (propertyNames != null) {
						length = propertyNames.Length;
						lowcasePropertyNames = new string [length];
						for(int i=0; i < length; i++)
							lowcasePropertyNames [i] = propertyNames [i].ToLower ();
					}
					foreach (LdapAttribute attribute in nextEntry.getAttributeSet ())	{
						string attributeName = attribute.Name;
						if ((propertyNames == null) || (Array.IndexOf (lowcasePropertyNames,attributeName.ToLower ()) != -1)) {
							properties [attributeName].Value = null;
							properties [attributeName].AddRange (attribute.StringValueArray);
							properties [attributeName].Mbit=false;
						}
					}
				}
			}
			finally {
				_inPropertiesLoading = false;
			}
		}
Ejemplo n.º 44
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator.ValuesEnumerator"]/*' />
 ///<internalonly/>
 public ValuesEnumerator(PropertyCollection propCollection)
 {
     this.propCollection = propCollection;
 }
Ejemplo n.º 45
0
 internal dSPropertyCollection(PropertyCollection pc) { _pc = pc; }
Ejemplo n.º 46
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysEnumerator.KeysEnumerator"]/*' />
 ///<internalonly/>
 public KeysEnumerator(PropertyCollection collection)
 : base(collection)
 {
 }
Ejemplo n.º 47
0
		/// <summary>
		/// Sets the WP.
		/// </summary>
		/// <param name="pc">The pc.</param>
		/// <param name="key">The key.</param>
		/// <param name="val">The val.</param>
		private void SetWP(
			PropertyCollection pc,
			string key,
			object val )
		{
			try
			{
				if ( pc[key] == null )
				{
					LogCentral.Current.LogWarn(
						string.Format(
						@"ActiveDirectory.SetWP(): 'pc[key]', with key='{0}' is null. Not setting.",
						key
						) );
				}
				else if ( pc[key].Count <= 0 )
				{
					LogCentral.Current.LogDebug(
						string.Format(
						@"ActiveDirectory.SetWP(): 'pc[key].Count', with key='{0}' is zero. Adding new value '{1}'.",
						key,
						val
						) );

					if ( debugSettedWPValues.Length > 0 )
					{
						debugSettedWPValues += @", ";
					}
					debugSettedWPValues += string.Format(
						@"'{0}'='{1}'",
						key,
						val );

					pc[key].Add( val );
				}
				else
				{
					LogCentral.Current.LogDebug(
						string.Format(
						@"ActiveDirectory.SetWP(): Setting 'pc[key][0]', with key='{0}' and value='{1}'.",
						key,
						val
						) );

					if ( debugSettedWPValues.Length > 0 )
					{
						debugSettedWPValues += @", ";
					}
					debugSettedWPValues += string.Format(
						@"'{0}'='{1}'",
						key,
						val );

					pc[key][0] = val;
				}
			}
			catch ( Exception x )
			{
				LogCentral.Current.LogError(
					string.Format(
					@"ActiveDirectory.SetWP(): Exception occured for setting key='{0}', value='{1}'.",
					key,
					val
					),
					x );

				throw;
			}
		}
Ejemplo n.º 48
0
    /*Given Domain, Username and Password, this method does authentication/validation of datas
     * by LDAP - Active Directory.
     * */
    public bool ValidateUserByLDAP(string domain, string username, string password)
    {
        General        g      = Session["app"] as General;
        bool           result = false;
        DirectoryEntry entry  = new DirectoryEntry(g.LDAPurl + "/" + g.LDAPContext, domain + @"\" + username, password);

        try
        {
            // Bind to the native AdsObject to force authentication.

            Object            obj    = entry.NativeObject;
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult resultUser = search.FindOne();

            if (null == resultUser)
            {
                return(false);                   //"Sorry, unable to verify your information";
            }
            string SQL = "SELECT iduser, username, type "
                         + "FROM usertab "
                         + "WHERE username='******' "
                         + "AND enabled = 1";

            OdbcCommand cmd = g.DB.PrepareSQL(SQL);

            try
            {
                OdbcDataReader resultUserDB = cmd.ExecuteReader();

                if (resultUserDB.HasRows)
                {
                    _idUser = resultUserDB["iduser"].ToString();
                    cmd.Dispose();
                    _Status = true;
                    result  = true;
                }
                else
                {
                    DirectorySearcher dirSearcher = new DirectorySearcher(
                        new DirectoryEntry(g.LDAPurl + "/" + g.LDAPContext), "(&(objectClass=user)(anr=" + username + "))",
                        new string[] { "sAMAccountName", "displayname", "sn", "givenName", "mail" });

                    string FirstName = "First Name", LastName = "Last Name", eMail = "";

                    foreach (SearchResult s in dirSearcher.FindAll())
                    {
                        System.DirectoryServices.PropertyCollection p = s.GetDirectoryEntry().Properties;

                        if (p["givenName"].Value != null)
                        {
                            FirstName = (string)p["givenName"].Value;
                        }
                        if (p["sn"].Value != null)
                        {
                            LastName = (string)p["sn"].Value;
                        }
                        if (p["mail"].Value != null)
                        {
                            eMail = (string)p["mail"].Value;
                        }
                    }

                    if (g.Users.eMailExist(eMail))
                    {
                        g.ErrorMSG = "e-Mail already exist! ";
                        return(false);
                    }
                    else
                    {
                        int i = 1;
                        while (g.Users.UserNameExist(username))
                        {
                            i++;
                        }
                        if (i > 1)
                        {
                            username += i.ToString();
                        }
                    }

                    if (g.Users.InsertUser(FirstName, LastName, username, eMail, g.getMd5Hash(password),
                                           "Standard", "LDAP", g.MakeMySQLDateTime(null), "1"))
                    {
                        result  = true;
                        _Status = true;
                    }
                    else
                    {
                        result = false;
                    }
                }

                resultUserDB.Close();
                resultUserDB.Dispose();
            }
            catch (OdbcException o)
            {
                result     = false;
                g.ErrorMSG = g.DB.catchODBCException(o, g.ErrorLevel);
            }
            finally
            {
                cmd.Dispose();
            }
        }
        catch (Exception ex)
        {
            result = false;//"Sorry, unable to verify your information";
        }
        return(result);
    }
 private void Unbind()
 {
     if (this.adsObject != null)
     {
         Marshal.ReleaseComObject(this.adsObject);
     }
     this.adsObject = null;
     this.propertyCollection = null;
     this.objectSecurityInitialized = false;
     this.objectSecurityModified = false;
 }
Ejemplo n.º 50
0
 private void SetProperties(PropertyCollection pcoll)
 {
     _Properties = pcoll;
 }
Ejemplo n.º 51
0
        //
        //
        //  This method will execute the process of searching the directory
        protected void m_searchDirectory()
        {
            DirectoryEntry    entry      = new DirectoryEntry("LDAP://OU=DC,DC=cov,DC=com");
            DirectorySearcher mySearcher = new DirectorySearcher(entry);


            //
            // Create a dataSet in which we can store dataTable
            //
            _dsUserInfo = new System.Data.DataSet("cbUserInfo");

            //
            // Create a dataTable in which we can store attributes from AD
            //
            _dtUserInfo = new System.Data.DataTable("cbUserInfo");


            //
            // Define datacolumns and stamp them with an appropriate datatype
            //
            _dc_cn              = new System.Data.DataColumn("u_cn");
            _dc_sn              = new System.Data.DataColumn("u_sn");
            _dc_givenName       = new System.Data.DataColumn("u_givenName");
            _dc_title           = new System.Data.DataColumn("u_title");
            _dc_telephoneNumber = new System.Data.DataColumn("u_telephoneNumber");
            _dc_otherTelephone  = new System.Data.DataColumn("u_otherTelephone");
            _dc_streetAddress   = new System.Data.DataColumn("u_streetAddress");
            _dc_email           = new System.Data.DataColumn("u_email");
            _dc_homePhone       = new System.Data.DataColumn("u_homePhone");
            _dc_bbPIN           = new System.Data.DataColumn("u_bbPIN");



            _dc_cn.DataType              = System.Type.GetType("System.String");
            _dc_sn.DataType              = System.Type.GetType("System.String");
            _dc_givenName.DataType       = System.Type.GetType("System.String");
            _dc_title.DataType           = System.Type.GetType("System.String");
            _dc_telephoneNumber.DataType = System.Type.GetType("System.String");
            _dc_otherTelephone.DataType  = System.Type.GetType("System.String");
            _dc_streetAddress.DataType   = System.Type.GetType("System.String");
            _dc_email.DataType           = System.Type.GetType("System.String");
            _dc_homePhone.DataType       = System.Type.GetType("System.String");
            _dc_bbPIN.DataType           = System.Type.GetType("System.String");



            //
            // Add the required columns to the datatable
            //
            _dtUserInfo.Columns.Add(_dc_cn);
            _dtUserInfo.Columns.Add(_dc_sn);
            _dtUserInfo.Columns.Add(_dc_givenName);
            _dtUserInfo.Columns.Add(_dc_title);
            _dtUserInfo.Columns.Add(_dc_telephoneNumber);
            _dtUserInfo.Columns.Add(_dc_otherTelephone);
            _dtUserInfo.Columns.Add(_dc_streetAddress);
            _dtUserInfo.Columns.Add(_dc_email);
            _dtUserInfo.Columns.Add(_dc_homePhone);
            _dtUserInfo.Columns.Add(_dc_bbPIN);

            //
            // Add the datatable to the dataset
            //
            _dsUserInfo.Tables.Add(_dtUserInfo);



            mySearcher.Filter = ("(anr= Jo)");
            foreach (SearchResult result in mySearcher.FindAll())
            {
                System.DirectoryServices.PropertyCollection myProps = result.GetDirectoryEntry().Properties;


                //
                // Define a new datarow
                //
                _drUserInfo = _dtUserInfo.NewRow();


                //
                // set local variables to the contents of user fields in AD
                //
                if (result.GetDirectoryEntry().Properties["cn"].Value != null)
                {
                    _cn = result.GetDirectoryEntry().Properties["cn"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["sn"].Value != null)
                {
                    _sn = result.GetDirectoryEntry().Properties["sn"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["givenName"].Value != null)
                {
                    _givenName = result.GetDirectoryEntry().Properties["givenName"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["title"].Value != null)
                {
                    _title = result.GetDirectoryEntry().Properties["title"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["telephoneNumber"].Value != null)
                {
                    _telephoneNumber = result.GetDirectoryEntry().Properties["telephoneNumber"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["otherTelephone"].Value != null)
                {
                    _otherTelephone = result.GetDirectoryEntry().Properties["otherTelephone"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["streetAddress"].Value != null)
                {
                    _streetAddress = result.GetDirectoryEntry().Properties["streetAddress"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["mail"].Value != null)
                {
                    _email = result.GetDirectoryEntry().Properties["mail"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["homePhone"].Value != null)
                {
                    _homePhone = result.GetDirectoryEntry().Properties["homePhone"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["extensionAttribute6"].Value != null)
                {
                    _bbPIN = result.GetDirectoryEntry().Properties["extensionAttribute6"].Value.ToString();
                }


                //
                // Populate the dataTable with the contents of local variables
                //
                _drUserInfo["U_cn"]              = _cn;
                _drUserInfo["U_sn"]              = _sn;
                _drUserInfo["U_givenName"]       = _givenName;
                _drUserInfo["u_title"]           = _title;
                _drUserInfo["u_telephoneNumber"] = _telephoneNumber;
                _drUserInfo["u_otherTelephone"]  = _otherTelephone;
                _drUserInfo["u_streetAddress"]   = _streetAddress;
                _drUserInfo["u_email"]           = _email;
                _drUserInfo["u_homePhone"]       = _homePhone;
                _drUserInfo["u_bbPIN"]           = _bbPIN;

                //
                // Add the new row to the underlying table
                //
                _dtUserInfo.Rows.Add(_drUserInfo);

                //
                // Output the values of the local variables to the page
                //
                Response.Output.Write("Record Count is: " + _dtUserInfo.Rows.Count + "<br><br>");
                Response.Output.Write(_cn + "<br>");
                Response.Output.Write(_sn + "<br>");
                Response.Output.Write(_givenName + "<br>");
                Response.Output.Write(_title + "<br>");
                Response.Output.Write(_telephoneNumber + "<br>");
                Response.Output.Write(_otherTelephone + "<br>");
                Response.Output.Write(_streetAddress + "<br>");
                Response.Output.Write("e-mail address: " + _email + "<br>");
                Response.Output.Write("Home Phone: " + _homePhone + "<br>");
                Response.Output.Write("Blackberry PIN: " + _bbPIN + "<br><br><br><br>");
            }
        }
        public string ippEmpLookup()
        {
            //
            //
            //  This method will execute the process of searching the directory
            // protected void m_searchDirectory() {
            DirectoryEntry    entry      = new DirectoryEntry("LDAP://DC=cov,DC=com");
            DirectorySearcher mySearcher = new DirectorySearcher(entry);


            //
            // Create a dataSet in which we can store dataTable
            //
            _dsUserInfo = new System.Data.DataSet("cbUserInfo");

            //
            // Create a dataTable in which we can store attributes from AD
            //
            _dtUserInfo = new System.Data.DataTable("cbUserInfo");


            //
            // Define datacolumns and stamp them with an appropriate datatype
            //
            //_dc_cn = new System.Data.DataColumn("u_cn");
            //_dc_sn = new System.Data.DataColumn("u_sn");
            //_dc_givenName = new System.Data.DataColumn("u_givenName");
            //_dc_title = new System.Data.DataColumn("u_title");
            //_dc_telephoneNumber = new System.Data.DataColumn("u_telephoneNumber");
            //_dc_otherTelephone = new System.Data.DataColumn("u_otherTelephone");
            //_dc_streetAddress = new System.Data.DataColumn("u_streetAddress");
            //_dc_email = new System.Data.DataColumn("u_email");
            //_dc_homePhone = new System.Data.DataColumn("u_homePhone");
            //_dc_bbPIN = new System.Data.DataColumn("u_bbPIN");



            //_dc_cn.DataType = System.Type.GetType("System.String");
            //_dc_sn.DataType = System.Type.GetType("System.String");
            //_dc_givenName.DataType = System.Type.GetType("System.String");
            //_dc_title.DataType = System.Type.GetType("System.String");
            //_dc_telephoneNumber.DataType = System.Type.GetType("System.String");
            //_dc_otherTelephone.DataType = System.Type.GetType("System.String");
            //_dc_streetAddress.DataType = System.Type.GetType("System.String");
            //_dc_email.DataType = System.Type.GetType("System.String");
            //_dc_homePhone.DataType = System.Type.GetType("System.String");
            //_dc_bbPIN.DataType = System.Type.GetType("System.String");



            //
            // Add the required columns to the datatable
            //
            //_dtUserInfo.Columns.Add(_dc_cn);
            //_dtUserInfo.Columns.Add(_dc_sn);
            //_dtUserInfo.Columns.Add(_dc_givenName);
            //_dtUserInfo.Columns.Add(_dc_title);
            //_dtUserInfo.Columns.Add(_dc_telephoneNumber);
            //_dtUserInfo.Columns.Add(_dc_otherTelephone);
            //_dtUserInfo.Columns.Add(_dc_streetAddress);
            //_dtUserInfo.Columns.Add(_dc_email);
            //_dtUserInfo.Columns.Add(_dc_homePhone);
            //_dtUserInfo.Columns.Add(_dc_bbPIN);

            //
            // Add the datatable to the dataset
            //
            //_dsUserInfo.Tables.Add(_dtUserInfo);



            //
            // Set content type for data returned to the phone
            //Response.ContentType = "text/xml";


            //
            // Begin Framing the directory entries returned to the phone
            _xmlHeader  = "<CiscoIPPhoneDirectory>";
            _xmlHeader += "<Title>Corpoate Directory</Title>";
            _xmlHeader += "<Prompt> </Prompt>";

            //
            // Get query param and build ldap query
            lName = this.Context.Request.QueryString["lName"];
            fName = this.Context.Request.QueryString["fName"];
            extN  = this.Context.Request.QueryString["extension"];
            ldpQ  = String.Format("(&(sn={0}*)(givenName={1}*)(otherTelephone={2}*))", lName, fName, extN);


            mySearcher.Filter = (ldpQ);
            foreach (SearchResult result in mySearcher.FindAll())
            {
                System.DirectoryServices.PropertyCollection myProps = result.GetDirectoryEntry().Properties;


                //
                // Define a new datarow
                //
                // _drUserInfo = _dtUserInfo.NewRow();


                //
                // set local variables to the contents of user fields in AD
                //
                if (result.GetDirectoryEntry().Properties["cn"].Value != null)
                {
                    _cn = result.GetDirectoryEntry().Properties["cn"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["sn"].Value != null)
                {
                    _sn = result.GetDirectoryEntry().Properties["sn"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["givenName"].Value != null)
                {
                    _givenName = result.GetDirectoryEntry().Properties["givenName"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["title"].Value != null)
                {
                    _title = result.GetDirectoryEntry().Properties["title"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["telephoneNumber"].Value != null)
                {
                    _telephoneNumber = result.GetDirectoryEntry().Properties["telephoneNumber"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["otherTelephone"].Value != null)
                {
                    _otherTelephone = result.GetDirectoryEntry().Properties["otherTelephone"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["streetAddress"].Value != null)
                {
                    _streetAddress = result.GetDirectoryEntry().Properties["streetAddress"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["mail"].Value != null)
                {
                    _email = result.GetDirectoryEntry().Properties["mail"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["homePhone"].Value != null)
                {
                    _homePhone = result.GetDirectoryEntry().Properties["homePhone"].Value.ToString();
                }

                if (result.GetDirectoryEntry().Properties["extensionAttribute6"].Value != null)
                {
                    _bbPIN = result.GetDirectoryEntry().Properties["extensionAttribute6"].Value.ToString();
                }


                //
                // Populate the dataTable with the contents of local variables
                //
                //_drUserInfo["U_cn"] = _cn;
                //_drUserInfo["U_sn"] = _sn;
                //_drUserInfo["U_givenName"] = _givenName;
                //_drUserInfo["u_title"] = _title;
                //_drUserInfo["u_telephoneNumber"] = _telephoneNumber;
                //_drUserInfo["u_otherTelephone"] = _otherTelephone;
                //_drUserInfo["u_streetAddress"] = _streetAddress;
                //_drUserInfo["u_email"] = _email;
                //_drUserInfo["u_homePhone"] = _homePhone;
                //_drUserInfo["u_bbPIN"] = _bbPIN;

                //
                // Add the new row to the underlying table
                //
                //_dtUserInfo.Rows.Add(_drUserInfo);

                //
                // Output the directory entries and send to the phone
                //
                _xmlTemp += "<DirectoryEntry>";
                _xmlTemp += "<Name>" + _sn + ", " + _givenName + "</Name>";
                _xmlTemp += "<Telephone>" + _otherTelephone + "</Telephone>";
                _xmlTemp += "</DirectoryEntry>";
            }
            _xmlFooter   = "</CiscoIPPhoneDirectory>";
            _xmlResponse = _xmlHeader + _xmlTemp + _xmlFooter;

            return(_xmlResponse);
        }
        //
        //
        //
        //
        // This method is responsible for handling the results to be returned to the phone
        protected string m_formulateCD(SearchResultCollection src_DEs, Int32 n_startingRecord, Int32 n_maxRecords)
        {
            Int32 i = 0;

            string str_xml = "";


            if (n_maxRecords <= 32)
            {
                foreach (SearchResult src_DEs_r in src_DEs)
                {
                    System.DirectoryServices.PropertyCollection myProps = src_DEs_r.GetDirectoryEntry().Properties;
                    //
                    // set local variables to the contents of user fields in AD
                    //
                    if (src_DEs_r.GetDirectoryEntry().Properties["cn"].Value != null)
                    {
                        _cn = src_DEs_r.GetDirectoryEntry().Properties["cn"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["sn"].Value != null)
                    {
                        _sn = src_DEs_r.GetDirectoryEntry().Properties["sn"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["givenName"].Value != null)
                    {
                        _givenName = src_DEs_r.GetDirectoryEntry().Properties["givenName"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["title"].Value != null)
                    {
                        _title = src_DEs_r.GetDirectoryEntry().Properties["title"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["telephoneNumber"].Value != null)
                    {
                        _telephoneNumber = src_DEs_r.GetDirectoryEntry().Properties["telephoneNumber"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["otherTelephone"].Value != null)
                    {
                        _otherTelephone = src_DEs_r.GetDirectoryEntry().Properties["otherTelephone"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["streetAddress"].Value != null)
                    {
                        _streetAddress = src_DEs_r.GetDirectoryEntry().Properties["streetAddress"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["mail"].Value != null)
                    {
                        _email = src_DEs_r.GetDirectoryEntry().Properties["mail"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["homePhone"].Value != null)
                    {
                        _homePhone = src_DEs_r.GetDirectoryEntry().Properties["homePhone"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["extensionAttribute6"].Value != null)
                    {
                        _bbPIN = src_DEs_r.GetDirectoryEntry().Properties["extensionAttribute6"].Value.ToString();
                    }


                    str_xml += "<DirectoryEntry>";
                    str_xml += "<Name>";
                    str_xml += _sn;
                    str_xml += ", ";
                    str_xml += _givenName;
                    str_xml += "</Name>";
                    str_xml += "<Telephone>";
                    str_xml += _otherTelephone;
                    str_xml += "</Telephone>";
                    str_xml += "</DirectoryEntry>";
                }
            }
            else
            {
                if (n_startingRecord == 0)
                {
                    i++;
                }
                else
                {
                    i = n_startingRecord;
                }

                foreach (SearchResult src_DEs_r in src_DEs)
                {
                    System.DirectoryServices.PropertyCollection myProps = src_DEs_r.GetDirectoryEntry().Properties;
                    //
                    // set local variables to the contents of user fields in AD
                    //
                    if (src_DEs_r.GetDirectoryEntry().Properties["cn"].Value != null)
                    {
                        _cn = src_DEs_r.GetDirectoryEntry().Properties["cn"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["sn"].Value != null)
                    {
                        _sn = src_DEs_r.GetDirectoryEntry().Properties["sn"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["givenName"].Value != null)
                    {
                        _givenName = src_DEs_r.GetDirectoryEntry().Properties["givenName"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["title"].Value != null)
                    {
                        _title = src_DEs_r.GetDirectoryEntry().Properties["title"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["telephoneNumber"].Value != null)
                    {
                        _telephoneNumber = src_DEs_r.GetDirectoryEntry().Properties["telephoneNumber"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["otherTelephone"].Value != null)
                    {
                        _otherTelephone = src_DEs_r.GetDirectoryEntry().Properties["otherTelephone"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["streetAddress"].Value != null)
                    {
                        _streetAddress = src_DEs_r.GetDirectoryEntry().Properties["streetAddress"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["mail"].Value != null)
                    {
                        _email = src_DEs_r.GetDirectoryEntry().Properties["mail"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["homePhone"].Value != null)
                    {
                        _homePhone = src_DEs_r.GetDirectoryEntry().Properties["homePhone"].Value.ToString();
                    }

                    if (src_DEs_r.GetDirectoryEntry().Properties["extensionAttribute6"].Value != null)
                    {
                        _bbPIN = src_DEs_r.GetDirectoryEntry().Properties["extensionAttribute6"].Value.ToString();
                    }


                    if (((i <= n_maxRecords) && ((i % 32) != 0)))
                    {
                        str_xml += "<DirectoryEntry>";
                        str_xml += "<Name>";
                        str_xml += _sn;
                        str_xml += ", ";
                        str_xml += _givenName;
                        str_xml += "</Name>";
                        str_xml += "<Telephone>";
                        str_xml += _otherTelephone;
                        str_xml += "</Telephone>";
                        str_xml += "</DirectoryEntry>";
                    }

                    i++;
                }

                Response.AppendHeader("Refresh", "0; http://cbivws06dc/IPPWS/CorporateDirectory/?qReqNext=" + i);
            }

            return(str_xml);
        }
Ejemplo n.º 54
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.ValuesCollection"]/*' />
 ///<internalonly/>
 public ValuesCollection(PropertyCollection props)
 {
     this.props = props;
 }
Ejemplo n.º 55
0
        private void Unbind()
        {
            if (_adsObject != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject);
            _adsObject = null;
            // we need to release that properties table.
            _propertyCollection = null;

            // need to refresh the objectSecurity property
            _objectSecurityInitialized = false;
            _objectSecurityModified = false;
        }
Ejemplo n.º 56
0
 /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysCollection.KeysCollection"]/*' />
 ///<internalonly/>
 public KeysCollection(PropertyCollection props)
 : base(props)
 {
 }
Ejemplo n.º 57
0
        internal void CommitIfNotCaching()
        {
            if (_justCreated)
                return;   // Do not write changes, beacuse the entry is just under construction until CommitChanges() is called.

            if (_useCache)
                return;

            if (!Bound)
                return;

            // do full demand before we commit changes back to the server
            new DirectoryServicesPermission(PermissionState.Unrestricted).Demand();

            try
            {
                //
                // Write the security descriptor to the cache
                //
                SetObjectSecurityInCache();

                _adsObject.SetInfo();
                _objectSecurityInitialized = false;
                _objectSecurityModified = false;
            }
            catch (COMException e)
            {
                throw COMExceptionHelper.CreateFormattedComException(e);
            }
            // we need to refresh that properties table.
            _propertyCollection = null;
        }
Ejemplo n.º 58
0
		internal dSPropertyCollection(PropertyCollection pc)
		{
			this.pc = pc;
		}