Represents a single entry in a directory, consisting of a distinguished name (DN) and zero or more attributes. An instance of LdapEntry is created in order to add an entry to a directory, and instances of LdapEntry are returned on a search by enumerating an LdapSearchResults.
Inheritance: System.IComparable
Exemplo n.º 1
0
        public static string[] CheckRequiredAttributes(Connection conn, LdapEntry entry)
        {
            List<string> missingAttributes = new List<string> ();

            LdapAttribute objAttr = entry.getAttribute ("objectClass");
            if (objAttr == null)
                return null;

            foreach (string o in objAttr.StringValueArray) {
                if (o.Equals ("top"))
                    continue;

                string[] reqs = conn.Data.GetRequiredAttrs (o);
                if (reqs == null)
                    continue;

                foreach (string r in reqs) {
                    if (r.Equals ("cn"))
                        continue;

                    if (IsAttributeEmpty (entry.getAttribute (r))) {
                        missingAttributes.Add (r);
                        continue;
                    }
                }
            }

            return missingAttributes.ToArray();
        }
Exemplo n.º 2
0
 /// <summary> Constructs an LdapSearchResult object from an LdapEntry.
 /// 
 /// </summary>
 /// <param name="entry">the LdapEntry represented by this search result.
 /// 
 /// </param>
 /// <param name="cont">controls associated with the search result
 /// </param>
 public LdapSearchResult(LdapEntry entry, LdapControl[] cont)
     : base()
 {
     if (entry == null)
     {
         throw new System.ArgumentException("Argument \"entry\" cannot be null");
     }
     this.entry = entry;
     return ;
 }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            if ( args.Length != 5)
            {
            Console.WriteLine("Usage:   mono AddEntry <host name> <ldap port>  <login dn>" + " <password> <container>");
            Console.WriteLine("Example: mono AddEntry Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String password = args[3];
            String containerName = args[4];

            try
            {
            LdapAttributeSet attributeSet = new LdapAttributeSet();
            attributeSet.Add(	new LdapAttribute(
                                "objectclass", "inetOrgPerson"));
                                attributeSet.Add( new LdapAttribute("cn",
                                new string[]{"James Smith", "Jim Smith", "Jimmy Smith"}));
            attributeSet.Add(	new LdapAttribute("givenname",
                                 "James"));
            attributeSet.Add(	new LdapAttribute("sn", "Smith"));
            attributeSet.Add(	new LdapAttribute("telephonenumber","1 801 555 1212"));
            attributeSet.Add(	new LdapAttribute("mail", "*****@*****.**"));
            attributeSet.Add(	new LdapAttribute("userpassword","newpassword"));

            string  dn  = "cn=KSmith," + containerName;
            LdapEntry newEntry = new LdapEntry( dn, attributeSet );
            LdapConnection conn= new LdapConnection();
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            conn.Add( newEntry );
            Console.WriteLine("Entry:" + dn + "  Added Successfully");
            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Exemplo n.º 4
0
        public HostsViewDialog(Connection connection, LdapEntry le)
            : base(connection, null)
        {
            isEdit = true;
            currentEntry = le;

            Init ();

            string hostName = conn.Data.GetAttributeValueFromEntry (currentEntry, "cn");
            hostDialog.Title = hostName + " Properties";
            hostNameEntry.Text = hostName;

            ipEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "ipHostNumber");
            descriptionEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "description");

            hostDialog.Run ();
            hostDialog.Destroy ();
        }
Exemplo n.º 5
0
        public EditAdComputerViewDialog(Connection connection, LdapEntry le)
            : base(connection, null)
        {
            currentEntry = le;

            Init ();

            computerNameLabel.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "cn");

            string cpName = (string) conn.Data.GetAttributeValueFromEntry (currentEntry, "cn");
            computerNameEntry.Text = cpName.ToUpper();

            editAdComputerDialog.Title = cpName + " Properties";

            dnsNameEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "dNSHostName");
            descriptionEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "description");

            osNameEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "operatingSystem");
            osVersionEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "operatingSystemVersion");
            osServicePackEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "operatingSystemServicePack");

            locationEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "location");

            string manName = conn.Data.GetAttributeValueFromEntry (currentEntry, "managedBy");
            manNameEntry.Text = manName;

            if (manName != "" || manName != null)
                updateManagedBy (manName);

            editAdComputerDialog.Icon = Global.latIcon;
            editAdComputerDialog.Run ();

            while (missingValues || errorOccured) {
                if (missingValues)
                    missingValues = false;
                else if (errorOccured)
                    errorOccured = false;

                editAdComputerDialog.Run ();
            }

            editAdComputerDialog.Destroy ();
        }
Exemplo n.º 6
0
        public GroupsViewDialog(Connection connection, LdapEntry le)
            : base(connection, null)
        {
            currentEntry = le;

            isEdit = true;

            Init ();

            string groupName = conn.Data.GetAttributeValueFromEntry (currentEntry, "cn");

            groupDialog.Title = groupName + " Properties";
            groupNameEntry.Text = groupName;
            descriptionEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "description");

            LdapAttribute attr = currentEntry.getAttribute ("member");
            if (attr != null) {
                foreach (string s in attr.StringValueArray) {
                    LdapEntry userEntry = conn.Data.GetEntry (s);
                    LdapAttribute userNameAttribute = userEntry.getAttribute ("name");

                    currentMemberStore.AppendValues (userNameAttribute.StringValue);
                    currentMembers.Add (userNameAttribute.StringValue);
                }
            }

            populateUsers ();

            groupDialog.Run ();

            while (missingValues || errorOccured){
                if (missingValues)
                    missingValues = false;
                else if (errorOccured)
                    errorOccured = false;

                groupDialog.Run ();
            }

            groupDialog.Destroy ();
        }
