public void TestCtorDictionarySingle() { // No exception var hash = new Hashtable(new Hashtable(), 1f); // No exception hash = new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()), 1f), 1f), 1f), 1f); // []test to see if elements really get copied from old dictionary to new hashtable Hashtable tempHash = new Hashtable(); // this for assumes that MinValue is a negative! for (long i = long.MinValue; i < long.MinValue + 100; i++) { tempHash.Add(i, i); } hash = new Hashtable(tempHash, 1f); // make sure that new hashtable has the elements in it that old hashtable had for (long i = long.MinValue; i < long.MinValue + 100; i++) { Assert.True(hash.ContainsKey(i)); Assert.True(hash.ContainsValue(i)); } //[]make sure that there are no connections with the old and the new hashtable tempHash.Clear(); for (long i = long.MinValue; i < long.MinValue + 100; i++) { Assert.True(hash.ContainsKey(i)); Assert.True(hash.ContainsValue(i)); } }
public void TestAddBasic() { Hashtable ht = null; string[] keys = { "key_0", "key_1"}; string[] values = { "val_0", "val_1" }; var k1 = new StringBuilder(keys[0]); var k2 = new StringBuilder(keys[1]); var v1 = new StringBuilder(values[0]); var v2 = new StringBuilder(values[1]); ht = new Hashtable(); ht.Add(k1, v1); ht.Add(k2, v2); Assert.True(ht.ContainsKey(k2)); Assert.True(ht.ContainsValue(v2)); ICollection allkeys = ht.Keys; Assert.Equal(allkeys.Count, ht.Count); IEnumerator allkeysEnum = allkeys.GetEnumerator(); int index = 0; string[] ary = new string[2]; while (allkeysEnum.MoveNext()) { ary[index++] = allkeysEnum.Current.ToString(); } // Not necessary the same order if (keys[0] == ary[0]) { Assert.Equal(keys[1], ary[1]); } else { Assert.Equal(keys[0], ary[1]); } ICollection allvalues = ht.Values; Assert.Equal(allvalues.Count, ht.Count); IEnumerator allvaluesEnum = allvalues.GetEnumerator(); index = 0; while (allvaluesEnum.MoveNext()) { ary[index++] = (string)allvaluesEnum.Current.ToString(); } if (values[0] == ary[0]) { Assert.Equal(values[1], ary[1]); } else { Assert.Equal(values[0], ary[1]); } }
//public static int esPalabraClave(string cadena) public static bool esPalabraClave(string cadena) { //int retorno = 0; //if (hashTableKeywords.ContainsValue(cadena)) // retorno=0; //else // retorno=-1; //return retorno; return(hashTableKeywords.ContainsValue(cadena)); }
/// <summary> /// Takes a hash table and compares it with its own hash table and adds /// the common words in passed list 'CommonWords' we assume that list already contains /// all common words and we have to only remove the words which are not found. /// </summary> /// <param name="ht"></param> /// <param name="CommonWords"></param> public void Compare(List <string> CommonWords) { for (int i = 0; i < CommonWords.Count; i++) { if (!Htable.ContainsValue(CommonWords.ElementAt(i))) { CommonWords.RemoveAt(i);//remove uncommon words from common list } } }
public bool ContainsValue(string tablename, object val) { Hashtable hashtable = (Hashtable)this.datastore[tablename]; if (hashtable != null) { return(hashtable.ContainsValue(SerializeIfPossible(val))); } return(false); }
static int ContainsValue(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 2); Hashtable obj = LuaScriptMgr.GetNetObject <Hashtable>(L, 1); object arg0 = LuaScriptMgr.GetVarObject(L, 2); bool o = obj.ContainsValue(arg0); LuaScriptMgr.Push(L, o); return(1); }
/// <summary> /// Enables or disables the ifolder action buttons. /// </summary> private void SetActionButtons() { Hashtable ht = CheckedUsers; DeleteButton.Enabled = (ht.Count > 0) ? true : false; DisableButton.Enabled = ht.ContainsValue(true); EnableButton.Enabled = ht.ContainsValue(false); ProvisionButton.Enabled = true; bool UnProvisionedUser = false; if (ht.Keys.Count > 0) { UnProvisionedUser = true; } if (UnProvisionedUser == false) { ProvisionButton.Enabled = false; } }
static void Main(string[] args) { #region System.Collections.Hashtable Hashtable ht = new Hashtable() { [1] = "하나", [2] = "둘", [3] = "셋" }; ht.Add("Name", "아이유"); ht["Age"] = 26; PrintHashtable(ht); if (ht.ContainsKey("Name")) { ht["Name"] = "장만월"; } else { ht.Add("Name", "장만월"); } PrintHashtable(ht); if (ht.ContainsValue("넷")) { Console.WriteLine("이미 값이 존재함."); } else { ht.Add(4, "넷"); } #endregion #region System.Collections.Generic.Dictionary Dictionary <int, string> dic = new Dictionary <int, string>() { [1] = "하나", [2] = "둘" }; dic[3] = "셋"; dic.Add(4, "넷"); PrintDictionary(dic); #endregion #region 추가 학습 PrintDictionary2 <int, string>(dic); Dictionary <string, string> dic2 = new Dictionary <string, string>() { ["one"] = "하나", ["two"] = "둘" }; PrintDictionary2 <string, string>(dic2); #endregion }
public void TestCtorIntSingle() { // variables used for tests Hashtable hash = null; // [] should get ArgumentException if trying to have large num of entries Assert.Throws <ArgumentException>(() => { hash = new Hashtable(int.MaxValue, .1f); } ); // []should not get any exceptions for valid values - we also check that the HT works here hash = new Hashtable(100, .1f); int iNumberOfElements = 100; for (int i = 0; i < iNumberOfElements; i++) { hash.Add("Key_" + i, "Value_" + i); } //Count Assert.Equal(hash.Count, iNumberOfElements); DictionaryEntry[] strValueArr = new DictionaryEntry[hash.Count]; hash.CopyTo(strValueArr, 0); Hashtable hsh3 = new Hashtable(); for (int i = 0; i < iNumberOfElements; i++) { Assert.True(hash.Contains("Key_" + i), "Error, Expected value not returned, " + hash.Contains("Key_" + i)); Assert.True(hash.ContainsKey("Key_" + i), "Error, Expected value not returned, " + hash.ContainsKey("Key_" + i)); Assert.True(hash.ContainsValue("Value_" + i), "Error, Expected value not returned, " + hash.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hash.ContainsValue(((DictionaryEntry)strValueArr[i]).Value), "Error, Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } }
public string getHashCode(string value) { if (ht.ContainsValue(value)) { return("empty"); } else { return("empty"); } }
public static bool Exist(string key) { if (_ht.ContainsValue(key)) { return(true); } else { return(false); } }
protected override CustomerAccount UpdateEntity(Hashtable entityContext, CustomerAccount entity) { var b = entityContext.ContainsValue(entity.AccountNo); if (b) { //TODO } return(entity); }
private void button9_Click(object sender, EventArgs e) { if (ht.ContainsValue(textBox2.Text) == true) { MessageBox.Show("Aradığınız " + textBox2.Text + " ifadesi dizi içinde bulunmuştur"); } else { MessageBox.Show("Aradığınız " + textBox2.Text + " ifadesi dizi içinde bulunamadı"); } }
static void Main(string[] args) { //map in c# Hashtable map = new Hashtable(); for (int i = 0; i < 10; i++) { map.Add(i, i + 10); } bool f = map.ContainsKey(0); bool t = map.ContainsValue(1); foreach (int i in map.Keys) { Console.WriteLine(i + " " + map[i]); } Console.ReadLine(); //Queue Queue q = new Queue(); q.Enqueue("Abhi"); q.Enqueue("Abhinav"); q.Enqueue("Ghosh"); while (q.Count > 0) { Console.WriteLine(q.Dequeue()); } Console.ReadLine(); //stack Stack stackObject = new Stack(); stackObject.Push("Joydip"); stackObject.Push("Steve"); stackObject.Push("Jini"); while (stackObject.Count > 0) { Console.WriteLine(stackObject.Pop()); } Console.ReadLine(); //ArrayList int intValue = 100; double doubleValue = 20.5; ArrayList arrayList = new ArrayList(); arrayList.Add("John"); arrayList.Add(intValue); arrayList.Add(doubleValue); for (int index = 0; index < arrayList.Count; index++) { Console.WriteLine(arrayList[index]); } Console.ReadLine(); }
static void Main(string[] args) { int a = 1; String b = "Bul"; Hashtable myHashtable = new Hashtable(); myHashtable.Add(a, "BITM"); myHashtable.Add(b, "Hasan"); Console.WriteLine(myHashtable[1]); Console.WriteLine(myHashtable["Bul"]); Console.WriteLine(myHashtable.ContainsValue("BITM")); foreach (DictionaryEntry dictionaryEntry in myHashtable) { Console.WriteLine(dictionaryEntry.Key + "-" + dictionaryEntry.Value); } /*Dictionary<int,String> mydDictionary = new Dictionary<int, string>(); * mydDictionary.Add(1,"Adbullah"); * mydDictionary.Add(2,"Al"); * mydDictionary.Add(3,"Hasan"); * * foreach (KeyValuePair<int, string> keyValuePair in mydDictionary) * { * Console.WriteLine(keyValuePair.Key+" - "+keyValuePair.Value); * }*/ //dynamic myDynamic = new System.Dynamic.ExpandoObject(); //var mydictionary = new Dictionary<int, dynamic>(); //mydictionary[1] = myDynamic; //mydictionary[1].FirstName = "Abdulllah"; //mydictionary[1].MiddleName = "Al"; //mydictionary[1].LastName = "Hasan"; //Console.WriteLine(mydictionary[1].FirstName+" "+mydictionary[1].MiddleName+" "+mydictionary[1].LastName); //String[] myName = {"Abdullah", "Al", "Hasan"}; //Dictionary<int,String[]> myStringses = new Dictionary<int, string[]>(); //mydictionary.Add(1,myStringses[0]); //mydictionary.Add(1, myStringses[1]); //mydictionary.Add(1, myStringses[2]); //foreach (KeyValuePair<int, string[]> keyValuePair in myStringses) //{ // Console.WriteLine(keyValuePair.Key+" "+keyValuePair.Value); //} Console.ReadKey(); }
public static bool ExistToken(string orderNo) { if (_ht.ContainsValue(orderNo)) { return(true); } else { return(false); } }
static void Main(string[] args) { Hashtable ht = new Hashtable(); ht.Add("001", ".Net"); ht.Add("002", "C#"); ht.Add("003", "ASP.Net"); Console.WriteLine(ht.ContainsKey("001")); Console.WriteLine(ht.ContainsValue("C#")); }
public bool InsertPerson(Pessoa p) { if (!dados.ContainsValue(p)) { //atributo é calculado! p.perfil = p.idade * 2; dados.Add(HashFunction(p), p); return(true); } return(false); }
public bool ContainsValue(string tablename, object val) { Hashtable hashtable = this.datastore[tablename] as Hashtable; if (hashtable == null) { return(false); } return(hashtable.ContainsValue(val)); }
public override Task OnConnected() { int i = 0; var name = Context.QueryString["name"]; string listusers = ""; if (!users.ContainsValue(name)) { users.Add(Context.ConnectionId, name); } foreach (DictionaryEntry item in users) { if (name != item.Value.ToString()) { listusers += item.Value.ToString() + ","; } } Clients.All.SendStatus(name, listusers); return(base.OnConnected()); }
private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { TreeListNode node = treeList1.FocusedNode; Ps_Forecast_Math pt = Services.BaseService.GetOneByKey <Ps_Forecast_Math>(node["ID"].ToString()); if (!hs.ContainsValue(pt)) { hs.Add(Guid.NewGuid().ToString(), pt); } this.DialogResult = DialogResult.OK; this.Close(); }
private void Form1_Load(object sender, EventArgs e) { this.Controls.Add(label1); this.Controls.Add(label12); this.Controls.Add(label2); this.Controls.Add(textBox1); this.Controls.Add(label14); this.Controls.Add(button1); this.Controls.Add(button2); this.Controls.Add(button3); this.Controls.Add(button4); this.Controls.Add(button5); this.Controls.Add(button6); this.Controls.Add(button7); this.Controls.Add(button8); this.Controls.Add(button9); a[0, 0] = button1; a[0, 1] = button2; a[0, 2] = button3; a[1, 0] = button4; a[1, 1] = button5; a[1, 2] = button6; a[2, 0] = button7; a[2, 1] = button8; a[2, 2] = button9; Hashtable hashtable = new Hashtable(); Random rm = new Random(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int nValue = rm.Next(0, 9); if (!hashtable.ContainsValue(nValue)) { a[i, j].Text = Convert.ToString(nValue); hashtable.Add(nValue, nValue); if (nValue == 0) { m = i; n = j; } } else { j--; } } } textBox1.Text = "hh"; label14.Text = "0"; }
public void TestClearBasic() { StringBuilder sblMsg = new StringBuilder(99); Hashtable ht1 = null; string s1 = null; string s2 = null; int i = 0; ht1 = new Hashtable(); //default constructor ht1.Clear(); Assert.Equal(0, ht1.Count); // add 100 key-val pairs ht1 = new Hashtable(); for (i = 0; i < 100; i++) { sblMsg = new StringBuilder(99); sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg = new StringBuilder(99); sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); ht1.Add(s1, s2); } Assert.Equal(100, ht1.Count); ht1.Clear(); Assert.Equal(0, ht1.Count); //[]we will make a token call for some important methods to make sure that this is indeed clear s1 = "key_0"; Assert.False(ht1.ContainsKey(s1)); s1 = "val_0"; Assert.False(ht1.ContainsValue(s1)); //[]repeated clears of the HT. Nothing should happen for (i = 0; i < 100; i++) { ht1.Clear(); Assert.Equal(0, ht1.Count); } }
public bool ContainsValue(string tablename, object val) { Contract.Requires(!string.IsNullOrEmpty(tablename)); Hashtable hashtable = (Hashtable)this.datastore[tablename]; if (hashtable != null) { return(hashtable.ContainsValue(StringifyIfVector3(val))); } return(false); }
/// <summary> /// 删除某个子窗体 /// </summary> /// <param name="gui"></param> public void Remove(IMdiChild gui) { if (_hash.ContainsValue(gui)) { Framework.WinGui.Menus.AppMenuCommand stype; if (this._active == gui) { this.DeactiveGui(); } _hash.Remove(gui.ID); //移除工具条菜单 Framework.WinGui.Menus.AppMenuCommand toollistmenu = AppMenuCommand.ToolBarList; if (toollistmenu != null) { if (gui.Tools != null) { for (int i = 0; i < gui.Tools.Length; i++) { for (int j = 0; j < toollistmenu.Parent.MenuItems.Count; j++) { if (toollistmenu.Parent.MenuItems[j] is AppMenuCommand) { stype = (AppMenuCommand)toollistmenu.Parent.MenuItems[j]; if (stype.ID == gui.ID + gui.Tools[i].Name) { toollistmenu.Parent.MenuItems.RemoveAt(j); break; } } } } } } //移除窗口菜单 Framework.WinGui.Menus.AppMenuCommand mdilist = AppMenuCommand.MidList; if (mdilist != null) { for (int j = 0; j < mdilist.Parent.MenuItems.Count; j++) { if (mdilist.Parent.MenuItems[j] is AppMenuCommand) { stype = (AppMenuCommand)mdilist.Parent.MenuItems[j]; if (stype.ID == gui.ID + "_MdiList") { mdilist.Parent.MenuItems.RemoveAt(j); break; } } } } //释放窗体资源 } }
/// <summary> /// Enables or disables the ifolder action buttons. /// </summary> private void SetActionButtons() { Hashtable ht = CheckediFolders; switch (ActiveiFolderTab) { case ListDisplayType.Orphaned: DeleteButton.Visible = true; DeleteButton.Enabled = (ht.Count > 0) ? true : false; break; case ListDisplayType.All: default: DeleteButton.Visible = true; break; } DeleteButton.Enabled = (ht.Count > 0) ? true : false; DisableButton.Enabled = ht.ContainsValue(Boolean.FalseString); EnableButton.Enabled = ht.ContainsValue(Boolean.TrueString); }
private void InitSodata2() { string sid = "1"; Hashtable hs1 = new Hashtable(); Hashtable hs3 = new Hashtable(); IList <substation> listsubstation = Services.BaseService.GetList <substation>("SelectsubstationByPowerIDStuff", sid); foreach (substation s1 in listsubstation) { hs1.Add(Guid.NewGuid().ToString(), s1.UID); } IList <Substation_Info> ll2 = Common.Services.BaseService.GetList <Substation_Info>("SelectSubstation_InfoByFlag", sid); foreach (Substation_Info ps in ll2) { hs3.Add(Guid.NewGuid().ToString(), ps.Code); } foreach (Substation_Info p2 in ll2) { if (p2.Code != "" && !hs1.ContainsValue(p2.Code)) { //删除 Services.BaseService.Delete <Substation_Info>(p2); } } foreach (substation s2 in listsubstation) { if (!hs3.ContainsValue(s2.UID) && s2.ObligateField1 != "") { //添加 try { Substation_Info substation1 = new Substation_Info(); substation1.L1 = int.Parse(s2.ObligateField1); substation1.Title = s2.EleName; substation1.Code = s2.UID; substation1.Flag = sid; Services.BaseService.Create <Substation_Info>(substation1); } catch { } } } }
private void addrowtodt1(DataRow dr, DataRow row, ref DataTable dt1) { //bool IScontiue = true; //if (Ishash1) //{ // if (!hash.ContainsValue(dr["Title"])) // IScontiue=false; //} //else //{ // if (!hash2.ContainsValue(dr["Title"])) // IScontiue = false; //} //if (IScontiue) //{ //row["Title1"] = row1["Title"].ToString().Replace(" ", ""); foreach (DataColumn dc in GridDataTable.Columns) { if (dc.ColumnName.IndexOf("定") > 0) { try { row[dc.ColumnName] = Convert.ToDouble(dr[dc.ColumnName].ToString()); } catch { row[dc.ColumnName] = 0; } } else { if (hash.ContainsValue(dr[dc.ColumnName])) { row["Title1"] = dr[dc.ColumnName].ToString(); continue; } else if (hash2.ContainsValue(dr[dc.ColumnName])) { row["Title2"] = dr[dc.ColumnName].ToString(); continue; } else if (dc.ColumnName == "Title") { row["Title"] = dr[dc.ColumnName].ToString(); continue; } } } dt1.Rows.Add(row); //} }
/// <summary> /// Update combox item whith vStorage server ip address /// </summary> private void InitStorageComboBox() { List <IXenConnection> xenConnectionsCopy = ConnectionsManager.XenConnectionsCopy; xenConnectionsCopy.Sort(); Hashtable items = new Hashtable(); int i = 0; foreach (IXenConnection connection in xenConnectionsCopy) { VM[] vMs = connection.Cache.VMs.Where(vm => vm.uuid != null).ToArray(); Array.Sort <VM>(vMs); Pool pool = Helpers.GetPool(connection); if (pool != null && pool.other_config.ContainsKey("halsign_br_ip_address")) { if (!items.ContainsValue(pool.other_config["halsign_br_ip_address"])) { items.Add(i, pool.other_config["halsign_br_ip_address"]); i++; } } foreach (VM vm in vMs) { if (vm != null && vm.other_config.ContainsKey("halsign_br_ip_address")) { if (!items.ContainsValue(vm.other_config["halsign_br_ip_address"])) { items.Add(i, vm.other_config["halsign_br_ip_address"]); i++; } } } } this.ComboBox_IP.BeginUpdate(); foreach (DictionaryEntry item in items) { this.ComboBox_IP.Items.Add(item.Value); } this.ComboBox_IP.EndUpdate(); }
public void TestVenueFactoryRegisterSuccess() { VenueFactory venueFactory = VenueFactory.GetInstance; PrivateObject privateAccessor = new PrivateObject(venueFactory); privateAccessor.SetField("venueFeatures", new Hashtable()); // Reset venueFeatures Hashtable refVenueFeatures = (Hashtable)privateAccessor.GetField("venueFeatures"); VenueAfternoonRefreshments mockVAfterRef = Substitute.For <VenueAfternoonRefreshments>(); VenueMorningRefreshments mockVMornRef = Substitute.For <VenueMorningRefreshments>(); VenueEveningMeal mockVEveMeal = Substitute.For <VenueEveningMeal>(); VenueBusTransport mockVBusTrans = Substitute.For <VenueBusTransport>(); VenueMiddayLunch mockVMidLunch = Substitute.For <VenueMiddayLunch>(); venueFactory.Register(VenueAddOns.MORNING_REFRESHMENTS, mockVMornRef); Assert.IsTrue(refVenueFeatures.ContainsKey(VenueAddOns.MORNING_REFRESHMENTS)); Assert.IsTrue(refVenueFeatures.ContainsValue(mockVMornRef)); Assert.AreEqual <int>(1, refVenueFeatures.Count); venueFactory.Register(VenueAddOns.AFTERNOON_REFRESHMENTS, mockVAfterRef); Assert.IsTrue(refVenueFeatures.ContainsKey(VenueAddOns.AFTERNOON_REFRESHMENTS)); Assert.IsTrue(refVenueFeatures.ContainsValue(mockVAfterRef)); Assert.AreEqual <int>(2, refVenueFeatures.Count); venueFactory.Register(VenueAddOns.EVENING_MEAL, mockVEveMeal); Assert.IsTrue(refVenueFeatures.ContainsKey(VenueAddOns.EVENING_MEAL)); Assert.IsTrue(refVenueFeatures.ContainsValue(mockVEveMeal)); Assert.AreEqual <int>(3, refVenueFeatures.Count); venueFactory.Register(VenueAddOns.BUS_TRANSPORTS, mockVBusTrans); Assert.IsTrue(refVenueFeatures.ContainsKey(VenueAddOns.BUS_TRANSPORTS)); Assert.IsTrue(refVenueFeatures.ContainsValue(mockVBusTrans)); Assert.AreEqual <int>(4, refVenueFeatures.Count); venueFactory.Register(VenueAddOns.MIDDAY_LUNCH, mockVMidLunch); Assert.IsTrue(refVenueFeatures.ContainsKey(VenueAddOns.MIDDAY_LUNCH)); Assert.IsTrue(refVenueFeatures.ContainsValue(mockVMidLunch)); Assert.AreEqual <int>(5, refVenueFeatures.Count); }
public int Inspect(out int keysum, out int valuesum) { table.Clear(); for (int i = 0; i < 10; i++) { table.Add(i, i * i); } int flag = 0; if (table.Contains(0)) { flag += 1; } if (table.Contains("0") == false) { flag += 10; } if (table.ContainsKey(3)) { flag += 100; } if (table.ContainsValue(81)) { flag += 1000; } if ((int)table[8] == 64) { flag += 10000; } table[8] = 89; if ((int)table[8] == 89) { flag += 100000; } if (table.Count == 10) { flag += 1000000; } keysum = 0; foreach (object o in table.Keys) { keysum += (int)o; } valuesum = 0; foreach (object o in table.Values) { valuesum += (int)o; } return(flag); }
// More info on https://www.tutorialspoint.com/csharp/csharp_hashtable.htm // More examples on https://www.geeksforgeeks.org/c-sharp-hashtable-with-examples/ // Avg time complexity O(1) constant time // Worst case time complexity O(n) linear time private static void HashTableOperations() { // Hashtable is a collection of key/value pairs arranged based on the hash code of the key // Keys cannot be null, must be immutable and unique // In C# it implements IDictionary, ICollection, IEnumerable // These can contain elements of different types // Systems.Collections Hashtable myHashTable = new Hashtable(); // Insert using Add() myHashTable.Add(1001, "Jon Doe"); myHashTable.Add(1002, "Mark Doe"); // Delete using Remove() by key myHashTable.Remove(1001); // Clear all contents myHashTable.Clear(); // Search // Contains (key), ContainsKey, ContainstValue bool findKey = myHashTable.Contains(1001); findKey = myHashTable.ContainsKey(1001); bool findValue = myHashTable.ContainsValue("Jon Doe"); string name = "NOT FOUND"; // get value by key if (findKey) { name = myHashTable[1001].ToString(); } Console.WriteLine("Name : " + name); foreach (DictionaryEntry pair in myHashTable) { Console.WriteLine(pair.Key.ToString() + " " + pair.Value.ToString()); } // Showing all values var allValues = myHashTable.Values; foreach (var val in allValues) { Console.WriteLine(val.ToString()); } return; }
/// <summary> /// Randoms the mines position. /// </summary> /// <returns>The mines position.</returns> /// <param name="sum">Sum.</param> int[] RandomMinesPosition(int sum) { int[] arr = new int[sum]; int j = 0; //表示键和值对的集合。 se hashable to store key and values Hashtable hashtable = new Hashtable(); System.Random rm = new System.Random(); for (int i = 0; hashtable.Count < sum; i++) { //返回一个小于所指定最大值的非负随机数 return a number < max but >0 int nValue = rm.Next(numOfCubes); //containsValue(object value) 是否包含特定值 if (!hashtable.ContainsValue(nValue) && nValue != 0) { //把键和值添加到hashtable add key value to hashtable hashtable.Add(nValue, nValue); //Debug.Log(i); arr[j] = nValue; j++; } } int temp; //最多做n-1趟排序 sort array for (int i = 0; i < arr.Length - 1; i++) { //对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的) for (j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; Hashtable hsh1; String strValue; Thread[] workers; ThreadStart ts1; Int32 iNumberOfWorkers = 15; Boolean fLoopExit; DictionaryEntry[] strValueArr; String[] strKeyArr; Hashtable hsh3; Hashtable hsh4; IDictionaryEnumerator idic; MemoryStream ms1; Boolean fPass; Object oValue; try { do { hsh1 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { hsh1.Add("Key_" + i, "Value_" + i); } hsh2 = Hashtable.Synchronized(hsh1); fPass = true; iCountTestcases++; if(hsh2.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count); } for(int i=0; i<iNumberOfElements; i++) { if(!((String)hsh2["Key_" + i]).Equals("Value_" + i)) { Console.WriteLine(hsh2["Key_" + i]); fPass = false; } } try { oValue = hsh2[null]; fPass = false; } catch(ArgumentNullException) { } catch(Exception) { fPass = false; } hsh2.Clear(); for(int i=0; i<iNumberOfElements; i++) { hsh2["Key_" + i] = "Value_" + i; } if(!fPass) { iCountErrors++; Console.WriteLine("Err_752dsgf! Oh man! This is busted!!!!"); } strValueArr = new DictionaryEntry[hsh2.Count]; hsh2.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh2.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh2.Contains("Key_" + i)); } if(!hsh2.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh2.ContainsKey("Key_" + i)); } if(!hsh2.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_563fgd! Expected value not returned, " + hsh2.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(strValueArr[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + strValueArr[i]); } } hsh4 = (Hashtable)hsh2.Clone(); if(hsh4.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_342342! Expected value not returned, " + hsh4.Count); } strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh4.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i)); } if(!hsh4.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i)); } if(!hsh4.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_6-4142dsf! Expected value not returned, " + hsh4.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + ((DictionaryEntry)strValueArr[i]).Value); } } if(hsh4.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly); } if(!hsh4.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized); } idic = hsh2.GetEnumerator(); hsh3 = new Hashtable(); hsh4 = new Hashtable(); while(idic.MoveNext()) { if(!hsh2.ContainsKey(idic.Key)) { iCountErrors++; Console.WriteLine("Err_4532sfds! Expected value not returned"); } if(!hsh2.ContainsValue(idic.Value)) { iCountErrors++; Console.WriteLine("Err_682wm! Expected value not returned"); } try { hsh3.Add(idic.Key, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_5243sfd! Exception thrown for " + idic.Key); } try { hsh4.Add(idic.Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_25sfs! Exception thrown for " + idic.Value); } } BinaryFormatter formatter = new BinaryFormatter(); ms1 = new MemoryStream(); formatter.Serialize(ms1, hsh2); ms1.Position = 0; hsh4 = (Hashtable)formatter.Deserialize(ms1); if(hsh4.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_072xsf! Expected value not returned, " + hsh4.Count); } strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh4.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i)); } if(!hsh4.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i)); } if(!hsh4.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_0672esfs! Expected value not returned, " + hsh4.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + strValueArr[i]); } } if(hsh4.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly); } if(!hsh4.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized); } if(hsh2.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsReadOnly); } if(!hsh2.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsSynchronized); } if(hsh2.SyncRoot != hsh1) { iCountErrors++; Console.WriteLine("Err_7428dsafd! Expected value not returned, "); } String[] strValueArr11 = new String[hsh1.Count]; strKeyArr = new String[hsh1.Count]; hsh2.Keys.CopyTo(strKeyArr, 0); hsh2.Values.CopyTo(strValueArr11, 0); hsh3 = new Hashtable(); hsh4 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hsh2.ContainsKey(strKeyArr[i])) { iCountErrors++; Console.WriteLine("Err_4532sfds! Expected value not returned"); } if(!hsh2.ContainsValue(strValueArr11[i])) { iCountErrors++; Console.WriteLine("Err_074dsd! Expected value not returned, " + strValueArr11[i]); } try { hsh3.Add(strKeyArr[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_5243sfd! Exception thrown for " + idic.Key); } try { hsh4.Add(strValueArr11[i], null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_25sfs! Exception thrown for " + idic.Value); } } hsh2.Remove("Key_1"); if(hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_64q213d! Expected value not returned, "); } hsh2.Add("Key_1", "Value_1"); if(!hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(!hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_74523esf! Expected value not returned, "); } hsh2["Key_1"] = "Value_Modified_1"; if(!hsh2.ContainsKey("Key_1")) { iCountErrors++; Console.WriteLine("Err_423ewd! Expected value not returned, "); } if(hsh2.ContainsValue("Value_1")) { iCountErrors++; Console.WriteLine("Err_74523esf! Expected value not returned, "); } if(!hsh2.ContainsValue("Value_Modified_1")) { iCountErrors++; Console.WriteLine("Err_342fs! Expected value not returned, "); } hsh3 = Hashtable.Synchronized(hsh2); if(hsh3.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh3.Count); } if(!hsh3.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh3.IsSynchronized); } hsh2.Clear(); if(hsh2.Count != 0) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count); } strLoc = "Loc_8345vdfv"; hsh1 = new Hashtable(); hsh2 = Hashtable.Synchronized(hsh1); workers = new Thread[iNumberOfWorkers]; ts1 = new ThreadStart(AddElements); for(int i=0; i<workers.Length; i++) { workers[i] = new Thread(ts1); workers[i].Name = "Thread worker " + i; workers[i].Start(); } while(true) { fLoopExit=false; for(int i=0; i<iNumberOfWorkers;i++) { if(workers[i].IsAlive) fLoopExit=true; } if(!fLoopExit) break; } iCountTestcases++; if(hsh2.Count != iNumberOfElements*iNumberOfWorkers) { iCountErrors++; Console.WriteLine("Err_75630fvbdf! Expected value not returned, " + hsh2.Count); } iCountTestcases++; for(int i=0; i<iNumberOfWorkers; i++) { for(int j=0; j<iNumberOfElements; j++) { strValue = "Thread worker " + i + "_" + j; if(!hsh2.Contains(strValue)) { iCountErrors++; Console.WriteLine("Err_452dvdf_" + i + "_" + j + "! Expected value not returned, " + strValue); } } } workers = new Thread[iNumberOfWorkers]; ts1 = new ThreadStart(RemoveElements); for(int i=0; i<workers.Length; i++) { workers[i] = new Thread(ts1); workers[i].Name = "Thread worker " + i; workers[i].Start(); } while(true) { fLoopExit=false; for(int i=0; i<iNumberOfWorkers;i++) { if(workers[i].IsAlive) fLoopExit=true; } if(!fLoopExit) break; } iCountTestcases++; if(hsh2.Count != 0) { iCountErrors++; Console.WriteLine("Err_6720fvdg! Expected value not returned, " + hsh2.Count); } iCountTestcases++; if(hsh1.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh1.IsSynchronized); } iCountTestcases++; if(!hsh2.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh2.IsSynchronized); } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public void TestSyncRoot() { // Different hashtables have different SyncRoots var hash1 = new Hashtable(); var hash2 = new Hashtable(); Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot); Assert.Equal(hash1.SyncRoot.GetType(), typeof(object)); // Cloned hashtables have different SyncRoots hash1 = new Hashtable(); hash2 = Hashtable.Synchronized(hash1); Hashtable hash3 = (Hashtable)hash2.Clone(); Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot); Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot); // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenrio we have in mind. // 1) Create your Down to earth mother Hashtable // 2) Get a synchronized wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var hashMother = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { hashMother.Add("Key_" + i, "Value_" + i); } Hashtable hashSon = Hashtable.Synchronized(hashMother); _hashGrandDaughter = Hashtable.Synchronized(hashSon); _hashDaughter = Hashtable.Synchronized(hashMother); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); // We are going to rumble with the Hashtables with some threads int iNumberOfWorkers = 30; var workers = new Task[iNumberOfWorkers]; var ts2 = new Action(RemoveElements); for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2) { var name = "Thread_worker_" + iThreads; var ts1 = new Action(() => AddMoreElements(name)); workers[iThreads] = Task.Run(ts1); workers[iThreads + 1] = Task.Run(ts2); } Task.WaitAll(workers); // Check: // Either there should be some elements (the new ones we added and/or the original ones) or none var hshPossibleValues = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { hshPossibleValues.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < iNumberOfWorkers; i++) { hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } IDictionaryEnumerator idic = hashMother.GetEnumerator(); while (idic.MoveNext()) { Assert.True(hshPossibleValues.ContainsKey(idic.Key)); Assert.True(hshPossibleValues.ContainsValue(idic.Value)); } }
public static void TestRemove_SameHashcode() { // We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable // does not expand but have to tread through collision bit set positions to insert the new elements. We do this // by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that // the hashtable does not expand as long as we have at most 7 elements at any given time? var hash = new Hashtable(); var arrList = new ArrayList(); for (int i = 0; i < 7; i++) { var hashConfuse = new BadHashCode(i); arrList.Add(hashConfuse); hash.Add(hashConfuse, i); } var rand = new Random(-55); int iCount = 7; for (int i = 0; i < 100; i++) { for (int j = 0; j < 7; j++) { Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value); } // Delete 3 elements from the hashtable for (int j = 0; j < 3; j++) { int iElement = rand.Next(6); hash.Remove(arrList[iElement]); Assert.False(hash.ContainsValue(null)); arrList.RemoveAt(iElement); int testInt = iCount++; var hashConfuse = new BadHashCode(testInt); arrList.Add(hashConfuse); hash.Add(hashConfuse, testInt); } } }
public void TestSynchronizedBasic() { Hashtable hsh1; string strValue; Task[] workers; Action ts1; int iNumberOfWorkers = 3; DictionaryEntry[] strValueArr; string[] strKeyArr; Hashtable hsh3; Hashtable hsh4; IDictionaryEnumerator idic; object oValue; //[]Vanila - Syncronized returns a wrapped HT. We must make sure that all the methods //are accounted for here for the wrapper hsh1 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { hsh1.Add("Key_" + i, "Value_" + i); } _hsh2 = Hashtable.Synchronized(hsh1); //Count Assert.Equal(_hsh2.Count, hsh1.Count); //get/set item for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(((string)_hsh2["Key_" + i]).Equals("Value_" + i)); } Assert.Throws<ArgumentNullException>(() => { oValue = _hsh2[null]; }); _hsh2.Clear(); for (int i = 0; i < _iNumberOfElements; i++) { _hsh2["Key_" + i] = "Value_" + i; } strValueArr = new DictionaryEntry[_hsh2.Count]; _hsh2.CopyTo(strValueArr, 0); //ContainsXXX hsh3 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(_hsh2.Contains("Key_" + i)); Assert.True(_hsh2.ContainsKey("Key_" + i)); Assert.True(_hsh2.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)); hsh3.Add(strValueArr[i], null); } hsh4 = (Hashtable)_hsh2.Clone(); Assert.Equal(hsh4.Count, hsh1.Count); strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); //ContainsXXX hsh3 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(hsh4.Contains("Key_" + i)); Assert.True(hsh4.ContainsKey("Key_" + i)); Assert.True(hsh4.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)); hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } Assert.False(hsh4.IsReadOnly); Assert.True(hsh4.IsSynchronized); //Phew, back to other methods idic = _hsh2.GetEnumerator(); hsh3 = new Hashtable(); hsh4 = new Hashtable(); while (idic.MoveNext()) { Assert.True(_hsh2.ContainsKey(idic.Key)); Assert.True(_hsh2.ContainsValue(idic.Value)); hsh3.Add(idic.Key, null); hsh4.Add(idic.Value, null); } hsh4 = (Hashtable)_hsh2.Clone(); strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(hsh4.Contains("Key_" + i)); Assert.True(hsh4.ContainsKey("Key_" + i)); Assert.True(hsh4.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)); hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } Assert.False(hsh4.IsReadOnly); Assert.True(hsh4.IsSynchronized); //Properties Assert.False(_hsh2.IsReadOnly); Assert.True(_hsh2.IsSynchronized); Assert.Equal(_hsh2.SyncRoot, hsh1.SyncRoot); //we will test the Keys & Values string[] strValueArr11 = new string[hsh1.Count]; strKeyArr = new string[hsh1.Count]; _hsh2.Keys.CopyTo(strKeyArr, 0); _hsh2.Values.CopyTo(strValueArr11, 0); hsh3 = new Hashtable(); hsh4 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(_hsh2.ContainsKey(strKeyArr[i])); Assert.True(_hsh2.ContainsValue(strValueArr11[i])); hsh3.Add(strKeyArr[i], null); hsh4.Add(strValueArr11[i], null); } //now we test the modifying methods _hsh2.Remove("Key_1"); Assert.False(_hsh2.ContainsKey("Key_1")); Assert.False(_hsh2.ContainsValue("Value_1")); _hsh2.Add("Key_1", "Value_1"); Assert.True(_hsh2.ContainsKey("Key_1")); Assert.True(_hsh2.ContainsValue("Value_1")); _hsh2["Key_1"] = "Value_Modified_1"; Assert.True(_hsh2.ContainsKey("Key_1")); Assert.False(_hsh2.ContainsValue("Value_1")); /////////////////////////// Assert.True(_hsh2.ContainsValue("Value_Modified_1")); hsh3 = Hashtable.Synchronized(_hsh2); //we are not going through all of the above again:) we will just make sure that this syncrnized and that //values are there Assert.Equal(hsh3.Count, hsh1.Count); Assert.True(hsh3.IsSynchronized); _hsh2.Clear(); Assert.Equal(_hsh2.Count, 0); //[] Synchronized returns a HT that is thread safe // We will try to test this by getting a number of threads to write some items // to a synchronized IList hsh1 = new Hashtable(); _hsh2 = Hashtable.Synchronized(hsh1); workers = new Task[iNumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { var name = "Thread worker " + i; ts1 = new Action(() => AddElements(name)); workers[i] = Task.Run(ts1); } Task.WaitAll(workers); //checking time Assert.Equal(_hsh2.Count, _iNumberOfElements * iNumberOfWorkers); for (int i = 0; i < iNumberOfWorkers; i++) { for (int j = 0; j < _iNumberOfElements; j++) { strValue = "Thread worker " + i + "_" + j; Assert.True(_hsh2.Contains(strValue)); } } //I dont think that we can make an assumption on the order of these items though //now we are going to remove all of these workers = new Task[iNumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { var name = "Thread worker " + i; ts1 = new Action(() => RemoveElements(name)); workers[i] = Task.Run(ts1); } Task.WaitAll(workers); Assert.Equal(_hsh2.Count, 0); Assert.False(hsh1.IsSynchronized); Assert.True(_hsh2.IsSynchronized); //[] Tyr calling Synchronized with null Assert.Throws<ArgumentNullException>(() => { Hashtable.Synchronized(null); } ); }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; Hashtable dic1; Int32 iNumberOfItems = 10; SerializationInfo ser1; Object[] serKeys; Object[] serValues; Hashtable hsh1; Hashtable hsh3; Hashtable hsh4; DictionaryEntry[] strValueArr; MemoryStream ms1; try { do { strLoc = "Loc_8345vdfv"; dic1 = new Hashtable(); for(int i=0; i<iNumberOfItems; i++) { dic1.Add(i, "String_" + i); } ser1 = new SerializationInfo(typeof(Hashtable), new FormatterConverter()); dic1.GetObjectData(ser1, new StreamingContext()); iCountTestcases++; if(ser1.GetSingle("LoadFactor") != 0.72f) { iCountErrors++; Console.WriteLine("Err_748cdg! Expected value not returned, " + ser1.GetSingle("LoadFactor")); } if(ser1.GetInt32("Version") != 11) { iCountErrors++; Console.WriteLine("Err_01823csdf! Expected value not returned, " + ser1.GetSingle("Version")); } if(ser1.GetSingle("HashSize") != 23) { iCountErrors++; Console.WriteLine("Err_7132fgfg! Expected value not returned, " + ser1.GetSingle("LoadFactor")); } serKeys = (Object[])ser1.GetValue("Keys", typeof(Object[])); serValues = (Object[])ser1.GetValue("Values", typeof(Object[])); Array.Sort(serKeys); Array.Sort(serValues); for(int i=0; i<iNumberOfItems; i++) { if((Int32)serKeys[i] != i) { iCountErrors++; Console.WriteLine("Err_1nd342_" + i + "! Expected value not returned, " + i); } if(!((String)serValues[i]).Equals("String_" + i)) { iCountErrors++; Console.WriteLine("Err_7539fdg_" + i + "! Expected value not returned, " + i); } } try { iCountTestcases++; dic1.GetObjectData(null, new StreamingContext()); iCountErrors++; Console.WriteLine("Err_7439dg! Exception not thrown"); } catch(ArgumentNullException) { } catch(Exception ex) { iCountErrors++; Console.WriteLine("Err_6572fdg! Unexpected exception thrown, " + ex); } iCountTestcases++; hsh1 = new Hashtable(); for(int i=0; i<10; i++) { hsh1.Add("Key_" + i, "Value_" + i); } BinaryFormatter formatter = new BinaryFormatter(); ms1 = new MemoryStream(); formatter.Serialize(ms1, hsh1); ms1.Position = 0; hsh4 = (Hashtable)formatter.Deserialize(ms1); if(hsh4.Count != hsh1.Count) { iCountErrors++; Console.WriteLine("Err_072xsf! Expected value not returned, " + hsh4.Count); } strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for(int i=0; i<10; i++) { if(!hsh4.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i)); } if(!hsh4.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i)); } if(!hsh4.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_0672esfs! Expected value not returned, " + hsh4.ContainsValue("Value_" + i)); } if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + ((DictionaryEntry)strValueArr[i]).Value); } } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public void TestCtorIntSingle() { // variables used for tests Hashtable hash = null; // [] should get ArgumentException if trying to have large num of entries Assert.Throws<ArgumentException>(() => { hash = new Hashtable(int.MaxValue, .1f); } ); // []should not get any exceptions for valid values - we also check that the HT works here hash = new Hashtable(100, .1f); int iNumberOfElements = 100; for (int i = 0; i < iNumberOfElements; i++) { hash.Add("Key_" + i, "Value_" + i); } //Count Assert.Equal(hash.Count, iNumberOfElements); DictionaryEntry[] strValueArr = new DictionaryEntry[hash.Count]; hash.CopyTo(strValueArr, 0); Hashtable hsh3 = new Hashtable(); for (int i = 0; i < iNumberOfElements; i++) { Assert.True(hash.Contains("Key_" + i), "Error, Expected value not returned, " + hash.Contains("Key_" + i)); Assert.True(hash.ContainsKey("Key_" + i), "Error, Expected value not returned, " + hash.ContainsKey("Key_" + i)); Assert.True(hash.ContainsValue("Value_" + i), "Error, Expected value not returned, " + hash.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hash.ContainsValue(((DictionaryEntry)strValueArr[i]).Value), "Error, Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } }
public void TestContainsValueBasic() { StringBuilder sblMsg = new StringBuilder(99); Hashtable ht1 = null; string s1 = null; string s2 = null; ht1 = new Hashtable(); //default constructor Assert.False(ht1.ContainsValue("No_Such_Val")); /// add few key-val pairs ht1 = new Hashtable(); for (int i = 0; i < 100; i++) { sblMsg = new StringBuilder(99); sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg = new StringBuilder(99); sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); ht1.Add(s1, s2); } for (int i = 0; i < ht1.Count; i++) { sblMsg = new StringBuilder(99); sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); Assert.True(ht1.ContainsValue(s2)); } // // Remove a key and then check // sblMsg = new StringBuilder(99); sblMsg.Append("key_50"); s1 = sblMsg.ToString(); ht1.Remove(s1); //removes "Key_50" sblMsg = new StringBuilder(99); sblMsg.Append("val_50"); s2 = sblMsg.ToString(); Assert.False(ht1.ContainsValue(s2)); // // Look for a null element after two element have been added with the same hashcode then one removed // sblMsg = new StringBuilder(99); sblMsg.Append("key_50"); s1 = sblMsg.ToString(); ht1 = new Hashtable(); int i1 = 0x10; int i2 = 0x100; long l1 = (((long)i1) << 32) + i2;// create two longs with same hashcode long l2 = (((long)i2) << 32) + i1; string str1 = "string 1"; object o1 = l1; object o2 = l2; ht1.Add(o1, str1); ht1.Add(o2, str1); // this will cause collision bit of the first entry to be set ht1.Remove(o1); // remove the first item, the hashtable should not // contain null value Assert.False(ht1.ContainsValue(0)); // // Look for a null element when the collection contains a null element // ht1 = new Hashtable(); for (int i = 0; i < 256; i++) { ht1.Add(i.ToString(), i); } ht1.Add(ht1.Count.ToString(), 0); Assert.True(ht1.ContainsValue(0)); }
public Boolean runTest() { Console.WriteLine( s_strTFPath +" "+ s_strTFName +" ,for "+ s_strClassMethod +" ,Source ver "+ s_strDtTmVer ); Hashtable hash = null; int iCountErrors = 0; int iCountTestcases = 0; try { ++iCountTestcases; hash = new Hashtable( null, 1 ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0001! hashtable should have thrown ArgumentNullException here" ); } catch( ArgumentNullException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1001! we expected ArgumentNullException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( new Hashtable(), Int32.MinValue ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0002! hashtable should have thrown ArgumentOutOfRangeException here" ); } catch( ArgumentOutOfRangeException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1002! we expected ArgumentOutOfRangeException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( new Hashtable(), Single.NaN ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0003! hashtable should have thrown ArgumentOutOfRangeException here" ); } catch( ArgumentOutOfRangeException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1003! we expected ArgumentOutOfRangeException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( new Hashtable(), 100.1f ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0004! hashtable should have thrown ArgumentOutOfRangeException here" ); } catch( ArgumentOutOfRangeException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1004! we expected ArgumentOutOfRangeException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( new Hashtable(), 1f ); } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1005! we expected no exception but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()), 1f), 1f), 1f), 1f ); } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1006! we expected no exception but got exception " + ex.ToString() ); } try { ++iCountTestcases; Hashtable tempHash = new Hashtable(); for ( long i = Int64.MinValue; i < Int64.MinValue + 100; i++ ) { tempHash.Add( i, i ); } hash = new Hashtable( tempHash, 1f ); for ( long i = Int64.MinValue; i < Int64.MinValue + 100; i++ ) { if ( ! hash.ContainsKey( i ) ) { Console.WriteLine( s_strTFAbbrev + " Error_007a! new Hashtable does not contain KEY " + i.ToString() ); } else if ( ! hash.ContainsValue( i ) ) { Console.WriteLine( s_strTFAbbrev + " Error_007b! new Hashtable does not contain VALUE " + i.ToString() ); } } ++iCountTestcases; tempHash.Clear(); for ( long i = Int64.MinValue; i < Int64.MinValue + 100; i++ ) { if ( ! hash.ContainsKey( i ) ) { Console.WriteLine( s_strTFAbbrev + " Error_007a! new Hashtable does not contain KEY " + i.ToString() ); } else if ( ! hash.ContainsValue( i ) ) { Console.WriteLine( s_strTFAbbrev + " Error_007b! new Hashtable does not contain VALUE " + i.ToString() ); } } } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1007! we expected no exception but got exception " + ex.ToString() ); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+ s_strTFPath +" "+ s_strTFName +" ,iCountTestcases="+ iCountTestcases.ToString() ); return true; } else { Console.WriteLine( "ACTIVE BUGS: " + s_strActiveBugNums ); Console.WriteLine( "FAiL! "+ s_strTFPath +" "+ s_strTFName +" ,iCountErrors="+ iCountErrors.ToString() +" ,BugNums?: "+ s_strActiveBugNums ); return false; } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; Hashtable arrSon; Hashtable arrMother; Thread[] workers; ThreadStart ts1; ThreadStart ts2; Int32 iNumberOfWorkers = 30; Boolean fLoopExit; Hashtable hshPossibleValues; IDictionaryEnumerator idic; Hashtable hsh1; Hashtable hsh2; Hashtable hsh3; try { do { hsh1 = new Hashtable(); hsh2 = new Hashtable(); iCountTestcases++; if(hsh1.SyncRoot == hsh2.SyncRoot) { iCountErrors++; Console.WriteLine("Err_47235fsd! Expected value not returned, "); } hsh1 = new Hashtable(); hsh2 = Hashtable.Synchronized(hsh1); hsh3 = (Hashtable)hsh2.Clone(); iCountTestcases++; if(hsh2.SyncRoot == hsh3.SyncRoot) { iCountErrors++; Console.WriteLine("Err_47235fsd! Expected value not returned, "); } if(hsh1.SyncRoot == hsh3.SyncRoot) { iCountErrors++; Console.WriteLine("Err_47235fsd! Expected value not returned, "); } strLoc = "Loc_8345vdfv"; arrMother = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { arrMother.Add("Key_" + i, "Value_" + i); } arrSon = Hashtable.Synchronized(arrMother); arrGrandDaughter = Hashtable.Synchronized(arrSon); arrDaughter = Hashtable.Synchronized(arrMother); iCountTestcases++; if(arrSon.SyncRoot != arrMother.SyncRoot) { iCountErrors++; Console.WriteLine("Err_234dnvf! Expected value not returned, " + (arrSon.SyncRoot==arrMother.SyncRoot)); } iCountTestcases++; if(arrSon.SyncRoot!=arrMother) { iCountErrors++; Console.WriteLine("Err_8230fvbd! Expected value not returned, " + (arrSon.SyncRoot==arrMother)); } iCountTestcases++; if(arrGrandDaughter.SyncRoot!=arrMother) { iCountErrors++; Console.WriteLine("Err_4927fd0fd! Expected value not returned, " + (arrGrandDaughter.SyncRoot==arrMother)); } iCountTestcases++; if(arrDaughter.SyncRoot!=arrMother) { iCountErrors++; Console.WriteLine("Err_85390gfg! Expected value not returned, " + (arrDaughter.SyncRoot==arrMother)); } iCountTestcases++; if(arrSon.SyncRoot != arrMother.SyncRoot) { iCountErrors++; Console.WriteLine("Err_234dnvf! Expected value not returned, " + (arrSon.SyncRoot==arrMother.SyncRoot)); } strLoc = "Loc_845230fgdg"; workers = new Thread[iNumberOfWorkers]; ts1 = new ThreadStart(AddMoreElements); ts2 = new ThreadStart(RemoveElements); for(int iThreads=0; iThreads<iNumberOfWorkers;iThreads+=2) { strLoc = "Loc_74329fd_" + iThreads; workers[iThreads] = new Thread(ts1); workers[iThreads].Name = "Thread_worker_" + iThreads; workers[iThreads+1] = new Thread(ts2); workers[iThreads+1].Name = "Thread_worker_" + iThreads + 1; workers[iThreads].Start(); workers[iThreads+1].Start(); } while(true) { fLoopExit=false; for(int i=0; i<iNumberOfWorkers;i++) { if(workers[i].IsAlive) fLoopExit=true; } if(!fLoopExit) break; } strLoc = "Loc_7539vfdg"; iCountTestcases++; hshPossibleValues = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { hshPossibleValues.Add("Key_" + i, "Value_" + i); } for(int i=0; i<iNumberOfWorkers; i++) { hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } if(arrMother.Count>0) Console.WriteLine("Loc_7428fdsg! Adds have it"); idic = arrMother.GetEnumerator(); while(idic.MoveNext()) { if(!hshPossibleValues.ContainsKey(idic.Key)) { iCountErrors++; Console.WriteLine("Err_7429dsf! Expected value not returned, " + idic.Key); } if(!hshPossibleValues.ContainsValue(idic.Value)) { iCountErrors++; Console.WriteLine("Err_2487dsf! Expected value not returned, " + idic.Value); } } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
protected void btnUpdateSeq_Click(object sender, EventArgs e) { Hashtable htList = new Hashtable(); for (int i = 0; i < gridViewCSList.Rows.Count; i++) { //首先判断是否是数据行 if (gridViewCSList.Rows[i].RowType == DataControlRowType.DataRow) { string FtID = gridViewCSList.Rows[i].Cells[0].Text.ToString(); TextBox tbBox = (TextBox)gridViewCSList.Rows[i].FindControl("txtSeqList"); if (!checkNum(tbBox.Text.Trim())) { messageContent.InnerHtml = GetLocalResourceObject("UpdateError1").ToString(); return; } htList.Add(FtID, tbBox.Text); } } Hashtable hNew = new Hashtable(); foreach (System.Collections.DictionaryEntry key in htList) { if (!hNew.ContainsValue(key.Value)) hNew.Add(key.Key, key.Value); } if (hNew.Values.Count != htList.Values.Count) { messageContent.InnerHtml = GetLocalResourceObject("UpdateError2").ToString(); return; } _hotelfacilitiesEntity.HotelFacilitiesDBEntity = new List<HotelFacilitiesDBEntity>(); _hotelfacilitiesEntity.LogMessages = new HotelVp.Common.Logger.LogMessage(); _commonEntity.LogMessages = new HotelVp.Common.Logger.LogMessage(); _hotelfacilitiesEntity.LogMessages.Userid = UserSession.Current.UserAccount; _hotelfacilitiesEntity.LogMessages.Username = UserSession.Current.UserDspName; _hotelfacilitiesEntity.LogMessages.IpAddress = UserSession.Current.UserIP; _hotelfacilitiesEntity.HotelFacilitiesDBEntity = new List<HotelFacilitiesDBEntity>(); HotelFacilitiesDBEntity hotelFacilitiesDBEntity = new HotelFacilitiesDBEntity(); hotelFacilitiesDBEntity.FTSeqList = htList; _hotelfacilitiesEntity.HotelFacilitiesDBEntity.Add(hotelFacilitiesDBEntity); int iResult = HotelFacilitiesBP.FtTypeSeqListUpdate(_hotelfacilitiesEntity); _commonEntity.LogMessages = _hotelfacilitiesEntity.LogMessages; _commonEntity.CommonDBEntity = new List<CommonDBEntity>(); CommonDBEntity commonDBEntity = new CommonDBEntity(); commonDBEntity.Event_Type = "服务设施类别管理-排序修改"; commonDBEntity.Event_ID = ""; string conTent = ""; conTent = GetLocalResourceObject("EventUpdateMessageSeq").ToString(); //conTent = string.Format(conTent, txtFtCode.Value, txtFtName.Value, lbFtSeq.Text, ddpStatusList.SelectedValue); commonDBEntity.Event_Type = ""; commonDBEntity.Event_ID = ""; commonDBEntity.Event_Content = conTent; if (iResult == 1) { messageContent.InnerHtml = GetLocalResourceObject("UpdateSuccessSeq").ToString(); commonDBEntity.Event_Result = GetLocalResourceObject("UpdateSuccessSeq").ToString(); BindFtListGrid(); } else { messageContent.InnerHtml = GetLocalResourceObject("UpdateError").ToString(); commonDBEntity.Event_Result = GetLocalResourceObject("UpdateError").ToString(); } foreach (System.Collections.DictionaryEntry key in htList) { conTent = string.Format(conTent, key.Key, key.Value); _commonEntity.CommonDBEntity.Add(commonDBEntity); CommonBP.InsertEventHistory(_commonEntity); } }
public Boolean runTest ( int p_inLoops0 ,int p_inLoops1 ) { Console.Error.WriteLine( "Co4310Add_Stress runTest(stress/perf) started." ); String strLoc="Loc_000oo"; StringBuilder sblMsg = new StringBuilder( 99 ); int iCountErrors = 0; int iCountTestcases = 0; Hashtable ht2 = null; Hashtable ht = null; StringBuilder sbl3 = new StringBuilder( 99 ); StringBuilder sbl4 = new StringBuilder( 99 ); StringBuilder sbl5 = new StringBuilder( 99 ); StringBuilder sblWork1 = new StringBuilder( 99 ); StringBuilder k1 = new StringBuilder(99); StringBuilder k2 = new StringBuilder(99); StringBuilder v1 = new StringBuilder(99); StringBuilder v2 = new StringBuilder(99); String str5 = null; String str6 = null; String str7 = null; int[] in4a = new int[9]; int[] in4TickCount = new int[9]; int inTCIdx = 0; try { do { in4TickCount[inTCIdx++] = Environment.TickCount; if ( p_inLoops0 < 2 ) p_inLoops0 = 2; if ( p_inLoops1 < 2 ) p_inLoops1 = 2; Console.Error.WriteLine( "Info Inf_201pa. parms are: " + p_inLoops0 + " ," + p_inLoops1 ); strLoc="10cc"; iCountTestcases++; k1 = new StringBuilder("key_0"); k2 = new StringBuilder("key_1"); v1 = new StringBuilder("val_0"); v2 = new StringBuilder("val_1"); ht = new Hashtable(); ht.Add (k1, v1); ht.Add (k2, v2); strLoc="20cc"; iCountTestcases++; if (!ht.ContainsKey (k2)) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_287! " ); } strLoc="30cc"; iCountTestcases++; if (!ht.ContainsValue (v2)) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_348! " ); } strLoc="40cc"; iCountTestcases++; try { ICollection allkeys = ht.Keys; if (allkeys.Count != ht.Count) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_892! " ); } IEnumerator allkeysEnum = allkeys.GetEnumerator(); while ( allkeysEnum.MoveNext() ) { String strTemp = allkeysEnum.Current.ToString(); } } catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_2yi! exc==" + exc ); } strLoc="50cc"; iCountTestcases++; try { ICollection allvalues = ht.Values; if (allvalues.Count != ht.Count) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_892! " ); } IEnumerator allvaluesEnum = allvalues.GetEnumerator(); while( allvaluesEnum.MoveNext() ) { String strTemp = (String) allvaluesEnum.Current.ToString(); } } catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_1io! exc==" + exc ); } strLoc="100cc"; ht2 = new Hashtable(); strLoc="101cc"; str5 = "key_150"; str6 = "value_150"; ht2.Add( str5 ,str6 ); in4a[0] = ht2.Count; ++iCountTestcases; if ( in4a[0] != 1 ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_144cg! in4a[0]==" + in4a[0] ); } str7 = (String)ht2[ str5 ]; ++iCountTestcases; if ( str7.Equals( str6 ) == false ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_184pr! str7==" + str7 ); } strLoc="102cc"; str5 = "key_130"; str6 = "value_130"; ht2.Add( str5 ,str6 ); in4a[2] = ht2.Count; ++iCountTestcases; if ( in4a[2] != 2 ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_105bo! in4a[2]==" + in4a[2] ); } str7 = (String)ht2[ "key_150" ]; ++iCountTestcases; if ( (str7 == null) || (str7.Equals( "value_150" ) == false ) ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_155tf! str7==" + str7 ); } str7 = (String)ht2[ str5 ]; ++iCountTestcases; if ( (str7 == null) || (str7.Equals( str6 ) == false ) ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_166tf! str7==" + str7 ); } strLoc="107ex"; try { ht2.Add( str5 , str6 + "_b" ); ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_366uf! ht2.GetSize()==" + ht2.Count ); } catch ( ArgumentException ) {} catch ( Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_466kf! exc==" + exc ); } strLoc="108ex"; str5 = null; str6 = "value_null"; try { ht2.Add( str5 ,str6 ); ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_726uw! ht2.GetSize()==" + ht2.Count ); } catch ( ArgumentNullException ) {} catch ( Exception exc ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_725yf! exc==" + exc ); } strLoc="139ou"; ht2 = new Hashtable(); sbl3.Length = 0 ; sbl3.Append( "key_f3" ); sbl4.Length = 0 ; sbl4.Append( "value_f3" ); ht2.Add( sbl3 ,sbl4 ); sbl4.Length = 0 ; sbl4.Append( "value_f4" ); sblWork1 = (StringBuilder)ht2[ sbl3 ]; ++iCountTestcases; if ( sblWork1.ToString().Equals( sbl4.ToString() ) == false ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_498so! sblWork1=="+ sblWork1 ); } strLoc="141pi"; ht2 = new Hashtable(); sbl3.Length = 0 ; sbl3.Append( "key_m5" ); sbl4.Length = 0 ; sbl4.Append( "value_m5" ); ht2.Add( sbl3 ,sbl4 ); sbl5 = new StringBuilder( "key_p7" ); sbl4.Length = 0 ; sbl4.Append( "value_p7" ); ht2.Add( sbl5 ,sbl4 ); try { strLoc="142ir"; sbl5.Length = 0 ; ++iCountTestcases; if ( ht2.Count != 2 ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_798kz! ht2.GetSize()=="+ ht2.Count ); } strLoc="142bs"; ++iCountTestcases; sbl5.Append( "key_m5" ); try { sblWork1 = (StringBuilder) ht2[sbl5]; strLoc="142bs.2"; Boolean bol2 = ht2.ContainsKey (sbl5); } catch (Exception exc) { Console.Error.WriteLine( "Find: Err_rh20! Exception caught exc==" + exc ); } strLoc="142qk"; strLoc="142cl"; ht2.Clear(); } catch ( Exception exc ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_180yl! ?!?! what exc is expected?? exc==" + exc ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_180yl) strLoc=="+ strLoc +" ,sbl3=="+ sbl3 ); } strLoc="200dd"; in4TickCount[inTCIdx++] = Environment.TickCount; ht2 = new Hashtable(); ++iCountTestcases; for ( int aa = 0 ;aa < p_inLoops0 ;aa++ ) { strLoc="202dd"; for ( int bb = 0 ;bb < p_inLoops1 ;bb++ ) { ht2.Add( "KEY: aa==" + aa + " ,bb==" + bb ,"VALUE: aa==" + aa + " ,bb==" + bb ); } strLoc="206dd"; ht.Clear(); } in4TickCount[inTCIdx++] = Environment.TickCount; } while ( false ); } catch( Exception exc_general ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_343un! (Co4310Add_Stress) exc_general==" + exc_general ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_343un) strLoc==" + strLoc ); } Console.Error.WriteLine( "Info Inf_483xb. Total Duration in Tick Counts==" + (in4TickCount[inTCIdx-1] - in4TickCount[0]) ); if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. Hashtable\\Co4310Add_Stress.cs iCountTestcases==" + iCountTestcases ); return true; } else { Console.Error.WriteLine( "FAiL! Hashtable\\Co4310Add_Stress.cs iCountErrors==" + iCountErrors ); return false; } }
public void TestGetSyncRootBasic() { Hashtable arrSon; Hashtable arrMother; Task[] workers; Action ts1; Action ts2; Int32 iNumberOfWorkers = 30; Hashtable hshPossibleValues; IDictionaryEnumerator idic; Hashtable hsh1; Hashtable hsh2; Hashtable hsh3; //[] we will create different HT and make sure that they return different SyncRoot values hsh1 = new Hashtable(); hsh2 = new Hashtable(); Assert.NotEqual(hsh1.SyncRoot, hsh2.SyncRoot); Assert.Equal(hsh1.SyncRoot.GetType(), typeof(object)); //[] a clone of a Syncronized HT should not be pointing to the same SyncRoot hsh1 = new Hashtable(); hsh2 = Hashtable.Synchronized(hsh1); hsh3 = (Hashtable)hsh2.Clone(); Assert.NotEqual(hsh2.SyncRoot, hsh3.SyncRoot); Assert.NotEqual(hsh1.SyncRoot, hsh3.SyncRoot); //[] testing SyncRoot is not as simple as its implementation looks like. This is the working //scenrio we have in mind. //1) Create your Down to earth mother Hashtable //2) Get a synchronized wrapper from it //3) Get a Synchronized wrapper from 2) //4) Get a synchronized wrapper of the mother from 1) //5) all of these should SyncRoot to the mother earth arrMother = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { arrMother.Add("Key_" + i, "Value_" + i); } arrSon = Hashtable.Synchronized(arrMother); _arrGrandDaughter = Hashtable.Synchronized(arrSon); _arrDaughter = Hashtable.Synchronized(arrMother); Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot); Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot); Assert.Equal(_arrGrandDaughter.SyncRoot, arrMother.SyncRoot); Assert.Equal(_arrDaughter.SyncRoot, arrMother.SyncRoot); Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot); //we are going to rumble with the Hashtables with some threads workers = new Task[iNumberOfWorkers]; ts2 = new Action(RemoveElements); for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2) { var name = "Thread_worker_" + iThreads; ts1 = new Action(() => AddMoreElements(name)); workers[iThreads] = Task.Run(ts1); workers[iThreads + 1] = Task.Run(ts2); } Task.WaitAll(workers); //checking time //Now lets see how this is done. //Either there should be some elements (the new ones we added and/or the original ones) or none hshPossibleValues = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { hshPossibleValues.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < iNumberOfWorkers; i++) { hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } idic = arrMother.GetEnumerator(); while (idic.MoveNext()) { Assert.True(hshPossibleValues.ContainsKey(idic.Key), "Error, Expected value not returned, " + idic.Key); Assert.True(hshPossibleValues.ContainsValue(idic.Value), "Error, Expected value not returned, " + idic.Value); } }
public void TestGetEnumeratorBasic() { Hashtable hash1; IDictionaryEnumerator dicEnum1; int ii; string str1; string strRetKey; int iExpValue; Queue que1; Queue que2; //[] 1) Empty Hash table //Get enumerator for an empty table hash1 = new Hashtable(); dicEnum1 = hash1.GetEnumerator(); Assert.Equal(dicEnum1.MoveNext(), false); //[] 2) Full hash table hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); ii = 0; //Enumerator (well, Hashtable really) does not hold values in the order we put them in!! //so we will use 2 ques to confirm that all the keys and values we put inside the hashtable was there que1 = new Queue(); que2 = new Queue(); while (dicEnum1.MoveNext() != false) { strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); //we make sure that the values are there Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); //we will make sure that enumerator get all the objects que1.Enqueue(strRetKey); que2.Enqueue(iExpValue); } //making sure the que size is right Assert.Equal(100, que1.Count); Assert.Equal(100, que2.Count); // 3) Full hash table, allow remove true hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); //Enumerator (well, Hashtable really) does not hold values in the order we put them in!! //so we will use 2 ques to confirm that all the keys and values we put inside the hashtable was there que1 = new Queue(); que2 = new Queue(); while (dicEnum1.MoveNext() != false) { strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); //we make sure that the values are there Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); //we will make sure that enumerator get all the objects que1.Enqueue(strRetKey); que2.Enqueue(iExpValue); } //making sure the que size is right Assert.Equal(100, que1.Count); Assert.Equal(100, que2.Count); //[] 3) change hash table externally whilst in the middle of enumerating hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); //this is the first object. we have a true Assert.True(dicEnum1.MoveNext()); strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); //we make sure that the values are there Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); // we will change the underlying hashtable ii = 87; str1 = string.Concat("key_", ii.ToString()); hash1[str1] = ii; // MoveNext should throw Assert.Throws<InvalidOperationException>(() => { dicEnum1.MoveNext(); } ); // Value should NOT throw object foo = dicEnum1.Value; object foo1 = dicEnum1.Key; // Current should NOT throw object foo2 = dicEnum1.Current; Assert.Throws<InvalidOperationException>(() => { dicEnum1.Reset(); } ); //[] 5) try getting object // a) before moving // b) twice before moving to next // c) after next returns false hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); // a) before moving Assert.Throws<InvalidOperationException>(() => { strRetKey = (string)dicEnum1.Key; } ); //Entry dicEnum1 = (IDictionaryEnumerator *)hash1.GetEnumerator(); dicEnum1 = hash1.GetEnumerator(); while (dicEnum1.MoveNext() != false) { ;//dicEntr1 = (dicEnum1.Entry); } Assert.Throws<InvalidOperationException>(() => { strRetKey = (string)dicEnum1.Key; } ); //[]We will get a valid enumerator, move to a valid position, then change the underlying HT. Current shouold not throw. //Only calling MoveNext should throw. //create the HT hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } //get the enumerator and move to a valid location dicEnum1 = hash1.GetEnumerator(); dicEnum1.MoveNext(); dicEnum1.MoveNext(); ii = 87; str1 = string.Concat("key_", ii.ToString()); //if we are currently pointer at the item that we are going to change then move to the next one if (0 == string.Compare((string)dicEnum1.Key, str1)) { dicEnum1.MoveNext(); } //change the underlying HT hash1[str1] = ii + 50; //calling current on the Enumerator should not throw strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); strRetKey = (string)dicEnum1.Entry.Key; iExpValue = Convert.ToInt32(dicEnum1.Entry.Value); Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); strRetKey = (string)(((DictionaryEntry)(dicEnum1.Current)).Key); iExpValue = Convert.ToInt32(((DictionaryEntry)dicEnum1.Current).Value); Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); // calling MoveNExt should throw Assert.Throws<InvalidOperationException>(() => { dicEnum1.MoveNext(); } ); //[] Try calling clone on the enumerator dicEnum1 = hash1.GetEnumerator(); var anotherEnumerator = hash1.GetEnumerator(); Assert.False(object.ReferenceEquals(dicEnum1, anotherEnumerator)); }
public void TestGetValues() { StringBuilder sblMsg = new StringBuilder(99); Hashtable ht1 = null; string s1 = null; string s2 = null; string s3 = null; object[] objArrKeys; object[] objArrValues; ICollection icol1; IEnumerator ienm1; int i = 0; int iCount = 0; ht1 = new Hashtable(); for (i = 0; i < 100; i++) { sblMsg = new StringBuilder(99); sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg = new StringBuilder(99); sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); ht1.Add(s1, s2); } // // test Get to make sure the key-vals are accessible // for (i = 0; i < ht1.Count; i++) { sblMsg = new StringBuilder(99); sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg = new StringBuilder(99); sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); s3 = (string)ht1[s1]; Assert.Equal(s3 , s2); } // // [] now GetValues and make sure every value is obtained // NOTE: the keys/values obtained may not necessarily be in any order // int temp = ht1.Count; objArrValues = new object[temp]; ht1.Values.CopyTo(objArrValues, 0); Assert.Equal(objArrValues.Length, ht1.Count); for (i = 0; i < objArrValues.Length; i++) { Assert.True(ht1.ContainsValue(objArrValues[i].ToString())); } //[] Returns a collection representing the keys of this hashtable. The order in which the returned collection represents the keys is unspecified, but it is guaranteed to be the same order in which a collection returned by GetValues represents the values of the hashtable. int temp1 = ht1.Count; objArrKeys = new object[temp1]; ht1.Keys.CopyTo(objArrKeys, 0); Assert.Equal(objArrKeys.Length, ht1.Count); for (i = 0; i < objArrKeys.Length; i++) { Assert.True(ht1.ContainsKey(objArrKeys[i].ToString())); // check the order of GetKeys and GetValues Assert.True(((string)ht1[objArrKeys[i].ToString()]).Equals(objArrValues[i].ToString())); } //[]We test other methods in the Collection to make sure that they work!! icol1 = ht1.Values; ienm1 = icol1.GetEnumerator(); iCount = 0; while (ienm1.MoveNext()) { iCount++; Assert.True(ht1.ContainsValue(ienm1.Current)); } Assert.Equal(iCount, ht1.Count); Assert.Equal(icol1.Count, ht1.Count); Assert.False(icol1.IsSynchronized); Assert.Equal(icol1.SyncRoot, ht1.SyncRoot); //[] The ICollection is alive - i.e. whatever changes we do to the Underlying HT is reflected in the collection sblMsg = new StringBuilder(); sblMsg.Append("key_"); sblMsg.Append(0); s1 = "key_0"; s2 = "val_0"; ht1.Remove(s1); ienm1 = icol1.GetEnumerator(); iCount = 0; while (ienm1.MoveNext()) { s3 = (string)ienm1.Current; Assert.False(s3.Equals(s2)); } Assert.Equal(icol1.Count, ht1.Count); //[] we will clear the HT and make sure that the Values are kaput ht1.Clear(); Assert.Equal(0, icol1.Count); iCount = 0; ienm1 = icol1.GetEnumerator(); while (ienm1.MoveNext()) { iCount++; } Assert.Equal(0, iCount); }
public Boolean runTest() { Console.WriteLine( s_strTFPath +" "+ s_strTFName +" ,for "+ s_strClassMethod +" ,Source ver "+ s_strDtTmVer ); String strLoc = "Loc_000oo"; Hashtable hash = null; int iCountErrors = 0; int iCountTestcases = 0; strLoc = "Loc_001oo"; try { ++iCountTestcases; hash = new Hashtable( Int32.MaxValue, .1f, null, null ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0001! hashtable should have thrown ArgumentException here" ); } catch( ArgumentException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1001! we expected ArgumentException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( 100, .1f, null, null ); } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1002! we expected no exception but got exception " + ex.ToString() ); } Int32 iNumberOfElements = 100; for(int i=0; i<iNumberOfElements; i++) { hash.Add("Key_" + i, "Value_" + i); } iCountTestcases++; if(hash.Count != iNumberOfElements) { iCountErrors++; Console.WriteLine("Err_742dsf! Expected value not returned, " + hash.Count); } DictionaryEntry[] strValueArr = new DictionaryEntry[hash.Count]; hash.CopyTo(strValueArr, 0); Hashtable hsh3 = new Hashtable(); for(int i=0; i<iNumberOfElements; i++) { if(!hash.Contains("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742ds8f! Expected value not returned, " + hash.Contains("Key_" + i)); } if(!hash.ContainsKey("Key_" + i)) { iCountErrors++; Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hash.ContainsKey("Key_" + i)); } if(!hash.ContainsValue("Value_" + i)) { iCountErrors++; Console.WriteLine("Err_563fgd! Expected value not returned, " + hash.ContainsValue("Value_" + i)); } if(!hash.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) { iCountErrors++; Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value); } try { hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } catch(Exception) { iCountErrors++; Console.WriteLine("Err_74298dsd! Exception thrown for " + ((DictionaryEntry)strValueArr[i]).Value); } } try { ++iCountTestcases; hash = new Hashtable( 5, .01f, null, null ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0003! hashtable should have thrown ArgumentOutOfRangeException here" ); } catch( ArgumentOutOfRangeException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1003! we expected ArgumentOutOfRangeException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( 5, 100.1f, null, null ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0004! hashtable should have thrown ArgumentOutOfRangeException here" ); } catch( ArgumentOutOfRangeException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1004! we expected ArgumentOutOfRangeException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( Int32.MaxValue, 100.1f, null, null ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0004! hashtable should have thrown ArgumentOutOfRangeException here" ); } catch( ArgumentOutOfRangeException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1004! we expected ArgumentOutOfRangeException but got exception " + ex.ToString() ); } try { ++iCountTestcases; hash = new Hashtable( Int32.MinValue, 10.1f, null, null ); ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_0005! hashtable should have thrown ArgumentOutOfRangeException here" ); } catch( ArgumentOutOfRangeException ) { } catch( Exception ex ) { ++iCountErrors; Console.WriteLine( s_strTFAbbrev +" Error_1005! we expected ArgumentOutOfRangeException but got exception strLoc= " + strLoc + ex.ToString() ); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+ s_strTFPath +" "+ s_strTFName +" ,iCountTestcases="+ iCountTestcases.ToString() ); return true; } else { Console.WriteLine( "ACTIVE BUGS: " + s_strActiveBugNums ); Console.WriteLine( "FAiL! "+ s_strTFPath +" "+ s_strTFName +" ,iCountErrors="+ iCountErrors.ToString() +" ,BugNums?: "+ s_strActiveBugNums ); return false; } }