public override void ModifyConfig(XDocument doc) { // Add the new audit config section, if the ForwardReceivedMessagesTo attribute has not been set in the UnicastBusConfig. var frmAttributeEnumerator = (IEnumerable)doc.XPathEvaluate("/configuration/UnicastBusConfig/@ForwardReceivedMessagesTo"); var isForwardReceivedMessagesAttributeDefined = frmAttributeEnumerator.Cast<XAttribute>().Any(); // Then add the audit config var sectionElement = doc.XPathSelectElement( "/configuration/configSections/section[@name='AuditConfig' and @type='NServiceBus.Config.AuditConfig, NServiceBus.Core']"); if (sectionElement == null) { if (isForwardReceivedMessagesAttributeDefined) doc.XPathSelectElement("/configuration/configSections").Add(new XComment(exampleAuditConfigSection)); else doc.XPathSelectElement("/configuration/configSections").Add(new XElement("section", new XAttribute("name", "AuditConfig"), new XAttribute("type", "NServiceBus.Config.AuditConfig, NServiceBus.Core"))); } var forwardingElement = doc.XPathSelectElement("/configuration/AuditConfig"); if (forwardingElement == null) { doc.Root.LastNode.AddAfterSelf(new XComment(Instructions), isForwardReceivedMessagesAttributeDefined ? (object) new XComment(@"Since we detected that you already have forwarding setup we haven't enabled the audit feature. Please remove the ForwardReceivedMessagesTo attribute from the UnicastBusConfig and uncomment the AuditConfig section. <AuditConfig QueueName=""audit"" />") : new XElement("AuditConfig", new XAttribute("QueueName", "audit"))); } }
internal string GetSingleValuedStringFromXPath(XDocument document, string xpath) { if (document == null) { throw new ArgumentNullException("document"); } if (string.IsNullOrEmpty(xpath)) { throw new ArgumentNullException("xpath"); } IEnumerable attributes = document.XPathEvaluate(xpath) as IEnumerable; return attributes.Cast<XAttribute>().Single().Value; }
/// <summary> /// Returns the XML documentation (summary tag) for the specified member. /// </summary> /// <param name="member">The reflected member.</param> /// <param name="xml">XML documentation.</param> /// <returns>The contents of the summary tag for the member.</returns> public static string GetXmlDocumentation(this MemberInfo member, XDocument xml) { return xml.XPathEvaluate( String.Format( "string(/doc/members/member[@name='{0}']/summary)", GetMemberElementName(member) ) ).ToString().Trim(); }
public static string GetXmlDocumentation(this TypedParameter parameter, XDocument xml) { if (xml == null) return String.Empty; return xml.XPathEvaluate( String.Format( "string(/doc/members/member[@name='{0}']/param[@name='{1}'])", GetMemberElementName(parameter.Function), parameter.Name ) ).ToString().Trim(); }
private static string GetXmlDocumentation(this FunctionDescriptor member, XDocument xml) { if (xml == null) return String.Empty; return xml.XPathEvaluate( String.Format( "string(/doc/members/member[@name='{0}']/summary)", GetMemberElementName(member) ) ).ToString().Trim(); }
public static IEnumerable<string> GetSearchTags(this FunctionDescriptor member, XDocument xml) { if (xml == null) return new List<string>(); return xml.XPathEvaluate( String.Format( "string(/doc/members/member[@name='{0}']/search)", GetMemberElementName(member) ) ).ToString().Split(',').Select(x => x.Trim()).Where(x => x != String.Empty); }
private string ValidatePath(XDocument document, XmlNamespaceManager xnm, string prefix) { try { var nsxpath = XPath.QualifyXPath(prefix); var check = ((IEnumerable)document.XPathEvaluate(nsxpath, xnm)).Cast<XObject>().FirstOrDefault(); return check != null ? string.Empty : XPath; } catch (Exception ex) { return XPath + ": " + ex.Message; } }
public string getWeatherJSON(string location) { string str = ""; try { httpReq = (HttpWebRequest)WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + location + "&mode=xml"); // starts a web request to an api hosted by openweathermap which returns an xml document with weather data response = (HttpWebResponse)httpReq.GetResponse(); // recieves the response readStream = response.GetResponseStream(); // the stream reader reads the response streamreader = new StreamReader(readStream, Encoding.UTF8); // sets it to a stream reader with the UTF8 encoding responseString = streamreader.ReadToEnd(); // reads ther esponse to a string XMLDoc = XDocument.Parse(responseString); // parses the recieved document into an object intended for working with xml documents IEnumerable att = (IEnumerable)XMLDoc.XPathEvaluate("/current/weather/@icon"); // the node we are interested in Console.WriteLine(att.Cast<XAttribute>().FirstOrDefault()); // debug info str = att.Cast<XAttribute>().FirstOrDefault().ToString(); // sets the string str to the found node string[] results = str.Split('"'); // splits it by the " character to get the data we are after split up return results[1]; } catch (System.Net.WebException e) // if an exception was thrown, this will execute { return e.ToString(); } //string responseWeather = returnIcon(responseString); }
private static XDocument PatchDtsIds(XDocument document) { var dtsIdDictionary = new Dictionary<string, string>(); XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(new NameTable()); xmlnsManager.AddNamespace("DTS", "www.microsoft.com/SqlServer/Dts"); foreach (var dtsIdElement in document.XPathSelectElements("//DTS:Property[@DTS:Name='DTSID']", xmlnsManager)) { XElement nameElement = dtsIdElement.Parent.XPathSelectElement("./DTS:Property[@DTS:Name='ObjectName']", xmlnsManager); if (nameElement != null) { dtsIdDictionary.Add(dtsIdElement.Value, nameElement.Value); dtsIdElement.Value = nameElement.Value; } else { dtsIdElement.Value = "__GUID__"; } } foreach (XAttribute refAttribute in (IEnumerable)document.XPathEvaluate("//@IDREF")) { refAttribute.Value = dtsIdDictionary[refAttribute.Value]; } foreach (XElement connectionRef in (IEnumerable)document.XPathEvaluate("//DTS:Executable//DTS:ObjectData//ExecutePackageTask//Connection", xmlnsManager)) { connectionRef.Value = dtsIdDictionary[connectionRef.Value]; } foreach (XAttribute connectionRef in (IEnumerable)document.XPathEvaluate("//connection/@connectionManagerID")) { connectionRef.Value = dtsIdDictionary[connectionRef.Value]; } return document; }
private static string GetMemberElement(FunctionDescriptor function, string suffix, XDocument xml) { // Construct the entire function descriptor name, including CLR style names string clrMemberName = GetMemberElementName(function); // match clr member name var match = xml.XPathEvaluate( String.Format("string(/doc/members/member[@name='{0}']/{1})", clrMemberName, suffix)); if (match is String && !string.IsNullOrEmpty((string)match)) { return match as string; } // fallback, namespace qualified method name var methodName = function.QualifiedName; // match with fallback match = xml.XPathEvaluate( String.Format( "string(/doc/members/member[contains(@name,'{0}')]/{1})", methodName, suffix)); if (match is String && !string.IsNullOrEmpty((string)match)) { return match as string; } return String.Empty; }
private static string GetTestProvider(XDocument file) { return file.XPathEvaluate("string(/configuration/specFlow/unitTestProvider/@name)") as string; }
protected virtual ParsedTemplate PrepareTemplate(TemplateData templateData) { // clone orig doc XDocument workingDoc = new XDocument(this._templateDefinition); // start by loading any parameters as they are needed for meta-template evaluation Dictionary<string, XPathVariable> globalParams = new Dictionary<string, XPathVariable>(); XElement[] paramNodes = workingDoc.Root.Elements("parameter").ToArray(); foreach (XElement paramNode in paramNodes) { var tmplVar = new XPathVariable { Name = paramNode.Attribute("name").Value, ValueExpression = paramNode.Attribute("select") == null ? null : paramNode.Attribute("select").Value, }; globalParams.Add(tmplVar.Name, tmplVar); } CustomXsltContext customContext = new CustomXsltContext(); Func<string, object> onFailedResolve = s => { throw new InvalidOperationException( String.Format("Parameter '{0}' could not be resolved.", s)); }; customContext.OnResolveVariable += s => { XPathVariable var; // if it's defined if (globalParams.TryGetValue(s, out var)) { // see if the user provided a value object value; if (templateData.Arguments.TryGetValue(s, out value)) return value; // evaluate default value if (!String.IsNullOrWhiteSpace(var.ValueExpression)) return workingDoc.XPathEvaluate(var.ValueExpression, customContext); } return onFailedResolve(s); }; // check for meta-template directives and expand XElement metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault(); // we're going to need this later XmlFileProviderResolver fileResolver = new XmlFileProviderResolver(this._fileProvider, this._basePath); while (metaNode != null) { if (EvalCondition(customContext, metaNode, this.GetAttributeValueOrDefault(metaNode, "condition"))) { #region Debug conditional #if DEBUG const bool debugEnabled = true; #else const bool debugEnabled = false; #endif #endregion XslCompiledTransform metaTransform = this.LoadStylesheet(metaNode.Attribute("stylesheet").Value); XsltArgumentList xsltArgList = new XsltArgumentList(); // TODO this is a quick fix/hack xsltArgList.AddExtensionObject("urn:lostdoc-core", new TemplateXsltExtensions(null, null)); var metaParamNodes = metaNode.Elements("with-param"); foreach (XElement paramNode in metaParamNodes) { string pName = paramNode.Attribute("name").Value; string pExpr = paramNode.Attribute("select").Value; xsltArgList.AddParam(pName, string.Empty, workingDoc.XPathEvaluate(pExpr, customContext)); } XDocument outputDoc = new XDocument(); using (XmlWriter outputWriter = outputDoc.CreateWriter()) { metaTransform.Transform(workingDoc.CreateNavigator(), xsltArgList, outputWriter, fileResolver); } TraceSources.TemplateSource.TraceVerbose("Template after transformation by {0}", metaNode.Attribute("stylesheet").Value); TraceSources.TemplateSource.TraceData(TraceEventType.Verbose, 1, outputDoc.CreateNavigator()); workingDoc = outputDoc; } else { // didn't process, so remove it metaNode.Remove(); } // select next template metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault(); } // loading template List<Stylesheet> stylesheets = new List<Stylesheet>(); List<Resource> resources = new List<Resource>(); List<Index> indices = new List<Index>(); foreach (XElement elem in workingDoc.Root.Elements()) { // we alread proessed the parameters if (elem.Name.LocalName == "parameter") continue; if (elem.Name.LocalName == "apply-stylesheet") { stylesheets.Add(this.ParseStylesheet(stylesheets, elem)); } else if (elem.Name.LocalName == "index") { indices.Add(this.ParseIndex(elem)); } else if (elem.Name.LocalName == "include-resource") { resources.Add(new Resource { Path = elem.Attribute("path").Value, ConditionExpression = this.GetAttributeValueOrDefault(elem, "condition") }); } else { throw new Exception("Unknown element: " + elem.Name.LocalName); } } return new ParsedTemplate { Resources = resources.ToArray(), Stylesheets = stylesheets.ToArray(), Indices = indices.ToArray() }; }
public static System.Xml.Linq.XAttribute XPathSelectAttribute(this System.Xml.Linq.XDocument xdocument, string expression, System.Xml.IXmlNamespaceResolver resolver) => ((IEnumerable)xdocument.XPathEvaluate(expression, resolver)).Cast <System.Xml.Linq.XAttribute>().FirstOrDefault();
/// <summary> /// Returns the XML documentation (returns/param tag) for the specified parameter. /// </summary> /// <param name="parameter">The reflected parameter (or return value).</param> /// <param name="xml">XML documentation.</param> /// <returns>The contents of the returns/param tag for the parameter.</returns> public static string GetXmlDocumentation(this ParameterInfo parameter, XDocument xml) { if (parameter.IsRetval || String.IsNullOrEmpty(parameter.Name)) return xml.XPathEvaluate( String.Format( "string(/doc/members/member[@name='{0}']/returns)", GetMemberElementName(parameter.Member) ) ).ToString().Trim(); else return xml.XPathEvaluate( String.Format( "string(/doc/members/member[@name='{0}']/param[@name='{1}'])", GetMemberElementName(parameter.Member), parameter.Name ) ).ToString().Trim(); }
private static XElement GetTargetImportNode(XDocument document) { var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("aw", "http://schemas.microsoft.com/developer/msbuild/2003"); var importProjectNode = (IEnumerable) document.XPathEvaluate("/aw:Project/aw:Import[@Project='BridgeBuildTask.targets']", namespaceManager); var linqBridgeTargetImportNode = importProjectNode.Cast<XElement>().FirstOrDefault(); return linqBridgeTargetImportNode; }
public static IEnumerable <System.Xml.Linq.XAttribute> XPathSelectAttributes(this System.Xml.Linq.XDocument xdocument, string expression) => ((IEnumerable)xdocument.XPathEvaluate(expression)).Cast <System.Xml.Linq.XAttribute>();
private static int XPathCount(XDocument output, string path) { return Convert.ToInt32(output.XPathEvaluate(String.Format("count({0})", path))); }
private bool XPathIsValid(XDocument doc, XElement element, string xPath) { var xPathEvaluate = doc.XPathEvaluate(xPath); var xPathResults = doc.XPathSelectElements(xPath).ToArray(); var result = (xPathResults.Count() == 1 && xPathResults.First().ToString() == element.ToString()); return result; }
public ValidationResultList Validate(T input) { if (null == this.Source) { throw new InvalidOperationException("The Source property must be set before calling Validate"); } ValidationResultCollection results = new ValidationResultCollection(); this.Source.ValidationEventHandler = (e) => { if (null == e) { throw new ArgumentNullException("e"); } if (null == e.Exception) { throw new ArgumentException("The validation event args must contain an exception"); } ValidationResult r = this.XmlExceptionInterpreters.Interpret("Structure", e.Exception); if (null != r) { ValidationInstance vi = null; if (e.Exception is System.Xml.Schema.XmlSchemaException) { vi = new ValidationInstance() { LinePosition = (e.Exception as System.Xml.Schema.XmlSchemaException).LinePosition, LineNumber = (e.Exception as System.Xml.Schema.XmlSchemaException).LineNumber, Status = ValidationStatus.Exception }; } if (null != vi) { r.Instances.Add(vi); } results.Add(r.Message, r); } else { results.Add(e.Message, new ValidationResult() { Exception = e.Exception, Message = e.Message }); } }; System.Xml.Linq.XDocument doc = null; //doc.Schemas = xmlReader.Settings.Schemas; using (this.TimedLogs.Step("Loading and parsing XML file")) { DateTime start = DateTime.Now; try { using (XmlReader xmlReader = this.Source.GetXmlReader(input)) { doc = System.Xml.Linq.XDocument.Load(xmlReader, System.Xml.Linq.LoadOptions.SetLineInfo); } } catch (System.Xml.XmlException e) { ValidationResult r = this.XmlExceptionInterpreters.Interpret("Structure", e); r.Instances.Add(new ValidationInstance() { LineNumber = e.LineNumber, LinePosition = e.LinePosition, Status = ValidationStatus.Exception }); if (null != r) { results.Add(r.Message, r); } } // Check to see whether there was an xsi:schemaLocation if ( (null != doc) && (results.Count != 0) && this.AttemptSchemaLocationInjection ) { XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(new NameTable()); xmlnsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); if (((double)doc.XPathEvaluate("count(//@xsi:schemaLocation)", xmlnsmgr)) == 0) { results.Clear(); // Add in to say we're missing an xsi:schemaLocation attribute ValidationResult r = this.XmlExceptionInterpreters.Interpret("Structure", new ValidationException("Missing xsi:schemaLocation attribute")); r.Instances.Add(new ValidationInstance() { LineNumber = (doc.Root as IXmlLineInfo).LineNumber, LinePosition = (doc.Root as IXmlLineInfo).LinePosition, Status = ValidationStatus.Warning }); if (null != r) { results.Add(r.Message, r); } // If we're missing an xsi:schemaLocation then it'll all go to pot. // Be nice and try and add the data. XmlSchemaSet schemaSet = new XmlSchemaSet(new NameTable()); schemaSet.XmlResolver = this.XmlCachingResolver as XmlResolver; schemaSet.Add ( "http://xcri.org/profiles/1.2/catalog", "http://www.xcri.co.uk/bindings/xcri_cap_1_2.xsd" ); schemaSet.Add ( "http://xcri.org/profiles/1.2/catalog/terms", "http://www.xcri.co.uk/bindings/xcri_cap_terms_1_2.xsd" ); schemaSet.Add ( "http://xcri.co.uk", "http://www.xcri.co.uk/bindings/coursedataprogramme.xsd" ); schemaSet.Compile(); doc.Validate(schemaSet, new ValidationEventHandler((o, e) => { this.Source.ValidationEventHandler(e); })); } } if (null != doc) { using (this.TimedLogs.Step("Executing content validators")) { if (null != this.XmlContentValidators) { foreach (var cv in this.XmlContentValidators) { var vrc = cv.Validate(doc.Root); if (null != vrc) { foreach (var vr in vrc) { if (null != vr) { results.Add(vr.Message, vr); } } } } } } } } return(new ValidationResultList(results.Values) { Document = doc }); }
private static XDocument PatchDataflowColumnIds(XDocument document) { var dtsIdDictionary = new Dictionary<string, string>(); XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(new NameTable()); xmlnsManager.AddNamespace("DTS", "www.microsoft.com/SqlServer/Dts"); var columnIdXPath = "//component/@id | //input/@id | //inputColumn/@id | //inputColumn/@lineageId | //output/@id | //output/@synchronousInputId | " + "//outputColumn/@id | //outputColumn/@lineageId | //property/@id | //path/@id | //externalMetadataColumn/@id | //connection/@id | " + "//inputColumn/@externalMetadataColumnId"; foreach (XAttribute dtsIdElement in (IEnumerable)document.XPathEvaluate(columnIdXPath, xmlnsManager)) { XAttribute nameAttribute = dtsIdElement.Parent.Attribute("name"); if (nameAttribute != null) { if (!dtsIdDictionary.ContainsKey(dtsIdElement.Value)) { dtsIdDictionary.Add(dtsIdElement.Value, nameAttribute.Value); } dtsIdElement.Value = nameAttribute.Value; } else { dtsIdElement.Value = "__GUID__"; } } foreach (XAttribute refAttribute in (IEnumerable)document.XPathEvaluate("//path/@startId | //path/@endId | //outputColumn/@externalMetadataColumnId")) { refAttribute.Value = dtsIdDictionary[refAttribute.Value]; } foreach (XElement refElement in (IEnumerable)document.XPathEvaluate("//property[@name='Expression'] | //property[@name='ParameterMap']")) { foreach (Match exp in Regex.Matches(refElement.Value, @"\#[0-9]*")) { string id = exp.Value.Substring(1); refElement.Value = refElement.Value.Replace(id, dtsIdDictionary[id]); } } foreach (XElement refElement in (IEnumerable)document.XPathEvaluate("//property[@name='OutputColumnLineageID'] | //property[@name='CustomLineageID'] | //property[@name='SortColumnId']")) { refElement.Value = dtsIdDictionary[refElement.Value]; } return document; }
protected virtual XDocument ApplyMetaTransforms(XDocument workingDoc, CustomXsltContext customContext, IFileProvider provider, TempFileCollection tempFiles) { // check for meta-template directives and expand int metaCount = 0; XElement metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault(); while (metaNode != null) { if (EvalCondition(customContext, metaNode, this.GetAttributeValueOrDefault(metaNode, "condition"))) { XslCompiledTransform metaTransform = this.LoadStylesheet(provider, this.GetAttributeValue(metaNode, "stylesheet")); XsltArgumentList xsltArgList = new XsltArgumentList(); // TODO this is a quick fix/hack xsltArgList.AddExtensionObject(Namespaces.Template, new TemplateXsltExtensions(null, null)); var metaParamNodes = metaNode.Elements("with-param"); foreach (XElement paramNode in metaParamNodes) { string pName = this.GetAttributeValue(paramNode, "name"); string pExpr = this.GetAttributeValue(paramNode, "select"); try { xsltArgList.AddParam(pName, string.Empty, workingDoc.XPathEvaluate(pExpr, customContext)); } catch (XPathException ex) { throw new TemplateException(this._templateSourcePath, paramNode.Attribute("select"), string.Format( "Unable to process XPath expression: '{0}'", pExpr), ex); } } // this isn't very nice, but I can't figure out another way to get LineInfo included in the transformed document XDocument outputDoc; using (MemoryStream tempStream = new MemoryStream()) using (XmlWriter outputWriter = XmlWriter.Create(tempStream, new XmlWriterSettings { Indent = true })) { metaTransform.Transform(workingDoc.CreateNavigator(), xsltArgList, outputWriter, new XmlFileProviderResolver(provider)); outputWriter.Close(); // rewind stream tempStream.Seek(0, SeekOrigin.Begin); outputDoc = XDocument.Load(tempStream, LoadOptions.SetLineInfo); // create and register temp file // this will override the value set in PrepareTemplate in case of template inhertence // TODO this is a bit hacky, maybe add Template.Name {get;} instead of this._basePath (which could be anything) string filename = this._basePath + ".meta." + (++metaCount).ToString(CultureInfo.InvariantCulture); this._templateSourcePath = this.SaveTempFile(tempFiles, outputDoc, filename); } TraceSources.TemplateSource.TraceVerbose("Template after transformation by {0}", this.GetAttributeValue(metaNode, "stylesheet")); TraceSources.TemplateSource.TraceData(TraceEventType.Verbose, 1, outputDoc.CreateNavigator()); workingDoc = outputDoc; } else { // didn't process, so remove it metaNode.Remove(); } // select next template metaNode = workingDoc.Root.Elements("meta-template").FirstOrDefault(); } return workingDoc; }
Documentation ToInlineDocs(XDocument doc, EnumProcessor enum_processor) { if (doc == null || enum_processor == null) throw new ArgumentNullException(); var no_const_processing = Settings.Legacy.NoAdvancedEnumProcessing | Settings.Legacy.ConstIntEnums; if (!Generator.Settings.IsEnabled(no_const_processing)) { // Translate all GL_FOO_BAR constants according to EnumProcessor foreach (var e in doc.XPathSelectElements("//constant")) { var c = e.Value; if (c.StartsWith(Settings.ConstantPrefix)) { // Remove "GL_" from the beginning of the string c = c.Replace(Settings.ConstantPrefix, String.Empty); } e.Value = enum_processor.TranslateConstantName(c, false); } } // Create inline documentation var inline = new Documentation { Summary = Cleanup( ((IEnumerable)doc.XPathEvaluate("/refentry/refnamediv/refpurpose")) .Cast<XElement>().First().Value), Parameters = ((IEnumerable)doc.XPathEvaluate("/refentry/refsect1[@id='parameters']/variablelist/varlistentry/term/parameter")) .Cast<XElement>() .Select(p => new DocumentationParameter( p.Value.Trim(), Cleanup(p.XPathSelectElement("../../listitem").Value))) .ToList() }; inline.Summary = Char.ToUpper(inline.Summary[0]) + inline.Summary.Substring(1); return inline; }
private static bool XPathExists(XDocument output, string path) { return Convert.ToBoolean(output.XPathEvaluate(String.Format("boolean({0})", path))); }