Exemplo n.º 7
0
        public void OnOkClicked(object o, EventArgs args)
        {
            string dn = String.Format ("{0},{1}", rdnEntry.Text, browseButton.Label);
            LdapAttributeSet lset = new LdapAttributeSet ();

            foreach (object[] row in attrListStore) {

                string n = (string) row[0];
                string v = (string) row[1];

                if (n == null || v == null || v == "")
                    continue;

                if (n.ToLower() == "objectclass") {
                    if (objAttr == null)
                        objAttr = new LdapAttribute (n, v);
                    else
                        objAttr.addValue (v);

                } else {

                    LdapAttribute attr = new LdapAttribute (n, v);
                    lset.Add (attr);
                }
            }

            lset.Add (objAttr);

            LdapEntry entry = new LdapEntry (dn, lset);
            if (!Util.AddEntry (conn, entry))
                errorOccured = true;
            else
                errorOccured = false;
        }
Exemplo n.º 8
0
        void DoInsert(LdapEntry[] objs, string[] attributes)
        {
            try {

                if (this.dataStore != null)
                    this.dataStore.Clear ();

                foreach (LdapEntry le in objs) {

                    string[] values = conn.Data.GetAttributeValuesFromEntry (le, attributes);
                    string[] newvalues = new string [values.Length + 1];

                    values.CopyTo (newvalues, 0);
                    newvalues [values.Length] = le.DN;

                    this.dataStore.AppendValues (newvalues);
                }

            } catch {

                string	msg = Mono.Unix.Catalog.GetString (
                    "Unable to read data from server");

                HIGMessageDialog dialog = new HIGMessageDialog (
                    parentWindow,
                    0,
                    Gtk.MessageType.Error,
                    Gtk.ButtonsType.Ok,
                    "Network error",
                    msg);

                dialog.Run ();
                dialog.Destroy ();
            }
        }
Exemplo n.º 9
0
		//*************************************************************************
		// add methods
		//*************************************************************************
		
		/// <summary> Synchronously adds an entry to the directory.
		/// 
		/// </summary>
		/// <param name="entry">   LdapEntry object specifying the distinguished
		/// name and attributes of the new entry.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// </exception>
		public virtual void  Add(LdapEntry entry)
		{
			Add(entry, defSearchCons);
			return ;
		}
Exemplo n.º 10
0
		/// <summary> Asynchronously adds an entry to the directory.
		/// 
		/// </summary>
		/// <param name="entry">  LdapEntry object specifying the distinguished
		/// name and attributes of the new entry.
		/// 
		/// </param>
		/// <param name="queue">  Handler for messages returned from a server in
		/// response to this request. If it is null, a
		/// queue object is created internally.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// </exception>
		public virtual LdapResponseQueue Add(LdapEntry entry, LdapResponseQueue queue)
		{
			return Add(entry, queue, defSearchCons);
		}
Exemplo n.º 11
0
Arquivo: Util.cs Projeto: MrJoe/lat
        public static bool AddEntry(Connection conn, LdapEntry entry)
        {
            try {

                conn.Data.Add (entry);
                return true;

            } catch (Exception e) {

                string errorMsg = Mono.Unix.Catalog.GetString ("Unable to add entry ") + entry.DN;
                errorMsg += "\nError: " + e.Message;

                Log.Debug (e);

                HIGMessageDialog dialog = new HIGMessageDialog (
                        null,
                        0,
                        Gtk.MessageType.Error,
                        Gtk.ButtonsType.Ok,
                        "Add error",
                        errorMsg);

                dialog.Run ();
                dialog.Destroy ();

                return false;
            }
        }
Exemplo n.º 12
0
        LdapEntry CreateEntry(string dn)
        {
            LdapAttributeSet aset = new LdapAttributeSet();
            aset.Add (new LdapAttribute ("objectClass", new string[] {"top", "person", "organizationalPerson", "contact" }));
            aset.Add (new LdapAttribute ("givenName", gnFirstNameEntry.Text));
            aset.Add (new LdapAttribute ("initials", gnInitialsEntry.Text));
            aset.Add (new LdapAttribute ("sn", gnLastNameEntry.Text));
            aset.Add (new LdapAttribute ("displayName", gnDisplayName.Text));
            aset.Add (new LdapAttribute ("cn", gnDisplayName.Text));
            aset.Add (new LdapAttribute ("wWWHomePage", gnWebPageEntry.Text));
            aset.Add (new LdapAttribute ("physicalDeliveryOfficeName", gnOfficeEntry.Text));
            aset.Add (new LdapAttribute ("mail", gnEmailEntry.Text));
            aset.Add (new LdapAttribute ("description", gnDescriptionEntry.Text));
            aset.Add (new LdapAttribute ("street", adStreetTextView.Buffer.Text));
            aset.Add (new LdapAttribute ("l", adCityEntry.Text));
            aset.Add (new LdapAttribute ("st", adStateEntry.Text));
            aset.Add (new LdapAttribute ("postalCode", adZipEntry.Text));
            aset.Add (new LdapAttribute ("postOfficeBox", adPOBoxEntry.Text));
            aset.Add (new LdapAttribute ("co", adCountryEntry.Text));
            aset.Add (new LdapAttribute ("telephoneNumber", gnTelephoneNumberEntry.Text));
            aset.Add (new LdapAttribute ("facsimileTelephoneNumber", tnFaxEntry.Text));
            aset.Add (new LdapAttribute ("pager", tnPagerEntry.Text));
            aset.Add (new LdapAttribute ("mobile", tnMobileEntry.Text));
            aset.Add (new LdapAttribute ("homePhone", tnHomeEntry.Text));
            aset.Add (new LdapAttribute ("ipPhone", tnIPPhoneEntry.Text));
            aset.Add (new LdapAttribute ("title", ozTitleEntry.Text));
            aset.Add (new LdapAttribute ("department", ozDeptEntry.Text));
            aset.Add (new LdapAttribute ("company", ozCompanyEntry.Text));
            aset.Add (new LdapAttribute ("streetAddress", adStreetTextView.Buffer.Text));
            aset.Add (new LdapAttribute ("info", tnNotesTextView.Buffer.Text));

            LdapEntry newEntry = new LdapEntry (dn, aset);
            return newEntry;
        }
