public NvdlFilteredXmlReader (XmlReader reader, NvdlValidateInterp validate) { this.reader = reader; reader_as_line_info = reader as IXmlLineInfo; this.validate = validate; }
public XPathDocumentBuilder(XPathDocument doc, IXmlLineInfo lineInfo, string baseUri, XPathDocument.LoadFlags flags) { this.nodePageFact.Init(0x100); this.nmspPageFact.Init(0x10); this.stkNmsp = new Stack<XPathNodeRef>(); this.Initialize(doc, lineInfo, baseUri, flags); }
static Exception Error(IXmlLineInfo lineInfo, string message) { if (lineInfo != null) return new HighlightingDefinitionInvalidException(HighlightingLoader.FormatExceptionMessage(message, lineInfo.LineNumber, lineInfo.LinePosition)); else return new HighlightingDefinitionInvalidException(message); }
private void ConfigError (IXmlLineInfo lineInfo, string message, params object [] args) { Console.Error.WriteLine ("Analyzer Configuration Error: {0} ({1}:{2},{3})", String.Format (message, args), configuration_path, lineInfo.LineNumber, lineInfo.LinePosition); throw new Exception (); }
internal XmlException(string res, string[] args, IXmlLineInfo lineInfo) { HResult = HResults.Xml; this.res = res; this.args = args; this.lineNumber = null == lineInfo ? 0 : lineInfo.LineNumber; this.linePosition = null == lineInfo ? 0 : lineInfo.LinePosition; }
private NvdlReader (XmlReader reader) { // FIXME: use .rnc validation. this.reader = reader; this.lineInfo = reader as IXmlLineInfo; reader.MoveToContent (); }
// Return false if there is already the same key. public bool SetIdentityField (object identity, bool isXsiNil, XsdAnySimpleType type, int depth, IXmlLineInfo li) { FieldFoundDepth = depth; Identity = identity; IsXsiNil = isXsiNil; FieldFound |= isXsiNil; FieldType = type; Consuming = false; Consumed = true; if (li != null && li.HasLineInfo ()) { FieldHasLineInfo = true; FieldLineNumber = li.LineNumber; FieldLinePosition = li.LinePosition; } if (!(this.entry.OwnerSequence.SourceSchemaIdentity is XmlSchemaKeyref)) { for (int i = 0; i < entry.OwnerSequence.FinishedEntries.Count; i++) { XsdKeyEntry other = (XsdKeyEntry) entry.OwnerSequence.FinishedEntries [i]; if (this.entry.CompareIdentity (other)) return false; } } return true; }
protected virtual Exception CreateParseException(IXmlLineInfo lineInfo, string format, params object[] args) { if (lineInfo != null && lineInfo.HasLineInfo()) return new HttpParseException(String.Format(CultureInfo.InvariantCulture, format, args), null, this.VirtualPath, null, lineInfo.LineNumber); else return new HttpParseException(String.Format(CultureInfo.InvariantCulture, format, args)); }
static Color? ParseColor(IXmlLineInfo lineInfo, string color) { if (string.IsNullOrEmpty(color)) return null; return ColorConverter.ConvertFromString(color); }
private void SetLineInfo(IXmlLineInfo lineInfo, SearchResult searchResult) { if(lineInfo.HasLineInfo()) { searchResult.LineNumber = lineInfo.LineNumber; searchResult.LinePosition = lineInfo.LinePosition; } }
private static string WrapMessage(IXmlLineInfo lineInfo, string message, Exception innerException) { if (innerException == null) return string.Format("{0} (line: {1}, col: {2})", message, lineInfo.LineNumber, lineInfo.LinePosition); return string.Format("{0} (line: {1}, col: {2}): [{3}] {4}", message, lineInfo.LineNumber, lineInfo.LinePosition, innerException.GetType().Name, innerException.Message); }
//Constructor internal XsdCachingReader(XmlReader reader, IXmlLineInfo lineInfo, CachingEventHandler handlerMethod) { this.coreReader = reader; this.lineInfo = lineInfo; this.cacheHandler = handlerMethod; attributeEvents = new ValidatingReaderNodeData[InitialAttributeCount]; contentEvents = new ValidatingReaderNodeData[InitialContentCount]; Init(); }
public Attribute(string name, IXmlLineInfo lineInfo) { this.name = name; _hasLineInfo = lineInfo.HasLineInfo(); _lineNumber = lineInfo.LineNumber; _linePosition = lineInfo.LinePosition; }
internal PositionXmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc, IXmlLineInfo lineInfo) : base(prefix, localName, namespaceURI, doc) { if (lineInfo != null) { this.lineNumber = lineInfo.LineNumber; this.linePosition = lineInfo.LinePosition; this.hasLineInfo = true; } }
internal static SystemColorHighlightingBrush GetSystemColorBrush(IXmlLineInfo lineInfo, string name) { Debug.Assert(name.StartsWith("SystemColors.", StringComparison.Ordinal)); string shortName = name.Substring(13); var property = typeof(SystemColors).GetProperty(shortName + "Brush"); if (property == null) throw Error(lineInfo, "Cannot find '" + name + "'."); return new SystemColorHighlightingBrush(property); }
private static string AddLineInfo(string message, IXmlLineInfo lineInfo) { if (lineInfo != null) { string[] args = new string[] { lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture) }; message = message + " " + Res.GetString("Xml_ErrorPosition", args); } return message; }
static string BuildMessage (string message, IXmlLineInfo li, string sourceUri) { if (li != null && li.HasLineInfo ()) { message = String.Format ("{0}. Location: {1} ({2}, {3}).", message, sourceUri, li.LineNumber, li.LinePosition); } else if (sourceUri != null) message = String.Format ("{0}. Location: {1}", message, sourceUri); return message; }
public XmlReaderProxy(XmlReader xmlreader, Uri baseUri, IXmlLineInfo lineNumberService) { Debug.Assert(xmlreader != null, "xmlreader != null"); Debug.Assert(baseUri != null, "baseUri != null"); _proxy = xmlreader; _baseUri = baseUri; _lineNumberService = lineNumberService; }
/// <summary> /// Loads the XML document from the specified <see cref="XmlReader"/>. /// </summary> public override void Load(XmlReader reader) { lineInfo = reader as IXmlLineInfo; try { base.Load(reader); } finally { lineInfo = null; } }
public override void Load(XmlReader reader) { if (reader is IXmlLineInfo) lineInfo = (IXmlLineInfo)reader; base.Load(reader); lineInfo = null; }
internal XsdCachingReader(XmlReader reader, IXmlLineInfo lineInfo, CachingEventHandler handlerMethod) { this.coreReader = reader; this.lineInfo = lineInfo; this.cacheHandler = handlerMethod; this.attributeEvents = new ValidatingReaderNodeData[8]; this.contentEvents = new ValidatingReaderNodeData[4]; this.Init(); }
/// <summary> /// Create a new XPathDocumentBuilder which creates nodes in "doc". /// </summary> public XPathDocumentBuilder(XPathDocument doc, IXmlLineInfo lineInfo, string baseUri, XPathDocument.LoadFlags flags) { // Allocate the initial node (for non-namespaces) page, and the initial namespace page this.nodePageFact.Init(256); this.nmspPageFact.Init(16); this.stkNmsp = new Stack<XPathNodeRef>(); Initialize(doc, lineInfo, baseUri, flags); }
protected internal ParseErrorEventArgs(string message, IXmlLineInfo lineInfo) { this._message = message; if (lineInfo != null) { this._hasLineInfo = lineInfo.HasLineInfo(); this._lineNumber = lineInfo.LineNumber; this._linePosition = lineInfo.LinePosition; } }
/// <summary> /// A default mapping (property "Foo" maps by convention to column "Foo"), if allowed, has the lowest precedence. /// A mapping for a specific type (EntityType="Bar") takes precedence over a mapping for a hierarchy (EntityType="IsTypeOf(Bar)")) /// If there are two hierarchy mappings, the most specific mapping takes precedence. /// For instance, given the types Base, Derived1 : Base, and Derived2 : Derived1, /// w.r.t. Derived1 "IsTypeOf(Derived1)" takes precedence over "IsTypeOf(Base)" when you ask for the rename of Derived1 /// </summary> /// <param name="lineInfo"> Empty for default rename mapping. </param> internal string GetRename(EdmType type, out IXmlLineInfo lineInfo) { DebugCheck.NotNull(type); Debug.Assert(type is StructuralType, "we can only rename structural type"); var rename = _renameCache.Evaluate(type as StructuralType); lineInfo = rename.LineInfo; return rename.ColumnName; }
protected XPathNavigatorReader(XPathNavigator navToRead, IXmlLineInfo xli, IXmlSchemaInfo xsi) { this.navToRead = navToRead; this.lineInfo = xli; this.schemaInfo = xsi; this.nav = XmlEmptyNavigator.Singleton; this.state = State.Initial; this.depth = 0; this.nodeType = ToXmlNodeType(this.nav.NodeType); }
public SubtreeXmlReader (XmlReader reader) { this.Reader = reader; li = reader as IXmlLineInfo; nsResolver = reader as IXmlNamespaceResolver; initial = true; startDepth = reader.Depth; if (reader.ReadState == ReadState.Initial) startDepth = -1; // end == the reader's end }
/// <summary> /// A default mapping (property "Foo" maps by convention to column "Foo"), if allowed, has the lowest precedence. /// A mapping for a specific type (EntityType="Bar") takes precedence over a mapping for a hierarchy (EntityType="IsTypeOf(Bar)")) /// If there are two hierarchy mappings, the most specific mapping takes precedence. /// For instance, given the types Base, Derived1 : Base, and Derived2 : Derived1, /// w.r.t. Derived1 "IsTypeOf(Derived1)" takes precedence over "IsTypeOf(Base)" when you ask for the rename of Derived1 /// </summary> /// <param name="lineInfo">Empty for default rename mapping.</param> internal string GetRename(EdmType type, out IXmlLineInfo lineInfo) { //Contract.Requires(type != null); Debug.Assert(type is StructuralType, "we can only rename structural type"); var rename = _renameCache.Evaluate(type as StructuralType); lineInfo = rename.LineInfo; return rename.ColumnName; }
public XmlSimpleDictionaryReader (XmlReader reader, XmlDictionary dictionary, OnXmlDictionaryReaderClose onClose) { this.reader = reader; this.onClose = onClose; as_line_info = reader as IXmlLineInfo; as_dict_reader = reader as XmlDictionaryReader; if (dictionary == null) dictionary = new XmlDictionary (); dict = dictionary; }
internal XamlScanner(XamlParserContext context, XmlReader xmlReader, XamlXmlReaderSettings settings) { this._xmlReader = xmlReader; this._xmlLineInfo = settings.ProvideLineInfo ? (xmlReader as IXmlLineInfo) : null; this._parserContext = context; this._scannerStack = new XamlScannerStack(); this._readNodesQueue = new Queue<XamlScannerNode>(); this._settings = settings; if (settings.XmlSpacePreserve) { this._scannerStack.CurrentXmlSpacePreserve = true; } }
internal PropertyTreeXmlReader(XmlReader reader) { this.reader = reader; this.readerLineInfoCache = (reader as IXmlLineInfo) ?? Utility.NullLineInfo; if (this.reader.ReadState == XReadState.Interactive) { this.state = PTXReaderState.ChooseState(reader); this.state.Accept(this, reader); } else { this.state = PTXReaderState.Initial; } }
static bool TryAddToResourceDictionary(ResourceDictionary resourceDictionary, object value, string xKey, IXmlLineInfo lineInfo, out Exception exception) { exception = null; if (resourceDictionary == null) { return(false); } if (xKey != null) { resourceDictionary.Add(xKey, value); } else if (value is Style) { resourceDictionary.Add((Style)value); } else if (value is ResourceDictionary) { resourceDictionary.Add((ResourceDictionary)value); } else { exception = new XamlParseException("resources in ResourceDictionary require a x:Key attribute", lineInfo); return(false); } return(true); }
internal XmlException(int res, string[] args, IXmlLineInfo lineInfo) : this(res, args, lineInfo, (string)null) { }
internal XmlException(int res, string arg, IXmlLineInfo lineInfo) : this(res, new string[1] { arg }, lineInfo, (string)null) { }
public static void SetPropertyValue(object xamlelement, XmlName propertyName, object value, object rootElement, INode node, HydrationContext context, IXmlLineInfo lineInfo) { var localName = propertyName.LocalName; var serviceProvider = new XamlServiceProvider(node, context); Exception xpe = null; var xKey = node is IElementNode && ((IElementNode)node).Properties.ContainsKey(XmlName.xKey) ? ((ValueNode)((IElementNode)node).Properties[XmlName.xKey]).Value as string : null; //If it's an attached BP, update elementType and propertyName var bpOwnerType = xamlelement.GetType(); var attached = GetRealNameAndType(ref bpOwnerType, propertyName.NamespaceURI, ref localName, context, lineInfo); var property = GetBindableProperty(bpOwnerType, localName, lineInfo, false); //If the target is an event, connect if (xpe == null && TryConnectEvent(xamlelement, localName, value, rootElement, lineInfo, out xpe)) { return; } //If Value is DynamicResource and it's a BP, SetDynamicResource if (xpe == null && TrySetDynamicResource(xamlelement, property, value, lineInfo, out xpe)) { return; } //If value is BindingBase, SetBinding if (xpe == null && TrySetBinding(xamlelement, property, localName, value, lineInfo, out xpe)) { return; } //If it's a BindableProberty, SetValue if (xpe == null && TrySetValue(xamlelement, property, attached, value, lineInfo, serviceProvider, out xpe)) { return; } //If we can assign that value to a normal property, let's do it if (xpe == null && TrySetProperty(xamlelement, localName, value, lineInfo, serviceProvider, context, out xpe)) { return; } //If it's an already initialized property, add to it if (xpe == null && TryAddToProperty(xamlelement, propertyName, value, xKey, lineInfo, serviceProvider, context, out xpe)) { return; } xpe = xpe ?? new XamlParseException($"Cannot assign property \"{localName}\": Property does not exists, or is not assignable, or mismatching type between value and property", lineInfo); if (context.ExceptionHandler != null) { context.ExceptionHandler(xpe); } else { throw xpe; } }
static bool TryConnectEvent(object element, string localName, object value, object rootElement, IXmlLineInfo lineInfo, out Exception exception) { exception = null; var elementType = element.GetType(); var eventInfo = elementType.GetRuntimeEvent(localName); var stringValue = value as string; if (eventInfo == null || IsNullOrEmpty(stringValue)) { return(false); } var methodInfo = rootElement.GetType().GetRuntimeMethods().FirstOrDefault(mi => mi.Name == (string)value); if (methodInfo == null) { exception = new XamlParseException($"No method {value} found on type {rootElement.GetType()}", lineInfo); return(false); } try { eventInfo.AddEventHandler(element, methodInfo.CreateDelegate(eventInfo.EventHandlerType, rootElement)); return(true); } catch (ArgumentException ae) { exception = new XamlParseException($"Method {stringValue} does not have the correct signature", lineInfo, ae); } return(false); }
static bool TrySetBinding(object element, BindableProperty property, string localName, object value, IXmlLineInfo lineInfo, out Exception exception) { exception = null; var elementType = element.GetType(); var binding = value.ConvertTo(typeof(BindingBase), pinfoRetriever: null, serviceProvider: null) as BindingBase; var bindable = element as BindableObject; var nativeBindingService = DependencyService.Get <INativeBindingService>(); if (binding == null) { return(false); } if (bindable != null && property != null) { bindable.SetBinding(property, binding); return(true); } if (nativeBindingService != null && property != null && nativeBindingService.TrySetBinding(element, property, binding)) { return(true); } if (nativeBindingService != null && nativeBindingService.TrySetBinding(element, localName, binding)) { return(true); } if (property != null) { exception = new XamlParseException($"{elementType.Name} is not a BindableObject or does not support native bindings", lineInfo); } return(false); }
static bool TryGetValue(object element, BindableProperty property, bool attached, out object value, IXmlLineInfo lineInfo, out Exception exception, out object targetProperty) { exception = null; value = null; targetProperty = property; var elementType = element.GetType(); var bindable = element as BindableObject; if (property == null) { return(false); } if (bindable == null) { return(false); } value = bindable.GetValue(property); return(true); }
public XmlNodeException(string message, XmlNode node) : base(message) { this.lineInfo = node as IXmlLineInfo; this.document = node.OwnerDocument as XmlFileInfoDocument; }
/// <summary> /// Initializes a new instance of the <see cref="YAXCannotAddObjectToCollection" /> class. /// </summary> /// <param name="propName">Name of the property.</param> /// <param name="obj">The object that could not be added to the collection.</param> /// <param name="lineInfo">IXmlLineInfo derived object, e.g. XElement, XAttribute containing line info</param> public YAXCannotAddObjectToCollection(string propName, object obj, IXmlLineInfo lineInfo) : base(lineInfo) { PropertyName = propName; ObjectToAdd = obj; }
public static TypeReference GetTypeReference(string namespaceURI, string typename, ModuleDefinition module, IXmlLineInfo xmlInfo) { return(new XmlType(namespaceURI, typename, null).GetTypeReference(module, xmlInfo)); }
public static TypeReference GetTypeReference(this XmlType xmlType, ModuleDefinition module, IXmlLineInfo xmlInfo, bool fromAllAssembly = false) { if (s_xmlnsDefinitions == null) { GatherXmlnsDefinitionAttributes(); } var namespaceURI = xmlType.NamespaceUri; var elementName = xmlType.Name; var typeArguments = xmlType.TypeArguments; if (elementName.Contains("-")) { elementName = elementName.Replace('-', '+'); } var lookupAssemblies = new List <XmlnsDefinitionAttribute>(); var lookupNames = new List <string>(); if (true == fromAllAssembly) { foreach (var xmlnsDef in s_xmlnsDefinitions) { lookupAssemblies.Add(xmlnsDef); } } else { foreach (var xmlnsDef in s_xmlnsDefinitions) { if (xmlnsDef.XmlNamespace != namespaceURI) { continue; } lookupAssemblies.Add(xmlnsDef); } } if (lookupAssemblies.Count == 0) { string ns; string typename; string asmstring; string targetPlatform; XmlnsHelper.ParseXmlns(namespaceURI, out typename, out ns, out asmstring, out targetPlatform); asmstring = asmstring ?? module.Assembly.Name.Name; if (ns != null) { lookupAssemblies.Add(new XmlnsDefinitionAttribute(namespaceURI, ns, 0) { AssemblyName = asmstring }); } } lookupNames.Add(elementName); lookupNames.Add(elementName + "Extension"); for (var i = 0; i < lookupNames.Count; i++) { var name = lookupNames[i]; if (name.Contains(":")) { name = name.Substring(name.LastIndexOf(':') + 1); } if (typeArguments != null) { name += "`" + typeArguments.Count; //this will return an open generic Type } lookupNames[i] = name; } TypeReference type = null; foreach (var asm in lookupAssemblies) { if (type != null) { break; } foreach (var name in lookupNames) { if (type != null) { break; } var clrNamespace = asm.ClrNamespace; var typeName = name.Replace('+', '/'); //Nested types var idx = typeName.LastIndexOf('.'); if (idx >= 0) { clrNamespace += '.' + typeName.Substring(0, typeName.LastIndexOf('.')); typeName = typeName.Substring(typeName.LastIndexOf('.') + 1); } type = module.GetTypeDefinition((asm.AssemblyName, clrNamespace, typeName)); } } if (type != null && typeArguments != null && type.HasGenericParameters) { type = module.ImportReference(type) .MakeGenericInstanceType(typeArguments.Select(x => GetTypeReference(x, module, xmlInfo)).ToArray()); } if (type == null) { throw new XamlParseException(string.Format("Type {0} not found in xmlns {1}", elementName, namespaceURI), xmlInfo); } return(module.ImportReference(type)); }
public static bool IsInRange(this IXmlLineInfo item, TextLocation begin, TextLocation end) { return(IsInRange(item, begin.Line, begin.Column, end.Line, end.Column)); }
static bool TryAddToProperty(object element, XmlName propertyName, object value, string xKey, IXmlLineInfo lineInfo, XamlServiceProvider serviceProvider, HydrationContext context, out Exception exception) { exception = null; object targetProperty; var collection = GetPropertyValue(element, propertyName, context, lineInfo, out targetProperty) as IEnumerable; if (collection == null) { return(false); } if (exception == null && TryAddToResourceDictionary(collection as ResourceDictionary, value, xKey, lineInfo, out exception)) { return(true); } if (exception != null) { return(false); } var addMethod = collection.GetType().GetRuntimeMethods().First(mi => mi.Name == "Add" && mi.GetParameters().Length == 1); if (addMethod == null) { return(false); } if (serviceProvider != null) { ((XamlValueTargetProvider)serviceProvider.IProvideValueTarget).TargetProperty = targetProperty; } addMethod.Invoke(collection, new [] { value.ConvertTo(addMethod.GetParameters() [0].ParameterType, (Func <TypeConverter>)null, serviceProvider) }); return(true); }
internal XmlException(int res, string arg, Exception innerException, IXmlLineInfo lineInfo) : this(res, new string[1] { arg }, innerException, lineInfo == null ? 0 : lineInfo.LineNumber, lineInfo == null ? 0 : lineInfo.LinePosition, (string)null) { }
static bool TryGetProperty(object element, string localName, out object value, IXmlLineInfo lineInfo, HydrationContext context, out Exception exception, out object targetProperty) { exception = null; value = null; var elementType = element.GetType(); PropertyInfo propertyInfo = null; try { propertyInfo = elementType.GetRuntimeProperty(localName); } catch (AmbiguousMatchException) { // Get most derived instance of property foreach (var property in elementType.GetRuntimeProperties().Where(prop => prop.Name == localName)) { if (propertyInfo == null || propertyInfo.DeclaringType.IsAssignableFrom(property.DeclaringType)) { propertyInfo = property; } } } MethodInfo getter; targetProperty = propertyInfo; if (propertyInfo == null || !propertyInfo.CanRead || (getter = propertyInfo.GetMethod) == null) { return(false); } if (!IsVisibleFrom(getter, context.RootElement)) { return(false); } value = getter.Invoke(element, new object[] { }); return(true); }
public XmlNodeException(Exception innerException, XmlNode node) : base(innerException.Message, innerException) { this.lineInfo = node as IXmlLineInfo; this.document = node.OwnerDocument as XmlFileInfoDocument; }
static bool TrySetValue(object element, BindableProperty property, bool attached, object value, IXmlLineInfo lineInfo, XamlServiceProvider serviceProvider, out Exception exception) { exception = null; var elementType = element.GetType(); var bindable = element as BindableObject; var nativeBindingService = DependencyService.Get <INativeBindingService>(); if (property == null) { return(false); } if (serviceProvider != null && serviceProvider.IProvideValueTarget != null) { ((XamlValueTargetProvider)serviceProvider.IProvideValueTarget).TargetProperty = property; } Func <MemberInfo> minforetriever; if (attached) { minforetriever = () => property.DeclaringType.GetRuntimeMethod("Get" + property.PropertyName, new [] { typeof(BindableObject) }); } else { minforetriever = () => property.DeclaringType.GetRuntimeProperty(property.PropertyName); } var convertedValue = value.ConvertTo(property.ReturnType, minforetriever, serviceProvider); if (bindable != null) { //SetValue doesn't throw on mismatching type, so check before to get a chance to try the property setting or the collection adding var nullable = property.ReturnTypeInfo.IsGenericType && property.ReturnTypeInfo.GetGenericTypeDefinition() == typeof(Nullable <>); if ((convertedValue == null && (!property.ReturnTypeInfo.IsValueType || nullable)) || (property.ReturnType.IsInstanceOfType(convertedValue))) { bindable.SetValue(property, convertedValue); return(true); } return(false); } if (nativeBindingService != null && nativeBindingService.TrySetValue(element, property, convertedValue)) { return(true); } exception = new XamlParseException($"{elementType.Name} is not a BindableObject or does not support setting native BindableProperties", lineInfo); return(false); }
/// <summary> /// Initializes a new instance of the <see cref="YAXAttributeMissingException" /> class. /// </summary> /// <param name="elementName">Name of the element.</param> /// <param name="lineInfo">IXmlLineInfo derived object, e.g. XElement, XAttribute containing line info</param> public YAXElementValueMissingException(string elementName, IXmlLineInfo lineInfo) : base(lineInfo) { ElementName = elementName; }
static bool TrySetDynamicResource(object element, BindableProperty property, object value, IXmlLineInfo lineInfo, out Exception exception) { exception = null; var elementType = element.GetType(); var dynamicResource = value as DynamicResource; var bindable = element as BindableObject; if (dynamicResource == null || property == null) { return(false); } if (bindable == null) { exception = new XamlParseException($"{elementType.Name} is not a BindableObject", lineInfo); return(false); } bindable.SetDynamicResource(property, dynamicResource.Key); return(true); }
static Instruction PushParsedEnum(TypeReference enumRef, string value, IXmlLineInfo lineInfo) { var enumDef = enumRef.ResolveCached(); if (!enumDef.IsEnum) { throw new InvalidOperationException(); } // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. // https://msdn.microsoft.com/en-us/library/sbbt4032.aspx byte b = 0; sbyte sb = 0; short s = 0; ushort us = 0; int i = 0; uint ui = 0; long l = 0; ulong ul = 0; bool found = false; TypeReference typeRef = null; foreach (var field in enumDef.Fields) { if (field.Name == "value__") { typeRef = field.FieldType; } } if (typeRef == null) { throw new ArgumentException(); } foreach (var v in value.Split(',')) { foreach (var field in enumDef.Fields) { if (field.Name == "value__") { continue; } if (field.Name == v.Trim()) { switch (typeRef.FullName) { case "System.Byte": b |= (byte)field.Constant; break; case "System.SByte": if (found) { throw new XamlParseException($"Multi-valued enums are not valid on sbyte enum types", lineInfo); } sb = (sbyte)field.Constant; break; case "System.Int16": s |= (short)field.Constant; break; case "System.UInt16": us |= (ushort)field.Constant; break; case "System.Int32": i |= (int)field.Constant; break; case "System.UInt32": ui |= (uint)field.Constant; break; case "System.Int64": l |= (long)field.Constant; break; case "System.UInt64": ul |= (ulong)field.Constant; break; } found = true; } } } if (!found) { throw new XamlParseException($"Enum value not found for {value}", lineInfo); } switch (typeRef.FullName) { case "System.Byte": return(Instruction.Create(OpCodes.Ldc_I4, (int)b)); case "System.SByte": return(Instruction.Create(OpCodes.Ldc_I4, (int)sb)); case "System.Int16": return(Instruction.Create(OpCodes.Ldc_I4, (int)s)); case "System.UInt16": return(Instruction.Create(OpCodes.Ldc_I4, (int)us)); case "System.Int32": return(Instruction.Create(OpCodes.Ldc_I4, (int)i)); case "System.UInt32": return(Instruction.Create(OpCodes.Ldc_I4, (uint)ui)); case "System.Int64": return(Instruction.Create(OpCodes.Ldc_I4, (long)l)); case "System.UInt64": return(Instruction.Create(OpCodes.Ldc_I4, (ulong)ul)); default: throw new XamlParseException($"Enum value not found for {value}", lineInfo); } }
public static object GetPropertyValue(object xamlElement, XmlName propertyName, HydrationContext context, IXmlLineInfo lineInfo, out object targetProperty) { var localName = propertyName.LocalName; Exception xpe = null; object value; targetProperty = null; //If it's an attached BP, update elementType and propertyName var bpOwnerType = xamlElement.GetType(); var attached = GetRealNameAndType(ref bpOwnerType, propertyName.NamespaceURI, ref localName, context, lineInfo); var property = GetBindableProperty(bpOwnerType, localName, lineInfo, false); //If it's a BindableProberty, GetValue if (xpe == null && TryGetValue(xamlElement, property, attached, out value, lineInfo, out xpe, out targetProperty)) { return(value); } //If it's a normal property, get it if (xpe == null && TryGetProperty(xamlElement, localName, out value, lineInfo, context, out xpe, out targetProperty)) { return(value); } xpe = xpe ?? new XamlParseException($"Property {localName} is not found or does not have an accessible getter", lineInfo); if (context.ExceptionHandler != null) { context.ExceptionHandler(xpe); } else { throw xpe; } return(null); }
internal static XmlContext CreateFrom(IXmlLineInfo lineInfo) { return(new XmlContext { LineInfo = lineInfo }); }
static object GetTargetProperty(object xamlelement, XmlName propertyName, HydrationContext context, IXmlLineInfo lineInfo) { var localName = propertyName.LocalName; //If it's an attached BP, update elementType and propertyName var bpOwnerType = xamlelement.GetType(); GetRealNameAndType(ref bpOwnerType, propertyName.NamespaceURI, ref localName, context, lineInfo); var property = GetBindableProperty(bpOwnerType, localName, lineInfo, false); if (property != null) { return(property); } var elementType = xamlelement.GetType(); var propertyInfo = elementType.GetRuntimeProperties().FirstOrDefault(p => p.Name == localName); return(propertyInfo); }
internal void ReadContentFrom(XmlReader r, LoadOptions o) { if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0) { ReadContentFrom(r); return; } if (r.ReadState != ReadState.Interactive) { throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); } XContainer c = this; XNode n = null; NamespaceCache eCache = new NamespaceCache(); NamespaceCache aCache = new NamespaceCache(); string baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null; IXmlLineInfo li = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null; do { string uri = r.BaseURI; switch (r.NodeType) { case XmlNodeType.Element: { XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName)); if (baseUri != null && baseUri != uri) { e.SetBaseUri(uri); } if (li != null && li.HasLineInfo()) { e.SetLineInfo(li.LineNumber, li.LinePosition); } if (r.MoveToFirstAttribute()) { do { XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value); if (li != null && li.HasLineInfo()) { a.SetLineInfo(li.LineNumber, li.LinePosition); } e.AppendAttributeSkipNotify(a); } while (r.MoveToNextAttribute()); r.MoveToElement(); } c.AddNodeSkipNotify(e); if (!r.IsEmptyElement) { c = e; if (baseUri != null) { baseUri = uri; } } break; } case XmlNodeType.EndElement: { if (c.content == null) { c.content = string.Empty; } // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement XElement e = c as XElement; Debug.Assert(e != null, "EndElement received but the current container is not an element."); if (e != null && li != null && li.HasLineInfo()) { e.SetEndElementLineInfo(li.LineNumber, li.LinePosition); } if (c == this) { return; } if (baseUri != null && c.HasBaseUri) { baseUri = c.parent.BaseUri; } c = c.parent; break; } case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: if ((baseUri != null && baseUri != uri) || (li != null && li.HasLineInfo())) { n = new XText(r.Value); } else { c.AddStringSkipNotify(r.Value); } break; case XmlNodeType.CDATA: n = new XCData(r.Value); break; case XmlNodeType.Comment: n = new XComment(r.Value); break; case XmlNodeType.ProcessingInstruction: n = new XProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.DocumentType: n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value); break; case XmlNodeType.EntityReference: if (!r.CanResolveEntity) { throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference); } r.ResolveEntity(); break; case XmlNodeType.EndEntity: break; default: throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType)); } if (n != null) { if (baseUri != null && baseUri != uri) { n.SetBaseUri(uri); } if (li != null && li.HasLineInfo()) { n.SetLineInfo(li.LineNumber, li.LinePosition); } c.AddNodeSkipNotify(n); n = null; } } while (r.Read()); }
static BindableProperty GetBindableProperty(Type elementType, string localName, IXmlLineInfo lineInfo, bool throwOnError = false) { var bindableFieldInfo = elementType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy).FirstOrDefault(fi => fi.Name == localName + "Property"); Exception exception = null; if (exception == null && bindableFieldInfo == null) { exception = new XamlParseException( Format("BindableProperty {0} not found on {1}", localName + "Property", elementType.Name), lineInfo); } if (exception == null) { return(bindableFieldInfo.GetValue(null) as BindableProperty); } if (throwOnError) { throw exception; } return(null); }
internal XmlException(int res, string arg, IXmlLineInfo lineInfo, string sourceUri) : this(res, new string[1] { arg }, lineInfo, sourceUri) { }
private void ProcessAttribute(XPathNavigator nav) { // skip attributes from non-default namespace if (nav.NamespaceURI != string.Empty) { return; } string value = nav.Value; switch (nav.LocalName) { case "cdata-section-elements": if (value.Length > 0) { cdSectsList.AddRange(XslNameUtil.FromListString(value, nav)); } break; case "method": if (value.Length == 0) { break; } switch (value) { case "xml": method = OutputMethod.XML; break; case "html": omitXmlDeclaration = true; method = OutputMethod.HTML; break; case "text": omitXmlDeclaration = true; method = OutputMethod.Text; break; default: method = OutputMethod.Custom; customMethod = XslNameUtil.FromString(value, nav); if (customMethod.Namespace == String.Empty) { IXmlLineInfo li = nav as IXmlLineInfo; throw new XsltCompileException(new ArgumentException( "Invalid output method value: '" + value + "'. It" + " must be either 'xml' or 'html' or 'text' or QName."), nav.BaseURI, li != null ? li.LineNumber : 0, li != null ? li.LinePosition : 0); } break; } break; case "version": if (value.Length > 0) { this.version = value; } break; case "encoding": if (value.Length > 0) { try { this.encoding = System.Text.Encoding.GetEncoding(value); } catch (ArgumentException) { // MS.NET just leaves the default encoding when encoding is unknown } catch (NotSupportedException) { // Workaround for a bug in System.Text, it throws invalid exception } } break; case "standalone": switch (value) { case "yes": this.standalone = StandaloneType.YES; break; case "no": this.standalone = StandaloneType.NO; break; default: if (stylesheetVersion != "1.0") { break; } IXmlLineInfo li = nav as IXmlLineInfo; throw new XsltCompileException(new XsltException( "'" + value + "' is an invalid value for 'standalone'" + " attribute.", (Exception)null), nav.BaseURI, li != null ? li.LineNumber : 0, li != null ? li.LinePosition : 0); } break; case "doctype-public": this.doctypePublic = value; break; case "doctype-system": this.doctypeSystem = value; break; case "media-type": if (value.Length > 0) { this.mediaType = value; } break; case "omit-xml-declaration": switch (value) { case "yes": this.omitXmlDeclaration = true; break; case "no": this.omitXmlDeclaration = false; break; default: if (stylesheetVersion != "1.0") { break; } IXmlLineInfo li = nav as IXmlLineInfo; throw new XsltCompileException(new XsltException( "'" + value + "' is an invalid value for 'omit-xml-declaration'" + " attribute.", (Exception)null), nav.BaseURI, li != null ? li.LineNumber : 0, li != null ? li.LinePosition : 0); } break; case "indent": indent = value; if (stylesheetVersion != "1.0") { break; } switch (value) { case "yes": case "no": break; default: switch (method) { case OutputMethod.Custom: break; default: throw new XsltCompileException(String.Format("Unexpected 'indent' attribute value in 'output' element: '{0}'", value), null, nav); } break; } break; default: if (stylesheetVersion != "1.0") { break; } IXmlLineInfo xli = nav as IXmlLineInfo; throw new XsltCompileException(new XsltException( "'" + nav.LocalName + "' is an invalid attribute for 'output'" + " element.", (Exception)null), nav.BaseURI, xli != null ? xli.LineNumber : 0, xli != null ? xli.LinePosition : 0); } }
internal XmlException(string res, String arg, IXmlLineInfo lineInfo) : this(res, new string[] { arg }, lineInfo) { }
internal XmlException(int res, string[] args, IXmlLineInfo lineInfo, string sourceUri) : this(res, args, (Exception)null, lineInfo == null ? 0 : lineInfo.LineNumber, lineInfo == null ? 0 : lineInfo.LinePosition, sourceUri) { }
public object ProvideValue(IServiceProvider serviceProvider) { if (Android == null && GTK == null && iOS == null && macOS == null && Tizen == null && UWP == null && WPF == null && Default == null) { var lineInfo = serviceProvider?.GetService <IXmlLineInfoProvider>()?.XmlLineInfo ?? new XmlLineInfo(); throw new XamlParseException("OnPlatformExtension requires a non-null value to be specified for at least one platform or Default.", lineInfo); } var valueProvider = serviceProvider?.GetService <IProvideValueTarget>() ?? throw new ArgumentException(); BindableProperty bp; PropertyInfo pi = null; Type propertyType = null; if (valueProvider.TargetObject is Setter setter) { bp = setter.Property; } else { bp = valueProvider.TargetProperty as BindableProperty; pi = valueProvider.TargetProperty as PropertyInfo; } propertyType = bp?.ReturnType ?? pi?.PropertyType ?? throw new InvalidOperationException("Cannot determine property to provide the value for."); var value = GetValue(); var info = propertyType.GetTypeInfo(); if (value == null && info.IsValueType) { return(Activator.CreateInstance(propertyType)); } if (Converter != null) { return(Converter.Convert(value, propertyType, ConverterParameter, CultureInfo.CurrentUICulture)); } var converterProvider = serviceProvider?.GetService <IValueConverterProvider>(); if (converterProvider != null) { MemberInfo minforetriever() { if (pi != null) { return(pi); } MemberInfo minfo = null; try { minfo = bp.DeclaringType.GetRuntimeProperty(bp.PropertyName); } catch (AmbiguousMatchException e) { IXmlLineInfo lineInfo = serviceProvider.GetService(typeof(IXmlLineInfoProvider)) is IXmlLineInfoProvider lineInfoProvider ? lineInfoProvider.XmlLineInfo : new XmlLineInfo(); throw new XamlParseException($"Multiple properties with name '{bp.DeclaringType}.{bp.PropertyName}' found.", lineInfo, innerException: e); } if (minfo != null) { return(minfo); } try { return(bp.DeclaringType.GetRuntimeMethod("Get" + bp.PropertyName, new[] { typeof(BindableObject) })); } catch (AmbiguousMatchException e) { IXmlLineInfo lineInfo = serviceProvider.GetService(typeof(IXmlLineInfoProvider)) is IXmlLineInfoProvider lineInfoProvider ? lineInfoProvider.XmlLineInfo : new XmlLineInfo(); throw new XamlParseException($"Multiple methods with name '{bp.DeclaringType}.Get{bp.PropertyName}' found.", lineInfo, innerException: e); } } return(converterProvider.Convert(value, propertyType, minforetriever, serviceProvider)); } return(value.ConvertTo(propertyType, () => pi, serviceProvider)); }