public AttributeParameterData(XamlType type, object value)
        {
            ValidateType(type);
            if (value == null && type.UnderlyingType.IsValueType)
            {
                throw FxTrace.Exception.Argument("value", SR.AttributeValueNotNullable(type.UnderlyingType));
            }
            if (value != null && !type.UnderlyingType.IsAssignableFrom(value.GetType()))
            {
                throw FxTrace.Exception.Argument("value", SR.AttributeValueNotAssignableToType(value.GetType(), type.UnderlyingType));
            }

            this.Type = type;
            if (value != null)
            {
                if (type.UnderlyingType.IsArray)
                {
                    Array array = (Array)value;
                    XamlType elementType = type.SchemaContext.GetXamlType(type.UnderlyingType.GetElementType());
                    this.arrayContents = new List<AttributeParameterData>();
                    foreach (object item in array)
                    {
                        this.arrayContents.Add(new AttributeParameterData(elementType, item));
                    }
                    this.IsArray = true;
                }
                else
                {
                    this.Value = value;
                    this.TextValue = AttributeData.GetParameterText(value, type);
                }
            }
        }
 private XamlNode Logic_StartElement(XamlType xamlType, string xamlNamespace)
 {
     this._context.PushScope();
     this._context.CurrentType = xamlType;
     this._context.CurrentTypeNamespace = xamlNamespace;
     return new XamlNode(XamlNodeType.StartObject, xamlType);
 }
 internal static XamlStackFrame ForObject(XamlType type)
 {
     XamlStackFrame result = new XamlStackFrame();
     result._data = type;
     result.FrameType = XamlStackFrameType.Object;
     return result;
 }
        void SetActivityType(XamlType activityXamlType, XamlType activityBuilderXamlType)
        {
            if (activityXamlType == null)
            {
                this.notRewriting = true;
            }
            else
            {
                this.activityXamlType = activityXamlType;
                this.activityBuilderXamlType = activityBuilderXamlType;
                this.xamlTypeXamlType = this.SchemaContext.GetXamlType(typeof(XamlType));
                this.typeXamlType = this.SchemaContext.GetXamlType(typeof(Type));

                this.activityPropertyXamlType = this.SchemaContext.GetXamlType(typeof(DynamicActivityProperty));
                this.activityPropertyType = this.activityPropertyXamlType.GetMember("Type");
                this.activityPropertyName = this.activityPropertyXamlType.GetMember("Name");
                this.activityPropertyValue = this.activityPropertyXamlType.GetMember("Value");

                this.activityBuilderName = this.activityBuilderXamlType.GetMember("Name");
                this.activityBuilderAttributes = this.activityBuilderXamlType.GetMember("Attributes");
                this.activityBuilderProperties = this.activityBuilderXamlType.GetMember("Properties");
                this.activityBuilderPropertyReference = this.SchemaContext.GetXamlType(typeof(ActivityBuilder)).GetAttachableMember("PropertyReference");
                this.activityBuilderPropertyReferences = this.SchemaContext.GetXamlType(typeof(ActivityBuilder)).GetAttachableMember("PropertyReferences");
                this.activityPropertyReferenceXamlType = this.SchemaContext.GetXamlType(typeof(ActivityPropertyReference));
            }
        }
Beispiel #5
0
        public object ConvertValueIfNecessary(object value, XamlType targetType)
        {
            if (IsAlreadyCompatible(value, targetType.UnderlyingType))
            {
                return value;
            }

            object converted;
            var success = TrySpecialConversion(value, targetType.UnderlyingType, out converted);
            if (success)
            {
                return converted;
            }

            var typeConverter = targetType.TypeConverter;
            if (typeConverter != null)
            {
                var context = new XamlTypeConverterContext(typeRepository, topDownValueContext);
                if (typeConverter.CanConvertFrom(context, value.GetType()))
                {
                    var anotherValue = typeConverter.ConvertFrom(context, CultureInfo.InvariantCulture, value);
                    return anotherValue;
                }
            }

            return value;
        }
 public DynamicActivityXamlReader(bool isBuilder, XamlReader innerReader, XamlSchemaContext schemaContext)
 {
     this.isBuilder = isBuilder;
     this.innerReader = innerReader;
     this.schemaContext = schemaContext ?? innerReader.SchemaContext;
     this.xamlTypeXamlType = this.schemaContext.GetXamlType(typeof(XamlType));
     this.typeXamlType = this.schemaContext.GetXamlType(typeof(System.Type));
     this.baseActivityXamlType = this.schemaContext.GetXamlType(typeof(Activity));
     this.activityPropertyXamlType = this.schemaContext.GetXamlType(typeof(DynamicActivityProperty));
     this.activityPropertyType = this.activityPropertyXamlType.GetMember("Type");
     this.activityPropertyName = this.activityPropertyXamlType.GetMember("Name");
     this.activityPropertyValue = this.activityPropertyXamlType.GetMember("Value");
     this.activityPropertyAttributes = this.activityPropertyXamlType.GetMember("Attributes");
     this.namespaceTable = new NamespaceTable();
     this.frontLoadedDirectives = true;
     this.nodeQueue = new XamlNodeQueue(this.schemaContext);
     this.nodeReader = this.nodeQueue.Reader;
     IXamlLineInfo info = innerReader as IXamlLineInfo;
     if ((info != null) && info.HasLineInfo)
     {
         this.innerReaderLineInfo = info;
         this.nodeReaderLineInfo = (IXamlLineInfo) this.nodeQueue.Reader;
         this.hasLineInfo = true;
     }
 }
Beispiel #7
0
 private IEnumerable<Instruction> Crop(IEnumerable<Instruction> original, XamlType newType, XamlType oldType)
 {
     var list = original.ToList();
     var nodeToReplace = list.First(node => NodeHasSameType(oldType, node));
     var id = list.IndexOf(nodeToReplace);
     list[id] = instructionBuilder.StartObject(newType.UnderlyingType);
     return list;
 }
 public XamlTypeInvoker(XamlType type)
 {
     if (type == null)
     {
         throw new ArgumentNullException("type");
     }
     this._xamlType = type;
 }
        public XamlAttribute(UnboundAttribute unboundAttribute, XamlType type, IXamlTypeRepository typeContext)
        {
            Type = unboundAttribute.Type;
            Value = unboundAttribute.Value;
            Locator = unboundAttribute.Locator;

            Property = GetProperty(Locator, type, typeContext);
        }
 private Type[] ConvertArrayOfXamlTypesToTypes(XamlType[] typeArgs)
 {
     Type[] typeArray = new Type[typeArgs.Length];
     for (int i = 0; i < typeArgs.Length; i++)
     {
         typeArray[i] = typeArgs[i].UnderlyingType;
     }
     return typeArray;
 }
 public XamlDirective(IEnumerable<string> xamlNamespaces, string name, XamlType xamlType, XamlValueConverter<TypeConverter> typeConverter, AllowedMemberLocations allowedLocation) : base(name, new MemberReflector(xamlType, typeConverter))
 {
     if (xamlType == null)
     {
         throw new ArgumentNullException("xamlType");
     }
     this._xamlNamespaces = GetReadOnly(xamlNamespaces);
     this._allowedLocation = allowedLocation;
 }
 public XamlValidatingReader(XamlReader underlyingReader, Assembly assembly, string rootNamespace, string realAssemblyName)
     : base(underlyingReader)
 {
     this.assembly = assembly;
     this.definedType = null;
     this.rootNamespace = rootNamespace;
     this.localAssemblyName = assembly != null ? assembly.GetName().Name : null;
     this.realAssemblyName = realAssemblyName;
     this.xNull = underlyingReader.SchemaContext.GetXamlType(new XamlTypeName(XamlLanguage.Null));
 }
        private IEnumerable<ProtoXamlNode> CommonNodesOfElement(XamlType owner, ProtoXamlNode elementToInject, AttributeFeed attributeFeed)
        {
            var attributes = attributeFeed;

            foreach (var node in attributes.PrefixRegistrations.Select(ConvertAttributeToNsPrefixDefinition)) yield return node;

            yield return elementToInject;

            foreach (var node in attributes.RawAttributes.Select(a => ConvertAttributeToNode(owner, a))) yield return node;
        }
 internal MemberReflector(XamlType type, XamlValueConverter<System.ComponentModel.TypeConverter> typeConverter)
 {
     this.Type = type;
     this._typeConverter.Value = typeConverter;
     this._designerSerializationVisibility = DesignerSerializationVisibility.Visible;
     this._memberBits = -65440;
     this._deferringLoader.Value = null;
     this._getter.Value = null;
     this._setter.Value = null;
     this._valueSerializer.Value = null;
 }
 public WpfKnownMember(XamlSchemaContext schema,
     XamlType declaringType,
     string name,
     Type type,
     bool isReadOnly,
     bool isAttachable)
     : base(name, declaringType, isAttachable)
 {
     _type = type;
     ReadOnly = isReadOnly;
 }
        private IEnumerable<ProtoXamlInstruction> CommonNodesOfElement(XamlType owner, ProtoXamlInstruction elementToInject, AttributeFeed attributeFeed)
        {
            var attributes = attributeFeed;

            foreach (var instruction in attributes.PrefixRegistrations.Select(ConvertAttributeToNsPrefixDefinition)) yield return instruction;

            yield return elementToInject;

            foreach (var instruction in attributes.Directives.Select(ConvertDirective)) yield return instruction;
            foreach (var instruction in attributes.RawAttributes.Select(a => ConvertAttributeToNode(owner, a))) yield return instruction;
        }
 public WpfKnownMember(XamlSchemaContext schema,
     XamlType declaringType,
     string name,
     DependencyProperty dProperty,
     bool isReadOnly,
     bool isAttachable)
     : base(dProperty, isAttachable)
 {
     DependencyProperty = dProperty;
     ReadOnly = isReadOnly;
 }
 private string LookupPrefix(XamlType type)
 {
     string str;
     string prefix = this.xamlXmlWriter.LookupPrefix(type.GetXamlNamespaces(), out str);
     if ((prefix == null) && !this.meSettings.ContinueWritingWhenPrefixIsNotFound)
     {
         this.failed = true;
         return string.Empty;
     }
     return prefix;
 }