Exemplo n.º 13
0
 /// <summary> Constructs a request to add an entry to the directory.
 ///
 /// </summary>
 /// <param name="entry">The LdapEntry to add to the directory.
 ///
 /// </param>
 /// <param name="cont">Any controls that apply to the add request,
 /// or null if none.
 /// </param>
 public LdapAddRequest(LdapEntry entry, LdapControl[] cont) : base(ADD_REQUEST, new RfcAddRequest(new RfcLdapDN(entry.DN), makeRfcAttrList(entry)), cont)
 {
 }
Exemplo n.º 14
0
		/// <summary> Constructs an LdapSchema object from attributes of an LdapEntry.
		/// The object is empty if the entry parameter contains no schema
		/// attributes.  The recognized schema attributes are the following: 
		/// <pre><code>
		/// "attributeTypes", "objectClasses", "ldapSyntaxes",
		/// "nameForms", "dITContentRules", "dITStructureRules",
		/// "matchingRules","matchingRuleUse"
		/// </code></pre>
		/// </summary>
		/// <param name="ent">         An LdapEntry containing schema information.
		/// </param>
		public LdapSchema(LdapEntry ent):base(ent.DN, ent.getAttributeSet())
		{
			InitBlock();
			//reset all definitions
			for (int i = 0; i < schemaTypeNames.Length; i++)
			{
				idTable[i] = new System.Collections.Hashtable();
				nameTable[i] = new System.Collections.Hashtable();
			}
			System.Collections.IEnumerator itr = base.getAttributeSet().GetEnumerator();
			while (itr.MoveNext())
			{
				
				LdapAttribute attr = (LdapAttribute) itr.Current;
				System.String value_Renamed, attrName = attr.Name;
				System.Collections.IEnumerator enumString = attr.StringValues;
				
				if (attrName.ToUpper().Equals(schemaTypeNames[OBJECT_CLASS].ToUpper()))
				{
					LdapObjectClassSchema classSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						try
						{
							classSchema = new LdapObjectClassSchema(value_Renamed);
						}
						catch (System.Exception e)
						{
							continue; //Error parsing: do not add this definition
						}
						addElement(OBJECT_CLASS, classSchema);
					}
				}
				else if (attrName.ToUpper().Equals(schemaTypeNames[ATTRIBUTE].ToUpper()))
				{
					LdapAttributeSchema attrSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						try
						{
							attrSchema = new LdapAttributeSchema(value_Renamed);
						}
						catch (System.Exception e)
						{
							continue; //Error parsing: do not add this definition
						}
						addElement(ATTRIBUTE, attrSchema);
					}
				}
				else if (attrName.ToUpper().Equals(schemaTypeNames[SYNTAX].ToUpper()))
				{
					LdapSyntaxSchema syntaxSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						syntaxSchema = new LdapSyntaxSchema(value_Renamed);
						addElement(SYNTAX, syntaxSchema);
					}
				}
				else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING].ToUpper()))
				{
					LdapMatchingRuleSchema matchingRuleSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						matchingRuleSchema = new LdapMatchingRuleSchema(value_Renamed, null);
						addElement(MATCHING, matchingRuleSchema);
					}
				}
				else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING_USE].ToUpper()))
				{
					LdapMatchingRuleUseSchema matchingRuleUseSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						matchingRuleUseSchema = new LdapMatchingRuleUseSchema(value_Renamed);
						addElement(MATCHING_USE, matchingRuleUseSchema);
					}
				}
				else if (attrName.ToUpper().Equals(schemaTypeNames[DITCONTENT].ToUpper()))
				{
					LdapDITContentRuleSchema dITContentRuleSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						dITContentRuleSchema = new LdapDITContentRuleSchema(value_Renamed);
						addElement(DITCONTENT, dITContentRuleSchema);
					}
				}
				else if (attrName.ToUpper().Equals(schemaTypeNames[DITSTRUCTURE].ToUpper()))
				{
					LdapDITStructureRuleSchema dITStructureRuleSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						dITStructureRuleSchema = new LdapDITStructureRuleSchema(value_Renamed);
						addElement(DITSTRUCTURE, dITStructureRuleSchema);
					}
				}
				else if (attrName.ToUpper().Equals(schemaTypeNames[NAME_FORM].ToUpper()))
				{
					LdapNameFormSchema nameFormSchema;
					while (enumString.MoveNext())
					{
						value_Renamed = ((System.String) enumString.Current);
						nameFormSchema = new LdapNameFormSchema(value_Renamed);
						addElement(NAME_FORM, nameFormSchema);
					}
				}
				//All non schema attributes are ignored.
				continue;
			}
		}
