NameObjectCollectionBase.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. //
  2. // System.Collections.Specialized.NameObjectCollectionBase.cs
  3. //
  4. // Author:
  5. // Gleb Novodran
  6. // Andreas Nahr ([email protected])
  7. //
  8. // (C) Ximian, Inc. http://www.ximian.com
  9. //
  10. //
  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:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  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.
  29. //
  30. using System;
  31. using System.Collections;
  32. using System.Runtime.Serialization;
  33. namespace System.Collections.Specialized
  34. {
  35. [Serializable]
  36. public abstract class NameObjectCollectionBase : ICollection, IEnumerable, ISerializable, IDeserializationCallback
  37. {
  38. private Hashtable m_ItemsContainer;
  39. /// <summary>
  40. /// Extends Hashtable based Items container to support storing null-key pairs
  41. /// </summary>
  42. private _Item m_NullKeyItem;
  43. private ArrayList m_ItemsArray;
  44. private IHashCodeProvider m_hashprovider;
  45. private IComparer m_comparer;
  46. private int m_defCapacity;
  47. private bool m_readonly;
  48. SerializationInfo infoCopy;
  49. internal IComparer Comparer {
  50. get {return m_comparer;}
  51. }
  52. internal IHashCodeProvider HashCodeProvider {
  53. get {return m_hashprovider;}
  54. }
  55. internal class _Item
  56. {
  57. public string key;
  58. public object value;
  59. public _Item(string key, object value)
  60. {
  61. this.key = key;
  62. this.value = value;
  63. }
  64. }
  65. /// <summary>
  66. /// Implements IEnumerable interface for KeysCollection
  67. /// </summary>
  68. [Serializable]
  69. internal class _KeysEnumerator : IEnumerator
  70. {
  71. private NameObjectCollectionBase m_collection;
  72. private int m_position;
  73. /*private*/internal _KeysEnumerator(NameObjectCollectionBase collection)
  74. {
  75. m_collection = collection;
  76. Reset();
  77. }
  78. public object Current
  79. {
  80. get{
  81. if ((m_position<m_collection.Count)||(m_position<0))
  82. return m_collection.BaseGetKey(m_position);
  83. else
  84. throw new InvalidOperationException();
  85. }
  86. }
  87. public bool MoveNext()
  88. {
  89. return ((++m_position)<m_collection.Count)?true:false;
  90. }
  91. public void Reset()
  92. {
  93. m_position = -1;
  94. }
  95. }
  96. /// <summary>
  97. /// SDK: Represents a collection of the String keys of a collection.
  98. /// </summary>
  99. [Serializable]
  100. public class KeysCollection : ICollection, IEnumerable
  101. {
  102. private NameObjectCollectionBase m_collection;
  103. internal/*protected?*/ KeysCollection(NameObjectCollectionBase collection)
  104. {
  105. this.m_collection = collection;
  106. }
  107. public virtual string Get( int index )
  108. {
  109. return m_collection.BaseGetKey(index);
  110. //throw new Exception("Not implemented yet");
  111. }
  112. // ICollection methods -----------------------------------
  113. void ICollection.CopyTo(Array arr, int index)
  114. {
  115. if (arr==null)
  116. throw new ArgumentNullException("array can't be null");
  117. IEnumerator en = this.GetEnumerator();
  118. int i = index;
  119. while (en.MoveNext())
  120. {
  121. arr.SetValue(en.Current,i);
  122. i++;
  123. }
  124. }
  125. bool ICollection.IsSynchronized
  126. {
  127. get{
  128. return false;
  129. }
  130. }
  131. object ICollection.SyncRoot
  132. {
  133. get{
  134. return m_collection;
  135. }
  136. }
  137. /// <summary>
  138. /// Gets the number of keys in the NameObjectCollectionBase.KeysCollection
  139. /// </summary>
  140. public int Count
  141. {
  142. get{
  143. return m_collection.Count;
  144. //throw new Exception("Not implemented yet");
  145. }
  146. }
  147. public string this [int index] {
  148. get { return Get (index); }
  149. }
  150. // IEnumerable methods --------------------------------
  151. /// <summary>
  152. /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.KeysCollection.
  153. /// </summary>
  154. /// <returns></returns>
  155. public IEnumerator GetEnumerator()
  156. {
  157. return new _KeysEnumerator(m_collection);
  158. // throw new Exception("Not implemented yet");
  159. }
  160. }
  161. //--------------- Protected Instance Constructors --------------
  162. /// <summary>
  163. /// SDK: Initializes a new instance of the NameObjectCollectionBase class that is empty.
  164. /// </summary>
  165. [MonoTODO]
  166. protected NameObjectCollectionBase():base()
  167. {
  168. m_readonly = false;
  169. #if NET_1_0
  170. m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
  171. m_comparer = CaseInsensitiveComparer.Default;
  172. #else
  173. m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
  174. m_comparer = CaseInsensitiveComparer.DefaultInvariant;
  175. #endif
  176. m_defCapacity = 0;
  177. Init();
  178. /*m_ItemsContainer = new Hashtable(m_hashprovider,m_comparer);
  179. m_ItemsArray = new ArrayList();
  180. m_NullKeyItem = null;*/
  181. //TODO: consider common Reset() method
  182. }
  183. protected NameObjectCollectionBase( int capacity )
  184. {
  185. m_readonly = false;
  186. #if NET_1_0
  187. m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
  188. m_comparer = CaseInsensitiveComparer.Default;
  189. #else
  190. m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
  191. m_comparer = CaseInsensitiveComparer.DefaultInvariant;
  192. #endif
  193. m_defCapacity = capacity;
  194. Init();
  195. /*m_ItemsContainer = new Hashtable(m_defCapacity, m_hashprovider,m_comparer);
  196. m_ItemsArray = new ArrayList();
  197. m_NullKeyItem = null; */
  198. //throw new Exception("Not implemented yet");
  199. }
  200. protected NameObjectCollectionBase( IHashCodeProvider hashProvider, IComparer comparer )
  201. {
  202. m_readonly = false;
  203. m_hashprovider = hashProvider;
  204. m_comparer = comparer;
  205. m_defCapacity = 0;
  206. Init();
  207. /*m_ItemsContainer = new Hashtable(m_hashprovider,m_comparer);
  208. m_ItemsArray = new ArrayList();
  209. m_NullKeyItem = null; */
  210. //throw new Exception("Not implemented yet");
  211. }
  212. protected NameObjectCollectionBase (SerializationInfo info, StreamingContext context)
  213. {
  214. infoCopy = info;
  215. }
  216. protected NameObjectCollectionBase( int capacity, IHashCodeProvider hashProvider, IComparer comparer )
  217. {
  218. m_readonly = false;
  219. m_hashprovider = hashProvider;
  220. m_comparer = comparer;
  221. m_defCapacity = capacity;
  222. Init();
  223. /*m_ItemsContainer = new Hashtable(m_defCapacity,m_hashprovider,m_comparer);
  224. m_ItemsArray = new ArrayList();
  225. m_NullKeyItem = null; */
  226. //throw new Exception("Not implemented yet");
  227. }
  228. private void Init(){
  229. m_ItemsContainer = new Hashtable(m_defCapacity,m_hashprovider,m_comparer);
  230. m_ItemsArray = new ArrayList();
  231. m_NullKeyItem = null;
  232. }
  233. //--------------- Public Instance Properties -------------------
  234. public virtual NameObjectCollectionBase.KeysCollection Keys
  235. {
  236. get
  237. {
  238. return new KeysCollection(this);
  239. //throw new Exception("Not implemented yet");
  240. }
  241. }
  242. //--------------- Public Instance Methods ----------------------
  243. //
  244. /// <summary>
  245. /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.
  246. ///
  247. /// <remark>This enumerator returns the keys of the collection as strings.</remark>
  248. /// </summary>
  249. /// <returns></returns>
  250. public
  251. #if NET_2_0
  252. virtual
  253. #endif
  254. IEnumerator GetEnumerator()
  255. {
  256. return new _KeysEnumerator(this);
  257. }
  258. // GetHashCode
  259. // ISerializable
  260. public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  261. {
  262. if (info == null)
  263. throw new ArgumentNullException ("info");
  264. int count = Count;
  265. string [] keys = new string [count];
  266. object [] values = new object [count];
  267. int i = 0;
  268. foreach (_Item item in m_ItemsArray) {
  269. keys [i] = item.key;
  270. values [i] = item.value;
  271. i++;
  272. }
  273. info.AddValue("HashProvider", m_hashprovider, typeof(IHashCodeProvider));
  274. info.AddValue("Comparer", m_comparer, typeof(IComparer));
  275. info.AddValue("ReadOnly", m_readonly);
  276. info.AddValue("Count", count);
  277. info.AddValue("Keys", keys, typeof(string[]));
  278. info.AddValue("Values", values, typeof(object[]));
  279. }
  280. // ICollection
  281. public virtual int Count
  282. {
  283. get{
  284. return m_ItemsArray.Count;
  285. //throw new Exception("Not implemented yet");
  286. }
  287. }
  288. bool ICollection.IsSynchronized
  289. {
  290. get { return false; }
  291. }
  292. object ICollection.SyncRoot
  293. {
  294. get { return this; }
  295. }
  296. void ICollection.CopyTo (Array array, int index)
  297. {
  298. throw new NotImplementedException ();
  299. }
  300. // IDeserializationCallback
  301. public virtual void OnDeserialization (object sender)
  302. {
  303. SerializationInfo info = infoCopy;
  304. // If a subclass overrides the serialization constructor
  305. // and inplements its own serialization process, infoCopy will
  306. // be null and we can ignore this callback.
  307. if (info == null)
  308. return;
  309. infoCopy = null;
  310. m_hashprovider = (IHashCodeProvider) info.GetValue ("HashProvider",
  311. typeof (IHashCodeProvider));
  312. if (m_hashprovider == null)
  313. throw new SerializationException ("The hash provider is null");
  314. m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
  315. if (m_comparer == null)
  316. throw new SerializationException ("The comparer is null");
  317. m_readonly = info.GetBoolean ("ReadOnly");
  318. string [] keys = (string []) info.GetValue ("Keys", typeof (string []));
  319. if (keys == null)
  320. throw new SerializationException ("keys is null");
  321. object [] values = (object []) info.GetValue ("Values", typeof (object []));
  322. if (values == null)
  323. throw new SerializationException ("values is null");
  324. Init ();
  325. int count = keys.Length;
  326. for (int i = 0; i < count; i++)
  327. BaseAdd (keys [i], values [i]);
  328. }
  329. //--------------- Protected Instance Properties ----------------
  330. /// <summary>
  331. /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.
  332. /// </summary>
  333. protected bool IsReadOnly
  334. {
  335. get{
  336. return m_readonly;
  337. }
  338. set{
  339. m_readonly=value;
  340. }
  341. }
  342. //--------------- Protected Instance Methods -------------------
  343. /// <summary>
  344. /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.
  345. /// </summary>
  346. /// <param name="name"></param>
  347. /// <param name="value"></param>
  348. protected void BaseAdd( string name, object value )
  349. {
  350. if (this.IsReadOnly)
  351. throw new NotSupportedException("Collection is read-only");
  352. _Item newitem=new _Item(name, value);
  353. if (name==null){
  354. //todo: consider nullkey entry
  355. if (m_NullKeyItem==null)
  356. m_NullKeyItem = newitem;
  357. }
  358. else
  359. if (m_ItemsContainer[name]==null){
  360. m_ItemsContainer.Add(name,newitem);
  361. }
  362. m_ItemsArray.Add(newitem);
  363. }
  364. protected void BaseClear()
  365. {
  366. if (this.IsReadOnly)
  367. throw new NotSupportedException("Collection is read-only");
  368. Init();
  369. //throw new Exception("Not implemented yet");
  370. }
  371. /// <summary>
  372. /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.
  373. /// </summary>
  374. /// <param name="index"></param>
  375. /// <returns></returns>
  376. protected object BaseGet( int index )
  377. {
  378. return ((_Item)m_ItemsArray[index]).value;
  379. //throw new Exception("Not implemented yet");
  380. }
  381. /// <summary>
  382. /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.
  383. /// </summary>
  384. /// <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>
  385. /// <param name="name"></param>
  386. /// <returns></returns>
  387. protected object BaseGet( string name )
  388. {
  389. _Item item = FindFirstMatchedItem(name);
  390. /// 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.
  391. if (item==null)
  392. return null;
  393. else
  394. return item.value;
  395. }
  396. /// <summary>
  397. /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.
  398. /// </summary>
  399. /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>
  400. protected string[] BaseGetAllKeys()
  401. {
  402. int cnt = m_ItemsArray.Count;
  403. string[] allKeys = new string[cnt];
  404. for(int i=0; i<cnt; i++)
  405. allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;
  406. return allKeys;
  407. }
  408. /// <summary>
  409. /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.
  410. /// </summary>
  411. /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>
  412. protected object[] BaseGetAllValues()
  413. {
  414. int cnt = m_ItemsArray.Count;
  415. object[] allValues = new object[cnt];
  416. for(int i=0; i<cnt; i++)
  417. allValues[i] = BaseGet(i);
  418. return allValues;
  419. }
  420. protected object[] BaseGetAllValues( Type type )
  421. {
  422. if (type == null)
  423. throw new ArgumentNullException("'type' argument can't be null");
  424. int cnt = m_ItemsArray.Count;
  425. object[] allValues = (object[]) Array.CreateInstance (type, cnt);
  426. for(int i=0; i<cnt; i++)
  427. allValues[i] = BaseGet(i);
  428. return allValues;
  429. }
  430. protected string BaseGetKey( int index )
  431. {
  432. return ((_Item)m_ItemsArray[index]).key;
  433. //throw new Exception("Not implemented yet");
  434. }
  435. /// <summary>
  436. /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference
  437. /// </summary>
  438. /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>
  439. protected bool BaseHasKeys()
  440. {
  441. return (m_ItemsContainer.Count>0);
  442. // throw new Exception("Not implemented yet");
  443. }
  444. protected void BaseRemove( string name )
  445. {
  446. int cnt = 0;
  447. String key;
  448. if (this.IsReadOnly)
  449. throw new NotSupportedException("Collection is read-only");
  450. if (name!=null)
  451. {
  452. m_ItemsContainer.Remove(name);
  453. }
  454. else {
  455. m_NullKeyItem = null;
  456. }
  457. cnt = m_ItemsArray.Count;
  458. for (int i=0 ; i< cnt; ){
  459. key=BaseGetKey(i);
  460. if (m_comparer.Compare (key, name) == 0) {
  461. m_ItemsArray.RemoveAt(i);
  462. cnt--;
  463. }
  464. else
  465. i++;
  466. }
  467. }
  468. /// <summary>
  469. ///
  470. /// </summary>
  471. /// <param name="index"></param>
  472. /// <LAME>This function implemented the way Microsoft implemented it -
  473. /// 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.
  474. /// E.g. if
  475. /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then
  476. /// after RemoveAt(1) the collection will be in following state:
  477. /// hashtable:[]
  478. /// array: [("Key1","value1")]
  479. /// It's ok only then the key is uniquely assosiated with the value
  480. /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added
  481. /// </LAME>>
  482. [MonoTODO]
  483. protected void BaseRemoveAt( int index )
  484. {
  485. if (this.IsReadOnly)
  486. throw new NotSupportedException("Collection is read-only");
  487. string key = BaseGetKey(index);
  488. if (key!=null){
  489. // TODO: see LAME description above
  490. m_ItemsContainer.Remove(key);
  491. }
  492. else
  493. m_NullKeyItem = null;
  494. m_ItemsArray.RemoveAt(index);
  495. // throw new Exception("Not implemented yet");
  496. }
  497. /// <summary>
  498. /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.
  499. /// </summary>
  500. /// <param name="index"></param>
  501. /// <param name="value"></param>
  502. protected void BaseSet( int index, object value )
  503. {
  504. if (this.IsReadOnly)
  505. throw new NotSupportedException("Collection is read-only");
  506. _Item item = (_Item)m_ItemsArray[index];
  507. item.value = value;
  508. //throw new Exception("Not implemented yet");
  509. }
  510. /// <summary>
  511. /// 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.
  512. /// </summary>
  513. /// <param name="name">The String key of the entry to set. The key can be a null reference </param>
  514. /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>
  515. protected void BaseSet( string name, object value )
  516. {
  517. if (this.IsReadOnly)
  518. throw new NotSupportedException("Collection is read-only");
  519. _Item item = FindFirstMatchedItem(name);
  520. if (item!=null)
  521. item.value=value;
  522. else
  523. BaseAdd(name, value);
  524. //throw new Exception("Not implemented yet");
  525. }
  526. [MonoTODO]
  527. private _Item FindFirstMatchedItem(string name)
  528. {
  529. if (name!=null)
  530. return (_Item)m_ItemsContainer[name];
  531. else {
  532. //TODO: consider null key case
  533. return m_NullKeyItem;
  534. //throw new Exception("Not implemented yet");
  535. }
  536. }
  537. //~Object();
  538. }
  539. }