public override object Evaluate(XPathExpression xpath, object context) { var result1 = Left.Evaluate(xpath, context); var result2 = Right.Evaluate(xpath, context); return EvaluateOperands(result1, result2); }
public override object Evaluate(XPathExpression xpath, object context) { object result = null; var parent = GetContextNode(context); if (parent == null) { return null; } while (parent != null) { if (Name == "*" || string.Equals(parent.ItemName, Name, StringComparison.OrdinalIgnoreCase)) { Process(xpath, parent, Predicate, NextStep, ref result); if (Break(xpath, result)) { break; } } parent = parent.GetParent(); } return result; }
public override object Evaluate(XPathExpression xpath, object context) { object result = null; Iterate(xpath, context, ref result); return result; }
public override object Evaluate(XPathExpression xpath, object context) { object result = null; Process(xpath, context, _predicate, NextStep, ref result); return result; }
public override object Evaluate(XPathExpression xpath, object context) { var item = context as IXPathItem; if (item == null) { return null; } if (_field) { switch (Name.ToLowerInvariant()) { case "@name": return item.ItemName; case "@key": return item.ItemName.ToLowerInvariant(); case "@id": return item.ItemId; case "@templatename": return item.TemplateName; case "@templatekey": return item.TemplateName.ToLowerInvariant(); case "@templateid": return item.TemplateId; case "@path": return item.ItemPath; default: return item[Name]; } } object result = null; foreach (var child in item.GetChildren()) { if (Name != "*" && !string.Equals(Name, child.ItemName, StringComparison.OrdinalIgnoreCase)) { continue; } Process(xpath, child, Predicate, NextStep, ref result); if (Break(xpath, result)) { break; } } return result; }
public XRDParser(Stream xrd) { doc_ = new XPathDocument (xrd); result_ = new XRDDocument (); cursor_ = doc_.CreateNavigator(); expires_exp_ = cursor_.Compile ("/XRD/Expires"); subject_exp_ = cursor_.Compile ("/XRD/Subject"); aliases_exp_ = cursor_.Compile ("/XRD/Alias"); types_exp_ = cursor_.Compile ("/XRD/Type"); link_rel_exp_ = cursor_.Compile ("/XRD/Link/Rel"); link_uri_exp_ = cursor_.Compile ("/XRD/Link/URI"); link_mediatype_exp_ = cursor_.Compile ("/XRD/Link/MediaType"); }
public override object Evaluate(XPathExpression xpath, object context) { object result = null; var item = context as IXPathItem; if (item == null) { return null; } var parent = item.GetParent(); if (parent == null) { return null; } Process(xpath, parent, null, NextStep, ref result); return result; }
public override object Evaluate(XPathExpression xpath, object context) { object result = null; var item = context as IXPathItem; if (item == null) { return null; } var parent = item.GetParent(); if (parent == null) { return null; } var following = false; foreach (var child in parent.GetChildren()) { if (following) { if (_name == "*" || string.Equals(child.ItemName, _name, StringComparison.OrdinalIgnoreCase)) { Process(xpath, child, _predicate, NextStep, ref result); if (Break(xpath, result)) { break; } } } if (child == context) { following = true; } } return result; }
void Success3(string expression) { var xpath = XPathExpression.Compile(expression); }
private void ParseConceptualConfiguration(XPathNavigator configuration) { XPathNavigator linkNavigator = configuration.SelectSingleNode( "conceptualLinks"); if (linkNavigator == null) { return; } string tempText = linkNavigator.GetAttribute("enabled", String.Empty); if (String.IsNullOrEmpty(tempText)) { return; } _hasTopicLinks = Convert.ToBoolean(tempText); if (!_hasTopicLinks) { return; } tempText = linkNavigator.GetAttribute("type", String.Empty); if (String.IsNullOrEmpty(tempText)) { _hasTopicLinks = false; this.WriteMessage(MessageLevel.Error, "The 'type' parameter for the conceptual links is not specified, but required."); return; } try { // convert the link type to an enumeration member _baseLinkType = (ConceptualLinkType)Enum.Parse(typeof(ConceptualLinkType), tempText, true); } catch (ArgumentException) { _hasTopicLinks = false; this.WriteMessage(MessageLevel.Error, String.Format( "'{0}' is not a valid link type.", tempText)); return; } tempText = linkNavigator.GetAttribute("showBrokenLinkText", String.Empty); if (!String.IsNullOrEmpty(tempText)) { _showBrokenLinkText = Convert.ToBoolean(tempText); } tempText = linkNavigator.GetAttribute("showText", String.Empty); if (!String.IsNullOrEmpty(tempText)) { _showText = tempText.Equals("true", StringComparison.OrdinalIgnoreCase); } XPathNodeIterator targetsNodes = linkNavigator.Select("conceptualTargets"); if (targetsNodes == null || targetsNodes.Count == 0) { _hasTopicLinks = false; return; } _targetController = ConceptualTargetController.GetInstance("reference"); foreach (XPathNavigator targetsNode in targetsNodes) { // the base directory containing target; required string baseValue = targetsNode.GetAttribute("base", String.Empty); if (String.IsNullOrEmpty(baseValue)) { this.WriteMessage(MessageLevel.Error, "Every targets element must have a base attribute that specifies the path to a directory of target metadata files."); } baseValue = Environment.ExpandEnvironmentVariables(baseValue); if (!Directory.Exists(baseValue)) { this.WriteMessage(MessageLevel.Error, String.Format( "The specified target metadata directory '{0}' does not exist.", baseValue)); } // an xpath expression to construct a file name // (not currently used; pattern is hard-coded to $target.cmp.xml string filesValue = targetsNode.GetAttribute("files", String.Empty); // an xpath expression to construct a url string urlValue = targetsNode.GetAttribute("url", String.Empty); XPathExpression urlExpression; if (String.IsNullOrEmpty(urlValue)) { urlExpression = XPathExpression.Compile( "concat(/metadata/topic/@id,'.htm')"); } else { urlExpression = CompileXPathExpression(urlValue); } // an xpath expression to construct link text string textValue = targetsNode.GetAttribute("text", String.Empty); XPathExpression textExpression; if (String.IsNullOrEmpty(textValue)) { textExpression = XPathExpression.Compile( "string(/metadata/topic/title)"); } else { textExpression = CompileXPathExpression(textValue); } // the type of link to create to targets found in the directory; required string typeValue = targetsNode.GetAttribute("type", String.Empty); if (String.IsNullOrEmpty(typeValue)) { WriteMessage(MessageLevel.Error, "Every targets element must have a type attribute that specifies what kind of link to create to targets found in that directory."); } // convert the link type to an enumeration member ConceptualLinkType type = ConceptualLinkType.None; try { type = (ConceptualLinkType)Enum.Parse(typeof(ConceptualLinkType), typeValue, true); } catch (ArgumentException) { this.WriteMessage(MessageLevel.Error, String.Format( "'{0}' is not a valid link type.", typeValue)); } // We have all the required information; create a TargetDirectory // and add it to our collection ConceptualTargetDirectory targetDirectory = new ConceptualTargetDirectory(baseValue, urlExpression, textExpression, type); _targetController.Add(targetDirectory); } if (_targetController.Count == 0) { _hasTopicLinks = false; return; } this.WriteMessage(MessageLevel.Info, String.Format( "Collected {0} conceptual targets directories.", _targetController.Count)); }
public override object Evaluate(XPathExpression xpath, object context) { return xpath.EvaluateFunction(this, _arguments.ToArray(), context); }
//===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="parent">The parent build component</param> /// <param name="basePath">The base path in which to find the files</param> /// <param name="fileXPath">The file XPath expression used to get the file from which to copy elements</param> /// <param name="sourceXPath">The source XPath expression</param> /// <param name="targetXPath">The target XPath expression</param> public CopyFromFilesCommand(BuildComponentCore parent, string basePath, string fileXPath, string sourceXPath, string targetXPath) : base(parent, sourceXPath, targetXPath) { this.BasePath = basePath; this.SourceFile = XPathExpression.Compile(fileXPath); }
/// <summary> /// Update the information for the selected Armor Mod. /// </summary> private void UpdateSelectedArmor() { // Retireve the information for the selected Accessory. XmlNode objXmlMod = _objXmlDocument.SelectSingleNode("/chummer/mods/mod[name = \"" + lstMod.SelectedValue + "\"]"); // Extract the Avil and Cost values from the Cyberware info since these may contain formulas and/or be based off of the Rating. // This is done using XPathExpression. XPathNavigator nav = _objXmlDocument.CreateNavigator(); lblA.Text = objXmlMod["armor"].InnerText; nudRating.Maximum = Convert.ToDecimal(objXmlMod["maxrating"].InnerText, GlobalOptions.Instance.CultureInfo); if (nudRating.Maximum <= 1) { nudRating.Enabled = false; } else { nudRating.Enabled = true; if (nudRating.Minimum == 0) { nudRating.Value = 1; nudRating.Minimum = 1; } } string strAvail = ""; string strAvailExpr = ""; strAvailExpr = objXmlMod["avail"].InnerText; XPathExpression xprAvail; if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" || strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R") { strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1); // Remove the trailing character if it is "F" or "R". strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1); } try { xprAvail = nav.Compile(strAvailExpr.Replace("Rating", nudRating.Value.ToString())); lblAvail.Text = (Convert.ToInt32(nav.Evaluate(xprAvail))).ToString() + strAvail; } catch { lblAvail.Text = objXmlMod["avail"].InnerText; } lblAvail.Text = lblAvail.Text.Replace("R", LanguageManager.Instance.GetString("String_AvailRestricted")).Replace("F", LanguageManager.Instance.GetString("String_AvailForbidden")); // Cost. string strCost = objXmlMod["cost"].InnerText.Replace("Rating", nudRating.Value.ToString()); strCost = strCost.Replace("Armor Cost", _intArmorCost.ToString()); XPathExpression xprCost = nav.Compile(strCost); // Apply any markup. double dblCost = Convert.ToDouble(nav.Evaluate(xprCost), GlobalOptions.Instance.CultureInfo); dblCost *= 1 + (Convert.ToDouble(nudMarkup.Value, GlobalOptions.Instance.CultureInfo) / 100.0); lblCost.Text = String.Format("{0:###,###,##0¥}", dblCost); int intCost = Convert.ToInt32(dblCost); lblTest.Text = _objCharacter.AvailTest(intCost, lblAvail.Text); // Capacity. // XPathExpression cannot evaluate while there are square brackets, so remove them if necessary. string strCapacity = objXmlMod["armorcapacity"].InnerText; // Handle YNT Softweave if (strCapacity.Contains("Capacity")) { lblCapacity.Text = "+50%"; } else { if (strCapacity.StartsWith("FixedValues")) { string[] strValues = strCapacity.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(','); strCapacity = strValues[Convert.ToInt32(nudRating.Value) - 1]; } strCapacity = strCapacity.Substring(1, strCapacity.Length - 2); XPathExpression xprCapacity = nav.Compile(strCapacity.Replace("Rating", nudRating.Value.ToString())); if (_objCapacityStyle == CapacityStyle.Standard) { lblCapacity.Text = "[" + nav.Evaluate(xprCapacity) + "]"; } else if (_objCapacityStyle == CapacityStyle.PerRating) { lblCapacity.Text = "[" + nudRating.Value.ToString() + "]"; } else if (_objCapacityStyle == CapacityStyle.Zero) { lblCapacity.Text = "[0]"; } } if (chkFreeItem.Checked) { lblCost.Text = String.Format("{0:###,###,##0¥}", 0); } string strBook = _objCharacter.Options.LanguageBookShort(objXmlMod["source"].InnerText); string strPage = objXmlMod["page"].InnerText; if (objXmlMod["altpage"] != null) { strPage = objXmlMod["altpage"].InnerText; } lblSource.Text = strBook + " " + strPage; tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(objXmlMod["source"].InnerText) + " " + LanguageManager.Instance.GetString("String_Page") + " " + strPage); }
/// <summary> /// /// </summary> /// <param name="Navigator"></param> /// <param name="XPath"></param> /// <returns></returns> public static bool NodeExists(XPathNavigator Navigator, XPathExpression XPath) { XPathNodeIterator i = Navigator.Select(XPath); return(i.MoveNext()); }
public ArrayList IndexDocuments(ArrayList fnames) { ArrayList failures = new ArrayList(); // create index if it doesn't exist IndexModifier writer = File.Exists(Path.Combine(_indexName, "segments")) ? new IndexModifier(_indexName, new StandardAnalyzer(), false) : new IndexModifier(_indexName, new StandardAnalyzer(), true); foreach (string fname in fnames) { try { if (_verbose) { _messageStringBuilder.AppendFormat("Indexing file: {0}\n", fname); } XPathDocument pathDocument = new XPathDocument(new StreamReader(fname)); XPathNavigator pathNavigator = pathDocument.CreateNavigator(); pathNavigator.MoveToFirstChild(); string docname = pathNavigator.Name; if (_verbose) { _messageStringBuilder.AppendFormat("Found document type: {0}\n", docname); } foreach (RuleSet ruleSet in _ruleSets) { if (ruleSet.Name == docname) { if (_verbose) { _messageStringBuilder.Append("Found matching ruleset, indexing.\n"); } pathNavigator.MoveToRoot(); // first thing is to read and cache global fields // these are duped for each document found ArrayList globals = new ArrayList(); foreach (Rule rule in ruleSet.GlobalRules) { XPathExpression pathExpression = pathNavigator.Compile(rule.XPath); XPathNodeIterator pathNodeIterator = pathNavigator.Select(pathExpression); while (pathNodeIterator.MoveNext()) { if (_verbose) { _messageStringBuilder.AppendFormat("Found field '{0}' value '{1}'\n", rule.Name, pathNodeIterator.Current.Value); } globals.Add(new RuleValue(rule, pathNodeIterator.Current.Value)); } } // ok, all globals cached. now to index documents pathNavigator.MoveToRoot(); foreach (DocItem docItem in ruleSet.DocItems) { XPathExpression pathExpression = pathNavigator.Compile(docItem.XPath); XPathNodeIterator pathNodeIterator = pathNavigator.Select(pathExpression); while (pathNodeIterator.MoveNext()) { XPathNavigator clone = pathNodeIterator.Current.Clone(); if (_verbose) { _messageStringBuilder.Append("Found document\n"); } // now compute key string key = string.Empty; if (docItem.Key != string.Empty) { //key = dn.Evaluate(doc.Key).ToString(); object result = clone.Evaluate(docItem.Key); XPathNodeIterator nodeIterator = result as XPathNodeIterator; if (nodeIterator != null) { while (nodeIterator.MoveNext()) { key = nodeIterator.Current.ToString(); } } else { key = result.ToString(); } } else { key = fname; } if (_verbose) { _messageStringBuilder.AppendFormat("Key is {0}\n", key); } // delete if document exists DeleteDocument(writer, key); Document ludoc = new Document(); AddKeyField(ludoc, key); AddNameField(ludoc, ruleSet.Name); string textField = string.Empty; Rule ruleText = null; foreach (Rule rule in docItem.Rules) { XPathExpression expr = clone.Compile(rule.XPath); XPathNodeIterator iter = clone.Select(expr); while (iter.MoveNext()) { string textVal = ParseHtml(iter.Current.Value); if (_verbose) { _messageStringBuilder.AppendFormat("Found field '{0}' value '{1}'\n", rule.Name, textVal); } // index away! if (rule.Name == "text") { if (ruleText == null) { ruleText = rule; textField = textVal; } else { textField += " ... " + textVal; } } else { AddField(ludoc, rule, iter.Current.Value); } } } if (textField.Length > 0) { AddField(ludoc, ruleText, textField); } // now add the globals into this document foreach (RuleValue ruleValue in globals) { AddField(ludoc, ruleValue.Rule, ruleValue.Value); } writer.AddDocument(ludoc); } } } } // end of fnames loop } catch (Exception e) { failures.Add(String.Format("Failed to index file {0}, exception: {1}", fname, e)); if (_verbose) { _messageStringBuilder.AppendFormat("Failed to index {0}\n", fname); _messageStringBuilder.Append(e.StackTrace + "\n"); } } } writer.Optimize(); writer.Close(); return(failures); }
/// <summary> /// Creates a new Tridion collection by calling GetListItems using the provided filter on the provided organizational item /// the collection is then filtered by applying the xpath query provided /// </summary> /// <param name="engine">An instantiated Engine object <typeparamref name="Tridion.ContentManager.Templating.Engine"/></param> /// <param name="root">The organizational element to get the list of items for</param> /// <param name="filter">An instantiated Filter object with preset conditions</param> /// <param name="xpath">An Xpath expression to further filter the retrieved results </param> public TridionCollectionBase(Engine engine, OrganizationalItem root, Filter filter, XPathExpression xpath) : this(engine, root.GetListItems(new OrganizationalItemItemsFilter(filter, engine.GetSession())), xpath) { }
/// <summary> /// This method returns a collection of the values of all nodes the XPath expression addresses. /// </summary> /// <param name="xPath">The compiled XPath expression</param> /// <param name="queryParameters">Parameters for the compiled XPath expression</param> public List <string> GetValuesFromNodes(XPathExpression xPath, DictionaryEntry[] queryParameters) { _ParamContext.AddParam(queryParameters); return(GetValuesFromNodes(xPath)); }
/// <summary> /// This method sets the inherent XPathNodeIterator instance. /// </summary> /// <param name="xPath">A compiled XPath expression</param> private void findXPath(XPathExpression xPath) { xPath.SetContext(_ParamContext); _XIter = _XNav.Select(xPath); InitializeCustomContext(_ParamContext); }
/// <summary> /// This method returns an XPathNodeIterator instance positioned at the nodes /// the XPath expression addresses. /// </summary> /// <param name="xPath">The compiled XPath expression</param> /// <param name="queryParameters">Parameters for the compiled XPath expression</param> public XPathNodeIterator GetIterator(XPathExpression xPath, DictionaryEntry[] queryParameters) { _ParamContext.AddParam(queryParameters); return(GetIterator(xPath)); }
/// <summary> /// This method returns an XPathNodeIterator instance positioned at the nodes /// the XPath expression addresses. /// </summary> /// <param name="xPath">The compiled XPath expression</param> public XPathNodeIterator GetIterator(XPathExpression xPath) { findXPath(xPath); return(_XIter.Clone()); }
static void Main(string[] args) { char keychar = ' '; while (true) { Console.Write("\r\nEnter key character to count in names: "); keychar = Console.ReadKey().KeyChar; if (keychar.Equals('q')) { return; } try { // Load source XML into an XPathDocument object instance. XPathDocument xmldoc = new XPathDocument("Tasks.xml"); // Create an XPathNavigator from the XPathDocument. XPathNavigator nav = xmldoc.CreateNavigator(); //Create argument list and add the parameters. XsltArgumentList varList = new XsltArgumentList(); varList.AddParam("charToCount", string.Empty, keychar); // Create an instance of custom XsltContext object. // Pass in the XsltArgumentList object // in which the user-defined variable will be defined. CustomContext context = new CustomContext(new NameTable(), varList); // Add a namespace definition for the namespace prefix that qualifies the // user-defined function name in the query expression. context.AddNamespace("Extensions", "http://xpathExtensions"); // Create the XPath expression using extension function to select nodes // that contain 2 occurences of the character entered by user. XPathExpression xpath = XPathExpression.Compile( "/Tasks/Name[Extensions:CountChar(., $charToCount) = 2]"); xpath.SetContext(context); XPathNodeIterator iter = nav.Select(xpath); if (iter.Count.Equals(0)) { Console.WriteLine("\n\n\rNo results contain 2 instances of " + keychar.ToString()); } else { Console.WriteLine("\n\n\rResults that contain 2 instances of : " + keychar.ToString()); // Iterate over the selected nodes and output the // results filtered by extension function. while (iter.MoveNext()) { Console.WriteLine(iter.Current.Value); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public static Power LoadFromXml(XmlElement rootElement) { Power power = new Power { mDefinition = rootElement.GetAttribute("definition") }; XPathNavigator navigator = rootElement.CreateNavigator(); XPathExpression expr = navigator.Compile("./PlayRequirement"); XPathNodeIterator iterator = navigator.Select(expr); List <PlayErrors.ErrorType> requirements = new List <PlayErrors.ErrorType>(); while (iterator.MoveNext()) { int num; XmlElement node = (XmlElement)((IHasXmlNode)iterator.Current).GetNode(); if (int.TryParse(node.GetAttribute("reqID"), out num)) { PlayErrors.ErrorType item = (PlayErrors.ErrorType)num; requirements.Add(item); switch (item) { case PlayErrors.ErrorType.REQ_TARGET_MIN_ATTACK: { if (!int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramMinAtk)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param minAtk for power {0}.", power.GetDefinition()), new object[0]); } continue; } case PlayErrors.ErrorType.REQ_TARGET_MAX_ATTACK: { if (!int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramMaxAtk)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param maxAtk for power {0}.", power.GetDefinition()), new object[0]); } continue; } case PlayErrors.ErrorType.REQ_TARGET_WITH_RACE: { if (!int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramRace)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param race for power {0}.", power.GetDefinition()), new object[0]); } continue; } case PlayErrors.ErrorType.REQ_NUM_MINION_SLOTS: { if (!int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramNumMinionSlots)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param num minion slots for power {0}.", power.GetDefinition()), new object[0]); } continue; } case PlayErrors.ErrorType.REQ_MINION_CAP_IF_TARGET_AVAILABLE: { if (!int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramNumMinionSlotsWithTarget)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param num minion slots with target for power {0}.", power.GetDefinition()), new object[0]); } continue; } case PlayErrors.ErrorType.REQ_MINIMUM_ENEMY_MINIONS: { if (!int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramMinNumEnemyMinions)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param num enemy minions for power {0}.", power.GetDefinition()), new object[0]); } continue; } case PlayErrors.ErrorType.REQ_MINIMUM_TOTAL_MINIONS: { if (!int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramMinNumTotalMinions)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param num total minions for power {0}.", power.GetDefinition()), new object[0]); } continue; } } if ((item == PlayErrors.ErrorType.REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS) && !int.TryParse(node.GetAttribute("param"), out power.mPlayRequirementInfo.paramMinNumFriendlyMinions)) { Log.Rachelle.Print(string.Format("Unable to read play requirement param num friendly minions for power {0}.", power.GetDefinition()), new object[0]); } } } power.mPlayRequirementInfo.requirementsMap = PlayErrors.GetRequirementsMap(requirements); return(power); }
/// <summary> /// Update the Mod's information based on the Mod selected and current Rating. /// </summary> private void UpdateGearInfo() { if (lstMod.Text != "") { // Retireve the information for the selected Mod. // Filtering is also done on the Category in case there are non-unique names across categories. XmlNode objXmlMod = _objXmlDocument.SelectSingleNode("/chummer/mods/mod[name = \"" + lstMod.SelectedValue + "\"]"); // Extract the Avil and Cost values from the Gear info since these may contain formulas and/or be based off of the Rating. // This is done using XPathExpression. XPathNavigator nav = _objXmlDocument.CreateNavigator(); // Avail. // If avail contains "F" or "R", remove it from the string so we can use the expression. string strAvail = ""; string strAvailExpr = ""; if (objXmlMod["avail"].InnerText.StartsWith("FixedValues")) { int intRating = Convert.ToInt32(nudRating.Value - 1); string[] strValues = objXmlMod["avail"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(','); if (intRating > strValues.Length || intRating < 0) { intRating = strValues.Length - 1; } strAvailExpr = strValues[intRating]; } else { strAvailExpr = objXmlMod["avail"].InnerText; } XPathExpression xprAvail; if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" || strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R") { strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1); // Remove the trailing character if it is "F" or "R". strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1); } try { xprAvail = nav.Compile(strAvailExpr.Replace("Rating", nudRating.Value.ToString())); lblAvail.Text = (Convert.ToInt32(nav.Evaluate(xprAvail))).ToString() + strAvail; } catch { lblAvail.Text = objXmlMod["avail"].InnerText; } lblAvail.Text = lblAvail.Text.Replace("R", LanguageManager.Instance.GetString("String_AvailRestricted")).Replace("F", LanguageManager.Instance.GetString("String_AvailForbidden")); // Cost. int intItemCost = 0; if (objXmlMod["cost"].InnerText.StartsWith("Variable")) { int intMin = 0; int intMax = 0; string strCost = objXmlMod["cost"].InnerText.Replace("Variable(", string.Empty).Replace(")", string.Empty); if (strCost.Contains("-")) { string[] strValues = strCost.Split('-'); intMin = Convert.ToInt32(strValues[0]); intMax = Convert.ToInt32(strValues[1]); } else { intMin = Convert.ToInt32(strCost.Replace("+", string.Empty)); } if (intMax == 0) { intMax = 1000000; lblCost.Text = String.Format("{0:###,###,##0¥+}", intMin); } else { lblCost.Text = String.Format("{0:###,###,##0}", intMin) + "-" + String.Format("{0:###,###,##0¥}", intMax); } intItemCost = intMin; } else { string strCost = ""; if (objXmlMod["cost"].InnerText.StartsWith("FixedValues")) { int intRating = Convert.ToInt32(nudRating.Value) - 1; string[] strValues = objXmlMod["cost"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(','); if (intRating < 0 || intRating > strValues.Length) { intRating = 0; } strCost = strValues[intRating]; } else { strCost = objXmlMod["cost"].InnerText; } strCost = ReplaceStrings(strCost); if (chkFreeItem.Checked) { strCost = "0"; } XPathExpression xprCost = nav.Compile(strCost); int intCost = Convert.ToInt32(Convert.ToDouble(nav.Evaluate(xprCost), GlobalOptions.Instance.CultureInfo)); intCost *= _intModMultiplier; // Apply any markup. double dblCost = Convert.ToDouble(intCost, GlobalOptions.Instance.CultureInfo); dblCost *= 1 + (Convert.ToDouble(nudMarkup.Value, GlobalOptions.Instance.CultureInfo) / 100.0); intCost = Convert.ToInt32(dblCost); lblCost.Text = String.Format("{0:###,###,##0¥}", intCost); intItemCost = intCost; } // Update the Avail Test Label. lblTest.Text = _objCharacter.AvailTest(intItemCost, lblAvail.Text); // If the rating is "qty", we're looking at Tires instead of actual Rating, so update the fields appropriately. if (objXmlMod["rating"].InnerText == "qty") { nudRating.Enabled = true; nudRating.Maximum = 20; nudRating.Minimum = 1; lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Qty"); } //Used for the Armor modifications. else if (objXmlMod["rating"].InnerText.ToLower() == "body") { nudRating.Maximum = _objVehicle.Body; nudRating.Minimum = 1; nudRating.Enabled = true; lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Body"); } //Used for Metahuman Adjustments. else if (objXmlMod["rating"].InnerText.ToLower() == "seats") { nudRating.Maximum = _objVehicle.Seats; nudRating.Minimum = 1; nudRating.Enabled = true; lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Qty"); } else { if (Convert.ToInt32(objXmlMod["rating"].InnerText) > 0) { nudRating.Maximum = Convert.ToInt32(objXmlMod["rating"].InnerText); nudRating.Minimum = 1; nudRating.Enabled = true; lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Rating"); } else { nudRating.Minimum = 0; nudRating.Maximum = 0; nudRating.Enabled = false; lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Rating"); } } // Slots. string strSlots = ""; if (objXmlMod["slots"].InnerText.StartsWith("FixedValues")) { string[] strValues = objXmlMod["slots"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(','); strSlots = strValues[Convert.ToInt32(nudRating.Value) - 1]; } else { strSlots = objXmlMod["slots"].InnerText; } strSlots = ReplaceStrings(strSlots); XPathExpression xprSlots = nav.Compile(strSlots); lblSlots.Text = nav.Evaluate(xprSlots).ToString(); try { if (objXmlMod["category"].InnerText == "Weapon Mod") { lblCategory.Text = LanguageManager.Instance.GetString("String_WeaponModification"); } else { // Translate the Category if possible. if (GlobalOptions.Instance.Language != "en-us") { XmlNode objXmlCategory = _objXmlDocument.SelectSingleNode("/chummer/modcategories/category[. = \"" + objXmlMod["category"].InnerText + "\"]"); if (objXmlCategory != null) { if (objXmlCategory.Attributes["translate"] != null) { lblCategory.Text = objXmlCategory.Attributes["translate"].InnerText; } else { lblCategory.Text = objXmlMod["category"].InnerText; } } else { lblCategory.Text = objXmlMod["category"].InnerText; } } else { lblCategory.Text = objXmlMod["category"].InnerText; } } } catch { lblCategory.Text = LanguageManager.Instance.GetString("String_WeaponModification"); } if (objXmlMod["limit"] != null) { // Translate the Limit if possible. if (GlobalOptions.Instance.Language != "en-us") { XmlNode objXmlLimit = _objXmlDocument.SelectSingleNode("/chummer/limits/limit[. = \"" + objXmlMod["limit"].InnerText + "\"]"); if (objXmlLimit != null) { if (objXmlLimit.Attributes["translate"] != null) { lblLimit.Text = " (" + objXmlLimit.Attributes["translate"].InnerText + ")"; } else { lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")"; } } else { lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")"; } } else { lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")"; } } else { lblLimit.Text = ""; } string strBook = _objCharacter.Options.LanguageBookShort(objXmlMod["source"].InnerText); string strPage = objXmlMod["page"].InnerText; if (objXmlMod["altpage"] != null) { strPage = objXmlMod["altpage"].InnerText; } lblSource.Text = strBook + " " + strPage; tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(objXmlMod["source"].InnerText) + " " + LanguageManager.Instance.GetString("String_Page") + " " + strPage); } }
public override object InvokeXPathFunction(AlpheusXPathFunction f, AlpheusXsltContext xslt_context, object[] args, XPathNavigator doc_context) { for (int argc = 0; argc < args.Length; argc++) { if (args[argc] is string) { args[argc] = ResolveXPathFunctionArgVariables((string)args[argc], xslt_context); } } switch (f.Prefix) { case "l": switch (f.Name) { case "any": string e; XPathNodeIterator iter = (args[0] as XPathNodeIterator).Clone(); if (args.Count() == 1) { e = "./"; } else { e = (string)args[1]; } XPathExpression expr = this.CompileXPathExpression(e, doc_context); if (expr == null) { Error("Failed to execute l:any with expression {0}.", e); return(false); } object r; while (iter.MoveNext()) { r = iter.Current.Evaluate(expr); if (r == null) { continue; } else if (r as bool? != null) { bool?b = r as bool?; if (b.HasValue && b.Value) { return(true); } } else if (r is XPathNodeIterator) { XPathNodeIterator i = r as XPathNodeIterator; if (i.Count > 0) { return(true); } } else if (r is double?) { double?d = r as double?; if (d.HasValue) { return(true); } } else if (r is string) { string s = (string)r; if (!string.IsNullOrEmpty(s)) { return(true); } } else { throw new Exception("Unknown result type from evaluating expression " + e + " at iterator position " + iter.CurrentPosition); } } return(f); default: throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not implemented."); } case "db": switch (f.Name) { case "query": if (this.AuditTarget is IDbAuditTarget) { IDbAuditTarget db = this.AuditTarget as IDbAuditTarget; return(db.ExecuteDbQueryToXml(args)); } else { this.AuditEnvironment.Error("The current target is not a database server or application and does not support queries."); XmlDocument doc = new XmlDocument(); doc.LoadXml("<error>No Database</error>"); return(doc.CreateNavigator().Select("/")); } default: throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by IDbAuditTarget."); } case "os": switch (f.Name) { case "exec": string output = string.Empty, command = "", arguments = ""; if (args.Count() == 1) { command = (string)args[0]; } else { command = (string)args[0]; arguments = (string)args[1]; } output = this.AuditEnvironment.OSExec(command, arguments); this.AuditEnvironment.Debug("os:exec {0} {1} returned {2}.", command, arguments, string.IsNullOrEmpty(output) ? "null" : output); return(output); default: throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by this audit target."); } case "fs": switch (f.Name) { case "unix-file-mode": return(this.AuditEnvironment.GetUnixFileMode((string)args[0])); case "find-files": return(this.AuditEnvironment.FindFiles((string)args[0], (string)args[1])); case "find-dirs": return(this.AuditEnvironment.FindDirectories((string)args[0], (string)args[1])); case "is-symbolic-link": return(this.AuditEnvironment.GetIsSymbolicLink((string)args[0])); case "symbolic-link-location": return(this.AuditEnvironment.GetSymbolicLinkLocation((string)args[0])); default: throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by any audit target."); } case "ver": string version = (string)args[0]; switch (f.Name) { case "lt": return(this.Application.IsVulnerabilityVersionInPackageVersionRange("<" + version, this.Application.Version)); case "gt": return(this.Application.IsVulnerabilityVersionInPackageVersionRange(">" + version, this.Application.Version)); case "eq": return(this.Application.IsVulnerabilityVersionInPackageVersionRange(version, this.Application.Version)); case "lte": return(this.Application.IsVulnerabilityVersionInPackageVersionRange("<=" + version, this.Application.Version)); case "gte": return(this.Application.IsVulnerabilityVersionInPackageVersionRange(">=" + version, this.Application.Version)); default: throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by any audit target."); } default: throw new NotImplementedException("The XPath function prefix" + f.Prefix + " is not supported by any audit targets."); } }
private List <string> ExecXpath(string attr, string xPathExpression, XmlDocument xmlDocument) { List <string> toReturn = new List <string>(); var xpaths = Regex.Matches(xPathExpression, "{(.*?)}"); if (xPathExpression.Contains("{") && xpaths.Count > 0) { // if there is more than one xpath to look up in this value, // object-{obj_id}-{part_id} then we want only one match for // each xpath term if (xpaths.Count > 1 || xPathExpression.Substring(0, 1) != "{" || xPathExpression.Substring(xPathExpression.Length - 1, 1) != "}") { bool matchedSomething = false; foreach (Match xPath in xpaths) { string result; XPathNavigator nav = xmlDocument.CreateNavigator(); XPathExpression expr = nav.Compile(RemoveClosingBrackets(xPath.Value)); switch (expr.ReturnType) { case XPathResultType.NodeSet: XPathNodeIterator iterator = (XPathNodeIterator)nav.Select(expr); if (iterator.Count == 1 || (xpaths.Count == 1 && iterator.Count > 0)) { iterator.MoveNext(); if (iterator.Current.Value.Trim().Length > 0) { matchedSomething = true; } xPathExpression = xPathExpression.Replace(xPath.Value, iterator.Current.Value); } else if (xpaths.Count != 1 && iterator.Count == 0) { throw new Exception("No match for " + xPath.Value + " in " + attr + "=\"" + xPathExpression + "\""); } else if (xpaths.Count > 1) { throw new Exception("Multiple matches for " + xPath.Value + " in " + attr + "=\"" + xPathExpression + "\""); } break; case XPathResultType.String: string st = (string)nav.Evaluate(expr); if (!string.IsNullOrEmpty(st) && st.Trim().Length > 0) { matchedSomething = true; xPathExpression = xPathExpression.Replace(xPath.Value, st); } break; case XPathResultType.Number: //Assume it's a double double dNumber = (double)nav.Evaluate(expr); int iNumber; matchedSomething = true; //if it can be an int, then make it so... if (int.TryParse(dNumber.ToString(), out iNumber)) { xPathExpression = xPathExpression.Replace(xPath.Value, iNumber.ToString()); } else { xPathExpression = xPathExpression.Replace(xPath.Value, dNumber.ToString()); } break; default: throw new Exception("No match for " + xPath.Value + " in " + attr + "=\"" + xPathExpression + "\""); } } if (matchedSomething && !string.IsNullOrEmpty(xPathExpression.Trim())) { toReturn.Add(xPathExpression); } } else { // quite happy to enumerate for all values which match the xpath var xpath = RemoveClosingBrackets(xPathExpression); string result; var matches = xmlDocument.SelectNodes(xpath); foreach (XmlNode node in matches) { // ignore empty strings if (!string.IsNullOrEmpty(node.InnerText)) { // apply modification function if required var v = xPathExpression.Replace("{" + xpath + "}", node.InnerText); if (!string.IsNullOrEmpty(v.Trim())) { toReturn.Add(v); } } } } } return(toReturn); }
/// <summary> /// Creates a new Tridion collection by loading the list provided, the list should be a result of calling GetListItems /// or a variation of that on a Tridion item. /// </summary> /// <param name="engine">An instantiated Engine object <typeparamref name="Tridion.ContentManager.Templating.Engine"/></param> /// <param name="list">An XML fragment containing the result of a GetList method </param> /// <param name="xpath">An Xpath expression to further filter the retrieved results</param> public TridionCollectionBase(Engine engine, XmlElement list, XPathExpression xpath) { Init(engine, list); m_Nodes = list.SelectNodes(xpath.Expression, NSManager); }
private void Carac_Tb_OnClick(object sender, EventArgs e) { XmlNode root; XmlNode node; TextBox Field_Input = (TextBox)sender; root = mod_global.Get_Codes_Obs_DocElement(); node = root.SelectSingleNode("/codes/code[id='" + current_code + "']/caracteristiques/caracteristique[@nom='" + Field_Input.Tag + "']"); mod_global.Focused_Control = Field_Input; mod_global.Focused_Carac_Panel = this; mod_global.MF.InputPreviewTb.Text = Field_Input.Text; // Afficher l'info au Status Panel if (node.Attributes["info"] != null) { mod_global.MF.statusPanel.Text = node.Attributes["info"].InnerText; } else { mod_global.MF.statusPanel.Text = ""; } //On applique le mode de saisie correspondant au champ focused if (node.Attributes["type"].InnerText == "item") { mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = true; mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"]; mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; mod_global.MF.flowLayoutPanel2.Controls.Clear(); //On utilise un navigateur pour pouvoir trier les noeuds XPathNavigator nav = root.CreateNavigator(); XPathExpression exp = nav.Compile("/codes/code[id='" + current_code + "']/caracteristiques/caracteristique[@nom='" + Field_Input.Tag + "']/item"); exp.AddSort("@position", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number); foreach (XPathNavigator item in nav.Select(exp)) { multiple_choice_button but; string but_text = item.GetAttribute("nom", "") + " | " + item.Value; //Si le choix contient des attributs concernant le comportement des champs suivants (on teste la présence de q1 comme attribut du choix en cours) if (item.GetAttribute("q1", "") != "") { but = new multiple_choice_button(but_text, Get_CaracFieldsNewState_HT(item), false, false); } else if (item.GetAttribute("lien", "") == "") { if (item.GetAttribute("ajoute", "") == "true") { but = new multiple_choice_button(but_text, null, false, true); } else { but = new multiple_choice_button(but_text, null, false, false); } } else if (item.GetAttribute("lien", "") == "true") { but = new multiple_choice_button(but_text, null, true, false); } else { but = new multiple_choice_button(but_text, null, true, false); } mod_global.MF.flowLayoutPanel2.Controls.Add(but); } /* ANCIEN CODE NS remplacé par GB le 16/12/2009 * foreach (XmlNode nod in node.ChildNodes) * { * multiple_choice_button but; * string but_text = nod.Attributes["nom"].InnerText + " | " + nod.InnerText; * * //Si le choix contient des attributs concernant le comportement des champs suivants (on teste la présence de q1 comme attribut du choix en cours) * if (nod.Attributes.GetNamedItem("q1") != null) * but = new multiple_choice_button(but_text, Get_CaracFieldsNewState_HT(nod), false); * else * if (nod.Attributes.GetNamedItem("lien") == null) * but = new multiple_choice_button(but_text, null, false); * else * if (nod.Attributes["lien"].InnerText == "true") * but = new multiple_choice_button(but_text, null, true); * else * but = new multiple_choice_button(but_text, null, true); * * * mod_global.MF.flowLayoutPanel2.Controls.Add(but); * }*/ } else if (node.Attributes["type"].InnerText == "texte") { mod_global.MF.flowLayoutPanel2.Controls.Clear(); mod_global.MF.virtual_kb1.Set_Alpha_Numeric(); mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = true; mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"]; mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; } else if (node.Attributes["type"].InnerText == "numerique") { mod_global.MF.flowLayoutPanel2.Controls.Clear(); mod_global.MF.virtual_kb1.Set_Only_Numeric(); mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = true; mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"]; mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; } else if (node.Attributes["type"].InnerText == "date") { mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = true; mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["DateTab"]; mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; } else if (node.Attributes["type"].InnerText == "video") { mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = true; mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["VideoTab"]; mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; } else if (node.Attributes["type"].InnerText == "photo") { mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = true; mod_global.MF.photo_select1.Read_Photos_From_TextList(mod_global.Focused_Control.Text); mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["PhotoTab"]; mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; } else if (node.Attributes["type"].InnerText == "audio") { mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = true; mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["AudioTab"]; mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; } else if (node.Attributes["type"].InnerText == "horaire") { mod_global.MF.SaisieTabControl.TabPages["SectionTab"].Enabled = true; mod_global.MF.section_horaire1.Init_Section_Img(current_forme); mod_global.MF.SaisieTabControl.SelectedTab = mod_global.MF.SaisieTabControl.TabPages["SectionTab"]; mod_global.MF.SaisieTabControl.TabPages["DateTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["KeyboardTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["VideoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["PhotoTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["AudioTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["ChoiceTab"].Enabled = false; mod_global.MF.SaisieTabControl.TabPages["SchemaTab"].Enabled = false; } }
/// <summary> /// /// </summary> /// <param name="Navigator"></param> /// <param name="XPath"></param> /// <returns></returns> public static bool GetBoolean(XPathNavigator Navigator, XPathExpression XPath) { string val = GetString(Navigator, XPath).Trim().ToUpper(CultureInfo.InvariantCulture); return(val == "1" || val == "YES" || val == "TRUE"); }
public virtual object Evaluate(XPathExpression expr) { }
private void ApplyCode(XPathNavigator docNavigator, XPathExpression codeSelector) { CodeController codeController = CodeController.GetInstance("conceptual"); if (codeController == null || codeController.Mode != CodeHighlightMode.IndirectIris) { return; } XPathNodeIterator iterator = docNavigator.Select(codeSelector); if (iterator == null || iterator.Count == 0) { return; } XPathNavigator navigator = null; XPathNavigator[] arrNavigator = BuildComponentUtilities.ConvertNodeIteratorToArray(iterator); int itemCount = arrNavigator.Length; string spanNamespace = "http://ddue.schemas.microsoft.com/authoring/2003/5"; string attrName = String.Empty; string attrClass = String.Empty; for (int i = 0; i < itemCount; i++) { navigator = arrNavigator[i]; if (navigator == null) { continue; } string codeLang = null; XPathNodeIterator nodeIterator = navigator.SelectChildren("span", spanNamespace); XPathNavigator placeHolder = null; if (nodeIterator == null || nodeIterator.Count == 0) { continue; } XPathNavigator[] arrSnipNavigator = BuildComponentUtilities.ConvertNodeIteratorToArray(nodeIterator); int nodeCount = arrSnipNavigator.Length; XPathNavigator tempHolder = arrSnipNavigator[0]; attrName = tempHolder.GetAttribute("name", String.Empty); attrClass = tempHolder.GetAttribute("class", String.Empty); if (String.Equals(attrName, "SandAssist") && String.Equals(attrClass, "tgtSentence")) { placeHolder = tempHolder; } if (placeHolder != null) { codeLang = placeHolder.Value; placeHolder.DeleteSelf(); } else { base.WriteMessage(MessageLevel.Info, "No code language found."); continue; } Highlighter highlighter = codeController.ApplyLanguage( null, codeLang); if (nodeCount == 1) { string codeText = navigator.Value; if (!String.IsNullOrEmpty(codeText)) { codeText = codeText.Trim(); XmlWriter xmlWriter = navigator.InsertAfter(); if (highlighter != null) { StringReader textReader = new StringReader(codeText); highlighter.Highlight(textReader, xmlWriter); // For the two-part or indirect, we add extra line-break // since this process delete the last extra line. xmlWriter.WriteStartElement("br"); // start - br xmlWriter.WriteEndElement(); // end - br } else { xmlWriter.WriteString(codeText); } xmlWriter.Close(); navigator.DeleteSelf(); } } else { XPathNavigator snipNavigator = null; for (int j = 1; j < nodeCount; j++) { snipNavigator = arrSnipNavigator[j]; if (snipNavigator == null) { base.WriteMessage(MessageLevel.Warn, "Null navigator!"); continue; } attrName = snipNavigator.GetAttribute("name", String.Empty); attrClass = snipNavigator.GetAttribute("class", String.Empty); if (String.Equals(attrName, "SandAssist") == false || String.Equals(attrClass, "srcSentence") == false) { base.WriteMessage(MessageLevel.Warn, attrName); base.WriteMessage(MessageLevel.Warn, attrClass); continue; } int snipIndex = snipNavigator.ValueAsInt; SnippetItem item = codeController[snipIndex]; string codeText = item.Text; if (!String.IsNullOrEmpty(codeText)) { codeText = codeText.Trim(); XmlWriter xmlWriter = snipNavigator.InsertAfter(); if (highlighter != null) { StringReader textReader = new StringReader(codeText); highlighter.Highlight(textReader, xmlWriter); } else { xmlWriter.WriteString(codeText); } xmlWriter.Close(); snipNavigator.DeleteSelf(); } } } } }
public virtual bool Matches(XPathExpression expr) { }
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); }
public virtual XPathNavigator SelectSingleNode(XPathExpression expression) { }
//===================================================================== /// <inheritdoc /> public override void Initialize(XPathNavigator configuration) { string attrValue, id; targets = new TargetTypeDictionary(); resolver = new LinkTextResolver(targets); // Get the shared instances dictionary. Create it if it doesn't exist. if (BuildComponentCore.Data.ContainsKey(SharedReferenceTargetsId)) { sharedTargets = BuildComponentCore.Data[SharedReferenceTargetsId] as Dictionary <string, TargetDictionary>; } if (sharedTargets == null) { BuildComponentCore.Data[SharedReferenceTargetsId] = sharedTargets = new Dictionary <string, TargetDictionary>(); } // base-url is an xpath expression applied against the current document to pick up the save location of the // document. If specified, local links will be made relative to the base-url. string baseUrlValue = configuration.GetAttribute("base-url", String.Empty); if (!String.IsNullOrWhiteSpace(baseUrlValue)) { baseUrl = XPathExpression.Compile(baseUrlValue); } // hrefFormat is a string format that is used to format the value of local href attributes. The // default is "{0}.htm" if not specified. hrefFormat = (string)configuration.Evaluate("string(hrefFormat/@value)"); if (String.IsNullOrWhiteSpace(hrefFormat)) { hrefFormat = "{0}.htm"; } // The container XPath can be replaced; this is useful string containerValue = configuration.GetAttribute("container", String.Empty); if (!String.IsNullOrWhiteSpace(containerValue)) { XmlTargetDictionaryUtilities.ContainerExpression = containerValue; } XPathNodeIterator targetsNodes = configuration.Select("targets"); #if DEBUG this.WriteMessage(MessageLevel.Diagnostic, "Loading reference link target info"); DateTime startLoad = DateTime.Now; #endif foreach (XPathNavigator targetsNode in targetsNodes) { // Get target type attrValue = targetsNode.GetAttribute("type", String.Empty); if (String.IsNullOrWhiteSpace(attrValue)) { this.WriteMessage(MessageLevel.Error, "Each targets element must have a type attribute " + "that specifies which type of links to create"); } if (!Enum.TryParse <ReferenceLinkType>(attrValue, true, out ReferenceLinkType type)) { this.WriteMessage(MessageLevel.Error, "'{0}' is not a supported reference link type", attrValue); } // Check for shared instance by ID. If not there, create it and add it. id = targetsNode.GetAttribute("id", String.Empty); if (!sharedTargets.TryGetValue(id, out TargetDictionary newTargets)) { this.WriteMessage(MessageLevel.Info, "Loading {0} reference link type targets", type); newTargets = this.CreateTargetDictionary(targetsNode); sharedTargets[newTargets.DictionaryId] = newTargets; } targets.Add(type, newTargets); } #if DEBUG TimeSpan loadTime = (DateTime.Now - startLoad); this.WriteMessage(MessageLevel.Diagnostic, "Load time: {0} seconds", loadTime.TotalSeconds); // Dump targets for comparison to other versions // targets.DumpTargetDictionary(Path.GetFullPath("TargetDictionary.xml")); // Serialization test // targets.SerializeDictionary(Directory.GetCurrentDirectory()); #endif // Getting the count from a database cache can be expensive so only report it if it will be seen if (this.BuildAssembler.VerbosityLevel == MessageLevel.Info) { this.WriteMessage(MessageLevel.Info, "{0} total reference link targets", targets.Count); } if (targets.NeedsMemberIdUrlResolver) { this.WriteMessage(MessageLevel.Info, "Creating member ID URL resolver"); this.UrlResolver = this.CreateMemberIdResolver(configuration); string localeValue = (string)configuration.Evaluate("string(locale/@value)"); if (this.UrlResolver != null && !String.IsNullOrWhiteSpace(localeValue)) { this.UrlResolver.Locale = localeValue; } } linkTarget = (string)configuration.Evaluate("string(linkTarget/@value)"); if (String.IsNullOrWhiteSpace(linkTarget)) { linkTarget = "_blank"; } }
void Success2() { var xpath = XPathExpression.Compile("/book[@npages = 100]/@title", null); }
public override void LocalInit() { base.LocalInit(); m_Expression = XPathExpression.Compile(m_Parameters.XPath); }
private void ParseReferenceConfiguration(XPathNavigator configuration) { TargetController controller = TargetController.Controller; Debug.Assert(controller != null); controller.Initialize(this); ReferenceLinkType localLink = ReferenceLinkType.None; ReferenceLinkType msdnLink = ReferenceLinkType.None; _targets = controller.GetCollection(configuration, out localLink, out msdnLink); Debug.Assert(_targets != null); _linkResolver = new ReferenceLinkTextResolver(_targets); if (msdnLink == ReferenceLinkType.Msdn && _msdnResolver == null) { XPathNavigator linkResolverNode = configuration.SelectSingleNode("linkResolver"); if (linkResolverNode != null) { WriteMessage(MessageLevel.Info, "Creating cached MSDN URL resolver."); _msdnResolver = TargetMsdnController.GetController(linkResolverNode); } else { WriteMessage(MessageLevel.Info, "Creating MSDN URL resolver."); _msdnResolver = TargetMsdnController.GetController(); } } XPathNavigator optionsNode = configuration.SelectSingleNode("options"); if (optionsNode == null) { optionsNode = configuration; } // base-url is an xpath expression applied against the current document to pick up the save location of the // document. If specified, local links will be made relative to the base-url. string baseUrlValue = optionsNode.GetAttribute("base-url", String.Empty); if (!String.IsNullOrEmpty(baseUrlValue)) { _baseUrl = XPathExpression.Compile(baseUrlValue); } // url-format is a string format that is used to format the value of local href attributes. The default is // "{0}.htm" for backwards compatibility. string hrefFormatValue = optionsNode.GetAttribute("href-format", String.Empty); if (!String.IsNullOrEmpty(hrefFormatValue)) { _hrefFormat = hrefFormatValue; } // the container XPath can be replaced; this is useful string containerValue = optionsNode.GetAttribute("container", String.Empty); if (!String.IsNullOrEmpty(containerValue)) { TargetCollectionXmlUtilities.ContainerExpression = containerValue; } string localeValue = optionsNode.GetAttribute("locale", String.Empty); if (!String.IsNullOrEmpty(localeValue) && _msdnResolver != null) { _msdnResolver.Locale = localeValue; } string versionValue = optionsNode.GetAttribute("version", String.Empty); if (!String.IsNullOrEmpty(versionValue) && _msdnResolver != null) { _msdnResolver.Version = versionValue; } string mvcVersionValue = optionsNode.GetAttribute("mvcVersion", String.Empty); if (!String.IsNullOrEmpty(mvcVersionValue) && _msdnResolver != null) { _msdnResolver.MvcVersion = mvcVersionValue; } string targetValue = optionsNode.GetAttribute("linkTarget", String.Empty); if (!String.IsNullOrEmpty(targetValue)) { _linkTarget = targetValue; } this.WriteMessage(MessageLevel.Info, String.Format( "Loaded {0} reference targets.", _targets.Count)); _writerSettings = new XmlWriterSettings(); _writerSettings.ConformanceLevel = ConformanceLevel.Fragment; _hasMsdnStorage = controller.HasMsdnStorage; }
public override object Evaluate(XPathExpression xpath, object context) { return Value; }
/// <summary> /// Selects a list of XmlNode matching an XPath expression. /// </summary> /// <param name="source">A source XmlNode.</param> /// <param name="expression">An XPath expression.</param> /// <param name="variables">A set of XPathVariables.</param> /// <returns>The list of XmlNode matching the XPath expression.</returns> /// <remarks> /// <para>If <param name="variables" /> is <c>null</c>, or is empty, or contains only one single /// value which itself is <c>null</c>, then variables are ignored.</para> /// <para>The XPath expression should reference variables as <c>$var</c>.</para> /// </remarks> public static XmlNodeList SelectNodes(this XmlNode source, XPathExpression expression, IEnumerable <XPathVariable> variables) { var av = variables == null ? null : variables.ToArray(); return(SelectNodes(source, expression, av)); }
public virtual object Evaluate(XPathExpression expr, XPathNodeIterator context) { }
/// <summary> /// Gets a dynamic content resulting from an XPath query. /// </summary> /// <param name="cache">The contextual cache.</param> /// <param name="xpath">The XPath query.</param> /// <param name="vars">Optional XPath variables</param> /// <returns>The dynamic content, or null.</returns> public static dynamic GetDynamicSingleByXPath(this ContextualPublishedContentCache cache, XPathExpression xpath, params XPathVariable[] vars) { var content = cache.GetSingleByXPath(xpath, vars); return(content == null ? new DynamicNull() : new DynamicPublishedContent(content).AsDynamic()); }
public virtual XPathNodeIterator Select(XPathExpression expr) { }
/// <summary> /// Gets dynamic contents resulting from an XPath query. /// </summary> /// <param name="cache">The contextual cache.</param> /// <param name="xpath">The XPath query.</param> /// <param name="vars">Optional XPath variables</param> /// <returns>The dynamic contents.</returns> public static dynamic GetDynamicByXPath(this ContextualPublishedContentCache cache, XPathExpression xpath, params XPathVariable[] vars) { var content = cache.GetByXPath(xpath, vars); return(new DynamicPublishedContentList(content.Select(c => new DynamicPublishedContent(c)))); }
public IEnumerable <IPublishedContent> ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars) => ItemsByXPath(xpath, vars, _publishedSnapshot.Content);
void Failure1() { var xpath = XPathExpression.Compile(bad1); }