Exemplo n.º 15
0
        /// <summary>
        ///     Constructs an LdapSchema object from attributes of an LdapEntry.
        ///     The object is empty if the entry parameter contains no schema
        ///     attributes.  The recognized schema attributes are the following:.
        ///     <pre>
        ///         <code>
        /// "attributeTypes", "objectClasses", "ldapSyntaxes",
        /// "nameForms", "dITContentRules", "dITStructureRules",
        /// "matchingRules","matchingRuleUse"
        /// </code>
        ///     </pre>
        /// </summary>
        /// <param name="ent">
        ///     An LdapEntry containing schema information.
        /// </param>
        public LdapSchema(LdapEntry ent)
            : base(ent.Dn, ent.GetAttributeSet())
        {
            _nameTable = new List <Dictionary <string, LdapSchemaElement> >(8);
            _idTable   = new List <Dictionary <string, LdapSchemaElement> >(8);

            // reset all definitions
            for (var i = 0; i < SchemaTypeNames.Length; i++)
            {
                _idTable[i]   = new Dictionary <string, LdapSchemaElement>();
                _nameTable[i] = new Dictionary <string, LdapSchemaElement>();
            }

            var itr = GetAttributeSet().GetEnumerator();

            while (itr.MoveNext())
            {
                var    attr = (LdapAttribute)itr.Current;
                string valueRenamed, attrName = attr.Name;
                var    enumString = attr.StringValues;

                if (attrName.EqualsOrdinalCI(SchemaTypeNames[ObjectClass]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        LdapObjectClassSchema classSchema;
                        try
                        {
                            classSchema = new LdapObjectClassSchema(valueRenamed);
                        }
                        catch (Exception e)
                        {
                            Logger.Log.LogWarning("Exception swallowed", e);
                            continue; // Error parsing: do not add this definition
                        }

                        AddElement(ObjectClass, classSchema);
                    }
                }
                else if (attrName.EqualsOrdinalCI(SchemaTypeNames[Attribute]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        LdapAttributeSchema attrSchema;
                        try
                        {
                            attrSchema = new LdapAttributeSchema(valueRenamed);
                        }
                        catch (Exception e)
                        {
                            Logger.Log.LogWarning("Exception swallowed", e);
                            continue; // Error parsing: do not add this definition
                        }

                        AddElement(Attribute, attrSchema);
                    }
                }
                else if (attrName.EqualsOrdinalCI(SchemaTypeNames[Syntax]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        var syntaxSchema = new LdapSyntaxSchema(valueRenamed);
                        AddElement(Syntax, syntaxSchema);
                    }
                }
                else if (attrName.EqualsOrdinalCI(SchemaTypeNames[Matching]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        var matchingRuleSchema = new LdapMatchingRuleSchema(valueRenamed, null);
                        AddElement(Matching, matchingRuleSchema);
                    }
                }
                else if (attrName.EqualsOrdinalCI(SchemaTypeNames[MatchingUse]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        var matchingRuleUseSchema = new LdapMatchingRuleUseSchema(valueRenamed);
                        AddElement(MatchingUse, matchingRuleUseSchema);
                    }
                }
                else if (attrName.EqualsOrdinalCI(SchemaTypeNames[Ditcontent]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        var dItContentRuleSchema = new LdapDitContentRuleSchema(valueRenamed);
                        AddElement(Ditcontent, dItContentRuleSchema);
                    }
                }
                else if (attrName.EqualsOrdinalCI(SchemaTypeNames[Ditstructure]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        var dItStructureRuleSchema = new LdapDitStructureRuleSchema(valueRenamed);
                        AddElement(Ditstructure, dItStructureRuleSchema);
                    }
                }
                else if (attrName.EqualsOrdinalCI(SchemaTypeNames[NameForm]))
                {
                    while (enumString.MoveNext())
                    {
                        valueRenamed = enumString.Current;
                        var nameFormSchema = new LdapNameFormSchema(valueRenamed);
                        AddElement(NameForm, nameFormSchema);
                    }
                }

                // All non schema attributes are ignored.
            }
        }
Exemplo n.º 16
0
		private void CommitEntry()
		{
			if(!Nflag)
			{
				System.Collections.ArrayList modList = new System.Collections.ArrayList();
				System.Collections.IDictionaryEnumerator id = Properties.GetEnumerator();
				while(id.MoveNext())
				{
					string attribute=(string)id.Key;
					LdapAttribute attr=null;
					if(Properties[attribute].Mbit)
					{
						if(Properties[attribute].Count==1)
						{
							String val = (String)Properties[attribute].Value;
							attr = 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);
							attr = new LdapAttribute( attribute , aStrVals);
						}
						modList.Add( new LdapModification(LdapModification.REPLACE, attr));
						Properties[attribute].Mbit=false;
					}
				}
				if (modList.Count > 0) {
					LdapModification[] mods = new LdapModification[modList.Count]; 	
					Type mtype=Type.GetType("System.DirectoryServices.LdapModification");
					mods = (LdapModification[])modList.ToArray(typeof(LdapModification));
					ModEntry(mods);
				}
			}
			else
			{
				LdapAttributeSet attributeSet = new LdapAttributeSet();
				System.Collections.IDictionaryEnumerator id = Properties.GetEnumerator();
				while(id.MoveNext())
				{
					string attribute=(string)id.Key;
					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;
			}
		}
Exemplo n.º 17
0
        /// <summary> Compares the the attributes of the first LdapEntry to the second.
        /// Only the values of the attributes named at the construction of this
        /// object will be compared.  Multi-valued attributes compare on the first
        /// value only.
        ///
        /// </summary>
        /// <param name="object1">        Target entry for comparison.
        ///
        /// </param>
        /// <param name="object2">        Entry to be compared to.
        ///
        /// </param>
        /// <returns>     Negative value if the first entry is less than the second and
        /// positive if the first is greater than the second.  Zero is returned if all
        /// attributes to be compared are the same.
        /// </returns>
        public virtual int Compare(object object1, object object2)
        {
            LdapEntry     entry1 = (LdapEntry)object1;
            LdapEntry     entry2 = (LdapEntry)object2;
            LdapAttribute one, two;

            string[] first;  //multivalued attributes are ignored.
            string[] second; //we just use the first element
            int      compare, i = 0;

            if (collator == null)
            {
                //using default locale
                collator = CultureInfo.CurrentCulture.CompareInfo;
            }

            do
            {
                //while first and second are equal
                one = entry1.getAttribute(sortByNames[i]);
                two = entry2.getAttribute(sortByNames[i]);
                if ((one != null) && (two != null))
                {
                    first   = one.StringValueArray;
                    second  = two.StringValueArray;
                    compare = collator.Compare(first[0], second[0]);
                }
                //We could also use the other multivalued attributes to break ties.
                //one of the entries was null
                else
                {
                    if (one != null)
                    {
                        compare = -1;
                    }
                    //one is greater than two
                    else if (two != null)
                    {
                        compare = 1;
                    }
                    //one is lesser than two
                    else
                    {
                        compare = 0; //tie - break it with the next attribute name
                    }
                }

                i++;
            }while ((compare == 0) && (i < sortByNames.Length));

            if (sortAscending[i - 1])
            {
                // return the normal ascending comparison.
                return(compare);
            }
            else
            {
                // negate the comparison for a descending comparison.
                return(-compare);
            }
        }
