Contains() public method

public Contains ( object key ) : bool
key object
return bool
コード例 #1
0
		public void All ()
		{
			HybridDictionary dict = new HybridDictionary (true);
			dict.Add ("CCC", "ccc");
			dict.Add ("BBB", "bbb");
			dict.Add ("fff", "fff");
			dict ["EEE"] = "eee";
			dict ["ddd"] = "ddd";
			
			Assert.AreEqual (5, dict.Count, "#1");
			Assert.AreEqual ("eee", dict["eee"], "#2");
			
			dict.Add ("CCC2", "ccc");
			dict.Add ("BBB2", "bbb");
			dict.Add ("fff2", "fff");
			dict ["EEE2"] = "eee";
			dict ["ddd2"] = "ddd";
			dict ["xxx"] = "xxx";
			dict ["yyy"] = "yyy";

			Assert.AreEqual (12, dict.Count, "#3");
			Assert.AreEqual ("eee", dict["eee"], "#4");

			dict.Remove ("eee");
			Assert.AreEqual (11, dict.Count, "Removed/Count");
			Assert.IsFalse (dict.Contains ("eee"), "Removed/Contains(xxx)");
			DictionaryEntry[] entries = new DictionaryEntry [11];
			dict.CopyTo (entries, 0);

			Assert.IsTrue (dict.Contains ("xxx"), "Contains(xxx)");
			dict.Clear ();
			Assert.AreEqual (0, dict.Count, "Cleared/Count");
			Assert.IsFalse (dict.Contains ("xxx"), "Cleared/Contains(xxx)");
		}
コード例 #2
0
		public void Empty () 
		{
			HybridDictionary hd = new HybridDictionary ();
			Assert.AreEqual (0, hd.Count, "Count");
			Assert.IsFalse (hd.Contains ("unexisting"), "unexisting");
			// under 1.x no exception, under 2.0 ArgumentNullException
			Assert.IsFalse (hd.Contains (null), "Contains(null)");
		}
コード例 #3
0
ファイル: Arguments.cs プロジェクト: kodenine/SubWriter
		// Constructor
		public Arguments(string[] Args){
			//Parameters=new StringDictionary();
			Parameters=new HybridDictionary();
			Regex Spliter=new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase|RegexOptions.Compiled);
			Regex Remover= new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase|RegexOptions.Compiled);
			string Parameter=null;
			string[] Parts;

			// Valid parameters forms:
			// {-,/,--}param{ ,=,:}((",')value(",'))
			// Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--'
			foreach(string Txt in Args){
				// Look for new parameters (-,/ or --) and a possible enclosed value (=,:)
				Parts=Spliter.Split(Txt,3);
				switch(Parts.Length){
					// Found a value (for the last parameter found (space separator))
					case 1:
						if(Parameter!=null){
							if(!Parameters.Contains(Parameter)){
								Parts[0]=Remover.Replace(Parts[0],"$1");
								Parameters.Add(Parameter,Parts[0]);
								}
							Parameter=null;
							}
						// else Error: no parameter waiting for a value (skipped)
						break;
					// Found just a parameter
					case 2:
						// The last parameter is still waiting. With no value, set it to true.
						if(Parameter!=null){
							if(!Parameters.Contains(Parameter)) Parameters.Add(Parameter,"true");
							}
						Parameter=Parts[1];
						break;
					// Parameter with enclosed value
					case 3:
						// The last parameter is still waiting. With no value, set it to true.
						if(Parameter!=null){
							if(!Parameters.Contains(Parameter)) Parameters.Add(Parameter,"true");
							}
						Parameter=Parts[1];
						// Remove possible enclosing characters (",')
						if(!Parameters.Contains(Parameter)){
							Parts[2]=Remover.Replace(Parts[2],"$1");
							Parameters.Add(Parameter,Parts[2]);
							}
						Parameter=null;
						break;
					}
				}
			// In case a parameter is still waiting
			if(Parameter!=null){
				if(!Parameters.Contains(Parameter)) Parameters.Add(Parameter,"true");
				}
			}
コード例 #4
0
ファイル: EnumConverter.cs プロジェクト: zanyants/mvp.xml
		private void AnalyzeEnum( Type enumType )
		{
			_enumName = enumType.Name;

			R.FieldInfo[] fieldInfos = enumType.GetFields( BindingFlags.Static | BindingFlags.Public );

			_namedValues = new HybridDictionary( fieldInfos.Length, false );
			_valuedNames = new HybridDictionary( fieldInfos.Length, false );

			foreach( R.FieldInfo fi in fieldInfos )
			{
				if( ( fi.Attributes & EnumField ) == EnumField )
				{
					string name = fi.Name;
					object value = fi.GetValue( null );

					Attribute[] attrs =
						Attribute.GetCustomAttributes( fi, typeof( XmlEnumAttribute ) );
					if( attrs.Length > 0 )
					{
						XmlEnumAttribute attr = (XmlEnumAttribute)attrs[0];
						name = attr.Name;
					}

					_namedValues.Add( name, value );
					if( !_valuedNames.Contains( value ))
						_valuedNames.Add( value, name );
				}
			}
		}
コード例 #5
0
		public void NotEmpty () 
		{
			HybridDictionary hd = new HybridDictionary (true);
			hd.Add ("CCC", "ccc");
			AssertEquals ("Count", 1, hd.Count);
			Assert ("null", !hd.Contains (null));
		}
        public ConsumerConnectionPointCollection(ICollection connectionPoints) {
            if (connectionPoints == null) {
                throw new ArgumentNullException("connectionPoints");
            }

            _ids = new HybridDictionary(connectionPoints.Count, true /* caseInsensitive */);
            foreach (object obj in connectionPoints) {
                if (obj == null) {
                    throw new ArgumentException(SR.GetString(SR.Collection_CantAddNull), "connectionPoints");
                }
                ConsumerConnectionPoint point = obj as ConsumerConnectionPoint;
                if (point == null) {
                    throw new ArgumentException(SR.GetString(SR.Collection_InvalidType, "ConsumerConnectionPoint"),
                                                "connectionPoints");
                }
                string id = point.ID;
                if (!_ids.Contains(id)) {
                    InnerList.Add(point);
                    _ids.Add(id, point);
                }
                else {
                    throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "ConsumerConnectionPoint", id), "connectionPoints");
                }
            }
        }
コード例 #7
0
ファイル: BadgeComponent.cs プロジェクト: BjkGkh/Azure2
 /// <summary>
 /// Initializes a new instance of the <see cref="BadgeComponent"/> class.
 /// </summary>
 /// <param name="userId">The user identifier.</param>
 /// <param name="data">The data.</param>
 internal BadgeComponent(uint userId, UserData data)
 {
     BadgeList = new HybridDictionary();
     foreach (var current in data.Badges.Where(current => !BadgeList.Contains(current.Code)))
         BadgeList.Add(current.Code, current);
     _userId = userId;
 }
コード例 #8
0
ファイル: PSAliasProperty.cs プロジェクト: nickchal/pash
 private void LookupMember(string name, HybridDictionary visitedAliases, out PSMemberInfo returnedMember, out bool hasCycle)
 {
     returnedMember = null;
     if (base.instance == null)
     {
         throw new ExtendedTypeSystemException("AliasLookupMemberOutsidePSObject", null, ExtendedTypeSystem.AccessMemberOutsidePSObject, new object[] { name });
     }
     PSMemberInfo info = PSObject.AsPSObject(base.instance).Properties[name];
     if (info == null)
     {
         throw new ExtendedTypeSystemException("AliasLookupMemberNotPresent", null, ExtendedTypeSystem.MemberNotPresent, new object[] { name });
     }
     PSAliasProperty property = info as PSAliasProperty;
     if (property == null)
     {
         hasCycle = false;
         returnedMember = info;
     }
     else if (visitedAliases.Contains(name))
     {
         hasCycle = true;
     }
     else
     {
         visitedAliases.Add(name, name);
         this.LookupMember(property.ReferencedMemberName, visitedAliases, out returnedMember, out hasCycle);
     }
 }
コード例 #9
0
        public WebPartDescriptionCollection(ICollection webPartDescriptions) {
            if (webPartDescriptions == null) {
                throw new ArgumentNullException("webPartDescriptions");
            }

            _ids = new HybridDictionary(webPartDescriptions.Count, true /* caseInsensitive */);
            foreach (object obj in webPartDescriptions) {
                if (obj == null) {
                    throw new ArgumentException(SR.GetString(SR.Collection_CantAddNull), "webPartDescriptions");
                }
                WebPartDescription description = obj as WebPartDescription;
                if (description == null) {
                    throw new ArgumentException(SR.GetString(SR.Collection_InvalidType, "WebPartDescription"),
                                                "webPartDescriptions");
                }
                string id = description.ID;
                if (!_ids.Contains(id)) {
                    InnerList.Add(description);
                    _ids.Add(id, description);
                }
                else {
                    throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "WebPartDescription", id), "webPartDescriptions");
                }
            }
        }
 private ICollection GetCollectionDelta(ICollection original, ICollection modified)
 {
     if (((original != null) && (modified != null)) && (original.Count != 0))
     {
         IEnumerator enumerator = modified.GetEnumerator();
         if (enumerator != null)
         {
             IDictionary dictionary = new HybridDictionary();
             foreach (object obj2 in original)
             {
                 if (dictionary.Contains(obj2))
                 {
                     int num = (int) dictionary[obj2];
                     dictionary[obj2] = ++num;
                 }
                 else
                 {
                     dictionary.Add(obj2, 1);
                 }
             }
             ArrayList list = null;
             for (int i = 0; (i < modified.Count) && enumerator.MoveNext(); i++)
             {
                 object current = enumerator.Current;
                 if (dictionary.Contains(current))
                 {
                     if (list == null)
                     {
                         list = new ArrayList();
                         enumerator.Reset();
                         for (int j = 0; (j < i) && enumerator.MoveNext(); j++)
                         {
                             list.Add(enumerator.Current);
                         }
                         enumerator.MoveNext();
                     }
                     int num4 = (int) dictionary[current];
                     if (--num4 == 0)
                     {
                         dictionary.Remove(current);
                     }
                     else
                     {
                         dictionary[current] = num4;
                     }
                 }
                 else if (list != null)
                 {
                     list.Add(current);
                 }
             }
             if (list != null)
             {
                 return list;
             }
         }
     }
     return modified;
 }
コード例 #11
0
ファイル: UserBadgeManager.cs プロジェクト: AngelRmz/Yupi
        /// <summary>
        ///     Initializes a new instance of the <see cref="UserBadgeManager" /> class.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="data">The data.</param>
        internal UserBadgeManager(uint userId, UserData data)
        {
            BadgeList = new HybridDictionary();

            foreach (Badge current in data.Badges.Where(current => !BadgeList.Contains(current.Code)))
                BadgeList.Add(current.Code, current);

            _userId = userId;
        }
コード例 #12
0
 public void InitServers(HybridDictionary servers)
 {
     this.cmbServers.Properties.Items.Clear();
     foreach (string str in servers.Keys)
     {
         this.cmbServers.Properties.Items.Add(str);
     }
     string str2 = PropertyService.Get<string>("DefaultServer", string.Empty);
     this.cmbServers.EditValue = (!string.IsNullOrEmpty(str2) && servers.Contains(str2)) ? str2 : this.cmbServers.Properties.Items[0];
     this.chkDefault.Checked = PropertyService.Get<bool>("IsHideServerDialogOnNext", true);
 }