Beispiel #19
0
        private static bool NodeHasSameType(XamlType oldType, Instruction instruction)
        {
            var xamlType = instruction.XamlType;
            if (xamlType != null)
            {
                var nodeHasSameType = xamlType.Equals(oldType);
                return nodeHasSameType;
            }

            return false;
        }
Beispiel #20
0
        private static bool NodeHasSameType(XamlType oldType, XamlNode node)
        {
            var xamlType = node.XamlType;
            if (xamlType != null)
            {
                var nodeHasSameType = xamlType.Equals(oldType);
                return nodeHasSameType;
            }

            return false;
        }
        private IEnumerable<ProtoInstruction> ParseExpandedElement(XamlType xamlType, NamespaceDeclaration namespaceDeclaration, AttributeFeed attributes)
        {
            var element = instructionBuilder.NonEmptyElement(xamlType.UnderlyingType, namespaceDeclaration);
            foreach (var instruction in CommonNodesOfElement(xamlType, element, attributes)) yield return instruction;

            reader.Read();

            foreach (var instruction in ParseInnerTextIfAny()) yield return instruction;
            foreach (var instruction in ParseNestedElements(xamlType)) yield return instruction;

            yield return instructionBuilder.EndTag();
        }
        private XamlMember GetContentProperty(XamlType parentType)
        {
            var propertyName = wiringContext.ContentPropertyProvider.GetContentPropertyName(parentType.UnderlyingType);

            if (propertyName == null)
            {
                return null;
            }

            var member = wiringContext.TypeContext.GetXamlType(parentType.UnderlyingType).GetMember(propertyName);
            return member;
        }
Beispiel #23
0
        public ObjectAssembler(IWiringContext wiringContext, ITopDownValueContext topDownValueContext, ObjectAssemblerSettings settings = null)
            : this(new StackingLinkedList<Level>(), wiringContext, topDownValueContext)
        {
            Guard.ThrowIfNull(wiringContext, nameof(wiringContext));
            Guard.ThrowIfNull(topDownValueContext, nameof(topDownValueContext));

            this.topDownValueContext = topDownValueContext;
            StateCommuter.RaiseLevel();

            rootInstance = settings?.RootInstance;
            var rootInstanceType = rootInstance?.GetType();
            rootInstanceXamlType = rootInstanceType != null ? wiringContext.TypeContext.TypeRepository.GetXamlType(rootInstanceType) : null;
        }
        public ObjectAssembler(IRuntimeTypeSource typeSource, IValueContext valueContext, Settings settings = null)
            : this(new StackingLinkedList<Level>(), typeSource, GetLifecycleListener(settings), valueContext)
        {
            this.valueContext = valueContext;
            Guard.ThrowIfNull(typeSource, nameof(typeSource));

            TypeSource = typeSource;
            StateCommuter.RaiseLevel();

            rootInstance = settings?.RootInstance;
            var rootInstanceType = rootInstance?.GetType();
            rootInstanceXamlType = rootInstanceType != null ? TypeSource.GetByType(rootInstanceType) : null;
        }
        public void WriteStartObject(XamlType type)
        {
            objectAssembler.SetUnfinishedResult();

            if (IsThereAnotherObjectBeingConfigured)
            {
                bag.PushScope();
            }

            bag.Current.Type = type;

            OverrideCurrentInstanceOnFirstLevel();
        }
 public XamlMember GetDottedProperty(XamlType tagType, string tagNamespace, XamlPropertyName propName, bool tagIsRoot)
 {
     if (tagType == null)
     {
         throw new XamlInternalException(System.Xaml.SR.Get("ParentlessPropertyElement", new object[] { propName.ScopedName }));
     }
     XamlMember xamlAttachableProperty = null;
     XamlType xamlType = null;
     string propNs = this.ResolveXamlNameNS(propName);
     if (propNs == null)
     {
         throw new XamlParseException(System.Xaml.SR.Get("PrefixNotFound", new object[] { propName.Prefix }));
     }
     XamlType rootTagType = tagIsRoot ? tagType : null;
     bool flag = false;
     if (tagType.IsGeneric)
     {
         flag = this.PropertyTypeMatchesGenericTagType(tagType, tagNamespace, propNs, propName.OwnerName);
         if (flag)
         {
             xamlAttachableProperty = this.GetInstanceOrAttachableProperty(tagType, propName.Name, rootTagType);
             if (xamlAttachableProperty != null)
             {
                 return xamlAttachableProperty;
             }
         }
     }
     XamlTypeName typeName = new XamlTypeName(propNs, propName.Owner.Name);
     xamlType = this.GetXamlType(typeName, true);
     bool flag2 = tagType.CanAssignTo(xamlType);
     if (flag2)
     {
         xamlAttachableProperty = this.GetInstanceOrAttachableProperty(xamlType, propName.Name, rootTagType);
     }
     else
     {
         xamlAttachableProperty = this.GetXamlAttachableProperty(xamlType, propName.Name);
     }
     if (xamlAttachableProperty != null)
     {
         return xamlAttachableProperty;
     }
     XamlType declaringType = flag ? tagType : xamlType;
     if (flag || flag2)
     {
         return this.CreateUnknownMember(declaringType, propName.Name);
     }
     return this.CreateUnknownAttachableMember(declaringType, propName.Name);
 }