Exemplo n.º 18
0
        LdapEntry CreateEntry(string dn)
        {
            LdapAttributeSet aset = new LdapAttributeSet();
            aset.Add (new LdapAttribute ("objectClass", new string[] {"computer"}));
            aset.Add (new LdapAttribute ("cn", computerNameLabel.Text));
            aset.Add (new LdapAttribute ("description", descriptionEntry.Text));
            aset.Add (new LdapAttribute ("dNSHostName", dnsNameEntry.Text));
            aset.Add (new LdapAttribute ("operatingSystem", osNameEntry.Text));
            aset.Add (new LdapAttribute ("operatingSystemVersion", osVersionEntry.Text));
            aset.Add (new LdapAttribute ("operatingSystemServicePack", osServicePackEntry.Text));
            aset.Add (new LdapAttribute ("location", locationEntry.Text));
            aset.Add (new LdapAttribute ("managedBy", manNameEntry.Text));

            LdapEntry newEntry = new LdapEntry (dn, aset);
            return newEntry;
        }
Exemplo n.º 19
0
        public CreateEntryDialog(Connection connection, LdapEntry le)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");
            if (le == null)
                throw new ArgumentNullException("le");

            conn = connection;

            Init ();

            LdapAttribute la = le.getAttribute ("objectClass");

            foreach (string s in la.StringValueArray) {
                attrListStore.AppendValues ("objectClass", s, "Optional");
                _objectClass.Add (s);
            }

            showAttributes ();

            createEntryDialog.Run ();
            while (errorOccured)
                createEntryDialog.Run ();

            createEntryDialog.Destroy ();
        }
Exemplo n.º 20
0
 private void Dispose(bool disposing)
 {
     if (!m_disposed)
     {
         try
         {
             if (disposing)
             {
                 m_userEntry = null;
             }
         }
         finally
         {
             m_enabled = false;  // Mark as disabled.
             m_disposed = true;  // Prevent duplicate dispose.
         }
     }
 }
Exemplo n.º 21
0
		/// <summary> Build the attribuite list from an LdapEntry.
		/// 
		/// </summary>
		/// <param name="entry">The LdapEntry associated with this add request.
		/// </param>
		private static RfcAttributeList makeRfcAttrList(LdapEntry entry)
		{
			// convert Java-API LdapEntry to RFC2251 AttributeList
			LdapAttributeSet attrSet = entry.getAttributeSet();
			RfcAttributeList attrList = new RfcAttributeList(attrSet.Count);
			System.Collections.IEnumerator itr = attrSet.GetEnumerator();
			while (itr.MoveNext())
			{
				LdapAttribute attr = (LdapAttribute) itr.Current;
				Asn1SetOf vals = new Asn1SetOf(attr.size());
				System.Collections.IEnumerator attrEnum = attr.ByteValues;
				while (attrEnum.MoveNext())
				{
					vals.add(new RfcAttributeValue((sbyte[]) attrEnum.Current));
				}
				attrList.add(new RfcAttributeTypeAndValues(new RfcAttributeDescription(attr.Name), vals));
			}
			return attrList;
		}
Exemplo n.º 22
0
        public bool Initialize()
        {
            if (!m_initialized)
            {
                // Load settings from config file.
                m_parent.LoadSettings();

                // Handle initialization
                m_enabled = false;

                UnixIdentity unixIdentity = GetUnixIdentity();

                // Set the domain as the local machine if one is not specified
                if (string.IsNullOrEmpty(m_parent.Domain))
                    m_parent.Domain = Environment.MachineName;

                // Determine if "domain" is for local machine or active directory
                if (UserInfo.IsLocalDomain(m_parent.Domain))
                {
                    uint userID;

                    // Determine if local user exists
                    if (GetLocalUserID(m_parent.UserName, out userID) == 0)
                    {
                        m_isLocalAccount = true;
                        m_enabled = true;
                        m_domainRespondsForUser = true;
                        m_parent.UserAccountControl = -1;
                    }
                    else
                    {
                        m_domainRespondsForUser = false;
                        throw new InitializationException(string.Format("Failed to retrieve local user info for '{0}'", m_parent.UserName));
                    }
                }
                else
                {
                    WindowsImpersonationContext currentContext = null;

                    // Initialize the LdapEntry object used to retrieve LDAP user attributes
                    try
                    {
                        // Impersonate to the privileged account if specified
                        currentContext = m_parent.ImpersonatePrivilegedAccount();

                        // If domain user has already been authenticated, we should already have an active LDAP connection
                        if ((object)unixIdentity != null && unixIdentity.LoginID.Equals(m_parent.LoginID, StringComparison.OrdinalIgnoreCase))
                        {
                            m_connection = unixIdentity.Connection;
                            m_ldapRoot = unixIdentity.LdapRoot ?? m_parent.Domain;
                        }

                        // If no LDAP connection is available, attempt anonymous binding - note that this has to be enabled on AD as it is not enabled by default
                        if ((object)m_connection == null)
                            unixIdentity = AttemptAnonymousBinding(unixIdentity);

                        if ((object)m_connection != null)
                        {
                            // Search for user by account name starting at root and moving through hierarchy recursively
                            LdapSearchResults results = m_connection.Search(
                                m_ldapRoot,
                                LdapConnection.SCOPE_SUB,
                                string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))", m_parent.UserName),
                                null,
                                false);

                            if (results.hasMore())
                            {
                                m_userEntry = results.next();
                                m_isLocalAccount = false;
                                m_enabled = true;
                                m_domainRespondsForUser = true;
                                m_parent.UserAccountControl = -1;
                            }
                        }
                        else
                        {
                            // If PAM authentication succeeded but no LDAP connection can be found, we will attempt to only use PAM
                            if ((object)unixIdentity != null && unixIdentity.LoginID.Equals(m_parent.LoginID, StringComparison.OrdinalIgnoreCase))
                            {
                                m_isLocalAccount = false;
                                m_enabled = true;
                                m_domainRespondsForUser = true; // PAM may be enough...
                                m_parent.UserAccountControl = -1;
                            }
                            else
                            {
                                // See if initialization is for current user
                                WindowsIdentity identity = WindowsIdentity.GetCurrent();

                                if ((object)identity != null && identity.IsAuthenticated && (identity.Name.Equals(m_parent.LoginID, StringComparison.OrdinalIgnoreCase) || identity.Name.Equals(m_parent.UserName, StringComparison.OrdinalIgnoreCase)))
                                {
                                    m_isLocalAccount = !identity.Name.Contains('\\');
                                    m_enabled = true;
                                    m_domainRespondsForUser = true;
                                    m_parent.UserAccountControl = -1;
                                }
                                else
                                {
                                    throw new InvalidOperationException("No valid LDAP connection was found or user is not authenticated");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        m_userEntry = null;
                        m_domainRespondsForUser = false;

                        throw new InitializationException(string.Format("Failed to initialize LDAP entry for domain user '{0}': {1}", m_parent.LoginID, ex.Message), ex);
                    }
                    finally
                    {
                        // Undo impersonation if it was performed
                        UserInfo.EndImpersonation(currentContext);
                    }
                }

                // Initialize user information only once
                m_initialized = true;
            }

            return m_initialized;
        }
Exemplo n.º 23
0
		/// <summary> Constructs a request to add an entry to the directory.
		/// 
		/// </summary>
		/// <param name="entry">The LdapEntry to add to the directory.
		/// 
		/// </param>
		/// <param name="cont">Any controls that apply to the add request,
		/// or null if none.
		/// </param>
		public LdapAddRequest(LdapEntry entry, LdapControl[] cont):base(LdapMessage.ADD_REQUEST, new RfcAddRequest(new RfcLdapDN(entry.DN), makeRfcAttrList(entry)), cont)
		{
			return ;
		}
		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;
			}
		}
