public static XAttribute TryGetAttribute(this XElement element, XName attributeName) { var attribute = element.Attribute(attributeName) ?? element.Attributes().SingleOrDefault( a => a.Name.ToString().Homogenize() == attributeName.ToString().Homogenize()); return attribute ?? new XAttribute(attributeName, string.Empty); }
public static void ShouldEqual(this XName actual, XName expected) { if (actual.ToString() != expected.ToString()) { throw new EqualException(expected, actual); } }
public static string TryGetAttributeValue(this XElement element, XName attributeName) { var attribute = element.Attribute(attributeName) ?? element.Attributes().SingleOrDefault( a => a.Name.ToString().Homogenize() == attributeName.ToString().Homogenize()); return attribute == null ? null : attribute.Value; }
/// <summary> /// Adds a new attribute to the element /// Does not permit modification of an existing attribute. /// Does not add empty or null attributes or values. /// </summary> /// <param name="element">The element to add the attribute to</param> /// <param name="attribute">The attribute to add</param> /// <param name="value">the value of the attribute to add</param> /// <returns>The element passed in. (Permits fluent usage)</returns> internal static XElement AddAttribute(this XElement element, XName attribute, string value) { if (element == null) { return null; } // we quietly ignore attempts to add empty data or attributes. if (string.IsNullOrWhiteSpace(value) || attribute == null || string.IsNullOrWhiteSpace(attribute.ToString())) { return element; } // Swidtag attributes can be added but not changed -- if it already exists, that's not permitted. var current = element.GetAttribute(attribute); if (!string.IsNullOrWhiteSpace(current)) { if (value != current) { throw new Exception("Attempt to change Attribute '{0}' present in element '{1}'".format(attribute.LocalName, element.Name.LocalName)); } // if the value was set to that already, don't worry about it. return element; } element.SetAttributeValue(attribute, value); return element; }
/// <summary> /// Gets the attribute value for a given element. /// </summary> /// <param name="element">the element that possesses the attribute</param> /// <param name="attribute">the attribute to find</param> /// <returns>the string value of the element. Returns null if the element or attribute does not exist.</returns> internal static string GetAttribute(this XElement element, XName attribute) { if (element == null || attribute == null || string.IsNullOrWhiteSpace(attribute.ToString())) { return null; } var a = element.Attribute(attribute); return a == null ? null : a.Value; }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="name"></param> public XsltContextFunctionAttribute(XName name) : base(typeof(IXsltContextFunction)) { Contract.Requires<ArgumentNullException>(name != null); this.expandedName = name.ToString(); }
public static string FormatName(this XElement element, XName name) { if (name.Namespace == null) return name.LocalName; if (name.Namespace == element.GetDefaultNamespace()) return name.LocalName; string prefix = element.GetPrefixOfNamespace(name.Namespace); if (!string.IsNullOrEmpty(prefix)) return prefix + ":" + name.LocalName; return name.ToString(); }
private static bool AreEqual(XName left, XName right) { if (left == null && right == null) { return true; } if (left == null || right == null) { return false; } return left.ToString() == right.ToString(); }
/// <summary> /// Returns a collection of the descendant elements for this document or element, in document order. Optionally ignores case. /// </summary> /// <param name="element"></param> /// <param name="name"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public static IEnumerable<XElement> Descendants( this XElement element, XName name, bool ignoreCase ) { var collection = element.Descendants(); if ( ignoreCase ) { collection = collection.Where( p => p.Name.ToString().ToLower() == name.ToString().ToLower() ); } return collection; }
/// <summary> /// Returns a filtered collection of the attributes of every element in the source /// collection. Only elements that have a matching <see cref="System.Xml.Linq.XName"/> are /// included in the collection. /// </summary> /// <param name="elements"></param> /// <param name="name"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public static IEnumerable<XAttribute> Attributes( this IEnumerable<XElement> elements, XName name, bool ignoreCase ) { if ( ignoreCase ) { return elements.Attributes().Where( p => p.Name.ToString().ToLower() == name.ToString().ToLower() ); } else { return elements.Attributes( name ); } }
/// <summary> /// Returns the <see cref="System.Xml.Linq.XAttribute"/> of this <see cref="System.Xml.Linq.XElement"/> that /// has the specified <see cref="System.Xml.Linq.XName"/>, optionally ignoring case. /// </summary> /// <param name="element"></param> /// <param name="name"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public static XAttribute Attribute( this XElement element, XName name, bool ignoreCase ) { if ( ignoreCase ) { return element.Attributes().Where( p => p.Name.ToString().ToLower() == name.ToString().ToLower() ).FirstOrDefault(); } else { return element.Attribute( name ); } }
public static XElement Element(this XElement element, XName name, bool ignoreCase) { var el = element.Element(name); if (el != null) return el; if (!ignoreCase) return null; var elements = element.Elements().Where(e => e.Name.LocalName.ToString().ToLowerInvariant() == name.ToString().ToLowerInvariant()); return elements.Count() == 0 ? null : elements.First(); }
// ignore case if set public static XAttribute Attribute( this XElement element, XName name, bool ignoreCase ) { var at = element.Attribute( name ); if (at != null) return at; if (!ignoreCase) return null; var ats = element.Attributes().Where( e => e.Name.LocalName.ToString().ToLowerInvariant() == name.ToString().ToLowerInvariant() ); return ats.Count() == 0 ? null : ats.First(); }
/// <summary> /// Gets the attribute value for a given element. /// </summary> /// <param name="element">the element that possesses the attribute</param> /// <param name="attribute">the attribute to find</param> /// <returns>the string value of the element. Returns null if the element or attribute does not exist.</returns> internal static string GetAttribute(this XElement element, XName attribute) { if (element == null || attribute == null || string.IsNullOrWhiteSpace(attribute.ToString())) { return null; } XAttribute result; // no name space, just check local name if (string.IsNullOrWhiteSpace(attribute.Namespace.NamespaceName)) { result = element.Attributes().Where(attr => attr != null && string.Equals(attr.Name.LocalName, attribute.LocalName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); } else { result = element.Attribute(attribute); } return result == null ? null : result.Value; }
/// <summary> /// Adds a new attribute to the element /// Does not permit modification of an existing attribute. /// Does not add empty or null attributes or values. /// </summary> /// <param name="element">The element to add the attribute to</param> /// <param name="attribute">The attribute to add</param> /// <param name="value">the value of the attribute to add</param> /// <returns>The element passed in. (Permits fluent usage)</returns> internal static XElement SetAttribute(this XElement element, XName attribute, string value) { if (element == null) { return null; } // we quietly ignore attempts to add empty data or attributes. if (attribute == null || string.IsNullOrWhiteSpace(attribute.ToString())) { return element; } if (element.Name.Namespace == attribute.Namespace || string.IsNullOrWhiteSpace(attribute.NamespaceName) || attribute.Namespace == Namespace.XmlNs || attribute.Namespace == Namespace.Xml) { element.SetAttributeValue(attribute.LocalName, value); } else { element.EnsureNamespaceAtTop(attribute.Namespace); element.SetAttributeValue(attribute, value); } return element; }
/// <summary> /// Retreives the collection value. /// </summary> /// <param name="colType">Type of the collection to be retrieved.</param> /// <param name="xelemValue">The value of xml element.</param> /// <param name="memberAlias">The member's alias, used only in exception titles.</param> /// <param name="colAttrInstance">The collection attribute instance.</param> /// <returns></returns> private object DeserializeCollectionValue(Type colType, XElement xelemValue, XName memberAlias, YAXCollectionAttribute colAttrInstance) { var lst = new List<object>(); // this will hold the actual data items Type itemType = ReflectionUtils.GetCollectionItemType(colType); if (ReflectionUtils.IsBasicType(itemType) && colAttrInstance != null && colAttrInstance.SerializationType == YAXCollectionSerializationTypes.Serially) { // What if the collection was serialized serially char[] seps = colAttrInstance.SeparateBy.ToCharArray(); // can white space characters be added to the separators? if (colAttrInstance == null || colAttrInstance.IsWhiteSpaceSeparator) { seps = seps.Union(new [] { ' ', '\t', '\r', '\n' }).ToArray(); } string elemValue = xelemValue.Value; string[] items = elemValue.Split(seps, StringSplitOptions.RemoveEmptyEntries); foreach (string wordItem in items) { try { lst.Add(ReflectionUtils.ConvertBasicType(wordItem, itemType)); } catch { OnExceptionOccurred(new YAXBadlyFormedInput(memberAlias.ToString(), elemValue), m_defaultExceptionType); } } } else { //What if the collection was serialized recursive bool isPrimitive = false; if (ReflectionUtils.IsBasicType(itemType)) { isPrimitive = true; } XName eachElemName = null; if (colAttrInstance != null && colAttrInstance.EachElementName != null) { eachElemName = StringUtils.RefineSingleElement(colAttrInstance.EachElementName); eachElemName = eachElemName.OverrideNsIfEmpty(memberAlias.Namespace.IfEmptyThen(TypeNamespace).IfEmptyThenNone()); } var elemsToSearch = eachElemName == null ? xelemValue.Elements() : xelemValue.Elements(eachElemName); foreach (XElement childElem in elemsToSearch) { Type curElementType = itemType; bool curElementIsPrimitive = isPrimitive; XAttribute realTypeAttribute = childElem.Attribute_NamespaceSafe(m_yaxLibNamespaceUri + m_trueTypeAttrName); if (realTypeAttribute != null) { Type theRealType = ReflectionUtils.GetTypeByName(realTypeAttribute.Value); if (theRealType != null) { curElementType = theRealType; curElementIsPrimitive = ReflectionUtils.IsBasicType(curElementType); } } // TODO: check if curElementType is derived or is the same is itemType, for speed concerns perform this check only when elementName is null if (eachElemName == null && (curElementType == typeof(object) || !ReflectionUtils.IsTypeEqualOrInheritedFromType(curElementType, itemType))) continue; if (curElementIsPrimitive) { try { lst.Add(ReflectionUtils.ConvertBasicType(childElem.Value, curElementType)); } catch { this.OnExceptionOccurred(new YAXBadlyFormedInput(childElem.Name.ToString(), childElem.Value), m_defaultExceptionType); } } else { var ser = new YAXSerializer(curElementType, m_exceptionPolicy, m_defaultExceptionType, m_serializationOption); ser.SetNamespaceToOverrideEmptyNamespace( memberAlias.Namespace. IfEmptyThen(this.TypeNamespace). IfEmptyThenNone()); lst.Add(ser.DeserializeBase(childElem)); m_parsingErrors.AddRange(ser.ParsingErrors); } } } // end of else if // Now what should I do with the filled list: lst Type dicKeyType, dicValueType; if (ReflectionUtils.IsArray(colType)) { XAttribute dimsAttr = xelemValue.Attribute_NamespaceSafe(m_yaxLibNamespaceUri + m_dimsAttrName); int[] dims = new int[0]; if (dimsAttr != null) { dims = StringUtils.ParseArrayDimsString(dimsAttr.Value); } Array arrayInstance = null; if (dims.Length > 0) { int[] lowerBounds = new int[dims.Length]; // an array of zeros arrayInstance = Array.CreateInstance(itemType, dims, lowerBounds); // create the array int count = Math.Min(arrayInstance.Length, lst.Count); // now fill the array for (int i = 0; i < count; i++) { int[] inds = GetArrayDimentionalIndex(i, dims); try { arrayInstance.SetValue(lst[i], inds); } catch { OnExceptionOccurred( new YAXCannotAddObjectToCollection(memberAlias.ToString(), lst[i]), this.m_defaultExceptionType); } } } else { arrayInstance = Array.CreateInstance(itemType, lst.Count); // create the array int count = Math.Min(arrayInstance.Length, lst.Count); // now fill the array for (int i = 0; i < count; i++) { try { arrayInstance.SetValue(lst[i], i); } catch { OnExceptionOccurred( new YAXCannotAddObjectToCollection(memberAlias.ToString(), lst[i]), this.m_defaultExceptionType); } } } return arrayInstance; } else if (ReflectionUtils.IsIDictionary(colType, out dicKeyType, out dicValueType)) { //The collection is a Dictionary object dic = colType.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, new object[0]); foreach (var lstItem in lst) { object key = itemType.GetProperty("Key").GetValue(lstItem, null); object value = itemType.GetProperty("Value").GetValue(lstItem, null); try { colType.InvokeMember("Add", BindingFlags.InvokeMethod, null, dic, new object[] { key, value }); } catch { this.OnExceptionOccurred(new YAXCannotAddObjectToCollection(memberAlias.ToString(), lstItem), this.m_defaultExceptionType); } } return dic; } else if (ReflectionUtils.IsNonGenericIDictionary(colType)) { object col = colType.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, new object[0]); foreach (var lstItem in lst) { object key = lstItem.GetType().GetProperty("Key", BindingFlags.Instance | BindingFlags.Public).GetValue(lstItem, null); object value = lstItem.GetType().GetProperty("Value", BindingFlags.Instance | BindingFlags.Public).GetValue(lstItem, null); try { colType.InvokeMember("Add", BindingFlags.InvokeMethod, null, col, new object[] { key, value }); } catch { this.OnExceptionOccurred(new YAXCannotAddObjectToCollection(memberAlias.ToString(), lstItem), this.m_defaultExceptionType); } } return col; } else if (ReflectionUtils.IsTypeEqualOrInheritedFromType(colType, typeof(BitArray))) { var bArray = new bool[lst.Count]; for (int i = 0; i < bArray.Length; i++) { try { bArray[i] = (bool)lst[i]; } catch { } } object col = colType.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, new object[] { bArray }); return col; } else if (ReflectionUtils.IsTypeEqualOrInheritedFromType(colType, typeof(Stack)) || ReflectionUtils.IsTypeEqualOrInheritedFromType(colType, typeof(Stack<>))) { object col = colType.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, new object[0]); const string additionMethodName = "Push"; for (int i = lst.Count - 1; i >= 0; i--) // the loop must be from end to front { try { colType.InvokeMember(additionMethodName, BindingFlags.InvokeMethod, null, col, new object[] { lst[i] }); } catch { this.OnExceptionOccurred(new YAXCannotAddObjectToCollection(memberAlias.ToString(), lst[i]), this.m_defaultExceptionType); } } return col; } else if (ReflectionUtils.IsIEnumerable(colType)) { object col; try { col = colType.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, new object[0]); } catch { return lst; } string additionMethodName = "Add"; if (ReflectionUtils.IsTypeEqualOrInheritedFromType(colType, typeof(Queue)) || ReflectionUtils.IsTypeEqualOrInheritedFromType(colType, typeof(Queue<>))) { additionMethodName = "Enqueue"; } else if (ReflectionUtils.IsTypeEqualOrInheritedFromType(colType, typeof(LinkedList<>))) { additionMethodName = "AddLast"; } foreach (var lstItem in lst) { try { colType.InvokeMember(additionMethodName, BindingFlags.InvokeMethod, null, col, new object[] { lstItem }); } catch { this.OnExceptionOccurred(new YAXCannotAddObjectToCollection(memberAlias.ToString(), lstItem), this.m_defaultExceptionType); } } return col; } return null; }
/// <summary> /// Returns a filtered collection of the child elements of this element or document, /// in document order. Only elements that have a matching System.Xml.Linq.XName /// are included in the collection. /// </summary> /// <param name="name">The System.Xml.Linq.XName to match.</param> /// <returns> /// An System.Collections.Generic.IEnumerable`1 of System.Xml.Linq.XElement /// containing the children of the System.Xml.Linq.XContainer that have a matching /// System.Xml.Linq.XName, in document order. /// </returns> public IEnumerable <XElement> Elements(XName name) { //note: we couldn't use INTERNAL_jsnode.getElementsByTagName(name) because it returns the children of the children nodes as well (we only want the immediate children). //jsNodesForElement = CSHTML5.Interop.ExecuteJavaScript("Array.from($0.childNodes).filter(node => node.tagName == $1)", INTERNAL_jsnode, name.ToString()); //todo: if IE learns that => isn't a syntax error (which breaks the whole file) and can use it properly, use the line above instead of the following because it seems to be more efficient. object jsNodesForElement = CSHTML5.Interop.ExecuteJavaScript("Array.from($0.childNodes).filter(document.functionToCompareWordForFilter($1))", INTERNAL_jsnode, name.ToString()); #region explanation of the line above //note: normal use of filter: myArray.filter( function(node) { return testOnNode; }) //problem here: testOnNode depends on the name than node and we cannot put $1 in there because JSIL changes it to "this.$name", but "this" does not exist where "testOnNode" is. //solution: document.functionToCompareWordForFilter(name) returns A FUNCTION that takes a node and compares its tagName to name (see in cshtml5.js) // when calling document.functionToCompareWordForFilter, this.$name exists // and the created method that is used by filter can use it normally. //in short: the function created by document.functionToCompareWordForFilter provides the name, filter provides the node. #endregion if (XDocument.IsNullOrUndefined(jsNodesForElement)) //nothing fits the request. { yield break; } int i = 0; while (true) { object nodeAtI = CSHTML5.Interop.ExecuteJavaScript("$0[$1]", jsNodesForElement, i); if (CSHTML5.Interop.IsUndefined(nodeAtI)) { break; } //note: they have a tagName so they are definitely XElements. yield return((XElement)XDocument.GetXNodeFromJSNode(nodeAtI)); ++i; } yield break; }
/// <summary> /// Returns a filtered collection of the descendant elements for this document /// or element, in document order. Only elements that have a matching System.Xml.Linq.XName /// are included in the collection. /// </summary> /// <param name="name">The System.Xml.Linq.XName to match.</param> /// <returns> /// An System.Collections.Generic.IEnumerable`1 of System.Xml.Linq.XElement /// containing the descendant elements of the System.Xml.Linq.XContainer that /// match the specified System.Xml.Linq.XName. /// </returns> public IEnumerable <XElement> Descendants(XName name) { //this one is much simpler than Elements since we can call the getElementsByTagName method that does exactly what we want. object jsNodesForElement = CSHTML5.Interop.ExecuteJavaScript("$0.getElementsByTagName($1)", INTERNAL_jsnode, name.ToString()); if (XDocument.IsNullOrUndefined(jsNodesForElement)) //no children. { yield break; } int i = 0; while (true) { object nodeAtI = CSHTML5.Interop.ExecuteJavaScript("$0[$1]", jsNodesForElement, i); if (CSHTML5.Interop.IsUndefined(nodeAtI)) { break; } //note: they have a tagName so they are definitely XElements. yield return((XElement)XDocument.GetXNodeFromJSNode(nodeAtI)); ++i; } yield break; }
/// <summary> /// Enqueue a message to be delivered /// </summary> /// <param name="contract"> /// The contract. /// </param> /// <param name="operation"> /// The operation. /// </param> /// <param name="messageContent"> /// The message content. /// </param> public void EnqueueReceive(XName contract, string operation, object messageContent) { lock (this.queue) { this.queue.Enqueue(new StubMessage(StubMessageType.Receive) { Contract = contract.ToString(), Content = messageContent, Operation = operation }); } }
public CorrelationKey(IDictionary<string, string> keyData, XName scopeName, XNamespace provider) : this((keyData == null) ? emptyDictionary : ((ReadOnlyDictionary<string, string>) ReadOnlyDictionary<string, string>.Create(keyData)), (scopeName != null) ? scopeName.ToString() : null, provider ?? CorrelationNamespace) { this.ScopeName = scopeName; }
/// <summary> /// Enqueue a reply to a send /// </summary> /// <param name="fromContract"> /// The from contract. /// </param> /// <param name="fromOperation"> /// The from operation. /// </param> /// <param name="parametersContent"> /// The parameters content. /// </param> public void EnqueueReceiveReply(XName fromContract, string fromOperation, IDictionary<string, object> parametersContent) { lock (this.queue) { this.queue.Enqueue( new StubMessage(StubMessageType.ReceiveReply) { Contract = fromContract.ToString(), Content = parametersContent, Operation = fromOperation }); } }
internal static bool CompareXName(XName x1, XName x2) { return x1.ToString() == x2.ToString(); }
private static void AddAttribute(AttributeInfo currentAttributeInfo, XName xNameValue, string valueIn) { string lastXMLTag = xNameValue.ToString(); if (lastXMLTag.Equals("ColumnName")) { currentAttributeInfo.ColumnNameOriginal = valueIn; } else if (lastXMLTag.Equals("DataType")) { string dataType = valueIn; // get rid of anything after a comma currentAttributeInfo.DataType = dataType.IndexOf(",", StringComparison.Ordinal) >= 0 ? dataType.Substring(0, dataType.IndexOf(",", StringComparison.Ordinal)) : dataType; } else if (lastXMLTag.Equals("ColumnSize")) { currentAttributeInfo.ColumnSize = Convert.ToInt32(valueIn); } else if (lastXMLTag.Equals("IsUnique")) { currentAttributeInfo.IsUnique = valueIn.ToUpper().Equals("TRUE") ? true : false; } else if (lastXMLTag.Equals("IsKey")) { currentAttributeInfo.IsKey = valueIn.ToUpper().Equals("TRUE") ? true : false; } else if (lastXMLTag.Equals("AllowDBNull")) { currentAttributeInfo.AllowDBNull = valueIn.ToUpper().Equals("TRUE") ? true : false; } else if (lastXMLTag.Equals("IsAutoIncrement")) { currentAttributeInfo.IsAutoIncrement = valueIn.ToUpper().Equals("TRUE") ? true : false; } }
private static string GetAttributeValue(XElement e, XName key, bool isMandatory, string providerName) { var att = e.Attribute(key); if (att == null) { if (isMandatory) { throw new ArgumentException( string.Format( "Element \"{0}\" does not contain mandatory \"{1}\" attribute (in the {2} provider config)", e.ToString(), key.ToString(), providerName), "e"); } else { return string.Empty; } } return att.Value; }
public CorrelationKey(IDictionary<string, string> keyData, XName scopeName, XNamespace provider) : this(keyData == null ? CorrelationKey.emptyDictionary : MakeReadonlyCopy(keyData), scopeName != null ? scopeName.ToString() : null, provider ?? CorrelationNamespace) { ScopeName = scopeName; }
//helper method to extract an attribute value, and throw if null, if required internal static String ParseAttribute(XElement element, XName name, bool required = false) { XAttribute attr = element.Attribute(name); if (attr == null || String.IsNullOrEmpty(attr.Value)) { if (required) { throw new ArgumentException(string.Empty, name.ToString()); } else { return String.Empty; } } else { return attr.Value; } }