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;
52 private IEqualityComparer equality_comparer;
54 internal IEqualityComparer EqualityComparer {
55 get { return equality_comparer; }
58 internal IComparer Comparer {
59 get {return m_comparer;}
62 internal IHashCodeProvider HashCodeProvider {
63 get {return m_hashprovider;}
70 public _Item(string key, object value)
77 /// Implements IEnumerable interface for KeysCollection
80 internal class _KeysEnumerator : IEnumerator
82 private NameObjectCollectionBase m_collection;
83 private int m_position;
85 internal _KeysEnumerator(NameObjectCollectionBase collection)
87 m_collection = collection;
94 if ((m_position<m_collection.Count)||(m_position<0))
95 return m_collection.BaseGetKey(m_position);
97 throw new InvalidOperationException();
101 public bool MoveNext()
103 return ((++m_position) < m_collection.Count);
112 /// SDK: Represents a collection of the String keys of a collection.
115 public class KeysCollection : ICollection, IEnumerable
117 private NameObjectCollectionBase m_collection;
119 internal KeysCollection (NameObjectCollectionBase collection)
121 this.m_collection = collection;
124 public virtual string Get( int index )
126 return m_collection.BaseGetKey(index);
129 // ICollection methods -----------------------------------
130 void ICollection.CopyTo (Array array, int arrayIndex)
132 ArrayList items = m_collection.m_ItemsArray;
134 throw new ArgumentNullException ("array");
137 throw new ArgumentOutOfRangeException ("arrayIndex");
139 if ((array.Length > 0) && (arrayIndex >= array.Length))
140 throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
142 if (arrayIndex + items.Count > array.Length)
143 throw new ArgumentException ("Not enough room from arrayIndex to end of array for this KeysCollection");
145 if (array != null && array.Rank > 1)
146 throw new ArgumentException ("array is multidimensional");
148 object[] objArray = (object[])array;
149 for (int i = 0; i < items.Count; i++, arrayIndex++)
150 objArray [arrayIndex] = ((_Item)items [i]).key;
153 bool ICollection.IsSynchronized
159 object ICollection.SyncRoot
166 /// Gets the number of keys in the NameObjectCollectionBase.KeysCollection
171 return m_collection.Count;
175 public string this [int index] {
176 get { return Get (index); }
179 // IEnumerable methods --------------------------------
181 /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.KeysCollection.
183 /// <returns></returns>
184 public IEnumerator GetEnumerator()
186 return new _KeysEnumerator(m_collection);
190 //--------------- Protected Instance Constructors --------------
193 /// SDK: Initializes a new instance of the NameObjectCollectionBase class that is empty.
195 protected NameObjectCollectionBase ()
198 m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
199 m_comparer = CaseInsensitiveComparer.DefaultInvariant;
204 protected NameObjectCollectionBase( int capacity )
207 m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
208 m_comparer = CaseInsensitiveComparer.DefaultInvariant;
209 m_defCapacity = capacity;
213 internal NameObjectCollectionBase (IEqualityComparer equalityComparer, IComparer comparer, IHashCodeProvider hcp)
215 equality_comparer = equalityComparer;
216 m_comparer = comparer;
217 m_hashprovider = hcp;
223 protected NameObjectCollectionBase (IEqualityComparer equalityComparer) : this( (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer), null, null)
227 [Obsolete ("Use NameObjectCollectionBase(IEqualityComparer)")]
228 protected NameObjectCollectionBase( IHashCodeProvider hashProvider, IComparer comparer )
230 m_comparer = comparer;
231 m_hashprovider = hashProvider;
237 protected NameObjectCollectionBase (SerializationInfo info, StreamingContext context)
242 protected NameObjectCollectionBase (int capacity, IEqualityComparer equalityComparer)
245 equality_comparer = (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer);
246 m_defCapacity = capacity;
250 [Obsolete ("Use NameObjectCollectionBase(int,IEqualityComparer)")]
251 protected NameObjectCollectionBase( int capacity, IHashCodeProvider hashProvider, IComparer comparer )
255 m_hashprovider = hashProvider;
256 m_comparer = comparer;
257 m_defCapacity = capacity;
263 if (m_ItemsContainer != null) {
264 m_ItemsContainer.Clear ();
265 m_ItemsContainer = null;
268 if (m_ItemsArray != null) {
269 m_ItemsArray.Clear ();
272 if (equality_comparer != null)
273 m_ItemsContainer = new Hashtable (m_defCapacity, equality_comparer);
275 m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
276 m_ItemsArray = new ArrayList();
277 m_NullKeyItem = null;
280 //--------------- Public Instance Properties -------------------
282 public virtual NameObjectCollectionBase.KeysCollection Keys {
284 if (keyscoll == null)
285 keyscoll = new KeysCollection (this);
290 //--------------- Public Instance Methods ----------------------
293 /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.
295 /// <remark>This enumerator returns the keys of the collection as strings.</remark>
297 /// <returns></returns>
298 public virtual IEnumerator GetEnumerator()
300 return new _KeysEnumerator(this);
304 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
307 throw new ArgumentNullException ("info");
310 string [] keys = new string [count];
311 object [] values = new object [count];
313 foreach (_Item item in m_ItemsArray) {
315 values [i] = item.value;
319 if (equality_comparer != null) {
320 info.AddValue ("KeyComparer", equality_comparer, typeof (IEqualityComparer));
321 info.AddValue ("Version", 4, typeof (int));
323 info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));
324 info.AddValue ("Comparer", m_comparer, typeof (IComparer));
325 info.AddValue ("Version", 2, typeof (int));
327 info.AddValue("ReadOnly", m_readonly);
328 info.AddValue("Count", count);
329 info.AddValue("Keys", keys, typeof(string[]));
330 info.AddValue("Values", values, typeof(object[]));
334 public virtual int Count
337 return m_ItemsArray.Count;
341 bool ICollection.IsSynchronized
343 get { return false; }
346 object ICollection.SyncRoot
351 void ICollection.CopyTo (Array array, int index)
353 ((ICollection)Keys).CopyTo (array, index);
356 // IDeserializationCallback
357 public virtual void OnDeserialization (object sender)
359 SerializationInfo info = infoCopy;
361 // If a subclass overrides the serialization constructor
362 // and inplements its own serialization process, infoCopy will
363 // be null and we can ignore this callback.
368 m_hashprovider = (IHashCodeProvider) info.GetValue ("HashProvider",
369 typeof (IHashCodeProvider));
370 if (m_hashprovider == null) {
371 equality_comparer = (IEqualityComparer) info.GetValue ("KeyComparer", typeof (IEqualityComparer));
373 m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
374 if (m_comparer == null)
375 throw new SerializationException ("The comparer is null");
377 m_readonly = info.GetBoolean ("ReadOnly");
378 string [] keys = (string []) info.GetValue ("Keys", typeof (string []));
380 throw new SerializationException ("keys is null");
382 object [] values = (object []) info.GetValue ("Values", typeof (object []));
384 throw new SerializationException ("values is null");
387 int count = keys.Length;
388 for (int i = 0; i < count; i++)
389 BaseAdd (keys [i], values [i]);
392 //--------------- Protected Instance Properties ----------------
394 /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.
396 protected bool IsReadOnly
406 //--------------- Protected Instance Methods -------------------
408 /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.
410 /// <param name="name"></param>
411 /// <param name="value"></param>
412 protected void BaseAdd( string name, object value )
415 throw new NotSupportedException("Collection is read-only");
417 _Item newitem=new _Item(name, value);
420 //todo: consider nullkey entry
421 if (m_NullKeyItem==null)
422 m_NullKeyItem = newitem;
425 if (m_ItemsContainer[name]==null){
426 m_ItemsContainer.Add(name,newitem);
428 m_ItemsArray.Add(newitem);
431 protected void BaseClear()
434 throw new NotSupportedException("Collection is read-only");
439 /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.
441 /// <param name="index"></param>
442 /// <returns></returns>
443 protected object BaseGet( int index )
445 return ((_Item)m_ItemsArray[index]).value;
449 /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.
451 /// <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>
452 /// <param name="name"></param>
453 /// <returns></returns>
454 protected object BaseGet( string name )
456 _Item item = FindFirstMatchedItem(name);
457 /// 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.
465 /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.
467 /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>
468 protected string[] BaseGetAllKeys()
470 int cnt = m_ItemsArray.Count;
471 string[] allKeys = new string[cnt];
472 for(int i=0; i<cnt; i++)
473 allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;
479 /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.
481 /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>
482 protected object[] BaseGetAllValues()
484 int cnt = m_ItemsArray.Count;
485 object[] allValues = new object[cnt];
486 for(int i=0; i<cnt; i++)
487 allValues[i] = BaseGet(i);
492 protected object[] BaseGetAllValues( Type type )
495 throw new ArgumentNullException("'type' argument can't be null");
496 int cnt = m_ItemsArray.Count;
497 object[] allValues = (object[]) Array.CreateInstance (type, cnt);
498 for(int i=0; i<cnt; i++)
499 allValues[i] = BaseGet(i);
504 protected string BaseGetKey( int index )
506 return ((_Item)m_ItemsArray[index]).key;
510 /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference
512 /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>
513 protected bool BaseHasKeys()
515 return (m_ItemsContainer.Count>0);
518 protected void BaseRemove( string name )
523 throw new NotSupportedException("Collection is read-only");
526 m_ItemsContainer.Remove(name);
529 m_NullKeyItem = null;
532 cnt = m_ItemsArray.Count;
533 for (int i=0 ; i< cnt; ){
535 if (Equals (key, name)) {
536 m_ItemsArray.RemoveAt(i);
547 /// <param name="index"></param>
548 /// <LAME>This function implemented the way Microsoft implemented it -
549 /// 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.
551 /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then
552 /// after RemoveAt(1) the collection will be in following state:
554 /// array: [("Key1","value1")]
555 /// It's ok only then the key is uniquely assosiated with the value
556 /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added
558 protected void BaseRemoveAt( int index )
561 throw new NotSupportedException("Collection is read-only");
562 string key = BaseGetKey(index);
564 // TODO: see LAME description above
565 m_ItemsContainer.Remove(key);
568 m_NullKeyItem = null;
569 m_ItemsArray.RemoveAt(index);
573 /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.
575 /// <param name="index"></param>
576 /// <param name="value"></param>
577 protected void BaseSet( int index, object value )
580 throw new NotSupportedException("Collection is read-only");
581 _Item item = (_Item)m_ItemsArray[index];
586 /// 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.
588 /// <param name="name">The String key of the entry to set. The key can be a null reference </param>
589 /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>
590 protected void BaseSet( string name, object value )
593 throw new NotSupportedException("Collection is read-only");
594 _Item item = FindFirstMatchedItem(name);
598 BaseAdd(name, value);
602 private _Item FindFirstMatchedItem(string name)
605 return (_Item)m_ItemsContainer[name];
607 //TODO: consider null key case
608 return m_NullKeyItem;
612 internal bool Equals (string s1, string s2)
614 if (m_comparer != null)
615 return (m_comparer.Compare (s1, s2) == 0);
617 return equality_comparer.Equals (s1, s2);