コード例 #13
0
ファイル: s2hDataExchanger.cs プロジェクト: aloux00/s2h
 public bool CloseConnection(string handle)
 {
     lock (m_Connections)
     {
         //System.Diagnostics.Debug.WriteLine("Connections before:" + m_Connections.Count.ToString());
         if (m_Connections.Contains(handle))
         {
             s2hConnection conn = (s2hConnection)m_Connections[handle];
             m_Connections.Remove(handle);
             try
             {
                 conn.Close();
             }
             catch (Exception) {}
             //System.Diagnostics.Debug.WriteLine("Connections after:" + m_Connections.Count.ToString());
             return(true);
         }
     }
     return(false);
 }
コード例 #14
0
ファイル: S2hState.cs プロジェクト: aloux00/s2h
 public s2hClient GetClient(string auth)
 {
     lock (m_Clients)
     {
         if (m_Clients.Contains(auth))
         {
             s2hClient client = (s2hClient)m_Clients[auth];
             long      nowIs  = DateTime.Now.ToFileTime();
             if (((nowIs - client.LastSeen) / (10 * 1000000)) > 60 * 5)
             {
                 client.CloseAllConnections();
                 m_Clients.Remove(client.AuthToken);
                 return(null);
             }
             client.ResetLastSeen();
             return(client);
         }
         else
         {
             return(null);
         }
     }
 }
コード例 #15
0
        private void Initialize(WebPartVerbCollection existingVerbs, ICollection verbs) {
            int count = ((existingVerbs != null) ? existingVerbs.Count : 0) + ((verbs != null) ? verbs.Count : 0);
            _ids = new HybridDictionary(count, /* caseInsensitive */ true);

            if (existingVerbs != null) {
                foreach (WebPartVerb existingVerb in existingVerbs) {
                    // Don't need to check arg, since we know it is valid since it came
                    // from a CatalogPartCollection.
                    if (_ids.Contains(existingVerb.ID)) {
                        throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "WebPartVerb", existingVerb.ID), "existingVerbs");
                    }
                    _ids.Add(existingVerb.ID, existingVerb);

                    InnerList.Add(existingVerb);
                }
            }

            if (verbs != null) {
                foreach (object obj in verbs) {
                    if (obj == null) {
                        throw new ArgumentException(SR.GetString(SR.Collection_CantAddNull), "verbs");
                    }
                    WebPartVerb webPartVerb = obj as WebPartVerb;
                    if (webPartVerb == null) {
                        throw new ArgumentException(SR.GetString(SR.Collection_InvalidType, "WebPartVerb"), "verbs");
                    }

                    if (_ids.Contains(webPartVerb.ID)) {
                        throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "WebPartVerb", webPartVerb.ID), "verbs");
                    }
                    _ids.Add(webPartVerb.ID, webPartVerb);

                    InnerList.Add(webPartVerb);
                }
            }
        }
コード例 #16
0
        private static string GetFontTable(Font font)
        {
            var fontTable = new StringBuilder();
            // Append table control string
            fontTable.Append(@"{\fonttbl{\f0");
            fontTable.Append(@"\");
            var rtfFontFamily = new HybridDictionary();
            rtfFontFamily.Add(FontFamily.GenericMonospace.Name, RtfFontFamilyDef.Modern);
            rtfFontFamily.Add(FontFamily.GenericSansSerif, RtfFontFamilyDef.Swiss);
            rtfFontFamily.Add(FontFamily.GenericSerif, RtfFontFamilyDef.Roman);
            rtfFontFamily.Add("UNKNOWN", RtfFontFamilyDef.Unknown);

            // If the font's family corresponds to an RTF family, append the
            // RTF family name, else, append the RTF for unknown font family.
            fontTable.Append(rtfFontFamily.Contains(font.FontFamily.Name) ? rtfFontFamily[font.FontFamily.Name] : rtfFontFamily["UNKNOWN"]);
            // \fcharset specifies the character set of a font in the font table.
            // 0 is for ANSI.
            fontTable.Append(@"\fcharset0 ");
            // Append the name of the font
            fontTable.Append(font.Name);
            // Close control string
            fontTable.Append(@";}}");
            return fontTable.ToString();
        }
コード例 #17
0
        public void Test01()
        {
            HybridDictionary hd;
            IDictionaryEnumerator en;

            DictionaryEntry curr;        // Enumerator.Current value
            DictionaryEntry de;        // Enumerator.Entry value
            Object k;        // Enumerator.Key value
            Object v;        // Enumerator.Value

            const int BIG_LENGTH = 100;

            // simple string values
            string[] valuesShort =
            {
                "",
                " ",
                "$%^#",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keysShort =
            {
                Int32.MaxValue.ToString(),
                " ",
                System.DateTime.Today.ToString(),
                "",
                "$%^#"
            };

            string[] valuesLong = new string[BIG_LENGTH];
            string[] keysLong = new string[BIG_LENGTH];

            for (int i = 0; i < BIG_LENGTH; i++)
            {
                valuesLong[i] = "Item" + i;
                keysLong[i] = "keY" + i;
            }

            // [] HybridDictionary GetEnumerator()
            //-----------------------------------------------------------------

            hd = new HybridDictionary();

            //  [] Enumerator for empty dictionary
            //
            en = hd.GetEnumerator();
            IEnumerator en2;
            en2 = ((IEnumerable)hd).GetEnumerator();
            string type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }

            //
            //  MoveNext should return false
            //
            bool res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //  ---------------------------------------------------------
            //   [] Enumerator for Filled dictionary  - list
            //  ---------------------------------------------------------
            //
            for (int i = 0; i < valuesShort.Length; i++)
            {
                hd.Add(keysShort[i], valuesShort[i]);
            }

            en = hd.GetEnumerator();
            type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }

            //
            //  MoveNext should return true
            //

            for (int i = 0; i < hd.Count; i++)
            {
                res = en.MoveNext();
                if (!res)
                {
                    Assert.False(true, string.Format("Error, MoveNext returned false", i));
                }

                curr = (DictionaryEntry)en.Current;
                de = en.Entry;
                //
                //enumerator enumerates in different than added order
                // so we'll check Contains
                //
                if (!hd.Contains(curr.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i));
                }
                if (!hd.Contains(en.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i));
                }
                if (!hd.Contains(de.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain Entry.Key from enumerator", i));
                }
                if (String.Compare(hd[curr.Key.ToString()].ToString(), curr.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i));
                }
                if (String.Compare(hd[de.Key.ToString()].ToString(), de.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, Entry.Value for current Entry.Key is different in dictionary", i));
                }
                if (String.Compare(hd[en.Key.ToString()].ToString(), en.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, En-tor.Value for current En-tor.Key is different in dictionary", i));
                }

                // while we didn't MoveNext, Current should return the same value
                DictionaryEntry curr1 = (DictionaryEntry)en.Current;
                if (!curr.Equals(curr1))
                {
                    Assert.False(true, string.Format("Error, second call of Current returned different result", i));
                }
                DictionaryEntry de1 = en.Entry;
                if (!de.Equals(de1))
                {
                    Assert.False(true, string.Format("Error, second call of Entry returned different result", i));
                }
            }

            // next MoveNext should bring us outside of the collection
            //
            res = en.MoveNext();
            res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            //  Attempt to get Entry should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { de = en.Entry; });

            //
            //  Attempt to get Key should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { k = en.Key; });

            //
            //  Attempt to get Value should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { v = en.Value; });

            en.Reset();

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            //  Attempt to get Entry should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { de = en.Entry; });

            //  ---------------------------------------------------------
            //   [] Enumerator for Filled dictionary  - hashtable
            //  ---------------------------------------------------------
            //
            for (int i = 0; i < valuesLong.Length; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }

            en = hd.GetEnumerator();
            type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }

            //
            //  MoveNext should return true
            //

            for (int i = 0; i < hd.Count; i++)
            {
                res = en.MoveNext();
                if (!res)
                {
                    Assert.False(true, string.Format("Error, MoveNext returned false", i));
                }

                curr = (DictionaryEntry)en.Current;
                de = en.Entry;
                //
                //enumerator enumerates in different than added order
                // so we'll check Contains
                //
                if (!hd.Contains(curr.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i));
                }
                if (!hd.Contains(en.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i));
                }
                if (!hd.Contains(de.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain Entry.Key from enumerator", i));
                }
                if (String.Compare(hd[curr.Key.ToString()].ToString(), curr.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i));
                }
                if (String.Compare(hd[de.Key.ToString()].ToString(), de.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, Entry.Value for current Entry.Key is different in dictionary", i));
                }
                if (String.Compare(hd[en.Key.ToString()].ToString(), en.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, En-tor.Value for current En-tor.Key is different in dictionary", i));
                }

                // while we didn't MoveNext, Current should return the same value
                DictionaryEntry curr1 = (DictionaryEntry)en.Current;
                if (!curr.Equals(curr1))
                {
                    Assert.False(true, string.Format("Error, second call of Current returned different result", i));
                }
                DictionaryEntry de1 = en.Entry;
                if (!de.Equals(de1))
                {
                    Assert.False(true, string.Format("Error, second call of Entry returned different result", i));
                }
            }

            // next MoveNext should bring us outside of the collection
            //
            res = en.MoveNext();
            res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            //  Attempt to get Entry should result in exception
            //

            Assert.Throws<InvalidOperationException>(() => { de = en.Entry; });

            //
            //  Attempt to get Key should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { k = en.Key; });

            //
            //  Attempt to get Value should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { v = en.Value; });

            en.Reset();

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            //  Attempt to get Entry should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { de = en.Entry; });

            //=========================================================
            // --------------------------------------------------------
            //
            //   Modify dictionary when enumerating
            //
            //  [] Enumerator and short modified HD (list)
            //
            hd.Clear();
            if (hd.Count < 1)
            {
                for (int i = 0; i < valuesShort.Length; i++)
                {
                    hd.Add(keysShort[i], valuesShort[i]);
                }
            }

            en = hd.GetEnumerator();
            res = en.MoveNext();
            if (!res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned false"));
            }
            curr = (DictionaryEntry)en.Current;
            de = en.Entry;
            k = en.Key;
            v = en.Value;
            int cnt = hd.Count;
            hd.Remove(keysShort[0]);
            if (hd.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item
            DictionaryEntry curr2 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr2))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }

            // will return just removed item
            DictionaryEntry de2 = en.Entry;
            if (!de.Equals(de2))
            {
                Assert.False(true, string.Format("Error, Entry returned different value after modification"));
            }

            // will return just removed item
            Object k2 = en.Key;
            if (!k.Equals(k2))
            {
                Assert.False(true, string.Format("Error, Key returned different value after modification"));
            }


            // will return just removed item
            Object v2 = en.Value;
            if (!v.Equals(v2))
            {
                Assert.False(true, string.Format("Error, Value returned different value after modification"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });

            // ==========================================================
            //
            //
            //  [] Enumerator and long modified HD (hashtable)
            //
            hd.Clear();
            if (hd.Count < 1)
            {
                for (int i = 0; i < valuesLong.Length; i++)
                {
                    hd.Add(keysLong[i], valuesLong[i]);
                }
            }

            en = hd.GetEnumerator();
            res = en.MoveNext();
            if (!res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned false"));
            }
            curr = (DictionaryEntry)en.Current;
            de = en.Entry;
            k = en.Key;
            v = en.Value;
            cnt = hd.Count;
            hd.Remove(keysLong[0]);
            if (hd.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item
            DictionaryEntry curr3 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr3))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }

            // will return just removed item

            DictionaryEntry de3 = en.Entry;
            if (!de.Equals(de3))
            {
                Assert.False(true, string.Format("Error, Entry returned different value after modification"));
            }


            // will return just removed item
            Object k3 = en.Key;
            if (!k.Equals(k3))
            {
                Assert.False(true, string.Format("Error, Key returned different value after modification"));
            }

            // will return just removed item
            Object v3 = en.Value;
            if (!v.Equals(v3))
            {
                Assert.False(true, string.Format("Error, Value returned different value after modification"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });

            //
            //   Modify collection when enumerated beyond the end
            //
            //  [] Enumerator and short HD (list) modified after enumerating beyond the end
            //
            hd.Clear();
            for (int i = 0; i < valuesShort.Length; i++)
            {
                hd.Add(keysShort[i], valuesShort[i]);
            }

            en = hd.GetEnumerator();
            for (int i = 0; i < hd.Count; i++)
            {
                en.MoveNext();
            }
            curr = (DictionaryEntry)en.Current;
            de = en.Entry;
            k = en.Key;
            v = en.Value;

            cnt = hd.Count;
            hd.Remove(keysShort[0]);
            if (hd.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item
            DictionaryEntry curr4 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr4))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }

            // will return just removed item
            DictionaryEntry de4 = en.Entry;
            if (!de.Equals(de4))
            {
                Assert.False(true, string.Format("Error, Entry returned different value after modification"));
            }

            // will return just removed item
            Object k4 = en.Key;
            if (!k.Equals(k4))
            {
                Assert.False(true, string.Format("Error, Key returned different value after modification"));
            }

            // will return just removed item
            Object v4 = en.Value;
            if (!v.Equals(v4))
            {
                Assert.False(true, string.Format("Error, Value returned different value after modification"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });

            //
            //  [] Enumerator and long HD (hashtable) modified after enumerating beyond the end

            hd.Clear();
            for (int i = 0; i < valuesLong.Length; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }

            en = hd.GetEnumerator();
            for (int i = 0; i < hd.Count; i++)
            {
                en.MoveNext();
            }
            curr = (DictionaryEntry)en.Current;
            de = en.Entry;
            k = en.Key;
            v = en.Value;

            cnt = hd.Count;
            hd.Remove(keysLong[0]);
            if (hd.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item

            DictionaryEntry curr5 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr5))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }


            // will return just removed item

            DictionaryEntry de5 = en.Entry;
            if (!de.Equals(de5))
            {
                Assert.False(true, string.Format("Error, Entry returned different value after modification"));
            }


            // will return just removed item
            Object k5 = en.Key;
            if (!k.Equals(k5))
            {
                Assert.False(true, string.Format("Error, Key returned different value after modification"));
            }


            // will return just removed item

            Object v5 = en.Value;
            if (!v.Equals(v5))
            {
                Assert.False(true, string.Format("Error, Value returned different value after modification"));
            }


            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });

            //  ---------------------------------------------------------
            //   [] Enumerator for empty case-insensitive dictionary
            //  ---------------------------------------------------------
            //
            hd = new HybridDictionary(true);

            en = hd.GetEnumerator();
            type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }
        }
