2 // System.Collections.Specialized.NameObjectCollectionBase.cs
6 // Andreas Nahr (ClassDevelopment@A-SoftTech.com)
8 // (C) Ximian, Inc. http://www.ximian.com
9 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Runtime.Serialization;
35 namespace System.Collections.Specialized
38 public abstract class NameObjectCollectionBase : ICollection, IEnumerable, ISerializable, IDeserializationCallback
40 private Hashtable m_ItemsContainer;
42 /// Extends Hashtable based Items container to support storing null-key pairs
44 private _Item m_NullKeyItem;
45 private ArrayList m_ItemsArray;
46 private IHashCodeProvider m_hashprovider;
47 private IComparer m_comparer;
48 private int m_defCapacity;
49 private bool m_readonly;
50 SerializationInfo infoCopy;
51 private KeysCollection keyscoll;
53 private IEqualityComparer equality_comparer;
55 internal IEqualityComparer EqualityComparer {
56 get { return equality_comparer; }
59 internal IComparer Comparer {
60 get {return m_comparer;}
63 internal IHashCodeProvider HashCodeProvider {
64 get {return m_hashprovider;}
71 public _Item(string key, object value)
78 /// Implements IEnumerable interface for KeysCollection
81 internal class _KeysEnumerator : IEnumerator
83 private NameObjectCollectionBase m_collection;
84 private int m_position;
86 internal _KeysEnumerator(NameObjectCollectionBase collection)
88 m_collection = collection;
95 if ((m_position<m_collection.Count)||(m_position<0))
96 return m_collection.BaseGetKey(m_position);
98 throw new InvalidOperationException();
102 public bool MoveNext()
104 return ((++m_position)<m_collection.Count)?true:false;
113 /// SDK: Represents a collection of the String keys of a collection.
116 public class KeysCollection : ICollection, IEnumerable
118 private NameObjectCollectionBase m_collection;
120 internal KeysCollection (NameObjectCollectionBase collection)
122 this.m_collection = collection;
125 public virtual string Get( int index )
127 return m_collection.BaseGetKey(index);
130 // ICollection methods -----------------------------------
131 void ICollection.CopyTo(Array arr, int index)
134 throw new ArgumentNullException("array can't be null");
135 IEnumerator en = this.GetEnumerator();
137 while (en.MoveNext())
139 arr.SetValue(en.Current,i);
144 bool ICollection.IsSynchronized
150 object ICollection.SyncRoot
157 /// Gets the number of keys in the NameObjectCollectionBase.KeysCollection
162 return m_collection.Count;
166 public string this [int index] {
167 get { return Get (index); }
170 // IEnumerable methods --------------------------------
172 /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.KeysCollection.
174 /// <returns></returns>
175 public IEnumerator GetEnumerator()
177 return new _KeysEnumerator(m_collection);
181 //--------------- Protected Instance Constructors --------------
184 /// SDK: Initializes a new instance of the NameObjectCollectionBase class that is empty.
186 protected NameObjectCollectionBase ()
190 m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
191 m_comparer = CaseInsensitiveComparer.Default;
193 m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
194 m_comparer = CaseInsensitiveComparer.DefaultInvariant;
200 protected NameObjectCollectionBase( int capacity )
204 m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
205 m_comparer = CaseInsensitiveComparer.Default;
207 m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
208 m_comparer = CaseInsensitiveComparer.DefaultInvariant;
210 m_defCapacity = capacity;
216 internal NameObjectCollectionBase (IEqualityComparer equalityComparer, IComparer comparer, IHashCodeProvider hcp)
218 equality_comparer = equalityComparer;
219 m_comparer = comparer;
220 m_hashprovider = hcp;
226 protected NameObjectCollectionBase (IEqualityComparer equalityComparer) : this( (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer), null, null)
230 [Obsolete ("Use NameObjectCollectionBase(IEqualityComparer)")]
232 protected NameObjectCollectionBase( IHashCodeProvider hashProvider, IComparer comparer )
234 m_comparer = comparer;
235 m_hashprovider = hashProvider;
241 protected NameObjectCollectionBase (SerializationInfo info, StreamingContext context)
247 protected NameObjectCollectionBase (int capacity, IEqualityComparer equalityComparer)
250 equality_comparer = (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer);
251 m_defCapacity = capacity;
255 [Obsolete ("Use NameObjectCollectionBase(int,IEqualityComparer)")]
257 protected NameObjectCollectionBase( int capacity, IHashCodeProvider hashProvider, IComparer comparer )
261 m_hashprovider = hashProvider;
262 m_comparer = comparer;
263 m_defCapacity = capacity;
270 if (equality_comparer != null)
271 m_ItemsContainer = new Hashtable (m_defCapacity, equality_comparer);
273 m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
275 m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
277 m_ItemsArray = new ArrayList();
278 m_NullKeyItem = null;
281 //--------------- Public Instance Properties -------------------
283 public virtual NameObjectCollectionBase.KeysCollection Keys {
285 if (keyscoll == null)
286 keyscoll = new KeysCollection (this);
291 //--------------- Public Instance Methods ----------------------
294 /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.
296 /// <remark>This enumerator returns the keys of the collection as strings.</remark>
298 /// <returns></returns>
303 IEnumerator GetEnumerator()
305 return new _KeysEnumerator(this);
309 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
312 throw new ArgumentNullException ("info");
315 string [] keys = new string [count];
316 object [] values = new object [count];
318 foreach (_Item item in m_ItemsArray) {
320 values [i] = item.value;
325 if (equality_comparer != null) {
326 info.AddValue ("KeyComparer", equality_comparer, typeof (IEqualityComparer));
327 info.AddValue ("Version", 4, typeof (int));
329 info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));
330 info.AddValue ("Comparer", m_comparer, typeof (IComparer));
331 info.AddValue ("Version", 2, typeof (int));
334 info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));
335 info.AddValue ("Comparer", m_comparer, typeof (IComparer));
337 info.AddValue("ReadOnly", m_readonly);
338 info.AddValue("Count", count);
339 info.AddValue("Keys", keys, typeof(string[]));
340 info.AddValue("Values", values, typeof(object[]));
344 public virtual int Count
347 return m_ItemsArray.Count;
351 bool ICollection.IsSynchronized
353 get { return false; }
356 object ICollection.SyncRoot
361 void ICollection.CopyTo (Array array, int index)
363 (Keys as ICollection).CopyTo (array, index);
366 // IDeserializationCallback
367 public virtual void OnDeserialization (object sender)
369 SerializationInfo info = infoCopy;
371 // If a subclass overrides the serialization constructor
372 // and inplements its own serialization process, infoCopy will
373 // be null and we can ignore this callback.
378 m_hashprovider = (IHashCodeProvider) info.GetValue ("HashProvider",
379 typeof (IHashCodeProvider));
381 if (m_hashprovider == null) {
382 equality_comparer = (IEqualityComparer) info.GetValue ("KeyComparer", typeof (IEqualityComparer));
384 m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
385 if (m_comparer == null)
386 throw new SerializationException ("The comparer is null");
389 if (m_hashprovider == null)
390 throw new SerializationException ("The hash provider is null");
392 m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
393 if (m_comparer == null)
394 throw new SerializationException ("The comparer is null");
396 m_readonly = info.GetBoolean ("ReadOnly");
397 string [] keys = (string []) info.GetValue ("Keys", typeof (string []));
399 throw new SerializationException ("keys is null");
401 object [] values = (object []) info.GetValue ("Values", typeof (object []));
403 throw new SerializationException ("values is null");
406 int count = keys.Length;
407 for (int i = 0; i < count; i++)
408 BaseAdd (keys [i], values [i]);
411 //--------------- Protected Instance Properties ----------------
413 /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.
415 protected bool IsReadOnly
425 //--------------- Protected Instance Methods -------------------
427 /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.
429 /// <param name="name"></param>
430 /// <param name="value"></param>
431 protected void BaseAdd( string name, object value )
434 throw new NotSupportedException("Collection is read-only");
436 _Item newitem=new _Item(name, value);
439 //todo: consider nullkey entry
440 if (m_NullKeyItem==null)
441 m_NullKeyItem = newitem;
444 if (m_ItemsContainer[name]==null){
445 m_ItemsContainer.Add(name,newitem);
447 m_ItemsArray.Add(newitem);
450 protected void BaseClear()
453 throw new NotSupportedException("Collection is read-only");
458 /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.
460 /// <param name="index"></param>
461 /// <returns></returns>
462 protected object BaseGet( int index )
464 return ((_Item)m_ItemsArray[index]).value;
468 /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.
470 /// <remark>CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.</remark>
471 /// <param name="name"></param>
472 /// <returns></returns>
473 protected object BaseGet( string name )
475 _Item item = FindFirstMatchedItem(name);
476 /// CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.
484 /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.
486 /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>
487 protected string[] BaseGetAllKeys()
489 int cnt = m_ItemsArray.Count;
490 string[] allKeys = new string[cnt];
491 for(int i=0; i<cnt; i++)
492 allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;
498 /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.
500 /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>
501 protected object[] BaseGetAllValues()
503 int cnt = m_ItemsArray.Count;
504 object[] allValues = new object[cnt];
505 for(int i=0; i<cnt; i++)
506 allValues[i] = BaseGet(i);
511 protected object[] BaseGetAllValues( Type type )
514 throw new ArgumentNullException("'type' argument can't be null");
515 int cnt = m_ItemsArray.Count;
516 object[] allValues = (object[]) Array.CreateInstance (type, cnt);
517 for(int i=0; i<cnt; i++)
518 allValues[i] = BaseGet(i);
523 protected string BaseGetKey( int index )
525 return ((_Item)m_ItemsArray[index]).key;
529 /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference
531 /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>
532 protected bool BaseHasKeys()
534 return (m_ItemsContainer.Count>0);
537 protected void BaseRemove( string name )
542 throw new NotSupportedException("Collection is read-only");
545 m_ItemsContainer.Remove(name);
548 m_NullKeyItem = null;
551 cnt = m_ItemsArray.Count;
552 for (int i=0 ; i< cnt; ){
554 if (Equals (key, name)) {
555 m_ItemsArray.RemoveAt(i);
566 /// <param name="index"></param>
567 /// <LAME>This function implemented the way Microsoft implemented it -
568 /// item is removed from hashtable and array without considering the case when there are two items with the same key but different values in array.
570 /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then
571 /// after RemoveAt(1) the collection will be in following state:
573 /// array: [("Key1","value1")]
574 /// It's ok only then the key is uniquely assosiated with the value
575 /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added
577 protected void BaseRemoveAt( int index )
580 throw new NotSupportedException("Collection is read-only");
581 string key = BaseGetKey(index);
583 // TODO: see LAME description above
584 m_ItemsContainer.Remove(key);
587 m_NullKeyItem = null;
588 m_ItemsArray.RemoveAt(index);
592 /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.
594 /// <param name="index"></param>
595 /// <param name="value"></param>
596 protected void BaseSet( int index, object value )
599 throw new NotSupportedException("Collection is read-only");
600 _Item item = (_Item)m_ItemsArray[index];
605 /// Sets the value of the first entry with the specified key in the NameObjectCollectionBase instance, if found; otherwise, adds an entry with the specified key and value into the NameObjectCollectionBase instance.
607 /// <param name="name">The String key of the entry to set. The key can be a null reference </param>
608 /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>
609 protected void BaseSet( string name, object value )
612 throw new NotSupportedException("Collection is read-only");
613 _Item item = FindFirstMatchedItem(name);
617 BaseAdd(name, value);
621 private _Item FindFirstMatchedItem(string name)
624 return (_Item)m_ItemsContainer[name];
626 //TODO: consider null key case
627 return m_NullKeyItem;
631 internal bool Equals (string s1, string s2)
634 if (m_comparer != null)
635 return (m_comparer.Compare (s1, s2) == 0);
637 return equality_comparer.Equals (s1, s2);
639 return (m_comparer.Compare (s1, s2) == 0);