public static void SetParameterValues(MySqlCommand command, ListDictionary parameterValues) { try { if (command == null || parameterValues == null) { return; } foreach (MySqlParameter sqlParameter in (DbParameterCollection)command.Parameters) { if (parameterValues.Contains((object)sqlParameter.ParameterName)) { sqlParameter.Value = parameterValues[(object)sqlParameter.ParameterName]; sqlParameter.SourceColumn = (string)null; } else if (parameterValues.Contains((object)sqlParameter.ParameterName.Substring(1))) { sqlParameter.Value = parameterValues[(object)sqlParameter.ParameterName.Substring(1)]; sqlParameter.SourceColumn = (string)null; } } } catch { throw; } }
public object ResolveSingletonOrType(Type type) { if (_singletons?.Contains(type) ?? false) { return(_singletons[type]); } object instance; try { var ctor = type .GetConstructor( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(IContext) }, null); instance = ctor == null ? Activator.CreateInstance(type) : ctor.Invoke(new object[] { this }); } catch (Exception exception) { if (type != typeof(ILoggerFactory)) { (_logger ?? (_logger = Resolve <ILoggerFactory>()?.GetFor(_selfType)))?.Log(_selfType, Level.Warn, $"can't build type of: {type.NameNice()}", exception); } return(null); } return(instance); }
object IResourceProvider.GetObject(string resourceKey, CultureInfo culture) { // Retrieve the currently active culture string cultureName = null; if (culture == null) { CultureInfo currentUICulture = CultureInfo.CurrentUICulture; if (currentUICulture != null) { cultureName = currentUICulture.Name; } } else { cultureName = culture.Name; } // Now get the dictionary for the retrieved culture ListDictionary dict = GetResources(cultureName); // If dictionary does not exist, fall back to // the dictionary for the neutral culture if (dict.Contains(resourceKey)) return dict[resourceKey]; else { dict = GetResources(null); if (dict.Contains(resourceKey)) return dict[resourceKey]; } // No dictionary found at all return null; }
/// <summary> /// 根据多语名称获取多语值 /// </summary> /// <param name="name"></param> /// <returns></returns> public string GetString(string name) { try { // 检查资源是否存在,如果不存在则加载资源 string culture = System.Threading.Thread.CurrentThread.CurrentUICulture.Name; if (!resourcesByCulture.Contains(culture)) { string path = Path.Combine(baseDir, string.Format(ResourceName, culture)); LoadResource(path, culture); } // 获取资源集合 var resources = resourcesByCulture[culture] as OrderedDictionary; if (resources != null) { if (resources.Contains(name)) { return(resources[name].ToString().Trim()); } } return(null); } catch (Exception e) { Log.Debug(e); } return(name); }
private void BasicTests(ListDictionary ld) { Assert.AreEqual(0, ld.Count, "Count"); Assert.IsFalse(ld.IsFixedSize, "IsFixedSize"); Assert.IsFalse(ld.IsReadOnly, "IsReadOnly"); Assert.IsFalse(ld.IsSynchronized, "IsSynchronized"); Assert.AreEqual(0, ld.Keys.Count, "Keys"); Assert.AreEqual(0, ld.Values.Count, "Values"); Assert.IsNotNull(ld.SyncRoot, "SyncRoot"); Assert.IsNotNull(ld.GetEnumerator(), "GetEnumerator"); Assert.IsNotNull((ld as IEnumerable).GetEnumerator(), "IEnumerable.GetEnumerator"); ld.Add("a", "1"); Assert.AreEqual(1, ld.Count, "Count-1"); Assert.IsTrue(ld.Contains("a"), "Contains(a)"); Assert.IsFalse(ld.Contains("1"), "Contains(1)"); ld.Add("b", null); Assert.AreEqual(2, ld.Count, "Count-2"); Assert.IsNull(ld["b"], "this[b]"); DictionaryEntry[] entries = new DictionaryEntry[2]; ld.CopyTo(entries, 0); ld["b"] = "2"; Assert.AreEqual("2", ld["b"], "this[b]2"); ld.Remove("b"); Assert.AreEqual(1, ld.Count, "Count-3"); ld.Clear(); Assert.AreEqual(0, ld.Count, "Count-4"); }
public double this [string from, string to] // Indexer declaration { get { string f = from.Trim().ToUpper(); string t = to.Trim().ToUpper(); if (f.Equals(t)) { return(1.0); } else if (map.Contains(f) && map.Contains(t)) { return(convert[(int)map[f], (int)map[t]]); } else { throw new Exception("Can't convert from " + f + " to " + t + ". Unit unknown"); } } set { string f = from.Trim().ToUpper(); string t = to.Trim().ToUpper(); if (map.Contains(f) && map.Contains(t)) { convert[(int)map[f], (int)map[t]] = value; } else { throw new Exception("Can't convert from " + f + " to " + t + ". Unit unknown"); } } }
public static void AddTest(bool addViaSet) { ListDictionary added = new ListDictionary(); IList keys = new ArrayList(); IList values = new ArrayList(); for (int i = 0; i < s_dictionaryData.Length; i++) { string key = s_dictionaryData[i].Key; string value = s_dictionaryData[i].Value; Assert.Equal(i, added.Count); Assert.Null(added[key]); Assert.False(added.Contains(key)); added.Add(addViaSet, key, value); keys.Add(key); values.Add(value); Assert.Equal(value, added[key]); Assert.True(added.Contains(key)); Assert.Equal(i + 1, added.Count); CollectionAsserts.Equal(keys, added.Keys); CollectionAsserts.Equal(values, added.Values); AssertExtensions.Throws <ArgumentException>(null, () => added.Add(key, value)); added[key] = value; } }
public static void GetParameterValues(MySqlCommand command, ListDictionary parameterValues) { try { if (command == null || parameterValues == null) { return; } foreach (MySqlParameter sqlParameter in (DbParameterCollection)command.Parameters) { if (sqlParameter.Direction == ParameterDirection.ReturnValue) { parameterValues[(object)sqlParameter.ParameterName] = sqlParameter.Value; } else if (parameterValues.Contains((object)sqlParameter.ParameterName)) { if (sqlParameter.Direction == ParameterDirection.InputOutput || sqlParameter.Direction == ParameterDirection.Output) { parameterValues[(object)sqlParameter.ParameterName] = sqlParameter.Value; } } else if (parameterValues.Contains((object)sqlParameter.ParameterName.Substring(1)) && (sqlParameter.Direction == ParameterDirection.InputOutput || sqlParameter.Direction == ParameterDirection.Output)) { parameterValues[(object)sqlParameter.ParameterName.Substring(1)] = sqlParameter.Value; } } } catch { throw; } }
public void PutToCache <TController>(TController controller) where TController : MonoBehaviourCache { // try put if (ReferenceEquals(null, controller)) { return; } var key = typeof(TController); Stack <GameObject> stack; if (_cache.Contains(key)) { stack = _cache[key] as Stack <GameObject>; } else { _cache.Add(key, stack = new Stack <GameObject>()); } // remove from actives var collection = _actives.Contains(key) ? _actives[key] as List <TController> : null; collection?.RemoveAll(_ => ReferenceEquals(_, controller)); // suspned & return controller.Suspend(); stack.Push(controller.gameObject); }
public ContextLifetimeManager() { if (allInstances.Contains(ItemsProvider) == false) { allInstances.Add(ItemsProvider, new List <ContextLifetimeManager>()); } (allInstances[ItemsProvider] as List <ContextLifetimeManager>).Add(this); }
public static void RemoveTest(ListDictionary ld, KeyValuePair <string, string>[] data) { Assert.All(data, element => { Assert.True(ld.Contains(element.Key)); ld.Remove(element.Key); Assert.False(ld.Contains(element.Key)); }); Assert.Equal(0, ld.Count); }
public void UsingInsensitiveComparerForListDictionary() { ListDictionary dictionary = new ListDictionary(new CaseInsensitiveComparer(CultureInfo.InvariantCulture)); //ordinarily this would result in two key/value pairs being added dictionary["Hello"] = "World"; dictionary["hello"] = "Arse"; Assert.That(dictionary.Count, Is.EqualTo(1)); //there is only one key/value pair stored Assert.That(dictionary.Contains("hello"), Is.True); Assert.That(dictionary.Contains("Hello"), Is.True); }
public static void Add_MultipleTypesTest(bool addViaSet) { ListDictionary added = new ListDictionary(); added.Add(addViaSet, "key", "value"); added.Add(addViaSet, "key".GetHashCode(), "hashcode".GetHashCode()); Assert.True(added.Contains("key")); Assert.True(added.Contains("key".GetHashCode())); Assert.Equal("value", added["key"]); Assert.Equal("hashcode".GetHashCode(), added["key".GetHashCode()]); }
// Oh why make properties not easily able to deal with data structures in a safe way. No way am I returning the whole // hashtable to the caller to screw up. public String GetAttributeValue(String attrName) { // avoid null reference exception with ToString() if (_attrList.Contains(attrName)) { return(_attrList[attrName].ToString()); } else { return(null); } }
public static void Remove_CustomComparerTest() { ObservableStringComparer comparer = new ObservableStringComparer(); ListDictionary ld = Fill(new ListDictionary(comparer), s_dictionaryData); Assert.All(s_dictionaryData.Reverse(), element => { int originalSize = ld.Count; Assert.True(ld.Contains(element.Key)); // Removing items in reverse order, so iterates over everything. comparer.AssertCompared(originalSize, () => ld.Remove(element.Key)); Assert.False(ld.Contains(element.Key)); }); Assert.Equal(0, ld.Count); }
/// <summary> /// Registers the client script block. /// </summary> /// <param name="page">The page.</param> /// <param name="key">The key.</param> /// <param name="script">The script.</param> internal static void RegisterClientScriptBlock(System.Web.UI.Page page, string key, string script) { Guid pageID = Guid.Empty; if (!System.Web.HttpContext.Current.Items.Contains(Constant.AjaxID + ".pageID")) { pageID = Guid.NewGuid(); System.Web.HttpContext.Current.Items.Add(Constant.AjaxID + ".pageID", pageID); } else { pageID = (Guid)System.Web.HttpContext.Current.Items[Constant.AjaxID + ".pageID"]; } page.PreRender += new EventHandler(page_PreRender); ListDictionary scripts = GetScripts(); if (scripts.Contains(key)) { return; } scripts.Add(key, script); }
/// <summary> /// 移除扩展点 /// </summary> /// <param name="item"></param> public void RemoveExtensionPoint(IExtensionPoint item) { lock (lockObj) { if (item == null) { return; } string key = item.Point.ToLower(); if (extensionPointsByName.Contains(key)) { // 从根据名称存贮扩展点集合中移除 extensionPointsByName.Remove(key); // 从以插件名存贮的扩展点集合中移除 IBundle bundle = item.Owner; key = bundle.ToString(); ListDictionary eps = extensionPointsByBundle[key] as ListDictionary; if (!eps.Contains(item.Point)) { return; } eps.Remove(item.Point); // 从扩展点列表中移除 extensionPoints.Remove(item); // 检索扩展点所有的扩展 foreach (IExtension extension in item.Extensions) { // 从扩展列表中删除 extensions.Remove(extension); } } } }
/// <summary> /// 添加扩展点 /// </summary> /// <param name="point"></param> public void AddExtensionPoint(IExtensionPoint item) { lock (lockObj) { if (item == null) { return; } string key = item.Point.ToLower(); if (extensionPointsByName.Contains(key)) { IBundle bundle = item.Owner; key = bundle.ToString(); extensionPointsByName.Add(key, item); if (extensionPointsByBundle.Contains(key)) { ListDictionary eps = extensionPointsByBundle[key] as ListDictionary; if (eps.Contains(item.Point.ToLower())) { return; } eps.Add(item.Point, item); extensionPoints.Add(item); } else { ListDictionary eps = new ListDictionary(); eps.Add(item.Point, item); extensionPoints.Add(item); extensionPointsByBundle.Add(key, eps); } } } }
public static void SetupField(C1FlexReport report, TextField f, string createInfo) { // get expression if (createInfo != null && _fieldList.Contains(createInfo)) { string expression = _fieldList[createInfo] as string; // System.Diagnostics.Debug.Assert(expression != null); // if the field expression starts with an equals sign, evaluate // the expression at creation time and store the value if (expression.StartsWith("=")) { f.Text = report.Evaluate(expression.Substring(1)).ToString(); } else // otherwise, evaluate at render time { f.Text = "=" + expression; } } else { // arbitrary formula: f.Text = ("=" + createInfo) ?? "data"; } }
public virtual T Get <T>(bool force = false) where T : SettingsBase, new() { var cachedSettings = AllSettings[typeof(T)] as T; lock (SyncRoot) { if (cachedSettings == null || force) { var settingsInstance = cachedSettings ?? new T(); //use cachedSettings if possible for change detection var savedSettings = Repository.ReadSettings(settingsInstance.Category).ToNonNullArray(); //todo: consider moving out of lock if (savedSettings.Length == 0) { if (AutoPersistOnCreate) { var model = ToDbModel(settingsInstance); Repository.WriteSettings(model); //todo: consider moving out of lock } } SetProperties(settingsInstance, savedSettings); if (cachedSettings == null && !AllSettings.Contains(typeof(T))) { AllSettings.Add(typeof(T), settingsInstance); } return(settingsInstance); } return(cachedSettings); } }
public void RenderActiveSubmitStatements(List <UpdatePanel> updatePanels, HtmlTextWriter writer) { Debug.Assert(writer != null, "Should always have a writer"); List <RegisteredScript> entriesToRender = new List <RegisteredScript>(); // no comparer needed because it will contain ScriptKeys which implement Equals ListDictionary uniqueEntries = new ListDictionary(); // For each entry registered in the page, check and see which ones // came from controls within UpdatePanels that are going to be updated. Control lastControl = null; foreach (RegisteredScript entry in ScriptSubmitStatements) { Control child = entry.Control; bool isActive = ((lastControl != null) && (child == lastControl)) || IsControlRegistrationActive(updatePanels, child, true); if (isActive) { lastControl = child; ScriptKey scriptKey = new ScriptKey(entry.Type, entry.Key); if (!uniqueEntries.Contains(scriptKey)) { entriesToRender.Add(entry); uniqueEntries.Add(scriptKey, entry); } } } foreach (RegisteredScript activeRegistration in entriesToRender) { PageRequestManager.EncodeString(writer, PageRequestManager.OnSubmitToken, null, activeRegistration.Script); } }
void FindAndRemoveTransaction(SmppAsyncObject AsyncObject) { lock (PendingResponse.SyncRoot) { lock (PendingQueue.SyncRoot) { AsyncObject.DisposeTimer(); if (PendingResponse.Contains(AsyncObject.Request.Header.SequenceNumber)) { PendingResponse.Remove(AsyncObject.Request.Header.SequenceNumber); if ((PendingQueue.Count > 0) && TcpConnection.Connected) { for (int i = 0; i < PendingQueue.Count; i++) { var obj2 = PendingQueue[i] as SmppAsyncObject; lock (obj2.SyncRoot) { if (obj2.AsyncState == SmppAsyncObject.SmppAsyncState.Enabled) { PendingQueue.Remove(obj2); obj2.StartTimer(); PendingResponse.Add(obj2.Request.Header.SequenceNumber, obj2); SendResPdu(obj2.Request.ToByteArray()); goto Label_0142; } } } } } else { PendingQueue.Remove(AsyncObject); } } Label_0142: ; } }
private PropertyInfoCacheItem?FindPropertyInfoFor(string propertyName) { PropertyInfoCacheItem cacheItem; if (_propertyInfoLookupCache.Contains(propertyName)) { return((PropertyInfoCacheItem)_propertyInfoLookupCache[propertyName]); } if (_shimmedProperties.TryGetValue(propertyName, out _)) { cacheItem = CreateCacheItemFor(_localMimicPropertyInfos[propertyName]); _propertyInfoLookupCache[propertyName] = cacheItem; return(cacheItem); } if (!_localPropertyInfos.TryGetValue(propertyName, out var pi)) { if (_allowReadonlyDefaultsForMissingMembers) { return(null); } // TODO: throw for the correct type throw new PropertyNotFoundException(_wrappedTypes[0], propertyName); } cacheItem = CreateCacheItemFor(pi); _propertyInfoLookupCache[propertyName] = cacheItem; return(cacheItem); }
public static void Main() { // Creates and initializes a new ListDictionary. ListDictionary myCol = new ListDictionary(); myCol.Add("Braeburn Apples", "1.49"); myCol.Add("Fuji Apples", "1.29"); myCol.Add("Gala Apples", "1.49"); myCol.Add("Golden Delicious Apples", "1.29"); myCol.Add("Granny Smith Apples", "0.89"); myCol.Add("Red Delicious Apples", "0.99"); // Displays the values in the ListDictionary in three different ways. Console.WriteLine("Initial contents of the ListDictionary:"); PrintKeysAndValues(myCol); // Searches for a key. if (myCol.Contains("Kiwis")) { Console.WriteLine("The collection contains the key \"Kiwis\"."); } else { Console.WriteLine("The collection does not contain the key \"Kiwis\"."); } Console.WriteLine(); }
public static ISessionFactory GetSessionFactoryInstance(ConnectionStringEnum connectionString) { ISessionFactory sessionFactory = null; if (_factories == null) { _factories = new ListDictionary(); } if (_factories.Contains(connectionString)) { sessionFactory = (ISessionFactory)_factories[connectionString]; } else { var connectionStringKey = EnumHelper <ConnectionStringEnum> .GetDisplayValue(connectionString); sessionFactory = CreateSessionFactory(connectionStringKey); _factories.Add(connectionString, sessionFactory); } sessionFactory = (ISessionFactory)_factories[connectionString]; return(sessionFactory); }
void UpdateObject(WidgetParser parser, string topType, XmlElement objectElem, ITypeDefinition widgetClass, ITypeDefinition wrapperClass) { if (widgetClass.IsPublic) { objectElem.RemoveAttribute("internal"); } else { objectElem.SetAttribute("internal", "true"); } ListDictionary properties = new ListDictionary(); ListDictionary events = new ListDictionary(); parser.CollectMembers(widgetClass, true, topType, properties, events); if (wrapperClass != null) { parser.CollectMembers(wrapperClass, false, null, properties, events); } foreach (IProperty prop in properties.Values) { MergeProperty(parser, objectElem, prop); } foreach (IEvent ev in events.Values) { MergeEvent(parser, objectElem, ev); } // Remove old properties ArrayList toDelete = new ArrayList(); foreach (XmlElement xprop in objectElem.SelectNodes("itemgroups/itemgroup/property")) { if (!properties.Contains(xprop.GetAttribute("name"))) { toDelete.Add(xprop); } } // Remove old signals foreach (XmlElement xevent in objectElem.SelectNodes("signals/itemgroup/signal")) { if (!events.Contains(xevent.GetAttribute("name"))) { toDelete.Add(xevent); } } foreach (XmlElement el in toDelete) { XmlElement pe = (XmlElement)el.ParentNode; pe.RemoveChild(el); if (pe.ChildNodes.Count == 0) { pe.ParentNode.RemoveChild(pe); } } }
private ListDictionary GetResources(string cultureName) { if (_resCache == null) { _resCache = new ListDictionary(); } if (cultureName == null) { cultureName = "none"; } ListDictionary dict; if (!_resCache.Contains(cultureName)) { dict = _db.GetResources(cultureName, GetVirtualPath(_provider)); _resCache.Add(cultureName, dict); } else { dict = (ListDictionary)_resCache[cultureName]; } return(dict); }
public ListDictionary GetResourcesByCulture(string cultureName) { Debug.WriteLine(String.Format("StringResourcesLinq.GetResourceByCulture(culture:{0}) for resourceType:{1}", cultureName, this.resourceType)); if (cultureName == null) { cultureName = ""; } // create the dictionary ListDictionary resourceDictionary = new ListDictionary(); // set up LINQ expression and get resource from database DBResourceDataClassesDataContext db = getDataContext(); IEnumerable <StringResource> res = db.StringResources.Where(m => m.CultureCode.Equals(cultureName) && m.ResourceType.Equals(this.resourceType)); foreach (StringResource r in res) { string k = r.ResourceKey; string v = r.ResourceValue; if (!resourceDictionary.Contains(k)) { resourceDictionary.Add(k, v); } } return(resourceDictionary); }
/// <summary> /// Sends data to connected client /// </summary> /// <param name="clientid">client id</param> /// <param name="byteData">data to send</param> /// <param name="count">how many bytes</param> public void Send(String clientid, byte[] byteData, int count) { if (clientList.Contains(clientid)) { var client = (ClientConnHandler)clientList[clientid]; client.SendToClient(byteData, count); } }
public static void Set_CustomComparerTest() { ObservableStringComparer comparer = new ObservableStringComparer(); ListDictionary ld = Fill(new ListDictionary(comparer), s_dictionaryData); int visited = s_dictionaryData.Length; Assert.All(s_dictionaryData.Reverse(), element => { string newValue = "new" + element.Value; Assert.True(ld.Contains(element.Key)); // Removing items in reverse order, so iterates over everything ahead of the key. comparer.AssertCompared(visited--, () => ld[element.Key] = newValue); Assert.True(ld.Contains(element.Key)); Assert.Equal(newValue, ld[element.Key]); }); }
public static void Constructor_DefaultTests(ListDictionary ld) { Assert.Equal(0, ld.Count); Assert.False(ld.IsReadOnly); Assert.Empty(ld); Assert.Empty(ld.Keys); Assert.Empty(ld.Values); Assert.False(ld.Contains(new object())); Assert.Null(ld[new object()]); }
public static void AddTest(bool addViaSet) { ListDictionary added = new ListDictionary(); IList keys = new ArrayList(); IList values = new ArrayList(); for (int i = 0; i < s_dictionaryData.Length; i++) { string key = s_dictionaryData[i].Key; string value = s_dictionaryData[i].Value; Assert.Equal(i, added.Count); Assert.Null(added[key]); Assert.False(added.Contains(key)); added.Add(addViaSet, key, value); keys.Add(key); values.Add(value); Assert.Equal(value, added[key]); Assert.True(added.Contains(key)); Assert.Equal(i + 1, added.Count); CollectionAsserts.Equal(keys, added.Keys); CollectionAsserts.Equal(values, added.Values); Assert.Throws<ArgumentException>(() => added.Add(key, value)); added[key] = value; } }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; ListDictionary ld; string [] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; string [] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; try { intl = new IntlStrings(); Console.WriteLine("--- create dictionary ---"); strLoc = "Loc_001oo"; iCountTestcases++; ld = new ListDictionary(); Console.WriteLine("1. Contains() on empty dictionary"); iCountTestcases++; Console.WriteLine(" - Contains(null)"); try { ld.Contains(null); iCountErrors++; Console.WriteLine("Err_0001a, no exception"); } catch (ArgumentNullException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0001b, unexpected exception: {0}", e.ToString()); } Console.WriteLine(" - Contains(some_object)"); if ( ld.Contains("some_string") ) { iCountErrors++; Console.WriteLine("Err_0001c, empty dictionary contains some_object"); } Console.WriteLine("2. add simple strings and check Contains()"); strLoc = "Loc_002oo"; iCountTestcases++; cnt = ld.Count; int len = values.Length; for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } if (ld.Count != len) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", ld.Count, values.Length); } for (int i = 0; i < len; i++) { iCountTestcases++; if ( ! ld.Contains(keys[i]) ) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, doesn't contain \"{1}\"", i, keys[i]); } } Console.WriteLine("3. add intl strings check Contains()"); strLoc = "Loc_003oo"; iCountTestcases++; string [] intlValues = new string [len * 2]; for (int i = 0; i < len*2; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if(intlValues[i].Length!=0 && intlValues[i].ToLower()==intlValues[i].ToUpper()) caseInsensitive = true; } iCountTestcases++; ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(intlValues[i+len], intlValues[i]); } if ( ld.Count != (len) ) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", ld.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; if ( ! ld.Contains(intlValues[i+len]) ) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, doesn't contain \"{1}\"", i, intlValues[i+len]); } } Console.WriteLine("4. case sensitivity"); strLoc = "Loc_004oo"; string [] intlValuesLower = new string [len * 2]; for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpper(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLower(); } ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(intlValues[i+len], intlValues[i]); } for (int i = 0; i < len; i++) { iCountTestcases++; if ( ! ld.Contains(intlValues[i+len]) ) { iCountErrors++; Console.WriteLine("Err_0004_{0}a, doesn't contain added uppercase \"{1}\"", i, intlValues[i+len]); } iCountTestcases++; if ( !caseInsensitive && ld.Contains(intlValuesLower[i+len]) ) { iCountErrors++; Console.WriteLine("Err_0004_{0}a, contains lowercase \"{1}\" - should not", i, intlValuesLower[i+len]); } } Console.WriteLine("5. similar_but_different_in_casing keys and Contains()"); strLoc = "Loc_005oo"; iCountTestcases++; ld.Clear(); string [] ks = {"Key", "kEy", "keY"}; len = ks.Length; for (int i = 0; i < len; i++) { ld.Add(ks[i], "Value"+i); } if (ld.Count != len) { iCountErrors++; Console.WriteLine("Err_0005a, count is {0} instead of {1}", ld.Count, len); } iCountTestcases++; if ( ld.Contains("Value0") ) { iCountErrors++; Console.WriteLine("Err_0005b, returned true when should not"); } for (int i = 0; i < len; i++) { iCountTestcases++; if ( !ld.Contains(ks[i]) ) { iCountErrors++; Console.WriteLine("Err_0005c_{0}, returned false when true expected", i); } } Console.WriteLine("6. Contains(null) for filled dictionary"); strLoc = "Loc_006oo"; iCountTestcases++; ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } try { ld.Contains(null); iCountErrors++; Console.WriteLine("Err_0006a, no exception"); } catch (ArgumentNullException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0006b, unexpected exception: {0}", e.ToString()); } Console.WriteLine("7. Contains() for case-insensitive comparer"); ld = new ListDictionary(new Co8686_InsensitiveComparer()); strLoc = "Loc_007oo"; iCountTestcases++; ld.Clear(); len = ks.Length; ld.Add(ks[0], "Value0"); for (int i = 1; i < len; i++) { try { ld.Add(ks[i], "Value"+i); iCountErrors++; Console.WriteLine("Err_0007a_{0}, no exception", i); } catch (ArgumentException e) { Console.WriteLine("_{0}, Expected exception: {1}", i, e.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_0007b_{0}, unexpected exception: {1}", i, ex.ToString()); } } if (ld.Count != 1) { iCountErrors++; Console.WriteLine("Err_0007c, count is {0} instead of {1}", ld.Count, 1); } iCountTestcases++; if ( ld.Contains("Value0") ) { iCountErrors++; Console.WriteLine("Err_0007d, returned true when should not"); } for (int i = 0; i < len; i++) { iCountTestcases++; if ( !ld.Contains(ks[i]) ) { iCountErrors++; Console.WriteLine("Err_0007e_{0}, returned false when true expected", i); } } iCountTestcases++; if ( !ld.Contains("KEY") ) { iCountErrors++; Console.WriteLine("Err_0007f, returned false non-existing-cased key"); } Console.WriteLine("10. Contains() and SpecialStructs_not_overriding_Equals"); ld = new ListDictionary(); strLoc = "Loc_010oo"; iCountTestcases++; Co8686_SpecialStruct s = new Co8686_SpecialStruct(); s.Num = 1; s.Wrd = "one"; Co8686_SpecialStruct s1 = new Co8686_SpecialStruct(); s.Num = 1; s.Wrd = "one"; ld.Add(s, "first"); ld.Add(s1, "second"); if (ld.Count != 2) { iCountErrors++; Console.WriteLine("Err_0010a, count is {0} instead of {1}", ld.Count, 2); } iCountTestcases++; if ( !ld.Contains(s) ) { iCountErrors++; Console.WriteLine("Err_0010b, returned false when true expected"); } iCountTestcases++; if ( !ld.Contains(s1) ) { iCountErrors++; Console.WriteLine("Err_0010c, returned false when true expected"); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! 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 static void RemoveTest(ListDictionary ld, KeyValuePair<string, string>[] data) { Assert.All(data, element => { Assert.True(ld.Contains(element.Key)); ld.Remove(element.Key); Assert.False(ld.Contains(element.Key)); }); Assert.Equal(0, ld.Count); }
public static void Contains_NullTest(ListDictionary ld, KeyValuePair<string, string>[] data) { Assert.Throws<ArgumentNullException>("key", () => ld.Contains(null)); }
public static void Add_CustomComparerTest(bool addViaSet) { ObservableStringComparer comparer = new ObservableStringComparer(); ListDictionary added = new ListDictionary(comparer); for (int i = 0; i < s_dictionaryData.Length; i++) { string key = s_dictionaryData[i].Key; string value = s_dictionaryData[i].Value; Assert.Equal(i, added.Count); comparer.AssertCompared(i, () => Assert.Null(added[key])); comparer.AssertCompared(i, () => Assert.False(added.Contains(key))); // comparer is called for each element in sequence during add. comparer.AssertCompared(i, () => added.Add(addViaSet, key, value)); comparer.AssertCompared(i + 1, () => Assert.Equal(value, added[key])); comparer.AssertCompared(i + 1, () => Assert.True(added.Contains(key))); Assert.Equal(i + 1, added.Count); comparer.AssertCompared(i + 1, () => Assert.Throws<ArgumentException>(() => added.Add(key, "duplicate"))); } Assert.Equal(s_dictionaryData.Length, added.Count); // Because the dictionary maintains insertion order, "add"-ing an already-present element only iterates // until the initial key is reached. int middleIndex = s_dictionaryData.Length / 2; string middleKey = s_dictionaryData[middleIndex].Key; string middleValue = s_dictionaryData[middleIndex].Value; Assert.Equal(middleValue, added[middleKey]); Assert.True(added.Contains(middleKey)); // Index is 0-based, count is 1-based // ... Add throws exception comparer.AssertCompared(middleIndex + 1, () => Assert.Throws<ArgumentException>(() => added.Add(middleKey, "middleValue"))); Assert.Equal(middleValue, added[middleKey]); Assert.True(added.Contains(middleKey)); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; ListDictionary ld; Object itm; string [] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; string [] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; try { intl = new IntlStrings(); Console.WriteLine("--- create dictionary ---"); strLoc = "Loc_001oo"; iCountTestcases++; ld = new ListDictionary(); Console.WriteLine("1. Item() on empty dictionary"); iCountTestcases++; cnt = ld.Count; Console.WriteLine(" - Item(null)"); try { itm = ld[null]; iCountErrors++; Console.WriteLine("Err_0001a, no exception"); } catch (ArgumentNullException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0001b, unexpected exception: {0}", e.ToString()); } iCountTestcases++; cnt = ld.Count; Console.WriteLine(" - Item(some_string)"); itm = ld["some_string"]; if (itm != null) { iCountErrors++; Console.WriteLine("Err_0001c, returned non=null"); } Console.WriteLine("2. add simple strings, access via Item(Object)"); strLoc = "Loc_002oo"; iCountTestcases++; cnt = ld.Count; int len = values.Length; for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } if (ld.Count != len) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", ld.Count, values.Length); } for (int i = 0; i < len; i++) { iCountTestcases++; if ( !ld.Contains(keys[i]) ) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, doesn't contain key", i); } iCountTestcases++; if (String.Compare(ld[keys[i]].ToString(), values[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0002_{0}c, returned wrong value", i); } } Console.WriteLine("3. add intl strings and access via Item()"); strLoc = "Loc_003oo"; iCountTestcases++; string [] intlValues = new string [len * 2]; for (int i = 0; i < len*2; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if(intlValues[i].Length!=0 && intlValues[i].ToLower()==intlValues[i].ToUpper()) caseInsensitive = true; } iCountTestcases++; cnt = ld.Count; for (int i = 0; i < len; i++) { ld.Add(intlValues[i+len], intlValues[i]); } if ( ld.Count != (cnt+len) ) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", ld.Count, cnt+len); } for (int i = 0; i < len; i++) { iCountTestcases++; if (! ld.Contains(intlValues[i+len]) ) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, doesn't contain key", i); } iCountTestcases++; if (String.Compare(ld[intlValues[i+len]].ToString(), intlValues[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0003_{0}c, returned wrong value", i); } } Console.WriteLine("4. case sensitivity"); strLoc = "Loc_004oo"; string [] intlValuesLower = new string [len * 2]; for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpper(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLower(); } ld.Clear(); Console.WriteLine(" - add uppercase and access using uppercase"); for (int i = 0; i < len; i++) { ld.Add(intlValues[i+len], intlValues[i]); } for (int i = 0; i < len; i++) { iCountTestcases++; if ( !ld.Contains( intlValues[i+len]) ) { iCountErrors++; Console.WriteLine("Err_0004_{0}b, doesn't contain key", i); } iCountTestcases++; if (String.Compare(ld[intlValues[i+len]].ToString(), intlValues[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0004_{0}c, returned wrong value", i); } } ld.Clear(); Console.WriteLine(" - add uppercase but access using lowercase"); for (int i = 0; i < len; i++) { ld.Add(intlValues[i+len], intlValues[i]); } for (int i = 0; i < len; i++) { cnt = ld.Count; iCountTestcases++; if ( !caseInsensitive && ld[intlValuesLower[i+len]] != null ) { iCountErrors++; Console.WriteLine("Err_0004_{0}d, failed: returned non-null for lowercase key", i); } } Console.WriteLine("5. access Item() on LD with insensitive comparer"); ld = new ListDictionary(new Co8694_InsensitiveComparer()); strLoc = "Loc_005oo"; iCountTestcases++; len = values.Length; ld.Clear(); string kk = "key"; for (int i = 0; i < len; i++) { ld.Add(kk+i, values[i]); } if (ld.Count != len) { iCountErrors++; Console.WriteLine("Err_0005a, count is {0} instead of {1}", ld.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; if (ld[kk.ToUpper() + i] == null) { iCountErrors++; Console.WriteLine("Err_0005b_{0}, returned null for differently cased key", i); } else { if (String.Compare(ld[kk.ToUpper() + i].ToString(), values[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0005b_{0}, returned wrong value", i); } } } Console.WriteLine("6. Item(null) for filled LD"); ld = new ListDictionary(); strLoc = "Loc_006oo"; iCountTestcases++; cnt = ld.Count; if (ld.Count < len) { ld.Clear(); for (int i = 0; i < len; i ++) { ld.Add(keys[i], values[i]); } } iCountTestcases++; try { itm = ld[null]; iCountErrors++; Console.WriteLine("Err_0006a, no exception"); } catch (ArgumentNullException ex) { Console.WriteLine(" Expected exception: {0}", ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0006b, unexpected exception: {0}", e.ToString()); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! 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; } }