Beispiel #27
0
		public XamlDirective (IEnumerable<string> xamlNamespaces, string name, XamlType xamlType, XamlValueConverter<TypeConverter> typeConverter, AllowedMemberLocations allowedLocation)
			: base (true, xamlNamespaces != null ? xamlNamespaces.FirstOrDefault () : null, name)
		{
			if (xamlNamespaces == null)
				throw new ArgumentNullException ("xamlNamespaces");
			if (xamlType == null)
				throw new ArgumentNullException ("xamlType");

			type = xamlType;
			xaml_namespaces = new List<string> (xamlNamespaces);
			AllowedLocation = allowedLocation;
			type_converter = typeConverter;
			
			invoker = new DirectiveMemberInvoker (this);
		}
 private void AddDependencyForUnresolvedChildren(object childThatHasUnresolvedChildren, XamlMember property, object parentInstance, XamlType parentType, bool parentIsGotten, XamlSavedContext deferredMarkupExtensionContext)
 {
     if (((property != null) && property.IsDirective) && ((parentInstance == null) && (property != XamlLanguage.Key)))
     {
         List<string> result = new List<string>();
         this._nameFixupGraph.GetDependentNames(childThatHasUnresolvedChildren, result);
         string str = string.Join(", ", result.ToArray());
         throw this.WithLineInfo(new XamlObjectWriterException(System.Xaml.SR.Get("TransitiveForwardRefDirectives", new object[] { childThatHasUnresolvedChildren.GetType(), property, str })));
     }
     NameFixupToken token = this.GetTokenForUnresolvedChildren(childThatHasUnresolvedChildren, property, deferredMarkupExtensionContext);
     token.Target.Instance = parentInstance;
     token.Target.InstanceType = parentType;
     token.Target.InstanceWasGotten = parentIsGotten;
     this.PendCurrentFixupToken_SetValue(token);
 }
        public AttributeParameterData(XamlType type, string textValue)
        {
            ValidateType(type);
            if (textValue == null && type.UnderlyingType.IsValueType)
            {
                throw FxTrace.Exception.Argument("value", SR.AttributeValueNotNullable(type.UnderlyingType));
            }

            this.Type = type;
            if (textValue != null)
            {
                this.Value = AttributeData.GetParameterValue(ref textValue, type);
                this.TextValue = textValue;
            }
        }
        private static IEnumerable<XamlInstruction> ParseProperties(IEnumerable<PropertyOption> options, XamlType xamlType)
        {
            foreach (var option in options)
            {
                var member = xamlType.GetMember(option.Property);
                yield return Inject.StartOfMember(member);

                var stringNode = option.Value as StringNode;
                if (stringNode != null)
                {
                    yield return Inject.Value(stringNode.Value);
                }

                yield return Inject.EndOfMember();
            }
        }
        // It expects that it is not invoked when there is no value to
        // assign.
        // When it is passed null, then it returns a default instance.
        // For example, passing null as Int32 results in 0.
        // But do not immediately try to instantiate with the type, since the type might be abstract.
        object GetCorrectlyTypedValue(XamlMember xm, XamlType xt, object value, bool fallbackToString = false)
        {
            try
            {
                if (value == null)
                {
                    if (xt.IsContentValue(service_provider))                     // it is for collection/dictionary key and item
                    {
                        return(null);
                    }
                    else
                    {
                        return(xt.IsNullable ? null : xt.Invoker.CreateInstance(new object[0]));
                    }
                }
                if (ReferenceEquals(xt, null))
                {
                    return(value);
                }

                // Not sure if this is really required though...
                var vt = sctx.GetXamlType(value.GetType());
                if (vt.CanAssignTo(xt))
                {
                    return(value);
                }

                // FIXME: this could be generalized by some means, but I cannot find any.
                if (xt.UnderlyingType == typeof(XamlType) && value is string)
                {
                    value = ResolveTypeFromName((string)value);
                }

                // FIXME: this could be generalized by some means, but I cannot find any.
                if (xt.UnderlyingType == typeof(Type))
                {
                    value = new TypeExtension((string)value).ProvideValue(service_provider);
                }
                if (ReferenceEquals(xt, XamlLanguage.Type) && value is string)
                {
                    value = new TypeExtension((string)value);
                }

                if (IsAllowedType(xt, value))
                {
                    return(value);
                }

                var xtc = xm?.TypeConverter ?? xt.TypeConverter;
                if (xtc != null && value != null)
                {
                    var tc = xtc.ConverterInstance;
                    if (tc != null && tc.CanConvertFrom(service_provider, value.GetType()))
                    {
                        value = tc.ConvertFrom(service_provider, CultureInfo.InvariantCulture, value);
                    }
                    return(value);
                }
            }
            catch (Exception ex)
            {
                // For + ex.Message, the runtime should print InnerException message like .NET does.
                throw new XamlObjectWriterException(String.Format("Could not convert object \'{0}' (of type {1}) to {2}: ", value, value != null ? (object)value.GetType() : "(null)", xt) + ex.Message, ex);
            }

            return(fallbackToString ?
                   value :
                   throw new XamlObjectWriterException(String.Format("Value '{0}' (of type {1}) is not of or convertible to type {2} (member {3})", value, value != null ? (object)value.GetType() : "(null)", xt, xm)));
        }
Beispiel #32
0
        private void ReadPropertyElement(XamlPropertyName name, XamlType tagType, string tagNamespace, bool isEmptyTag)
        {
            // <Button>   <== currentElement
            //   <FrameworkElement.Width>   <== FrameworkElement is ownerType

            XamlScannerNode node = new XamlScannerNode(_xmlLineInfo);

            // Attributes aren't allowed on property elements.
            // but if they are there we need to scan them so the
            // XamlParser can error, or whatever.
            // (don't want to skip them w/o error)
            PreprocessAttributes();

            // It is possible for an application to provide XML nodes via XmlNodeReader
            // where the URI is defined but there was no xmlns attribute for use to resolve against.
            // See app Paperboy
            Debug.Assert(_xmlReader.NodeType == XmlNodeType.Element);
            string     ownerNamespace = _xmlReader.NamespaceURI;
            XamlMember property       = null;

            bool tagIsRoot = _scannerStack.Depth == 1; // PEs are processed after frame is pushed

            property = _parserContext.GetDottedProperty(tagType, tagNamespace, name, tagIsRoot);

            node.Prefix        = name.Prefix;
            node.TypeNamespace = ownerNamespace;
            node.IsEmptyTag    = isEmptyTag;

            // node.Type is not set (this is a property)
            // so this processing does less.
            PostprocessAttributes(node);

            if (_scannerStack.Depth > 0)
            {
                // A property Element tag will be the end of content.
                // This also allows to to start content again.
                // That is an error, but at least the parser/scanner can
                // understand what is going on.
                _scannerStack.CurrentlyInContent = false;
            }

            node.PropertyElement = property;

            node.IsCtorForcingMember = !property.IsAttachable;

            if (!node.IsEmptyTag)
            {
                _scannerStack.CurrentProperty = node.PropertyElement;
                node.NodeType = ScannerNodeType.PROPERTYELEMENT;
            }
            else
            {
                node.NodeType = ScannerNodeType.EMPTYPROPERTYELEMENT;
            }

            _readNodesQueue.Enqueue(node);

            while (HaveUnprocessedAttributes)
            {
                EnqueueAnotherAttribute(isEmptyTag);
            }
        }
Beispiel #33
0
 public virtual MethodInfo GetAddMethod(XamlType contentType)
 {
     return(Type == null || Type.UnderlyingType == null || Type.ItemType == null || Type.CollectionKind == XamlCollectionKind.None
                         ? null
                         : Type.UnderlyingType.GetRuntimeMethod("Add", new Type[] { contentType.UnderlyingType }));
 }
Beispiel #34
0
 /// <summary>
 /// Returns true if whitespace is discardable at this phase in
 /// the parsing.  Here we discard whitespace between property elements
 /// but keep it between object elements for collections that accept it.
 /// Discarding trailing whitespace in collections cannot be decided here.
 /// [see: Logic_ReadAhead_ApplyFinalTextTrimming
 /// </summary>
 /// <param name="text"></param>
 /// <returns></returns>
 private bool Logic_IsDiscardableWhitespace(XamlText text)
 {
     if (!text.IsWhiteSpaceOnly)
     {
         return(false);
     }
     else
     {
         // Force unknown members to behave as whitespace significant collections in order to preserve as much information as possible.
         if (_context.CurrentMember != null && _context.CurrentMember.IsUnknown)
         {
             return(false);
         }
         else if (_context.CurrentInContainerDirective)
         {
             XamlType collectionType = _context.CurrentMember == XamlLanguage.Items ? _context.CurrentType : _context.CurrentMember.Type;
             if (collectionType.IsWhitespaceSignificantCollection)
             {
                 return(false);
             }
         }
         else
         {
             // Whitespace, by itself does not start content.  Eg. The WS between
             // the Start Element and the first Property Element is not content, but
             // the WS between the Start Element and the first child Element (ie. other content)
             // is content.
             XamlMember prop = _context.CurrentMember;
             if (_xamlScanner.PeekNodeType == ScannerNodeType.ELEMENT)
             {
                 if (prop == null)
                 {
                     prop = _context.CurrentType.ContentProperty;
                 }
                 if (prop != null && prop.Type != null && prop.Type.IsWhitespaceSignificantCollection)
                 {
                     return(false);
                 }
                 if (prop == null && _context.CurrentType.IsWhitespaceSignificantCollection)
                 {
                     return(false);
                 }
             }
             // Whitespace can also start content if space is preserved and it's at the end of an element and...
             else if (text.IsSpacePreserved && _xamlScanner.PeekNodeType == ScannerNodeType.ENDTAG)
             {
                 // ...it's by itself in a PE with no other children
                 if (prop != null)
                 {
                     if (_context.CurrentPreviousChildType == null)
                     {
                         return(false);
                     }
                 }
                 // ...it's in an element with a string content property
                 else if (_context.CurrentType.ContentProperty != null)
                 {
                     prop = _context.CurrentType.ContentProperty;
                     // For backcompat we need to support CPs of type object here.
                     // Theoretically we'd also like to support all type-convertible CPs.
                     // However, for non-string CPs, 3.0 only surfaced whitespace as text if
                     // the CP hadn't already been set. For string, it surfaced it in all cases.
                     // So to avoid a breaking change, we only surface string right now.
                     if (prop.Type == XamlLanguage.String)
                     {
                         return(false);
                     }
                     if (prop.Type.IsWhitespaceSignificantCollection)
                     {
                         return(false);
                     }
                 }
                 // ...it's in a type-convertible element
                 else if (_context.CurrentType.TypeConverter != null && !_context.CurrentForcedToUseConstructor)
                 {
                     return(false);
                 }
             }
         }
     }
     return(true);
 }
