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 void Remove(Object key) { if (hash != null) { hash.Remove(key); } else { list.Remove(key); } }
public void Remove(object key) { if (_hashtable != null) { _hashtable.Remove(key); } else if (_list != null) { _list.Remove(key); } else { if (key == null) { throw new ArgumentNullException("key", SR.ArgumentNull_Key); } } }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(object key) { if (hashtable != null) { hashtable.Remove(key); } else if (list != null) { list.Remove(key); } else { if (key == null) { throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key)); } } }
//ExtendedProperties // Per config // Platform : Eg. Any CPU // SolutionConfigurationPlatforms // SolutionFolder LoadSolution (Solution sol, string fileName, MSBuildFileFormat format, IProgressMonitor monitor) { string headerComment; string version = GetSlnFileVersion (fileName, out headerComment); ListDictionary globals = null; SolutionFolder folder = null; SlnData data = null; List<Section> projectSections = null; List<string> lines = null; FileFormat projectFormat = Services.ProjectService.FileFormats.GetFileFormat (format); monitor.BeginTask (GettextCatalog.GetString ("Loading solution: {0}", fileName), 1); //Parse the .sln file using (StreamReader reader = new StreamReader(fileName)) { sol.FileName = fileName; sol.ConvertToFormat (projectFormat, false); folder = sol.RootFolder; sol.Version = "0.1"; //FIXME: data = new SlnData (); folder.ExtendedProperties [typeof (SlnFileFormat)] = data; data.VersionString = version; data.HeaderComment = headerComment; string s = null; projectSections = new List<Section> (); lines = new List<string> (); globals = new ListDictionary (); //Parse while (reader.Peek () >= 0) { s = GetNextLine (reader, lines).Trim (); if (String.Compare (s, "Global", StringComparison.OrdinalIgnoreCase) == 0) { ParseGlobal (reader, lines, globals); continue; } if (s.StartsWith ("Project", StringComparison.Ordinal)) { Section sec = new Section (); projectSections.Add (sec); sec.Start = lines.Count - 1; int e = ReadUntil ("EndProject", reader, lines); sec.Count = (e < 0) ? 1 : (e - sec.Start + 1); continue; } if (s.StartsWith ("VisualStudioVersion = ", StringComparison.Ordinal)) { Version v; if (Version.TryParse (s.Substring ("VisualStudioVersion = ".Length), out v)) data.VisualStudioVersion = v; else monitor.Log.WriteLine ("Ignoring unparseable VisualStudioVersion value in sln file"); } if (s.StartsWith ("MinimumVisualStudioVersion = ", StringComparison.Ordinal)) { Version v; if (Version.TryParse (s.Substring ("MinimumVisualStudioVersion = ".Length), out v)) data.MinimumVisualStudioVersion = v; else monitor.Log.WriteLine ("Ignoring unparseable MinimumVisualStudioVersion value in sln file"); } } } monitor.BeginTask("Loading projects ..", projectSections.Count + 1); Dictionary<string, SolutionItem> items = new Dictionary<string, SolutionItem> (); List<SolutionItem> sortedList = new List<SolutionItem> (); foreach (Section sec in projectSections) { monitor.Step (1); Match match = ProjectRegex.Match (lines [sec.Start]); if (!match.Success) { LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project definition on line number #{0} in file '{1}'. Ignoring.", sec.Start + 1, fileName)); continue; } try { // Valid guid? new Guid (match.Groups [1].Value); } catch (FormatException) { //Use default guid as projectGuid LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project type guid '{0}' on line #{1}. Ignoring.", match.Groups [1].Value, sec.Start + 1)); continue; } string projTypeGuid = match.Groups [1].Value.ToUpper (); string projectName = match.Groups [2].Value; string projectPath = match.Groups [3].Value; string projectGuid = match.Groups [4].Value.ToUpper (); List<string> projLines; if (projTypeGuid == MSBuildProjectService.FolderTypeGuid) { //Solution folder SolutionFolder sfolder = new SolutionFolder (); sfolder.Name = projectName; MSBuildProjectService.InitializeItemHandler (sfolder); MSBuildProjectService.SetId (sfolder, projectGuid); projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DeserializeSolutionItem (sol, sfolder, projLines); foreach (string f in ReadFolderFiles (projLines)) sfolder.Files.Add (MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), f)); SlnData slnData = new SlnData (); slnData.Extra = projLines.ToArray (); sfolder.ExtendedProperties [typeof (SlnFileFormat)] = slnData; items.Add (projectGuid, sfolder); sortedList.Add (sfolder); continue; } if (projectPath.StartsWith("http://")) { monitor.ReportWarning (GettextCatalog.GetString ( "{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.", fileName, sec.Start + 1, projectPath)); data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count)); continue; } string path = MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), projectPath); if (String.IsNullOrEmpty (path)) { monitor.ReportWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); LoggingService.LogWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); continue; } projectPath = Path.GetFullPath (path); SolutionEntityItem item = null; try { if (sol.IsSolutionItemEnabled (projectPath)) { item = ProjectExtensionUtil.LoadSolutionItem (monitor, projectPath, delegate { return MSBuildProjectService.LoadItem (monitor, projectPath, format, projTypeGuid, projectGuid); }); if (item == null) { throw new UnknownSolutionItemTypeException (projTypeGuid); } } else { var uitem = new UnloadedSolutionItem () { FileName = projectPath }; var h = new MSBuildHandler (projTypeGuid, projectGuid) { Item = uitem, }; uitem.SetItemHandler (h); item = uitem; } } catch (Exception e) { // If we get a TargetInvocationException from using Activator.CreateInstance we // need to unwrap the real exception while (e is TargetInvocationException) e = ((TargetInvocationException) e).InnerException; bool loadAsProject = false; if (e is UnknownSolutionItemTypeException) { var name = ((UnknownSolutionItemTypeException)e).TypeName; var relPath = new FilePath (path).ToRelative (sol.BaseDirectory); if (!string.IsNullOrEmpty (name)) { var guids = name.Split (';'); var projectInfo = MSBuildProjectService.GetUnknownProjectTypeInfo (guids, fileName); if (projectInfo != null) { loadAsProject = projectInfo.LoadFiles; LoggingService.LogWarning (string.Format ("Could not load {0} project '{1}'. {2}", projectInfo.Name, relPath, projectInfo.GetInstructions ())); monitor.ReportWarning (GettextCatalog.GetString ("Could not load {0} project '{1}'. {2}", projectInfo.Name, relPath, projectInfo.GetInstructions ())); } else { LoggingService.LogWarning (string.Format ("Could not load project '{0}' with unknown item type '{1}'", relPath, name)); monitor.ReportWarning (GettextCatalog.GetString ("Could not load project '{0}' with unknown item type '{1}'", relPath, name)); } } else { LoggingService.LogWarning (string.Format ("Could not load project '{0}' with unknown item type", relPath)); monitor.ReportWarning (GettextCatalog.GetString ("Could not load project '{0}' with unknown item type", relPath)); } } else if (e is UserException) { var ex = (UserException) e; LoggingService.LogError ("{0}: {1}", ex.Message, ex.Details); monitor.ReportError (string.Format ("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.Details), null); } else { LoggingService.LogError (string.Format ("Error while trying to load the project {0}", projectPath), e); monitor.ReportWarning (GettextCatalog.GetString ( "Error while trying to load the project '{0}': {1}", projectPath, e.Message)); } SolutionEntityItem uitem; if (loadAsProject) { uitem = new UnknownProject () { FileName = projectPath, LoadError = e.Message, }; } else { uitem = new UnknownSolutionItem () { FileName = projectPath, LoadError = e.Message, }; } var h = new MSBuildHandler (projTypeGuid, projectGuid) { Item = uitem, }; uitem.SetItemHandler (h); item = uitem; } MSBuildHandler handler = (MSBuildHandler) item.ItemHandler; projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DataItem it = GetSolutionItemData (projLines); handler.UnresolvedProjectDependencies = ReadSolutionItemDependencies (projLines); handler.SlnProjectContent = projLines.ToArray (); handler.ReadSlnData (it); if (!items.ContainsKey (projectGuid)) { items.Add (projectGuid, item); sortedList.Add (item); data.ItemsByGuid [projectGuid] = item; } else { monitor.ReportError (GettextCatalog.GetString ("Invalid solution file. There are two projects with the same GUID. The project {0} will be ignored.", projectPath), null); } } monitor.EndTask (); if (globals != null && globals.Contains ("NestedProjects")) { LoadNestedProjects (globals ["NestedProjects"] as Section, lines, items, monitor); globals.Remove ("NestedProjects"); } // Resolve project dependencies foreach (var it in items.Values.OfType<SolutionEntityItem> ()) { MSBuildHandler handler = (MSBuildHandler) it.ItemHandler; if (handler.UnresolvedProjectDependencies != null) { foreach (var id in handler.UnresolvedProjectDependencies.ToArray ()) { SolutionItem dep; if (items.TryGetValue (id, out dep) && dep is SolutionEntityItem) { handler.UnresolvedProjectDependencies.Remove (id); it.ItemDependencies.Add ((SolutionEntityItem)dep); } } if (handler.UnresolvedProjectDependencies.Count == 0) handler.UnresolvedProjectDependencies = null; } } //Add top level folders and projects to the main folder foreach (SolutionItem ce in sortedList) { if (ce.ParentFolder == null) folder.Items.Add (ce); } //FIXME: This can be just SolutionConfiguration also! if (globals != null) { if (globals.Contains ("SolutionConfigurationPlatforms")) { LoadSolutionConfigurations (globals ["SolutionConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("SolutionConfigurationPlatforms"); } if (globals.Contains ("ProjectConfigurationPlatforms")) { LoadProjectConfigurationMappings (globals ["ProjectConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("ProjectConfigurationPlatforms"); } if (globals.Contains ("MonoDevelopProperties")) { LoadMonoDevelopProperties (globals ["MonoDevelopProperties"] as Section, lines, sol, monitor); globals.Remove ("MonoDevelopProperties"); } ArrayList toRemove = new ArrayList (); foreach (DictionaryEntry e in globals) { string name = (string) e.Key; if (name.StartsWith ("MonoDevelopProperties.")) { int i = name.IndexOf ('.'); LoadMonoDevelopConfigurationProperties (name.Substring (i+1), (Section)e.Value, lines, sol, monitor); toRemove.Add (e.Key); } } foreach (object key in toRemove) globals.Remove (key); } //Save the global sections that we dont use List<string> globalLines = new List<string> (); foreach (Section sec in globals.Values) globalLines.InsertRange (globalLines.Count, lines.GetRange (sec.Start, sec.Count)); data.GlobalExtra = globalLines; monitor.EndTask (); // When reloading a project, keep the solution data and item id sol.SolutionItemAdded += delegate(object sender, SolutionItemChangeEventArgs e) { if (e.Reloading) { ItemSlnData.TransferData (e.ReplacedItem, e.SolutionItem); var ih = e.SolutionItem.ItemHandler as MSBuildHandler; if (ih != null) ih.ItemId = e.ReplacedItem.ItemId; } }; return folder; }
public void Remove () { ListDictionary ld = new ListDictionary (); ld.Remove (null); }
public MemberInfo[] GetMembers(Type type) { Stack stack = new Stack(); while (type != null) { stack.Push(type); type = type.BaseType; } IDictionary members = new ListDictionary(); foreach (Type htype in stack) { foreach (MemberInfo member in htype.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) { if (members.Contains(member.Name)) members.Remove(member.Name); members.Add(member.Name, member); } } return (MemberInfo[]) new ArrayList(members.Values).ToArray(typeof(MemberInfo)); }
private bool IsValidMarkup(ContextProperty cp, Dimension.MeasureHyperCubeInfo mhci, ref ArrayList errors) { BuildValidMembersByDimension(); ListDictionary instanceDimensionInfos = new ListDictionary(); if (mhci.IsScenario) { foreach (Scenario sc in cp.Scenarios) { if (sc.DimensionInfo != null) { instanceDimensionInfos[sc.DimensionInfo.dimensionId] = sc.DimensionInfo; } } } else { //TODO: same thing for segments.. } ListDictionary validationByDimension = new ListDictionary(); int baseValidationData = 0; if (mhci.IsAllRelationShip) { baseValidationData += ValidationDataEnum.ALLRelationShip.GetHashCode(); } else { baseValidationData += ValidationDataEnum.NotAllRelationShip.GetHashCode(); } if (mhci.IsClosed) { baseValidationData += ValidationDataEnum.IsClosed.GetHashCode(); } else { baseValidationData += ValidationDataEnum.IsNotClosed.GetHashCode(); } foreach (DictionaryEntry de in validMembersByDimension) { int validationData = baseValidationData; bool found = false; bool hasDefault = false; ContextDimensionInfo cdi = instanceDimensionInfos[de.Key] as ContextDimensionInfo; instanceDimensionInfos.Remove(de.Key); if (cdi == null) { validationData += ValidationDataEnum.DimensionNotInInstance.GetHashCode(); } else { HybridDictionary validMembers = de.Value as HybridDictionary; if (validMembers != null) { found = validMembers[cdi.Id] != null; } } if (found) { validationData += ValidationDataEnum.Found.GetHashCode(); } else { validationData += ValidationDataEnum.NotFound.GetHashCode(); } if (hasDefault) { validationData += ValidationDataEnum.DimensionHasDefault.GetHashCode(); //TODO: determine if the default value is being used //which is not a good thing and is an error condition. } ValidateResult(validationData, errors); } if (instanceDimensionInfos.Keys.Count != 0) { if (mhci.IsClosed) { //this is an error condition as we have dimensions that are not part of //the cube in the instance but the cube is a closed cube and does not //allow other dimension infos //TODO: enhance the error message... string error = "Found invalid dimension for an element that is using a closed hypercube"; errors.Add(error); } } return errors.Count == 0; }
//ExtendedProperties // Per config // Platform : Eg. Any CPU // SolutionConfigurationPlatforms // SolutionFolder LoadSolution (Solution sol, string fileName, MSBuildFileFormat format, IProgressMonitor monitor) { string headerComment; string version = GetSlnFileVersion (fileName, out headerComment); ListDictionary globals = null; SolutionFolder folder = null; SlnData data = null; List<Section> projectSections = null; List<string> lines = null; FileFormat projectFormat = Services.ProjectService.FileFormats.GetFileFormat (format); monitor.BeginTask (GettextCatalog.GetString ("Loading solution: {0}", fileName), 1); //Parse the .sln file using (StreamReader reader = new StreamReader(fileName)) { sol.FileName = fileName; sol.ConvertToFormat (projectFormat, false); folder = sol.RootFolder; sol.Version = "0.1"; //FIXME: data = new SlnData (); folder.ExtendedProperties [typeof (SlnFileFormat)] = data; data.VersionString = version; data.HeaderComment = headerComment; string s = null; projectSections = new List<Section> (); lines = new List<string> (); globals = new ListDictionary (); //Parse while (reader.Peek () >= 0) { s = GetNextLine (reader, lines).Trim (); if (String.Compare (s, "Global", true) == 0) { ParseGlobal (reader, lines, globals); continue; } if (s.StartsWith ("Project")) { Section sec = new Section (); projectSections.Add (sec); sec.Start = lines.Count - 1; int e = ReadUntil ("EndProject", reader, lines); sec.Count = (e < 0) ? 1 : (e - sec.Start + 1); continue; } } } monitor.BeginTask("Loading projects ..", projectSections.Count + 1); Dictionary<string, SolutionItem> items = new Dictionary<string, SolutionItem> (); List<SolutionItem> sortedList = new List<SolutionItem> (); foreach (Section sec in projectSections) { monitor.Step (1); Match match = ProjectRegex.Match (lines [sec.Start]); if (!match.Success) { LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project definition on line number #{0} in file '{1}'. Ignoring.", sec.Start + 1, fileName)); continue; } try { // Valid guid? new Guid (match.Groups [1].Value); } catch (FormatException) { //Use default guid as projectGuid LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project type guid '{0}' on line #{1}. Ignoring.", match.Groups [1].Value, sec.Start + 1)); continue; } string projTypeGuid = match.Groups [1].Value.ToUpper (); string projectName = match.Groups [2].Value; string projectPath = match.Groups [3].Value; string projectGuid = match.Groups [4].Value; if (projTypeGuid == MSBuildProjectService.FolderTypeGuid) { //Solution folder SolutionFolder sfolder = new SolutionFolder (); sfolder.Name = projectName; MSBuildProjectService.InitializeItemHandler (sfolder); MSBuildProjectService.SetId (sfolder, projectGuid); List<string> projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DeserializeSolutionItem (sol, sfolder, projLines); foreach (string f in ReadFolderFiles (projLines)) sfolder.Files.Add (MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), f)); SlnData slnData = new SlnData (); slnData.Extra = projLines.ToArray (); sfolder.ExtendedProperties [typeof (SlnFileFormat)] = slnData; items.Add (projectGuid, sfolder); sortedList.Add (sfolder); continue; } if (projectPath.StartsWith("http://")) { monitor.ReportWarning (GettextCatalog.GetString ( "{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.", fileName, sec.Start + 1, projectPath)); data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count)); continue; } string path = MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), projectPath); if (String.IsNullOrEmpty (path)) { monitor.ReportWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); LoggingService.LogWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); continue; } projectPath = Path.GetFullPath (path); SolutionEntityItem item = null; try { item = ProjectExtensionUtil.LoadSolutionItem (monitor, projectPath, delegate { return MSBuildProjectService.LoadItem (monitor, projectPath, projTypeGuid, projectGuid); }); if (item == null) { LoggingService.LogWarning (GettextCatalog.GetString ( "Unknown project type guid '{0}' on line #{1}. Ignoring.", projTypeGuid, sec.Start + 1)); monitor.ReportWarning (GettextCatalog.GetString ( "{0}({1}): Unsupported or unrecognized project : '{2}'.", fileName, sec.Start + 1, projectPath)); continue; } MSBuildProjectHandler handler = (MSBuildProjectHandler) item.ItemHandler; List<string> projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DataItem it = GetSolutionItemData (projLines); handler.SlnProjectContent = projLines.ToArray (); handler.ReadSlnData (it); } catch (Exception e) { if (e is UnknownSolutionItemTypeException) { var name = ((UnknownSolutionItemTypeException)e).TypeName; LoggingService.LogWarning (!string.IsNullOrEmpty (name)? string.Format ("Could not load project '{0}' with unknown item type '{1}'", projectPath, name) : string.Format ("Could not load project '{0}' with unknown item type", projectPath)); monitor.ReportWarning (!string.IsNullOrEmpty (name)? GettextCatalog.GetString ("Could not load project '{0}' with unknown item type '{1}'", projectPath, name) : GettextCatalog.GetString ("Could not load project '{0}' with unknown item type", projectPath)); } else { LoggingService.LogError (string.Format ("Error while trying to load the project {0}", projectPath), e); monitor.ReportWarning (GettextCatalog.GetString ( "Error while trying to load the project '{0}': {1}", projectPath, e.Message)); } var uitem = new UnknownSolutionItem () { FileName = projectPath, LoadError = e.Message, }; var h = new MSBuildHandler (projTypeGuid, projectGuid) { Item = uitem, }; uitem.SetItemHandler (h); item = uitem; } if (!items.ContainsKey (projectGuid)) { items.Add (projectGuid, item); sortedList.Add (item); data.ItemsByGuid [projectGuid] = item; } else { monitor.ReportError (GettextCatalog.GetString ("Invalid solution file. There are two projects with the same GUID. The project {0} will be ignored.", projectPath), null); } } monitor.EndTask (); if (globals != null && globals.Contains ("NestedProjects")) { LoadNestedProjects (globals ["NestedProjects"] as Section, lines, items, monitor); globals.Remove ("NestedProjects"); } //Add top level folders and projects to the main folder foreach (SolutionItem ce in sortedList) { if (ce.ParentFolder == null) folder.Items.Add (ce); } //FIXME: This can be just SolutionConfiguration also! if (globals != null) { if (globals.Contains ("SolutionConfigurationPlatforms")) { LoadSolutionConfigurations (globals ["SolutionConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("SolutionConfigurationPlatforms"); } if (globals.Contains ("ProjectConfigurationPlatforms")) { LoadProjectConfigurationMappings (globals ["ProjectConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("ProjectConfigurationPlatforms"); } if (globals.Contains ("MonoDevelopProperties")) { LoadMonoDevelopProperties (globals ["MonoDevelopProperties"] as Section, lines, sol, monitor); globals.Remove ("MonoDevelopProperties"); } ArrayList toRemove = new ArrayList (); foreach (DictionaryEntry e in globals) { string name = (string) e.Key; if (name.StartsWith ("MonoDevelopProperties.")) { int i = name.IndexOf ('.'); LoadMonoDevelopConfigurationProperties (name.Substring (i+1), (Section)e.Value, lines, sol, monitor); toRemove.Add (e.Key); } } foreach (object key in toRemove) globals.Remove (key); } //Save the global sections that we dont use List<string> globalLines = new List<string> (); foreach (Section sec in globals.Values) globalLines.InsertRange (globalLines.Count, lines.GetRange (sec.Start, sec.Count)); data.GlobalExtra = globalLines; monitor.EndTask (); return folder; }
public void Test01() { IntlStrings intl; ListDictionary ld; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] ListDictionary is constructed as expected //----------------------------------------------------------------- ld = new ListDictionary(); // [] Remove() on empty dictionary // cnt = ld.Count; Assert.Throws<ArgumentNullException>(() => { ld.Remove(null); }); cnt = ld.Count; ld.Remove("some_string"); if (ld.Count != cnt) { Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)")); } cnt = ld.Count; ld.Remove(new Hashtable()); if (ld.Count != cnt) { Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)")); } // [] add simple strings and Remove() // cnt = ld.Count; int len = values.Length; for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } if (ld.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, values.Length)); } // for (int i = 0; i < len; i++) { cnt = ld.Count; ld.Remove(keys[i]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } if (ld.Contains(keys[i])) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // Intl strings // [] Add Intl strings and Remove() // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLower() == intlValues[i].ToUpper()) caseInsensitive = true; } cnt = ld.Count; for (int i = 0; i < len; i++) { ld.Add(intlValues[i + len], intlValues[i]); } if (ld.Count != (cnt + len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, cnt + len)); } for (int i = 0; i < len; i++) { // cnt = ld.Count; ld.Remove(intlValues[i + len]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } if (ld.Contains(intlValues[i + len])) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // [] Case sensitivity // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // 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(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { ld.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // for (int i = 0; i < len; i++) { // uppercase key cnt = ld.Count; ld.Remove(intlValues[i + len]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } if (ld.Contains(intlValues[i + len])) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } ld.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { ld.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // LD is case-sensitive by default for (int i = 0; i < len; i++) { // lowercase key cnt = ld.Count; ld.Remove(intlValuesLower[i + len]); if (!caseInsensitive && ld.Count != cnt) { Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i)); } } // // [] Remove() on LD with case-insensitive comparer // ld = new ListDictionary(new InsensitiveComparer()); 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) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len)); } for (int i = 0; i < len; i++) { cnt = ld.Count; ld.Remove(kk.ToUpper() + i); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, failed to remove item", i)); } if (ld.Contains(kk + i)) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // [] Remove(null) // ld = new ListDictionary(); cnt = ld.Count; if (ld.Count < len) { ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } } Assert.Throws<ArgumentNullException>(() => { ld.Remove(null); }); ld = new ListDictionary(); ld.Clear(); ArrayList b = new ArrayList(); ArrayList b1 = new ArrayList(); Hashtable lbl = new Hashtable(); Hashtable lbl1 = new Hashtable(); ld.Add(lbl, b); ld.Add(lbl1, b1); if (ld.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 2)); } cnt = ld.Count; ld.Remove(lbl); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, failed to remove special object")); } if (ld.Contains(lbl)) { Assert.False(true, string.Format("Error, removed wrong special object")); } }
public void Test01() { IntlStrings intl; ListDictionary ld; // simple string values string[] values = { "", " ", "a", "aa", "tExt", " spAces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; Array arr; ICollection ks; // Keys collection int ind; // initialize IntStrings intl = new IntlStrings(); // [] ListDictionary is constructed as expected //----------------------------------------------------------------- ld = new ListDictionary(); // [] get Keys for empty dictionary // if (ld.Count > 0) ld.Clear(); if (ld.Keys.Count != 0) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ld.Keys.Count)); } // [] get Keys for filled dictionary // int len = values.Length; ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } if (ld.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len)); } ks = ld.Keys; if (ks.Count != len) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } arr = Array.CreateInstance(typeof(Object), len); ks.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, keys[i]); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key. Search result: {2}", i, keys[i], ind)); } } // // get Keys on dictionary with identical values // // [] get Keys for filled dictionary with identical value // ld.Clear(); string intlStr = intl.GetRandomString(MAX_LEN); ld.Add("keykey", intlStr); // 1st key for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } ld.Add("keyKey", intlStr); // 2nd key if (ld.Count != len + 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len + 2)); } // get Keys // ks = ld.Keys; if (ks.Count != ld.Count) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } arr = Array.CreateInstance(typeof(Object), len + 2); ks.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, keys[i]); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key", i, keys[i])); } } ind = Array.IndexOf(arr, "keykey"); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain {0} key", "keykey")); } ind = Array.IndexOf(arr, "keyKey"); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{0}\" key", "keyKey")); } // // Intl strings // // [] get Keys for dictionary filled with Intl strings // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } // // will use first half of array as values and second half as keys // ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(intlValues[i + len], intlValues[i]); } if (ld.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len)); } ks = ld.Keys; if (ks.Count != len) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } arr = Array.CreateInstance(typeof(Object), len); ks.CopyTo(arr, 0); for (int i = 0; i < arr.Length; i++) { ind = Array.IndexOf(arr, intlValues[i + len]); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key", i, intlValues[i + len])); } } // // [] Change dictionary and verify Keys // ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } if (ld.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len)); } ks = ld.Keys; if (ks.Count != len) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } ld.Remove(keys[0]); if (ld.Count != len - 1) { Assert.False(true, string.Format("Error, didn't remove element")); } if (ks.Count != len - 1) { Assert.False(true, string.Format("Error, Keys were not updated after removal")); } arr = Array.CreateInstance(typeof(Object), ld.Count); ks.CopyTo(arr, 0); ind = Array.IndexOf(arr, keys[0]); if (ind >= 0) { Assert.False(true, string.Format("Error, Keys still contains removed key " + ind)); } ld.Add(keys[0], "new item"); if (ld.Count != len) { Assert.False(true, string.Format("Error, didn't add element")); } if (ks.Count != len) { Assert.False(true, string.Format("Error, Keys were not updated after addition")); } arr = Array.CreateInstance(typeof(Object), ld.Count); ks.CopyTo(arr, 0); ind = Array.IndexOf(arr, keys[0]); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain added key ")); } ICollection icol1; ListDictionary Hd = new ListDictionary(); for (int i = 0; i < 10; i++) Hd.Add("key_" + i, "val_" + i); icol1 = Hd.Keys; if (Hd.SyncRoot != icol1.SyncRoot) { Assert.False(true, string.Format("Error, SyncRoot is not the same for ListDictionary's SyncRoot and ICollection.SyncRoot")); } // [] Run IEnumerable tests Hd = new ListDictionary(); String[] expectedKeys = new String[10]; for (int i = 0; i < 10; i++) { Hd.Add("key_" + i, "val_" + i); expectedKeys[i] = "key_" + i; } TestSupport.Collections.IEnumerable_Test iEnumerableTest; iEnumerableTest = new TestSupport.Collections.IEnumerable_Test(Hd.Keys, expectedKeys); if (!iEnumerableTest.RunAllTests()) { Assert.False(true, string.Format("Err_98382apeuie System.Collections.IEnumerable tests FAILED")); } }
public void Test01() { ListDictionary ld; IDictionaryEnumerator en; DictionaryEntry curr; // Enumerator.Current value DictionaryEntry de; // Enumerator.Entry value Object k; // Enumerator.Key value Object v; // Enumerator.Value // simple string values string[] values = { "a", "aa", "", " ", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; // [] ListDictionary GetEnumerator() //----------------------------------------------------------------- ld = new ListDictionary(); // [] for empty dictionary // en = ld.GetEnumerator(); string type = en.GetType().ToString(); if (type.IndexOf("Enumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not Enumerator")); } // // MoveNext should return false // bool res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); // // [] for Filled dictionary // for (int i = 0; i < values.Length; i++) { ld.Add(keys[i], values[i]); } en = ld.GetEnumerator(); type = en.GetType().ToString(); if (type.IndexOf("Enumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not Enumerator")); } // // MoveNext should return true // for (int i = 0; i < ld.Count; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } curr = (DictionaryEntry)en.Current; de = en.Entry; // //enumerator enumerates in different than added order // so we'll check Contains // if (!ld.Contains(curr.Key.ToString())) { Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i)); } if (!ld.Contains(en.Key.ToString())) { Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i)); } if (!ld.Contains(de.Key.ToString())) { Assert.False(true, string.Format("Error, Current dictionary doesn't contain Entry.Key from enumerator", i)); } if (String.Compare(ld[curr.Key.ToString()].ToString(), curr.Value.ToString()) != 0) { Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i)); } if (String.Compare(ld[de.Key.ToString()].ToString(), de.Value.ToString()) != 0) { Assert.False(true, string.Format("Error, Entry.Value for current Entry.Key is different in dictionary", i)); } if (String.Compare(ld[en.Key.ToString()].ToString(), en.Value.ToString()) != 0) { Assert.False(true, string.Format("Error, En-tor.Value for current En-tor.Key is different in dictionary", i)); } // while we didn't MoveNext, Current should return the same value DictionaryEntry curr1 = (DictionaryEntry)en.Current; if (!curr.Equals(curr1)) { Assert.False(true, string.Format("Error, second call of Current returned different result", i)); } DictionaryEntry de1 = en.Entry; if (!de.Equals(de1)) { Assert.False(true, string.Format("Error, second call of Entry returned different result", i)); } } // next MoveNext should bring us outside of the collection // res = en.MoveNext(); res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); // // Attempt to get Entry should result in exception // Assert.Throws<InvalidOperationException>(() => { de = en.Entry; }); // // Attempt to get Key should result in exception // Assert.Throws<InvalidOperationException>(() => { k = en.Key; }); // // Attempt to get Value should result in exception // Assert.Throws<InvalidOperationException>(() => { v = en.Value; }); en.Reset(); // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); // // Attempt to get Entry should result in exception // Assert.Throws<InvalidOperationException>(() => { de = en.Entry; }); // // [] Modify dictionary when enumerating // if (ld.Count < 1) { for (int i = 0; i < values.Length; i++) { ld.Add(keys[i], values[i]); } } en = ld.GetEnumerator(); res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false")); } curr = (DictionaryEntry)en.Current; de = en.Entry; k = en.Key; v = en.Value; int cnt = ld.Count; ld.Remove(keys[0]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove item with 0th key")); } // will return just removed item DictionaryEntry curr2 = (DictionaryEntry)en.Current; if (!curr.Equals(curr2)) { Assert.False(true, string.Format("Error, current returned different value after modification")); } // will return just removed item DictionaryEntry de2 = en.Entry; if (!de.Equals(de2)) { Assert.False(true, string.Format("Error, Entry returned different value after modification")); } // will return just removed item Object k2 = en.Key; if (!k.Equals(k2)) { Assert.False(true, string.Format("Error, Key returned different value after modification")); } // will return just removed item Object v2 = en.Value; if (!v.Equals(v2)) { Assert.False(true, string.Format("Error, Value returned different value after modification")); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); // exception expected Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); // // [] Modify dictionary after enumerated beyond the end // ld.Clear(); for (int i = 0; i < values.Length; i++) { ld.Add(keys[i], values[i]); } en = ld.GetEnumerator(); for (int i = 0; i < ld.Count; i++) { en.MoveNext(); } curr = (DictionaryEntry)en.Current; de = en.Entry; k = en.Key; v = en.Value; cnt = ld.Count; ld.Remove(keys[0]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove item with 0th key")); } // will return just removed item DictionaryEntry curr3 = (DictionaryEntry)en.Current; if (!curr.Equals(curr3)) { Assert.False(true, string.Format("Error, current returned different value after modification")); } // will return just removed item de2 = en.Entry; if (!de.Equals(de2)) { Assert.False(true, string.Format("Error, Entry returned different value after modification")); } // will return just removed item k2 = en.Key; if (!k.Equals(k2)) { Assert.False(true, string.Format("Error, Key returned different value after modification")); } // will return just removed item v2 = en.Value; if (!v.Equals(v2)) { Assert.False(true, string.Format("Error, Value returned different value after modification")); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); // exception expected Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); ///////////////////////////////////// //// Code coverage // // [] Call IEnumerable.GetEnumerator() // en = ld.GetEnumerator(); IEnumerator en2 = ((IEnumerable)ld).GetEnumerator(); if (en2 == null) { Assert.False(true, string.Format("Error, enumerator was null")); } }
public void Test01() { ListDictionary ld; // [] ListDictionary is constructed as expected //----------------------------------------------------------------- ld = new ListDictionary(); if (ld == null) { Assert.False(true, string.Format("Error, dictionary is null after default ctor")); } if (ld.Count != 0) { Assert.False(true, string.Format("Error, Count = {0} after default ctor", ld.Count)); } if (ld["key"] != null) { Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor")); } System.Collections.ICollection keys = ld.Keys; if (keys.Count != 0) { Assert.False(true, string.Format("Error, Keys contains {0} keys after default ctor", keys.Count)); } System.Collections.ICollection values = ld.Values; if (values.Count != 0) { Assert.False(true, string.Format("Error, Values contains {0} items after default ctor", values.Count)); } // // [] Add(string, string) // ld.Add("Name", "Value"); if (ld.Count != 1) { Assert.False(true, string.Format("Error, Count returned {0} instead of 1", ld.Count)); } if (String.Compare(ld["Name"].ToString(), "Value") != 0) { Assert.False(true, string.Format("Error, Item() returned unexpected value")); } // // [] Clear() // ld.Clear(); if (ld.Count != 0) { Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", ld.Count)); } if (ld["Name"] != null) { Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()")); } // // [] elements not overriding Equals() // ld.Clear(); Hashtable lbl = new Hashtable(); Hashtable lbl1 = new Hashtable(); ArrayList b = new ArrayList(); ArrayList b1 = new ArrayList(); ld.Add(lbl, b); ld.Add(lbl1, b1); if (ld.Count != 2) { Assert.False(true, string.Format("Error, Count returned {0} instead of 2", ld.Count)); } if (!ld.Contains(lbl)) { Assert.False(true, string.Format("Error, doesn't contain 1st special item")); } if (!ld.Contains(lbl1)) { Assert.False(true, string.Format("Error, doesn't contain 2nd special item")); } if (ld.Values.Count != 2) { Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", ld.Values.Count)); } ld.Remove(lbl1); if (ld.Count != 1) { Assert.False(true, string.Format("Error, failed to remove item")); } if (ld.Contains(lbl1)) { Assert.False(true, string.Format("Error, failed to remove special item")); } }