static void Main(string[] args) { Stack ast = new Stack(); ast.Push("Item 1"); ast.Push("Item 2"); ast.Push("Item 3"); ast.Push("Item 4"); Console.WriteLine("Count: {0}", ast.Count); PrintValues(ast); // Peek item but do not remove object item = ast.Peek(); Console.WriteLine("Peek: {0}", item); PrintValues(ast); // Peek and cast but do not remove string itemString = ast.Peek() as string; // fast cast Console.WriteLine("Peek: {0}", item); PrintValues(ast); // Contains Boolean contains = ast.Contains("Item 3"); Console.WriteLine("Contains: {0}", contains); // Remove items object item4 = ast.Pop(); object item3 = ast.Pop(); Console.WriteLine("Pop: {0} {1}", item4, item3); PrintValues(ast); Console.WriteLine("Count: {0}", ast.Count); // no TrimToSize method }
static public int Contains(IntPtr l) { try { System.Collections.Stack self = (System.Collections.Stack)checkSelf(l); System.Object a1; checkType(l, 2, out a1); var ret = self.Contains(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static int Contains(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); System.Collections.Stack obj = (System.Collections.Stack)ToLua.CheckObject(L, 1, typeof(System.Collections.Stack)); object arg0 = ToLua.ToVarObject(L, 2); bool o = obj.Contains(arg0); LuaDLL.lua_pushboolean(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
private void Timer1_Tick(object sender, EventArgs e) { try { bool isNewAppl = false; IntPtr hWnd = W32.getForegroundWindow(); Int32 pid = W32.GetWindowProcessID(hWnd); Process p = Process.GetProcessById(pid); appName = p.ProcessName; appltitle = W32.ActiveAppTitle().Trim().Replace("\0", ""); if (!applnames.Contains(appltitle + appName)) { applnames.Push(appltitle + appName); applhash.Add(appltitle + appName, 0); isNewAppl = true; } if (preValue != (appltitle + appName)) { IDictionaryEnumerator en = applhash.GetEnumerator(); applfocusinterval = DateTime.Now.Subtract(applfocustime); while (en.MoveNext()) { if (en.Key.ToString() == preValue) { double prevseconds = Convert.ToDouble(en.Value); applhash.Remove(preValue); applhash.Add(preValue, (applfocusinterval.TotalSeconds + prevseconds)); break; } } preValue = appltitle + appName; applfocustime = DateTime.Now; } if (isNewAppl) { applfocustime = DateTime.Now; } } catch (Exception ex) { Debug.WriteLine(ex.Message + " : " + ex.StackTrace); } }
public void getFollow(string name,Stack follows , Stack checkedNonTerm) { if(name==nonTerminals.ExtraNonTerm) { follows.Push("$"); return; } nonTerminalNode temp=first; while(temp!=null) { if( temp.lawLink.getFollow(name,follows)==true) { if( !checkedNonTerm.Contains(temp.item.Name)) { checkedNonTerm.Push(temp.item.Name); getFollow(temp.item.Name , follows,checkedNonTerm); } } temp=temp.next; } }
private static void measureGoalDepth(StoryData inputStory, Stack goalStack, Hashtable goalTable, AuthorGoal currentGoal, ArrayList pathDepths, int currentDepth) { if(currentDepth > 50) { return; } if(goalStack.Contains(currentGoal)) { //recursion occurring, end search return; } if(currentGoal == null) { //Null author goal pathDepths.Add(currentDepth); return; } if(currentGoal.PlotFragments.Count == 0) { //No plot fragment for subgoal, count as leaf of tree pathDepths.Add(currentDepth); return; } foreach (PlotFragment f in currentGoal.PlotFragments) { int numSubgoals = 0; foreach(Action a in f.Actions) { if(a is ActionSubgoal) { numSubgoals++; AuthorGoal goalToSearch = (AuthorGoal)goalTable[((ActionSubgoal)a).SubGoalId]; goalStack.Push(currentGoal); measureGoalDepth(inputStory,goalStack, goalTable, goalToSearch, pathDepths, currentDepth + 1); goalStack.Pop(); } } if (numSubgoals == 0) { //No subgoaling occured, so this path is a leaf of the tree pathDepths.Add(currentDepth); } } }
/// <summary> /// Merges multiple test configuration files including default and user defined ones into one XmlDocument. /// </summary> /// <param name="configFileNames">The names of test configuration files. It contains three elements.</param> /// <returns>The XmlDocument which contains data of all test configuration files.</returns> private XmlDocument MergeConfigFiles(string[] configFileNames) { try { if (configFileNames == null || configFileNames.Length < 2) { throw new ArgumentException("At least two PTF config files should be passed in."); } Logging.ApplicationLog.TraceLog("Try to load " + configFileNames.Length + " config files."); XmlDocument docBase = new XmlDocument(); docBase.XmlResolver = null; Logging.ApplicationLog.TraceLog("Loading configFileNames[0] :" + configFileNames[0]); docBase.Load(XmlReader.Create(configFileNames[0], new XmlReaderSettings() { XmlResolver = null })); Stack<XmlDocument> xmlDocs = new Stack<XmlDocument>(); Stack<string> xmlDocsName = new Stack<string>(); Stack<string> configFiles = new Stack<string>(); for (int n = 1; n < configFileNames.Length; n++) { if (configFileNames[n] != null) configFiles.Push(configFileNames[n]); } while (configFiles.Count > 0) { string fileName = configFiles.Pop(); // Ignore multiple reference. if (xmlDocsName.Contains(fileName)) { Logging.ApplicationLog.TraceLog("Ignore multiple references: " + fileName); continue; } XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; Logging.ApplicationLog.TraceLog("Loading config file:" + fileName); doc.Load(XmlReader.Create(fileName, new XmlReaderSettings() { XmlResolver = null })); xmlDocs.Push(doc); xmlDocsName.Push(fileName); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("tc", DefaultNamespace); XmlNode root = doc.DocumentElement; XmlNode incNode = root.SelectSingleNode("tc:Include", nsmgr); if (incNode != null) { foreach (XmlNode nod in incNode.ChildNodes) { FileInfo fi = new FileInfo(fileName); string path = Path.Combine(fi.DirectoryName, nod.Attributes["name"].Value); if (!ValidateConfigFiles(new string[] { path }, false)) { throw new XmlException( String.Format("Validating configuration {0} failed: {1}", invalidFilename, validateErrorMessages)); } configFiles.Push(path); } } } while (xmlDocs.Count > 0) { XmlDocument doc = xmlDocs.Pop(); string configFileName = xmlDocsName.Pop(); try { MergeXmlDocument(docBase, doc); } catch (XmlException e) { throw new InvalidOperationException( String.Format( "Merging the configuration file ({0}) failed. " + "Please make sure it is valid. Otherwise, please validate the Xml namespace and schema location in this file. " + "To specify the correct Xml namespace and schema location, " + "the TestSite tag in configuration file(s) should be " + DefaultTestSiteTag, configFileName), e); } catch (InvalidOperationException e) { throw new InvalidOperationException( String.Format( "Merging the configuration file ({0}) failed. " + "Please make sure it is valid. Otherwise, please validate the Xml namespace and schema location in this file. " + "To specify the correct Xml namespace and schema location, " + "the TestSite tag in configuration file(s) should be " + DefaultTestSiteTag, configFileName), e); } } this.Document = docBase; Logging.ApplicationLog.TraceLog("Merged config file content: " + docBase.OuterXml); return docBase; } catch (XmlException e) { throw new InvalidOperationException("Failed to read test configuration file.", e); } }
/// <summary> /// /// </summary> public virtual LabelNode AddChildrenAndLookForSelected (int hvoToSelect, Stack ownershipStack, List<int> rghvoChosen) { LabelNode nodeRepresentingCurrentChoice = null; // JohnT: if this.Nodes[0] is not a LabelNode, it is a dummy node we added so that // its parent LOOKS like something we can expand. That is the usual case for a node // we can expand. Therefore finding one of those, or finding more or less than one // node, is evidence that we haven't previously computed the real children of this, // and should do so. bool fExpanded = this.Nodes.Count != 1 || (this.Nodes[0] as LabelNode) != null; if (!fExpanded) { this.Nodes.Clear(); nodeRepresentingCurrentChoice = AddSecondaryNodesAndLookForSelected(this, Nodes, nodeRepresentingCurrentChoice, hvoToSelect, ownershipStack, rghvoChosen); foreach (ObjectLabel label in ((ObjectLabel)this.Tag).SubItems) { if (!WantNodeForLabel(label)) continue; LabelNode node = Create(label, m_stylesheet); if (rghvoChosen != null) node.Checked = (rghvoChosen.BinarySearch(label.Hvo) >= 0); this.Nodes.Add(node); nodeRepresentingCurrentChoice = CheckForSelection(label, hvoToSelect, node, nodeRepresentingCurrentChoice, ownershipStack); nodeRepresentingCurrentChoice = AddSecondaryNodesAndLookForSelected( node, node.Nodes, nodeRepresentingCurrentChoice, hvoToSelect, ownershipStack, rghvoChosen); } } else { // Even if we don't have to create children for this, we need to search the // children for matches, and perhaps expand some of them. foreach (LabelNode node in this.Nodes) { nodeRepresentingCurrentChoice = CheckForSelection(node.Label, hvoToSelect, node, nodeRepresentingCurrentChoice, ownershipStack); } } if (nodeRepresentingCurrentChoice == null) { foreach (LabelNode node in this.Nodes) { if (ownershipStack.Contains(node.Label.Hvo)) { nodeRepresentingCurrentChoice = node.AddChildrenAndLookForSelected( hvoToSelect, ownershipStack, rghvoChosen); return nodeRepresentingCurrentChoice; } } } else { this.Expand(); nodeRepresentingCurrentChoice.EnsureVisible(); } return nodeRepresentingCurrentChoice; }
static Queue<string> ConvertToRPN(List<string> elements) { Stack<string> stack = new Stack<string>(); Queue<string> queue = new Queue<string>(); for (int i = 0; i < elements.Count; i++) { var currentElement = elements[i]; double number; if (double.TryParse(currentElement, out number)) { queue.Enqueue(currentElement); } else if (mathFunctions.Contains(currentElement)) { stack.Push(currentElement); } else if (currentElement == ",") { if (!stack.Contains("(") || stack.Count == 0) { throw new ArgumentException("Invalid bracket or function operator!"); } while (stack.Peek() != "(") { string currentOperator = stack.Pop(); queue.Enqueue(currentOperator); } } else if (mathOperators.Contains(currentElement[0])) { //if not working refactor logic for operator while (stack.Count != 0 && mathOperators.Contains(stack.Peek()[0]) && OperatorPrecedence(currentElement) <= OperatorPrecedence(stack.Peek())) { queue.Enqueue(stack.Pop()); } stack.Push(currentElement); } else if (currentElement == "(") { stack.Push("("); } else if (currentElement == ")") { if (!stack.Contains("(") || stack.Count == 0) { throw new ArgumentException("Invalid bracket position!"); } while (stack.Count != 0 && stack.Peek() != "(") { queue.Enqueue(stack.Pop()); } stack.Pop(); if (stack.Count != 0 && mathFunctions.Contains(stack.Peek())) { queue.Enqueue(stack.Pop()); } } } while (stack.Count != 0) { if (barcketSymbols.Contains(stack.Peek()[0])) { throw new ArgumentException("Invalid bracket position!"); } queue.Enqueue(stack.Pop()); } return queue; }
public void PushPanel(Panel Container, Stack PanelStack, Type ControlType, bool MakeItVisible) { EnterWaitMode(); try { Control target = null; // Lookup a control of this type foreach (Control ctrl in Container.Controls) { if (ctrl.GetType() == ControlType) { target = ctrl; } } // Create a control of this type if it doesn't exist if (target == null) { target = (Control)(ControlType.GetConstructor(new Type[]{}).Invoke(new object[]{})); target.Dock = DockStyle.Fill; target.Visible = MakeItVisible; Container.Controls.Add(target); } else { target.Visible = MakeItVisible; } // Prevent two pushes to the same panel if (PanelStack.Count > 1 && PanelStack.Peek() == target) { return; } // Prevent recursive use of a panel in a context stack if (PanelStack.Contains(target)) { throw new ArgumentException(ControlType.FullName + " is already in use."); } // Hide previous MasterPanel, if exists if (PanelStack.Count > 0) { ((Control)(PanelStack.Peek())).Visible = false; } PanelStack.Push(target); } finally { LeaveWaitMode(); } }
internal override void CheckRecursion (Stack stack, ValidationEventHandler h, XmlSchema schema) { if (TargetGroup == null) return; if (stack.Contains (this)) throw new XmlSchemaException ("Circular group reference was found.", this, null); stack.Push (this); TargetGroup.Particle.CheckRecursion (stack, h, schema); stack.Pop (); }
/// <summary> /// Recursively processes the group. /// </summary> /// <param name="parentTypeAndId">String combination type and id of group to process next.</param> /// <param name="loopDetector">Stack of groups processed thus far. Used to detect loops.</param> /// <param name="parentGroups">Hash table of complex references grouped by parent id.</param> /// <param name="parentGroupsNeedingProcessing">Hash table of parent groups that still have nested groups that need to be flattened.</param> private void FlattenGroup(string parentTypeAndId, Stack loopDetector, Hashtable parentGroups, Hashtable parentGroupsNeedingProcessing) { Debug.Assert(parentGroupsNeedingProcessing.Contains(parentTypeAndId)); loopDetector.Push(parentTypeAndId); // push this complex reference parent identfier into the stack for loop verifying ArrayList allNewChildComplexReferences = new ArrayList(); ArrayList referencesToParent = (ArrayList)parentGroups[parentTypeAndId]; foreach (WixComplexReferenceRow wixComplexReferenceRow in referencesToParent) { Debug.Assert(ComplexReferenceParentType.ComponentGroup == wixComplexReferenceRow.ParentType || ComplexReferenceParentType.FeatureGroup == wixComplexReferenceRow.ParentType || ComplexReferenceParentType.Feature == wixComplexReferenceRow.ParentType || ComplexReferenceParentType.Module == wixComplexReferenceRow.ParentType || ComplexReferenceParentType.Product == wixComplexReferenceRow.ParentType || ComplexReferenceParentType.PatchFamilyGroup == wixComplexReferenceRow.ParentType || ComplexReferenceParentType.Patch == wixComplexReferenceRow.ParentType); Debug.Assert(parentTypeAndId == CombineTypeAndId(wixComplexReferenceRow.ParentType, wixComplexReferenceRow.ParentId)); // We are only interested processing when the child is a group. if ((ComplexReferenceChildType.ComponentGroup == wixComplexReferenceRow.ChildType) || (ComplexReferenceChildType.FeatureGroup == wixComplexReferenceRow.ChildType) || (ComplexReferenceChildType.PatchFamilyGroup == wixComplexReferenceRow.ChildType)) { string childTypeAndId = CombineTypeAndId(wixComplexReferenceRow.ChildType, wixComplexReferenceRow.ChildId); if (loopDetector.Contains(childTypeAndId)) { // Create a comma delimited list of the references that participate in the // loop for the error message. Start at the bottom of the stack and work the // way up to present the loop as a directed graph. object[] stack = loopDetector.ToArray(); StringBuilder loop = new StringBuilder(); for (int i = stack.Length - 1; i >= 0; --i) { loop.Append((string)stack[i]); if (0 < i) { loop.Append(" -> "); } } this.OnMessage(WixErrors.ReferenceLoopDetected(wixComplexReferenceRow.Table.Section == null ? null : wixComplexReferenceRow.Table.Section.SourceLineNumbers, loop.ToString())); // Cleanup the parentGroupsNeedingProcessing and the loopDetector just like the // exit of this method does at the end because we are exiting early. loopDetector.Pop(); parentGroupsNeedingProcessing.Remove(parentTypeAndId); return; // bail } // Check to see if the child group still needs to be processed. If so, // go do that so that we'll get all of that children's (and children's // children) complex references correctly merged into our parent group. if (parentGroupsNeedingProcessing.ContainsKey(childTypeAndId)) { this.FlattenGroup(childTypeAndId, loopDetector, parentGroups, parentGroupsNeedingProcessing); } // If the child is a parent to anything (i.e. the parent has grandchildren) // clone each of the children's complex references, repoint them to the parent // complex reference (because we're moving references up the tree), and finally // add the cloned child's complex reference to the list of complex references // that we'll eventually add to the parent group. ArrayList referencesToChild = (ArrayList)parentGroups[childTypeAndId]; if (null != referencesToChild) { foreach (WixComplexReferenceRow crefChild in referencesToChild) { // Only merge up the non-group items since groups are purged // after this part of the processing anyway (cloning them would // be a complete waste of time). if ((ComplexReferenceChildType.FeatureGroup != crefChild.ChildType) || (ComplexReferenceChildType.ComponentGroup != crefChild.ChildType) || (ComplexReferenceChildType.PatchFamilyGroup != crefChild.ChildType)) { WixComplexReferenceRow crefChildClone = crefChild.Clone(); Debug.Assert(crefChildClone.ParentId == wixComplexReferenceRow.ChildId); crefChildClone.Reparent(wixComplexReferenceRow); allNewChildComplexReferences.Add(crefChildClone); } } } } } // Add the children group's complex references to the parent // group. Clean out any left over groups and quietly remove any // duplicate complex references that occurred during the merge. referencesToParent.AddRange(allNewChildComplexReferences); referencesToParent.Sort(); for (int i = referencesToParent.Count - 1; i >= 0; --i) { WixComplexReferenceRow wixComplexReferenceRow = (WixComplexReferenceRow)referencesToParent[i]; if ((ComplexReferenceChildType.FeatureGroup == wixComplexReferenceRow.ChildType) || (ComplexReferenceChildType.ComponentGroup == wixComplexReferenceRow.ChildType) || (ComplexReferenceChildType.PatchFamilyGroup == wixComplexReferenceRow.ChildType)) { referencesToParent.RemoveAt(i); } else if (i > 0) { // Since the list is already sorted, we can find duplicates by simply // looking at the next sibling in the list and tossing out one if they // match. WixComplexReferenceRow crefCompare = (WixComplexReferenceRow)referencesToParent[i - 1]; if (0 == wixComplexReferenceRow.CompareToWithoutConsideringPrimary(crefCompare)) { referencesToParent.RemoveAt(i); } } } loopDetector.Pop(); // pop this complex reference off the stack since we're done verify the loop here parentGroupsNeedingProcessing.Remove(parentTypeAndId); // remove the newly processed complex reference }
private void makeStats(int stateNumber) { StateNode newStateNode; Stack exports=new Stack(); StateNode temp = this.first; while(temp!=null) { if(temp.StateNumber == stateNumber) { StateLawNode stateLaw = temp.laws.Head; while(stateLaw!=null) { LawsNode law = this.parsHead.findLaw(stateLaw.data.lawNum); PartsNode part = law.parts[stateLaw.data.dotPos]; if(part != null) { if(!exports.Contains(part.item.name)) { exports.Push(part.item.name); newStateNode=new StateNode(this.count+1); newStateNode.laws.add(stateLaw.data.dotPos+1,stateLaw.data.lawNum); StateLawNode remainLaw = stateLaw.next; while(remainLaw!=null) { LawsNode remLaw = this.parsHead.findLaw(remainLaw.data.lawNum); PartsNode remPart = remLaw.parts[remainLaw.data.dotPos]; if(remPart != null)//if2 { if(remPart.item.name==part.item.name) { newStateNode.laws.add(remainLaw.data.dotPos+1,remainLaw.data.lawNum); } }//if2 remainLaw = remainLaw.next; }//while this.stateTravers(newStateNode); StateNode existState; existState=this.isCreated(newStateNode); if(existState==null) { this.add(newStateNode); temp.exports.add(part.item.name,part.item.isTerminal,newStateNode.StateNumber); this.makeStats(newStateNode.StateNumber); } else { temp.exports.add(part.item.name,part.item.isTerminal,existState.StateNumber); } }//if new export }//if dot place is not end else { stateLaw.data.IsDotEnded = true; } stateLaw = stateLaw.next; } }//if find state temp = temp.next; }//while in state }
private void stateTravers(StateNode tra) { StateLawNode lawNode=tra.laws.Head; Stack lawExists=new Stack(); while(lawNode!=null) { LawsNode law=parsHead.findLaw(lawNode.data.lawNum); if(law!=null) { PartsNode part=law.parts[lawNode.data.dotPos]; if(part!=null) { if(!part.item.isTerminal ) { if(!lawExists.Contains(part.item.name)) { Stack lawNumbers = new Stack(); lawNumbers.Clear(); law.parts.Parent.Parent.NonTerminals.findLaws(part.item.name,lawNumbers); while(lawNumbers.Count != 0) tra.laws.add(0,(int)lawNumbers.Pop()); lawExists.Push(part.item.name); } } } } lawNode=lawNode.next; } }
public bool findFollows(string name,Stack follows) { PartsNode temp=first; while(temp!=null) { if(temp.item.name==name) { if(temp.next==null)//if this token is the last token and there is no token next of it { return true; } else if(temp.next.item.isTerminal)//if next token is a terminal element { if( !follows.Contains(temp.next.item.name)) follows.Push(temp.next.item.name); } else //if next token is a nonterminal element { PartsNode t = temp.next; nonTerminals head=this.parent.Parent.NonTerminals; while(head.getFirst(t.item.name,follows,false) ==true ) //we must chaeck next part { t = t.next; if( t == null) return true; if(t.item.isTerminal) { if(!follows.Contains(t.item.name) ) follows.Push(t.item.name); break; }//if }//while }//else }//if temp = temp.next; }//while return false; }
public bool findFirsts(Stack firsts,Stack checkNonTerm) { PartsNode temp = first; if(first == null) return true; while(temp!=null) { if(temp.item.isTerminal) { if(!firsts.Contains(temp.item.name)) firsts.Push(temp.item.name); return false; } if(!checkNonTerm.Contains(temp.item.name)) { checkNonTerm.Push(temp.item.name); if(!this.parent.Parent.NonTerminals.getFirst(temp.item.name,firsts,checkNonTerm,false)) { return false; } } else { if(!this.parent.Parent.NonTerminals.haveEpsilonLaw(temp.item.name)) { return false; } } temp= temp.next; } return true; }
private static CheckResult ReferenceVerificationHelper(IElement element, ref string cycleString, Stack<IElement> visitedElements) { List<string> typesReferenced = new List<string>(); //Assign the current VerificationId to identify nodes that have been visited ((INamedObjectContainer)element).VerificationIndex = VerificationId; if (visitedElements.Contains(element)) { cycleString += "The type " + element + " causes a circular reference"; return CheckResult.Failed; } else { visitedElements.Push(element); foreach (NamedObjectSave namedObject in element.NamedObjects) { if ((!namedObject.SetByContainer && !namedObject.SetByDerived) && namedObject.SourceType == SourceType.Entity) { EntitySave nosEntity = ObjectFinder.Self.GetEntitySave(namedObject.SourceClassType); if (nosEntity != null) { CheckResult returnValue = ReferenceVerificationHelper(nosEntity, ref cycleString, visitedElements); if (returnValue == CheckResult.Failed) { return CheckResult.Failed; } } } } visitedElements.Pop(); return CheckResult.Passed; } }
bool ResolveLoadDependencies(ArrayList addins, Stack depCheck, string id, bool optional) { if (IsAddinLoaded (id)) return true; if (depCheck.Contains (id)) throw new InvalidOperationException ("A cyclic addin dependency has been detected."); depCheck.Push (id); Addin iad = Registry.GetAddin (id); if (iad == null || !iad.Enabled) { if (optional) return false; else if (iad != null && !iad.Enabled) throw new MissingDependencyException (GettextCatalog.GetString ("The required addin '{0}' is disabled.", id)); else throw new MissingDependencyException (GettextCatalog.GetString ("The required addin '{0}' is not installed.", id)); } // If this addin has already been requested, bring it to the head // of the list, so it is loaded earlier than before. addins.Remove (iad); addins.Add (iad); foreach (Dependency dep in iad.AddinInfo.Dependencies) { AddinDependency adep = dep as AddinDependency; if (adep != null) { try { string adepid = Addin.GetFullId (iad.AddinInfo.Namespace, adep.AddinId, adep.Version); ResolveLoadDependencies (addins, depCheck, adepid, false); } catch (MissingDependencyException) { if (optional) return false; else throw; } } } if (iad.AddinInfo.OptionalDependencies != null) { foreach (Dependency dep in iad.AddinInfo.OptionalDependencies) { AddinDependency adep = dep as AddinDependency; if (adep != null) { string adepid = Addin.GetFullId (iad.Namespace, adep.AddinId, adep.Version); if (!ResolveLoadDependencies (addins, depCheck, adepid, true)) return false; } } } depCheck.Pop (); return true; }
public static void CalculateTime(Stack stack, int k) { // Add var startAdding = DateTime.Now; string test = "Test string"; for (int i = 0; i < k; i++) { stack.Push(test); } var finishAdding = DateTime.Now; Console.WriteLine("Addition time (" + k + " elements) : " + stack.GetType() + " " + (finishAdding - startAdding)); // Search var startSearch = DateTime.Now; for (int i = 0; i < k; i++) { bool a = stack.Contains(test); } var finishSearch = DateTime.Now; Console.WriteLine("Search time (" + k + " elements) : " + stack.GetType() + " " + (finishSearch - startSearch)); // Remove k = 1000000; var startRemoving = DateTime.Now; for (int i = 0; i < k; i++) { stack.Pop(); } var finishRemoving = DateTime.Now; Console.WriteLine("Removal time (" + k + " elements) : " + stack.GetType() + " " + (finishRemoving - startRemoving) + "\n"); }
/// <summary> /// Formats all public instance properties and fields from the specified object to a /// multi-line string. /// </summary> /// <param name="data">The object containing public properties and/or fields.</param> /// <param name="level">Indenting level.</param> /// <param name="seenObjects">Stack of objects already seen along this path. Used to break reference loops.</param> /// <returns>The formatted values of the object.</returns> public static string FormatValues(object data, int level = 0, Stack seenObjects = null) { // NOTE: Nullable<T> values need no special handling because as soon as they're passed // in an object variable, they're either null or the value itself boxed as their // internal type. (Source: http://stackoverflow.com/a/5194550/143684) try { if (seenObjects != null) { if (seenObjects.Contains(data)) { return "<reference loop>"; } if (seenObjects.Count >= 6) { return "<nesting too deep>"; } } if (data == null) { return "null"; } // Block certain namespaces that contain types that are impossible to dump this way Type dataType = data.GetType(); string typeNamespace = dataType.Namespace; string typeName = dataType.Name; if (typeNamespace == "System" && typeName == "Type" || typeNamespace == "System.Reflection" || typeNamespace == "System.Windows.Media" || typeNamespace == "System.Windows.Media.Imaging") // NOTE: This list of namespaces may not be complete. { return "<blocked type " + typeNamespace + "." + typeName + ">"; } if (data is bool || data is byte || data is ushort || data is uint || data is ulong || data is sbyte || data is short || data is int || data is long || data is float || data is double || data is decimal) { return Convert.ToString(data, CultureInfo.InvariantCulture); } if (data is char) { return "'" + data.ToString().Replace("\\", "\\\\").Replace("'", "\\'") + "'"; } if (data is string) { return "\"" + ((string)data).Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; } if (data is DateTime) { return ((DateTime)data).ToString("yyyy-MM-dd'T'HH:mm:ss.ffffff"); } if (data is DateTimeOffset) { return ((DateTimeOffset)data).ToString("yyyy-MM-dd'T'HH:mm:ss.ffffffK"); } if (data is TimeSpan) { return ((TimeSpan)data).ToString(); } if (data is DBNull) { return "DBNull"; } if (data is Enum) { return ((Enum)data).ToString("G") + " (" + ((Enum)data).ToString("D") + ")"; } if (data is Guid) { return ((Guid)data).ToString("B"); } if (data is IntPtr) { if (IntPtr.Size == 4) return "0x" + ((IntPtr)data).ToInt32().ToString("X4"); return "0x" + ((IntPtr)data).ToInt64().ToString("X8"); } if (data is UIntPtr) { if (UIntPtr.Size == 4) return "0x" + ((UIntPtr)data).ToUInt32().ToString("X4"); return "0x" + ((UIntPtr)data).ToUInt64().ToString("X8"); } if (data is StringBuilder) { return "\"" + ((StringBuilder)data).ToString().Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; } string indent = new string('\t', level); StringBuilder sb = new StringBuilder(); if (level > 0) { sb.AppendLine(); sb.Append(indent); } sb.Append("{"); int count = 0; if (seenObjects == null) seenObjects = new Stack(); seenObjects.Push(data); NameValueCollection nvc = data as NameValueCollection; if (nvc != null) { foreach (var key in nvc.AllKeys) { if (count++ > 0) sb.Append(","); sb.AppendLine(); sb.Append(indent); sb.Append("\t"); sb.Append(key); sb.Append(": "); try { sb.Append(FormatValues(nvc[key], level + 1, seenObjects)); } catch (Exception ex) { sb.Append("<").Append(ex.GetType().Name).Append(":").Append(ex.Message).Append(">"); } } } else { IEnumerable ie = data as IEnumerable; if (ie != null) { foreach (var item in ie) { if (count++ > 0) sb.Append(","); string str; try { str = FormatValues(item, level + 1, seenObjects); } catch (Exception ex) { str = "<" + ex.GetType().Name + ":" + ex.Message + ">"; } if (!str.StartsWith(Environment.NewLine, StringComparison.Ordinal)) { sb.AppendLine(); sb.Append(indent); sb.Append("\t"); } sb.Append(str); } } else { foreach (var property in data.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (count++ > 0) sb.Append(","); sb.AppendLine(); sb.Append(indent); sb.Append("\t"); sb.Append(property.Name); sb.Append(": "); try { sb.Append(FormatValues(property.GetValue(data, null), level + 1, seenObjects)); } catch (Exception ex) { sb.Append("<").Append(ex.GetType().Name).Append(":").Append(ex.Message).Append(">"); } } foreach (var field in data.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)) { if (count++ > 0) sb.Append(","); sb.AppendLine(); sb.Append(indent); sb.Append("\t"); sb.Append(field.Name); sb.Append(": "); try { sb.Append(FormatValues(field.GetValue(data), level + 1, seenObjects)); } catch (Exception ex) { sb.Append("<").Append(ex.GetType().Name).Append(":").Append(ex.Message).Append(">"); } } } } seenObjects.Pop(); sb.AppendLine(); sb.Append(indent); sb.Append("}"); return sb.ToString(); } catch (Exception ex) { return "<" + ex.GetType().Name + ":" + ex.Message + ">"; } }
private static object FindLayoutOrBranchOwner(DependencyObject node, out bool isSecondLineageWhenOwnerIsBranch) { isSecondLineageWhenOwnerIsBranch = false; var ancestoryStack = new Stack<DependencyObject>(); do { ancestoryStack.Push(node); node = VisualTreeHelper.GetParent(node); if (node is Layout) return node; var branch = node as Branch; if (branch == null) continue; isSecondLineageWhenOwnerIsBranch = ancestoryStack.Contains(branch.SecondContentPresenter); return branch; } while (node != null); return null; }
private void createOPFAuto(string strPath) { //fbdSplit.ShowDialog(); string strSavePath = strPath; System.Collections.Stack stkImgs; stkImgs = new System.Collections.Stack(); stkImgs.Clear(); MatchCollection mc; if (strSavePath.Length > 2) { try { Application.UseWaitCursor = true; toolStripStatusLabel1.Text = "Creating .OPF File... Please Wait"; this.Refresh(); string strContent = ""; string[] strLines; strContent = rtbContent.Text; strLines = strContent.Split('\n'); long i = strLines.Length; toolStripProgressBar1.Maximum = Convert.ToInt32(i) + 1; toolStripProgressBar1.Minimum = 1; toolStripProgressBar1.Value = 1; this.Refresh(); StreamWriter swFiles; string strFileNames = ""; string strChapterTitle = ""; //bool blSplitStart = false; bool blIdFound = false; bool blSrcFound = false; bool blTitleFound = false; bool blATitleFound = false; string strWrite = ""; string strIdFound = ""; string strSrcFound = ""; string strTitleFound = ""; string strATitleFound = ""; long lnImgIDCount = 1; swFiles = new StreamWriter(strSavePath + "\\content.opf"); swFiles.WriteLine("<?xml version=\"1.0\"?>\n" + "<package version=\"2.0\" xmlns=\"http://www.idpf.org/2007/opf\"\n" + " unique-identifier=\"isbn\">\n" + " <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n" + " xmlns:opf=\"http://www.idpf.org/2007/opf\">\n" + " <dc:title>***Book Name***</dc:title> \n" + " <dc:creator>***Author Name***</dc:creator>\n" + " <dc:language>en-US</dc:language> \n" + " <dc:rights>***Copyright***</dc:rights>\n" + " <dc:publisher>***Publisher***</dc:publisher>\n" + " <dc:identifier id=\"isbn\">****</dc:identifier>\n" + " <meta name=\"cover\" content=\"cover-image\"/> \n" + " </metadata>\n" + " <manifest>\n" + "\n" + "<!-- Images -->\n"); for (int j = 0; j < i; j++) { mc = Regex.Matches(strLines[j], "<img src=\"([^\"]+)\""); foreach (Match singleMc in mc) { if (stkImgs.Contains(singleMc.Result("$1")) == false) { stkImgs.Push(singleMc.Result("$1")); swFiles.WriteLine(" <item href=\"" + singleMc.Result("$1") + "\" id=\"img_" + lnImgIDCount.ToString() + "\" media-type=\"image/jpeg\"/>"); lnImgIDCount++; } } toolStripProgressBar1.Value = j + 1; } swFiles.WriteLine("<!-- NCX -->\n" + "\n" + "<item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\"/>\n" + "\n" + " <!-- CSS Style Sheets -->\n" + "\n" + "<item id=\"style_bv\" href=\"bv_ebook_style.css\" media-type=\"text/css\"/>\n" + "<item id=\"style_basic\" href=\"stylesheet.css\" media-type=\"text/css\"/>\n" + "<item id=\"pagetemplate\" href=\"page-template.xpgt\" media-type=\"application/vnd.adobe-page-template+xml\"/>\n" + "<!-- Content Documents -->\n" + "\n"); string strIDRef = " <spine toc=\"ncx\">"; for (int j = 0; j < i; j++) { if (strLines[j].StartsWith("<split")) { strFileNames = Regex.Replace(strLines[j], "^<split filename=\"([^<>]+)\">$", "$1"); //blSplitStart = true; //swFiles.WriteLine(" <content src=\"" + strFileNames + "\"/>"); blSrcFound = true; strSrcFound = strFileNames; } if (strLines[j].StartsWith("<div>") == true) { j++; if (strLines[j].StartsWith("<a id=") == true) { strChapterTitle = Regex.Replace(strLines[j], "^<a id=\"([^<]*)\"></a>(.*)$", "$1"); //swFiles.WriteLine(" <navPoint class=\"chapter\" id=\"" + strChapterTitle + "\" playOrder=\"1\">"); blIdFound = true; strIdFound = strChapterTitle; } } if (strLines[j].StartsWith("</split")) { strWrite = ""; if (blIdFound == true) { if (blSrcFound == true) { strWrite = " <item id=\"" + strIdFound + "\" href=\"" + strSrcFound + "\" media-type=\"application/xhtml+xml\"/>"; swFiles.WriteLine(strWrite); strIDRef = strIDRef + "\n" + " <itemref idref=\"" + strIdFound + "\" linear=\"yes\" />"; } } blIdFound = false; blSrcFound = false; blTitleFound = false; blATitleFound = false; strIdFound = ""; strSrcFound = ""; strTitleFound = ""; strATitleFound = ""; //blSplitStart = false; } toolStripProgressBar1.Value = j + 1; } swFiles.WriteLine(" </manifest>\n"); swFiles.WriteLine(strIDRef); swFiles.WriteLine("<guide>"); for (int j = 0; j < i; j++) { if (strLines[j].StartsWith("<split")) { strFileNames = Regex.Replace(strLines[j], "^<split filename=\"([^<>]+)\">$", "$1"); //blSplitStart = true; //swFiles.WriteLine(" <content src=\"" + strFileNames + "\"/>"); blSrcFound = true; strSrcFound = strFileNames; } if (strLines[j].StartsWith("<head>") == true) { j++; if (strLines[j].StartsWith("<title>") == true) { strChapterTitle = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1"); //swFiles.WriteLine(" <text>" + strChapterTitle + "</text>"); blTitleFound = true; strTitleFound = strChapterTitle; } } if (strLines[j].StartsWith("<h2 class=\"chaptertitle\">") == true) { strChapterTitle = Regex.Replace(strLines[j], "^<h2 class=\"chaptertitle\">(.*)</h2>$", "$1"); strChapterTitle = RemoveTag(strChapterTitle); blATitleFound = true; strATitleFound = strChapterTitle; } if (strLines[j].StartsWith("<div>") == true) { j++; if (strLines[j].StartsWith("<a id=") == true) { strChapterTitle = Regex.Replace(strLines[j], "^<a id=\"([^<]*)\"></a>(.*)$", "$1"); //swFiles.WriteLine(" <navPoint class=\"chapter\" id=\"" + strChapterTitle + "\" playOrder=\"1\">"); blIdFound = true; strIdFound = strChapterTitle; } } if (strLines[j].StartsWith("</split")) { strWrite = ""; if (blIdFound == true) { strWrite = strIdFound; if (blATitleFound == true) { //strATitleFound } else { if (blTitleFound == true) { strATitleFound = strTitleFound; } } strWrite = "<reference type=\"text\"\n" + " title=\"" + strATitleFound + "\"\n" + " href=\"" + strSrcFound + "\"/>"; swFiles.WriteLine(strWrite); } blIdFound = false; blSrcFound = false; blTitleFound = false; blATitleFound = false; strIdFound = ""; strSrcFound = ""; strTitleFound = ""; strATitleFound = ""; //blSplitStart = false; } toolStripProgressBar1.Value = j + 1; } swFiles.WriteLine("</guide>\n</package>"); swFiles.Flush(); swFiles.Close(); this.Refresh(); rtbContent.Text = string.Join("\n", strLines); toolStripProgressBar1.Value = toolStripProgressBar1.Maximum; toolStripStatusLabel1.Text = "Ready"; Application.UseWaitCursor = false; } catch { MessageBox.Show("Unexpected Error", "ERR", MessageBoxButtons.OK); } } }
public override bool Contains(Object obj) { lock (_root) { return(_s.Contains(obj)); } }
/*Function takes an array of type string containg elements of maze and returns reversed solution path as a stack*/ static Stack GetPathForMaze(string[,] mazeArray, int[,] indexS, int[,] indexF) { //Stack returnStack = new Stack(); Stack adjacentElems = new Stack(); Stack pathStack = new Stack(); int row = mazeArray.GetLength(0); //number of rows int col = mazeArray.GetLength(1); //number of cols int i = 0, j = 0, startIndex = 0; //to track the neighbours visited adjacent to the point in context. int[,] adjancencyMatrix = new int[row, col]; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { adjancencyMatrix[i, j] = 0; } } try { //to handle floating starting point across top boundary.. for (int k = 0; k < col; k++) { if (mazeArray[0, k].Equals("S")) { startIndex = k; break; } } int[,] coordinates = new int[1, 2]; int[,] coord = new int[1, 2]; //coordinates[0, 0] = 0; //coordinates[0, 1] = startIndex; coordinates[0, 0] = indexS[0, 0]; coordinates[0, 1] = indexS[0, 1]; adjacentElems.Push(coordinates); adjancencyMatrix[coordinates[0, 0], coordinates[0, 1]] = 1; int movement; //used to track if any useful movement in maze while (adjacentElems.Count > 0) { movement = 0; coord = (int[,])adjacentElems.Peek(); if (!pathStack.Contains(coord)) pathStack.Push(coord); //checking element below if (((coord[0, 0] + 1) < row) && (mazeArray[(coord[0, 0] + 1), coord[0, 1]].Equals("0") || mazeArray[(coord[0, 0] + 1), coord[0, 1]].Equals("F")) && (adjancencyMatrix[(coord[0, 0] + 1), coord[0, 1]] == 0)) { int[,] tempCoord = new int[1, 2]; tempCoord = (int[,])coord.Clone(); tempCoord[0, 0] += 1; adjacentElems.Push(tempCoord); adjancencyMatrix[tempCoord[0, 0], tempCoord[0, 1]] = 1; //marking visited.. movement = 1; if (mazeArray[(tempCoord[0, 0]), tempCoord[0, 1]].Equals("F")) { pathStack.Push(tempCoord); //pathQueue.Enqueue("F"); break; } } //checking element right if (((coord[0, 1] + 1) < col) && (mazeArray[coord[0, 0], (coord[0, 1] + 1)].Equals("0") || mazeArray[coord[0, 0], (coord[0, 1] + 1)].Equals("F")) && (adjancencyMatrix[coord[0, 0], (coord[0, 1] + 1)] == 0)) { int[,] tempCoord = new int[1, 2]; tempCoord = (int[,])coord.Clone(); tempCoord[0, 1] += 1; adjacentElems.Push(tempCoord); adjancencyMatrix[tempCoord[0, 0], tempCoord[0, 1]] = 1; movement = 1; if (mazeArray[(tempCoord[0, 0]), tempCoord[0, 1]].Equals("F")) { pathStack.Push(tempCoord); //pathQueue.Enqueue("F"); break; } } //checking element left if (((coord[0, 1] - 1) >= 0) && (mazeArray[coord[0, 0], (coord[0, 1] - 1)].Equals("0") || mazeArray[coord[0, 0], (coord[0, 1] - 1)].Equals("F")) && (adjancencyMatrix[coord[0, 0], (coord[0, 1] - 1)] == 0)) { int[,] tempCoord = new int[1, 2]; tempCoord = (int[,])coord.Clone(); tempCoord[0, 1] -= 1; adjacentElems.Push(tempCoord); adjancencyMatrix[tempCoord[0, 0], tempCoord[0, 1]] = 1; movement = 1; if (mazeArray[(tempCoord[0, 0]), tempCoord[0, 1]].Equals("F")) { pathStack.Push(tempCoord); //pathQueue.Enqueue("F"); break; } } //checking element above if (((coord[0, 0] - 1) >= 0) && (mazeArray[(coord[0, 0] - 1), coord[0, 1]].Equals("0") || mazeArray[(coord[0, 0] - 1), coord[0, 1]].Equals("F")) && (adjancencyMatrix[(coord[0, 0] - 1), coord[0, 1]] == 0)) { int[,] tempCoord = new int[1, 2]; tempCoord = (int[,])coord.Clone(); tempCoord[0, 0] -= 1; adjacentElems.Push(tempCoord); adjancencyMatrix[tempCoord[0, 0], tempCoord[0, 1]] = 1; movement = 1; if (mazeArray[(tempCoord[0, 0]), tempCoord[0, 1]].Equals("F")) { pathStack.Push(tempCoord); //pathQueue.Enqueue("F"); break; } } //if nothing added, last added needs to be poped. pop the last elem if (movement == 0) { adjacentElems.Pop(); pathStack.Pop(); } } } catch (Exception ex) { Console.WriteLine(ex.Message + " : " + ex.StackTrace); } return pathStack; }
object GetInstance(Registration registration, IInstanceStore tempInstanceStore, Stack<Type> buildStack) { if (buildStack.Contains(registration.ConcreteType)) throw new ContainerException("Cyclic dependency detected when trying to construct `" + registration.ConcreteType.AssemblyQualifiedName + "`", buildStack); buildStack.Push(registration.ConcreteType); var constructor = registration.Ctor ?? (container => { var constructors = registration.ConcreteType.GetConstructors(); var ctorsWithParams = constructors.Select(c => new {ctor = c, parameters = c.GetParameters()}); var orderedEnumerable = ctorsWithParams.OrderBy(x => x.parameters.Length); foreach (var ctor in orderedEnumerable) { var parameterInfos = ctor.parameters.Select(p => p.ParameterType); this.CheckDependencies(registration.ConcreteType, parameterInfos, registration.Lifecycle, tempInstanceStore, buildStack); var parameters = new object[ctor.parameters.Length]; for (var i = 0; i < ctor.parameters.Length; i++) { var newBuildStack = new Stack<Type>(buildStack.Reverse()); if (ctor.parameters[i].ParameterType.IsGenericType && ctor.parameters[i].ParameterType.GetGenericTypeDefinition() == typeof (IEnumerable<>)) { var genericArgument = ctor.parameters[i].ParameterType.GetGenericArguments()[0]; parameters[i] = this.ResolveAll(genericArgument, newBuildStack); } else { parameters[i] = this.Resolve(ctor.parameters[i].ParameterType, tempInstanceStore, newBuildStack); } } try { return ctor.ctor.Invoke(parameters); } catch(Exception e) { throw new ContainerException("Cannot create type `" + ctor.ctor.DeclaringType.FullName + "`", buildStack, e); } } throw new ContainerException("Unable to construct `" + registration.ConcreteType.AssemblyQualifiedName + "`", buildStack); }); return constructor(this); }
private string ResolveEmbedded (string embeddedtag, string[] tagparts, Stack<string> resolvestack) { string tag = Unembed(embeddedtag, tagparts); return resolvestack.Contains(tag) ? tag : Resolve(tag, resolvestack); }
/// <summary> /// Recursively explores the <see cref="Release"/> definitions to determine /// the shortest conversion path between two releases. /// </summary> /// <param name="source">The source <see cref="Release"/> for the search.</param> /// <param name="target">The target <see cref="Release"/> for the search.</param> /// <param name="stack">A <see cref="Stack"/> used to detect cycles.</param> /// <returns>A <B>Conversion</B> that transforms between the source and /// target releases or <c>null</c> if no conversion is possible.</returns> private static Conversion DepthFirstSearch(Release source, Release target, Stack stack) { Conversion best = null; if (!stack.Contains (source)) { stack.Push (source); foreach (Conversion first in source.SourceConversions) { Release release = first.TargetRelease; Conversion result = null; if (release == target) result = first; else { Conversion second = DepthFirstSearch (release, target, stack); if (second != null) result = new IndirectConversion (first, second); } if (result != null) { if ((best == null)||(result.Complexity < best.Complexity)) best = result; } } stack.Pop (); } return (best); }
/// <summary> /// This method checks to see if the BasedOn hierarchy contains /// a loop in the chain of references. /// </summary> /// <remarks> /// Classic "when did we enter the cycle" problem where we don't know /// what to start remembering and what to check against. Brute- /// force approach here is to remember everything with a stack /// and do a linear comparison through everything. Since the Style /// BasedOn hierarchy is not expected to be large, this should be OK. /// </remarks> private void CheckForCircularBasedOnReferences() { Stack basedOnHierarchy = new Stack(10); // 10 because that's the default value (see MSDN) and the perf team wants us to specify something. Style latestBasedOn = this; while( latestBasedOn != null ) { if( basedOnHierarchy.Contains( latestBasedOn ) ) { // Uh-oh. We've seen this Style before. This means // the BasedOn hierarchy contains a loop. throw new InvalidOperationException(SR.Get( SRID.StyleBasedOnHasLoop)); // Debugging note: If we stop here, the basedOnHierarchy // object is still alive and we can browse through it to // see what we've explored. (This does not apply if // somebody catches this exception and re-throws.) } // Haven't seen it, push on stack and go to next level. basedOnHierarchy.Push( latestBasedOn ); latestBasedOn = latestBasedOn.BasedOn; } return; }
private static void ReorderStack(GeneralTransformationRule originalTransformationRule, Computation comp, Stack<GeneralTransformationRule> ruleStack) { var testTransformationRule = originalTransformationRule; var missingStack = new Stack<GeneralTransformationRule>(); while (!ruleStack.Contains(testTransformationRule)) { missingStack.Push(testTransformationRule); testTransformationRule = testTransformationRule.BaseRule; } while (ruleStack.Peek() != testTransformationRule) { ruleStack.Pop(); if (ruleStack.Count == 0) throw new InvalidOperationException("The rule stack from the transformation rule did not contain the base rule of the computation"); } while (missingStack.Count > 0) { testTransformationRule = missingStack.Pop(); ruleStack.Push(testTransformationRule); } while (!testTransformationRule.IsLeafTransformation) { var found = false; foreach (var next in testTransformationRule.Children) { if (next.IsInstantiating(comp)) { testTransformationRule = next; ruleStack.Push(next); found = true; break; } } if (!found) break; } }
private static XmlRpcType GetXmlRpcType(Type t, Stack<Type> typeStack) { XmlRpcType ret; if (t == typeof(Int32)) ret = XmlRpcType.tInt32; else if (t == typeof(Int64)) ret = XmlRpcType.tInt64; else if (t == typeof(Boolean)) ret = XmlRpcType.tBoolean; else if (t == typeof(String)) ret = XmlRpcType.tString; else if (t == typeof(Double)) ret = XmlRpcType.tDouble; else if (t == typeof(DateTime)) ret = XmlRpcType.tDateTime; else if (t == typeof(byte[])) ret = XmlRpcType.tBase64; else if (t == typeof(XmlRpcStruct)) { ret = XmlRpcType.tHashtable; } else if (t == typeof(Array)) ret = XmlRpcType.tArray; else if (t.IsArray) { #if (!COMPACT_FRAMEWORK) Type elemType = t.GetElementType(); if (elemType != typeof(Object) && GetXmlRpcType(elemType, typeStack) == XmlRpcType.tInvalid) { ret = XmlRpcType.tInvalid; } else { if (t.GetArrayRank() == 1) // single dim array ret = XmlRpcType.tArray; else ret = XmlRpcType.tMultiDimArray; } #else //!! check types of array elements if not Object[] Type elemType = null; string[] checkSingleDim = Regex.Split(t.FullName, "\\[\\]$"); if (checkSingleDim.Length > 1) // single dim array { elemType = Type.GetType(checkSingleDim[0]); ret = XmlRpcType.tArray; } else { string[] checkMultiDim = Regex.Split(t.FullName, "\\[,[,]*\\]$"); if (checkMultiDim.Length > 1) { elemType = Type.GetType(checkMultiDim[0]); ret = XmlRpcType.tMultiDimArray; } else ret = XmlRpcType.tInvalid; } if (elemType != null) { if (elemType != typeof(Object) && GetXmlRpcType(elemType, typeStack) == XmlRpcType.tInvalid) { ret = XmlRpcType.tInvalid; } } #endif } else if (t == typeof(int?)) ret = XmlRpcType.tInt32; else if (t == typeof(long?)) ret = XmlRpcType.tInt64; else if (t == typeof(Boolean?)) ret = XmlRpcType.tBoolean; else if (t == typeof(Double?)) ret = XmlRpcType.tDouble; else if (t == typeof(DateTime?)) ret = XmlRpcType.tDateTime; else if (t == typeof(void)) { ret = XmlRpcType.tVoid; } else if ((t.IsValueType && !t.IsPrimitive && !t.IsEnum) || t.IsClass) { // if type is struct or class its only valid for XML-RPC mapping if all // its members have a valid mapping or are of type object which // maps to any XML-RPC type MemberInfo[] mis = t.GetMembers(); foreach (MemberInfo mi in mis) { if (Attribute.IsDefined(mi, typeof(NonSerializedAttribute))) continue; if (mi.MemberType == MemberTypes.Field) { FieldInfo fi = (FieldInfo)mi; if (typeStack.Contains(fi.FieldType)) continue; try { typeStack.Push(fi.FieldType); if ((fi.FieldType != typeof(Object) && GetXmlRpcType(fi.FieldType, typeStack) == XmlRpcType.tInvalid)) { return XmlRpcType.tInvalid; } } finally { typeStack.Pop(); } } else if (mi.MemberType == MemberTypes.Property) { PropertyInfo pi = (PropertyInfo)mi; if (typeStack.Contains(pi.PropertyType)) continue; try { typeStack.Push(pi.PropertyType); if ((pi.PropertyType != typeof(Object) && GetXmlRpcType(pi.PropertyType, typeStack) == XmlRpcType.tInvalid)) { return XmlRpcType.tInvalid; } } finally { typeStack.Pop(); } } } ret = XmlRpcType.tStruct; } else if (t.IsEnum) { Type enumBaseType = Enum.GetUnderlyingType(t); if (enumBaseType == typeof(int) || enumBaseType == typeof(byte) || enumBaseType == typeof(sbyte) || enumBaseType == typeof(short) || enumBaseType == typeof(ushort)) ret = XmlRpcType.tInt32; else if (enumBaseType == typeof(long) || enumBaseType == typeof(UInt32)) ret = XmlRpcType.tInt64; else ret = XmlRpcType.tInvalid; } else ret = XmlRpcType.tInvalid; return ret; }
private static void TestStackQueneCollection() { Random rand = new Random(); Stopwatch sw = new Stopwatch(); Stack<int> stack = new Stack<int>(); Queue<int> queue = new Queue<int>(); int el; //Stack sw.Reset(); Console.Write("Adding to Stack..."); sw.Start(); for (int i = 0; i < 100000; i++) { stack.Push(i); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Search in Stack..."); sw.Start(); for (int i = 0; i < 100000; i++) { var index = stack.Contains(50000); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Removing from Stack..."); sw.Start(); for (int i = 0; i < 100000; i++) { el = stack.Pop(); el++; } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks\n"); sw.Reset(); //Queue Console.Write("Add to Queue..."); sw.Start(); for (int i = 0; i < 100000; i++) { queue.Enqueue(i); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Search in Queue..."); sw.Start(); for (int i = 0; i < 100000; i++) { queue.Contains(50000); } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks"); sw.Reset(); Console.Write("Removing from Queue..."); sw.Start(); for (int i = 0; i < 100000; i++) { el = queue.Dequeue(); el++; } sw.Stop(); Console.WriteLine(" Time used: " + sw.ElapsedTicks + " ticks\n"); }