Exemplo n.º 25
0
 public override void OnEditEntry(Connection conn, LdapEntry le)
 {
     new EditUserViewDialog (conn, le);
 }
Exemplo n.º 26
0
Arquivo: Util.cs Projeto: MrJoe/lat
        public static bool CheckSamba(LdapEntry le)
        {
            bool retVal = false;

            LdapAttribute la = le.getAttribute ("objectClass");

            if (la == null)
                return retVal;

            foreach (string s in la.StringValueArray)
                if (s.ToLower() == "sambasamaccount")
                    retVal = true;

            return retVal;
        }
Exemplo n.º 27
0
        //public LdapUser(LdapSettings ldapSettings, String userName)
        //{
        //    // in some cases with Active Directory
        //    // we can't actually retrieve ldap entries
        //    // we really just need to create a mojoportal user
        //    // from the ldap user so if we can't read it, just create an ldap user
        //    // with the properties we do have
        //    // Active Directory allows us to bind a connection for authentication
        //    // even if we can't query for entries
        //    email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain);
        //    commonname = new LdapAttribute("commonname", userName);
        //    userid = new LdapAttribute("userid", userName);
        //}
        public LdapUser(LdapEntry entry)
        {
            dn = entry.DN;

            LdapAttributeSet las = entry.getAttributeSet();

            foreach(LdapAttribute a in las)
            {
                switch(a.Name)
                {
                    case "mail":
                        this.email = a;
                        break;
                    case "cn":
                        this.commonname = a;
                        break;
                    case "userPassword":
                        this.password = a;
                        break;
                    case "uidNumber":
                        this.uidNumber = a;
                        break;
                    case "uid":
                        this.userid = a;
                        break;
                    case "sAMAccountName":
                        this.userid = a;
                        break;
                    case "givenName":
                        this.firstName = a.StringValue;
                        break;
                    case "sn":
                        this.lastName = a.StringValue;
                        break;
                }
            }
        }
Exemplo n.º 28
0
        public EditContactsViewDialog(Connection connection, LdapEntry le)
            : base(connection, null)
        {
            currentEntry = le;

            Init ();

            string displayName = conn.Data.GetAttributeValueFromEntry (currentEntry, "displayName");

            gnNameLabel.Text = displayName;
            gnFirstNameEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "givenName");
            gnInitialsEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "initials");
            gnLastNameEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "sn");
            gnDisplayName.Text = displayName;
            gnDescriptionEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "description");
            gnOfficeEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "physicalDeliveryOfficeName");
            gnTelephoneNumberEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "telephoneNumber");
            gnEmailEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "mail");

            adPOBoxEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "postOfficeBox");
            adCityEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "l");
            adStateEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "st");
            adZipEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "postalCode");

            tnHomeEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "homePhone");
            tnPagerEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "pager");
            tnMobileEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "mobile");
            tnFaxEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "facsimileTelephoneNumber");

            ozTitleEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "title");

            string contactName = conn.Data.GetAttributeValueFromEntry (currentEntry, "cn");
            editContactDialog.Title = contactName + " Properties";

            gnWebPageEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "wWWHomePage");

            adStreetTextView.Buffer.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "streetAddress");
            adCountryEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "co");

            tnIPPhoneEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "ipPhone");
            tnNotesTextView.Buffer.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "info");

            ozDeptEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "department");
            ozCompanyEntry.Text = conn.Data.GetAttributeValueFromEntry (currentEntry, "company");

            editContactDialog.Icon = Global.latIcon;
            editContactDialog.Run ();

            while (missingValues || errorOccured) {

                if (missingValues)
                    missingValues = false;
                else if (errorOccured)
                    errorOccured = false;

                editContactDialog.Run ();
            }

            editContactDialog.Destroy ();
        }
