/// <summary> /// Determines whether this XElement instance contains a runat="server" attribute. /// </summary> /// <returns> /// <c>true</c> if this instance contains a runat="server" attribute; otherwise, <c>false</c>. /// </returns> /// <param name='el'> /// The XElement instace to be checked /// </param> public static bool IsRunAtServer (XElement el) { XName runat = new XName ("runat"); foreach (XAttribute a in el.Attributes) { if ((a.Name.ToLower () == runat) && (a.Value.ToLower () == "server")) return true; } return false; }
/// <summary> /// Gets the value of an attribute with name. The name is queried with a case insensitive search /// </summary> /// <returns> /// The value of the attribute or null if the an attribute with that name was not found /// </returns> /// <param name='attributes'> /// Attribute collection to be traversed /// </param> /// <param name='key'> /// Name of the attribute. /// </param> public static string GetAttributeValueCI (XAttributeCollection attributes, string key) { XName nameKey = new XName (key.ToLowerInvariant ()); foreach (XAttribute attr in attributes) { if (attr.Name.ToLower () == nameKey) return attr.Value; } return String.Empty; }
/// <summary> /// Gets the value of the attribute as a GUID. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <returns></returns> public static Guid AttributeValueAsGuid(this XElement element, XName attributeName) { XAttribute attribute = element.Attribute(attributeName); if (attribute == null) { string message = String.Format("The required attribute '{0}' was not found on '{1}'.", attributeName, element.Name); throw new XmlException(message); } return attribute.Value.ToGuid(); }
/// <summary> /// Gets the XAttribute instance of an attribute. The name is queried with a case insensitive search /// </summary> /// <returns> /// The XAttribute instance of an attribute or null, if none was found. /// </returns> /// <param name='attributes'> /// Attribute collection. /// </param> /// <param name='key'> /// Name of the attribute. /// </param> public static XAttribute GetAttributeCI (XAttributeCollection attributes, string key) { XName nameKey = new XName (key.ToLowerInvariant ()); foreach (XAttribute attr in attributes) { if (attr.Name.ToLower () == nameKey) return attr; } return null; }
/// <summary> /// Gets the value of the attribute as a Boolean. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <exception cref="XmlException">Thrown if the attribute is missing.</exception> public static bool AttributeValueAsBool(this XElement element, XName attributeName) { return (bool)element.EnsureAttribute(attributeName); }
private static XName GetElementName(string name) { return(XName.Get(name, XMLElementNamespace)); }
protected void AddHtmlAttributeCompletionData (CompletionDataList list, HtmlSchema schema, XName tagName, Dictionary<string, string> existingAtts) { //add atts only if they're not aready in the tag foreach (CompletionData datum in schema.CompletionProvider.GetAttributeCompletionData (tagName.FullName)) if (existingAtts == null || !existingAtts.ContainsKey (datum.DisplayText)) list.Add (datum); }
protected static void AddHtmlTagCompletionData(CompletionDataList list, HtmlSchema schema, XName parentName) { if (schema == null) { return; } if (parentName.IsValid) { list.AddRange(schema.CompletionProvider.GetChildElementCompletionData(parentName.FullName.ToLower())); } else { list.AddRange(schema.CompletionProvider.GetElementCompletionData()); } }
protected static async Task AddHtmlTagCompletionData (CompletionDataList list, HtmlSchema schema, XName parentName, CancellationToken token) { if (schema == null) return; if (parentName.IsValid) { list.AddRange (await schema.CompletionProvider.GetChildElementCompletionData (parentName.FullName.ToLower (), token)); } else { list.AddRange (await schema.CompletionProvider.GetElementCompletionData (token)); } }
static void GenerateCU (XmlParsedDocument doc) { if (doc.XDocument == null || doc.XDocument.RootElement == null) { doc.Add (new Error (ErrorType.Error, 1, 1, "No root node found.")); return; } XAttribute rootClass = doc.XDocument.RootElement.Attributes [new XName ("x", "Class")]; if (rootClass == null) { doc.Add (new Error (ErrorType.Error, 1, 1, "Root node does not contain an x:Class attribute.")); return; } bool isApplication = doc.XDocument.RootElement.Name.Name == "Application"; string rootNamespace, rootType, rootAssembly; XamlG.ParseXmlns (rootClass.Value, out rootType, out rootNamespace, out rootAssembly); CompilationUnit cu = new CompilationUnit (doc.FileName); doc.CompilationUnit = cu; DomRegion rootRegion = doc.XDocument.RootElement.Region; if (doc.XDocument.RootElement.IsClosed) rootRegion.End = doc.XDocument.RootElement.ClosingTag.Region.End; DomType declType = new DomType (cu, ClassType.Class, Modifiers.Partial | Modifiers.Public, rootType, doc.XDocument.RootElement.Region.Start, rootNamespace, rootRegion); cu.Add (declType); DomMethod initcomp = new DomMethod (); initcomp.Name = "InitializeComponent"; initcomp.Modifiers = Modifiers.Public; initcomp.ReturnType = DomReturnType.Void; declType.Add (initcomp); DomField _contentLoaded = new DomField ("_contentLoaded"); _contentLoaded.ReturnType = new DomReturnType ("System.Boolean"); if (isApplication) return; cu.Add (new DomUsing (DomRegion.Empty, "System")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Controls")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Documents")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Input")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Media")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Media.Animation")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Shapes")); cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Controls.Primitives")); // Dictionary<string,string> namespaceMap = new Dictionary<string, string> (); // namespaceMap["x"] = "http://schemas.microsoft.com/winfx/2006/xaml"; XName nameAtt = new XName ("x", "Name"); foreach (XElement el in doc.XDocument.RootElement.AllDescendentElements) { XAttribute name = el.Attributes [nameAtt]; if (name != null && name.IsComplete) { string type = ResolveType (el); if (type == null || type.Length == 0) doc.Add (new Error (ErrorType.Error, el.Region.Start, "Could not find namespace for '" + el.Name.FullName + "'.")); else declType.Add (new DomField (name.Value, Modifiers.Internal, el.Region.Start, new DomReturnType (type))); } } }
private static bool isResourceNameElement(XName elementName) { return Char.IsUpper(elementName.LocalName, 0) && elementName.Namespace == XmlNs.XFHIR; }
private static void InitFsm() { var transitions = new Dictionary <int, Transitions>(); transitions.Add(1, new Transitions(new SingleTransition(XName.Get("Documentation", XMLNamespaceFactory.SSDL), 2), new SingleTransition(XName.Get("DefiningQuery", XMLNamespaceFactory.SSDL), 4), new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 5))); transitions.Add(2, new Transitions(new SingleTransition(XName.Get("DefiningQuery", XMLNamespaceFactory.SSDL), 4), new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 5))); transitions.Add(4, new Transitions(new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 4))); transitions.Add(5, new Transitions(new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 5))); _validationStates = new FSM(1, new Set <int>(new[] { 2, 1, 4, 5 }), transitions); }
private static void BuildElementDictionary() { LocalElementDictionary.Add(XName.Get("Documentation", XMLNamespaceFactory.SSDL), typeof(Documentation)); LocalElementDictionary.Add(XName.Get("DefiningQuery", XMLNamespaceFactory.SSDL), typeof(string)); }
private static void BuildElementDictionary() { LocalElementDictionary.Add(XName.Get("Documentation", XMLNamespaceFactory.SSDL), typeof(Documentation)); LocalElementDictionary.Add(XName.Get("End", XMLNamespaceFactory.SSDL), typeof(EndLocalType)); }
private static void InitFsm() { var transitions = new Dictionary <int, Transitions>(); transitions.Add(1, new Transitions(new SingleTransition(XName.Get("Documentation", XMLNamespaceFactory.SSDL), 2), new SingleTransition(XName.Get("EntitySet", XMLNamespaceFactory.SSDL), 3), new SingleTransition(XName.Get("AssociationSet", XMLNamespaceFactory.SSDL), 3), new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 7))); transitions.Add(2, new Transitions(new SingleTransition(XName.Get("EntitySet", XMLNamespaceFactory.SSDL), 2), new SingleTransition(XName.Get("AssociationSet", XMLNamespaceFactory.SSDL), 2), new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 7))); transitions.Add(7, new Transitions(new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 7))); transitions.Add(3, new Transitions(new SingleTransition(XName.Get("EntitySet", XMLNamespaceFactory.SSDL), 3), new SingleTransition(XName.Get("AssociationSet", XMLNamespaceFactory.SSDL), 3), new SingleTransition(new WildCard("##other", XMLNamespaceFactory.SSDL), 7))); _validationStates = new FSM(1, new Set <int>(new[] { 2, 1, 3, 7 }), transitions); }
private static GeometryAndTimes GetGeometries(XElement root) { var geometries = new List <object>(); var coordTimes = new List <string[]>(); if (root.Element(Kml + "MultiGeometry") != null) { return(GetGeometries(root.Element(Kml + "MultiGeometry"))); } if (root.Element(Kml + "MultiTrack") != null) { return(GetGeometries(root.Element(Kml + "MultiTrack"))); } if (root.Element(Ext + "MultiTrack") != null) { return(GetGeometries(root.Element(Ext + "MultiTrack"))); } foreach (var geotype in Geotypes) { var geometryNodes = root .Elements(geotype) .ToList(); if (geometryNodes.Count > 0) { foreach (var geomNode in geometryNodes) { if (geotype == XName.Get("Point", Kml.NamespaceName)) { var coordinates = GetCoordinates(geomNode.Element(Kml + "coordinates").Value); if (coordinates != null) { var point = new Point { Coordinates = coordinates }; geometries.Add(point); } } else if (geotype == XName.Get("LineString", Kml.NamespaceName)) { var coordinates = GetCoordinatesArray(geomNode.Element(Kml + "coordinates").Value); if (coordinates != null) { var lineString = new LineString { Coordinates = coordinates }; geometries.Add(lineString); } } else if (geotype == XName.Get("Polygon", Kml.NamespaceName)) { var rings = new List <XElement>(); // Get Inner Boundary Linear Ring: var innerBoundaryNode = geomNode.Element(Kml + "innerBoundaryIs"); if (innerBoundaryNode != null) { var innerBoundaryRings = innerBoundaryNode.Elements(Kml + "LinearRing"); rings.AddRange(innerBoundaryRings); } var outerBoundaryNode = geomNode.Element(Kml + "outerBoundaryIs"); if (outerBoundaryNode != null) { var outerBoundaryRings = outerBoundaryNode.Elements(Kml + "LinearRing"); rings.AddRange(outerBoundaryRings); } var coordinates = new List <float[][]>(); foreach (var ring in rings) { var coordinatesNode = ring.Element(Kml + "coordinates")?.Value; var coordinatesOfRing = GetCoordinatesArray(coordinatesNode); if (coordinatesOfRing != null) { coordinates.Add(coordinatesOfRing); } } if (coordinates.Count > 0) { var polygon = new Polygon { Coordinates = coordinates }; geometries.Add(polygon); } } else if (geotype == XName.Get("Track", Kml.NamespaceName) || geotype == XName.Get("Track", Ext.NamespaceName)) { var track = GetGxCoords(geomNode); if (track.Coordinates != null) { var lineString = new LineString { Coordinates = track.Coordinates }; geometries.Add(lineString); } var times = track.Times; if (times != null) { coordTimes.Add(track.Times); } } } } } return(new GeometryAndTimes { GeometryNodes = geometries.ToArray(), Times = coordTimes.ToArray() }); }
protected void AddHtmlAttributeValueCompletionData(CompletionDataList list, HtmlSchema schema, XName tagName, XName attributeName) { list.AddRange(schema.CompletionProvider.GetAttributeValueCompletionData(tagName.FullName, attributeName.FullName)); }
/// <summary> /// Gets the value of the attribute as a DateTime. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <exception cref="XmlException">Thrown if the attribute is missing.</exception> public static DateTime AttributeValueAsDateTime(this XElement element, XName attributeName) { return (DateTime)element.EnsureAttribute(attributeName); }
/// <summary> /// Gets the value of the attribute as a double. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <exception cref="XmlException">Thrown if the attribute is missing.</exception> public static double AttributeValueAsDouble(this XElement element, XName attributeName) { return (double)element.EnsureAttribute(attributeName); }
protected virtual object Map(object x, XElement root) { Type objType = x.GetType(); PropertyInfo[] props = objType.GetProperties(); bool deserializeFromContentAttributeAlreadyUsed = false; foreach (var prop in props) { var type = prop.PropertyType.GetTypeInfo(); var typeIsPublic = type.IsPublic || type.IsNestedPublic; if (!typeIsPublic || !prop.CanWrite) { continue; } bool deserializeFromContent = false; bool isNameDefinedInAttribute = false; XName name = null; var attributes = prop.GetCustomAttributes(typeof(DeserializeAsAttribute), false); if (attributes.Any()) { DeserializeAsAttribute attribute = (DeserializeAsAttribute)attributes.First(); name = attribute.Name.AsNamespaced(Namespace); isNameDefinedInAttribute = !string.IsNullOrEmpty(name?.LocalName); deserializeFromContent = attribute.Content; if (deserializeFromContentAttributeAlreadyUsed && deserializeFromContent) { throw new ArgumentException("Class cannot have two properties marked with " + "SerializeAs(Content = true) attribute."); } deserializeFromContentAttributeAlreadyUsed |= deserializeFromContent; } if (name == null) { name = prop.Name.AsNamespaced(Namespace); } var value = GetValueFromXml(root, name, prop, isNameDefinedInAttribute); if (value == null) { // special case for text content node if (deserializeFromContent) { var textNode = root.Nodes().FirstOrDefault(n => n is XText); if (textNode != null) { value = ((XText)textNode).Value; prop.SetValue(x, value, null); } continue; } // special case for inline list items if (type.IsGenericType) { var genericType = type.GetGenericArguments()[0]; var first = GetElementByName(root, genericType.Name); var list = (IList)Activator.CreateInstance(type.AsType()); if (first != null && root != null) { var elements = root.Elements(first.Name); PopulateListFromElements(genericType, elements, list); } prop.SetValue(x, list, null); } continue; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { // if the value is empty, set the property to null... if (string.IsNullOrEmpty(value.ToString())) { prop.SetValue(x, null, null); continue; } type = type.GetGenericArguments()[0].GetTypeInfo(); } var asType = type.AsType(); if (asType == typeof(bool)) { var toConvert = value.ToString() .ToLower(); prop.SetValue(x, XmlConvert.ToBoolean(toConvert), null); } else if (type.IsPrimitive) { prop.SetValue(x, value.ChangeType(asType, Culture), null); } else if (type.IsEnum) { var converted = type.AsType().FindEnumValue(value.ToString(), Culture); prop.SetValue(x, converted, null); } else if (asType == typeof(Uri)) { var uri = new Uri(value.ToString(), UriKind.RelativeOrAbsolute); prop.SetValue(x, uri, null); } else if (asType == typeof(string)) { prop.SetValue(x, value, null); } else if (asType == typeof(DateTime)) { value = DateFormat.HasValue() ? DateTime.ParseExact(value.ToString(), DateFormat, Culture) : DateTime.Parse(value.ToString(), Culture); prop.SetValue(x, value, null); } else if (asType == typeof(DateTimeOffset)) { var toConvert = value.ToString(); if (string.IsNullOrEmpty(toConvert)) { continue; } DateTimeOffset deserialisedValue; try { deserialisedValue = XmlConvert.ToDateTimeOffset(toConvert); prop.SetValue(x, deserialisedValue, null); } catch (Exception) { if (TryGetFromString(toConvert, out var result, asType)) { prop.SetValue(x, result, null); } else { //fallback to parse deserialisedValue = DateTimeOffset.Parse(toConvert); prop.SetValue(x, deserialisedValue, null); } } }
static void GenerateCU (XmlParsedDocument doc) { if (doc.XDocument == null || doc.XDocument.RootElement == null) { doc.Add (new Error (ErrorType.Error, "No root node found.", 1, 1)); return; } XAttribute rootClass = doc.XDocument.RootElement.Attributes [new XName ("x", "Class")]; if (rootClass == null) { doc.Add (new Error (ErrorType.Error, "Root node does not contain an x:Class attribute.", 1, 1)); return; } bool isApplication = doc.XDocument.RootElement.Name.Name == "Application"; string rootNamespace, rootType, rootAssembly; XamlG.ParseXmlns (rootClass.Value, out rootType, out rootNamespace, out rootAssembly); var cu = new DefaultParsedDocument (doc.FileName); DomRegion rootRegion = doc.XDocument.RootElement.Region; if (doc.XDocument.RootElement.IsClosed) rootRegion = new DomRegion (doc.XDocument.RootElement.Region.FileName, doc.XDocument.RootElement.Region.Begin, doc.XDocument.RootElement.ClosingTag.Region.End); var declType = new DefaultUnresolvedTypeDefinition (rootNamespace, rootType) { Kind = TypeKind.Class, Accessibility = Accessibility.Public, Region = rootRegion }; cu.TopLevelTypeDefinitions.Add (declType); var initcomp = new DefaultUnresolvedMethod (declType, "InitializeComponent") { ReturnType = KnownTypeReference.Void, Accessibility = Accessibility.Public }; declType.Members.Add (initcomp); var _contentLoaded = new DefaultUnresolvedField (declType, "_contentLoaded") { ReturnType = KnownTypeReference.Boolean }; // was missing in the original code: correct ? // declType.Fields.Add (_contentLoaded); if (isApplication) return; // cu.Add (new DomUsing (DomRegion.Empty, "System")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Controls")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Documents")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Input")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Media")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Media.Animation")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Shapes")); // cu.Add (new DomUsing (DomRegion.Empty, "System.Windows.Controls.Primitives")); // Dictionary<string,string> namespaceMap = new Dictionary<string, string> (); // namespaceMap["x"] = "http://schemas.microsoft.com/winfx/2006/xaml"; XName nameAtt = new XName ("x", "Name"); foreach (XElement el in doc.XDocument.RootElement.AllDescendentElements) { XAttribute name = el.Attributes [nameAtt]; if (name != null && name.IsComplete) { string type = ResolveType (el); if (type == null || type.Length == 0) cu.Add (new Error (ErrorType.Error, "Could not find namespace for '" + el.Name.FullName + "'.", el.Region.Begin)); else declType.Members.Add (new DefaultUnresolvedField (declType, name.Value) { Accessibility = Accessibility.Internal, Region = el.Region, ReturnType = new DefaultUnresolvedTypeDefinition (type) }); } } }
public void Execute(InstrumentationResult result, IFileInfo output) { var hits = _hitsReader.TryReadFromDirectory(result.HitsPath); int fileIndex = 0; int sequencePointMegaCounter = 0; var data = new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='coverage.xsl'"); var document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), data); var coverageElement = new XElement( XName.Get("CoverageSession") ); var modulesListElement = new XElement("Modules", result.Assemblies.Select(assembly => { var moduleElement = new XElement( XName.Get("Module"), new XAttribute(XName.Get("hash"), Guid.NewGuid().ToString()) ); var fullNameElement = new XElement( XName.Get("FullName"), new XText(assembly.Name) ); var moduleNameElement = new XElement( XName.Get("ModuleName"), new XText(assembly.Name) ); Dictionary <SourceFile, int> dctSourceFileCount = new Dictionary <SourceFile, int>(); var filesElement = new XElement("Files", assembly.SourceFiles.Select(file => { dctSourceFileCount.Add(file, ++fileIndex); var fileElement = new XElement( XName.Get("File"), new XAttribute(XName.Get("uid"), dctSourceFileCount[file]), new XAttribute(XName.Get("fullPath"), Path.Combine(result.SourcePath, file.Path)) ); return(fileElement); })); var classesElement = new XElement("Classes", assembly.SourceFiles.Select(file => { var hitInstructions = file.Sequences.Where(h => hits.WasHit(h.HitId)).ToArray(); return(file.Sequences .GroupBy(instruction => new { instruction.Method.Class }) .Select(classes => { var classElement = new XElement( XName.Get("Class") ); var classfullNameElement = new XElement( XName.Get("FullName"), new XText(classes.Key.Class) ); var methodsList = new XElement("Methods", classes .GroupBy(instruction => instruction.Method) .Select(method => { var nameElement = new XElement( XName.Get("Name"), new XText(method.Key.FullName) ); var fileRefElement = new XElement( XName.Get("FileRef"), new XAttribute(XName.Get("uid"), dctSourceFileCount[file]) ); int sequencePointMiniCounter = 0; var sequencePoints = new XElement("SequencePoints", method .OrderBy(methodPoint => methodPoint.StartLine) .Select(methodPoint => { var hitCount = hitInstructions.Count(hit => hit.Equals(methodPoint)); return new XElement( XName.Get("SequencePoint"), new XAttribute(XName.Get("vc"), hitCount), new XAttribute(XName.Get("uspid"), ++sequencePointMegaCounter), new XAttribute(XName.Get("ordinal"), ++sequencePointMiniCounter), new XAttribute(XName.Get("sl"), methodPoint.StartLine), new XAttribute(XName.Get("sc"), methodPoint.StartColumn), new XAttribute(XName.Get("el"), methodPoint.EndLine), new XAttribute(XName.Get("ec"), methodPoint.EndColumn) ); })); var methodElement = new XElement( XName.Get("Method"), new XAttribute(XName.Get("visited"), method.Any(p => hitInstructions.Any(hit => hit == p))), new XAttribute(XName.Get("isConstructor"), method.Key.Name == ".ctor") ); methodElement.Add(nameElement); methodElement.Add(fileRefElement); methodElement.Add(sequencePoints); return methodElement; })); classElement.Add(classfullNameElement); classElement.Add(methodsList); return classElement; })); })); moduleElement.Add(fullNameElement); moduleElement.Add(moduleNameElement); moduleElement.Add(filesElement); moduleElement.Add(classesElement); return(moduleElement); })); coverageElement.Add(modulesListElement); document.Add(coverageElement); output.Directory.Create(); _fileSystem.File.WriteAllText(output.FullName, document.ToString()); }
public AspNetDirective (DomLocation start, XName name) : this (start) { this.name = name; }
public static int GetAttributeValue(this XElement element, XName attributeName, int defaultValue) { int result = element.GetAttributeValue(attributeName, defaultValue, x => int.Parse(x, CultureInfo.CurrentCulture)); return result; }
protected async Task AddHtmlAttributeValueCompletionData (CompletionDataList list, HtmlSchema schema, XName tagName, XName attributeName, CancellationToken token) { list.AddRange (await schema.CompletionProvider.GetAttributeValueCompletionData (tagName.FullName, attributeName.FullName, token)); }
public static string GetAttributeValue(this XElement element, XName attributeName, string defaultValue) { string result = element.GetAttributeValue(attributeName, defaultValue, x => x); return result; }
public string Attribute(XName xName) { return "attr[" + xName + "]"; }
public static T GetAttributeValue<T>(this XElement element, XName attributeName, T defaultValue) where T : struct { T result = element.GetAttributeValue(attributeName, defaultValue, x => (T)Enum.Parse(typeof(T), x, false)); return result; }
public WebFormsDirective (TextLocation start, XName name) : this (start) { this.name = name; }
public static Formatting Parse(XElement rPr) { Formatting formatting = new Formatting(); // Build up the Formatting object. foreach (XElement option in rPr.Elements()) { switch (option.Name.LocalName) { case "lang": formatting.Language = new CultureInfo(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName), null) ?? option.GetAttribute(XName.Get("eastAsia", DocX.w.NamespaceName), null) ?? option.GetAttribute(XName.Get("bidi", DocX.w.NamespaceName))); break; case "spacing": formatting.Spacing = Double.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 20.0; break; case "position": formatting.Position = Int32.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2; break; case "kern": formatting.Position = Int32.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2; break; case "w": formatting.PercentageScale = Int32.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))); break; case "rFonts": break; case "vanish": formatting.hidden = true; break; case "b": formatting.Bold = true; break; case "i": formatting.Italic = true; break; default: break; } } return(formatting); }
public static XElement ToXElementIfNotEmpty(this string value, XName name) { return String.IsNullOrWhiteSpace(value) ? null : new XElement(name, value); }
public XDeferredAxis(Func <XElement, XName, IEnumerable <T> > func, XElement element, XName name) { if (func == null) { throw new ArgumentNullException("func"); } if (element == null) { throw new ArgumentNullException("element"); } this.func = func; this.element = element; this.name = name; }
/// <summary> /// Gets the value of the attribute as a Boolean, or the specified default value if the attribute missing. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">The default value if the attribute is missing.</param> public static bool AttributeValueAsBool(this XElement element, XName attributeName, bool defaultValue) { XAttribute attribute = element.Attribute(attributeName); return (attribute == null) ? defaultValue : (bool)attribute; }
/// <summary> /// The Get Operation Status operation returns the status of /// thespecified operation. After calling an asynchronous operation, /// you can call Get Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// The request ID for the request you wish to track. The request ID is /// returned in the x-ms-request-id response header for every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task <AddOnOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = new Uri(this.BaseUri, "/").ToString() + this.Credentials.SubscriptionId + "/operations/" + requestId; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result AddOnOperationStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AddOnOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = (OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, false); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, false); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { AddOnOperationStatusResponse.ErrorDetails errorInstance = new AddOnOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Gets the value of the attribute as a DateTime, or the specified default value if the attribute missing. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">The default value if the attribute is missing.</param> public static DateTime AttributeValueAsDateTime(this XElement element, XName attributeName, DateTime defaultValue) { XAttribute attribute = element.Attribute(attributeName); return (attribute == null) ? defaultValue : (DateTime)attribute; }
// Use a forward-only XmlReader to scan through a possibly huge bundled file, // and yield the feed entries, so only one entry is in memory at a time internal IEnumerable <XElement> StreamResources() { var reader = SerializationUtil.XmlReaderFromStream(_input); var root = getRootName(reader); if (root == "Bundle") { if (!reader.ReadToDescendant("entry", XmlNs.FHIR)) { yield break; } while (!reader.EOF) { if (reader.NodeType == XmlNodeType.Element && reader.NamespaceURI == XmlNs.FHIR && reader.LocalName == "entry") { var entryNode = (XElement)XElement.ReadFrom(reader); var fullUrl = entryNode.Elements(XmlNs.XFHIR + "fullUrl").Attributes("value").SingleOrDefault(); if (fullUrl != null) { var resourceNode = entryNode.Element(XName.Get("resource", XmlNs.FHIR)); if (resourceNode != null) { var resource = resourceNode.Elements().First(); resource.AddAnnotation(new FullUrlAnnotation { FullUrl = fullUrl.Value }); yield return(resource); } } } else { reader.Read(); } } } #if true // [WMR 20160908] Originally commented out logic //else if (root != null) //{ // var resourceNode = (XElement)XElement.ReadFrom(reader); // var resourceId = resourceNode.Elements(XmlNs.XFHIR + "id").Attributes("value").SingleOrDefault(); // if (resourceId != null) // { // var fullUrl = resourceNode.Name.LocalName + "/" + resourceId.Value; // resourceNode.Add(new XAttribute("scannerUrl", fullUrl)); // yield return resourceNode; // } //} // [WMR 20160908] Fixed, parse stand-alone (conformance) resources else if (root != null) { var resourceNode = (XElement)XElement.ReadFrom(reader); // First try to initialize from canonical url (conformance resources) var canonicalUrl = resourceNode.Elements(XmlNs.XFHIR + "url").Attributes("value").SingleOrDefault(); if (canonicalUrl != null) { resourceNode.AddAnnotation(new FullUrlAnnotation { FullUrl = canonicalUrl.Value }); yield return(resourceNode); } else { // Otherwise try to initialize from resource id var resourceId = resourceNode.Elements(XmlNs.XFHIR + "id").Attributes("value").SingleOrDefault(); if (resourceId != null) { var fullUrl = resourceNode.Name.LocalName + "/" + resourceId.Value; resourceNode.AddAnnotation(new FullUrlAnnotation { FullUrl = fullUrl }); yield return(resourceNode); } } } #endif else { yield break; } }
/// <summary> /// Gets the value of the attribute as a double, or the specified default value if the attribute is missing. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">The default value if the attribute is missing.</param> public static double AttributeValueAsDouble(this XElement element, XName attributeName, double defaultValue) { XAttribute attribute = element.Attribute(attributeName); return (attribute == null) ? defaultValue : (double)attribute; }
// The following method is written using tree modification, not RPFT, because it is easier to write in this fashion. // These types of operations are not as easy to write using RPFT. // Unless you are completely clear on the semantics of LINQ to XML DML, do not make modifications to this method. private static void NormalizeTablesRepeatAndConditional(XElement xDoc, TemplateError te) { var tables = xDoc.Descendants(PA.Table).ToList(); foreach (var table in tables) { var followingElement = table.ElementsAfterSelf().Where(e => e.Name == W.tbl || e.Name == W.p).FirstOrDefault(); if (followingElement == null || followingElement.Name != W.tbl) { table.ReplaceWith(CreateParaErrorMessage("Table metadata is not immediately followed by a table", te)); continue; } // remove superflous paragraph from Table metadata table.RemoveNodes(); // detach w:tbl from parent, and add to Table metadata followingElement.Remove(); table.Add(followingElement); } int repeatDepth = 0; int conditionalDepth = 0; foreach (var metadata in xDoc.Descendants().Where(d => d.Name == PA.Repeat || d.Name == PA.Conditional || d.Name == PA.EndRepeat || d.Name == PA.EndConditional)) { if (metadata.Name == PA.Repeat) { ++repeatDepth; metadata.Add(new XAttribute(PA.Depth, repeatDepth)); continue; } if (metadata.Name == PA.EndRepeat) { metadata.Add(new XAttribute(PA.Depth, repeatDepth)); --repeatDepth; continue; } if (metadata.Name == PA.Conditional) { ++conditionalDepth; metadata.Add(new XAttribute(PA.Depth, conditionalDepth)); continue; } if (metadata.Name == PA.EndConditional) { metadata.Add(new XAttribute(PA.Depth, conditionalDepth)); --conditionalDepth; continue; } } while (true) { bool didReplace = false; foreach (var metadata in xDoc.Descendants().Where(d => (d.Name == PA.Repeat || d.Name == PA.Conditional) && d.Attribute(PA.Depth) != null).ToList()) { var depth = (int)metadata.Attribute(PA.Depth); XName matchingEndName = null; if (metadata.Name == PA.Repeat) { matchingEndName = PA.EndRepeat; } else if (metadata.Name == PA.Conditional) { matchingEndName = PA.EndConditional; } if (matchingEndName == null) { throw new OpenXmlPowerToolsException("Internal error"); } var matchingEnd = metadata.ElementsAfterSelf(matchingEndName).FirstOrDefault(end => { return((int)end.Attribute(PA.Depth) == depth); }); if (matchingEnd == null) { metadata.ReplaceWith(CreateParaErrorMessage(string.Format("{0} does not have matching {1}", metadata.Name.LocalName, matchingEndName.LocalName), te)); continue; } metadata.RemoveNodes(); var contentBetween = metadata.ElementsAfterSelf().TakeWhile(after => after != matchingEnd).ToList(); foreach (var item in contentBetween) { item.Remove(); } contentBetween = contentBetween.Where(n => n.Name != W.bookmarkStart && n.Name != W.bookmarkEnd).ToList(); metadata.Add(contentBetween); metadata.Attributes(PA.Depth).Remove(); matchingEnd.Remove(); didReplace = true; break; } if (!didReplace) { break; } } }
/// <summary> /// Gets the value of the attribute as a GUID, or the default value if the attribute is missing. /// </summary> /// <param name="element">The element.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static Guid AttributeValueAsGuid(this XElement element, XName attributeName, Guid defaultValue) { XAttribute attribute = element.Attribute(attributeName); return attribute == null ? defaultValue : attribute.Value.ToGuid(); }
private static void UpdateSeries(ChartPart chartPart, ChartData chartData) { UpdateEmbeddedWorkbook(chartPart, chartData); XDocument cpXDoc = chartPart.GetXDocument(); XElement root = cpXDoc.Root; var firstSeries = root.Descendants(C.ser).FirstOrDefault(); var numRef = firstSeries.Elements(C.val).Elements(C.numRef).FirstOrDefault(); string sheetName = null; var f = (string)firstSeries.Descendants(C.f).FirstOrDefault(); if (f != null) { sheetName = f.Split('!')[0]; } // remove all but first series XName chartType = firstSeries.Parent.Name; firstSeries.Parent.Elements(C.ser).Skip(1).Remove(); var newSetOfSeries = chartData.SeriesNames .Select((string sn, int si) => { XElement cat = null; var oldCat = firstSeries.Elements(C.cat).FirstOrDefault(); if (oldCat == null) { throw new OpenXmlPowerToolsException("Invalid chart markup"); } var catHasFormula = oldCat.Descendants(C.f).Any(); if (catHasFormula) { XElement newFormula = null; if (sheetName != null) { newFormula = new XElement(C.f, string.Format("{0}!$A$2:$A${1}", sheetName, chartData.CategoryNames.Length + 1)); } if (chartData.CategoryDataType == ChartDataType.String) { cat = new XElement(C.cat, new XElement(C.strRef, newFormula, new XElement(C.strCache, new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)), chartData.CategoryNames.Select((string cn, int ci) => { var newPt = new XElement(C.pt, new XAttribute("idx", ci), new XElement(C.v, chartData.CategoryNames[ci])); return(newPt); })))); } else { cat = new XElement(C.cat, new XElement(C.numRef, newFormula, new XElement(C.numCache, new XElement(C.formatCode, FormatCodes[chartData.CategoryFormatCode]), new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)), chartData.CategoryNames.Select((string cn, int ci) => { var newPt = new XElement(C.pt, new XAttribute("idx", ci), new XElement(C.v, chartData.CategoryNames[ci])); return(newPt); })))); } } else { if (chartData.CategoryDataType == ChartDataType.String) { cat = new XElement(C.cat, new XElement(C.strLit, new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)), chartData.CategoryNames.Select((string cn, int ci) => { var newPt = new XElement(C.pt, new XAttribute("idx", ci), new XElement(C.v, chartData.CategoryNames[ci])); return(newPt); }))); } else { cat = new XElement(C.cat, new XElement(C.numLit, new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)), chartData.CategoryNames.Select((string cn, int ci) => { var newPt = new XElement(C.pt, new XAttribute("idx", ci), new XElement(C.v, chartData.CategoryNames[ci])); return(newPt); }))); } } XElement newCval = null; if (sheetName == null) { newCval = new XElement(C.val, new XElement(C.numLit, new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)), chartData.CategoryNames.Select((string cn, int ci) => { var newPt = new XElement(C.pt, new XAttribute("idx", ci), new XElement(C.v, chartData.Values[si][ci])); return(newPt); }))); } else { newCval = new XElement(C.val, new XElement(C.numRef, sheetName != null ? new XElement(C.f, string.Format("{0}!${2}$2:${2}${1}", sheetName, chartData.CategoryNames.Length + 1, SpreadsheetMLUtil.IntToColumnId(si + 1))) : null, new XElement(C.numCache, sheetName != null ? numRef.Descendants(C.formatCode) : null, new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)), chartData.CategoryNames.Select((string cn, int ci) => { var newPt = new XElement(C.pt, new XAttribute("idx", ci), new XElement(C.v, chartData.Values[si][ci])); return(newPt); })))); } var serHasFormula = firstSeries.Descendants(C.f).Any(); XElement tx = null; if (serHasFormula) { XElement newFormula = null; if (sheetName != null) { newFormula = new XElement(C.f, string.Format("{0}!${1}$1", sheetName, SpreadsheetMLUtil.IntToColumnId(si + 1))); } tx = new XElement(C.tx, new XElement(C.strRef, newFormula, new XElement(C.strCache, new XElement(C.ptCount, new XAttribute("val", 1)), new XElement(C.pt, new XAttribute("idx", 0), new XElement(C.v, chartData.SeriesNames[si]))))); } else { tx = new XElement(C.tx, new XElement(C.v, chartData.SeriesNames[si])); } XElement newSer = null; if (chartType == C.area3DChart || chartType == C.areaChart) { newSer = new XElement(C.ser, // common new XElement(C.idx, new XAttribute("val", si)), new XElement(C.order, new XAttribute("val", si)), tx, firstSeries.Elements(C.spPr), // CT_AreaSer firstSeries.Elements(C.pictureOptions), firstSeries.Elements(C.dPt), firstSeries.Elements(C.dLbls), firstSeries.Elements(C.trendline), firstSeries.Elements(C.errBars), cat, newCval, firstSeries.Elements(C.extLst)); } else if (chartType == C.bar3DChart || chartType == C.barChart) { newSer = new XElement(C.ser, // common new XElement(C.idx, new XAttribute("val", si)), new XElement(C.order, new XAttribute("val", si)), tx, firstSeries.Elements(C.spPr), // CT_BarSer firstSeries.Elements(C.invertIfNegative), firstSeries.Elements(C.pictureOptions), firstSeries.Elements(C.dPt), firstSeries.Elements(C.dLbls), firstSeries.Elements(C.trendline), firstSeries.Elements(C.errBars), cat, newCval, firstSeries.Elements(C.shape), firstSeries.Elements(C.extLst)); } else if (chartType == C.line3DChart || chartType == C.lineChart || chartType == C.stockChart) { newSer = new XElement(C.ser, // common new XElement(C.idx, new XAttribute("val", si)), new XElement(C.order, new XAttribute("val", si)), tx, firstSeries.Elements(C.spPr), // CT_LineSer firstSeries.Elements(C.marker), firstSeries.Elements(C.dPt), firstSeries.Elements(C.dLbls), firstSeries.Elements(C.trendline), firstSeries.Elements(C.errBars), cat, newCval, firstSeries.Elements(C.smooth), firstSeries.Elements(C.extLst)); } else if (chartType == C.doughnutChart || chartType == C.ofPieChart || chartType == C.pie3DChart || chartType == C.pieChart) { newSer = new XElement(C.ser, // common new XElement(C.idx, new XAttribute("val", si)), new XElement(C.order, new XAttribute("val", si)), tx, firstSeries.Elements(C.spPr), // CT_PieSer firstSeries.Elements(C.explosion), firstSeries.Elements(C.dPt), firstSeries.Elements(C.dLbls), cat, newCval, firstSeries.Elements(C.extLst)); } else if (chartType == C.surface3DChart || chartType == C.surfaceChart) { newSer = new XElement(C.ser, // common new XElement(C.idx, new XAttribute("val", si)), new XElement(C.order, new XAttribute("val", si)), tx, firstSeries.Elements(C.spPr), // CT_SurfaceSer cat, newCval, firstSeries.Elements(C.extLst)); } if (newSer == null) { throw new OpenXmlPowerToolsException("Unsupported chart type"); } int accentNumber = (si % 6) + 1; newSer = (XElement)UpdateAccentTransform(newSer, accentNumber); return(newSer); }); firstSeries.ReplaceWith(newSetOfSeries); chartPart.PutXDocument(); }
static string GetNamespace (XElement el) { XName attName; if (el.Name.HasPrefix) { attName = new XName ("xmlns", el.Name.Prefix); } else { attName = new XName ("xmlns"); XAttribute att = el.Attributes[attName]; if (att != null) return att.Value; } foreach (XNode node in el.Parents) { XElement parentElement = node as XElement; if (parentElement != null) { XAttribute att = parentElement.Attributes[attName]; if (att != null) return att.Value; } } return null; }
/// <summary> /// The List Resource Extensions operation lists the resource /// extensions that are available to add to a Virtual Machine. In /// Azure, a process can run as a resource extension of a Virtual /// Machine. For example, Remote Desktop Access or the Azure /// Diagnostics Agent can run as resource extensions to the Virtual /// Machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Resource Extensions operation response. /// </returns> public async Task <VirtualMachineExtensionListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/resourceextensions"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineExtensionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineExtensionListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement resourceExtensionsSequenceElement = responseDoc.Element(XName.Get("ResourceExtensions", "http://schemas.microsoft.com/windowsazure")); if (resourceExtensionsSequenceElement != null) { foreach (XElement resourceExtensionsElement in resourceExtensionsSequenceElement.Elements(XName.Get("ResourceExtension", "http://schemas.microsoft.com/windowsazure"))) { VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension(); result.ResourceExtensions.Add(resourceExtensionInstance); XElement publisherElement = resourceExtensionsElement.Element(XName.Get("Publisher", "http://schemas.microsoft.com/windowsazure")); if (publisherElement != null) { string publisherInstance = publisherElement.Value; resourceExtensionInstance.Publisher = publisherInstance; } XElement nameElement = resourceExtensionsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; resourceExtensionInstance.Name = nameInstance; } XElement versionElement = resourceExtensionsElement.Element(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); if (versionElement != null) { string versionInstance = versionElement.Value; resourceExtensionInstance.Version = versionInstance; } XElement labelElement = resourceExtensionsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; resourceExtensionInstance.Label = labelInstance; } XElement descriptionElement = resourceExtensionsElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; resourceExtensionInstance.Description = descriptionInstance; } XElement publicConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (publicConfigurationSchemaElement != null) { string publicConfigurationSchemaInstance = TypeConversion.FromBase64String(publicConfigurationSchemaElement.Value); resourceExtensionInstance.PublicConfigurationSchema = publicConfigurationSchemaInstance; } XElement privateConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (privateConfigurationSchemaElement != null) { string privateConfigurationSchemaInstance = TypeConversion.FromBase64String(privateConfigurationSchemaElement.Value); resourceExtensionInstance.PrivateConfigurationSchema = privateConfigurationSchemaInstance; } XElement sampleConfigElement = resourceExtensionsElement.Element(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure")); if (sampleConfigElement != null) { string sampleConfigInstance = TypeConversion.FromBase64String(sampleConfigElement.Value); resourceExtensionInstance.SampleConfig = sampleConfigInstance; } XElement replicationCompletedElement = resourceExtensionsElement.Element(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure")); if (replicationCompletedElement != null && !string.IsNullOrEmpty(replicationCompletedElement.Value)) { bool replicationCompletedInstance = bool.Parse(replicationCompletedElement.Value); resourceExtensionInstance.ReplicationCompleted = replicationCompletedInstance; } XElement eulaElement = resourceExtensionsElement.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement != null) { Uri eulaInstance = TypeConversion.TryParseUri(eulaElement.Value); resourceExtensionInstance.Eula = eulaInstance; } XElement privacyUriElement = resourceExtensionsElement.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement.Value); resourceExtensionInstance.PrivacyUri = privacyUriInstance; } XElement homepageUriElement = resourceExtensionsElement.Element(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure")); if (homepageUriElement != null) { Uri homepageUriInstance = TypeConversion.TryParseUri(homepageUriElement.Value); resourceExtensionInstance.HomepageUri = homepageUriInstance; } XElement isJsonExtensionElement = resourceExtensionsElement.Element(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure")); if (isJsonExtensionElement != null && !string.IsNullOrEmpty(isJsonExtensionElement.Value)) { bool isJsonExtensionInstance = bool.Parse(isJsonExtensionElement.Value); resourceExtensionInstance.IsJsonExtension = isJsonExtensionInstance; } XElement isInternalExtensionElement = resourceExtensionsElement.Element(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure")); if (isInternalExtensionElement != null && !string.IsNullOrEmpty(isInternalExtensionElement.Value)) { bool isInternalExtensionInstance = bool.Parse(isInternalExtensionElement.Value); resourceExtensionInstance.IsInternalExtension = isInternalExtensionInstance; } XElement disallowMajorVersionUpgradeElement = resourceExtensionsElement.Element(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure")); if (disallowMajorVersionUpgradeElement != null && !string.IsNullOrEmpty(disallowMajorVersionUpgradeElement.Value)) { bool disallowMajorVersionUpgradeInstance = bool.Parse(disallowMajorVersionUpgradeElement.Value); resourceExtensionInstance.DisallowMajorVersionUpgrade = disallowMajorVersionUpgradeInstance; } XElement supportedOSElement = resourceExtensionsElement.Element(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure")); if (supportedOSElement != null) { string supportedOSInstance = supportedOSElement.Value; resourceExtensionInstance.SupportedOS = supportedOSInstance; } XElement companyNameElement = resourceExtensionsElement.Element(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure")); if (companyNameElement != null) { string companyNameInstance = companyNameElement.Value; resourceExtensionInstance.CompanyName = companyNameInstance; } XElement publishedDateElement = resourceExtensionsElement.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement != null && !string.IsNullOrEmpty(publishedDateElement.Value)) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement.Value, CultureInfo.InvariantCulture); resourceExtensionInstance.PublishedDate = publishedDateInstance; } XElement regionsElement = resourceExtensionsElement.Element(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure")); if (regionsElement != null) { string regionsInstance = regionsElement.Value; resourceExtensionInstance.Regions = regionsInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public XClosingTag (XName name, DocumentLocation start) : base (start) { this.Name = name; }
/// <summary> /// Retrieve a list of Cloud services (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list cloud service operation. /// </returns> public async Task <CloudServiceListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string baseUrl = this.Client.BaseUri.AbsoluteUri; string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices?"; url = url + "resourceType=AutomationAccount"; url = url + "&detailLevel=Full"; url = url + "&resourceProviderNamespace=automation"; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result CloudServiceListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CloudServiceListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement cloudServicesSequenceElement = responseDoc.Element(XName.Get("CloudServices", "http://schemas.microsoft.com/windowsazure")); if (cloudServicesSequenceElement != null) { foreach (XElement cloudServicesElement in cloudServicesSequenceElement.Elements(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"))) { CloudService cloudServiceInstance = new CloudService(); result.CloudServices.Add(cloudServiceInstance); XElement nameElement = cloudServicesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; cloudServiceInstance.Name = nameInstance; } XElement labelElement = cloudServicesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; cloudServiceInstance.Label = labelInstance; } XElement descriptionElement = cloudServicesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; cloudServiceInstance.Description = descriptionInstance; } XElement geoRegionElement = cloudServicesElement.Element(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure")); if (geoRegionElement != null) { string geoRegionInstance = geoRegionElement.Value; cloudServiceInstance.GeoRegion = geoRegionInstance; } XElement resourcesSequenceElement = cloudServicesElement.Element(XName.Get("Resources", "http://schemas.microsoft.com/windowsazure")); if (resourcesSequenceElement != null) { foreach (XElement resourcesElement in resourcesSequenceElement.Elements(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"))) { AutomationResource resourceInstance = new AutomationResource(); cloudServiceInstance.Resources.Add(resourceInstance); XElement resourceProviderNamespaceElement = resourcesElement.Element(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure")); if (resourceProviderNamespaceElement != null) { string resourceProviderNamespaceInstance = resourceProviderNamespaceElement.Value; resourceInstance.Namespace = resourceProviderNamespaceInstance; } XElement typeElement = resourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; resourceInstance.Type = typeInstance; } XElement nameElement2 = resourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; resourceInstance.Name = nameInstance2; } XElement planElement = resourcesElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); if (planElement != null) { string planInstance = planElement.Value; resourceInstance.Plan = planInstance; } XElement schemaVersionElement = resourcesElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure")); if (schemaVersionElement != null) { string schemaVersionInstance = schemaVersionElement.Value; resourceInstance.SchemaVersion = schemaVersionInstance; } XElement eTagElement = resourcesElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure")); if (eTagElement != null) { string eTagInstance = eTagElement.Value; resourceInstance.ETag = eTagInstance; } XElement stateElement = resourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; resourceInstance.State = stateInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
void DocumentOutlineSelectionChanged (MonoDevelop.Xml.StateEngine.XNode selNode) { if (selNode == null) return; // not what we are looking for XElement el = selNode as XElement; if (el == null) return; // not a XML tag node bool isRunAtServer = false; string id = string.Empty; XName runatName = new XName ("runat"); XName idName = new XName ("id"); foreach (XAttribute attr in el.Attributes) { if (attr.Name.ToLower () == runatName) { if (attr.Value == "server") isRunAtServer = true; else break; } else if (attr.Name.ToLower () == idName) { id = attr.Value; } } if (isRunAtServer && (id != string.Empty) && (host != null)) { // TODO: Add a unique field to editable nodes. the id of the node is not guaranteed to be the component's Site.Name IComponent selected = host.DesignerHost.GetComponent (id); if (selected != null) { //var properties = TypeDescriptor.GetProperties (selected) as PropertyDescriptorCollection; var selServ = host.Services.GetService (typeof (ISelectionService)) as ISelectionService; selServ.SetSelectedComponents (new IComponent[] {selected}); } } }
static void Main(string[] args) { #if false // X-DOM Overview 文档对象模型 概述 { XElement config = XElement.Parse( @"<configuration> <client enabled='true'> <timeout>30</timeout> </client> </configuration>"); foreach (XElement child in config.Elements()) { child.Name.Dump("Child element name"); } XElement client = config.Element("client"); bool enabled = (bool)client.Attribute("enabled"); // Read attribute enabled.Dump("enabled attribute"); client.Attribute("enabled").SetValue(!enabled); // Update attribute int timeout = (int)client.Element("timeout"); // Read element timeout.Dump("timeout element"); client.Element("timeout").SetValue(timeout * 2); // Update element client.Add(new XElement("retries", 3)); // Add new elememt } // Instantiation X-DOM 实例化 X-DOM { // 方法 添加 元素节点 节点值 属性 熟悉值 XElement lastName = new XElement("lastname", "Bloggs"); lastName.Add(new XComment("nice name")); XElement customer = new XElement("customer"); customer.Add(new XAttribute("id", 123)); customer.Add(new XElement("firstname", "Joe")); customer.Add(lastName); customer.Dump(); // Functional Construction 函数式构建 new XElement("customer", new XAttribute("id", 123), new XElement("firstname", "joe"), new XElement("lastname", "bloggs", new XComment("nice name") ) ); // Fucntional Construction from Database Query 为每个实体对象 创建 元素节点 NutshellEntities dataContext = new NutshellEntities(); new XElement("customers", from c in dataContext.Customer select new XElement("customer", new XAttribute("id", c.ID), new XElement("name", c.Name, new XComment("nice name")))); // Automatic Deep Cloing 自动深度克隆 var address = new XElement("address", new XElement("street", "Lawley St"), new XElement("town", "North Beach") ); var customer1 = new XElement("customer1", address); var customer2 = new XElement("customer2", address); customer1.Element("address").Element("street").Value = "Another St"; Console.WriteLine(customer2.Element("address").Element("street").Value); } #elif false // Navigating and Querying 导航查询 { // FirstNode LastNode and Nodes var bench = new XElement("bench", new XElement("toolbox", new XElement("handtool", "Hammer"), new XElement("handtool", "Rasp") ), new XElement("toolbox", new XElement("handtool", "Saw"), new XElement("powertool", "Nailgun") ), new XComment("Be careful with the nailgun") ); bench.FirstNode.Dump("FirstNode"); bench.LastNode.Dump("LastNode"); foreach (XNode node in bench.Nodes()) { Console.WriteLine(node.ToString(SaveOptions.DisableFormatting) + "."); // toolbox = HammerRasp } // toolbox = SawNailgun // Enumerating Elements 检索元素 foreach (XElement e in bench.Elements()) { Console.WriteLine(e.Name + "=" + e.Value); } // Quering Elements IEnumerable <string> toolboxWithNailgun = from toolbox in bench.Elements() where toolbox.Elements().Any(tool => tool.Value == "Nailgun") select toolbox.Value; var handTools = from toolbox in bench.Elements() from tool in toolbox.Elements() where tool.Name == "handtool" select tool.Value; int toolboxCount = bench.Elements("toolbox").Count(); var handTools2 = from tool in bench.Elements("toolbox").Elements("handtool") select tool.Value.ToUpper(); toolboxWithNailgun.Dump("The toolbox with the nailgun"); handTools.Dump("The hand tools in all toolboxes"); toolboxCount.Dump("Number of toolboxes"); handTools2.Dump("The hand tools in all toolboxes"); XElement singnal = bench.Element("toolbox").Element("xyc"); string nullableValue = singnal?.Value; // Quering Elements - Recursive // Descendants 返回所有叶子节点 并 可筛选 // DescendantNodes 返回包含所有的父节点 和 叶子节点 bench.Descendants("handtool").Count().Dump(); foreach (XNode node in bench.DescendantNodes()) { Console.WriteLine(node.ToString(SaveOptions.DisableFormatting)); } ( from c in bench.DescendantNodes().OfType <XComment>() where c.Value.Contains("careful") orderby c.Value select c.Value ).Dump("Comments anywhere in the X-DOM containing the word 'careful'"); } #elif false // Updating X-DOM 更新 X-DOM { // SetValue Replaces Child Content XElement settings = new XElement("settings", new XElement("timeout", 30)); settings.Dump("Original XML"); settings.SetValue("blah"); settings.Dump("Notice the timeout node has disappeared"); // SetElementValue 添加或覆盖 XElement settings2 = new XElement("settings"); settings.SetElementValue("timeout", 30); settings2.Dump("Adds child element"); settings.SetElementValue("timeout", 60); settings2.Dump("Updates child element"); // AddAfterSelf Remove Replace XElement items = new XElement("items", new XElement("one"), new XElement("three") ); items.Dump("Original XML"); items.FirstNode.AddAfterSelf(new XElement("two")); items.Dump("After calling items.FirstNode.AddAfterSelf"); items.FirstNode.ReplaceWith(new XComment("One was here")); items.Dump("After calling ReplaceWith"); XElement contacts = XElement.Parse(@" <contacts> <customer name='Mary'/> <customer name='Chris' archived='true'/> <supplier name='Susan'> <phone archived='true'>012345678<!--confidential--></phone> </supplier> </contacts>"); contacts.Dump("Before"); contacts.Elements("customer").Remove(); contacts.Dump("After"); contacts.Dump("Before"); contacts.Elements() // <customer name='Chris' archived='true'/> 被移除 .Where(e1 => (bool?)e1.Attribute("archived") == true) .Remove(); contacts.Dump("After"); contacts.Dump("Before"); contacts.Descendants() // 所有 属性archived的值为 true 的元素被移除 .Where(e2 => (bool?)e2.Attribute("archived") == true) .Remove(); contacts.Dump("After"); contacts.Dump("Before"); contacts.Elements() .Where(e3 => e3.DescendantNodes().OfType <XComment>().Any(c => c.Value == "confidential")) .Remove(); contacts.Dump("After"); contacts.Descendants().OfType <XComment>().Remove(); // 移除整个树🌳中的注释节点 contacts.DescendantNodes().OfType <XComment>().Remove(); // Get and Set Value var e = new XElement("date", DateTime.Now); e.SetValue(DateTime.Now.AddDays(1)); e.Value.Dump(); DateTime dt = (DateTime)e; XAttribute a = new XAttribute("resolution", 1.234); double res = (double)a; // Nullables 可空类型 int? timeout = (int?)e.Element("timeout"); double resolution = (double?)e.Attribute("resolution") ?? 1.0; var nullXe = new XElement("Empty"); try { int timeout1 = (int)nullXe.Element("timeout"); } catch (Exception ex) { ex.Message.Dump("Element (\"timeout\") returns null so the result cannot be cast to int"); } int?timeout2 = (int?)nullXe.Element("timeout"); timeout2.Dump("Casting to a nullable type solve this problem"); var data = XElement.Parse(@" <data> <customer id='1' name='Mary' credit='100' /> <customer id='2' name='John' credit='150' /> <customer id='3' name='Anne' /> </data>"); IEnumerable <string> query = from cust in data.Elements() where (int?)cust.Attribute("credit") > 100 // 属性值转换为 nullable,避免 NullReferenceException select cust.Attribute("name").Value; query.Dump(); IEnumerable <string> query2 = from cust in data.Elements() where cust.Attributes("credit").Any() && (int)cust.Attribute("credit") > 100 select cust.Attribute("name").Value; query2.Dump(); // XText 与 XElement 混合内容 XElement summary = new XElement("summary", new XText("An XAttribute is "), new XElement("bold", "not"), new XText(" an XNode") ); summary.Dump(); // An XAttribute is not an XNode { var e1 = new XElement("test", "Hello"); e1.Add("World"); var e2 = new XElement("test", "Hello", "World"); var e3 = new XElement("test", new XText("Hello"), new XText("World")); e1.Dump(); e2.Dump(); e3.Dump(); // 均输出 Hello World e1.Nodes().Count().Dump("Number of children in e1"); // 均为 2 e2.Nodes().Count().Dump("Number of children in e2"); e3.Nodes().Count().Dump("Number of children in e3"); } } #elif false // Documents and Declarations 文档和声明 { // Building an XHTML document 建立一个XHTML 文档{ { var styleInstruction = new XProcessingInstruction( "xml-stylesheet", "href='styles.css' type='text/css'"); var docType = new XDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", null); XNamespace ns = "http://www.w3.org/1999/xhtml"; var root = new XElement(ns + "html", new XElement(ns + "head", new XElement(ns + "title", "An XHTML page")), new XElement(ns + "body", new XElement(ns + "h1", "This is a heading."), new XElement(ns + "p", "This is some content.")) ); var doc = new XDocument( new XDeclaration("1.0", "utf-8", "no"), new XComment("Reference a stylesheet"), styleInstruction, docType, root ); string tempPath = Path.Combine(Path.GetTempPath(), "sample.html"); doc.Save(tempPath); Process.Start(tempPath); // This will display the page in IE or FireFox File.ReadAllText(tempPath).Dump(); doc.Root.Name.LocalName.Dump("Root element's local name"); XElement bodyNode = doc.Root.Element(ns + "body"); (bodyNode.Document == doc).Dump("bodyNode.Document == doc"); (doc.Root.Parent == null).Dump("doc.Root.Parent is null"); foreach (XNode node in doc.Nodes()) { Console.Write(node.Parent == null); } } // Declarations 声明 { var doc = new XDocument( new XDeclaration("1.0", "utf-16", "yes"), new XElement("test", "data") ); string tempPath = Path.Combine(Path.GetTempPath(), "test.xml"); doc.Save(tempPath); File.ReadAllText(tempPath).Dump(); var output = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true }; using (XmlWriter xw = XmlWriter.Create(output, settings)) doc.Save(xw); output.ToString().Dump("Notice the encoding is utf-16 and not utf-8"); } // Names and Namespaces 名称和命名空间 { // 直接使用 {} new XElement("{http://domain.com/xmlspace}customer", "Bloggs"); // 使用 XName 和 XNamespace XName localName = "customer"; localName.Dump("localName"); XName fullName1 = "{http://domain.com/xmlspace}customer"; fullName1.Dump("fullname1"); XNamespace ns = "http://domain.com/xmlspace"; XName fullName2 = ns + "customer"; fullName2.Dump("fullname2 - same result, but cleaner and more efficient"); var data = new XElement(ns + "data", new XAttribute(ns + "id", 123) ); data.Dump(); XElement x = data.Element(ns + "customer"); // OK XElement y = data.Element("customer"); // null // 为每一个元素分配命名空间 var data2 = new XElement(ns + "data", new XElement("customer", "Bloggs"), new XElement("purchase", "Bicycle") ); data.Dump("Before"); foreach (XElement e in data2.DescendantsAndSelf()) { if (e.Name.Namespace == "") { e.Name = ns + e.Name.LocalName; } } data.Dump("After"); // Prefixes 前缀 XNamespace ns1 = "http://domain.com/space1"; XNamespace ns2 = "http://domain.com/space2"; var mix = new XElement(ns1 + "data", new XElement(ns2 + "element", "value"), new XElement(ns2 + "element", "value"), new XElement(ns2 + "element", "value") ); mix.Dump("Without prefixes"); mix.SetAttributeValue(XNamespace.Xmlns + "ns1", ns1); mix.SetAttributeValue(XNamespace.Xmlns + "ns2", ns2); mix.Dump("With prefixes"); XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; var nil = new XAttribute(xsi + "nil", true); var cust = new XElement("customers", new XAttribute(XNamespace.Xmlns + "xsi", xsi), new XElement("customer", new XElement("lastname", "Bloggs"), new XElement("dob", nil), new XElement("credit", nil) ) ); cust.Dump(); } } #elif true // Annotations 注解 { #if true { XElement e = new XElement("test"); e.AddAnnotation("Hello"); e.Annotation <string>().Dump("String annotations"); e.RemoveAnnotations <string>(); e.Annotation <string>().Dump("String annotations"); } { XElement e = new XElement("test"); e.AddAnnotation(new Customer { ID = 13, Name = "Linaggan", Purchase = null }); e.Annotations <Customer>().First().Name.Dump(); e.RemoveAnnotations <Customer>(); e.Annotations <Customer>().Count(); } #endif } // Projecting into an X-DOM 将数据映射到X-DOM中 { var customers = new XElement("Customers", new XElement("Customer", new XAttribute("id", 13), new XElement("name", "Lianggan13"), new XElement("buys", 3))); NutshellEntities dataContext = new NutshellEntities(); var customers2 = new XElement("Customers", from c in dataContext.Customer.ToList() // 注:此处 要有 ToList() select new XElement("Customer", new XAttribute("id", c.ID), new XElement("name", c.Name), new XElement("buys", (c.Purchase.Count)))); { IEnumerable <XElement> queryxe = from c in dataContext.Customer select new XElement("Customer", new XAttribute("id", c.ID), new XElement("name", c.Name), new XElement("buys", c.Purchase.Count)); //var customers3 = new XElement("Customers", queryxe.AsQueryable()); } { // 在查询的客户信息中还包含客户最近的高价购买记录的详细信息 (排除空元素) IEnumerable <XElement> queryxe2 = from c in dataContext.Customer let lastBigBuy = ( from p in c.Purchase where p.Price > 1000 orderby p.Date descending select p ).FirstOrDefault() select new XElement("Customer", new XAttribute("id", c.ID), new XElement("name", c.Name), new XElement("buys", c.Purchase.Count), lastBigBuy == null ? null : // 客户没有lastBigBuy时,返回null,其内容自动被忽略 new XElement("LastBigBuy", new XElement("Description", lastBigBuy.Description), new XElement("Price", lastBigBuy.Price) )); // var customers4 = new XElement("Customers", queryxe2); } // Transfer X-DOM 转换 X-DOM // 获取项目文件中的文件信息 XElement project = XElement.Parse(@" <Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform> <ProductVersion>9.0.11209</ProductVersion> </PropertyGroup> <ItemGroup> <Compile Include=""ObjectGraph.cs"" /> <Compile Include=""Program.cs"" /> <Compile Include=""Properties\AssemblyInfo.cs"" /> <Compile Include=""Tests\Aggregation.cs"" /> <Compile Include=""Tests\Advanced\RecursiveXml.cs"" /> </ItemGroup> </Project>"); XNamespace ns = project.Name.Namespace; var queryFiles = new XElement("ProjectReport", from complieItem in project.Elements(ns + "ItemGroup").Elements(ns + "Compile") let include = complieItem.Attribute("Include") where include != null select new XElement("File", include.Value)); queryFiles.Save(Directory.GetCurrentDirectory() + "\\" + "Files.xml"); var paths = from complieItem in project.Elements(ns + "ItemGroup").Elements(ns + "Compile") let include = complieItem.Attribute("Include") where include != null select include.Value; var queryFoderFiles = new XElement("ProjectReport", ExpandPaths(paths)); queryFoderFiles.Save(Directory.GetCurrentDirectory() + "\\" + "FoderFiles .xml"); } #endif Console.ReadKey(); }
protected async Task AddHtmlAttributeCompletionData (CompletionDataList list, HtmlSchema schema, XName tagName, Dictionary<string, string> existingAtts, CancellationToken token) { //add atts only if they're not aready in the tag foreach (var datum in await schema.CompletionProvider.GetAttributeCompletionData (tagName.FullName.ToLower (), token)) if (existingAtts == null || !existingAtts.ContainsKey (datum.DisplayText)) list.Add (datum); }
public XElement (DocumentLocation start, XName name) : this (start) { this.Name = name; }
/// <summary> /// Initializes a new instance of the <see cref="LicenseAttributes"/> class. /// </summary> internal LicenseAttributes(XElement xmlData, XName childName) { this.xmlData = xmlData ?? new XElement("null"); this.childName = childName; }
internal protected virtual void Write(IPropertySet pset) { pset.SetPropertyOrder("DebugSymbols", "DebugType", "Optimize", "OutputPath", "DefineConstants", "ErrorReport"); FilePath defaultImPath; if (!string.IsNullOrEmpty(Platform)) { defaultImPath = ParentItem.BaseIntermediateOutputPath.Combine(Platform, Name); } else { defaultImPath = ParentItem.BaseIntermediateOutputPath.Combine(Name); } pset.SetValue("IntermediateOutputPath", IntermediateOutputDirectory, defaultImPath); // xbuild returns 'false' for DebugSymbols if DebugType==none, no matter which value is defined // in the project file. Here we avoid overwriting the value if it has not changed. if (debugType != "none" || !debugTypeWasNone) { pset.SetValue("DebugSymbols", debugMode, false); } pset.SetValue("OutputPath", outputDirectory, defaultValue: new FilePath("." + Path.DirectorySeparatorChar)); pset.SetValue("ConsolePause", pauseConsoleOutput, true); if (writeExternalConsoleLowercase) { pset.SetValue("Externalconsole", externalConsole, false); } else { pset.SetValue("ExternalConsole", externalConsole, false); } pset.SetValue("Commandlineparameters", commandLineParameters, ""); pset.SetValue("RunWithWarnings", runWithWarnings, true); if (debugType != "none" || !debugTypeReadAsEmpty) { pset.SetValue("DebugType", debugType, ""); } // Save the env vars only if the dictionary has changed. if (loadedEnvironmentVariables == null || loadedEnvironmentVariables.Count != environmentVariables.Count || loadedEnvironmentVariables.Any(e => !environmentVariables.ContainsKey(e.Key) || environmentVariables[e.Key] != e.Value)) { if (environmentVariables.Count > 0) { string xmlns = GetProjectNamespace(); XElement e = new XElement(XName.Get("EnvironmentVariables", xmlns)); foreach (var v in environmentVariables) { var val = new XElement(XName.Get("Variable", xmlns)); val.SetAttributeValue("name", v.Key); val.SetAttributeValue("value", v.Value); e.Add(val); } pset.SetValue("EnvironmentVariables", e.ToString(SaveOptions.DisableFormatting)); } else { pset.RemoveProperty("EnvironmentVariables"); } loadedEnvironmentVariables = new Dictionary <string, string> (environmentVariables); } pset.WriteObjectProperties(this, GetType(), true); }
/// <summary> /// Sets IP Forwarding on a network interface. /// </summary> /// <param name='serviceName'> /// Required. /// </param> /// <param name='deploymentName'> /// Required. /// </param> /// <param name='roleName'> /// Required. /// </param> /// <param name='networkInterfaceName'> /// Required. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Set IP Forwarding on network /// interface operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task <OperationStatusResponse> BeginSettingIPForwardingOnNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, IPForwardingSetParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (roleName == null) { throw new ArgumentNullException("roleName"); } if (networkInterfaceName == null) { throw new ArgumentNullException("networkInterfaceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.State == null) { throw new ArgumentNullException("parameters.State"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("roleName", roleName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginSettingIPForwardingOnNetworkInterfaceAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/roles/"; url = url + Uri.EscapeDataString(roleName); url = url + "/networkinterfaces/"; url = url + Uri.EscapeDataString(networkInterfaceName); url = url + "/ipforwarding"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement iPForwardingElement = new XElement(XName.Get("IPForwarding", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(iPForwardingElement); XElement stateElement = new XElement(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); stateElement.Value = parameters.State; iPForwardingElement.Add(stateElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public virtual SelectRecipientDataResponse Decode(string xmlResponse) { if (xmlResponse == null) { throw new ArgumentNullException("xmlResponse"); } var xml = XElement.Parse(xmlResponse); if (xml.Name != "Envelope") { throw new ArgumentException("xmlResponse must have a root <Envelope> node."); } var bodyXML = xml.Element(XName.Get("Body")); bool success = Convert.ToBoolean(bodyXML.Element(XName.Get("RESULT")).Element(XName.Get("SUCCESS")).Value); var error = bodyXML.Element(XName.Get("Fault")); string errorString = "", email = "", recipientId = "", organizationId = ""; List <KeyValuePair <string, string> > parsedCols = new List <KeyValuePair <string, string> >(); if (error != null) { errorString = error.Element(XName.Get("FaultString")).Value; } else { var resultBody = bodyXML.Element(XName.Get("RESULT")); email = resultBody.Element(XName.Get("EMAIL")).Value; recipientId = resultBody.Element(XName.Get("RecipientId")).Value; organizationId = resultBody.Element(XName.Get("ORGANIZATION_ID")).Value; var columns = resultBody.Element(XName.Get("COLUMNS")).Nodes(); foreach (var column in columns) { try { var colName = (column as XElement).Element("NAME").Value; var colValue = (column as XElement).Element("VALUE").Value; parsedCols.Add(new KeyValuePair <string, string>(colName, colValue)); } catch { // Do Nothing ? } } //visitorAssociation = bodyXML.Element(XName.Get("RESULT")).Element(XName.Get("VISITOR_ASSOCIATION")).Value; } return(new SelectRecipientDataResponse() { RawResponse = xmlResponse, Success = success, ErrorString = errorString, RecipientId = recipientId, OrganizationId = organizationId, Email = email, Columns = parsedCols }); }
public XAttribute (DocumentLocation start, XName name, string value) : base (start) { this.Name = name; this.Value = value; }
internal static PackagePart CreateOrGetSettingsPart(Package package) { PackagePart settingsPart; Uri settingsUri = new Uri("/word/settings.xml", UriKind.Relative); if (!package.PartExists(settingsUri)) { settingsPart = package.CreatePart(settingsUri, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", CompressionOption.Maximum); PackagePart mainDocumentPart = package.GetParts().Where ( p => p.ContentType.Equals ( "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", StringComparison.CurrentCultureIgnoreCase ) ).Single(); mainDocumentPart.CreateRelationship(settingsUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings"); XDocument settings = XDocument.Parse (@"<?xml version='1.0' encoding='utf-8' standalone='yes'?> <w:settings xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:sl='http://schemas.openxmlformats.org/schemaLibrary/2006/main'> <w:zoom w:percent='100' /> <w:defaultTabStop w:val='720' /> <w:characterSpacingControl w:val='doNotCompress' /> <w:compat /> <w:rsids> <w:rsidRoot w:val='00217F62' /> <w:rsid w:val='001915A3' /> <w:rsid w:val='00217F62' /> <w:rsid w:val='00A906D8' /> <w:rsid w:val='00AB5A74' /> <w:rsid w:val='00F071AE' /> </w:rsids> <m:mathPr> <m:mathFont m:val='Cambria Math' /> <m:brkBin m:val='before' /> <m:brkBinSub m:val='--' /> <m:smallFrac m:val='off' /> <m:dispDef /> <m:lMargin m:val='0' /> <m:rMargin m:val='0' /> <m:defJc m:val='centerGroup' /> <m:wrapIndent m:val='1440' /> <m:intLim m:val='subSup' /> <m:naryLim m:val='undOvr' /> </m:mathPr> <w:themeFontLang w:val='en-IE' w:bidi='ar-SA' /> <w:clrSchemeMapping w:bg1='light1' w:t1='dark1' w:bg2='light2' w:t2='dark2' w:accent1='accent1' w:accent2='accent2' w:accent3='accent3' w:accent4='accent4' w:accent5='accent5' w:accent6='accent6' w:hyperlink='hyperlink' w:followedHyperlink='followedHyperlink' /> <w:shapeDefaults> <o:shapedefaults v:ext='edit' spidmax='2050' /> <o:shapelayout v:ext='edit'> <o:idmap v:ext='edit' data='1' /> </o:shapelayout> </w:shapeDefaults> <w:decimalSymbol w:val='.' /> <w:listSeparator w:val=',' /> </w:settings>" ); XElement themeFontLang = settings.Root.Element(XName.Get("themeFontLang", DocX.w.NamespaceName)); themeFontLang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture); // Save the settings document. using (TextWriter tw = new StreamWriter(settingsPart.GetStream())) settings.Save(tw); } else { settingsPart = package.GetPart(settingsUri); } return(settingsPart); }
protected static void AddHtmlTagCompletionData (CompletionDataList list, HtmlSchema schema, XName parentName) { if (schema == null) return; if (parentName.IsValid) { list.AddRange (schema.CompletionProvider.GetChildElementCompletionData (parentName.FullName)); } else { list.AddRange (schema.CompletionProvider.GetElementCompletionData ()); } }
/// <summary> /// If this document does not contain a /word/styles.xml add the default one generated by Microsoft Word. /// </summary> /// <param name="package"></param> /// <param name="mainDocumentPart"></param> /// <returns></returns> internal static XDocument AddDefaultStylesXml(Package package) { XDocument stylesDoc; // Create the main document part for this package PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum); stylesDoc = HelperFunctions.DecompressXMLResource("Novacode.Resources.default_styles.xml.gz"); XElement lang = stylesDoc.Root.Element(XName.Get("docDefaults", DocX.w.NamespaceName)).Element(XName.Get("rPrDefault", DocX.w.NamespaceName)).Element(XName.Get("rPr", DocX.w.NamespaceName)).Element(XName.Get("lang", DocX.w.NamespaceName)); lang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture); // Save /word/styles.xml using (TextWriter tw = new StreamWriter(word_styles.GetStream(FileMode.Create, FileAccess.Write))) stylesDoc.Save(tw, SaveOptions.None); PackagePart mainDocumentPart = package.GetParts().Where ( p => p.ContentType.Equals ( "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", StringComparison.CurrentCultureIgnoreCase ) ).Single(); mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"); return(stylesDoc); }
protected void AddHtmlAttributeValueCompletionData (CompletionDataList list, HtmlSchema schema, XName tagName, XName attributeName) { list.AddRange (schema.CompletionProvider.GetAttributeValueCompletionData (tagName.FullName, attributeName.FullName)); }
/// <summary> /// </summary> /// <param name="value">The date time.</param> /// <param name="name">The name.</param> /// <returns></returns> public static XElement ToXElementDateTime(this DateTime value, XName name) { if (value.Kind != DateTimeKind.Utc) { value = value.ToUniversalTime(); } return new XElement(name, value.ToString(Formats.XmlDateTime)); }
protected override void ShallowCopyFrom (XObject copyFrom) { base.ShallowCopyFrom (copyFrom); WebFormsDirective copyFromEl = (WebFormsDirective)copyFrom; name = copyFromEl.name; //XName is immutable value type }
/// <summary> /// Gets an array of <see cref="XElement"/> matching the specified <paramref name="name"/> and parses each element using <paramref name="callback"/>. /// </summary> /// <typeparam name="T">The type of the items to be returned.</typeparam> /// <param name="element">The parent <see cref="XElement"/>.</param> /// <param name="name">An instance of <see cref="XName"/> identifying the elements.</param> /// <param name="callback">A callback function for parsing the element.</param> /// <returns>The elements as parsed by the specified <paramref name="callback"/>.</returns> public static T[] GetElements <T>(this XElement element, XName name, Func <XElement, T> callback) { return(element?.Elements(name).Select(callback).ToArray() ?? new T[0]); }