Beispiel #35
0
        ///////////////////////////
        //  ElementContent ::= ( PREFIXDEFINITION* Element ) | TEXT
        //
        public IEnumerable <XamlNode> P_ElementContent()
        {
            XamlType currentType = _context.CurrentType;

            List <XamlNode> savedPrefixDefinitions = null;
            ScannerNodeType nodeType = _xamlScanner.NodeType;

            switch (nodeType)
            {
            case ScannerNodeType.PREFIXDEFINITION:
            case ScannerNodeType.ELEMENT:
            case ScannerNodeType.EMPTYELEMENT:
            case ScannerNodeType.TEXT:
                if (nodeType == ScannerNodeType.TEXT)
                {
                    XamlText text = _xamlScanner.TextContent;

                    if (Logic_IsDiscardableWhitespace(text))
                    {
                        _xamlScanner.Read();
                        if (ProvideLineInfo)
                        {
                            yield return(Logic_LineInfo());
                        }
                        break;
                    }
                }

                // Don't immediately emit the prefix Definitions.
                // buffer them for moment because if this is the first object
                // in a collection, we may need to jam an implicit _Items property
                // on Content Property in before the PrefixDef's and then the ObjectType.
                while (nodeType == ScannerNodeType.PREFIXDEFINITION)
                {
                    if (savedPrefixDefinitions == null)
                    {
                        savedPrefixDefinitions = new List <XamlNode>();
                    }
                    if (ProvideLineInfo)
                    {
                        savedPrefixDefinitions.Add(Logic_LineInfo());
                    }
                    savedPrefixDefinitions.Add(Logic_PrefixDefinition());
                    _xamlScanner.Read();
                    if (ProvideLineInfo)
                    {
                        yield return(Logic_LineInfo());
                    }
                    nodeType = _xamlScanner.NodeType;
                }

                // Check for any preambles we need to emit before the
                // emitting the actual element or Text.
                bool isTextInitialization = false;
                if (!_context.CurrentInItemsProperty && !_context.CurrentInUnknownContent)
                {
                    bool isContentProperty = false;
                    // In case of text, we look first for a string or object content property,
                    // then a TypeConverter
                    if (nodeType == ScannerNodeType.TEXT)
                    {
                        if (currentType.ContentProperty != null && CanAcceptString(currentType.ContentProperty))
                        {
                            isContentProperty = true;
                        }
                        // If there have been "real" properties then we are forced to use the
                        // Constructor.  Otherwise we can consider a TypeConverter on the TEXT.
                        else if (!_context.CurrentForcedToUseConstructor &&
                                 !_xamlScanner.TextContent.IsEmpty &&
                                 currentType.TypeConverter != null)
                        {
                            isTextInitialization = true;
                        }
                    }
                    // Otherwise, we look first for a collection, and then fall back to content property
                    if (!isTextInitialization && !isContentProperty)
                    {
                        // If we are first in a collection
                        if (currentType.IsCollection || currentType.IsDictionary)
                        {
                            yield return(Logic_StartItemsProperty(currentType));
                        }
                        else  // Back to ContentProperty (either element or unknown content)
                        {
                            isContentProperty = true;
                        }
                    }
                    // Don't yield more than one unknown content property for multiple,
                    // contiguous content objects and values.
                    if (isContentProperty && !_context.CurrentInUnknownContent)
                    {
                        XamlMember contentProperty = currentType.ContentProperty;
                        if (contentProperty != null)
                        {
                            bool isVisible = _context.IsVisible(
                                contentProperty, _context.CurrentTypeIsRoot ? _context.CurrentType : null);
                            // Visible content properties produce known members.
                            // Invisible content properties produce unknown members.
                            // Protected content properties of root instances and internal
                            // content properties can be visible, depending on the reader settings.
                            if (!isVisible)
                            {
                                // We use the current type, not the actual declaring type of the non-visible property,
                                // for consistency with how non-visible PEs and Attribute Properties are handled.
                                contentProperty = new XamlMember(contentProperty.Name, currentType, false);
                            }
                        }
                        // A null argument produces an unknown content member.
                        yield return(Logic_StartContentProperty(contentProperty));

                        // Check for and emit the get collection from member.
                        foreach (XamlNode node in LogicStream_CheckForStartGetCollectionFromMember())
                        {
                            yield return(node);
                        }
                    }
                }

                // Now we are ready for the given element.
                // so now emit the saved prefix definitions.
                if (savedPrefixDefinitions != null)
                {
                    for (int i = 0; i < savedPrefixDefinitions.Count; i++)
                    {
                        yield return(savedPrefixDefinitions[i]);
                    }
                    if (ProvideLineInfo)
                    {
                        yield return(Logic_LineInfo());
                    }
                }

                if (nodeType == ScannerNodeType.TEXT)
                {
                    XamlText text        = _xamlScanner.TextContent;
                    string   trimmed     = Logic_ApplyFinalTextTrimming(text);
                    bool     isXDataText = _xamlScanner.IsXDataText;
                    _xamlScanner.Read();
                    if (ProvideLineInfo)
                    {
                        yield return(Logic_LineInfo());
                    }

                    if (trimmed == string.Empty)
                    {
                        break;
                    }

                    if (isTextInitialization)
                    {
                        yield return(Logic_StartInitProperty(currentType));
                    }

                    if (isXDataText)
                    {
                        yield return(Logic_StartObject(XamlLanguage.XData, null));

                        XamlMember xDataTextProperty = XamlLanguage.XData.GetMember("Text");
                        yield return(Logic_EndOfAttributes());

                        yield return(Logic_StartMember(xDataTextProperty));
                    }

                    yield return(new XamlNode(XamlNodeType.Value, trimmed));

                    if (isXDataText)
                    {
                        yield return(Logic_EndMember());

                        yield return(Logic_EndObject());
                    }
                }
                else
                {
                    foreach (XamlNode node in P_Element())
                    {
                        yield return(node);
                    }
                }

                // If we are not in an items or unknown content property, then
                // there cannot be more objects or values that follow this content
                // (a singular property), and thus we can end this property now.
                if (!_context.CurrentInItemsProperty && !_context.CurrentInUnknownContent)
                {
                    yield return(Logic_EndMember());
                }
                break;
            } // end switch
        }
Beispiel #36
0
        private static ConstructorInfo SelectConstructor(XamlType xamlType, int count)
        {
            var declaredConstructors = xamlType.UnderlyingType.GetTypeInfo().DeclaredConstructors;

            return(declaredConstructors.First(info => info.GetParameters().Length == count));
        }
Beispiel #37
0
 /// <summary>
 ///     Initializes a new instance of the
 ///     System.Xaml.Schema.XamlValueConverter`1 class, based on
 ///     a
 ///     converter implementing <see cref="System.Type" /> and the
 ///     target/destination type of the
 ///     System.Xaml.Schema.XamlValueConverter`1.
 /// </summary>
 /// <param name="converterType">
 ///     The <see cref="System.Type" /> that implements
 ///     the converter behavior.
 /// </param>
 /// <param name="targetType">
 ///     The target/destination
 ///     <see cref="System.Xaml.XamlType" /> of the
 ///     System.Xaml.Schema.XamlValueConverter`1.
 /// </param>
 public CustomResourceLoader(Type converterType, XamlType targetType) :
     base(converterType, targetType)
 {
     Logger.Warn($"{nameof ( CustomResourceLoader )} - {converterType} - {targetType}");
 }
Beispiel #38
0
 public PropertyInfo GetPropertyByName(XamlType declaringType, string propertyName)
 => GetPropertyByName(FindType(declaringType), propertyName);