Exemplo n.º 29
0
 /// <summary>
 ///     Constructs an LdapSearchResult object from an LdapEntry.
 /// </summary>
 /// <param name="entry">
 ///     the LdapEntry represented by this search result.
 /// </param>
 /// <param name="cont">
 ///     controls associated with the search result.
 /// </param>
 public LdapSearchResult(LdapEntry entry, LdapControl[] cont)
 {
     _entry = entry ?? throw new ArgumentException("Argument \"entry\" cannot be null");
 }
Exemplo n.º 30
0
		/// <summary> 
		/// Synchronously adds an entry to the directory, using the specified
		/// constraints.
		/// 
		/// </summary>
		/// <param name="entry">  LdapEntry object specifying the distinguished
		/// name and attributes of the new entry.
		/// 
		/// </param>
		/// <param name="cons">   Constraints specific to the operation.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// </exception>
		
		public virtual void  Add(LdapEntry entry, LdapConstraints cons)
		{
			LdapResponseQueue queue = Add(entry, null, cons);
			
			// Get a handle to the add response
			LdapResponse addResponse = (LdapResponse) (queue.getResponse());
			
			// Set local copy of responseControls synchronously if there were any
			lock (responseCtlSemaphore)
			{
				responseCtls = addResponse.Controls;
			}
			chkResultCode(queue, cons, addResponse);
			return ;
		}
Exemplo n.º 31
0
        void ChangePassword(LdapEntry entry, PasswordDialog pd)
        {
            List<LdapModification> mods = new List<LdapModification> ();

            LdapAttribute la;
            LdapModification lm;

            la = new LdapAttribute ("userPassword", pd.UnixPassword);
            lm = new LdapModification (LdapModification.REPLACE, la);
            mods.Add (lm);

            if (Util.CheckSamba (entry)) {
                la = new LdapAttribute ("sambaLMPassword", pd.LMPassword);
                lm = new LdapModification (LdapModification.REPLACE, la);
                mods.Add (lm);

                la = new LdapAttribute ("sambaNTPassword", pd.NTPassword);
                lm = new LdapModification (LdapModification.REPLACE, la);
                mods.Add (lm);
            }

            Util.ModifyEntry (conn, entry.DN, mods.ToArray());
        }
Exemplo n.º 32
0
		/// <summary> Asynchronously adds an entry to the directory, using the specified
		/// constraints.
		/// 
		/// </summary>
		/// <param name="entry">  LdapEntry object specifying the distinguished
		/// name and attributes of the new entry.
		/// 
		/// </param>
		/// <param name="queue"> Handler for messages returned from a server in
		/// response to this request. If it is null, a
		/// queue object is created internally.
		/// 
		/// </param>
		/// <param name="cons">  Constraints specific to the operation.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// </exception>
		public virtual LdapResponseQueue Add(LdapEntry entry, LdapResponseQueue queue, LdapConstraints cons)
		{
			if (cons == null)
				cons = defSearchCons;
			
			// error check the parameters
			if (entry == null)
			{
				throw new System.ArgumentException("The LdapEntry parameter" + " cannot be null");
			}
			if ((System.Object) entry.DN == null)
			{
				throw new System.ArgumentException("The DN value must be present" + " in the LdapEntry object");
			}
			
			LdapMessage msg = new LdapAddRequest(entry, cons.getControls());
			
			return SendRequestToServer(msg, cons.TimeLimit, queue, null);
		}
 /// <summary>
 ///     Constructs a request to add an entry to the directory.
 /// </summary>
 /// <param name="entry">
 ///     The LdapEntry to add to the directory.
 /// </param>
 /// <param name="cont">
 ///     Any controls that apply to the add request,
 ///     or null if none.
 /// </param>
 public LdapAddRequest(LdapEntry entry, LdapControl[] cont)
     : base(AddRequest, new RfcAddRequest(new RfcLdapDn(entry.Dn), MakeRfcAttrList(entry)), cont)
 {
 }
Exemplo n.º 34
0
        private void addTelephoneNumber(NameValueCollection collection, LdapEntry entry, string name, string attributeName)
        {
            LdapAttribute attribute;

            attribute = entry.getAttribute(attributeName);

            if(attribute != null)
                collection.Add(name, Contact.NormaliseTelephoneNumber(attribute.StringValue));
        }
Exemplo n.º 35
0
    /**
     * Prints the DN and attributes in an LDAPEntry to System.out.
     * This method used TreeSet to sort the attributes by name.
     */
    public static void PrintEntry(LdapEntry entry)
    {
        /* To print an entry,
         *   -- Loop through all the attributes
         *   -- Loop through all the attribute values
         */

        Console.WriteLine(entry.DN);
        Console.WriteLine("\tAttributes: ");

        LdapAttributeSet attributeSet = entry.getAttributeSet();
        IEnumerator allAttributes = attributeSet.GetEnumerator();

        while(allAttributes.MoveNext())
        {
            LdapAttribute attribute = (LdapAttribute)(allAttributes.Current);
            string attributeName = attribute.Name;

            Console.WriteLine("\t\t" + attributeName);

            IEnumerator allValues = attribute.StringValues;

            if( allValues != null)
            {
                while(allValues.MoveNext())
                {
                    String Value = (String) allValues.Current;
                    Console.WriteLine("\t\t\t" + Value);
                }
            }
        }
        return;
    }