コード例 #18
0
        public void SetItem_CaseInsensitiveDictionary_IgnoresCaseOfKey()
        {
            var hybridDictionary = new HybridDictionary(false);
            hybridDictionary["key"] = "value";
            Assert.Equal("value", hybridDictionary["key"]);
            Assert.False(hybridDictionary.Contains("KEY"));
 
            hybridDictionary = new HybridDictionary(true);
            hybridDictionary["key"] = "value";
            Assert.Equal("value", hybridDictionary["key"]);
            Assert.Equal("value", hybridDictionary["KEY"]);
        }
コード例 #19
0
        protected internal virtual void DeserializeElement(XmlReader reader, bool serializeCollectionKey) {
            ConfigurationPropertyCollection props = Properties;
            ConfigurationValue LockedAttributesList = null;
            ConfigurationValue LockedAllExceptList = null;
            ConfigurationValue LockedElementList = null;
            ConfigurationValue LockedAllElementsExceptList = null;
            bool ItemLockedLocally = false;

            _bElementPresent = true;

            ConfigurationElement defaultCollection = null;
            ConfigurationProperty defaultCollectionProperty = props != null ? props.DefaultCollectionProperty : null;
            if (defaultCollectionProperty != null) {
                defaultCollection = (ConfigurationElement)this[defaultCollectionProperty];
            }

            // Process attributes
            _elementTagName = reader.Name;
            PropertySourceInfo rootInfo = new PropertySourceInfo(reader);
            _values.SetValue(reader.Name, null, ConfigurationValueFlags.Modified, rootInfo);
            _values.SetValue(DefaultCollectionPropertyName, defaultCollection, ConfigurationValueFlags.Modified, rootInfo);

            if ((_lockedElementsList != null && (_lockedElementsList.Contains(reader.Name) || 
                    (_lockedElementsList.Contains(LockAll) && reader.Name != ElementTagName))) ||
                (_lockedAllExceptElementsList != null && _lockedAllExceptElementsList.Count != 0 && !_lockedAllExceptElementsList.Contains(reader.Name)) ||
                ((_fItemLocked & ConfigurationValueFlags.Locked) != 0 && (_fItemLocked & ConfigurationValueFlags.Inherited) != 0)
               ) {
                throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_element_locked, reader.Name), reader);
            }


            if (reader.AttributeCount > 0) {
                while (reader.MoveToNextAttribute()) {

                    String propertyName = reader.Name;
                    if ((_lockedAttributesList != null && (_lockedAttributesList.Contains(propertyName) || _lockedAttributesList.Contains(LockAll))) ||
                        (_lockedAllExceptAttributesList != null && !_lockedAllExceptAttributesList.Contains(propertyName))
                       ) {
                        if (propertyName != LockAttributesKey && propertyName != LockAllAttributesExceptKey)
                            throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_attribute_locked, propertyName), reader);
                    }

                    ConfigurationProperty prop = props != null ? props[propertyName] : null;
                    if (prop != null) {
                        if (serializeCollectionKey && !prop.IsKey) {
                            throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_unrecognized_attribute, propertyName), reader);
                        }

                        _values.SetValue(propertyName,
                                            DeserializePropertyValue(prop, reader),
                                            ConfigurationValueFlags.Modified,
                                            new PropertySourceInfo(reader));

                    }   // if (deserializing a remove OR an add that does not handle optional attributes)
                    else if (propertyName == LockItemKey) {
                        try {
                                ItemLockedLocally = bool.Parse(reader.Value);
                        }
                        catch {
                            throw new ConfigurationErrorsException(SR.GetString(SR.Config_invalid_boolean_attribute, propertyName), reader);
                        }
                    }
                    else if (propertyName == LockAttributesKey) {
                        LockedAttributesList = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                    }
                    else if (propertyName == LockAllAttributesExceptKey) {
                        LockedAllExceptList = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                    }
                    else if (propertyName == LockElementsKey) {
                        LockedElementList = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                    }
                    else if (propertyName == LockAllElementsExceptKey) {
                        LockedAllElementsExceptList = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                    }
                    else if (serializeCollectionKey || !OnDeserializeUnrecognizedAttribute(propertyName, reader.Value)) {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_unrecognized_attribute, propertyName), reader);
                    }
                }
            }

            reader.MoveToElement();

            // Check for nested elements.
            try {

                HybridDictionary nodeFound = new HybridDictionary();
                if (!reader.IsEmptyElement) {
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element) {
                            String propertyName = reader.Name;

                            CheckLockedElement(propertyName, null);

                            ConfigurationProperty prop = props != null ? props[propertyName] : null;
                            if (prop != null) {
                                if (typeof(ConfigurationElement).IsAssignableFrom(prop.Type)) {
                                    if (nodeFound.Contains(propertyName))
                                        throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_element_cannot_have_multiple_child_elements, propertyName), reader);
                                    nodeFound.Add(propertyName, propertyName);
                                    ConfigurationElement childElement = (ConfigurationElement)this[prop];
                                    childElement.DeserializeElement(reader, serializeCollectionKey);

                                    // Validate the new element with the per-property Validator
                                    // Note that the per-type validator for childElement has been already executed as part of Deserialize
                                    ValidateElement(childElement, prop.Validator, false);
                                }
                                else {
                                    throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_property_is_not_a_configuration_element, propertyName), reader);
                                }
                            }
                            else if (!OnDeserializeUnrecognizedElement(propertyName, reader)) {
                                // Let the default collection, if there is one, handle this node.
                                if (defaultCollection == null ||
                                        !defaultCollection.OnDeserializeUnrecognizedElement(propertyName, reader)) {
                                    throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_unrecognized_element_name, propertyName), reader);
                                }
                            }
                        }
                        else if (reader.NodeType == XmlNodeType.EndElement) {
                            break;
                        }
                        else if ((reader.NodeType == XmlNodeType.CDATA) || (reader.NodeType == XmlNodeType.Text)) {
                            throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_section_invalid_content), reader);
                        }
                    }
                }

                EnsureRequiredProperties(serializeCollectionKey);

                // Call the per-type validator for this object
                ValidateElement(this, null, false);
            }
            catch (ConfigurationException e) {
                // Catch the generic message from deserialization and include line info if necessary
                if (e.Filename == null || e.Filename.Length == 0)
                    throw new ConfigurationErrorsException(e.Message, reader); // give it some info
                else
                    throw e;
            }

            if (ItemLockedLocally) {
                SetLocked();
                _fItemLocked = ConfigurationValueFlags.Locked;
            }

            if (LockedAttributesList != null) {
                if (_lockedAttributesList == null)
                    _lockedAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedAttributes);
                foreach (string key in ParseLockedAttributes(LockedAttributesList, ConfigurationLockCollectionType.LockedAttributes)) {
                    if (!_lockedAttributesList.Contains(key))
                        _lockedAttributesList.Add(key, ConfigurationValueFlags.Default);  // add the local copy
                    else
                        _lockedAttributesList.Add(key, ConfigurationValueFlags.Modified | ConfigurationValueFlags.Inherited);  // add the local copy
                }
            }
            if (LockedAllExceptList != null) {
                ConfigurationLockCollection newCollection = ParseLockedAttributes(LockedAllExceptList, ConfigurationLockCollectionType.LockedExceptionList);
                if (_lockedAllExceptAttributesList == null) {
                    _lockedAllExceptAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedExceptionList, String.Empty, newCollection);
                    _lockedAllExceptAttributesList.ClearSeedList(); // Prevent the list from thinking this was set by a parent.
                }
                StringCollection intersectionCollection = IntersectLockCollections(_lockedAllExceptAttributesList, newCollection);
                /*
                if (intersectionCollection.Count == 0) {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Config_empty_lock_attributes_except_effective,
                                                                        LockAllAttributesExceptKey,
                                                                        LockedAllExceptList.Value,
                                                                        LockAttributesKey),
                                                                        LockedAllExceptList.SourceInfo.FileName,
                                                                        LockedAllExceptList.SourceInfo.LineNumber);

                }
                */
                _lockedAllExceptAttributesList.ClearInternal(false);
                foreach (string key in intersectionCollection) {
                    _lockedAllExceptAttributesList.Add(key, ConfigurationValueFlags.Default);
                }
            }
            if (LockedElementList != null) {
                if (_lockedElementsList == null)
                    _lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements);

                ConfigurationLockCollection localLockedElementList = ParseLockedAttributes(LockedElementList, ConfigurationLockCollectionType.LockedElements);

                ConfigurationElementCollection collection = null;
                if (props.DefaultCollectionProperty != null) // this is not a collection but it may contain a default collection
                {
                    collection = this[props.DefaultCollectionProperty] as ConfigurationElementCollection;
                    if (collection != null && collection._lockedElementsList == null)
                        collection._lockedElementsList = _lockedElementsList;
                }

                foreach (string key in localLockedElementList) {
                    if (!_lockedElementsList.Contains(key)) {
                        _lockedElementsList.Add(key, ConfigurationValueFlags.Default);  // add the local copy

                        ConfigurationProperty propToLock = Properties[key];
                        if (propToLock != null && typeof(ConfigurationElement).IsAssignableFrom(propToLock.Type)) {
                            ((ConfigurationElement)this[key]).SetLocked();
                        }
                        if (key == LockAll) {
                            foreach (ConfigurationProperty prop in Properties) {
                                if (!string.IsNullOrEmpty(prop.Name) &&
                                    typeof(ConfigurationElement).IsAssignableFrom(prop.Type)) {
                                    ((ConfigurationElement)this[prop]).SetLocked();
                                }
                            }
                        }

                    }
                }
            }

            if (LockedAllElementsExceptList != null) {
                ConfigurationLockCollection newCollection = ParseLockedAttributes(LockedAllElementsExceptList, ConfigurationLockCollectionType.LockedElementsExceptionList);
                if (_lockedAllExceptElementsList == null) {
                    _lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, _elementTagName, newCollection);
                    _lockedAllExceptElementsList.ClearSeedList();
                }

                StringCollection intersectionCollection = IntersectLockCollections(_lockedAllExceptElementsList, newCollection);

                ConfigurationElementCollection collection = null;
                if (props.DefaultCollectionProperty != null) // this is not a collection but it may contain a default collection
                {
                    collection = this[props.DefaultCollectionProperty] as ConfigurationElementCollection;
                    if (collection != null && collection._lockedAllExceptElementsList == null)
                        collection._lockedAllExceptElementsList = _lockedAllExceptElementsList;
                }

                _lockedAllExceptElementsList.ClearInternal(false);
                foreach (string key in intersectionCollection) {
                    if (!_lockedAllExceptElementsList.Contains(key) || key == ElementTagName)
                        _lockedAllExceptElementsList.Add(key, ConfigurationValueFlags.Default);  // add the local copy
                }

                foreach (ConfigurationProperty prop in Properties) {
                    if (!(string.IsNullOrEmpty(prop.Name) || _lockedAllExceptElementsList.Contains(prop.Name)) &&
                        typeof(ConfigurationElement).IsAssignableFrom(prop.Type)) {
                        ((ConfigurationElement)this[prop]).SetLocked();
                    }
                }

            }

            // Make sure default collections use the same lock element lists
            if (defaultCollectionProperty != null) {
                defaultCollection = (ConfigurationElement)this[defaultCollectionProperty];
                if (_lockedElementsList == null) {
                    _lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements);
                }
                defaultCollection._lockedElementsList = _lockedElementsList; 
                if (_lockedAllExceptElementsList == null) {
                    _lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, reader.Name);
                    _lockedAllExceptElementsList.ClearSeedList();
                }
                defaultCollection._lockedAllExceptElementsList = _lockedAllExceptElementsList;
            }

            // This has to be the last thing to execute
            PostDeserialize();
        }
