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;
215 protected NameObjectCollectionBase (IEqualityComparer equalityComparer)
218 equality_comparer = equalityComparer;
223 [Obsolete ("Use NameObjectCollectionBase(IEqualityComparer)")]
225 protected NameObjectCollectionBase( IHashCodeProvider hashProvider, IComparer comparer )
229 m_hashprovider = hashProvider;
230 m_comparer = comparer;
235 protected NameObjectCollectionBase (SerializationInfo info, StreamingContext context)
241 protected NameObjectCollectionBase (int capacity, IEqualityComparer equalityComparer)
244 equality_comparer = equalityComparer;
245 m_defCapacity = capacity;
249 [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;
264 if (equality_comparer != null)
265 m_ItemsContainer = new Hashtable (m_defCapacity, equality_comparer);
267 m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
269 m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
271 m_ItemsArray = new ArrayList();
272 m_NullKeyItem = null;
275 //--------------- Public Instance Properties -------------------
277 public virtual NameObjectCollectionBase.KeysCollection Keys {
279 if (keyscoll == null)
280 keyscoll = new KeysCollection (this);
285 //--------------- Public Instance Methods ----------------------
288 /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.
290 /// <remark>This enumerator returns the keys of the collection as strings.</remark>
292 /// <returns></returns>
297 IEnumerator GetEnumerator()
299 return new _KeysEnumerator(this);
303 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
306 throw new ArgumentNullException ("info");
309 string [] keys = new string [count];
310 object [] values = new object [count];
312 foreach (_Item item in m_ItemsArray) {
314 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));
328 info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));
329 info.AddValue ("Comparer", m_comparer, typeof (IComparer));
331 info.AddValue("ReadOnly", m_readonly);
332 info.AddValue("Count", count);
333 info.AddValue("Keys", keys, typeof(string[]));
334 info.AddValue("Values", values, typeof(object[]));
338 public virtual int Count
341 return m_ItemsArray.Count;
345 bool ICollection.IsSynchronized
347 get { return false; }
350 object ICollection.SyncRoot
355 void ICollection.CopyTo (Array array, int index)
357 (Keys as ICollection).CopyTo (array, index);
360 // IDeserializationCallback
361 public virtual void OnDeserialization (object sender)
363 SerializationInfo info = infoCopy;
365 // If a subclass overrides the serialization constructor
366 // and inplements its own serialization process, infoCopy will
367 // be null and we can ignore this callback.
372 m_hashprovider = (IHashCodeProvider) info.GetValue ("HashProvider",
373 typeof (IHashCodeProvider));
375 if (m_hashprovider == null) {
376 equality_comparer = (IEqualityComparer) info.GetValue ("KeyComparer", typeof (IEqualityComparer));
378 m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
379 if (m_comparer == null)
380 throw new SerializationException ("The comparer is null");
383 if (m_hashprovider == null)
384 throw new SerializationException ("The hash provider is null");
386 m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
387 if (m_comparer == null)
388 throw new SerializationException ("The comparer is null");
390 m_readonly = info.GetBoolean ("ReadOnly");
391 string [] keys = (string []) info.GetValue ("Keys", typeof (string []));
393 throw new SerializationException ("keys is null");
395 object [] values = (object []) info.GetValue ("Values", typeof (object []));
397 throw new SerializationException ("values is null");
400 int count = keys.Length;
401 for (int i = 0; i < count; i++)
402 BaseAdd (keys [i], values [i]);
405 //--------------- Protected Instance Properties ----------------
407 /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.
409 protected bool IsReadOnly
419 //--------------- Protected Instance Methods -------------------
421 /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.
423 /// <param name="name"></param>
424 /// <param name="value"></param>
425 protected void BaseAdd( string name, object value )
428 throw new NotSupportedException("Collection is read-only");
430 _Item newitem=new _Item(name, value);
433 //todo: consider nullkey entry
434 if (m_NullKeyItem==null)
435 m_NullKeyItem = newitem;
438 if (m_ItemsContainer[name]==null){
439 m_ItemsContainer.Add(name,newitem);
441 m_ItemsArray.Add(newitem);
444 protected void BaseClear()
447 throw new NotSupportedException("Collection is read-only");
452 /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.
454 /// <param name="index"></param>
455 /// <returns></returns>
456 protected object BaseGet( int index )
458 return ((_Item)m_ItemsArray[index]).value;
462 /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.
464 /// <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>
465 /// <param name="name"></param>
466 /// <returns></returns>
467 protected object BaseGet( string name )
469 _Item item = FindFirstMatchedItem(name);
470 /// 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.
478 /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.
480 /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>
481 protected string[] BaseGetAllKeys()
483 int cnt = m_ItemsArray.Count;
484 string[] allKeys = new string[cnt];
485 for(int i=0; i<cnt; i++)
486 allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;
492 /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.
494 /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>
495 protected object[] BaseGetAllValues()
497 int cnt = m_ItemsArray.Count;
498 object[] allValues = new object[cnt];
499 for(int i=0; i<cnt; i++)
500 allValues[i] = BaseGet(i);
505 protected object[] BaseGetAllValues( Type type )
508 throw new ArgumentNullException("'type' argument can't be null");
509 int cnt = m_ItemsArray.Count;
510 object[] allValues = (object[]) Array.CreateInstance (type, cnt);
511 for(int i=0; i<cnt; i++)
512 allValues[i] = BaseGet(i);
517 protected string BaseGetKey( int index )
519 return ((_Item)m_ItemsArray[index]).key;
523 /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference
525 /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>
526 protected bool BaseHasKeys()
528 return (m_ItemsContainer.Count>0);
531 protected void BaseRemove( string name )
536 throw new NotSupportedException("Collection is read-only");
539 m_ItemsContainer.Remove(name);
542 m_NullKeyItem = null;
545 cnt = m_ItemsArray.Count;
546 for (int i=0 ; i< cnt; ){
548 if (Equals (key, name)) {
549 m_ItemsArray.RemoveAt(i);
560 /// <param name="index"></param>
561 /// <LAME>This function implemented the way Microsoft implemented it -
562 /// 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.
564 /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then
565 /// after RemoveAt(1) the collection will be in following state:
567 /// array: [("Key1","value1")]
568 /// It's ok only then the key is uniquely assosiated with the value
569 /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added
572 protected void BaseRemoveAt( int index )
575 throw new NotSupportedException("Collection is read-only");
576 string key = BaseGetKey(index);
578 // TODO: see LAME description above
579 m_ItemsContainer.Remove(key);
582 m_NullKeyItem = null;
583 m_ItemsArray.RemoveAt(index);
587 /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.
589 /// <param name="index"></param>
590 /// <param name="value"></param>
591 protected void BaseSet( int index, object value )
594 throw new NotSupportedException("Collection is read-only");
595 _Item item = (_Item)m_ItemsArray[index];
600 /// 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.
602 /// <param name="name">The String key of the entry to set. The key can be a null reference </param>
603 /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>
604 protected void BaseSet( string name, object value )
607 throw new NotSupportedException("Collection is read-only");
608 _Item item = FindFirstMatchedItem(name);
612 BaseAdd(name, value);
616 private _Item FindFirstMatchedItem(string name)
619 return (_Item)m_ItemsContainer[name];
621 //TODO: consider null key case
622 return m_NullKeyItem;
626 internal bool Equals (string s1, string s2)
629 if (m_comparer != null)
630 return (m_comparer.Compare (s1, s2) == 0);
632 return equality_comparer.Equals (s1, s2);
634 return (m_comparer.Compare (s1, s2) == 0);