Beispiel #39
0
 public XamlMainObjectNode(XamlType xamlType)
     : base(xamlType)
 {
 }
 public XamlBindingExtensionObjectNode(XamlType xamlType)
     : base(xamlType)
 {
 }
        public override void WriteStartObject(XamlType type)
        {
            if (type.UnderlyingType == typeof(string))
            {
                isWritingElementStyleString = true;
            }
            // this is the top-level object
            if (this.currentDepth == 0)
            {
                if (!this.debugSymbolNamespaceAdded)
                {
                    string sadsNamespaceAlias = GenerateNamespaceAlias(NameSpaces.DebugSymbolPrefix);
                    this.WriteNamespace(new NamespaceDeclaration(NameSpaces.DebugSymbol, sadsNamespaceAlias));
                    this.debugSymbolNamespaceAdded = true;
                }

                // we need to write MC namespace if any namespaces need to be ignored
                if (this.namespacesToIgnore.Count > 0)
                {
                    string mcNamespaceAlias = GenerateNamespaceAlias(NameSpaces.McPrefix);
                    this.WriteNamespace(new NamespaceDeclaration(NameSpaces.Mc, mcNamespaceAlias));
                }


                if (this.localNamespacesWithAssemblyInfo != null)
                {
                    foreach (NamespaceDeclaration xamlNamespace in this.localNamespacesWithAssemblyInfo)
                    {
                        if ((this.emittedNamespacesInLocalAssembly == null) || (!this.emittedNamespacesInLocalAssembly.Contains(xamlNamespace.Namespace)))
                        {
                            base.WriteNamespace(xamlNamespace);
                        }
                    }
                }

                if ((type.UnderlyingType == typeof(Activity)) ||
                    (type.IsGeneric && type.UnderlyingType != null && type.UnderlyingType.GetGenericTypeDefinition() == typeof(Activity <>)) ||
                    (type.UnderlyingType == typeof(WorkflowService)))
                {   // Exist ActivityBuilder, DebugSymbolObject will be inserted at the depth == 1.
                    debugSymbolDepth = 1;
                }
                else
                {
                    debugSymbolDepth = 0;
                }
            }

            if (this.currentDepth == debugSymbolDepth)
            {
                if (type.UnderlyingType != null && type.UnderlyingType.IsSubclassOf(typeof(Activity)) && this.shouldWriteDebugSymbol)
                {
                    this.writeDebugSymbol = true;
                }
            }

            base.WriteStartObject(type);

            if (this.currentDepth == 0)
            {
                // we need to add Ignore attribute for all namespaces which we don't want to load assemblies for
                // this has to be done after WriteStartObject
                if (this.namespacesToIgnore.Count > 0)
                {
                    string nsString = null;
                    foreach (string ns in this.namespacesToIgnore)
                    {
                        if (nsString == null)
                        {
                            nsString = ns;
                        }
                        else
                        {
                            nsString += " " + ns;
                        }
                    }

                    XamlDirective ignorable = new XamlDirective(NameSpaces.Mc, "Ignorable");
                    base.WriteStartMember(ignorable);
                    base.WriteValue(nsString);
                    base.WriteEndMember();
                    this.namespacesToIgnore.Clear();
                }
            }

            ++this.currentDepth;
        }
Beispiel #42
0
 public override bool CanAssignTo(XamlType xamlType)
 {
     return(!_notAssignable.Contains(xamlType.UnderlyingType));
 }
Beispiel #43
0
        private XAML3.INameScopeDictionary HuntAroundForARootNameScope(ObjectWriterFrame rootFrame)
        {
            Debug.Assert(rootFrame.Depth == 1);

            object inst = rootFrame.Instance;

            if (inst == null && rootFrame.XamlType.IsNameScope)
            {
                throw new InvalidOperationException(SR.Get(SRID.NameScopeOnRootInstance));
            }

            XAML3.INameScopeDictionary nameScopeDictionary = null;

            nameScopeDictionary = inst as XAML3.INameScopeDictionary;

            if (nameScopeDictionary == null)
            {
                XAML3.INameScope nameScope = inst as XAML3.INameScope;
                if (nameScope != null)
                {
                    nameScopeDictionary = new NameScopeDictionary(nameScope);
                }
            }

            // If the root instance isn't a name scope
            // then perhaps it designated a property as the name scope.
            if (nameScopeDictionary == null)
            {
                XamlType xamlType = rootFrame.XamlType;
                if (xamlType.UnderlyingType != null)
                {
                    // Get the Name Scope Property (from attribute on the class)
                    XamlMember nameScopeProperty = TypeReflector.LookupNameScopeProperty(xamlType);
                    if (nameScopeProperty != null)
                    {
                        // Read the value of the property.  If it is an object we are good.
                        // if it is null create a stock name scope dictionary object and assign it back.
                        XAML3.INameScope nameScope = (XAML3.INameScope)_runtime.GetValue(inst, nameScopeProperty, false);
                        if (nameScope == null)
                        {
#if TARGETTING35SP1
                            nameScopeDictionary = new NameScopeDictionary(new NameScope());
#else
                            nameScopeDictionary = new NameScope();
#endif
                            _runtime.SetValue(inst, nameScopeProperty, nameScopeDictionary);
                        }
                        else
                        {
                            nameScopeDictionary = nameScope as XAML3.INameScopeDictionary;
                            if (nameScopeDictionary == null)
                            {
                                nameScopeDictionary = new NameScopeDictionary(nameScope);
                            }
                        }
                    }
                }
            }

            if (nameScopeDictionary == null && _settings != null &&
                _settings.RegisterNamesOnExternalNamescope)
            {
                ObjectWriterFrame frameZero = (ObjectWriterFrame)rootFrame.Previous;
                nameScopeDictionary = frameZero.NameScopeDictionary;
            }

            // Otherwise we still need a namescope at the root of the parse
            // for our own usage.  For IXamlNameResolver() to use.
            if (nameScopeDictionary == null)
            {
#if TARGETTING35SP1
                nameScopeDictionary = new NameScopeDictionary(new NameScope());
#else
                nameScopeDictionary = new NameScope();
#endif
            }

            rootFrame.NameScopeDictionary = nameScopeDictionary;
            return(nameScopeDictionary);
        }
Beispiel #44
0
 protected PropertyXamlMember(string name, XamlType declaringType, bool isAttachable)
     : base(name, declaringType, isAttachable)
 {
 }