コード例 #20
0
ファイル: ContainsObjTests.cs プロジェクト: sprityao/corefx
        public void Test01()
        {
            IntlStrings intl;
            HybridDictionary hd;

            const int BIG_LENGTH = 100;

            // simple string values
            string[] valuesShort =
            {
                "",
                " ",
                "$%^#",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keysShort =
            {
                Int32.MaxValue.ToString(),
                " ",
                System.DateTime.Today.ToString(),
                "",
                "$%^#"
            };

            string[] valuesLong = new string[BIG_LENGTH];
            string[] keysLong = new string[BIG_LENGTH];

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();

            for (int i = 0; i < BIG_LENGTH; i++)
            {
                valuesLong[i] = "Item" + i;
                keysLong[i] = "keY" + i;
            }

            // [] HybridDictionary is constructed as expected
            //-----------------------------------------------------------------

            hd = new HybridDictionary();

            // [] Contains on empty dictionary

            Assert.Throws<ArgumentNullException>(() => { hd.Contains(null); });


            if (hd.Contains("some_string"))
            {
                Assert.False(true, string.Format("Error, empty dictionary contains some_object"));
            }
            if (hd.Contains(new Hashtable()))
            {
                Assert.False(true, string.Format("Error, empty dictionary contains some_object"));
            }

            // [] simple strings and Contains()
            //

            cnt = hd.Count;
            int len = valuesShort.Length;
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysShort[i], valuesShort[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesShort.Length));
            }
            //
            for (int i = 0; i < len; i++)
            {
                if (!hd.Contains(keysShort[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, keysShort[i]));
                }
            }

            cnt = hd.Count;
            len = valuesLong.Length;
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len + cnt)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len + cnt));
            }
            // verify new keys
            for (int i = 0; i < len; i++)
            {
                if (!hd.Contains(keysLong[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, keysLong[i]));
                }
            }
            // verify old keys
            for (int i = 0; i < valuesShort.Length; i++)
            {
                if (!hd.Contains(keysShort[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, keysShort[i]));
                }
            }


            //
            // [] Intl strings and Contains()
            //

            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }


            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(intlValues[i + len], intlValues[i]);
            }
            if (hd.Count != (len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                if (!hd.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, intlValues[i + len]));
                }
            }


            //
            // [] Case sensitivity
            // by default HybridDictionary is case-sensitive
            //


            hd.Clear();
            len = valuesLong.Length;
            //
            // will use first half of array as valuesShort and second half as keysShort
            //
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key
                if (!hd.Contains(keysLong[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain added uppercase \"{1}\"", i, keysLong[i]));
                }

                // lowercase key
                if (hd.Contains(keysLong[i].ToUpper()))
                {
                    Assert.False(true, string.Format("Error, contains uppercase \"{1}\" - should not", i, keysLong[i].ToUpper()));
                }
            }

            //  [] different_in_casing_only keys and Contains()
            //

            hd.Clear();
            string[] ks = { "Key", "kEy", "keY" };
            len = ks.Length;
            for (int i = 0; i < len; i++)
            {
                hd.Add(ks[i], "Value" + i);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
            }

            if (hd.Contains("Value0"))
            {
                Assert.False(true, string.Format("Error, returned true when should not"));
            }
            for (int i = 0; i < len; i++)
            {
                if (!hd.Contains(ks[i]))
                {
                    Assert.False(true, string.Format("Error, returned false when true expected", i));
                }
            }

            cnt = hd.Count;
            len = valuesLong.Length;
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len + cnt)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len + cnt));
            }
            // verify new keys
            for (int i = 0; i < len; i++)
            {
                if (!hd.Contains(keysLong[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, keysLong[i]));
                }
            }
            // verify old keys
            for (int i = 0; i < ks.Length; i++)
            {
                if (!hd.Contains(ks[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, ks[i]));
                }
            }


            //
            //   [] Contains(null) - for filled dictionary
            //
            len = valuesShort.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysShort[i], valuesShort[i]);
            }

            Assert.Throws<ArgumentNullException>(() => { hd.Contains(null); });

            // [] Contains() for case-insensitive comparer dictionary
            //

            hd = new HybridDictionary(true);
            hd.Clear();
            len = ks.Length;
            hd.Add(ks[0], "Value0");

            for (int i = 1; i < len; i++)
            {
                Assert.Throws<ArgumentException>(() => { hd.Add(ks[i], "Value" + i); });
            }
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, 1));
            }

            if (hd.Contains("Value0"))
            {
                Assert.False(true, string.Format("Error, returned true when should not"));
            }
            for (int i = 0; i < len; i++)
            {
                if (!hd.Contains(ks[i]))
                {
                    Assert.False(true, string.Format("Error, returned false when true expected", i));
                }
            }
            if (!hd.Contains("KEY"))
            {
                Assert.False(true, string.Format("Error, returned false non-existing-cased key"));
            }

            // [] few not_overriding_Equals objects and Contains()
            //

            hd = new HybridDictionary();
            hd.Clear();
            Hashtable[] lbl = new Hashtable[2];
            lbl[0] = new Hashtable();
            lbl[1] = new Hashtable();
            ArrayList[] b = new ArrayList[2];
            b[0] = new ArrayList();
            b[1] = new ArrayList();
            hd.Add(lbl[0], b[0]);
            hd.Add(lbl[1], b[1]);

            Assert.Throws<ArgumentException>(() => { hd.Add(lbl[0], "Hello"); });

            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, 2));
            }

            if (!hd.Contains(lbl[0]))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            if (!hd.Contains(lbl[1]))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            if (hd.Contains(new Hashtable()))
            {
                Assert.False(true, string.Format("Error, returned true when false expected"));
            }

            // [] many not_overriding_Equals objects and Contains()
            //

            hd = new HybridDictionary();
            hd.Clear();
            int num = 40;
            lbl = new Hashtable[num];
            b = new ArrayList[num];
            for (int i = 0; i < num; i++)
            {
                lbl[i] = new Hashtable();
                b[i] = new ArrayList();
                hd.Add(lbl[i], b[i]);
            }

            Assert.Throws<ArgumentException>(() => { hd.Add(lbl[0], "Hello"); });


            if (hd.Count != num)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, num));
            }

            for (int i = 0; i < num; i++)
            {
                if (!hd.Contains(lbl[i]))
                {
                    Assert.False(true, string.Format("Error, returned false when true expected", i));
                }
            }
            if (hd.Contains(new Hashtable()))
            {
                Assert.False(true, string.Format("Error, returned true when false expected"));
            }

            // [] few not_overriding_Equals structs and Contains()

            hd = new HybridDictionary();
            SpecialStruct s = new SpecialStruct();
            s.Num = 1;
            s.Wrd = "one";
            SpecialStruct s1 = new SpecialStruct();
            s1.Num = 1;
            s1.Wrd = "one";
            hd.Add(s, "first");
            hd.Add(s1, "second");
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, 2));
            }
            if (!hd.Contains(s))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            if (!hd.Contains(s1))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }

            // [] many not_overriding_Equals structs and Contains()

            hd = new HybridDictionary();
            SpecialStruct[] ss = new SpecialStruct[num];
            for (int i = 0; i < num; i++)
            {
                ss[i] = new SpecialStruct();
                ss[i].Num = i;
                ss[i].Wrd = "value" + i;
                hd.Add(ss[i], "item" + i);
            }
            if (hd.Count != num)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, num));
            }
            for (int i = 0; i < num; i++)
            {
                if (!hd.Contains(ss[i]))
                {
                    Assert.False(true, string.Format("Error, returned false when true expected", i));
                }
            }
            s = new SpecialStruct();
            s.Num = 1;
            s.Wrd = "value1";
            if (hd.Contains(s))
            {
                Assert.False(true, string.Format("Error, returned true when false expected"));
            }
        }
コード例 #21
0
    public string setInLineStyles(string htmlContent)
    {
        htmlContent = this.removeStylesForFirstDiv(htmlContent);

        int startIndex = 0;
        int indexClass = htmlContent.IndexOf("class", startIndex);

        HybridDictionary hdStyles = new System.Collections.Specialized.HybridDictionary();

        // The token class was found:
        while (indexClass >= 0)
        {
            int nextChar = indexClass + 5;

            string className = string.Empty;

            // It is a class attribute applied to a html tag:
            if (nextChar < htmlContent.Length && htmlContent[nextChar] == '=')
            {
                // Get the class name:
                for (int i = nextChar + 1; htmlContent[i] != ' ' && htmlContent[i] != '>'; i++)
                {
                    className += htmlContent[i];
                }
            }

            if (!string.IsNullOrEmpty(className) && !hdStyles.Contains(className))
            {
                string classDef = this.getClassDefinition(htmlContent, className);

                if (!string.IsNullOrEmpty(classDef) && !hdStyles.Contains(className))
                {
                    hdStyles.Add(className, classDef);
                }
            }

            startIndex = indexClass + 5;
            indexClass = htmlContent.IndexOf("class", startIndex);
        }

        string htmlContentChanged = string.Empty;

        // We finished to collect all the class elements and its definitions:
        if (hdStyles.Count > 0)
        {
            StringBuilder sbClasses = new StringBuilder(htmlContent);

            // We are ready to replace class entries to inline styles:
            IDictionaryEnumerator e = hdStyles.GetEnumerator();

            while (e.MoveNext())
            {
                string classToReplace = "class=" + e.Key.ToString();
                string inlineStyle    = "style=\"" + e.Value.ToString() + "\"";

                // First option:
                sbClasses.Replace(classToReplace, inlineStyle);

                // Second option:
                classToReplace = "class=\"" + e.Key.ToString() + "\"";
                sbClasses.Replace(classToReplace, inlineStyle);
            }

            htmlContentChanged = sbClasses.ToString();
        }
        else
        {
            htmlContentChanged = htmlContent;
        }

        return(htmlContentChanged);
    }