Exemplo n.º 36
0
        public virtual void AddUser(LdapUser user, string password)
        {
            var dn = $"CN={user.FirstName} {user.LastName},{this._ldapSettings.ContainerName}";

            var attributeSet = new LdapAttributeSet
            {
                new LdapAttribute("instanceType", "4"),
                new LdapAttribute("objectCategory", $"CN=Person,CN=Schema,CN=Configuration,{this._ldapSettings.DomainDistinguishedName}"),
                new LdapAttribute("objectClass", new[] { "top", "person", "organizationalPerson", "user" }),
                new LdapAttribute("name", user.UserName),
                new LdapAttribute("cn", $"{user.FirstName} {user.LastName}"),
                new LdapAttribute("sAMAccountName", user.UserName),
                new LdapAttribute("userPrincipalName", user.UserName),
                new LdapAttribute("unicodePwd", Convert.ToBase64String(Encoding.Unicode.GetBytes($"\"{user.Password}\""))),
                new LdapAttribute("userAccountControl", user.MustChangePasswordOnNextLogon ? "544" : "512"),
                new LdapAttribute("givenName", user.FirstName),
                new LdapAttribute("sn", user.LastName),
                new LdapAttribute("mail", user.EmailAddress)
            };

            if (user.DisplayName != null)
            {
                attributeSet.Add(new LdapAttribute("displayName", user.DisplayName));
            }

            if (user.Description != null)
            {
                attributeSet.Add(new LdapAttribute("description", user.Description));
            }
            if (user.Phone != null)
            {
                attributeSet.Add(new LdapAttribute("telephoneNumber", user.Phone));
            }
            if (user.Address?.Street != null)
            {
                attributeSet.Add(new LdapAttribute("streetAddress", user.Address.Street));
            }
            if (user.Address?.City != null)
            {
                attributeSet.Add(new LdapAttribute("l", user.Address.City));
            }
            if (user.Address?.PostalCode != null)
            {
                attributeSet.Add(new LdapAttribute("postalCode", user.Address.PostalCode));
            }
            if (user.Address?.StateName != null)
            {
                attributeSet.Add(new LdapAttribute("st", user.Address.StateName));
            }
            if (user.Address?.CountryName != null)
            {
                attributeSet.Add(new LdapAttribute("co", user.Address.CountryName));
            }
            if (user.Address?.CountryCode != null)
            {
                attributeSet.Add(new LdapAttribute("c", user.Address.CountryCode));
            }

            var newEntry = new Novell.Directory.Ldap.LdapEntry(dn, attributeSet);

            using (var ldapConnection = this.GetConnection())
            {
                ldapConnection.Add(newEntry);
            }
        }
Exemplo n.º 37
0
        /// <summary> Constructs an LdapSchema object from attributes of an LdapEntry.
        /// The object is empty if the entry parameter contains no schema
        /// attributes.  The recognized schema attributes are the following:
        /// <pre><code>
        /// "attributeTypes", "objectClasses", "ldapSyntaxes",
        /// "nameForms", "dITContentRules", "dITStructureRules",
        /// "matchingRules","matchingRuleUse"
        /// </code></pre>
        /// </summary>
        /// <param name="ent">         An LdapEntry containing schema information.
        /// </param>
        public LdapSchema(LdapEntry ent) : base(ent.DN, ent.getAttributeSet())
        {
            InitBlock();
            //reset all definitions
            for (int i = 0; i < schemaTypeNames.Length; i++)
            {
                idTable[i]   = new System.Collections.Hashtable();
                nameTable[i] = new System.Collections.Hashtable();
            }
            System.Collections.IEnumerator itr = base.getAttributeSet().GetEnumerator();
            while (itr.MoveNext())
            {
                LdapAttribute attr = (LdapAttribute)itr.Current;
                System.String value_Renamed, attrName = attr.Name;
                System.Collections.IEnumerator enumString = attr.StringValues;

                if (attrName.ToUpper().Equals(schemaTypeNames[OBJECT_CLASS].ToUpper()))
                {
                    LdapObjectClassSchema classSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed = ((System.String)enumString.Current);
                        try
                        {
                            classSchema = new LdapObjectClassSchema(value_Renamed);
                        }
                        catch (System.Exception e)
                        {
                            continue; //Error parsing: do not add this definition
                        }
                        addElement(OBJECT_CLASS, classSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[ATTRIBUTE].ToUpper()))
                {
                    LdapAttributeSchema attrSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed = ((System.String)enumString.Current);
                        try
                        {
                            attrSchema = new LdapAttributeSchema(value_Renamed);
                        }
                        catch (System.Exception e)
                        {
                            continue; //Error parsing: do not add this definition
                        }
                        addElement(ATTRIBUTE, attrSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[SYNTAX].ToUpper()))
                {
                    LdapSyntaxSchema syntaxSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed = ((System.String)enumString.Current);
                        syntaxSchema  = new LdapSyntaxSchema(value_Renamed);
                        addElement(SYNTAX, syntaxSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING].ToUpper()))
                {
                    LdapMatchingRuleSchema matchingRuleSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed      = ((System.String)enumString.Current);
                        matchingRuleSchema = new LdapMatchingRuleSchema(value_Renamed, null);
                        addElement(MATCHING, matchingRuleSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING_USE].ToUpper()))
                {
                    LdapMatchingRuleUseSchema matchingRuleUseSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed         = ((System.String)enumString.Current);
                        matchingRuleUseSchema = new LdapMatchingRuleUseSchema(value_Renamed);
                        addElement(MATCHING_USE, matchingRuleUseSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[DITCONTENT].ToUpper()))
                {
                    LdapDITContentRuleSchema dITContentRuleSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed        = ((System.String)enumString.Current);
                        dITContentRuleSchema = new LdapDITContentRuleSchema(value_Renamed);
                        addElement(DITCONTENT, dITContentRuleSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[DITSTRUCTURE].ToUpper()))
                {
                    LdapDITStructureRuleSchema dITStructureRuleSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed          = ((System.String)enumString.Current);
                        dITStructureRuleSchema = new LdapDITStructureRuleSchema(value_Renamed);
                        addElement(DITSTRUCTURE, dITStructureRuleSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[NAME_FORM].ToUpper()))
                {
                    LdapNameFormSchema nameFormSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed  = ((System.String)enumString.Current);
                        nameFormSchema = new LdapNameFormSchema(value_Renamed);
                        addElement(NAME_FORM, nameFormSchema);
                    }
                }
                //All non schema attributes are ignored.
                continue;
            }
        }