public void Add() { int count = 10; StringDictionary stringDictionary = new StringDictionary(); for (int i = 0; i < count; i++) { string key = "Key_" + i; string value = "Value_" + i; stringDictionary.Add(key, value); Assert.Equal(i + 1, stringDictionary.Count); Assert.True(stringDictionary.ContainsKey(key)); Assert.True(stringDictionary.ContainsValue(value)); Assert.Equal(value, stringDictionary[key]); } Assert.False(stringDictionary.ContainsValue(null)); stringDictionary.Add("nullkey", null); Assert.Equal(count + 1, stringDictionary.Count); Assert.True(stringDictionary.ContainsKey("nullkey")); Assert.True(stringDictionary.ContainsValue(null)); Assert.Null(stringDictionary["nullkey"]); }
public void ContainsKey_IsCaseInsensitive() { StringDictionary stringDictionary = new StringDictionary(); stringDictionary.Add("key", "value"); Assert.True(stringDictionary.ContainsKey("KEY")); Assert.True(stringDictionary.ContainsKey("kEy")); Assert.True(stringDictionary.ContainsKey("key")); }
public void Remove_DuplicateValues() { StringDictionary stringDictionary = new StringDictionary(); stringDictionary.Add("key1", "value"); stringDictionary.Add("key2", "value"); stringDictionary.Remove("key1"); Assert.Equal(1, stringDictionary.Count); Assert.False(stringDictionary.ContainsKey("key1")); Assert.True(stringDictionary.ContainsValue("value")); stringDictionary.Remove("key2"); Assert.Equal(0, stringDictionary.Count); Assert.False(stringDictionary.ContainsKey("key2")); Assert.False(stringDictionary.ContainsValue("value")); }
/// <summary> /// Binds the country dropdown list with countries retrieved /// from the .NET Framework. /// </summary> public void BindCountries() { StringDictionary dic = new StringDictionary(); List<string> col = new List<string>(); foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { RegionInfo ri = new RegionInfo(ci.Name); if (!dic.ContainsKey(ri.EnglishName)) dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant()); if (!col.Contains(ri.EnglishName)) col.Add(ri.EnglishName); } // Add custom cultures if (!dic.ContainsValue("bd")) { dic.Add("Bangladesh", "bd"); col.Add("Bangladesh"); } col.Sort(); ddlCountry.Items.Add(new ListItem("[Not specified]", "")); foreach (string key in col) { ddlCountry.Items.Add(new ListItem(key, dic[key])); } SetDefaultCountry(); }
/// <summary> /// Binds the country dropdown list with countries retrieved /// from the .NET Framework. /// </summary> public void BindCountries() { StringDictionary dic = new StringDictionary(); List<string> col = new List<string>(); foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { RegionInfo ri = new RegionInfo(ci.Name); if (!dic.ContainsKey(ri.EnglishName)) dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant()); if (!col.Contains(ri.EnglishName)) col.Add(ri.EnglishName); } // Add custom cultures if (!dic.ContainsValue("bd")) { dic.Add("Bangladesh", "bd"); col.Add("Bangladesh"); } col.Sort(); ddlCountry.Items.Add(new ListItem("[Not specified]", "")); foreach (string key in col) { ddlCountry.Items.Add(new ListItem(key, dic[key])); } if (ddlCountry.SelectedIndex == 0 && Request.UserLanguages != null && Request.UserLanguages[0].Length == 5) { ddlCountry.SelectedValue = Request.UserLanguages[0].Substring(3); SetFlagImageUrl(); } }
/// <summary> /// Replaces one or more placeholders in a string with the specified values. /// </summary> /// <param name="format">The composite format string.</param> /// <param name="args"> /// A string dictionary containing the placeholder names and values that /// they are to be replaced with. /// </param> /// <param name="date"> /// A <see cref="DateTime"/> object to format dates and times with. /// </param> /// <returns> /// A new string with the placeholders replaced by their values. /// </returns> public static string Format(string format, StringDictionary args, DateTime date) { if (format == null) { return(null); } if (args == null) { return(format); } var stringBuilder = new StringBuilder(format.Length); var i = 0; var c = '\0'; while (i < format.Length) { c = format[i]; i++; if (c == PlaceholderStart) { var end = format.IndexOf(PlaceholderEnd, i); if (end <= i) { var message = SR.ExpectedAtPos.With(PlaceholderEnd, i); throw new FormatException(message); } var placeholder = format.Substring(i, end - i); var value = args[placeholder]; if (!args.ContainsKey(placeholder)) { try { value = date.ToString(placeholder); } catch (Exception ex) { var message = SR.InvalidPlaceholder.With(placeholder); throw new FormatException(message, ex); } } stringBuilder.Append(RemoveInvalidFilenameChars(value)); i = end + 1; } else if (c == PlaceholderEscape) { if (i >= format.Length) { var message = SR.EndOfString.With(PlaceholderEscape); throw new FormatException(message); } stringBuilder.Append(format[i]); i++; } else { stringBuilder.Append(c); } } return(stringBuilder.ToString()); }
public string GetValue(string key) { return(sd.ContainsKey(key) ? sd[key] : "item not found"); }
/// <summary> /// This method checks if the PID file is stored on the disk and then terminates runaway processes if they exist. /// </summary> /// <param name="logger">Unused logger</param> public override void OnWrapperStarted() { // Read PID file from the disk int pid; if (System.IO.File.Exists(Pidfile)) { string pidstring; try { pidstring = System.IO.File.ReadAllText(Pidfile); } catch (Exception ex) { Logger.Error("Cannot read PID file from " + Pidfile, ex); return; } try { pid = Int32.Parse(pidstring); } catch (FormatException e) { Logger.Error("Invalid PID file number in '" + Pidfile + "'. The runaway process won't be checked", e); return; } } else { Logger.Warn("The requested PID file '" + Pidfile + "' does not exist. The runaway process won't be checked"); return; } // Now check the process Logger.DebugFormat("Checking the potentially runaway process with PID={0}", pid); Process proc; try { proc = Process.GetProcessById(pid); } catch (ArgumentException ex) { Logger.Debug("No runaway process with PID=" + pid + ". The process has been already stopped."); return; } // Ensure the process references the service String affiliatedServiceId; // TODO: This method is not ideal since it works only for vars explicitly mentioned in the start info // No Windows 10- compatible solution for EnvVars retrieval, see https://blog.gapotchenko.com/eazfuscator.net/reading-environment-variables StringDictionary previousProcessEnvVars = proc.StartInfo.EnvironmentVariables; String expectedEnvVarName = WinSWSystem.ENVVAR_NAME_SERVICE_ID; if (previousProcessEnvVars.ContainsKey(expectedEnvVarName)) { // StringDictionary is case-insensitive, hence it will fetch variable definitions in any case affiliatedServiceId = previousProcessEnvVars[expectedEnvVarName]; } else if (CheckWinSWEnvironmentVariable) { Logger.Warn("The process " + pid + " has no " + expectedEnvVarName + " environment variable defined. " + "The process has not been started by WinSW, hence it won't be terminated."); if (Logger.IsDebugEnabled) { //TODO replace by String.Join() in .NET 4 String[] keys = new String[previousProcessEnvVars.Count]; previousProcessEnvVars.Keys.CopyTo(keys, 0); Logger.DebugFormat("Env vars of the process with PID={0}: {1}", new Object[] { pid, String.Join(",", keys) }); } return; } else { // We just skip this check affiliatedServiceId = null; } // Check the service ID value if (CheckWinSWEnvironmentVariable && !ServiceId.Equals(affiliatedServiceId)) { Logger.Warn("The process " + pid + " has been started by Windows service with ID='" + affiliatedServiceId + "'. " + "It is another service (current service id is '" + ServiceId + "'), hence the process won't be terminated."); return; } // Kill the runaway process Logger.Warn("Stopping the runaway process (pid=" + pid + ") and its children."); ProcessHelper.StopProcessAndChildren(pid, this.StopTimeout, this.StopParentProcessFirst); }
public MDPStat BuildQuotientMDP(VerificationOutput VerificationOutput) { //return this; MDPStat toReturn = new MDPStat(Precision, MAX_DIFFERENCE); //todo change to set List <KeyValuePair <string, string> > BoundaryOneTransition = new List <KeyValuePair <string, string> >(); //todo change to set List <DistributionStat> ProbTransitions = new List <DistributionStat>(); Dictionary <string, List <DistributionStat> > GlobalProbTransitions = new Dictionary <string, List <DistributionStat> >(); StringDictionary <bool> visited = new StringDictionary <bool>(States.Count); List <KeyValuePair <HashSet <string>, MDPStateStat> > sccs = new List <KeyValuePair <HashSet <string>, MDPStateStat> >(); Dictionary <string, int> preorder = new Dictionary <string, int>(); Dictionary <string, int> lowlink = new Dictionary <string, int>(); //HashSet<string> scc_found = new HashSet<string>(); Stack <MDPStateStat> TaskStack = new Stack <MDPStateStat>(); //Dictionary<string, List<string>> OutgoingTransitionTable = new Dictionary<string, List<string>>(); Stack <MDPStateStat> stepStack = new Stack <MDPStateStat>(1024); visited.Add(InitState.ID, false); TaskStack.Push(InitState); //# Preorder counter int preor = 0; do { while (TaskStack.Count > 0) { MDPStateStat pair = TaskStack.Peek(); string v = pair.ID; if (visited.GetContainsKey(v) && visited.GetContainsKey(v)) { TaskStack.Pop(); continue; } if (!preorder.ContainsKey(v)) { preorder.Add(v, preor); preor++; } bool done = true; List <DistributionStat> list = pair.Distributions; List <MDPStateStat> nonProbTrans = new List <MDPStateStat>(); List <DistributionStat> ProbTrans = new List <DistributionStat>(); for (int i = 0; i < list.Count; i++) { if (list[i].IsTrivial()) { nonProbTrans.Add(list[i].States[0].Value); } else { ProbTrans.Add(list[i]); } } if (ProbTrans.Count > 0 && !GlobalProbTransitions.ContainsKey(v)) { GlobalProbTransitions.Add(v, ProbTrans); ProbTransitions.AddRange(ProbTrans); } for (int k = nonProbTrans.Count - 1; k >= 0; k--) { MDPStateStat step = nonProbTrans[k]; string tmp = step.ID; if (visited.ContainsKey(tmp)) { //if this node is still not visited if (!preorder.ContainsKey(tmp)) { //only put the first one to the work list stack. //if there are more than one node to be visited, //simply ignore them and keep its event step in the list. if (done) { TaskStack.Push(step); done = false; } } } else { visited.Add(tmp, false); //OutgoingTransitionTable.Add(tmp, new List<string>(8)); //only put the first one into the stack. if (done) { TaskStack.Push(step); done = false; } } } if (done) { int lowlinkV = preorder[v]; int preorderV = preorder[v]; bool selfLoop = false; for (int j = 0; j < nonProbTrans.Count; j++) { string w = nonProbTrans[j].ID; if (w == v) { selfLoop = true; } if (!visited.GetContainsKey(w)) { if (preorder[w] > preorderV) { lowlinkV = Math.Min(lowlinkV, lowlink[w]); } else { lowlinkV = Math.Min(lowlinkV, preorder[w]); } } else //in this case, there is a tau transition leading to an SCC; must add the transition into the toReturn automaton { BoundaryOneTransition.Add(new KeyValuePair <string, string>(v, w)); } } lowlink[v] = lowlinkV; TaskStack.Pop(); HashSet <string> scc = new HashSet <string>(); if (lowlinkV == preorderV) { scc.Add(v); visited.SetValue(v, true); while (stepStack.Count > 0 && preorder[stepStack.Peek().ID] > preorderV) { string s = stepStack.Pop().ID; scc.Add(s); visited.SetValue(s, true); } MDPStateStat newstate = new MDPStateStat(toReturn.States.Count.ToString()); if (scc.Count > 1 || (scc.Count == 1 && selfLoop)) { newstate.AddDistribution(new DistributionStat(Constants.TAU, newstate)); //add self loop: sun jun } sccs.Add(new KeyValuePair <HashSet <string>, MDPStateStat>(scc, newstate)); toReturn.AddState(newstate); if (scc.Contains(InitState.ID)) { toReturn.SetInit(newstate); } foreach (MDPStateStat state in TargetStates) { if (scc.Contains(state.ID)) { toReturn.AddTargetStates(newstate); } } } else { stepStack.Push(pair); } } } if (ProbTransitions.Count > 0) { foreach (DistributionStat step in ProbTransitions) { foreach (KeyValuePair <double, MDPStateStat> pair in step.States) { string stateID = pair.Value.ID; if (!visited.ContainsKey(stateID)) { TaskStack.Push(pair.Value); visited.Add(stateID, false); } } } ProbTransitions.Clear(); } } while (TaskStack.Count > 0); foreach (KeyValuePair <string, string> pair in BoundaryOneTransition) { MDPStateStat source = null; MDPStateStat target = null; foreach (KeyValuePair <HashSet <string>, MDPStateStat> sccstate in sccs) { if (sccstate.Key.Contains(pair.Key)) { source = sccstate.Value; } if (sccstate.Key.Contains(pair.Value)) { target = sccstate.Value; } } toReturn.AddDistribution(source.ID, new DistributionStat(Constants.TAU, target)); VerificationOutput.ReducedMDPTransitions++; } foreach (KeyValuePair <string, List <DistributionStat> > pair in GlobalProbTransitions) { MDPStateStat source = null; foreach (KeyValuePair <HashSet <string>, MDPStateStat> sccstate in sccs) { if (sccstate.Key.Contains(pair.Key)) { source = sccstate.Value; break; } } foreach (DistributionStat distribution in pair.Value) { DistributionStat disNew = new DistributionStat(distribution.Event); foreach (KeyValuePair <double, MDPStateStat> state in distribution.States) { foreach (KeyValuePair <HashSet <string>, MDPStateStat> sccstate in sccs) { if (sccstate.Key.Contains(state.Value.ID)) { disNew.AddProbStatePair(state.Key, sccstate.Value); VerificationOutput.ReducedMDPTransitions++; break; } } } toReturn.AddDistribution(source.ID, disNew); } } VerificationOutput.ReducedMDPStates = toReturn.States.Count; return(toReturn); }
public static string GetLocalePlaceholderDateString(string languagePreference) { return((dateFormats.ContainsKey(languagePreference)) ? dateFormats[languagePreference] : dateFormats["en-AU"]); }
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"; StringDictionary sd; string ind; 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 collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sd = new StringDictionary(); Console.WriteLine("1. Check for empty dictionary"); for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (sd.ContainsValue(values[i])) { iCountErrors++; Console.WriteLine("Err_0001_{0}, returned true for empty dictionary", i); } } Console.WriteLine("2. add simple strings and verify ContainsValue()"); strLoc = "Loc_002oo"; iCountTestcases++; cnt = values.Length; for (int i = 0; i < cnt; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != cnt) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sd.Count, cnt); } for (int i = 0; i < cnt; i++) { iCountTestcases++; if (!sd.ContainsValue(values[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, collection doesn't contain value \"{1}\"", i, values[i]); } iCountTestcases++; if (!sd.ContainsKey(keys[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}c, collection doesn't contain key \"{1}\"", i, keys[i]); } } Console.WriteLine("3. add intl strings and verify ContainsValue()"); strLoc = "Loc_003oo"; int len = values.Length; 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; } for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Add(intlValues[i+len], intlValues[i]); if (sd.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0003_{0}a, count is {1} instead of {2}", i, sd.Count, cnt+1); } iCountTestcases++; if (!sd.ContainsValue(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, collection doesn't contain value of new item", i); } iCountTestcases++; if (!sd.ContainsKey(intlValues[i+len])) { iCountErrors++; Console.WriteLine("Err_0003_{0}c, collection doesn't contain key of new item", i); } ind = intlValues[i+len]; iCountTestcases++; if (String.Compare(sd[ind], intlValues[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0003_{0}d, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i]); } } Console.WriteLine("4. add null string with non-null key and verify ContainsValue()"); strLoc = "Loc_004oo"; iCountTestcases++; cnt = sd.Count; string k = "keykey"; sd.Add(k, null); if (sd.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0004a, count is {1} instead of {2}", sd.Count, cnt+1); } iCountTestcases++; if (!sd.ContainsValue(null)) { iCountErrors++; Console.WriteLine("Err_0004b, dictionary doesn't contain value null"); } Console.WriteLine("5. Case sensitivity"); strLoc = "Loc_005oo"; iCountTestcases++; sd.Clear(); if (sd.Count != 0) { iCountErrors++; Console.WriteLine("Err_0005, count is {1} instead of {2} after Clear()", sd.Count, 0); } 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(); } sd.Clear(); for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Add(intlValues[i+len], intlValues[i]); if (sd.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0005_{0}a, count is {1} instead of {2}", i, sd.Count, cnt+1); } iCountTestcases++; if (!sd.ContainsValue(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0005_{0}b, collection doesn't contain value of new item", i); } iCountTestcases++; if (!sd.ContainsKey(intlValues[i+len])) { iCountErrors++; Console.WriteLine("Err_0005_{0}c, collection doesn't contain key of new item", i); } iCountTestcases++; if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i])) { iCountErrors++; Console.WriteLine("Err_0005_{0}d, collection contains lowercase value of new item", i); } iCountTestcases++; if ( !sd.ContainsKey(intlValuesLower[i+len])) { iCountErrors++; Console.WriteLine("Err_0005_{0}e, collection doesn't contain lowercase key of new item", i); } } } 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; } }
} // IsTarInstalled /// <summary> /// Generates the list of files to be deleted. /// Uses recursion to walk the entire directory tree. /// </summary> /// <param name="RemoveDir"></param> /// <param name="OutFile"></param> /// <param name="FileTable"></param> /// <param name="DeleteList"></param> public static void CreateDeletionFile(DirectoryInfo RemoveDir, StreamWriter OutFile, StringDictionary FileTable, ArrayList DeleteList, string DeleteCommand, Settings CurrentSettings) { try { // Iterate over all files foreach (DirectoryInfo di in RemoveDir.GetDirectories()) { CreateDeletionFile(di , OutFile, FileTable, DeleteList, DeleteCommand, CurrentSettings); //Recurse } foreach (FileInfo fi in RemoveDir.GetFiles()) { string FileName = fi.FullName; // If file isn't in list, add for deletion. // Don't delete the .tar/.tgz file if it's in the directory. if (!FileTable.ContainsKey(FileName.ToLower()) && !FileName.ToLower().EndsWith(".tar") && !FileName.ToLower().EndsWith(".tgz")) { DeleteList.Add(FileName); if (CurrentSettings.Verbose) { Console.WriteLine("Added for deletion: {0}", FileName); } //if OutFile.WriteLine(DeleteCommand + FileName); } //if } //foreach } //try catch (Exception e) { Console.WriteLine("Exception in CreateDeletionFile: {0}", e.ToString()); } //catch } //CreateDeletionFile()
/// ----------------------------------------------------------------------------- /// <summary> /// Infers the Default Namespace of the provided assembly /// </summary> /// <returns>The inferred Default Namespace of the provided assembly /// </returns> /// <remarks> /// Since there is no "Default Namespace" property of an Assembly, /// returns the greatest common namespace segment derived from all /// the Types and Resources within the assembly. For best accuracy, /// there should be at least one type or resource defined in the "default namespace" /// Code from: http://www.developersdex.com/gurus/articles/828.asp?Page=1 /// </remarks> public static string InferDefaultNamespace(this System.Reflection.Assembly asm) { //INSTANT C# NOTE: Commented this declaration since looping variables in 'foreach' loops are declared in the 'foreach' header in C#: // Type t = null; var ns = string.Empty; var lst = new StringDictionary(); var excludeNamespace = new List <string> { "jetbrains", "my" }; // Get all types in the assembly and add their namespaces to the list foreach (var t in asm.GetTypes()) { if (t.Namespace != null && !(lst.ContainsKey(t.Namespace.ToLower()))) { if (excludeNamespace.All(val => t.Namespace.ToLower().IndexOf(val, System.StringComparison.Ordinal) == -1)) { lst.Add(t.Namespace.ToLower(), t.Namespace); } } } // Get all resources in the assembly and add their namespaces to the list foreach (string res in asm.GetManifestResourceNames()) { if (!(lst.ContainsKey(res.ToLower()))) { lst.Add(res.ToLower(), res); } } if (lst.Count == 1) { // There is only one namespace in the assembly var arrValues = new string[1]; lst.Values.CopyTo(arrValues, 0); ns = arrValues[0]; } else if (lst.Count > 1) { // There are multiple namespaces in the assembly. // We must compare them now. string strShortestNs = string.Empty; //INSTANT C# NOTE: Commented this declaration since looping variables in 'foreach' loops are declared in the 'foreach' header in C#: // string nsTemp = null; // Get the shortest namespace as a starting point. // We are looking for common nodes in the namespaces, so // it is only logical to start with the shortest one. foreach (string nsTemp in lst.Keys) { if (string.IsNullOrEmpty(strShortestNs) && !string.IsNullOrEmpty(nsTemp)) { strShortestNs = string.Copy(lst[nsTemp]); } if ((nsTemp == null ? 0 : nsTemp.Length) < (strShortestNs.Length)) { if (nsTemp != null) { strShortestNs = string.Copy(lst[nsTemp]); } } } int i; var nodes = strShortestNs.Split('.'); var nodeStack = new ArrayList(); var blnContinue = true; // Begin comparing nodes: // For each node on the shortest namespace... for (i = 0; i < nodes.Length; i++) { // Compare it to the corresponding node in the other namespaces. foreach (string nsTemp in lst.Keys) { // There is no point in comparing the shortest namespace to itself. if (strShortestNs.ToLower() != nsTemp) { // Get the nodes of the namespace being compared. string[] nodesTemp = lst[nsTemp].Split('.'); if (nodesTemp.Length >= i) { if (nodes[i] != nodesTemp[i]) { // Has a different node. Nodes are no longer common. Exit for. blnContinue = false; break; } } else { // Has less nodes. Shouldn't happen, but if it does, exit for. blnContinue = false; break; } } } // If the node was acceptable if (blnContinue) { // Add it to the list of nodes of the common namespace nodeStack.Add(nodes[i]); } else { // Otherwise quit comparing break; } } // Assemble nodes to form greatest common Namespace. ns = string.Join(".", (string[])nodeStack.ToArray(typeof(string))); } return(ns); }
/// <summary> /// Constructor that takes a array of command line arguments as a parameter /// </summary> /// <param name="args">Command line arguments</param> public AppCmdLineArguments(string[] args) { Params = new StringDictionary(); string param = null; string[] argument_parts; foreach (string str in args) { argument_parts = splitter.Split(str, 3); switch (argument_parts.Length) { //. The argument has 3 parts like in example: /plugin:"Microsoft ASP.NET Analyzer" //. In the above example argument_parts[1] will have plugin //. and argument_parts[2] will have the actual string "Microsoft ASP.NET Analyzer" case 3: if (param != null) { if (!Params.ContainsKey(param)) { Params.Add(param, "true"); } } param = argument_parts[1]; if (!Params.ContainsKey(param)) { Trim(ref argument_parts[2]); Params.Add(param, argument_parts[2]); } param = null; break; //. The argument has only 2 parts like /trace //. argument_parts[1] will be set to trace case 2: if (param != null) { if (!Params.ContainsKey(param)) { Params.Add(param, "true"); } } param = argument_parts[1]; break; //. The argument has only one part esp in case of /trace true //. In the above example argument_parts[0] would be true so the previous option's value is set to true //. case 1: if (param != null) { if (!Params.ContainsKey(param)) { Trim(ref argument_parts[0]); Params.Add(param, argument_parts[0]); } } break; } } if (param != null) { if (!Params.ContainsKey(param)) { Params.Add(param, "true"); } } }
public bool Contains(string key ) { return(_parameters.ContainsKey(key)); }
/// <summary> /// Creates a <see cref="CommandLineArguments"/> object to parse /// command lines. /// </summary> /// <param name="args">The command line to parse.</param> internal CommandLineArguments(string[] args) { Regex splitter = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); Regex remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string parameter = null; string[] parts; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: -param1 value1 --param2 /param3:"Test-:-work" // /param4=happy -param5 '--=nice=--' foreach (string str in args) { // Do we have a parameter (starting with -, /, or --)? if (str.StartsWith("-") || str.StartsWith("/")) { // Look for new parameters (-,/ or --) and a possible // enclosed value (=,:) parts = splitter.Split(str, 3); switch (parts.Length) { // Found a value (for the last parameter found // (space separator)) case 1: if (parameter != null) { if (!namedParameters.ContainsKey(parameter)) { parts[0] = remover.Replace(parts[0], "$1"); namedParameters.Add( parameter, parts[0]); } parameter = null; } // else Error: no parameter waiting for a value // (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. With no // value, set it to true. if (parameter != null) { if (!namedParameters.ContainsKey(parameter)) { namedParameters.Add(parameter, "true"); } } parameter = parts[1]; break; // parameter with enclosed value case 3: // The last parameter is still waiting. With no // value, set it to true. if (parameter != null) { if (!namedParameters.ContainsKey(parameter)) { namedParameters.Add(parameter, "true"); } } parameter = parts[1]; // Remove possible enclosing characters (",') if (!namedParameters.ContainsKey(parameter)) { parts[2] = remover.Replace(parts[2], "$1"); namedParameters.Add(parameter, parts[2]); } parameter = null; break; } } else { unnamedParameters.Add(str); } } // In case a parameter is still waiting if (parameter != null) { if (!namedParameters.ContainsKey(parameter)) { namedParameters.Add(parameter, "true"); } } }
protected object GetEntity(IDataReader reader, Type t) { object obj = Activator.CreateInstance(t); //object obj = new t(); StringDictionary columnsNames = new StringDictionary(); DataTable dt = reader.GetSchemaTable(); //--------------------------------- ProfilesEntity profile = null; string columnname; for (int i = 0; i < reader.FieldCount; i++) { columnname = reader.GetName(i); if (!columnsNames.ContainsKey(columnname)) { columnsNames.Add(columnname, null); PropertyInfo myPropInfo; myPropInfo = t.GetProperty(columnname); if (reader[columnname] != DBNull.Value && myPropInfo != null) { //myPropInfo.SetValue(obj, Convert.ChangeType(reader[columnname], myPropInfo.PropertyType), null); if (myPropInfo.PropertyType.BaseType == typeof(System.Enum)) { //int intVal = Convert.ToInt32(attr.Value); myPropInfo.SetValue(obj, Enum.Parse(myPropInfo.PropertyType, reader[columnname].ToString()), null); //Enum.Parse(typeof(myPropInfo.), "FirstName"); } /* * else if (reader[columnname].GetType() == typeof(Byte[])) * { * byte[] buf = (byte[])reader[columnname]; * myPropInfo.SetValue(obj, Convert.ChangeType(OurSerializer.Deserialize(buf), myPropInfo.PropertyType), null); * }*/ else if (columnname.ToLower() == "extradata") { string buf = (string)reader[columnname]; myPropInfo.SetValue(obj, Convert.ChangeType(OurSerializer.Deserialize(buf), myPropInfo.PropertyType), null); } else { myPropInfo.SetValue(obj, Convert.ChangeType(reader[columnname], myPropInfo.PropertyType), null); } } else { if (columnname.ToLower() == "propertynames") { if (profile == null) { profile = new ProfilesEntity(); } if (reader["PropertyNames"] != DBNull.Value) { profile.PropertyNames = (string)reader["PropertyNames"]; } } else if (columnname.ToLower() == "propertyvaluesstring") { if (profile == null) { profile = new ProfilesEntity(); } if (reader["PropertyValuesString"] != DBNull.Value) { profile.PropertyValuesString = (string)reader["PropertyValuesString"]; } } } } } if (profile != null) { PropertyInfo myPropInfo = t.GetProperty("Profile"); if (myPropInfo != null) { //------------------------------------------------------------- object objProfile = Activator.CreateInstance(myPropInfo.PropertyType); //------------------------------------------------------------- //------------------------------------------------------------- ProfilesEntity Tempprofile = (ProfilesEntity)objProfile; Tempprofile.PropertyNames = profile.PropertyNames; Tempprofile.PropertyValuesString = profile.PropertyValuesString; //------------------------------------------------------------- ProfileBuilder.ParseProfileData(Tempprofile.PropertyNames, Tempprofile.PropertyValuesString, Tempprofile.PropertyValueCollection); //------------------------------------------------------------- myPropInfo.SetValue(obj, objProfile, null); //------------------------------------------------------------- } } //--------------------------------- return(obj); }
//--------------------------------------------------------- //LoadList //--------------------------------------------------------- public void LoadList() { StringDictionary tempDictionary = new StringDictionary(); List <MessagesEntity> arabicList = null; List <MessagesEntity> englishList = null; //-------------------------------------------------------------------- Languages langID = Languages.Unknowen; if (!string.IsNullOrEmpty(Request.QueryString["lang"])) { langID = (Languages)Convert.ToInt32(Request.QueryString["lang"]); } else { if (SiteSettings.Languages_HasMultiLanguages) { langID = (Languages)Convert.ToInt32(ddlLanguages.SelectedValue); } } //-------------------------------------------------------------------- int typeID = 0; if (!string.IsNullOrEmpty(Request.QueryString["type"])) { typeID = Convert.ToInt32(Request.QueryString["type"]); } else { if (currentModule.HasType) { typeID = Convert.ToInt32(ddlType.SelectedValue); } } //-------------------------------------------------------------------- if (SiteSettings.Languages_HasMultiLanguages && langID == Languages.Unknowen) { messagesList = MessagesFactory.ExportData(ModuleTypeID, -1, Languages.Ar, typeID, -1, false, false, false, OwnerID); foreach (MessagesEntity msg in messagesList) { tempDictionary.Add(msg.MessageID.ToString(), null); } //------------------------------------------ englishList = MessagesFactory.ExportData(ModuleTypeID, -1, Languages.En, typeID, -1, false, false, false, OwnerID); foreach (MessagesEntity msg in englishList) { if (!tempDictionary.ContainsKey(msg.MessageID.ToString())) { messagesList.Add(msg); } } } //------------------------------------------------------------------- else { messagesList = MessagesFactory.ExportData(ModuleTypeID, -1, langID, typeID, -1, false, false, false, OwnerID); foreach (MessagesEntity msg in messagesList) { tempDictionary.Add(msg.MessageID.ToString(), null); } } //------------------------------------------------------------------- }
/// <summary> /// Takes a Tab ID and builds the url for get the desidered page (non default) /// containing the application path, portal alias, tab ID, and language. /// </summary> /// <param name="targetPage">Linked page</param> /// <param name="pageID">ID of the page</param> /// <param name="modID">ID of the module</param> /// <param name="culture">Client culture</param> /// <param name="customAttributes">Any custom attribute that can be needed. Use the following format...single attribute: paramname--paramvalue . Multiple attributes: paramname--paramvalue/paramname2--paramvalue2/paramname3--paramvalue3 </param> /// <param name="currentAlias">Current Alias</param> /// <param name="urlKeywords">Add some keywords to uniquely identify this tab. Usual source is UrlKeyword from TabSettings.</param> public override string BuildUrl(string targetPage, int pageID, int modID, CultureInfo culture, string customAttributes, string currentAlias, string urlKeywords) { // Get Url Elements this helper method (Will either retrieve from cache or database) UrlElements urlElements = UrlBuilderHelper.GetUrlElements(pageID, _cacheMinutes); //2_aug_2004 Cory Isakson //Begin Navigation Enhancements if (!(targetPage.ToLower().EndsWith(_ignoreTargetPage.ToLower()))) // Do not modify URLs when working with TabLayout Administration Page { // if it is a placeholder it is not supposed to have any url if (urlElements.IsPlaceHolder) { return(string.Empty); } // if it is a tab link it means it is a link to an external resource //if (urlElements.TabLink.Length != 0) return urlElements.TabLink; if (urlElements.TabLink.Length != 0) { if (urlElements.TabLink.ToLower().Contains("http://") || urlElements.TabLink.ToLower().Contains("https://")) { return(urlElements.TabLink); } else { return("http://" + urlElements.TabLink); } } } //End Navigation Enhancements if (targetPage.StartsWith("~/")) { targetPage = targetPage.Substring(2); } //[email protected] - 2014/12/24 - Added for getting friendly url from cache PageUrl pageurl = GetCachePageUrl(pageID); string cacheUrl = string.Empty; if (pageurl != null && (targetPage.Equals(HttpUrlBuilder.DefaultPage) || targetPage.Equals("DesktopDefault.aspx"))) { if (PortalSettings.HasEnablePageFriendlyUrl(pageID, currentAlias)) { if (!string.IsNullOrEmpty(pageurl.PageFriendlyUrl)) { return(pageurl.PageFriendlyUrl); } } else { if (!string.IsNullOrEmpty(pageurl.PageNormalUrl)) { return(pageurl.PageNormalUrl); } } } StringBuilder sb = new StringBuilder(); // Obtain ApplicationPath if (targetPage.StartsWith("~/")) { sb.Append(UrlBuilderHelper.ApplicationPath); targetPage = targetPage.Substring(2); } sb.Append("/"); //if (!targetPage.EndsWith(".aspx")) //Images //{ // sb.Append(targetPage); // return sb.ToString(); //} HttpContext.Current.Trace.Warn("Target Page = " + targetPage); // Separate path // If page contains path, or it is not an aspx // or handlerFlag is not set: do not use handler if (!targetPage.Equals(HttpUrlBuilder.DefaultPage) && !targetPage.Equals("DesktopDefault.aspx")) { sb.Append(targetPage); // if !!targetPage.EndsWith(".aspx") it's an image. Return if (!targetPage.EndsWith(".aspx")) { return(sb.ToString()); } else { sb.Append("?"); // Add pageID to URL sb.Append("pageId="); sb.Append(pageID.ToString()); // Add Alias to URL if (_aliasInUrl) { sb.Append("&alias="); // changed for compatibility with handler sb.Append(currentAlias); } // Add ModID to URL if (modID > 0) { sb.Append("&mid="); sb.Append(modID.ToString()); } // Add Language to URL if (_langInUrl && culture != null) { sb.Append("&lang="); // changed for compatibility with handler sb.Append(culture.Name); // manu fix: culture.Name } // Add custom attributes if (customAttributes != null && customAttributes != string.Empty) { sb.Append("&"); customAttributes = customAttributes.ToString().Replace("/", "&"); customAttributes = customAttributes.ToString().Replace(_defaultSplitter, "="); sb.Append(customAttributes); } return(sb.ToString().Replace("&&", "&")); } } else // use handler { PortalSettings settings = PortalSettings.GetPortalSettingsbyPageID(pageID, currentAlias); var hasFriendUrl = false; if (settings.EnablePageFriendlyUrl) { PagesDB pages = new PagesDB(); //[email protected] - 2014/12/16 - Get friendlyUrl from database var friendlyURL = pages.GetFriendlyURl(pageID); //[email protected] - 2014/12/16 - Check friendlyUrl not null if (friendlyURL != "") { hasFriendUrl = true; sb.Append(friendlyURL).ToString(); } } string queryLeft = ""; string queryRigth = ""; // Add custom attributes #region custom attributes if (customAttributes != null && customAttributes != string.Empty) { var parts = customAttributes.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { try { var key = parts[i].Split('=')[0]; if (!(key.Equals("pageId") || key.Equals("pageID"))) { if (queryList.ContainsKey(key)) { var q = parts[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); queryRigth += HttpUtility.UrlEncode(q[0], System.Text.Encoding.GetEncoding(28591)) + "=" + HttpUtility.UrlEncode(q[1], System.Text.Encoding.GetEncoding(28591)) + "&"; } else { var q = parts[i].Split('='); queryLeft += HttpUtility.UrlEncode(q[0], System.Text.Encoding.GetEncoding(28591)) + "=" + HttpUtility.UrlEncode(q[1], System.Text.Encoding.GetEncoding(28591)) + "&"; } } } catch (Exception) { } } if (!string.IsNullOrEmpty(queryLeft)) { // If its null, all the attributes are at the end, else, should add the ones from the queryLeft queryLeft = queryLeft.Remove(queryLeft.Length - 1); queryLeft = queryLeft.Replace("+", "%20"); queryLeft = queryLeft.ToString().Replace("&", "/"); queryLeft = queryLeft.ToString().Replace("=", _defaultSplitter); } } #endregion if (!hasFriendUrl) { #region Existing Url Builing code // Add smarturl tag and if friendlyURL false if (!string.IsNullOrEmpty(_handlerFlag) && !settings.EnablePageFriendlyUrl) { sb.Append(_handlerFlag); sb.Append("/"); } // Add custom Keywords to the Url if (urlKeywords != null && urlKeywords != string.Empty) { sb.Append(urlKeywords); sb.Append("/"); } else { urlKeywords = urlElements.UrlKeywords; // Add custom Keywords to the Url if (urlKeywords != null && urlKeywords.Length != 0) { sb.Append(urlKeywords); sb.Append("/"); } } // Add Alias to URL if (_aliasInUrl) { sb.Append("alias"); sb.Append(_defaultSplitter + currentAlias); sb.Append("/"); } // Add Language to URL if (_langInUrl && culture != null) { sb.Append("lang"); sb.Append(_defaultSplitter + culture.Name); sb.Append("/"); } // Add ModID to URL if (modID > 0) { sb.Append("mid"); sb.Append(_defaultSplitter + modID.ToString()); sb.Append("/"); } if (!string.IsNullOrEmpty(queryLeft)) { sb.Append(queryLeft); sb.Append("/"); } //get setting from portalsettings //HttpContext.Item - add/update key all the codes are managed by this method //PortalSettings settings = PortalSettings.GetPortalSettingsbyPageID(Portal.PageID, Portal.UniqueID); //[email protected] - 2014/12/16 - Appends if EnableFrindlyURl is false if (!settings.EnablePageFriendlyUrl) { sb.Append(pageID); sb.Append("/"); } if (!string.IsNullOrEmpty(urlElements.PageName))// TODO : Need to fix page names rewrites { sb.Append(urlElements.PageName); } else if (!string.IsNullOrEmpty(urlElements.PageTitle)) { string PageName = urlElements.PageTitle; // Write page Hieranchy if (Hieranchy) { int parentId = 0; bool found = false; //Get the parent pageId of the actual pageId for (int i = 0; i < settings.DesktopPages.Count && !found; i++) { if (settings.DesktopPages[i].PageID == pageID) { parentId = settings.DesktopPages[i].ParentPageID; found = true; } } if (found) { bool exit = false; // while the parentId it's diferent of 0 or the parentId isn't in settings while (parentId != 0 && !exit) { found = false; // find the parent in the setting for (int i = 0; i < settings.DesktopPages.Count && !found; i++) { if (settings.DesktopPages[i].PageID == parentId) { PageName = UrlBuilderHelper.CleanNoAlphanumerics(settings.DesktopPages[i].PageName) + "/" + PageName; parentId = settings.DesktopPages[i].ParentPageID; found = true; } } // If the parent isn't in settings the loop should stop if (!found) { exit = true; } } } } sb.Append(PageName); } else { sb.Append(_friendlyPageName); } #endregion } // [email protected] - 2014/12/16 - // check friendly URL is enabled and requested file is exist physically or not. // If not exists and friendly url is enabled, the extension will be appended. if (settings.EnablePageFriendlyUrl && !System.IO.File.Exists(HttpContext.Current.Server.MapPath(sb.ToString())) && !_friendlyUrlNoExtension) { sb.Append(this._friendlyUrlExtension); } // Add the query at the end if (!string.IsNullOrEmpty(queryRigth)) { queryRigth = queryRigth.Remove(queryRigth.Length - 1); sb.Append("?" + queryRigth); } //[email protected] - 2014/12/24 - Modified for setting friendly url into cache var url = sb.ToString().Replace("//", "/"); if (settings.EnablePageFriendlyUrl) { SetCachePageUrl(pageID, string.Empty, url); } else { SetCachePageUrl(pageID, url, string.Empty); } return(url); } }
private void InitializeMappings() { using (ILogMethod method = Log.LogMethod(this.DYN_MODULE_NAME, "InitializeMappings")) { IDictionary<string, IMonitorHandler> handlerInstances = null; try { _handlerMappings = new StringDictionary<IMonitorHandler>(); handlerInstances = new StringDictionary<IMonitorHandler>(); foreach (var mappingType in _handlerMappingTypes.AsParallel()) { MonitorHandlerBase handler = null; string mappingTypeKey = mappingType.Value.FullName; if (handlerInstances.ContainsKey(mappingTypeKey)) { handler = handlerInstances[mappingTypeKey] as MonitorHandlerBase; } else { handler = Activator.CreateInstance(mappingType.Value, true) as MonitorHandlerBase; handlerInstances.Add(mappingTypeKey, handler); } if (handler == null) continue; if (!_handlerMappings.ContainsKey(mappingType.Key)) { _handlerMappings.Add(mappingType.Key, handler); } } const string faultKey = "-1_-1"; _faultHandler = _handlerMappings[faultKey]; } catch (Exception ex) { method.Exception(ex); } finally { if (handlerInstances != null) { handlerInstances.Clear(); handlerInstances = null; } } } }
/// <summary> /// Retrieves the arguments. /// </summary> /// <param name="args">An array with command line arguments.</param> /// <param name="bibformIn">Path to the localized bibform.</param> /// <param name="bibformOut">Path to the bibform output.</param> /// <param name="typedefs">Path to the xml file containing the definition for the different types.</param> static void ParseArguments(string[] args, ref string bibformIn, ref string typedefs, ref string bibformOut) { // Add all parameters to a string dictionary with the switch as key. StringDictionary dict = new StringDictionary(); for (int i = 0; i < args.Length; i++) { dict.Add(args[i].Substring(1, 1), args[i].Substring(3)); } // Initialize variables. bibformIn = ""; typedefs = ""; bibformOut = ""; // Indicates if the parameters are valid or not. bool valid = true; // Verify the type definitions parameter. if (dict.ContainsKey("t") == true) { if (File.Exists(dict["t"]) == true) { typedefs = dict["t"]; } else { Console.WriteLine("File with source type definitions does not exist (/t switch)."); valid = false; } } else { Console.WriteLine("No file with source type definitions specified (/t switch)."); valid = false; } // Verify the output parameter. if (dict.ContainsKey("o") == true) { if (File.Exists(dict["o"]) == false) { bibformOut = dict["o"]; } else { Console.WriteLine("Output file already exists (/o switch)."); valid = false; } } else { Console.WriteLine("No output file was specified (/o switch)."); valid = false; } // Verify the bibform parameter. if (dict.ContainsKey("l") == true) { if (File.Exists(dict["l"]) == true) { bibformIn = dict["l"]; } else { Console.WriteLine("Localized bibform file does not exist (/l switch)."); valid = false; } } // If there is an error in the parameters, show help functionality and quit. if (valid == false) { Console.WriteLine(); Console.WriteLine("Usage: BibType /t:typedefs /o:output [/l:bibform]"); Console.WriteLine(); Console.WriteLine(" /t:typedefs Path to the xml document containing the definition for the"); Console.WriteLine(" different source types."); Console.WriteLine(" the document and looks for it in the default directory."); Console.WriteLine(" /o:output Path to the output document that will be created."); Console.WriteLine(" /l:bibform Optional. Path to a localized bibform.xml which will be used"); Console.WriteLine(" to localize the output."); Environment.Exit(0); } }
private string RenderPosts(List<Post> posts, StringDictionary settings) { if (posts.Count == 0) { //HttpRuntime.Cache.Insert("widget_recentposts", "<p>" + Resources.labels.none + "</p>"); return "<p>" + Resources.labels.none + "</p>"; } StringBuilder sb = new StringBuilder(); sb.Append("<ul class=\"recentPosts\" id=\"recentPosts\">"); bool showComments = DEFAULT_SHOW_COMMENTS; bool showRating = DEFAULT_SHOW_RATING; if (settings.ContainsKey("showcomments")) { bool.TryParse(settings["showcomments"], out showComments); } if (settings.ContainsKey("showrating")) { bool.TryParse(settings["showrating"], out showRating); } foreach (Post post in posts) { if (!post.IsVisibleToPublic) continue; string rating = Math.Round(post.Rating, 1).ToString(System.Globalization.CultureInfo.InvariantCulture); string link = "<li><a href=\"{0}\">{1}</a>{2}{3}</li>"; string comments = string.Format("<span>{0}: {1}</span>", Resources.labels.comments, post.ApprovedComments.Count); if(BlogSettings.Instance.ModerationType == BlogSettings.Moderation.Disqus) comments = string.Format("<span><a href=\"{0}#disqus_thread\">{1}</a></span>", post.PermaLink, Resources.labels.comments); string rate = string.Format("<span>{0}: {1} / {2}</span>", Resources.labels.rating, rating, post.Raters); if (!showComments || !BlogSettings.Instance.IsCommentsEnabled) comments = null; if (!showRating || !BlogSettings.Instance.EnableRating) rate = null; if (post.Raters == 0) rating = Resources.labels.notRatedYet; sb.AppendFormat(link, post.RelativeLink, HttpUtility.HtmlEncode(post.Title), comments, rate); } sb.Append("</ul>"); //HttpRuntime.Cache.Insert("widget_recentposts", sb.ToString()); return sb.ToString(); }
void DoCheck(object obj) { ClientConfig ci = obj as ClientConfig; Host[] hosts = new Host[ci.HostCollection.Count]; ci.HostCollection.Values.CopyTo(hosts, 0); int interval = ci.PollingInterval * 1000; while (true) { StringBuilder sb = new StringBuilder(); foreach (Host host in hosts) { #region Remoting调用方式检测Host try { //若服务不可用,耗时比较长,需改用其他方式检测 string objectUri = "Kalman.Remoting.HostMonitorService"; HostMonitorService srv = RCHelper.Instance.GetWellKnownObject <HostMonitorService>(host.Url, objectUri); //Trace.WriteLine(srv.GetCurrentDate()); //HostMonitorService srv = (HostMonitorService)RemotingServices.Connect(typeof(HostMonitorService), string.Format("{0}/{1}", host.Url, objectUri)); //srv.GetCurrentDate(); sb.Append(host.Url); sb.Append("|"); } catch (Exception ex) { string key = string.Format("{0}|{1}", ci.Name, host.Name); lock (hostStateInfo.SyncRoot) { if (hostStateInfo.ContainsKey(key)) { hostStateInfo[key] = ex.Message; } else { hostStateInfo.Add(key, ex.Message); } } //Trace.WriteLine(key+"."+ex.Message); } #endregion #region //string[] ss = host.Url.TrimStart("tcp://".ToCharArray()).Split(':'); //string ip = ss[0]; //int port = int.Parse(ss[1]); //string errMsg = string.Empty; //bool flag = NetUtil.TestIpAndPort(ip, port, out errMsg); //if (flag) //{ // sb.Append(host.Url); // sb.Append("|"); //} //else //{ // string key = string.Format("{0}|{1}", ci.Name, host.Name); // lock (hostStateInfo.SyncRoot) // { // if (hostStateInfo.ContainsKey(key)) // hostStateInfo[key] = errMsg; // else // hostStateInfo.Add(key, errMsg); // } //} #endregion }//foreach string s = sb.ToString().TrimEnd('|'); //更新可用Host列表 lock (ht.SyncRoot) { if (ht.ContainsKey(ci.Name)) { ht[ci.Name] = s; } else { ht.Add(ci.Name, s); } } Thread.Sleep(interval); } }
// Constructor public Arguments(string[] args) { parameters = new StringDictionary(); Regex splitter = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); Regex remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string parameter = null; string[] parts; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: // -param1 value1 --param2 /param3:"Test-:-work" // /param4=happy -param5 '--=nice=--' foreach (string txt in args) { // Look for new parameters (-,/ or --) and a // possible enclosed value (=,:) parts = splitter.Split(txt, 3); switch (parts.Length) { // Found a value (for the last parameter // found (space separator)) case 1: if (parameter != null) { if (!parameters.ContainsKey(parameter)) { parts[0] = remover.Replace(parts[0], "$1"); parameters.Add(parameter, parts[0]); } parameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. // With no value, set it to true. if (parameter != null) { if (!parameters.ContainsKey(parameter)) parameters.Add(parameter, "true"); } parameter = parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. // With no value, set it to true. if (parameter != null) { if (!parameters.ContainsKey(parameter)) parameters.Add(parameter, "true"); } parameter = parts[1]; // Remove possible enclosing characters (",') if (!parameters.ContainsKey(parameter)) { parts[2] = remover.Replace(parts[2], "$1"); parameters.Add(parameter, parts[2]); } parameter = null; break; } } // In case a parameter is still waiting if (parameter != null) { if (!parameters.ContainsKey(parameter)) parameters.Add(parameter, "true"); } }
private static void EmitC99(TextWriter outputStream, string assemblyName, IEnumerable <ExportedMethod> exports) { // Emit header/preamble outputStream.WriteLine( @"// // Auto-generated by dnne-gen // #include <stdint.h> #include <dnne.h> // // Forward declarations // extern void* get_callable_managed_function( const char_t* dotnet_type, const char_t* dotnet_type_method, const char_t* dotnet_delegate_type); extern void* get_fast_callable_managed_function( const char_t* dotnet_type, const char_t* dotnet_type_method);"); // Emit string table outputStream.WriteLine( @" // // string constants // "); int count = 1; var map = new StringDictionary(); foreach (var method in exports) { if (map.ContainsKey(method.EnclosingTypeName)) { continue; } string id = $"t{count++}_name"; outputStream.WriteLine($"static const char_t* {id} = DNNE_STR(\"{method.EnclosingTypeName}, {assemblyName}\");"); map.Add(method.EnclosingTypeName, id); } // Emit the exports outputStream.WriteLine( @" // // exports // "); foreach (var export in exports) { // Create declaration and call signature. string delim = ""; var declsig = new StringBuilder(); var callsig = new StringBuilder(); for (int i = 0; i < export.ArgumentTypes.Count; ++i) { if (i > 0) { delim = ", "; } declsig.AppendFormat("{0}{1} {2}", delim, export.ArgumentTypes[i], export.ArgumentNames[i]); callsig.AppendFormat("{0}{1}", delim, export.ArgumentNames[i]); } // Special casing for void signature. if (declsig.Length == 0) { declsig.Append("void"); } // Special casing for void return. string returnStatementKeyword = "return "; if (export.ReturnType.Equals("void")) { returnStatementKeyword = string.Empty; } string callConv = GetCallConv(export.CallingConvention); string classNameConstant = map[export.EnclosingTypeName]; Debug.Assert(!string.IsNullOrEmpty(classNameConstant)); // Generate the acquire managed function based on the export type. string acquireManagedFunction; if (export.Type == ExportType.Export) { acquireManagedFunction = $@"const char_t* methodName = DNNE_STR(""{export.MethodName}""); const char_t* delegateType = DNNE_STR(""{export.EnclosingTypeName}+{export.MethodName}Delegate, {assemblyName}""); {export.ExportName}_ptr = get_callable_managed_function({classNameConstant}, methodName, delegateType);"; } else { Debug.Assert(export.Type == ExportType.UnmanagedCallersOnly); acquireManagedFunction = $@"const char_t* methodName = DNNE_STR(""{export.MethodName}""); {export.ExportName}_ptr = get_fast_callable_managed_function({classNameConstant}, methodName);"; } outputStream.WriteLine( $@"// Computed from {export.EnclosingTypeName}{Type.Delimiter}{export.MethodName} static {export.ReturnType} ({callConv}* {export.ExportName}_ptr)({declsig}); DNNE_API {export.ReturnType} {callConv} {export.ExportName}({declsig}) {{ if ({export.ExportName}_ptr == NULL) {{ {acquireManagedFunction} }} {returnStatementKeyword}{export.ExportName}_ptr({callsig}); }} "); }
static void Main() { StringDictionary myDict = new StringDictionary(); myDict.Add("One", "This"); myDict.Add("Two", "is"); myDict.Add("Three", "String"); myDict.Add("Four", "Dictionary"); myDict.Add("Five", "Demo"); myDict.Add("Six", "using"); myDict.Add("Seven", "System"); myDict.Add("Eight", "Collections"); myDict.Add("Nine", "Specialized"); foreach (DictionaryEntry item in myDict) { Console.WriteLine("Keys : {0} Values : {1}", item.Key, item.Value); } Console.WriteLine("--------------"); Console.WriteLine("Elements after copy to in myArr :"); DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count]; myDict.CopyTo(myArr, 0); foreach (DictionaryEntry de in myArr) { Console.WriteLine("Keys : {0} Values : {1}", de.Key, de.Value); } Console.WriteLine("-------------------"); Console.WriteLine("Checks for provided key and value :"); if (myDict.ContainsKey("Six")) { Console.WriteLine("StringDictionary myDict contains the key"); } else { Console.WriteLine("StringDictionary myDict does not contain the key"); } if (myDict.ContainsValue("Demo")) { Console.WriteLine("StringDictionary myDict contains the value"); } else { Console.WriteLine("StringDictionary myDict does not contain the vlaue"); } Console.WriteLine("-----------------"); myDict.Remove("Nine"); Console.WriteLine("Elements after Remove in StringDictionary"); Console.WriteLine("The number of key/value pairs are : " + myDict.Count); foreach (DictionaryEntry a in myDict) { Console.WriteLine("Keys : {0} Values : {1}", a.Key, a.Value); } Console.WriteLine("------------------"); Console.WriteLine("Values in StringDictionary :"); foreach (string val in myDict.Values) { Console.WriteLine(val); } Console.WriteLine("Keys in StringDictionary :"); foreach (string val in myDict.Keys) { Console.WriteLine(val); } }
public override bool ContainsKey(string key) { return(_dict.ContainsKey(key)); }
/// <summary> /// Wrapper around the object holding the application configuration settings extracted /// from the App.Config file. /// </summary> /// <param name="key">The name of the configuration setting wanted.</param> /// <returns>The value of the configuration setting.</returns> public static string GetConfigSetting(string key) { try { if (m_appConfigSettings != null && m_appConfigSettings.ContainsKey(key)) { return(m_appConfigSettings[key]); } else { string setting = ConfigurationManager.AppSettings[key]; if (!setting.IsNullOrBlank()) { if (setting.StartsWith(ENCRYPTED_SETTING_PREFIX)) { logger.Debug("Decrypting appSetting " + key + "."); X509Certificate2 encryptedSettingsCertificate = GetEncryptedSettingsCertificate(); if (encryptedSettingsCertificate != null) { if (encryptedSettingsCertificate.HasPrivateKey) { logger.Debug("Private key on encrypted settings certificate is available."); setting = setting.Substring(2); byte[] encryptedBytes = Convert.FromBase64String(setting); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)encryptedSettingsCertificate.PrivateKey; byte[] plainTextBytes = rsa.Decrypt(encryptedBytes, false); setting = Encoding.ASCII.GetString(plainTextBytes); logger.Debug("Successfully decrypted appSetting " + key + "."); } else { throw new ApplicationException( "Could not access private key on encrypted settings certificate."); } } else { throw new ApplicationException( "Could not load the encrypted settings certificate to decrypt setting " + key + "."); } } m_appConfigSettings[key] = setting; return(setting); } else { return(null); } } } catch (Exception excp) { logger.Error("Exception AppState.GetSetting. " + excp.Message); throw; } }
protected override void SearchInternal(string artist, string album, AlbumArtDownloader.Scripts.IScriptResults results) { //Add the pattern used to the history list. CustomSettingsUI.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.DataBind, new System.Threading.ThreadStart(delegate { ((LocalFilesSourceSettings)CustomSettingsUI).mSearchPathPatternBox.AddPatternToHistory(); })); //Avoid duplicates StringDictionary addedFiles = new StringDictionary(); string pathPattern = GetSearchPath(artist, album); foreach (string alternate in pathPattern.Split('|')) { int? embeddedIndex = null; string unembeddedPathPattern = alternate; if (EmbeddedArtHelpers.IsEmbeddedArtPath(alternate)) { //TODO: Allow a pattern to specify multiple embedded images as "<?>" or similar. int i; EmbeddedArtHelpers.SplitToFilenameAndIndex(alternate, out unembeddedPathPattern, out i); embeddedIndex = i; } //Match path with wildcards foreach (string filename in Common.ResolvePathPattern(unembeddedPathPattern)) { if (!addedFiles.ContainsKey(filename)) //Don't re-add a file that's already been added { addedFiles.Add(filename, null); if (embeddedIndex.HasValue) { //Read embedded image from file, rather than the file itself as an image TagLib.File fileTags = null; try { fileTags = TagLib.File.Create(filename, TagLib.ReadStyle.None); var embeddedPictures = fileTags.Tag.Pictures; if (embeddedIndex.Value == -1) //Special value indicating "all embedded images" { for (int i = 0; i < embeddedPictures.Length; i++) { AddEmbeddedPictureToResults(results, embeddedPictures, i, filename); } } else if (embeddedPictures.Length > embeddedIndex.Value) { //Found the embedded image AddEmbeddedPictureToResults(results, embeddedPictures, embeddedIndex.Value, filename); } else { System.Diagnostics.Trace.WriteLine("Skipping file missing specified embedded image in local file search: " + EmbeddedArtHelpers.GetEmbeddedFilePath(filename, embeddedIndex.Value)); } } catch (Exception e) { System.Diagnostics.Trace.WriteLine("Skipping unreadable embedded image from file in local file search: " + EmbeddedArtHelpers.GetEmbeddedFilePath(filename, embeddedIndex.Value)); System.Diagnostics.Trace.Indent(); System.Diagnostics.Trace.WriteLine(e.Message); System.Diagnostics.Trace.Unindent(); } finally { if (fileTags != null) { fileTags.Mode = TagLib.File.AccessMode.Closed; } } } else { //Each filename is potentially an image, so try to load it try { IntPtr hBitmap; int status = GdipCreateBitmapFromFile(filename, out hBitmap); GdipDisposeImage(new HandleRef(this, hBitmap)); if (status == 0) { //Successfully opened as image //Create an in-memory copy so that the bitmap file isn't in use, and can be replaced byte[] fileBytes = File.ReadAllBytes(filename); //Read the file, closing it after use Bitmap bitmap = new Bitmap(new MemoryStream(fileBytes)); //NOTE: Do not dispose of MemoryStream, or it will cause later saving of the bitmap to throw a generic GDI+ error (annoyingly) results.Add(bitmap, Path.GetFileName(filename), filename, bitmap.Width, bitmap.Height, null); } else { System.Diagnostics.Trace.WriteLine("Skipping non-bitmap file in local file search: " + filename); } } catch (Exception e) { System.Diagnostics.Trace.WriteLine("Skipping unreadable file in local file search: " + filename); System.Diagnostics.Trace.Indent(); System.Diagnostics.Trace.WriteLine(e.Message); System.Diagnostics.Trace.Unindent(); } } } } } }
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"; StringDictionary sd; 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++; sd = new StringDictionary(); Console.WriteLine("1. Remove() from empty dictionary"); iCountTestcases++; if (sd.Count > 0) { sd.Clear(); } for (int i = 0; i < keys.Length; i++) { sd.Remove(keys[0]); } Console.WriteLine("2. Remove() on filled dictionary"); strLoc = "Loc_002oo"; int len = values.Length; iCountTestcases++; sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sd.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Remove(keys[i]); if (sd.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0002b_{0}, didn't remove element with {0} key", i); } iCountTestcases++; if (sd.ContainsValue(values[i])) { iCountErrors++; Console.WriteLine("Err_0002c_{0}, removed wrong value", i); } iCountTestcases++; if (sd.ContainsKey(keys[i])) { iCountErrors++; Console.WriteLine("Err_0002d_{0}, removed wrong value", i); } } Console.WriteLine("3. Remove() on dictionary with duplicate values "); strLoc = "Loc_003oo"; iCountTestcases++; sd.Clear(); string intlStr = intl.GetString(MAX_LEN, true, true, true); sd.Add("keykey1", intlStr); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } sd.Add("keykey2", intlStr); if (sd.Count != len + 2) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sd.Count, len + 2); } iCountTestcases++; sd.Remove("keykey2"); if (!sd.ContainsValue(intlStr)) { iCountErrors++; Console.WriteLine("Err_0003b, removed both duplicates"); } if (sd.ContainsKey("keykey2")) { iCountErrors++; Console.WriteLine("Err_0003c, removed not given instance"); } if (!sd.ContainsKey("keykey1")) { iCountErrors++; Console.WriteLine("Err_0003d, removed wrong instance"); } Console.WriteLine("4. Remove() from dictionary with intl strings"); strLoc = "Loc_004oo"; 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; } sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(intlValues[i + len], intlValues[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0004a, count is {0} instead of {1}", sd.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Remove(intlValues[i + len]); if (sd.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0004b_{0}, didn't remove element with {0} key", i + len); } iCountTestcases++; if (sd.ContainsValue(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0004c_{0}, removed wrong value", i); } iCountTestcases++; if (sd.ContainsKey(intlValues[i + len])) { iCountErrors++; Console.WriteLine("Err_0004d_{0}, removed wrong key", i); } } Console.WriteLine("5. Case sensitivity"); strLoc = "Loc_005oo"; iCountTestcases++; sd.Clear(); string [] intlValuesUpper = new string [len]; for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToLower(); } for (int i = 0; i < len; i++) { intlValuesUpper[i] = intlValues[i + len].ToUpper(); } sd.Clear(); Console.WriteLine(" ... add Lowercased ..."); for (int i = 0; i < len; i++) { sd.Add(intlValues[i + len], intlValues[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0005a, count is {0} instead of {1}", sd.Count, len); } Console.WriteLine(" ... remove Uppercased ..."); for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Remove(intlValuesUpper[i]); if (sd.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0005b_{0}, didn't remove element with {0} lower key", i + len); } iCountTestcases++; if (sd.ContainsValue(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0005c_{0}, removed wrong value", i); } iCountTestcases++; if (sd.ContainsKey(intlValuesUpper[i])) { iCountErrors++; Console.WriteLine("Err_0005d_{0}, removed wrong key", i); } } Console.WriteLine("6. Remove(null)"); strLoc = "Loc_006oo"; iCountTestcases++; try { sd.Remove(null); iCountErrors++; Console.WriteLine("Err_0006a, ArgumentNullException expected"); } // catch (System.ArgumentNullException e) { Console.WriteLine("expected exception: {0}", e.ToString()); } 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); } }
/// <summary> /// 解析命令行参数 /// </summary> /// <param name="value">值</param> /// <returns>一个命令行参数字符串字典对象</returns> public static StringDictionary ParseCommandlineParams(this string[] value) { var parameters = new StringDictionary(); var spliter = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); var remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string parameter = null; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--' foreach (string txt in value) { // Look for new parameters (-,/ or --) and a possible enclosed value (=,:) string[] parts = spliter.Split(txt, 3); switch (parts.Length) { // Found a value (for the last parameter found (space separator)) case 1: if (parameter != null) { if (!parameters.ContainsKey(parameter)) { parts[0] = remover.Replace(parts[0], "$1"); parameters.Add(parameter, parts[0]); } parameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. With no value, set it to true. if (parameter != null) { if (!parameters.ContainsKey(parameter)) { parameters.Add(parameter, "true"); } } parameter = parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. With no value, set it to true. if (parameter != null) { if (!parameters.ContainsKey(parameter)) { parameters.Add(parameter, "true"); } } parameter = parts[1]; // Remove possible enclosing characters (",') if (!parameters.ContainsKey(parameter)) { parts[2] = remover.Replace(parts[2], "$1"); parameters.Add(parameter, parts[2]); } parameter = null; break; } } // In case a parameter is still waiting if (parameter != null) { if (!parameters.ContainsKey(parameter)) { parameters.Add(parameter, "true"); } } return(parameters); }
public Arguments(string[] args) { _parameters = new StringDictionary(); var Spliter = new Regex(@"^-{1,2}|^/|=|:"); var Remover = new Regex(@"^['""]?(.*?)['""]?$"); string parameter = null; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: // -param1 value1 --param2 /param3:"Test-:-work" // /param4=happy -param5 '--=nice=--' foreach (var txt in args) { // Look for new parameters (-,/ or --) and a // possible enclosed value (=,:) var parts = Spliter.Split(txt, 3); switch (parts.Length) { // Found a value (for the last parameter found (space separator)) case 1: if (parameter != null) { if (!_parameters.ContainsKey(parameter)) { parts[0] = Remover.Replace(parts[0], "$1"); _parameters.Add(parameter, parts[0]); } parameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. With no value, set it to true. if (parameter != null) { if (!_parameters.ContainsKey(parameter)) { _parameters.Add(parameter, "true"); } } parameter = parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. With no value, set it to true. if (parameter != null) { if (!_parameters.ContainsKey(parameter)) { _parameters.Add(parameter, "true"); } } parameter = parts[1]; // Remove possible enclosing characters (",') if (!_parameters.ContainsKey(parameter)) { parts[2] = Remover.Replace(parts[2], "$1"); _parameters.Add(parameter, parts[2]); } parameter = null; break; } } // In case a parameter is still waiting if (parameter != null) { if (!_parameters.ContainsKey(parameter)) { _parameters.Add(parameter, "true"); } } }
/// <summary> /// Gets all the properties of the table. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static IList <PropertyInfo> GetWritableProperties(object obj, StringDictionary propsToExclude) { var props = ReflectionUtils.GetWritableProperties(obj.GetType(), delegate(PropertyInfo property) { var okToAdd = propsToExclude == null ? property.CanWrite : (property.CanWrite && !propsToExclude.ContainsKey(property.Name)); return(okToAdd); }); return(props); }
/// <summary> /// This method will obtain all the arguments and their values. Each /// argument will become the key in the returned StringDictionary, with the /// associated value being stored alongside the key. /// /// Examples: -param1 value1 --param2 /param3:"Test-:-work" /// /param4=happy -param5 '--=nice=--' /// </summary> /// <param name="args">String array of arguments</param> /// <returns>A StringDictionary collection of parameters and values</returns> public static StringDictionary GetArguments(string[] args) { // A String Key/Value Dictionary of all the parameters StringDictionary Parameters = new StringDictionary(); // Regular Expression to split a parameter and it's value Regex Spliter = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); // Regular Expression to remove all starting and trailing ' or " characters Regex Remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); // Stores the current parameter that is being worked upon String Parameter = null; // Holds all the parts of the split parameter/value string String[] Parts; // Loop over all the arguments foreach (String arg in args) { // Look for new parameters (-,/ or --) and a possible enclosed value (=,:) Parts = Spliter.Split(arg, 3); // Swtich between a parameter, value or other switch (Parts.Length) { // Found a value (for the last parameter found (space separator)) case 1: if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parts[0] = Remover.Replace(Parts[0], "$1"); Parameters.Add(Parameter, Parts[0]); } Parameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } Parameter = Parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } Parameter = Parts[1]; // Remove possible enclosing characters (",') if (!Parameters.ContainsKey(Parameter)) { Parts[2] = Remover.Replace(Parts[2], "$1"); Parameters.Add(Parameter, Parts[2]); } Parameter = null; break; } } // In case a parameter is still waiting if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } return(Parameters); }
public void Test01() { IntlStrings intl; StringDictionary sd; string ind; // 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(); // [] StringDictionary is constructed as expected //----------------------------------------------------------------- sd = new StringDictionary(); // [] check for empty dictionary // for (int i = 0; i < values.Length; i++) { if (sd.ContainsKey(keys[i])) { Assert.False(true, string.Format("Error, returned true for empty dictionary", i)); } } // [] add simple strings and verify ContainsKey() // cnt = values.Length; for (int i = 0; i < cnt; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != cnt) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt)); } for (int i = 0; i < cnt; i++) { // verify that collection contains all added items // if (!sd.ContainsValue(values[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value \"{1}\"", i, values[i])); } if (!sd.ContainsKey(keys[i])) { Assert.False(true, string.Format("Error, collection doesn't contain key \"{1}\"", i, keys[i])); } } // // Intl strings // [] add Intl strings and verify ContainsKey() // int len = values.Length; string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) { val = intl.GetRandomString(MAX_LEN); } intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) { caseInsensitive = true; } } // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // ind = intlValues[i + len]; if (String.Compare(sd[ind], intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i])); } } // // add null string with non-null key // [] add null string with non-null key and verify ContainsKey() // cnt = sd.Count; string k = "keykey"; sd.Add(k, null); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsKey(k)) { Assert.False(true, string.Format("Error, dictionary doesn't contain new key")); } // // [] Case sensitivity: search should be case-sensitive // sd.Clear(); if (sd.Count != 0) { Assert.False(true, string.Format("Error, count is {1} instead of {2} after Clear()", sd.Count, 0)); } string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } sd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added uppercase item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // verify that collection doesn't contains lowercase item // if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i])) { Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i)); } // key is case insensitive if (!sd.ContainsKey(intlValuesLower[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i)); } } // // call ContainsKey with null - ArgumentNullException expected // [] ContainsKey (null) // Assert.Throws <ArgumentNullException>(() => { sd.ContainsKey(null); }); }
private static void ArrangeExecutionSteps(this ExecutionStepDictionary execSteps, IDictionary<string, ExecutionStepCollection> messageWiseSteps, IDictionary<int, ExecutionStepCollection> groupedSteps) { using (ILogMethod method = Log.LogMethod(DYN_MODULE_NAME, "ArrangeExecutionSteps")) { try { Stack<IExecutionStep> st = new Stack<IExecutionStep>(); st.Push(execSteps.Start); IDictionary<string, IExecutionStep> steps = new StringDictionary<IExecutionStep>(); while (st.Count != 0) { IExecutionStep step = st.Pop(); int level = Math.Max(0, (from p in step.PrevSteps select p.Level).DefaultIfEmpty().Max()) + 1; if (!steps.ContainsKey(step.UniqueKey)) { step.Level = level; steps.Add(step.UniqueKey, step); } foreach (var step2 in step.NextSteps) { if (!steps.ContainsKey(step2.UniqueKey)) { st.Push(step2); } } } // last step execSteps.End.Level = Math.Max(0, (from p in steps.Values select p.Level).DefaultIfEmpty().Max()) + 1; // Ordered projects groupedSteps.Clear(); var orderedSteps = (from p in execSteps.Values orderby p.Level group p by p.Level); foreach (var orderedStep in orderedSteps) { ExecutionStepCollection stepsList = new ExecutionStepCollection(); groupedSteps.Add(orderedStep.Key, stepsList); foreach (var step in orderedStep) { stepsList.Add(step); } } } catch (Exception ex) { method.Exception(ex); } } }
void Button2Click(object sender, EventArgs e) { string filename = textBox1.Text; string enviroments = textBox2.Text; if (filename != "" && File.Exists(filename)) { int processflags = processflags = 0 | (int)ProcessCreationFlags.CREATE_SUSPENDED; IntPtr memptr = IntPtr.Zero; button2.Enabled = false; textBox3.Text = ""; GCHandle gchenv = new GCHandle(); if (enviroments.Length != 0) { if (enviroments.Length >= 3 && enviroments.Contains("=")) { textBox3.AppendText("Setting Environment Variables..."); try { char[] separator = "\r\n".ToCharArray(); string[] realvalues = enviroments.Split(separator); IntPtr newptr = memptr; bool unicode = false; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { processflags = processflags | (int)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT; unicode = true; } StringDictionary environmentVariables = new StringDictionary(); // add Environments of the parent to the child! foreach (System.Collections.DictionaryEntry entry in Environment.GetEnvironmentVariables()) { environmentVariables.Add((string)entry.Key, (string)entry.Value); } for (int i = 0; i < realvalues.Length; i++) { if (realvalues[i] != "" && realvalues[i].Contains("=")) { separator = "=".ToCharArray(); string[] currentvalue = realvalues[i].Split(separator); if (currentvalue[0] != "") { if (environmentVariables.ContainsKey(currentvalue[0])) { textBox3.AppendText("\r\n" + "The key whit the name " + currentvalue[0] + " is already on dictinonary!"); } else { environmentVariables.Add(currentvalue[0], currentvalue[1]); } } } } gchenv = GCHandle.Alloc(ToByteArray(environmentVariables, unicode), GCHandleType.Pinned); memptr = gchenv.AddrOfPinnedObject(); textBox3.AppendText("\r\n" + "Environment Variables setted!"); } catch (Exception exc) { textBox3.AppendText("\r\n" + exc.Message + "\r\n"); } } else { textBox3.AppendText("Invalid Environment Variables!" + "\r\n"); } } STARTUPINFO structure = new STARTUPINFO(); PROCESS_INFORMATION process_information = new PROCESS_INFORMATION(); IntPtr lpApplicationName = Marshal.StringToHGlobalUni(filename); try { CreateProcess(lpApplicationName, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, processflags, memptr, IntPtr.Zero, ref structure, ref process_information); hprocess = process_information.hProcess; hcthread = process_information.hThread; cprocessid = process_information.dwProcessId; if (gchenv.IsAllocated) { gchenv.Free(); } textBox3.AppendText("\r\n" + "Process created"); if (checkBox1.Checked) { textBox3.AppendText(" on suspended mode"); button3.Enabled = true; } textBox3.AppendText("!" + "\r\n"); } catch (Exception ex3) { textBox3.AppendText("\r\n" + "Failed to start process whit the message" + ex3.Message + "\r\n"); return; } checktimer = new System.Windows.Forms.Timer(); checktimer.Interval = 30; checktimer.Enabled = true; checktimer.Tick += new System.EventHandler(CheckStatut); if (checkBox2.Checked) { ProcModule.ModuleInfo[] modules = null; for (int k = 0; k < 500; k++) // try it 500 times! { LoopWhileModulesAreLoadedNt(process_information.dwProcessId, process_information.hThread); modules = ProcModule.GetModuleInfos((int)process_information.dwProcessId); if (modules != null && modules.Length > 0) { for (int i = 0; i < modules.Length; i++) { if (modules[i].baseName.ToLower().Contains("kernel32")) { targetkernel32 = modules[i]; break; } } } if (targetkernel32 != null) { break; } } if (targetkernel32 != null && targetkernel32.baseOfDll != IntPtr.Zero) { HookCreateProcess(targetkernel32.baseOfDll); } } if (checkBox3.Checked) { ProcModule.ModuleInfo[] modules = null; for (int k = 0; k < 50; k++) // try it 50 times! { LoopWhileModulesAreLoadedNt(process_information.dwProcessId, process_information.hThread); modules = ProcModule.GetModuleInfos((int)process_information.dwProcessId); if (modules != null && modules.Length > 0) { for (int i = 0; i < modules.Length; i++) { if (modules[i].baseName.Length > 10 && modules[i].baseName.ToLower().StartsWith("msvcr")) { targetMSVCR80 = modules[i]; break; } } } if (targetMSVCR80 != null) { break; } } if (targetMSVCR80 != null && targetMSVCR80.baseOfDll != IntPtr.Zero) { LogmemcpyInit(targetMSVCR80.baseOfDll); } } if (!checkBox1.Checked) { ResumeThread(process_information.hThread); } } else { textBox3.Text = "Please select a valid file!" + "\r\n"; } }
} //Main /// <summary> /// Invokes tar and builds the list of files in the archive which are not to be deleted. /// </summary> /// <param name="CurrentSettings"></param> public static void RunCommand(Settings CurrentSettings) { try { StringDictionary FileTable = new StringDictionary(); ArrayList DeleteList = new ArrayList(); string DeleteCommand = null; string sep = Path.DirectorySeparatorChar.ToString(); StreamWriter OutFile = new StreamWriter(CurrentSettings.DeletionScriptPath + Path.DirectorySeparatorChar + m_DeleteScriptName); switch (CurrentSettings.OSType) { case OSTypeEnum.Windows: { DeleteCommand = "@del /f "; break; } //case case OSTypeEnum.Unix: { OutFile.WriteLine("#!/bin/sh"); DeleteCommand = "rm -f -v "; break; } //case default: { throw new System.InvalidOperationException("Invalid OSTypeEnum value."); } //case } //switch string fullCommand = m_CommandArgument + CurrentSettings.TarFileName; // Check to see that tar is in path. Console.WriteLine(); // tar fails on the Mac. Try gnutar first. if (ToolInstalled("gnutar")) { m_CommandName = "gnutar"; Console.WriteLine("Found utility named: {0}", m_CommandName); } //if else { if (ToolInstalled("tar")) { m_CommandName = "tar"; Console.WriteLine("Found utility named: {0}", m_CommandName); Console.WriteLine("Tar utility may truncate file names on Mac OS X."); } //if else //No tar installed. { Console.WriteLine("No tar utility found. Exiting..."); System.InvalidOperationException ioe = new System.InvalidOperationException("No tar utility found."); throw ioe; } //else } ConsoleProcess toolProc = new ConsoleProcess(m_CommandName, fullCommand); Console.WriteLine(m_nl + "Starting command {0} {1}", m_CommandName, fullCommand); toolProc.Start(); // Wait for all IO to complete. toolProc.WaitForOutput(); // Get standard output and error (if any). string toolStdOut = toolProc.StandardOutputString; string toolStdError = toolProc.StandardErrorString; // If there is output to stdErr or a bad command exit code output warning. if (toolStdError != null || toolProc.BaseProcess.ExitCode != 0) { Console.WriteLine(m_nl + "*************************** Tool Error ***************************"); Console.WriteLine(m_nl + "Exit code: {0}", toolProc.BaseProcess.ExitCode); Console.WriteLine(m_nl + "Error in tool operation: {0}", toolStdError); System.Environment.ExitCode = toolProc.BaseProcess.ExitCode; return; } //if if (toolStdOut == null || toolStdOut.Length < 1) { Console.WriteLine(m_nl + "No file list generated, exiting"); System.Environment.ExitCode = 1; return; } //if Console.WriteLine(m_nl + "Finished {0} {1}, searching for files to delete ...", m_CommandName, m_CommandArgument); StringReader outputList = new StringReader(toolStdOut); string fname = null; string line = null; while (outputList.Peek() > -1) { line = outputList.ReadLine(); // Tar always outputs using forward slashes as the separator char. if (CurrentSettings.OSType == OSTypeEnum.Windows) { fname = CurrentSettings.SSCLIRootDirectory + sep + line.Replace("/", sep); } //if else { fname = CurrentSettings.SSCLIRootDirectory + sep + line; } //else if (!Directory.Exists(fname)) // filter out directory names { // There is a rare case where the table already contains the name. if (!FileTable.ContainsKey(fname.ToLower())) { FileTable.Add(fname.ToLower(), fname.ToLower()); } //if } //if } //while CreateDeletionFile(new DirectoryInfo(CurrentSettings.SSCLIRootDirectory), OutFile, FileTable, DeleteList, DeleteCommand, CurrentSettings); OutFile.Flush(); OutFile.Close(); // Make script executable on Unix if (CurrentSettings.OSType == OSTypeEnum.Unix) { System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(); si.FileName = "chmod"; si.Arguments = "+x " + CurrentSettings.DeletionScriptPath + Path.DirectorySeparatorChar + m_DeleteScriptName; si.UseShellExecute = false; System.Diagnostics.Process chmodproc= System.Diagnostics.Process.Start(si); chmodproc.WaitForExit(); } //if Console.WriteLine(m_nl + "*********************************************************"); Console.WriteLine("Deletion script file created at: {0}", CurrentSettings.DeletionScriptPath + Path.DirectorySeparatorChar + m_DeleteScriptName); } //try catch (Exception e) { Console.WriteLine("Exception in GenerateFile: {0}", e.ToString()); } //catch } //GenerateFile()
public MDP BuildQuotientMDP(VerificationOutput VerificationOutput) { //return this; MDP toReturn = new MDP(Precision, MAX_DIFFERENCE); //todo change to set List<KeyValuePair<string, string>> BoundaryOneTransition = new List<KeyValuePair<string, string>>(); //todo change to set List<Distribution> ProbTransitions = new List<Distribution>(); Dictionary<string, List<Distribution>> GlobalProbTransitions = new Dictionary<string, List<Distribution>>(); StringDictionary<bool> visited = new StringDictionary<bool>(States.Count); List<KeyValuePair<HashSet<string>, MDPState>> sccs = new List<KeyValuePair<HashSet<string>, MDPState>>(); Dictionary<string, int> preorder = new Dictionary<string, int>(); Dictionary<string, int> lowlink = new Dictionary<string, int>(); //HashSet<string> scc_found = new HashSet<string>(); Stack<MDPState> TaskStack = new Stack<MDPState>(); //Dictionary<string, List<string>> OutgoingTransitionTable = new Dictionary<string, List<string>>(); Stack<MDPState> stepStack = new Stack<MDPState>(1024); visited.Add(InitState.ID, false); TaskStack.Push(InitState); //# Preorder counter int preor = 0; do { while (TaskStack.Count > 0) { MDPState pair = TaskStack.Peek(); string v = pair.ID; if (visited.GetContainsKey(v) && visited.GetContainsKey(v)) { TaskStack.Pop(); continue; } if (!preorder.ContainsKey(v)) { preorder.Add(v, preor); preor++; } bool done = true; List<Distribution> list = pair.Distributions; List<MDPState> nonProbTrans = new List<MDPState>(); List<Distribution> ProbTrans = new List<Distribution>(); for (int i = 0; i < list.Count; i++) { if (list[i].IsTrivial()) { nonProbTrans.Add(list[i].States[0].Value); } else { ProbTrans.Add(list[i]); } } if (ProbTrans.Count > 0 && !GlobalProbTransitions.ContainsKey(v)) { GlobalProbTransitions.Add(v, ProbTrans); ProbTransitions.AddRange(ProbTrans); } for (int k = nonProbTrans.Count - 1; k >= 0; k--) { MDPState step = nonProbTrans[k]; string tmp = step.ID; if (visited.ContainsKey(tmp)) { //if this node is still not visited if (!preorder.ContainsKey(tmp)) { //only put the first one to the work list stack. //if there are more than one node to be visited, //simply ignore them and keep its event step in the list. if (done) { TaskStack.Push(step); done = false; } } } else { visited.Add(tmp, false); //OutgoingTransitionTable.Add(tmp, new List<string>(8)); //only put the first one into the stack. if (done) { TaskStack.Push(step); done = false; } } } if (done) { int lowlinkV = preorder[v]; int preorderV = preorder[v]; bool selfLoop = false; for (int j = 0; j < nonProbTrans.Count; j++) { string w = nonProbTrans[j].ID; if (w == v) { selfLoop = true; } if (!visited.GetContainsKey(w)) { if (preorder[w] > preorderV) { lowlinkV = Math.Min(lowlinkV, lowlink[w]); } else { lowlinkV = Math.Min(lowlinkV, preorder[w]); } } else //in this case, there is a tau transition leading to an SCC; must add the transition into the toReturn automaton { BoundaryOneTransition.Add(new KeyValuePair<string, string>(v, w)); } } lowlink[v] = lowlinkV; TaskStack.Pop(); HashSet<string> scc = new HashSet<string>(); if (lowlinkV == preorderV) { scc.Add(v); visited.SetValue(v, true); while (stepStack.Count > 0 && preorder[stepStack.Peek().ID] > preorderV) { string s = stepStack.Pop().ID; scc.Add(s); visited.SetValue(s, true); } MDPState newstate = new MDPState(toReturn.States.Count.ToString()); if (scc.Count > 1 || (scc.Count == 1 && selfLoop)) { newstate.AddDistribution(new Distribution(Constants.TAU, newstate)); //add self loop: sun jun } sccs.Add(new KeyValuePair<HashSet<string>, MDPState>(scc, newstate)); toReturn.AddState(newstate); if (scc.Contains(InitState.ID)) { toReturn.SetInit(newstate); } foreach (MDPState state in TargetStates) { if (scc.Contains(state.ID)) { toReturn.AddTargetStates(newstate); } } } else { stepStack.Push(pair); } } } if (ProbTransitions.Count > 0) { foreach (Distribution step in ProbTransitions) { foreach (KeyValuePair<double, MDPState> pair in step.States) { string stateID = pair.Value.ID; if (!visited.ContainsKey(stateID)) { TaskStack.Push(pair.Value); visited.Add(stateID, false); } } } ProbTransitions.Clear(); } } while (TaskStack.Count > 0); foreach (KeyValuePair<string, string> pair in BoundaryOneTransition) { MDPState source = null; MDPState target = null; foreach (KeyValuePair<HashSet<string>, MDPState> sccstate in sccs) { if (sccstate.Key.Contains(pair.Key)) { source = sccstate.Value; } if (sccstate.Key.Contains(pair.Value)) { target = sccstate.Value; } } toReturn.AddDistribution(source.ID, new Distribution(Constants.TAU, target)); VerificationOutput.ReducedMDPTransitions++; } foreach (KeyValuePair<string, List<Distribution>> pair in GlobalProbTransitions) { MDPState source = null; foreach (KeyValuePair<HashSet<string>, MDPState> sccstate in sccs) { if (sccstate.Key.Contains(pair.Key)) { source = sccstate.Value; break; } } foreach (Distribution distribution in pair.Value) { Distribution disNew = new Distribution(distribution.Event); foreach (KeyValuePair<double, MDPState> state in distribution.States) { foreach (KeyValuePair<HashSet<string>, MDPState> sccstate in sccs) { if (sccstate.Key.Contains(state.Value.ID)) { disNew.AddProbStatePair(state.Key, sccstate.Value); VerificationOutput.ReducedMDPTransitions++; break; } } } toReturn.AddDistribution(source.ID, disNew); } } VerificationOutput.ReducedMDPStates = toReturn.States.Count; return toReturn; }
/// <summary> /// The local function of each process running Improved MultiCore Tarjan algorithm /// </summary> /// <returns></returns> public void localImprovedTarjanGeldenhuysValmari() { //local data for on-the-fly and Tarjan algorithm Dictionary<string, List<string>> outgoingTransitionTable = new Dictionary<string, List<string>>(Ultility.Ultility.MC_INITIAL_SIZE); StringDictionary<int[]> dfsData = new StringDictionary<int[]>(5000); Dictionary<string, List<LocalPair>> expendedNodes = new Dictionary<string, List<LocalPair>>(1024); Stack<LocalPair> callStack = new Stack<LocalPair>(5000); Stack<LocalPair> currentStack = new Stack<LocalPair>(1024); int counter = 0; string goal = null; int[] goalData = new int[2] { -2, 0 }; //-------------------------- //create initial states List<LocalPair> initialStates = LocalPair.GetInitialPairsLocal(BA, InitialStep); if (initialStates.Count == 0 || !BA.HasAcceptState) { VerificationOutput.VerificationResult = VerificationResultType.VALID; return; } //create random variable for each process Random rand = null; lock (MultiCoreLock) { rand = new Random(MultiCoreSeed); MultiCoreSeed++; } //put all initial states to callStack in different order & init data int[] initPermutation = generatePermutation(initialStates.Count, rand); for (int i = 0; i < initPermutation.Length; i++) { //get data from initialStates LocalPair tmp = initialStates[initPermutation[i]]; callStack.Push(tmp); string tmpID = tmp.GetCompressedState(); dfsData.Add(tmpID, new int[] { VISITED_NOPREORDER, 0 }); outgoingTransitionTable.Add(tmpID, new List<string>(8)); } //start loop while (callStack.Count > 0) { //cancel if too long action if (CancelRequested || StopMutliCoreThreads) { return; } //get the top of callStack LocalPair pair = callStack.Peek(); ConfigurationBase LTSState = pair.configuration; string BAState = pair.state; string v = pair.GetCompressedState(); //get local data of the top List<string> outgoing = outgoingTransitionTable[v]; int[] vData = dfsData.GetContainsKey(v); //if not expended then expend to next states from v if (!expendedNodes.ContainsKey(v)) { //create next states of v //ConfigurationBase[] nextLTSStates = LTSState.MakeOneMove().ToArray(); IEnumerable<ConfigurationBase> nextLTSStates = LTSState.MakeOneMove(); //.ToArray() pair.SetEnabled(nextLTSStates, FairnessType); List<LocalPair> nextStates = LocalPair.NextLocal(BA, nextLTSStates, BAState); expendedNodes.Add(v, nextStates); //update outgoing of v and set initial data for successors //no need to use inverse for statement and use nextStates foreach (LocalPair next in nextStates) { string w = next.GetCompressedState(); outgoing.Add(w); if (!dfsData.ContainsKey(w)) { dfsData.Add(w, new int[] { VISITED_NOPREORDER, 0 }); outgoingTransitionTable.Add(w, new List<string>(8)); } } } //get successors of v List<LocalPair> successors = expendedNodes[v]; //process if v is not numbered yet if (vData[0] == VISITED_NOPREORDER) { vData[0] = counter; vData[1] = counter; counter = counter + 1; //push to currentStack currentStack.Push(pair); //check whether v is accepting if (pair.state.EndsWith(Constants.ACCEPT_STATE)) { goal = v; goalData = vData; } //update lowlink according to successors in currentStack //remove already visited successors //no need random because consider all successors for (int i = successors.Count - 1; i >= 0; i--) { LocalPair succ = successors[i]; string w = succ.GetCompressedState(); int[] wData = dfsData.GetContainsKey(w); if (wData[0] >= 0 && !foundSCCTarjanGeldenhuysValmari.ContainsKey(w)) { //update & remove from expendedNodes(v) vData[1] = Math.Min(vData[1], wData[0]); successors.RemoveAt(i); //check for report accepting cycle if (vData[1] <= goalData[0]) { //REPORT COUNTEREXAMPLE localReportAcceptingCycle(succ, callStack, dfsData, outgoingTransitionTable); return; } } } } //check if there is any successor not numbered & not visited by other threads //choose random bool completed = true; LocalPair firstUnnumbered = null; for (int i = successors.Count - 1; i >= 0; i--) { int randIndex = rand.Next(successors.Count); LocalPair succ = successors[randIndex]; string w = succ.GetCompressedState(); int[] wData = dfsData.GetContainsKey(w); //only check states not in foundSCCTarjanGeldenhuysValmari if (wData[0] == VISITED_NOPREORDER && !foundSCCTarjanGeldenhuysValmari.ContainsKey(w)) { completed = false; firstUnnumbered = succ; successors.RemoveAt(randIndex); break; } else { successors.RemoveAt(randIndex); } } // if there at least one unnumbered successor if (!completed) { callStack.Push(firstUnnumbered); } else //all successors are numbered { //check for loop at an accepting & deadlock state if (LTSState.IsDeadLock && pair.state.EndsWith(Constants.ACCEPT_STATE)) { //report AcceptingCycle localReportAcceptingCycle(pair, callStack, dfsData, outgoingTransitionTable); return; } if (vData[0] == vData[1]) { //find the root -> mark as local and global for all processes LocalPair tmp = null; string tmpID = null; //pop currentStack and update SCC_FOUND and add to global memory until v do { //local tmp = currentStack.Pop(); tmpID = tmp.GetCompressedState(); int[] tmpData = dfsData.GetContainsKey(tmpID); tmpData[0] = SCC_FOUND; //global lock (MultiCoreLock) { if (!foundSCCTarjanGeldenhuysValmari.ContainsKey(tmpID)) { foundSCCTarjanGeldenhuysValmari.Add(tmpID, true); } } } while (!tmpID.Equals(v)); //pop callStack callStack.Pop(); } else { //pop callStack & update the parent LocalPair pop = callStack.Pop(); LocalPair top = callStack.Peek(); string popID = pop.GetCompressedState(); string topID = top.GetCompressedState(); int[] popData = dfsData.GetContainsKey(popID); int[] topData = dfsData.GetContainsKey(topID); topData[1] = Math.Min(topData[1], popData[1]); } } } }
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"; StringDictionary sd; 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++; sd = new StringDictionary(); Console.WriteLine("1. Remove() from empty dictionary"); iCountTestcases++; if (sd.Count > 0) sd.Clear(); for (int i = 0; i < keys.Length; i++) { sd.Remove(keys[0]); } Console.WriteLine("2. Remove() on filled dictionary"); strLoc = "Loc_002oo"; int len = values.Length; iCountTestcases++; sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sd.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Remove(keys[i]); if (sd.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0002b_{0}, didn't remove element with {0} key", i); } iCountTestcases++; if ( sd.ContainsValue(values[i]) ) { iCountErrors++; Console.WriteLine("Err_0002c_{0}, removed wrong value", i); } iCountTestcases++; if ( sd.ContainsKey(keys[i]) ) { iCountErrors++; Console.WriteLine("Err_0002d_{0}, removed wrong value", i); } } Console.WriteLine("3. Remove() on dictionary with duplicate values "); strLoc = "Loc_003oo"; iCountTestcases++; sd.Clear(); string intlStr = intl.GetString(MAX_LEN, true, true, true); sd.Add("keykey1", intlStr); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } sd.Add("keykey2", intlStr); if (sd.Count != len+2) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sd.Count, len+2); } iCountTestcases++; sd.Remove("keykey2"); if (!sd.ContainsValue(intlStr)) { iCountErrors++; Console.WriteLine("Err_0003b, removed both duplicates"); } if ( sd.ContainsKey("keykey2") ) { iCountErrors++; Console.WriteLine("Err_0003c, removed not given instance"); } if (! sd.ContainsKey("keykey1") ) { iCountErrors++; Console.WriteLine("Err_0003d, removed wrong instance"); } Console.WriteLine("4. Remove() from dictionary with intl strings"); strLoc = "Loc_004oo"; 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; } sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(intlValues[i+len], intlValues[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0004a, count is {0} instead of {1}", sd.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Remove(intlValues[i+len]); if (sd.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0004b_{0}, didn't remove element with {0} key", i+len); } iCountTestcases++; if ( sd.ContainsValue(intlValues[i]) ) { iCountErrors++; Console.WriteLine("Err_0004c_{0}, removed wrong value", i); } iCountTestcases++; if ( sd.ContainsKey(intlValues[i+len]) ) { iCountErrors++; Console.WriteLine("Err_0004d_{0}, removed wrong key", i); } } Console.WriteLine("5. Case sensitivity"); strLoc = "Loc_005oo"; iCountTestcases++; sd.Clear(); string [] intlValuesUpper = new string [len]; for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToLower(); } for (int i = 0; i < len; i++) { intlValuesUpper[i] = intlValues[i+len].ToUpper(); } sd.Clear(); Console.WriteLine(" ... add Lowercased ..."); for (int i = 0; i < len; i++) { sd.Add(intlValues[i+len], intlValues[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0005a, count is {0} instead of {1}", sd.Count, len); } Console.WriteLine(" ... remove Uppercased ..."); for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Remove(intlValuesUpper[i]); if (sd.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0005b_{0}, didn't remove element with {0} lower key", i+len); } iCountTestcases++; if ( sd.ContainsValue(intlValues[i]) ) { iCountErrors++; Console.WriteLine("Err_0005c_{0}, removed wrong value", i); } iCountTestcases++; if ( sd.ContainsKey(intlValuesUpper[i]) ) { iCountErrors++; Console.WriteLine("Err_0005d_{0}, removed wrong key", i); } } Console.WriteLine("6. Remove(null)"); strLoc = "Loc_006oo"; iCountTestcases++; try { sd.Remove(null); iCountErrors++; Console.WriteLine("Err_0006a, no exception"); } catch (NullReferenceException ex) { Console.WriteLine(" expected exception: " + 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; } }
public virtual 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"; StringDictionary sd; IEnumerator en; DictionaryEntry curr; 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" }; try { Console.WriteLine("--- create dictionary ---"); strLoc = "Loc_001oo"; iCountTestcases++; sd = new StringDictionary(); Console.WriteLine("1. Enumerator for empty dictionary"); Console.WriteLine(" - get type"); iCountTestcases++; en = sd.GetEnumerator(); string type = en.GetType().ToString(); if ( type.IndexOf("Enumerator", 0) == 0 ) { iCountErrors++; Console.WriteLine("Err_0001a, type is not Enumerator"); } Console.WriteLine(" - MoveNext"); iCountTestcases++; bool res = en.MoveNext(); if ( res ) { iCountErrors++; Console.WriteLine("Err_0001b, MoveNext returned true"); } Console.WriteLine(" - Current"); iCountTestcases++; try { curr = (DictionaryEntry)en.Current; iCountErrors++; Console.WriteLine("Err_0001c, no exception"); } catch (InvalidOperationException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0001d, unexpected exception: {0}", e.ToString()); } Console.WriteLine("2. GetEnumerator for filled collection"); strLoc = "Loc_002oo"; iCountTestcases++; for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } Console.WriteLine(" - get type"); iCountTestcases++; en = sd.GetEnumerator(); type = en.GetType().ToString(); if ( type.IndexOf("Enumerator", 0) == 0 ) { iCountErrors++; Console.WriteLine("Err_0002a, type is not Enumerator"); } Console.WriteLine(" - MoveNext and Current within collection"); for (int i = 0; i < sd.Count; i++) { iCountTestcases++; res = en.MoveNext(); if ( !res ) { iCountErrors++; Console.WriteLine("Err_0002b_{0}, MoveNext returned false", i); } iCountTestcases++; curr = (DictionaryEntry)en.Current; if (! sd.ContainsValue(curr.Value.ToString()) ) { iCountErrors++; Console.WriteLine("Err_0002c_{0}, Current dictionary doesn't contain value from enumerator", i); } iCountTestcases++; if (! sd.ContainsKey(curr.Key.ToString()) ) { iCountErrors++; Console.WriteLine("Err_0002d_{0}, Current dictionary doesn't contain key from enumerator", i); } iCountTestcases++; if ( String.Compare(sd[curr.Key.ToString()], curr.Value.ToString(), false) != 0 ) { iCountErrors++; Console.WriteLine("Err_0002e_{0}, Value for current Key is different in dictionary", i); } iCountTestcases++; DictionaryEntry curr1 = (DictionaryEntry)en.Current; if (! curr.Equals(curr1) ) { iCountErrors++; Console.WriteLine("Err_0002f_{0}, second call of Current returned different result", i); } } res = en.MoveNext(); Console.WriteLine(" - MoveNext outside of the collection"); iCountTestcases++; res = en.MoveNext(); if ( res ) { iCountErrors++; Console.WriteLine("Err_0002g, MoveNext returned true"); } Console.WriteLine(" - Current outside of the collection"); iCountTestcases++; try { curr = (DictionaryEntry)en.Current; iCountErrors++; Console.WriteLine("Err_0002h, no exception"); } catch (InvalidOperationException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0002i, unexpected exception: {0}", e.ToString()); } Console.WriteLine(" - Reset"); iCountTestcases++; en.Reset(); Console.WriteLine(" - get Current after Reset"); iCountTestcases++; try { curr = (DictionaryEntry)en.Current; iCountErrors++; Console.WriteLine("Err_0002j, no exception"); } catch (InvalidOperationException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0002k, unexpected exception: {0}", e.ToString()); } Console.WriteLine("3. Enumerator and modified dictionary"); strLoc = "Loc_003oo"; iCountTestcases++; if (sd.Count < 1) { for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } } iCountTestcases++; en = sd.GetEnumerator(); Console.WriteLine(" - MoveNext"); res = en.MoveNext(); if (!res) { iCountErrors++; Console.WriteLine("Err_0003a, MoveNext returned false"); } Console.WriteLine(" - modify collection"); curr = (DictionaryEntry)en.Current; int cnt = sd.Count; iCountTestcases++; sd.Remove(keys[0]); if ( sd.Count != cnt - 1 ) { iCountErrors++; Console.WriteLine("Err_0003b, didn't remove item with 0th key"); } Console.WriteLine(" - get Current"); iCountTestcases++; DictionaryEntry curr2 = (DictionaryEntry)en.Current; if (! curr.Equals(curr2) ) { iCountErrors++; Console.WriteLine("Err_0003c, current returned different value after midification"); } Console.WriteLine(" - call MoveNext"); iCountTestcases++; try { res = en.MoveNext(); iCountErrors++; Console.WriteLine("Err_0003d, no exception"); } catch (InvalidOperationException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0003e, unexpected exception: {0}", e.ToString()); } Console.WriteLine("4. Modify dictionary after enumerated beyond the end"); strLoc = "Loc_004oo"; iCountTestcases++; sd.Clear(); for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } iCountTestcases++; en = sd.GetEnumerator(); for (int i = 0; i < sd.Count; i ++) { en.MoveNext(); } Console.WriteLine(" - get Current at the end of the dictionary"); curr = (DictionaryEntry)en.Current; Console.WriteLine(" - modify collection"); curr = (DictionaryEntry)en.Current; cnt = sd.Count; iCountTestcases++; sd.Remove(keys[0]); if ( sd.Count != cnt - 1 ) { iCountErrors++; Console.WriteLine("Err_0004b, didn't remove item with 0th key"); } Console.WriteLine(" - get Current after modifying"); iCountTestcases++; curr2 = (DictionaryEntry)en.Current; if (! curr.Equals(curr2) ) { iCountErrors++; Console.WriteLine("Err_0004c, current returned different value after midification"); } Console.WriteLine(" - call MoveNext after modifying"); iCountTestcases++; try { res = en.MoveNext(); iCountErrors++; Console.WriteLine("Err_0004d, no exception"); } catch (InvalidOperationException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0004e, 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; } }
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"; StringDictionary sd; 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; string ind; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sd = new StringDictionary(); Console.WriteLine("1. add simple strings"); for (int i = 0; i < values.Length; i++) { iCountTestcases++; cnt = sd.Count; sd.Add(keys[i], values[i]); if (sd.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0001_{0}a, count is {1} instead of {2}", i, sd.Count, cnt+1); } iCountTestcases++; if (!sd.ContainsValue(values[i])) { iCountErrors++; Console.WriteLine("Err_0001_{0}b, collection doesn't contain value of new item", i); } iCountTestcases++; if (!sd.ContainsKey(keys[i])) { iCountErrors++; Console.WriteLine("Err_0001_{0}c, collection doesn't contain key of new item", i); } iCountTestcases++; if (String.Compare(sd[keys[i]], values[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0001_{0}d, returned item \"{1}\" instead of \"{2}\"", i, sd[keys[i]], values[i]); } } Console.WriteLine("2. add intl strings"); int len = values.Length; 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; } Console.WriteLine(" initial number of items: " + sd.Count); strLoc = "Loc_002oo"; for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Add(intlValues[i+len], intlValues[i]); if (sd.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0002_{0}a, count is {1} instead of {2}", i, sd.Count, cnt+1); } iCountTestcases++; if (!sd.ContainsValue(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, collection doesn't contain value of new item", i); } iCountTestcases++; if (!sd.ContainsKey(intlValues[i+len])) { iCountErrors++; Console.WriteLine("Err_0002_{0}c, collection doesn't contain key of new item", i); } ind = intlValues[i+len]; iCountTestcases++; if (String.Compare(sd[ind], intlValues[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0002_{0}d, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i]); } } Console.WriteLine("3. Case sensitivity"); 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(); } sd.Clear(); Console.WriteLine(" initial number of items: " + sd.Count); strLoc = "Loc_003oo"; for (int i = 0; i < len; i++) { iCountTestcases++; cnt = sd.Count; sd.Add(intlValues[i+len], intlValues[i]); if (sd.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0003_{0}a, count is {1} instead of {2}", i, sd.Count, cnt+1); } iCountTestcases++; if (!sd.ContainsValue(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, collection doesn't contain value of new item", i); } iCountTestcases++; if (!sd.ContainsKey(intlValues[i+len])) { iCountErrors++; Console.WriteLine("Err_0003_{0}c, collection doesn't contain key of new item", i); } iCountTestcases++; if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i])) { iCountErrors++; Console.WriteLine("Err_0003_{0}d, collection contains lowercase value of new item", i); } iCountTestcases++; if ( !sd.ContainsKey(intlValuesLower[i+len])) { iCountErrors++; Console.WriteLine("Err_0003_{0}e, collection doesn't contain lowercase key of new item", i); } } Console.WriteLine("4. Add (string, null) "); Console.WriteLine(" initial number of items: " + sd.Count); strLoc = "Loc_004oo"; iCountTestcases++; cnt = sd.Count; sd.Add("keykey", null); iCountTestcases++; if (sd.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0004a, count is {0} instead of {1}", sd.Count, cnt+1); } iCountTestcases++; if (!sd.ContainsValue(null)) { iCountErrors++; Console.WriteLine("Err_0004b, collection doesn't contain null"); } iCountTestcases++; if (sd["keykey"] != null) { iCountErrors++; Console.WriteLine("Err_0004c, returned non-null on place of null"); } Console.WriteLine("5. Add (null, string) "); Console.WriteLine(" initial number of items: " + sd.Count); strLoc = "Loc_005oo"; iCountTestcases++; try { sd.Add(null, "item"); iCountErrors++; Console.WriteLine("Err_0005a, ArgumentNullException Expected"); } // catch (System.ArgumentNullException e) { Console.WriteLine("expected exception: {0}", e.ToString()); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0005b, unexpected exception: " + e.ToString()); } Console.WriteLine("6. Add (key, value) with duplicate key "); Console.WriteLine(" initial number of items: " + sd.Count); strLoc = "Loc_006oo"; iCountTestcases++; string k = intl.GetString(MAX_LEN, true, true, true); if (! sd.ContainsKey(k)) { sd.Add(k, "newItem"); } if (! sd.ContainsKey(k)) { iCountErrors++; Console.WriteLine("Err_0005a,failed to add item"); } else { try { sd.Add(k, "itemitemitem"); iCountErrors++; Console.WriteLine("Err_0005b, no exception"); } catch (ArgumentException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0005c, unexpected exception: " + 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; } }
// Constructor public Arguments(string[] Args) { Parameters = new StringDictionary(); //Regex Spliter = new Regex(@"^-{1,2}|^/|=|:", no need to support: type=3, type:3, to avoid arugments like: -regex "a=\w+" Regex Spliter = new Regex(@"^-{1,2}", RegexOptions.IgnoreCase | RegexOptions.Compiled); Regex Remover = new Regex(@"^(['""]?)(.*?)\1$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string Parameter = null; string[] Parts; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: // -param1 value1 --param2 /param3:"Test-:-work" // /param4=happy -param5 '--=nice=--' foreach (string Txt in Args) { // Look for new parameters (-,/ or --) and a // possible enclosed value (=,:) Parts = Spliter.Split(Txt, 3); switch (Parts.Length) { // Found a value (for the last parameter // found (space separator)) case 1: if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parts[0] = Remover.Replace(Parts[0], "$2"); Parameters.Add(Parameter, Parts[0]); } Parameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. // With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } Parameter = Parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. // With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } Parameter = Parts[1]; // Remove possible enclosing characters (",') if (!Parameters.ContainsKey(Parameter)) { Parts[2] = Remover.Replace(Parts[2], "$2"); Parameters.Add(Parameter, Parts[2]); } Parameter = null; break; } } // In case a parameter is still waiting if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } }
// Constructor public CommandLineArguments(string[] Args) { Parameters = new StringDictionary(); Regex Spliter = new Regex(@"^/|:", RegexOptions.IgnoreCase | RegexOptions.Compiled); Regex Remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled); string Parameter = null; string[] Parts; // Examples: // /param3:"Test" foreach (string Txt in Args) { // Look for new parameters (-,/ or --) and a // possible enclosed value (=,:) Parts = Spliter.Split(Txt, 3); switch (Parts.Length) { // Found a value (for the last parameter // found (space separator)) case 1: if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parts[0] = Remover.Replace(Parts[0], "$1"); Parameters.Add(Parameter, Parts[0]); } Parameter = null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. // With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } Parameter = Parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. // With no value, set it to true. if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } Parameter = Parts[1]; // Remove possible enclosing characters (",') if (!Parameters.ContainsKey(Parameter)) { Parts[2] = Remover.Replace(Parts[2], "$1"); Parameters.Add(Parameter, Parts[2]); } Parameter = null; break; } } // In case a parameter is still waiting if (Parameter != null) { if (!Parameters.ContainsKey(Parameter)) { Parameters.Add(Parameter, "true"); } } }
public virtual 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"; StringDictionary sd; try { Console.WriteLine("--- default ctor ---"); strLoc = "Loc_001oo"; iCountTestcases++; sd = new StringDictionary(); Console.WriteLine("1. compare to null"); iCountTestcases++; if (sd == null) { iCountErrors++; Console.WriteLine("Err_0001, collection is null after default ctor"); } Console.WriteLine("2. check Count"); iCountTestcases++; if (sd.Count != 0) { iCountErrors++; Console.WriteLine("Err_0002, Count = {0} after default ctor", sd.Count); } Console.WriteLine("3. check ContainsValue()"); iCountTestcases++; if (sd.ContainsValue("string")) { iCountErrors++; Console.WriteLine("Err_0003, ContainsValue() returned true after default ctor"); } Console.WriteLine("4. check ContainsKey()"); iCountTestcases++; if (sd.ContainsKey("string")) { iCountErrors++; Console.WriteLine("Err_0004, ContainsKey() returned true after default ctor"); } Console.WriteLine("5. check ToString()"); iCountTestcases++; string temp = sd.ToString(); Console.WriteLine(" ToString(): " + temp); if (temp.IndexOf("StringDictionary") == -1) { iCountErrors++; Console.WriteLine("Err_0005, ToString() doesn't contain \"StringDictionary\""); } Console.WriteLine("6. check returned Type"); iCountTestcases++; temp = sd.GetType().ToString().Trim(); Console.WriteLine(" GetType(): " + temp); if (temp.IndexOf("StringDictionary") == -1) { iCountErrors++; Console.WriteLine("Err_0006: returned type doesn't contain \"StringDictionary\""); } Console.WriteLine("7. compare returned Type of two Dictionaries"); iCountTestcases++; string temp1 = (new StringDictionary()).GetType().ToString().Trim(); if (String.Compare(temp, temp1) != 0) { iCountErrors++; Console.WriteLine("Err_0007: returned types of two collections differ"); } Console.WriteLine("8. check IsSynchronized"); iCountTestcases++; Console.WriteLine(" IsSynchronized: " + sd.IsSynchronized); if (sd.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_0008: IsSynchronized returned {0}", sd.IsSynchronized); } Console.WriteLine("9. add item and verify"); iCountTestcases++; sd.Add("key", "value"); iCountTestcases++; if (sd.Count != 1) { iCountErrors++; Console.WriteLine("Err_0009a: Count returned {0}", sd.Count); } iCountTestcases++; if ( !sd.ContainsKey("key") ) { iCountErrors++; Console.WriteLine("Err_0009b: ContainsKey() returned false"); } iCountTestcases++; if ( !sd.ContainsValue("value") ) { iCountErrors++; Console.WriteLine("Err_0009c: ContainsValue() returned false"); } } 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 void TestEnvironmentVariablesPropertyUnix() { ProcessStartInfo psi = new ProcessStartInfo(); // Creating a detached ProcessStartInfo will pre-populate the environment // with current environmental variables. StringDictionary environmentVariables = psi.EnvironmentVariables; Assert.NotEqual(0, environmentVariables.Count); int CountItems = environmentVariables.Count; environmentVariables.Add("NewKey", "NewValue"); environmentVariables.Add("NewKey2", "NewValue2"); Assert.Equal(CountItems + 2, environmentVariables.Count); environmentVariables.Remove("NewKey"); Assert.Equal(CountItems + 1, environmentVariables.Count); //Exception not thrown with invalid key AssertExtensions.Throws <ArgumentException>(null, () => { environmentVariables.Add("NewKey2", "NewValue2"); }); Assert.False(environmentVariables.ContainsKey("NewKey")); environmentVariables.Add("newkey2", "newvalue2"); Assert.True(environmentVariables.ContainsKey("newkey2")); Assert.Equal("newvalue2", environmentVariables["newkey2"]); Assert.Equal("NewValue2", environmentVariables["NewKey2"]); environmentVariables.Clear(); Assert.Equal(0, environmentVariables.Count); environmentVariables.Add("NewKey", "newvalue"); environmentVariables.Add("newkey2", "NewValue2"); Assert.False(environmentVariables.ContainsKey("newkey")); Assert.False(environmentVariables.ContainsValue("NewValue")); string result = null; int index = 0; foreach (string e1 in environmentVariables.Values) { index++; result += e1; } Assert.Equal(2, index); Assert.Equal("newvalueNewValue2", result); result = null; index = 0; foreach (string e1 in environmentVariables.Keys) { index++; result += e1; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); result = null; index = 0; foreach (DictionaryEntry e1 in environmentVariables) { index++; result += e1.Key; } Assert.Equal("NewKeynewkey2", result); Assert.Equal(2, index); //Key not found Assert.Throws <KeyNotFoundException>(() => { string stringout = environmentVariables["NewKey99"]; }); //Exception not thrown with invalid key Assert.Throws <ArgumentNullException>(() => { string stringout = environmentVariables[null]; }); //Exception not thrown with invalid key Assert.Throws <ArgumentNullException>(() => environmentVariables.Add(null, "NewValue2")); AssertExtensions.Throws <ArgumentException>(null, () => environmentVariables.Add("newkey2", "NewValue2")); //Use DictionaryEntry Enumerator var x = environmentVariables.GetEnumerator() as IEnumerator; x.MoveNext(); var y1 = (DictionaryEntry)x.Current; Assert.Equal("NewKey newvalue", y1.Key + " " + y1.Value); x.MoveNext(); y1 = (DictionaryEntry)x.Current; Assert.Equal("newkey2 NewValue2", y1.Key + " " + y1.Value); environmentVariables.Add("newkey3", "newvalue3"); KeyValuePair <string, string>[] kvpa = new KeyValuePair <string, string> [10]; environmentVariables.CopyTo(kvpa, 0); Assert.Equal("NewKey", kvpa[0].Key); Assert.Equal("newkey3", kvpa[2].Key); Assert.Equal("newvalue3", kvpa[2].Value); string[] kvp = new string[10]; AssertExtensions.Throws <ArgumentException>(null, () => { environmentVariables.CopyTo(kvp, 6); }); environmentVariables.CopyTo(kvpa, 6); Assert.Equal("NewKey", kvpa[6].Key); Assert.Equal("newvalue", kvpa[6].Value); Assert.Throws <ArgumentOutOfRangeException>(() => { environmentVariables.CopyTo(kvpa, -1); }); AssertExtensions.Throws <ArgumentException>(null, () => { environmentVariables.CopyTo(kvpa, 9); }); Assert.Throws <ArgumentNullException>(() => { KeyValuePair <string, string>[] kvpanull = null; environmentVariables.CopyTo(kvpanull, 0); }); }
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"; StringDictionary sd; 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" }; string itm; try { intl = new IntlStrings(); Console.WriteLine("--- create dictionary ---"); strLoc = "Loc_001oo"; iCountTestcases++; sd = new StringDictionary(); Console.WriteLine("1. set Item on empty dictionary"); iCountTestcases++; for (int i = 0; i < keys.Length; i++) { if (sd.Count > 0) sd.Clear(); sd[keys[i]] = values[i]; if (sd.Count != 1) { iCountErrors++; Console.WriteLine("Err_0001a_{0}, didn't add item with {0} key", i); } if (String.Compare(sd[keys[i]], values[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0001b_{0}, added wrong value", i); } } Console.WriteLine("2. set Item on filled dictionary"); strLoc = "Loc_002oo"; int len = values.Length; iCountTestcases++; sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sd.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; itm = "item" + i; sd[keys[i]] = itm; if (String.Compare(sd[keys[i]], itm, false) != 0) { iCountErrors++; Console.WriteLine("Err_0002b_{0}, returned {1} instead of {2}", i, sd[keys[i]], itm); } } Console.WriteLine("3. set Item on dictionary with duplicate values "); strLoc = "Loc_003oo"; iCountTestcases++; sd.Clear(); string intlStr = intl.GetString(MAX_LEN, true, true, true); string intlStr1 = intl.GetString(MAX_LEN, true, true, true); sd.Add("keykey1", intlStr); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } sd.Add("keykey2", intlStr); if (sd.Count != len+2) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sd.Count, len+2); } iCountTestcases++; sd["keykey1"] = intlStr1; if (String.Compare(sd["keykey1"], intlStr1, false) != 0) { iCountErrors++; Console.WriteLine("Err_0003b, returned {1} instead of {2}", sd["keykey1"],intlStr1); } iCountTestcases++; sd["keykey2"] = intlStr1; if (String.Compare(sd["keykey2"], intlStr1, false) != 0) { iCountErrors++; Console.WriteLine("Err_0003c, returned {1} instead of {2}", sd["keykey2"],intlStr1); } Console.WriteLine("4. set Item on dictionary with intl strings"); strLoc = "Loc_004oo"; string [] intlValues = new string [len*2]; string [] intlSets = new string [len]; 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; } for (int i = 0; i < len; i++) { intlSets[i] = intl.GetString(MAX_LEN, true, true, true); } sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(intlValues[i+len], intlValues[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0004a, count is {0} instead of {1}", sd.Count, len); } for (int i = 0; i < len; i++) { iCountTestcases++; sd[intlValues[i+len]] = intlSets[i]; if (String.Compare(sd[intlValues[i+len]], intlSets[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0002b_{0}, returned {1} instead of {2}", i, sd[intlValues[i+len]], intlSets[i]); } } Console.WriteLine("5. Case sensitivity"); strLoc = "Loc_005oo"; iCountTestcases++; sd.Clear(); string [] intlValuesUpper = new string [len]; for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToLower(); } for (int i = 0; i < len; i++) { intlValuesUpper[i] = intlValues[i].ToUpper(); } sd.Clear(); Console.WriteLine(" ... add Lowercased ..."); for (int i = 0; i < len; i++) { sd.Add(intlValues[i+len], intlValues[i]); } if (sd.Count != len) { iCountErrors++; Console.WriteLine("Err_0005a, count is {0} instead of {1}", sd.Count, len); } Console.WriteLine(" ... set to Uppercased ..."); for (int i = 0; i < len; i++) { iCountTestcases++; sd[intlValues[i+len]] = intlValuesUpper[i]; if (String.Compare(sd[intlValues[i+len]], intlValuesUpper[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0005b_{0}, returned {1} instead of {2}", i, sd[intlValues[i+len]], intlValuesUpper[i]); } } Console.WriteLine("6. set Item(null)"); strLoc = "Loc_006oo"; iCountTestcases++; try { sd[null] = intlStr; iCountErrors++; Console.WriteLine("Err_0006a, no exception"); } catch (ArgumentNullException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0006b, unexpected exception: {0}", e.ToString()); } Console.WriteLine("7. set Item to null"); strLoc = "Loc_007oo"; iCountTestcases++; if (!sd.ContainsKey(keys[0]) ) { sd.Add(keys[0], values[0]); } sd[keys[0]] = null; if ( sd[keys[0]] != null ) { iCountErrors++; Console.WriteLine("Err_0007, returned non-null"); } } 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 bool Contains(this StringDictionary self, string key) { return(self.ContainsKey(key) && !self[key].IsNullOrEmpty()); }