コード例 #22
0
ファイル: Gamemap.cs プロジェクト: sgf/Yupi
        /// <summary>
        ///     Removes from map.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="handleGameItem">if set to <c>true</c> [handle game item].</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        internal bool RemoveFromMap(RoomItem item, bool handleGameItem)
        {
            RemoveSpecialItem(item);
            if (_room.GotSoccer())
                _room.GetSoccer().OnGateRemove(item);
            bool result = false;
            foreach (Point current in item.GetCoords.Where(current => RemoveCoordinatedItem(item, current)))
                result = true;
            HybridDictionary hybridDictionary = new HybridDictionary();
            foreach (Point current2 in item.GetCoords)
            {
                int point = CoordinatesFormatter.PointToInt(current2);
                if (CoordinatedItems.Contains(point))
                {
                    List<RoomItem> value = (List<RoomItem>) CoordinatedItems[point];
                    if (!hybridDictionary.Contains(current2))
                        hybridDictionary.Add(current2, value);
                }
                SetDefaultValue(current2.X, current2.Y);
            }
            foreach (Point point2 in hybridDictionary.Keys)
            {
                List<RoomItem> list = (List<RoomItem>) hybridDictionary[point2];
                foreach (RoomItem current3 in list)
                    ConstructMapForItem(current3, point2);
            }
            if (GuildGates.ContainsKey(item.Coordinate))
                GuildGates.Remove(item.Coordinate);
            _room.GetRoomItemHandler().OnHeightMapUpdate(hybridDictionary.Keys);
            hybridDictionary.Clear();

            return result;
        }
コード例 #23
0
ファイル: CtorTests.cs プロジェクト: noahfalk/corefx
        public void Test01()
        {
            HybridDictionary hd;

            const int BIG_LENGTH = 100;

            string[] valuesLong = new string[BIG_LENGTH];
            string[] keysLong = new string[BIG_LENGTH];
            int len;

            for (int i = 0; i < BIG_LENGTH; i++)
            {
                valuesLong[i] = "Item" + i;
                keysLong[i] = "keY" + i;
            }

            // [] HybridDictionary is constructed as expected
            //-----------------------------------------------------------------

            hd = new HybridDictionary();


            if (hd == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count));
            }

            if (hd["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            System.Collections.ICollection keys = hd.Keys;
            if (keys.Count != 0)
            {
                Assert.False(true, string.Format("Error, Keys contains {0} keys after default ctor", keys.Count));
            }

            System.Collections.ICollection values = hd.Values;
            if (values.Count != 0)
            {
                Assert.False(true, string.Format("Error, Values contains {0} items after default ctor", values.Count));
            }

            //
            // [] Add(string, string)
            //
            hd.Add("Name", "Value");
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            if (String.Compare(hd["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }
            // by default should be case sensitive
            if (hd["NAME"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value for uppercase key"));
            }

            //
            // [] Clear()
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }
            if (hd["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] numerous Add(string, string)
            //
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value", i));
                }
                if (hd[keysLong[i].ToUpper()] != null)
                {
                    Assert.False(true, string.Format("Error, Item() returned non-null for uppercase key", i));
                }
            }

            //
            // [] Clear() for dictionary with multiple entries
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }

            //
            // [] few elements not overriding Equals()
            //
            hd.Clear();
            Hashtable[] lbls = new Hashtable[2];
            ArrayList[] bs = new ArrayList[2];
            lbls[0] = new Hashtable();
            lbls[1] = new Hashtable();
            bs[0] = new ArrayList();
            bs[1] = new ArrayList();
            hd.Add(lbls[0], bs[0]);
            hd.Add(lbls[1], bs[1]);
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count));
            }
            if (!hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
            }
            if (!hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 2nd special item"));
            }
            if (hd.Values.Count != 2)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", hd.Values.Count));
            }

            hd.Remove(lbls[1]);
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }

            //
            // [] many elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[BIG_LENGTH];
            bs = new ArrayList[BIG_LENGTH];
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                lbls[i] = new Hashtable();
                bs[i] = new ArrayList();
                hd.Add(lbls[i], bs[i]);
            }
            if (hd.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, BIG_LENGTH));
            }
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                if (!hd.Contains(lbls[0]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
                }
            }
            if (hd.Values.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of {1}", hd.Values.Count, BIG_LENGTH));
            }

            hd.Remove(lbls[0]);
            if (hd.Count != BIG_LENGTH - 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }
        }
コード例 #24
0
		private IEnumerable<Mailbox> RemoveAddress(IEnumerable<Mailbox> source, string email)
		{
			email = email.With(_ => _.Trim());
			var addresses = new HybridDictionary();
			if (!string.IsNullOrEmpty(email))
				foreach (PX.Common.Mail.Address address in AddressList.Parse(email))
				{
					var group = address as Group;
					if (group != null)
					{
						foreach (Mailbox mailbox in group.Members)
							if (!string.IsNullOrEmpty(mailbox.Address))
								addresses.Add(mailbox.Address.ToLower(), mailbox);
					}
					else
					{
						var mailbox = (Mailbox)address;
						if (!string.IsNullOrEmpty(mailbox.Address))
							addresses.Add(mailbox.Address.ToLower(), mailbox);
					}
				}
			foreach (Mailbox item in source)
				if (addresses.Count == 0 || !addresses.Contains(item.Address.ToLower()))
					yield return item;
		}
コード例 #25
0
ファイル: BuildSelectPanel.cs プロジェクト: ikvm/webmatrix
 private string GetSql()
 {
     IDictionary dictionary = new HybridDictionary(true);
     StringBuilder builder = new StringBuilder();
     builder.Append("SELECT ");
     int num = 0;
     int count = this.CheckedItems.Count;
     foreach (TableColumn column in this.CheckedItems.Values)
     {
         builder.Append('[');
         builder.Append(column.Table);
         builder.Append(']');
         if (!dictionary.Contains(column.Table))
         {
             dictionary[column.Table] = string.Empty;
         }
         builder.Append('.');
         if (column.Column != "*")
         {
             builder.Append('[');
             builder.Append(column.Column);
             builder.Append(']');
         }
         else
         {
             builder.Append('*');
         }
         num++;
         if (num < count)
         {
             builder.Append(", ");
         }
     }
     builder.Append(" FROM ");
     string whereClause = this._whereClauseBuilder.WhereClause;
     foreach (string str2 in this._whereClauseBuilder.TablesUsed)
     {
         if (!dictionary.Contains(str2))
         {
             dictionary[str2] = string.Empty;
         }
     }
     num = 0;
     count = dictionary.Count;
     foreach (string str3 in dictionary.Keys)
     {
         builder.Append('[');
         builder.Append(str3);
         builder.Append(']');
         num++;
         if (num < count)
         {
             builder.Append(", ");
         }
     }
     if (whereClause.Length > 0)
     {
         builder.Append(" WHERE ");
         builder.Append(whereClause);
     }
     return builder.ToString();
 }