Beispiel #45
0
        //private readonly ProjectDataItemBase _selectedProject;

        //public XamlFileParser(ProjectDataItemBase selectedProject)
        //{
        //    _selectedProject = selectedProject;
        //}

        //public async Task CollectStringsAsync()
        //{
        //    //_selectedProject.UiFiles.Clear();
        //    foreach (FileDataItemBase fileDataItem in _selectedProject.AllFiles)
        //    {
        //        if (fileDataItem.ItemType == FileDataItemBase.EItemType.XamlPage
        //            || fileDataItem.ItemType == FileDataItemBase.EItemType.XamlApplicationDefinition)
        //        {
        //            fileDataItem.Translations.Clear();
        //            XamlRootNode root = Parse(fileDataItem.FullPath);
        //            //XamlNodeTracer.TraceNode(root);
        //            XamlNodeWalker nodeWalker = new XamlNodeWalker();

        //            XamlTranslationWriter translationTracer = new XamlTranslationWriter(fileDataItem);
        //            XamlCodeTextVisitor visitor = new XamlCodeTextVisitor(translationTracer);
        //            nodeWalker.Visit(root, visitor);
        //        }

        //        await Task.Delay(10);
        //    }
        //}

        public static XamlRootNode Parse(string fullPath)
        {
            int          xamlObjectCount = 0;
            XamlRootNode root            = new XamlRootNode();

            try
            {
                //XamlNamespaces namespaces = new XamlNamespaces();
                //root.Children.Add(namespaces);
                Stack <XamlObjectNode>              objStack           = new Stack <XamlObjectNode>();
                Stack <XamlStartMemberTempData>     memberStack        = new Stack <XamlStartMemberTempData>();
                Stack <XamlExtensionObjectNodeBase> extensionsObjStack = new Stack <XamlExtensionObjectNodeBase>();

                XamlStartMemberTempData startMemberTempData = null;
                XamlValueTempData       valueTempData       = null;
                //bool wasGetObject = false;

                XmlReaderSettings readerSettings = new XmlReaderSettings();
                readerSettings.IgnoreComments = false;

                XamlXmlReaderSettings xamlReaderSettings = new XamlXmlReaderSettings();
                xamlReaderSettings.IgnoreUidsOnPropertyElements = false;
                xamlReaderSettings.ProvideLineInfo = true;

                XmlReader     xmlReader  = XmlReader.Create(fullPath, readerSettings);
                XamlXmlReader xamlReader = new XamlXmlReader(xmlReader, xamlReaderSettings);

                xamlReader.Read();
                while (!xamlReader.IsEof)
                {
                    XamlNodeType nodeType = xamlReader.NodeType;
                    Trace.WriteLine($"--{xamlReader.LineNumber}:{xamlReader.LinePosition}.{nodeType}--");
                    switch (nodeType)
                    {
                    case XamlNodeType.None:
                        break;

                    case XamlNodeType.StartObject:
                    {
                        //XamlBindingObjectNode
                        if (xamlObjectCount == 0)
                        {
                            XamlMainObjectNode mainObject = new XamlMainObjectNode(xamlReader.Type)
                            {
                                LineNumberStart   = xamlReader.LineNumber,
                                LinePositionStart = xamlReader.LinePosition
                            };
                            root.MainObject = mainObject;
                            objStack.Push(mainObject);
                        }
                        else
                        {
                            XamlObjectNode obj;
                            if (xamlReader.Type.Name == XamlBindingExtensionObjectNode.Ident)
                            {
                                obj = new XamlBindingExtensionObjectNode(xamlReader.Type);
                                extensionsObjStack.Push((XamlExtensionObjectNodeBase)obj);
                            }
                            else if (xamlReader.Type.Name == XamlTemplateBindingExtensionObjectNode.Ident)
                            {
                                obj = new XamlTemplateBindingExtensionObjectNode(xamlReader.Type);
                                extensionsObjStack.Push((XamlExtensionObjectNodeBase)obj);
                            }
                            else if (xamlReader.Type.Name == XamlDynResObjectNode.Ident)
                            {
                                obj = new XamlDynResObjectNode(xamlReader.Type);
                                extensionsObjStack.Push((XamlExtensionObjectNodeBase)obj);
                            }
                            else if (xamlReader.Type.Name == XamlTypeExtensionObjectNode.Ident)
                            {
                                obj = new XamlTypeExtensionObjectNode(xamlReader.Type);
                                extensionsObjStack.Push((XamlExtensionObjectNodeBase)obj);
                            }
                            else if (xamlReader.Type.Name == XamlStatResObjectNode.Ident)
                            {
                                obj = new XamlStatResObjectNode(xamlReader.Type);
                                extensionsObjStack.Push((XamlExtensionObjectNodeBase)obj);
                            }
                            else if (xamlReader.Type.Name == XamlStaticExtensionObjectNode.Ident)
                            {
                                obj = new XamlStaticExtensionObjectNode(xamlReader.Type);
                                extensionsObjStack.Push((XamlExtensionObjectNodeBase)obj);
                            }
                            else
                            {
                                obj = new XamlObjectNode(xamlReader.Type);
                                //if (memberStack.Count == 0)
                                {
                                    if (objStack.Count > 0)
                                    {
                                        XamlObjectNode objNode = objStack.Peek();
                                        obj.Parent = objNode;
                                        objNode.Children.Add(obj);
                                    }
                                }
                                //else
                                //{
                                //    XamlStartMemberTempData memberTempData = memberStack.Peek();
                                //    XamlObjectNode obj2 = new XamlObjectNode(memberTempData.Type){Name = memberTempData.Name};
                                //    obj2.Children.Add(obj);
                                //}
                            }

                            obj.LineNumberStart   = xamlReader.LineNumber;
                            obj.LinePositionStart = xamlReader.LinePosition;

                            //root.Children.Add(obj);
                            objStack.Push(obj);
                        }

                        XamlSchemaContext schemaContext = xamlReader.SchemaContext;
                        XamlType          readerType    = xamlReader.Type;
                        Trace.WriteLine($"{xamlReader.Type},{xamlReader.Type.ItemType}---{readerType.Name}");
                        xamlObjectCount++;
                    }
                    break;

                    case XamlNodeType.GetObject:
                    {
                        XamlObjectNode obj;

                        //if (startMemberTempData.Name == ResourcesSectionName)
                        //{
                        //    obj = root.Resources;
                        //}
                        //else
                        //{
                        //    obj = new XamlObjectNode(startMemberTempData.Type) { Name = startMemberTempData.Name };
                        //    if (objStack.Count > 0)
                        //    {
                        //        XamlObjectNode objNode = objStack.Peek();
                        //        objNode.Children.Add(obj);
                        //    }
                        //}

                        //obj.LinePositionStart = xamlReader.LinePosition;
                        //obj.LineNumberStart = xamlReader.LineNumber;
                        //objStack.Push(obj);
                    }
                        //wasGetObject = true;
                        break;

                    case XamlNodeType.EndObject:
                    {
                        if (objStack.Count > 0)
                        {
                            //remove current object
                            XamlObjectNode objNode = objStack.Pop();

                            objNode.LineNumberEnd   = xamlReader.LineNumber;
                            objNode.LinePositionEnd = xamlReader.LinePosition;
                            //if (objNode.NodeType == XamlNodeBase.ENodeType.BindingObject)
                            //{
                            //    bindingStack
                            //}
                        }
                        else
                        {
                            //for breakpoint
                            Trace.WriteLine("Error obj stack is empty");
                        }
                    }
                    break;

                    case XamlNodeType.StartMember:
                    {
                        //if (wasGetObject)
                        //{
                        //    break;
                        //}
                        XamlMember member        = xamlReader.Member;
                        XamlType   memberType    = member.Type;
                        XamlType   declaringType = member.DeclaringType;
                        if (declaringType != null && member.Name == ResourcesSectionName)
                        {
                            XamlResourceCollectionNode xamlResourceCollectionNode = new XamlResourceCollectionNode(member.Type);
                            //root.Resources = new List<XamlNodeBase>();
                            root.MainObject.Resources = xamlResourceCollectionNode;

                            xamlResourceCollectionNode.Name = member.Name;
                            xamlResourceCollectionNode.LinePositionStart = xamlReader.LinePosition;
                            xamlResourceCollectionNode.LineNumberStart   = xamlReader.LineNumber;

                            xamlResourceCollectionNode.Parent = root.MainObject;
                            root.MainObject.Children.Add(xamlResourceCollectionNode);
                            objStack.Push(xamlResourceCollectionNode);
                        }

                        IList <string> xamlNamespaces = member.GetXamlNamespaces();
                        string         namespacesStr  = String.Join(";", xamlNamespaces);
                        Trace.WriteLine($"{namespacesStr} ___ {memberType}({declaringType}).{member.Name} === {member}");
                        startMemberTempData                   = new XamlStartMemberTempData();
                        startMemberTempData.Type              = member.Type;
                        startMemberTempData.Name              = member.Name;
                        startMemberTempData.DeclaringType     = member.DeclaringType;
                        startMemberTempData.IsWritePublic     = member.IsWritePublic;
                        startMemberTempData.LineNumberStart   = xamlReader.LineNumber;
                        startMemberTempData.LinePositionStart = xamlReader.LinePosition;
                        valueTempData = null;
                        memberStack.Push(startMemberTempData);
                    }

                    break;

                    case XamlNodeType.EndMember:
                    {
                        if (startMemberTempData != null)
                        {
                            if (valueTempData != null)
                            {
                                //remove last member
                                if (memberStack.Count > 0)
                                {
                                    XamlStartMemberTempData memberTempData = memberStack.Pop();
                                }

                                if (startMemberTempData.Name == "base")
                                {
                                    root.Path = valueTempData.Value?.ToString();
                                }
                                else
                                {
                                    XamlAttribute attribute = new XamlAttribute(
                                        startMemberTempData.Type,
                                        startMemberTempData.Name,
                                        valueTempData.Value);

                                    attribute.LineNumberStart   = startMemberTempData.LineNumberStart;
                                    attribute.LinePositionStart = startMemberTempData.LinePositionStart;
                                    attribute.LineNumberEnd     = xamlReader.LineNumber;
                                    attribute.LinePositionEnd   = xamlReader.LinePosition;
                                    attribute.DeclaringType     = startMemberTempData.DeclaringType;
                                    attribute.IsWritePublic     = startMemberTempData.IsWritePublic;
                                    if (objStack.Count > 0)
                                    {
                                        XamlObjectNode objNode = objStack.Peek();

                                        AddAttribute(attribute, objNode);
                                    }
                                }

                                valueTempData = null;
                            }
                            else
                            {
                                AddAttributesWithObjValue(memberStack, extensionsObjStack, objStack);
                            }

                            startMemberTempData = null;
                        }
                        else
                        {
                            AddAttributesWithObjValue(memberStack, extensionsObjStack, objStack);
                        }
                    }

                    break;

                    case XamlNodeType.Value:
                    {
                        object value = xamlReader.Value;
                        Trace.WriteLine($"{value.GetType()}-{value}");
                        valueTempData = new XamlValueTempData {
                            Type = value.GetType(), Value = value
                        };
                    }

                    break;

                    case XamlNodeType.NamespaceDeclaration:
                    {
                        if (root.Namespaces == null)
                        {
                            root.Namespaces = new List <XamlNamespace>();
                        }

                        NamespaceDeclaration namespaceDeclaration = xamlReader.Namespace;
                        XamlNamespace        ns = new XamlNamespace(namespaceDeclaration.Prefix, namespaceDeclaration.Namespace)
                        {
                            LineNumberStart = xamlReader.LineNumber, LinePositionStart = xamlReader.LinePosition
                        };
                        Trace.WriteLine($"{namespaceDeclaration.Prefix}:{namespaceDeclaration.Namespace} ");
                        root.Namespaces.Add(ns);
                    }
                    break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    bool isNext = xamlReader.Read();
                }
                //XamlReader builderReader = ActivityXamlServices.CreateBuilderReader(xamlReader);
                //ActivityBuilder ab = XamlServices.Load(builderReader) as ActivityBuilder;

                //XmlWriterSettings writerSettings = new XmlWriterSettings { Indent = true };
                //XmlWriter xmlWriter = XmlWriter.Create(File.OpenWrite(args[1]), writerSettings);
                //XamlXmlWriter xamlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext());
                //XamlServices.Save(new ViewStateCleaningWriter(ActivityXamlServices.CreateBuilderWriter(xamlWriter)), ab);

                //Console.WriteLine("{0} written without viewstate information", args[1]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception encountered {0}", ex);
            }


            return(root);
        }
Beispiel #46
0
 public XamlTypeReference(XamlType type, int lineNo, int lineOffset)
 {
     Type       = type;
     LineNumber = lineNo;
     LineOffset = lineOffset;
 }
 public override void WriteStartObject(XamlType xamlType)
 {
     base.WriteStartObject(xamlType);
 }
Beispiel #48
0
        private IEnumerable <XamlNode> LogicStream_CheckForStartGetCollectionFromMember()
        {
            XamlType   currentType     = _context.CurrentType;
            XamlMember currentProperty = _context.CurrentMember;

            XamlType propertyType = currentProperty.Type;

            XamlType valueElementType = (_xamlScanner.NodeType == ScannerNodeType.TEXT)
                            ? XamlLanguage.String
                            : _xamlScanner.Type;

            if (propertyType.IsArray && _xamlScanner.Type != ArrayExtensionType)
            {
                IEnumerable <NamespaceDeclaration> newNamespaces = null;
                XamlTypeName           typeName       = new XamlTypeName(propertyType.ItemType);
                INamespacePrefixLookup prefixResolver = new NamespacePrefixLookup(out newNamespaces, _context.FindNamespaceByPrefix);
                string typeNameString = typeName.ToString(prefixResolver);    // SideEffects!!! prefixResolver will populate newNamespaces

                foreach (NamespaceDeclaration nsDecl in newNamespaces)
                {
                    yield return(new XamlNode(XamlNodeType.NamespaceDeclaration, nsDecl));
                }
                yield return(Logic_StartObject(ArrayExtensionType, null));

                _context.CurrentInImplicitArray = true;
                yield return(Logic_StartMember(ArrayTypeMember));

                yield return(new XamlNode(XamlNodeType.Value, typeNameString));

                yield return(Logic_EndMember());

                yield return(Logic_EndOfAttributes());

                yield return(Logic_StartMember(ItemsTypeMember));

                currentType     = _context.CurrentType;
                currentProperty = _context.CurrentMember;
                propertyType    = currentProperty.Type;
            }

            // Now Consider inserting special preamble to "Get" the collection:
            //   . GO
            //   . . SM _items
            if (!currentProperty.IsDirective && (propertyType.IsCollection || propertyType.IsDictionary))
            {
                bool emitPreamble = false;

                // If the collection property is Readonly then "Get" the collection.
                if (currentProperty.IsReadOnly || !_context.CurrentMemberIsWriteVisible())
                {
                    emitPreamble = true;
                }
                // If the collection is R/W and there is a type converter and we have Text
                // use the type converter rather than the GO; SM _items;
                else if (propertyType.TypeConverter != null && !currentProperty.IsReadOnly &&
                         _xamlScanner.NodeType == ScannerNodeType.TEXT)
                {
                    emitPreamble = false;
                }
                // Or if the Value (this is the first value in the collection)
                // isn't assignable to the Collection then "Get" the collection.
                else if (valueElementType == null || !valueElementType.CanAssignTo(propertyType))
                {
                    if (valueElementType != null)
                    {
                        // Unless: the Value is a Markup extension, in which case it is
                        // assumed that the ProvideValue() type will be AssignableFrom
                        // or If the next object has an x:Key in which case it must be
                        // a dictionary entry.
                        // so Don't "Get" the collection.
                        if (!valueElementType.IsMarkupExtension || _xamlScanner.HasKeyAttribute)
                        {
                            emitPreamble = true;
                        }
                        // Except: the Array Extension can never return a dictionary
                        // so for Array Extension do "Get" the collection.
                        // Note Array Extension would be suitable for List Collections
                        // Note: a fully validating parser should look at MarkupExtensionReturnType
                        // for this choice, there might be other MarkupExtensions that fit this.
                        else if (valueElementType == XamlLanguage.Array)
                        {
                            emitPreamble = true;
                        }
                    }
                }
                if (emitPreamble)
                {
                    yield return(Logic_StartGetObjectFromMember(propertyType));

                    yield return(Logic_StartItemsProperty(propertyType));
                }
            }
        }
 public XamlTypeInvoker(XamlType type)
 {
     _xamlType = type ?? throw new ArgumentNullException(nameof(type));
 }
Beispiel #50
0
        private IEnumerable <Instruction> ParseProperties(IEnumerable <PropertyOption> options, XamlType xamlType)
        {
            foreach (var option in options)
            {
                var member = xamlType.GetMember(option.Property);
                yield return(Inject.StartOfMember(member));


                var stringNode = option.Value as StringNode;
                if (stringNode != null)
                {
                    yield return(Inject.Value(stringNode.Value));
                }

                var markupExtensionNode = option.Value as MarkupExtensionNode;
                if (markupExtensionNode != null)
                {
                    foreach (var xamlInstruction in ParseMarkupExtensionNode(markupExtensionNode))
                    {
                        yield return(xamlInstruction);
                    }
                }

                yield return(Inject.EndOfMember());
            }
        }
Beispiel #51
0
        ////////////////////////////////
        // MarkupExtension ::= '{' TYPENAME Arguments? '}'
        //
        private IEnumerable <XamlNode> P_MarkupExtension(Found f)
        {
            // MarkupExtension ::= @'{' TYPENAME Arguments? '}'
            if (Expect(MeTokenType.Open, "MarkupExtension ::= @'{' Expr '}'"))
            {
                NextToken();

                // MarkupExtension ::= '{' @TYPENAME Arguments? '}'
                if (_tokenizer.Token == MeTokenType.TypeName)
                {
                    XamlType xamlType = _tokenizer.TokenType;

                    yield return(Logic_StartElement(xamlType, _tokenizer.Namespace));

                    NextToken();

                    // MarkupExtension ::= '{' TYPENAME @(Arguments)? '}'
                    Found f2 = new Found();
                    switch (_tokenizer.Token)
                    {
                    // MarkupExtension ::= '{' TYPENAME (Arguments)? @'}'
                    case MeTokenType.Close:  // legal, Arguments is optional
                        yield return(Logic_EndObject());

                        NextToken();
                        f.found = true;
                        break;

                    case MeTokenType.String:
                    case MeTokenType.QuotedMarkupExtension:
                    case MeTokenType.PropertyName:
                    case MeTokenType.Open:
                        // MarkupExtension ::= '{' TYPENAME (@Arguments)? '}'
                        foreach (XamlNode node in P_Arguments(f2))
                        {
                            yield return(node);
                        }
                        break;

                    default:
                        SetBrokenRuleString("MarkupExtension ::= '{' TYPENAME @(Arguments)? '}'");
                        break;
                    }

                    if (f2.found)
                    {
                        if (Expect(MeTokenType.Close, "MarkupExtension ::= '{' TYPENAME (Arguments)? @'}'"))
                        {
                            yield return(Logic_EndObject());

                            f.found = true;
                            NextToken();
                        }
                    }
                }
                else
                {
                    SetBrokenRuleString("MarkupExtension ::= '{' @TYPENAME (Arguments)? '}'");
                }
            }
        }
 public DynamicActivityXamlMember(PropertyDescriptor property, XamlType declaringType)
     : base(property, declaringType)
 {
 }
Beispiel #53
0
        ///////////////////////////
        //  ElementBody ::= ATTRIBUTE* ( PropertyElement | ElementContent+ )* ENDTAG
        //
        public IEnumerable <XamlNode> P_ElementBody()
        {
            while (_xamlScanner.NodeType == ScannerNodeType.ATTRIBUTE)
            {
                foreach (XamlNode node in LogicStream_Attribute())
                {
                    yield return(node);
                }
                _xamlScanner.Read();
                if (ProvideLineInfo)
                {
                    yield return(Logic_LineInfo());
                }
            }

            yield return(Logic_EndOfAttributes());

            bool doneWithElementContent = false;
            bool hasContent             = false;

            do
            {
                ScannerNodeType nodeType = _xamlScanner.NodeType;
                switch (nodeType)
                {
                case ScannerNodeType.PROPERTYELEMENT:
                case ScannerNodeType.EMPTYPROPERTYELEMENT:
                    hasContent = true;
                    foreach (XamlNode node in P_PropertyElement())
                    {
                        yield return(node);
                    }
                    break;

                case ScannerNodeType.PREFIXDEFINITION:
                case ScannerNodeType.ELEMENT:
                case ScannerNodeType.EMPTYELEMENT:
                case ScannerNodeType.TEXT:
                    hasContent = true;
                    do
                    {
                        foreach (XamlNode node in P_ElementContent())
                        {
                            yield return(node);
                        }
                        nodeType = _xamlScanner.NodeType;
                    } while (nodeType == ScannerNodeType.PREFIXDEFINITION ||
                             nodeType == ScannerNodeType.ELEMENT ||
                             nodeType == ScannerNodeType.EMPTYELEMENT ||
                             nodeType == ScannerNodeType.TEXT);

                    // If the above started a container directive or an unknown content property, then end the collection.
                    if (_context.CurrentInItemsProperty || _context.CurrentInInitProperty || _context.CurrentInUnknownContent)
                    {
                        yield return(Logic_EndMember()); // Container or unknown content property.

                        if (_context.CurrentInCollectionFromMember)
                        {
                            yield return(Logic_EndObject());   // Getter pseudo Object

                            yield return(Logic_EndMember());   // Content Property

                            _context.CurrentInCollectionFromMember = false;
                            if (_context.CurrentInImplicitArray)
                            {
                                _context.CurrentInImplicitArray = false;
                                yield return(Logic_EndObject());

                                yield return(Logic_EndMember());
                            }
                        }
                    }
                    break;

                case ScannerNodeType.ENDTAG:
                    // <Foo></Foo> if foo has no default constructor we need to output SM _Initialization V "" EM
                    XamlType currentType      = _context.CurrentType;
                    bool     hasTypeConverter = currentType.TypeConverter != null;
                    bool     isConstructable  = currentType.IsConstructible && !currentType.ConstructionRequiresArguments;
                    if (!hasContent && hasTypeConverter && !isConstructable)
                    {
                        yield return(Logic_StartInitProperty(currentType));

                        yield return(new XamlNode(XamlNodeType.Value, string.Empty));

                        yield return(Logic_EndMember());
                    }
                    doneWithElementContent = true;
                    break;

                default:
                    doneWithElementContent = true;
                    break;
                }
            } while (!doneWithElementContent);

            if (_xamlScanner.NodeType != ScannerNodeType.ENDTAG)
            {
                throw new XamlUnexpectedParseException(_xamlScanner, _xamlScanner.NodeType,
                                                       SR.Get(SRID.ElementBodyRuleException));
            }
            yield return(Logic_EndObject());

            _xamlScanner.Read();
            if (ProvideLineInfo)
            {
                yield return(Logic_LineInfo());
            }
        }
Beispiel #54
0
 public XamlDuplicateMemberException(XamlMember member, XamlType type)
     : base(SR.Get(SRID.DuplicateMemberSet, (member != null) ? member.Name : null, (type != null) ? type.Name : null))
 {
     DuplicateMember = member;
     ParentType      = type;
 }
 public XamlTypeValueConverter(Type converterType, XamlType targetType, string name)
     : base(converterType, targetType, name)
 {
 }
Beispiel #56
0
 protected override object CreateInstanceWithCtor(XamlType xamlType, object[] args)
 {
     DemandXamlLoadPermission();
     return(CreateInstanceWithCtor(xamlType.UnderlyingType, args));
 }
 public XamlValueConverter(Type converterType, XamlType targetType)
     : this(converterType, targetType, null)
 {
 }
        // This method reads a ViewStateData node from the xaml nodestream. It outputs the Id property into viewStateId
        // and the attached viewstate related properties in viewStateNodes. The input reader is positioned on a
        // ViewStateData node within ViewStateManager.
        static void ReadViewState(XamlType viewStateType, XamlReader xamlReader, out string viewStateId, out XamlNodeList viewStateNodes, out SourceLocation sourceLocation)
        {
            int  globalMemberLevel = 0;
            bool skippingUnexpectedAttachedProperty      = false;
            int  skippingUnexpectedAttachedPropertyLevel = 0;

            viewStateId    = null;
            viewStateNodes = new XamlNodeList(viewStateType.SchemaContext);
            sourceLocation = null;

            Stack <Frame> objectNodes = new Stack <Frame>();
            XamlMember    idMember    = new XamlMember(typeof(ViewStateData).GetProperty("Id"), xamlReader.SchemaContext);

            int[] viewStateDataSourceLocation = new int[4];
            int   sourceLocationIndex         = -1;

            IXamlLineInfo         lineInfo         = xamlReader as IXamlLineInfo;
            IXamlLineInfoConsumer lineInfoComsumer = viewStateNodes.Writer as IXamlLineInfoConsumer;
            bool shouldPassLineInfo = lineInfo != null && lineInfo.HasLineInfo && lineInfoComsumer != null && lineInfoComsumer.ShouldProvideLineInfo;

            while (xamlReader.Read())
            {
                bool skipWritingToNodeList = false;
                switch (xamlReader.NodeType)
                {
                case XamlNodeType.StartObject:
                    if (xamlReader.Type.Equals(viewStateType))
                    {
                        skipWritingToNodeList = true;
                    }
                    objectNodes.Push(new Frame {
                        Type = xamlReader.Type
                    });
                    break;

                case XamlNodeType.GetObject:
                    objectNodes.Push(new Frame {
                        Type = null
                    });
                    break;

                case XamlNodeType.StartMember:
                    globalMemberLevel++;
                    if (xamlReader.Member.Equals(idMember))
                    {
                        XamlReader idNode = xamlReader.ReadSubtree();
                        while (idNode.Read())
                        {
                            if (idNode.NodeType == XamlNodeType.Value)
                            {
                                viewStateId = idNode.Value as string;
                            }
                        }
                    }
                    // The xamlReader.ReadSubtree and subsequent while loop to get the Id member
                    // has moved the xamlReader forward to the next member. We need to check to see
                    // if it is an Attached Property that we care about. If it isn't then we need to
                    // skip it and not put it in the resulting XamlNodeList.
                    if (globalMemberLevel == 1 && !IsAttachablePropertyForConvert(xamlReader))
                    {
                        skippingUnexpectedAttachedProperty = true;
                    }
                    if (skippingUnexpectedAttachedProperty)
                    {
                        skippingUnexpectedAttachedPropertyLevel++;
                    }

                    sourceLocationIndex = GetViewStateDataSourceLocationIndexFromCurrentReader(xamlReader);
                    break;

                case XamlNodeType.EndMember:
                    globalMemberLevel--;
                    if (skippingUnexpectedAttachedProperty)
                    {
                        skippingUnexpectedAttachedPropertyLevel--;
                    }
                    break;

                case XamlNodeType.Value:
                    if (xamlReader.Value is int &&
                        sourceLocationIndex >= 0 &&
                        sourceLocationIndex < viewStateDataSourceLocation.Length)
                    {
                        viewStateDataSourceLocation[sourceLocationIndex] = (int)xamlReader.Value;
                    }

                    break;

                case XamlNodeType.EndObject:
                    Frame objectNode = objectNodes.Pop();
                    if (objectNode.Type != null && objectNode.Type.Equals(viewStateType))
                    {
                        skipWritingToNodeList = true;
                        // The ViewStateData's source location should be valid, because
                        // before each EndObject, its SourceLocation is injected.
                        // If not, an exception will be thrown from constructor
                        // of SourceLocation.
                        sourceLocation = new SourceLocation(null,
                                                            viewStateDataSourceLocation[0],
                                                            viewStateDataSourceLocation[1],
                                                            viewStateDataSourceLocation[2],
                                                            viewStateDataSourceLocation[3]
                                                            );
                    }

                    Array.Clear(viewStateDataSourceLocation, 0, viewStateDataSourceLocation.Length);
                    break;
                }
                ;

                if (!skipWritingToNodeList && !skippingUnexpectedAttachedProperty)
                {
                    if (shouldPassLineInfo)
                    {
                        lineInfoComsumer.SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition);
                    }

                    viewStateNodes.Writer.WriteNode(xamlReader);
                }

                if (skippingUnexpectedAttachedPropertyLevel == 0)
                {
                    skippingUnexpectedAttachedProperty = false;
                }
            }
            viewStateNodes.Writer.Close();
        }
Beispiel #59
0
 public AvaloniaPropertyXamlMember(AvaloniaProperty property, XamlType type) :
     base(property.Name, type, false)
 {
     Property = property;
 }
 public XamlXmlWriterTest()
 {
     xt  = new XamlType(typeof(string), sctx);
     xt2 = new XamlType(typeof(List <int>), sctx);
     xm  = new XamlMember(str_len, sctx);
 }