コード例 #26
0
ファイル: CtorIntBoolTests.cs プロジェクト: noahfalk/corefx
        public void Test01()
        {
            HybridDictionary hd;

            const int BIG_LENGTH = 100;

            string[] valuesLong = new string[BIG_LENGTH];
            string[] keysLong = new string[BIG_LENGTH];
            int len;

            for (int i = 0; i < BIG_LENGTH; i++)
            {
                valuesLong[i] = "Item" + i;
                keysLong[i] = "keY" + i;
            }

            // [] HybridDictionary is constructed as expected
            //-----------------------------------------------------------------

            // [] Capacity 0, Case-sensitive ctor

            hd = new HybridDictionary(0, false);

            if (hd == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count));
            }

            if (hd["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            //
            // [] Add(string, string)
            //
            // should be able to add keys that differ only in casing
            hd.Add("Name", "Value");
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            if (String.Compare(hd["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }
            hd.Add("NaMe", "Value");
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count));
            }
            if (String.Compare(hd["NaMe"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }
            // by default should be case sensitive
            if (hd["NAME"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value for uppercase key"));
            }

            //
            // [] Clear() short dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }
            if (hd["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] numerous Add(string, string)
            //
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value", i));
                }
                if (hd[keysLong[i].ToUpper()] != null)
                {
                    Assert.False(true, string.Format("Error, Item() returned non-null for uppercase key", i));
                }
            }

            //
            // [] Clear() long dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }

            //
            // [] few elements not overriding Equals()
            //
            hd.Clear();
            Hashtable[] lbls = new Hashtable[2];
            ArrayList[] bs = new ArrayList[2];
            lbls[0] = new Hashtable();
            lbls[1] = new Hashtable();
            bs[0] = new ArrayList();
            bs[1] = new ArrayList();
            hd.Add(lbls[0], bs[0]);
            hd.Add(lbls[1], bs[1]);
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count));
            }
            if (!hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
            }
            if (!hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 2nd special item"));
            }
            if (hd.Values.Count != 2)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", hd.Values.Count));
            }

            hd.Remove(lbls[1]);
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }

            //
            // [] many elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[BIG_LENGTH];
            bs = new ArrayList[BIG_LENGTH];
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                lbls[i] = new Hashtable();
                bs[i] = new ArrayList();
                hd.Add(lbls[i], bs[i]);
            }
            if (hd.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, BIG_LENGTH));
            }
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                if (!hd.Contains(lbls[0]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
                }
            }
            if (hd.Values.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of {1}", hd.Values.Count, BIG_LENGTH));
            }

            hd.Remove(lbls[0]);
            if (hd.Count != BIG_LENGTH - 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }

            // ----------------------------------------------------------------
            //-----------------------------------------------------------------

            // [] Capacity 10 - Case-sensitive

            hd = new HybridDictionary(10, false);

            if (hd == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count));
            }

            if (hd["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            //
            // [] Add(string, string)
            //
            // should be able to add keys that differ only in casing
            hd.Add("Name", "Value");
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            if (String.Compare(hd["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }
            hd.Add("NaMe", "Value");
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count));
            }
            if (String.Compare(hd["NaMe"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }
            // by default should be case sensitive
            if (hd["NAME"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value for uppercase key"));
            }

            //
            // [] Clear() short dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }
            if (hd["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] numerous Add(string, string)
            //
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value", i));
                }
                if (hd[keysLong[i].ToUpper()] != null)
                {
                    Assert.False(true, string.Format("Error, Item() returned non-null for uppercase key", i));
                }
            }

            //
            // [] Clear() long dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }

            //
            // [] few elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[2];
            bs = new ArrayList[2];
            lbls[0] = new Hashtable();
            lbls[1] = new Hashtable();
            bs[0] = new ArrayList();
            bs[1] = new ArrayList();
            hd.Add(lbls[0], bs[0]);
            hd.Add(lbls[1], bs[1]);
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count));
            }
            if (!hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
            }
            if (!hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 2nd special item"));
            }
            if (hd.Values.Count != 2)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", hd.Values.Count));
            }

            hd.Remove(lbls[1]);
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }

            //
            // [] many elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[BIG_LENGTH];
            bs = new ArrayList[BIG_LENGTH];
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                lbls[i] = new Hashtable();
                bs[i] = new ArrayList();
                hd.Add(lbls[i], bs[i]);
            }
            if (hd.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, BIG_LENGTH));
            }
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                if (!hd.Contains(lbls[0]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
                }
            }
            if (hd.Values.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of {1}", hd.Values.Count, BIG_LENGTH));
            }

            hd.Remove(lbls[0]);
            if (hd.Count != BIG_LENGTH - 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }

            // ---------------------------------------------------------------
            //----------------------------------------------------------------

            // [] Capacity 100  - case-sensitive

            hd = new HybridDictionary(100, false);

            if (hd == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count));
            }

            if (hd["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            //
            // [] Add(string, string)
            //
            // should be able to add keys that differ only in casing
            hd.Add("Name", "Value");
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            if (String.Compare(hd["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }
            hd.Add("NaMe", "Value");
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count));
            }
            if (String.Compare(hd["NaMe"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }
            // by default should be case sensitive
            if (hd["NAME"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value for uppercase key"));
            }

            //
            // [] Clear() short dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }
            if (hd["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] numerous Add(string, string)
            //
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value", i));
                }
                if (hd[keysLong[i].ToUpper()] != null)
                {
                    Assert.False(true, string.Format("Error, Item() returned non-null for uppercase key", i));
                }
            }

            //
            // [] Clear() long dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }

            //
            // [] few elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[2];
            bs = new ArrayList[2];
            lbls[0] = new Hashtable();
            lbls[1] = new Hashtable();
            bs[0] = new ArrayList();
            bs[1] = new ArrayList();
            hd.Add(lbls[0], bs[0]);
            hd.Add(lbls[1], bs[1]);
            if (hd.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", hd.Count));
            }
            if (!hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
            }
            if (!hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, doesn't contain 2nd special item"));
            }
            if (hd.Values.Count != 2)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", hd.Values.Count));
            }

            hd.Remove(lbls[1]);
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[1]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }

            //
            // [] many elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[BIG_LENGTH];
            bs = new ArrayList[BIG_LENGTH];
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                lbls[i] = new Hashtable();
                bs[i] = new ArrayList();
                hd.Add(lbls[i], bs[i]);
            }
            if (hd.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, BIG_LENGTH));
            }
            for (int i = 0; i < BIG_LENGTH; i++)
            {
                if (!hd.Contains(lbls[0]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
                }
            }
            if (hd.Values.Count != BIG_LENGTH)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of {1}", hd.Values.Count, BIG_LENGTH));
            }

            hd.Remove(lbls[0]);
            if (hd.Count != BIG_LENGTH - 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (hd.Contains(lbls[0]))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }


            // **************************************************************//
            ///// Case-insensitive ctor ///////////////////////////////////////


            // [] Capacity 0   -  Case-insensitive ctor

            hd = new HybridDictionary(0, true);

            if (hd == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count));
            }

            if (hd["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            //
            // [] Add(string, string)
            //
            hd.Add("Name", "Value");
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            if (String.Compare(hd["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }

            // should not allow keys that differ only in casing
            Assert.Throws<ArgumentException>(() => { hd.Add("NaMe", "vl"); });

            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            // we created case-insensitive  - should find this key
            if (String.Compare(hd["NAME"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value for uppercase key"));
            }

            //
            // [] Clear() short dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }
            if (hd["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] numerous Add(string, string)
            //
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value", i));
                }
                // should have case-insensitive dictionary
                if (String.Compare(hd[keysLong[i].ToUpper()].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value for uppercase key", i));
                }
            }

            //
            // [] Clear() long dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }

            //
            // [] few elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[2];
            bs = new ArrayList[2];
            lbls[0] = new Hashtable();
            lbls[1] = new Hashtable();
            bs[0] = new ArrayList();
            bs[1] = new ArrayList();
            hd.Add(lbls[0], bs[0]);
            // should get ArgumentException here
            Assert.Throws<ArgumentException>(() => { hd.Add(lbls[1], bs[1]); });

            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }

            // ---------------------------------------------------------------
            // ---------------------------------------------------------------

            //  [] Capacity 10  - case-insensitive

            hd = new HybridDictionary(10, true);

            if (hd == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count));
            }

            if (hd["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            //
            // [] Add(string, string)
            //
            hd.Add("Name", "Value");
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            if (String.Compare(hd["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }

            // should not allow keys that differ only in casing
            Assert.Throws<ArgumentException>(() => { hd.Add("NaMe", "vl"); });

            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            // we created case-insensitive  - should find this key
            if (String.Compare(hd["NAME"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value for uppercase key"));
            }

            //
            // [] Clear() short dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }
            if (hd["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] numerous Add(string, string)
            //
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value", i));
                }
                // should have case-insensitive dictionary
                if (String.Compare(hd[keysLong[i].ToUpper()].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value for uppercase key", i));
                }
            }

            //
            // [] Clear() long dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }

            //
            // [] few elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[2];
            bs = new ArrayList[2];
            lbls[0] = new Hashtable();
            lbls[1] = new Hashtable();
            bs[0] = new ArrayList();
            bs[1] = new ArrayList();
            hd.Add(lbls[0], bs[0]);
            // should get ArgumentException here
            Assert.Throws<ArgumentException>(() => { hd.Add(lbls[1], bs[1]); });

            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }

            // ---------------------------------------------------------------
            // ---------------------------------------------------------------

            // [] Capacity 100, case-insensitive

            hd = new HybridDictionary(100, true);

            if (hd == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", hd.Count));
            }

            if (hd["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            //
            // [] Add(string, string)
            //
            hd.Add("Name", "Value");
            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            if (String.Compare(hd["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }

            // should not allow keys that differ only in casing
            Assert.Throws<ArgumentException>(() => { hd.Add("NaMe", "vl"); });

            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
            // we created case-insensitive  - should find this key
            if (String.Compare(hd["NAME"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value for uppercase key"));
            }

            //
            // [] Clear()
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }
            if (hd["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] numerous Add(string, string)
            //
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", hd.Count, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(hd[keysLong[i]].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value", i));
                }
                // should have case-insensitive dictionary
                if (String.Compare(hd[keysLong[i].ToUpper()].ToString(), valuesLong[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, Item() returned unexpected value for uppercase key", i));
                }
            }

            //
            // [] Clear() long dictionary
            //
            hd.Clear();
            if (hd.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", hd.Count));
            }

            //
            // [] few elements not overriding Equals()
            //
            hd.Clear();
            lbls = new Hashtable[2];
            bs = new ArrayList[2];
            lbls[0] = new Hashtable();
            lbls[1] = new Hashtable();
            bs[0] = new ArrayList();
            bs[1] = new ArrayList();
            hd.Add(lbls[0], bs[0]);
            // should get ArgumentException here
            Assert.Throws<ArgumentException>(() => { hd.Add(lbls[1], bs[1]); });

            if (hd.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", hd.Count));
            }
        }
コード例 #27
0
ファイル: SearchEngine.cs プロジェクト: chandru9279/StarBase
        /// <summary>
        /// Method called from UI
        /// </summary>
        /// <param name="searchterm">search query</param>
        /// <param name="catalog">catalog to search</param>
        /// <returns>ResultFile SortedList for display</returns>
        public SortedList GetResults(string searchterm, Catalog catalog)
        {
            SortedList output = new SortedList();

            // ----------------------- DOING A SEARCH -----------------------
            if ((null != searchterm) && (null != catalog))
            {
                SetPreferences();

                string[] searchTermArray = null, searchTermDisplay = null;

                /****** Too *********/
                Regex r = new Regex(@"\s+");             // matches continuous whitespace
                searchterm = r.Replace(searchterm, " "); // replaces 'em with a single space
                searchTermArray = searchterm.Split(' '); // then split
                searchTermDisplay = (string[])searchTermArray.Clone();
                for (int i = 0; i < searchTermArray.Length; i++)
                {
                    if (_GoChecker.IsGoWord(searchTermArray[i]))
                    {	// was a Go word, just Lower it
                        searchTermArray[i] = searchTermArray[i].ToLower();
                    }
                    else
                    {	// Not a Go word, apply stemming
                        searchTermArray[i] = searchTermArray[i].Trim(' ', '?', '\"', ',', '\'', ';', ':', '.', '(', ')').ToLower();
                        searchTermArray[i] = _Stemmer.StemWord(searchTermArray[i].ToString());
                    }
                }

                if (searchterm == String.Empty)
                {
                    // After trimming the search term, it was found to be empty!
                    return output;
                }
                else
                {	// we have a search term!
                    DateTime start = DateTime.Now;  // to show 'time taken' to perform search

                    // Array of arrays of results that match ONE of the search criteria
                    Hashtable[] searchResultsArrayArray = new Hashtable[searchTermArray.Length];
                    // finalResultsArray is populated with pages that *match* ALL the search criteria
                    HybridDictionary finalResultsArray = new HybridDictionary();

                    bool botherToFindMatches = true;
                    int indexOfShortestResultSet = -1, lengthOfShortestResultSet = -1;

                    for (int i = 0; i < searchTermArray.Length; i++)
                    {	// ##### THE SEARCH #####
                        searchResultsArrayArray[i] = catalog.Search(searchTermArray[i].ToString());
                        if (null == searchResultsArrayArray[i])
                        {
                            _Matches += searchTermDisplay[i] + " <font color='gray' style='font-size:xx-small'>(not found)</font> ";
                            botherToFindMatches = false; // if *any one* of the terms isn't found, there won't be a 'set' of Matches
                        }
                        else
                        {
                            int resultsInThisSet = searchResultsArrayArray[i].Count;
                            _Matches += "<a href=\"?" + Preferences.QuerystringParameterName + "=" + searchTermDisplay[i] + "\" title=\"" + searchTermArray[i] + "\">"
                                    + searchTermDisplay[i]
                                    + "</a> <font color=gray style='font-size:xx-small'>(" + resultsInThisSet + ")</font> ";
                            if ((lengthOfShortestResultSet == -1) || (lengthOfShortestResultSet > resultsInThisSet))
                            {
                                indexOfShortestResultSet = i;
                                lengthOfShortestResultSet = resultsInThisSet;
                            }
                        }
                    }

                    // Find the common files from the array of arrays of documents
                    // matching ONE of the criteria
                    if (botherToFindMatches)                                            // all words have *some* matches
                    {																	// for each result set [NOT required, but maybe later if we do AND/OR searches)
                        int c = indexOfShortestResultSet;                               // loop through the *shortest* resultset
                        Hashtable searchResultsArray = searchResultsArrayArray[c];

                        foreach (object foundInFile in searchResultsArray)             // for each file in the *shortest* result set
                        {
                            DictionaryEntry fo = (DictionaryEntry)foundInFile;          // find matching files in the other resultsets

                            int matchcount = 0, totalcount = 0, weight = 0;

                            for (int cx = 0; cx < searchResultsArrayArray.Length; cx++)
                            {
                                totalcount += (cx + 1);                                // keep track, so we can compare at the end (if term is in ALL resultsets)
                                if (cx == c)                                      // current resultset
                                {
                                    matchcount += (cx + 1);                          // implicitly matches in the current resultset
                                    weight += (int)fo.Value;                       // sum the weighting
                                }
                                else
                                {
                                    Hashtable searchResultsArrayx = searchResultsArrayArray[cx];
                                    if (null != searchResultsArrayx)
                                    {
                                        foreach (object foundInFilex in searchResultsArrayx)
                                        {   // for each file in the result set
                                            DictionaryEntry fox = (DictionaryEntry)foundInFilex;
                                            if (fo.Key == fox.Key)
                                            {
                                                matchcount += (cx + 1);               // and if it matches, track the matchcount
                                                weight += (int)fox.Value;           // and weighting; then break out of loop, since
                                                break;                              // no need to keep looking through this resultset
                                            }
                                        } // foreach
                                    } // if
                                } // else
                            } // for
                            if ((matchcount > 0) && (matchcount == totalcount))		// was matched in each Array
                            {   // we build the finalResults here, to pass to the formatting code below
                                // - we could do the formatting here, but it would mix up the 'result generation'
                                // and display code too much
                                fo.Value = weight; // set the 'weight' in the combined results to the sum of individual document matches
                                if (!finalResultsArray.Contains(fo.Key)) finalResultsArray.Add(fo.Key, fo);
                            } // if
                        } // foreach
                    }

                    // Time taken calculation
                    Int64 ticks = DateTime.Now.Ticks - start.Ticks;
                    TimeSpan taken = new TimeSpan(ticks);
                    if (taken.Seconds > 0)
                    {
                        _DisplayTime = taken.Seconds + " seconds";
                    }
                    else if (taken.TotalMilliseconds > 0)
                    {
                        _DisplayTime = Convert.ToInt32(taken.TotalMilliseconds) + " milliseconds";
                    }
                    else
                    {
                        _DisplayTime = "less than 1 millisecond";
                    }

                    // Format the results
                    if (finalResultsArray.Count > 0)
                    {	// intermediate data-structure for 'ranked' result HTML
                        //SortedList
                        output = new SortedList(finalResultsArray.Count); // empty sorted list
                        ResultFile infile;
                        int sortrank = 0;

                        // build each result row
                        foreach (object foundInFile in finalResultsArray.Keys)
                        {
                            // Create a ResultFile with it's own Rank
                            infile = new ResultFile((File)foundInFile);

                            infile.Rank = (int)((DictionaryEntry)finalResultsArray[foundInFile]).Value;
                            sortrank = infile.Rank * -1000;		// Assume not 'thousands' of results
                            if (output.Contains(sortrank))
                            { // rank exists - drop key index one number until it fits
                                for (int i = 1; i < 999; i++)
                                {
                                    sortrank++;
                                    if (!output.Contains(sortrank))
                                    {
                                        output.Add(sortrank, infile);
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                output.Add(sortrank, infile);
                            }
                            sortrank = 0;	// reset for next pass
                        }
                        // Jim Harkins [paged results]
                        // http://aspnet.4guysfromrolla.com/articles/081804-1.aspx
                    } // else Count == 0, so output SortedList will be empty
                }
            }
            return output;
        }
 protected internal virtual void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
 {
     ConfigurationPropertyCollection properties = this.Properties;
     ConfigurationValue value2 = null;
     ConfigurationValue value3 = null;
     ConfigurationValue value4 = null;
     ConfigurationValue value5 = null;
     bool flag = false;
     this._bElementPresent = true;
     ConfigurationElement element = null;
     ConfigurationProperty property = (properties != null) ? properties.DefaultCollectionProperty : null;
     if (property != null)
     {
         element = (ConfigurationElement) this[property];
     }
     this._elementTagName = reader.Name;
     PropertySourceInfo sourceInfo = new PropertySourceInfo(reader);
     this._values.SetValue(reader.Name, null, ConfigurationValueFlags.Modified, sourceInfo);
     this._values.SetValue("", element, ConfigurationValueFlags.Modified, sourceInfo);
     if (((this._lockedElementsList != null) && (this._lockedElementsList.Contains(reader.Name) || (this._lockedElementsList.Contains("*") && (reader.Name != this.ElementTagName)))) || ((((this._lockedAllExceptElementsList != null) && (this._lockedAllExceptElementsList.Count != 0)) && !this._lockedAllExceptElementsList.Contains(reader.Name)) || (((this._fItemLocked & ConfigurationValueFlags.Locked) != ConfigurationValueFlags.Default) && ((this._fItemLocked & ConfigurationValueFlags.Inherited) != ConfigurationValueFlags.Default))))
     {
         throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_element_locked", new object[] { reader.Name }), reader);
     }
     if (reader.AttributeCount > 0)
     {
         while (reader.MoveToNextAttribute())
         {
             string name = reader.Name;
             if ((((this._lockedAttributesList != null) && (this._lockedAttributesList.Contains(name) || this._lockedAttributesList.Contains("*"))) || ((this._lockedAllExceptAttributesList != null) && !this._lockedAllExceptAttributesList.Contains(name))) && ((name != "lockAttributes") && (name != "lockAllAttributesExcept")))
             {
                 throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_attribute_locked", new object[] { name }), reader);
             }
             ConfigurationProperty prop = (properties != null) ? properties[name] : null;
             if (prop != null)
             {
                 if (serializeCollectionKey && !prop.IsKey)
                 {
                     throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_unrecognized_attribute", new object[] { name }), reader);
                 }
                 this._values.SetValue(name, this.DeserializePropertyValue(prop, reader), ConfigurationValueFlags.Modified, new PropertySourceInfo(reader));
             }
             else
             {
                 if (name == "lockItem")
                 {
                     try
                     {
                         flag = bool.Parse(reader.Value);
                         continue;
                     }
                     catch
                     {
                         throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_invalid_boolean_attribute", new object[] { name }), reader);
                     }
                 }
                 if (name == "lockAttributes")
                 {
                     value2 = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                 }
                 else
                 {
                     if (name == "lockAllAttributesExcept")
                     {
                         value3 = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                         continue;
                     }
                     if (name == "lockElements")
                     {
                         value4 = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                         continue;
                     }
                     if (name == "lockAllElementsExcept")
                     {
                         value5 = new ConfigurationValue(reader.Value, ConfigurationValueFlags.Default, new PropertySourceInfo(reader));
                         continue;
                     }
                     if (serializeCollectionKey || !this.OnDeserializeUnrecognizedAttribute(name, reader.Value))
                     {
                         throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_unrecognized_attribute", new object[] { name }), reader);
                     }
                 }
             }
         }
     }
     reader.MoveToElement();
     try
     {
         HybridDictionary dictionary = new HybridDictionary();
         if (!reader.IsEmptyElement)
         {
             while (reader.Read())
             {
                 if (reader.NodeType == XmlNodeType.Element)
                 {
                     string elementName = reader.Name;
                     this.CheckLockedElement(elementName, null);
                     ConfigurationProperty property3 = (properties != null) ? properties[elementName] : null;
                     if (property3 == null)
                     {
                         if (!this.OnDeserializeUnrecognizedElement(elementName, reader) && ((element == null) || !element.OnDeserializeUnrecognizedElement(elementName, reader)))
                         {
                             throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_unrecognized_element_name", new object[] { elementName }), reader);
                         }
                     }
                     else
                     {
                         if (!property3.IsConfigurationElementType)
                         {
                             throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_property_is_not_a_configuration_element", new object[] { elementName }), reader);
                         }
                         if (dictionary.Contains(elementName))
                         {
                             throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_element_cannot_have_multiple_child_elements", new object[] { elementName }), reader);
                         }
                         dictionary.Add(elementName, elementName);
                         ConfigurationElement elem = (ConfigurationElement) this[property3];
                         elem.DeserializeElement(reader, serializeCollectionKey);
                         ValidateElement(elem, property3.Validator, false);
                     }
                 }
                 else
                 {
                     if (reader.NodeType == XmlNodeType.EndElement)
                     {
                         break;
                     }
                     if ((reader.NodeType == XmlNodeType.CDATA) || (reader.NodeType == XmlNodeType.Text))
                     {
                         throw new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_section_invalid_content"), reader);
                     }
                 }
             }
         }
         this.EnsureRequiredProperties(serializeCollectionKey);
         ValidateElement(this, null, false);
     }
     catch (ConfigurationException exception)
     {
         if ((exception.Filename != null) && (exception.Filename.Length != 0))
         {
             throw exception;
         }
         throw new ConfigurationErrorsException(exception.Message, reader);
     }
     if (flag)
     {
         this.SetLocked();
         this._fItemLocked = ConfigurationValueFlags.Locked;
     }
     if (value2 != null)
     {
         if (this._lockedAttributesList == null)
         {
             this._lockedAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedAttributes);
         }
         foreach (string str3 in this.ParseLockedAttributes(value2, ConfigurationLockCollectionType.LockedAttributes))
         {
             if (!this._lockedAttributesList.Contains(str3))
             {
                 this._lockedAttributesList.Add(str3, ConfigurationValueFlags.Default);
             }
             else
             {
                 this._lockedAttributesList.Add(str3, ConfigurationValueFlags.Modified | ConfigurationValueFlags.Inherited);
             }
         }
     }
     if (value3 != null)
     {
         ConfigurationLockCollection parentCollection = this.ParseLockedAttributes(value3, ConfigurationLockCollectionType.LockedExceptionList);
         if (this._lockedAllExceptAttributesList == null)
         {
             this._lockedAllExceptAttributesList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedExceptionList, string.Empty, parentCollection);
             this._lockedAllExceptAttributesList.ClearSeedList();
         }
         StringCollection strings = this.IntersectLockCollections(this._lockedAllExceptAttributesList, parentCollection);
         this._lockedAllExceptAttributesList.ClearInternal(false);
         foreach (string str4 in strings)
         {
             this._lockedAllExceptAttributesList.Add(str4, ConfigurationValueFlags.Default);
         }
     }
     if (value4 != null)
     {
         if (this._lockedElementsList == null)
         {
             this._lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements);
         }
         ConfigurationLockCollection locks2 = this.ParseLockedAttributes(value4, ConfigurationLockCollectionType.LockedElements);
         ConfigurationElementCollection elements = null;
         if (properties.DefaultCollectionProperty != null)
         {
             elements = this[properties.DefaultCollectionProperty] as ConfigurationElementCollection;
             if ((elements != null) && (elements._lockedElementsList == null))
             {
                 elements._lockedElementsList = this._lockedElementsList;
             }
         }
         foreach (string str5 in locks2)
         {
             if (!this._lockedElementsList.Contains(str5))
             {
                 this._lockedElementsList.Add(str5, ConfigurationValueFlags.Default);
                 ConfigurationProperty property4 = this.Properties[str5];
                 if ((property4 != null) && typeof(ConfigurationElement).IsAssignableFrom(property4.Type))
                 {
                     ((ConfigurationElement) this[str5]).SetLocked();
                 }
                 if (str5 == "*")
                 {
                     foreach (ConfigurationProperty property5 in this.Properties)
                     {
                         if (!string.IsNullOrEmpty(property5.Name) && property5.IsConfigurationElementType)
                         {
                             ((ConfigurationElement) this[property5]).SetLocked();
                         }
                     }
                 }
             }
         }
     }
     if (value5 != null)
     {
         ConfigurationLockCollection locks3 = this.ParseLockedAttributes(value5, ConfigurationLockCollectionType.LockedElementsExceptionList);
         if (this._lockedAllExceptElementsList == null)
         {
             this._lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, this._elementTagName, locks3);
             this._lockedAllExceptElementsList.ClearSeedList();
         }
         StringCollection strings2 = this.IntersectLockCollections(this._lockedAllExceptElementsList, locks3);
         ConfigurationElementCollection elements2 = null;
         if (properties.DefaultCollectionProperty != null)
         {
             elements2 = this[properties.DefaultCollectionProperty] as ConfigurationElementCollection;
             if ((elements2 != null) && (elements2._lockedAllExceptElementsList == null))
             {
                 elements2._lockedAllExceptElementsList = this._lockedAllExceptElementsList;
             }
         }
         this._lockedAllExceptElementsList.ClearInternal(false);
         foreach (string str6 in strings2)
         {
             if (!this._lockedAllExceptElementsList.Contains(str6) || (str6 == this.ElementTagName))
             {
                 this._lockedAllExceptElementsList.Add(str6, ConfigurationValueFlags.Default);
             }
         }
         foreach (ConfigurationProperty property6 in this.Properties)
         {
             if ((!string.IsNullOrEmpty(property6.Name) && !this._lockedAllExceptElementsList.Contains(property6.Name)) && property6.IsConfigurationElementType)
             {
                 ((ConfigurationElement) this[property6]).SetLocked();
             }
         }
     }
     if (property != null)
     {
         element = (ConfigurationElement) this[property];
         if (this._lockedElementsList == null)
         {
             this._lockedElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElements);
         }
         element._lockedElementsList = this._lockedElementsList;
         if (this._lockedAllExceptElementsList == null)
         {
             this._lockedAllExceptElementsList = new ConfigurationLockCollection(this, ConfigurationLockCollectionType.LockedElementsExceptionList, reader.Name);
             this._lockedAllExceptElementsList.ClearSeedList();
         }
         element._lockedAllExceptElementsList = this._lockedAllExceptElementsList;
     }
     this.PostDeserialize();
 }
コード例 #29
0
        /// <devdoc>
        /// Convenience method for grabbing the set of property entries that we need to set
        /// on an instance of the object this controlbuilder builds.
        /// </devdoc>
        internal ICollection GetFilteredPropertyEntrySet(ICollection entries) {
            // If we encounter the default value, put it in the table if it doesn't already exist
            // If we encounter the filter value, replace whatevers in the table.
            IDictionary filteredEntries = new HybridDictionary(true);
            IFilterResolutionService filterResolutionService = CurrentFilterResolutionService;

            if (filterResolutionService != null) {
                foreach (PropertyEntry entry in entries) {
                    if (!filteredEntries.Contains(entry.Name)) {
                        String filter = entry.Filter;
                        // empty filter always matches.
                        if (String.IsNullOrEmpty(filter) || filterResolutionService.EvaluateFilter(filter)) {
                            filteredEntries[entry.Name] = entry;
                        }
                    }
                }
            }
            else {
                // If there isn't a filter resolution service, just add anything from the default filter
                foreach (PropertyEntry entry in entries) {
                    if (String.IsNullOrEmpty(entry.Filter)) {
                        filteredEntries[entry.Name] = entry;
                    }
                }
            }

            return filteredEntries.Values;
        }
コード例 #30
0
		/// <summary>
		/// Check the fields for duplicates.
		/// </summary>
		/// <param name="fields"></param>
		/// <returns></returns>
		/// <remarks>
		/// I have to add this check as some stored procedures
		/// return duplicate columns (doh!) and this isn't good
		/// for the binder.
		/// </remarks>
		private int[] FindDuplicateFields(string[] fields)
		{
			HybridDictionary dict = new HybridDictionary(fields.Length, true);
			ArrayList duplicateList = new ArrayList();
			
			for(int i=0; i < fields.Length; i++)
			{
				String field = fields[i];
				
				if (dict.Contains(field))
				{
					duplicateList.Add(i);
					continue;
				}	
				
				dict.Add(field, String.Empty);
			}
			
			return (int[]) duplicateList.ToArray(typeof(int));
		}
コード例 #31
0
		public void NotEmpty () 
		{
			HybridDictionary hd = new HybridDictionary (1, false);
			hd.Add ("CCC", "ccc");
			Assert.AreEqual (1, hd.Count, "Count");
			// ArgumentNullException under all fx versions
			Assert.IsFalse (hd.Contains (null), "Contains(null)");
		}
コード例 #32
0
        /// <summary>
        /// Gets the bar width distribution and calculates narrow bar width over the specified
        /// range of the histogramResult. A histogramResult could have multiple ranges, separated 
        /// by quiet zones.
        /// </summary>
        /// <param name="hist">histogramResult data</param>
        /// <param name="iStart">start coordinate to be considered</param>
        /// <param name="iEnd">end coordinate + 1</param>
        private static void GetBarWidthDistribution(ref histogramResult hist, int iStart, int iEnd)
        {
            HybridDictionary hdLightBars = new HybridDictionary();
            HybridDictionary hdDarkBars = new HybridDictionary();
            bool bDarkBar = (hist.histogram[iStart] <= hist.threshold);
            int iBarStart = 0;
            for (int i = iStart + 1; i < iEnd; i++)
            {
                bool bDark = (hist.histogram[i] <= hist.threshold);
                if (bDark != bDarkBar)
                {
                    int iBarWidth = i - iBarStart;
                    if (bDarkBar)
                    {
                        if (!hdDarkBars.Contains(iBarWidth))
                            hdDarkBars.Add(iBarWidth, 1);
                        else
                            hdDarkBars[iBarWidth] = (int)hdDarkBars[iBarWidth] + 1;
                    }
                    else
                    {
                        if (!hdLightBars.Contains(iBarWidth))
                            hdLightBars.Add(iBarWidth, 1);
                        else
                            hdLightBars[iBarWidth] = (int)hdLightBars[iBarWidth] + 1;
                    }
                    bDarkBar = bDark;
                    iBarStart = i;
                }
            }

            // Now get the most common bar widths
            CalcNarrowBarWidth(hdLightBars, out hist.lightnarrowbarwidth, out hist.lightwiderbarwidth);
            CalcNarrowBarWidth(hdDarkBars, out hist.darknarrowbarwidth, out hist.darkwiderbarwidth);
        }
コード例 #33
0
ファイル: RemoveObjTests.cs プロジェクト: noahfalk/corefx
        public void Test01()
        {
            IntlStrings intl;
            HybridDictionary hd;

            const int BIG_LENGTH = 100;

            // simple string values
            string[] valuesShort =
            {
                "",
                " ",
                "$%^#",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keysShort =
            {
                Int32.MaxValue.ToString(),
                " ",
                System.DateTime.Today.ToString(),
                "",
                "$%^#"
            };

            string[] valuesLong = new string[BIG_LENGTH];
            string[] keysLong = new string[BIG_LENGTH];

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();

            for (int i = 0; i < BIG_LENGTH; i++)
            {
                valuesLong[i] = "Item" + i;
                keysLong[i] = "keY" + i;
            }

            // [] HybridDictionary is constructed as expected
            //-----------------------------------------------------------------

            hd = new HybridDictionary();

            // [] Remove() on empty dictionary
            //
            cnt = hd.Count;
            try
            {
                hd.Remove(null);
                Assert.False(true, string.Format("Error, no exception"));
            }
            catch (ArgumentNullException)
            {
            }
            catch (Exception e)
            {
                Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
            }

            cnt = hd.Count;
            hd.Remove("some_string");
            if (hd.Count != cnt)
            {
                Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
            }

            cnt = hd.Count;
            hd.Remove(new Hashtable());
            if (hd.Count != cnt)
            {
                Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
            }

            //
            // [] Remove() on short dictionary with simple strings
            //

            cnt = hd.Count;
            int len = valuesShort.Length;
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysShort[i], valuesShort[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesShort.Length));
            }
            //

            for (int i = 0; i < len; i++)
            {
                cnt = hd.Count;
                hd.Remove(keysShort[i]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(keysShort[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
                // remove second time
                hd.Remove(keysShort[i]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed when Remove() second time", i));
                }
            }

            // [] Remove() on long dictionary with simple strings
            //

            hd.Clear();
            cnt = hd.Count;
            len = valuesLong.Length;
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
            }
            //

            for (int i = 0; i < len; i++)
            {
                cnt = hd.Count;
                hd.Remove(keysLong[i]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(keysLong[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
                // remove second time
                hd.Remove(keysLong[i]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed when Remove() second time", i));
                }
            }

            //
            // [] Remove() on long dictionary with Intl strings
            // Intl strings
            //

            len = valuesLong.Length;
            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }


            cnt = hd.Count;
            for (int i = 0; i < len; i++)
            {
                hd.Add(intlValues[i + len], intlValues[i]);
            }
            if (hd.Count != (cnt + len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                cnt = hd.Count;
                hd.Remove(intlValues[i + len]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }

            // [] Remove() on short dictionary with Intl strings
            //

            len = valuesShort.Length;

            hd.Clear();
            cnt = hd.Count;
            for (int i = 0; i < len; i++)
            {
                hd.Add(intlValues[i + len], intlValues[i]);
            }
            if (hd.Count != (cnt + len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                cnt = hd.Count;
                hd.Remove(intlValues[i + len]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            //  Case sensitivity
            // [] Case sensitivity - hashtable
            //

            len = valuesLong.Length;

            hd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper());     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key

                cnt = hd.Count;
                hd.Remove(keysLong[i].ToUpper());
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(keysLong[i].ToUpper()))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }

            hd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper());     // adding uppercase strings
            }

            //  LD is case-sensitive by default
            for (int i = 0; i < len; i++)
            {
                // lowercase key
                cnt = hd.Count;
                hd.Remove(keysLong[i].ToLower());
                if (hd.Count != cnt)
                {
                    Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i));
                }
            }

            //
            // [] Case sensitivity - list


            len = valuesShort.Length;

            hd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper());     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key

                cnt = hd.Count;
                hd.Remove(keysLong[i].ToUpper());
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(keysLong[i].ToUpper()))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }

            hd.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper());     // adding uppercase strings
            }

            //  LD is case-sensitive by default
            for (int i = 0; i < len; i++)
            {
                // lowercase key
                cnt = hd.Count;
                hd.Remove(keysLong[i].ToLower());
                if (hd.Count != cnt)
                {
                    Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i));
                }
            }

            //
            // [] Remove() on case-insensitive HD - list
            //

            hd = new HybridDictionary(true);

            len = valuesShort.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                cnt = hd.Count;
                hd.Remove(keysLong[i].ToUpper());
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(keysLong[i].ToLower()))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }

            //
            // [] Remove() on case-insensitive HD - hashtable
            //
            hd = new HybridDictionary(true);

            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
            }
            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                cnt = hd.Count;
                hd.Remove(keysLong[i].ToUpper());
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (hd.Contains(keysLong[i].ToLower()))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            //  [] Remove(null)  from filled HD - list
            //
            hd = new HybridDictionary();
            len = valuesShort.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysShort[i], valuesShort[i]);
            }

            try
            {
                hd.Remove(null);
                Assert.False(true, string.Format("Error, no exception"));
            }
            catch (ArgumentNullException)
            {
            }
            catch (Exception e)
            {
                Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
            }

            //
            //  [] Remove(null)  from filled HD - hashtable
            //
            hd = new HybridDictionary();
            len = valuesLong.Length;
            hd.Clear();
            for (int i = 0; i < len; i++)
            {
                hd.Add(keysLong[i], valuesLong[i]);
            }

            try
            {
                hd.Remove(null);
                Assert.False(true, string.Format("Error, no exception"));
            }
            catch (ArgumentNullException)
            {
            }
            catch (Exception e)
            {
                Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
            }

            //
            //  [] Remove(special_object)  from filled HD - list
            //
            hd = new HybridDictionary();

            hd.Clear();
            len = 2;
            ArrayList[] b = new ArrayList[len];
            Hashtable[] lbl = new Hashtable[len];
            for (int i = 0; i < len; i++)
            {
                lbl[i] = new Hashtable();
                b[i] = new ArrayList();
                hd.Add(lbl[i], b[i]);
            }

            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                cnt = hd.Count;
                hd.Remove(lbl[i]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove special object"));
                }
                if (hd.Contains(lbl[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong special object"));
                }
            }

            //
            //  [] Remove(special_object)  from filled HD - hashtable
            //
            hd = new HybridDictionary();

            hd.Clear();
            len = 40;
            b = new ArrayList[len];
            lbl = new Hashtable[len];
            for (int i = 0; i < len; i++)
            {
                lbl[i] = new Hashtable();
                b[i] = new ArrayList();
                hd.Add(lbl[i], b[i]);
            }

            if (hd.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                cnt = hd.Count;
                hd.Remove(lbl[i]);
                if (hd.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove special object"));
                }
                if (hd.Contains(lbl[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong special object"));
                }
            }
        }