/// <summary>
        /// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
        /// </summary>
        /// <param name="underlyingType">The underlying type for the contract.</param>
        public JsonArrayContract(Type underlyingType)
            : base(underlyingType)
        {
            ContractType = JsonContractType.Array;

            if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection <>), out _genericCollectionDefinitionType))
            {
                CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
            }
            else if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable <>))
            {
                _genericCollectionDefinitionType = typeof(IEnumerable <>);
                CollectionItemType = underlyingType.GetGenericArguments()[0];
            }
            else
            {
                CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
            }

            if (CollectionItemType != null)
            {
                _isCollectionItemTypeNullableType = ReflectionUtils.IsNullableType(CollectionItemType);
            }

            if (IsTypeGenericCollectionInterface(UnderlyingType))
            {
                CreatedType = ReflectionUtils.MakeGenericType(typeof(List <>), CollectionItemType);
            }

            IsMultidimensionalArray = (UnderlyingType.IsArray && UnderlyingType.GetArrayRank() > 1);
        }
Exemple #2
0
        protected override XamlValueConverter <System.ComponentModel.TypeConverter> LookupTypeConverter()
        {
            if (typeConverter != null)
            {
                return(typeConverter);
            }
            var typeConverterAttrib = UnderlyingType.GetCustomAttribute <Eto.TypeConverterAttribute>();

            if (typeConverterAttrib != null)
            {
                var converterType = Type.GetType(typeConverterAttrib.ConverterTypeName);
                if (converterType != null)
                {
                    typeConverter = new EtoValueConverter(converterType, this);
                }
            }
            if (typeof(MulticastDelegate).IsAssignableFrom(UnderlyingType))
            {
                var context = SchemaContext as EtoXamlSchemaContext;
                if (context.DesignMode)
                {
                    return(null);
                }
            }


            if (typeConverter == null)
            {
                // convert from Eto.TypeConverter to System.ComponentModel.TypeConverter
                typeConverter = base.LookupTypeConverter();
            }
            return(typeConverter);
        }
Exemple #3
0
        private Enum GetUndefinedValue()
        {
            var undefinedEnumValueAttribute = AttributeUtility.GetCustomAttribute <UndefinedEnumValueAttribute> (UnderlyingType, false);

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

            if (!UnderlyingType.IsInstanceOfType(undefinedEnumValueAttribute.GetValue()))
            {
                throw new InvalidOperationException(
                          string.Format(
                              "The enum type '{0}' defines a '{1}' with an enum value that belongs to a different enum type.",
                              UnderlyingType,
                              typeof(UndefinedEnumValueAttribute)));
            }

            if (IsNullable)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "The property '{0}' defined on type '{1}' must not be nullable since the property's type already defines a '{2}'.",
                              Identifier,
                              PropertyInfo.DeclaringType,
                              typeof(UndefinedEnumValueAttribute)));
            }

            return(undefinedEnumValueAttribute.GetValue());
        }
        static EnumBinaryTranslation()
        {
            var underlying = Enum.GetUnderlyingType(typeof(E));

            if (underlying == typeof(int))
            {
                Underlying = UnderlyingType.Int;
            }
            else if (underlying == typeof(uint))
            {
                Underlying = UnderlyingType.UInt;
            }
            else if (underlying == typeof(long))
            {
                Underlying = UnderlyingType.Long;
            }
            else if (underlying == typeof(ulong))
            {
                Underlying = UnderlyingType.ULong;
            }
            else if (underlying == typeof(byte))
            {
                Underlying = UnderlyingType.Byte;
            }
            else
            {
                throw new NotImplementedException();
            }
        }
Exemple #5
0
        protected virtual AttachableMember LookupAttachableMember(string name)
        {
            var getter = UnderlyingType.GetTypeInfo().GetDeclaredMethod("Get" + name);
            var setter = UnderlyingType.GetTypeInfo().GetDeclaredMethod("Set" + name);

            return(TypeRepository.GetAttachableMember(name, getter, setter));
        }
Exemple #6
0
 // Returns properties that don't yet have corresponding XamlMembers
 internal IList <PropertyInfo> LookupRemainingProperties()
 {
     Debug.Assert(UnderlyingType != null, "Caller should check for UnderlyingType == null");
     Debug.Assert(_nonAttachableMemberCache != null, "Members property should have been invoked before this");
     PropertyInfo[] propList = UnderlyingType.GetProperties(AllProperties_BF);
     return(FilterProperties(propList, null, false));
 }
        protected override void GenerateInner(CodeGenerator generator)
        {
            Modifiers.Generate(generator);

            generator.Write(TokenType.Keyword, "enum");
            generator.Write(TokenType.Space, ' ');
            generator.OutputIdentifier(TokenType.TypeIdentifier, Name);

            if (UnderlyingType != null)
            {
                generator.Write(TokenType.Space, ' ');
                generator.Write(TokenType.Punctuation, ':');
                generator.Write(TokenType.Space, ' ');
                UnderlyingType.Generate(generator);
            }

            if (Members.Count > 0)
            {
                generator.WriteOpeningBrace();
                generator.Indent++;

                foreach (var member in Members)
                {
                    member.Generate(generator);
                }

                generator.Indent--;
                generator.WriteClosingBrace();
            }
            else
            {
                generator.WriteEmptyBlock();
            }
        }
Exemple #8
0
 public override int GetHashCode()
 {
     unchecked
     {
         return((UnderlyingType?.GetHashCode() ?? 0) * 397);
     }
 }
Exemple #9
0
        protected virtual IList <XamlType> LookupPositionalParameters(int parameterCount)
        {
            if (UnderlyingType == null /* || !IsMarkupExtension*/)            // see nunit tests...
            {
                return(null);
            }

            // check if there is applicable ConstructorArgumentAttribute.
            // If there is, then return its type.
            if (parameterCount == 1)
            {
                foreach (var xm in LookupAllMembers())
                {
                    var ca = xm.GetCustomAttributeProvider().GetCustomAttribute <ConstructorArgumentAttribute> (false);
                    if (ca != null)
                    {
                        return new XamlType [] { xm.Type }
                    }
                    ;
                }
            }

            var methods = (from m in UnderlyingType.GetTypeInfo().GetConstructors() where m.GetParameters().Length == parameterCount select m).ToArray();

            if (methods.Length == 1)
            {
                return((from p in methods [0].GetParameters() select SchemaContext.GetXamlType(p.ParameterType)).ToArray());
            }

            if (SchemaContext.SupportMarkupExtensionsWithDuplicateArity)
            {
                throw new NotSupportedException("The default LookupPositionalParameters implementation does not allow duplicate arity of markup extensions");
            }
            return(null);
        }
Exemple #10
0
        public TypeContainer AddProperties(Predicate <PropertyInfo> property)
        {
            List <PropertyContainer> foo = new List <PropertyContainer>();
            int cnt = 0;

            BindingFlags flags;

            if (includeInheritedProperties)
            {
                flags = BindingFlags.Public | BindingFlags.Instance;
            }
            else
            {
                flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
            }

            foreach (var c in UnderlyingType.GetProperties(flags).Where(x => property(x)))
            {
                if (c.IsWritable() || includeReadOnlyProperties)
                {
                    if (setFirstPropertyPrimaryKey && cnt == 0)
                    {
                        foo.Add(new PropertyContainer(c, cnt++, true));
                    }
                    else
                    {
                        foo.Add(new PropertyContainer(c, cnt++, false));
                    }
                }
            }
            Properties = foo;
            return(this);
        }
Exemple #11
0
        protected virtual bool LookupConstructionRequiresArguments()
        {
            if (UnderlyingType == null)
            {
                return(false);
            }

            var typeInfo = UnderlyingType.GetTypeInfo();

            if (typeInfo.IsValueType)
            {
                return(false);
            }

            // not sure if it is required, but MemberDefinition return true while they are abstract and it makes no sense.
            if (typeInfo.IsAbstract)
            {
                return(true);
            }

            // FIXME: probably some primitive types are treated as special.
            if (typeof(string).GetTypeInfo().IsAssignableFrom(typeInfo))
            {
                return(true);
            }
            if (typeof(TimeSpan) == UnderlyingType)
            {
                return(false);
            }


            return(typeInfo.GetConstructors().Where(r => r.IsPublic).All(r => r.GetParameters().Length > 0));
        }
Exemple #12
0
        public virtual bool CanAssignTo(XamlType xamlType)
        {
            if (xamlType == null)
            {
                return(false);
            }
            if (IsUnknown && xamlType.IsUnknown)
            {
                return(Equals(xamlType));
            }

            if (UnderlyingType == null)
            {
                return(xamlType == XamlLanguage.Object);
            }
            var ut = (xamlType.UnderlyingType ?? typeof(object)).GetTypeInfo();

            // if we are assigning to a nullable type, we allow null
            if (ut.IsValueType &&
                ut.IsGenericType &&
                ut.GetGenericTypeDefinition() == typeof(Nullable <>) &&
                this == XamlLanguage.Null)
            {
                return(true);
            }

            return(ut.IsAssignableFrom(UnderlyingType.GetTypeInfo()));
        }
        private static string GetFlagsEnumHintString(Type enumType)
        {
            Dictionary <UnderlyingType, List <string> > flagNamesByFlag = new Dictionary <UnderlyingType, List <string> >();
            UnderlyingType flag = (UnderlyingType)1;

            foreach (string name in Enum.GetNames(enumType))
            {
                UnderlyingType value = (UnderlyingType)Convert.ChangeType(Enum.Parse(enumType, name), typeof(UnderlyingType));
                while (value > flag)
                {
                    if (!flagNamesByFlag.ContainsKey(flag))
                    {
                        flagNamesByFlag.Add(flag, new List <string>());
                    }
                    flag <<= 1;
                }
                if (value == flag)
                {
                    if (!flagNamesByFlag.TryGetValue(flag, out List <string> names))
                    {
                        names = new List <string>();
                        flagNamesByFlag.Add(flag, names);
                    }
                    names.Add(name);
                }
            }
            return(string.Join(", ", flagNamesByFlag.Values.Select(flagNames => string.Join(" / ", flagNames))));
        }
Exemple #14
0
        protected virtual bool LookupConstructionRequiresArguments()
        {
            if (UnderlyingType == null)
            {
                return(false);
            }

            // not sure if it is required, but MemberDefinition return true while they are abstract and it makes no sense.
            if (UnderlyingType.IsAbstract)
            {
                return(true);
            }

            // FIXME: probably some primitive types are treated as special.
            switch (Type.GetTypeCode(UnderlyingType))
            {
            case TypeCode.String:
                return(true);

            case TypeCode.Object:
                if (UnderlyingType == typeof(TimeSpan))
                {
                    return(false);
                }
                break;

            default:
                return(false);
            }

            return(UnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null) == null);
        }
Exemple #15
0
        IEnumerable <XamlMember> DoLookupAllMembers()
        {
            // This is a hack that is likely required due to internal implementation difference in System.Uri. Our Uri has two readonly collection properties
            if (this == XamlLanguage.Uri)
            {
                yield break;
            }

            var bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

            foreach (var pi in UnderlyingType.GetProperties(bf))
            {
                if (pi.Name.Contains("."))                  // exclude explicit interface implementations.
                {
                    continue;
                }
                if (pi.CanRead && (pi.CanWrite || IsCollectionType(pi.PropertyType) || typeof(IXmlSerializable).IsAssignableFrom(pi.PropertyType)) && pi.GetIndexParameters().Length == 0)
                {
                    yield return(new XamlMember(pi, SchemaContext));
                }
            }
            foreach (var ei in UnderlyingType.GetEvents(bf))
            {
                yield return(new XamlMember(ei, SchemaContext));
            }
        }
        protected override bool SetValueInternal(object value, ValueUpdateSource updateSource)
        {
            bool result = false;

#if _DOTNET2
            NullableConverter nc = TypeConverter as NullableConverter;
            if ((value == null) || ((value != null) && UnderlyingType.IsInstanceOfType(value)) ||
                ((nc != null) && ((value == null) || nc.UnderlyingType.IsInstanceOfType(value))))
#else
            if ((value != null) && UnderlyingType.IsInstanceOfType(value))
#endif
            {
                UnderlyingValue = value;
                result          = true;
            }

            if (updateSource != ValueUpdateSource.FromChild)
            {
                if ((mOwnerEnumerator != null) &&   // mOwnerEnumerator could be null for the boolean of Property._enabledVariable
                    !mOwnerEnumerator.Property.Value.NoLinkWithChildren)
                {
                    PropertyTypeDescriptorContext context = GetTypeDescriptorContext(OwnerEnumerator);
                    if (TypeConverter.GetPropertiesSupported(context) == false)
                    {
                        PropertyEnumerator childEnum = mOwnerEnumerator.Children;
                        if (childEnum.Count > 0)
                        {
                            string masterStr = mOwnerEnumerator.Property.Value.GetStringValue();

                            char separator = mOwnerEnumerator.Property.Value.GroupedValueSeparator;
                            while (childEnum != childEnum.RightBound)
                            {
                                masterStr.TrimStart(null);

                                int count = masterStr.IndexOf(separator);

                                if (count != -1)
                                {
                                    childEnum.Property.Value.SetValue(masterStr.Substring(0, count));
                                    if (count + 2 < masterStr.Length)
                                    {
                                        masterStr = masterStr.Substring(count + 2); // advance after the separator and the leading space
                                    }
                                }
                                else
                                {
                                    childEnum.Property.Value.SetValue(masterStr);
                                    break;
                                }

                                childEnum.MoveNext();
                            }
                        }
                    }
                }
            }

            return(result);
        }
Exemple #17
0
        protected override AttachableXamlMember LookupAttachableMember(string name)
        {
            // OmniXAML seems to require a getter and setter even though we don't use them.
            var getter = UnderlyingType.GetTypeInfo().GetDeclaredMethod("Get" + name);
            var setter = UnderlyingType.GetTypeInfo().GetDeclaredMethod("Set" + name);

            return(new PerspexAttachableXamlMember(name, this, getter, setter, TypeRepository, FeatureProvider));
        }
Exemple #18
0
        private List <MethodInfo> LookupStaticSetters(string name)
        {
            MemberInfo[]      setters = UnderlyingType.GetMember(KnownStrings.Set + name, MemberTypes.Method, AttachableProperties_BF);
            List <MethodInfo> preferredSetters, otherSetters;

            PrioritizeAccessors(setters, false /*isEvent*/, false /*isGetter*/, out preferredSetters, out otherSetters);
            return(preferredSetters ?? otherSetters);
        }
Exemple #19
0
        public override bool Equals(object o)
        {
            ProjectingType other = o as ProjectingType;

            return(other != null &&
                   Projector == other.Projector &&
                   UnderlyingType.Equals(other.UnderlyingType));
        }
Exemple #20
0
        /*************************************/
        /**** Public Methods              ****/
        /*************************************/

        public static Func <IDataAccessor, int, object> InputAccessor(Type accessorType, Type dataType)
        {
            UnderlyingType subType    = dataType.UnderlyingType();
            string         methodName = (subType.Depth == 0) ? "GetDataItem" : (subType.Depth == 1) ? "GetDataList" : "GetDataTree";

            Type inputType = subType.Type;

            if (inputType.IsByRef && inputType.HasElementType)
            {
                inputType = inputType.GetElementType();
            }
            MethodInfo method = accessorType.GetMethod(methodName).MakeGenericMethod(inputType);

            ParameterExpression lambdaInput1 = Expression.Parameter(typeof(IDataAccessor), "accessor");
            ParameterExpression lambdaInput2 = Expression.Parameter(typeof(int), "index");

            ParameterExpression[] lambdaInputs = new ParameterExpression[] { lambdaInput1, lambdaInput2 };

            Expression[]         methodInputs        = new Expression[] { lambdaInput2 };
            MethodCallExpression methodExpression    = Expression.Call(Expression.Convert(lambdaInput1, accessorType), method, methodInputs);
            Func <IDataAccessor, int, object> lambda = Expression.Lambda <Func <IDataAccessor, int, object> >(Expression.Convert(methodExpression, typeof(object)), lambdaInputs).Compile();

            if (dataType.IsArray)
            {
                // If dataType is an array type, the underlying method asks for an array type
                // Thus, we add a new node to the syntax tree that casts the List to an Array
                MethodInfo            castMethod     = typeof(Enumerable).GetMethod("ToArray").MakeGenericMethod(subType.Type);
                ParameterExpression   lambdaResult   = Expression.Parameter(typeof(object), "lambdaResult");
                MethodCallExpression  castExpression = Expression.Call(null, castMethod, Expression.Convert(lambdaResult, typeof(IEnumerable <>).MakeGenericType(subType.Type)));
                Func <object, object> castDelegate   = Expression.Lambda <Func <object, object> >(castExpression, lambdaResult).Compile();

                return((accessor, index) => { return castDelegate(lambda(accessor, index)); });
            }
            else if (subType.Depth == 1 && !dataType.IsValueType && dataType.Name != "List`1" && dataType.Name != "IEnumerable`1")
            {
                // If we have a `DataList` that isn't actually a list, lets try to create it from teh list through the appropriate constructor
                foreach (ConstructorInfo constructor in dataType.GetConstructors())
                {
                    ParameterInfo[] parameters = constructor.GetParameters();
                    if (parameters.Count() == 1)
                    {
                        string paramType = parameters[0].ParameterType.Name;
                        if (paramType == "List`1" || paramType == "IEnumerable`1")
                        {
                            ParameterExpression   lambdaResult   = Expression.Parameter(typeof(object), "lambdaResult");
                            NewExpression         castExpression = Expression.New(constructor, Expression.Convert(lambdaResult, parameters[0].ParameterType));
                            Func <object, object> castDelegate   = Expression.Lambda <Func <object, object> >(castExpression, lambdaResult).Compile();
                            return((accessor, index) => { return castDelegate(lambda(accessor, index)); });
                        }
                    }
                }
                return(lambda);
            }
            else
            {
                return(lambda);
            }
        }
Exemple #21
0
 public override int GetHashCode()
 {
     unchecked {
         var hashCode = UnderlyingType.GetHashCode();
         hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Definitions.GetHashCode();
         return(hashCode);
     }
 }
Exemple #22
0
        private List <MethodInfo> LookupStaticAdders(string name)
        {
            string adderName = KnownStrings.Add + name + KnownStrings.Handler;

            MemberInfo[]      adders = UnderlyingType.GetMember(adderName, MemberTypes.Method, AttachableProperties_BF);
            List <MethodInfo> preferredAdders, otherAdders;

            PrioritizeAccessors(adders, true /*isEvent*/, false /*isGetter*/, out preferredAdders, out otherAdders);
            return(preferredAdders ?? otherAdders);
        }
Exemple #23
0
        protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
        {
            var decl = other as EnumDeclaration;

            return(decl != null &&
                   MatchAttributesAndModifiers(decl, match) &&
                   Name.DoMatch(decl.Name, match) &&
                   UnderlyingType.DoMatch(decl.UnderlyingType, match) &&
                   Members.DoMatch(decl.Members, match));
        }
Exemple #24
0
        public override bool IsAssignableFrom(Type c)
        {
            ProjectingType otherType = c as ProjectingType;

            if (otherType == null || Projector != otherType.Projector)
            {
                return(false);
            }

            return(UnderlyingType.IsAssignableFrom(otherType.UnderlyingType));
        }
Exemple #25
0
        /// <summary>
        /// Return a writer for writing a single property value.
        /// </summary>
        /// <param name="propertyName">to write to</param>
        /// <returns>
        /// null or writer if writable
        /// </returns>
        public EventPropertyWriter GetWriter(String propertyName)
        {
            if (_writeablePropertyDescriptors == null)
            {
                InitializeWriters();
            }

            var pair = _writerMap.Get(propertyName);

            if (pair != null)
            {
                return(pair.Second);
            }

            var property = PropertyParser.ParseAndWalk(propertyName, false);

            if (property is MappedProperty)
            {
                var mapProp    = (MappedProperty)property;
                var methodName = string.Format("Set{0}", mapProp.PropertyNameAtomic);
                var methodInfo = UnderlyingType.GetMethod(
                    methodName, BindingFlags.Public | BindingFlags.Instance, null,
                    new Type[] { typeof(string), typeof(object) }, null);
                if (methodInfo == null)
                {
                    Log.Info("Failed to find mapped property '" + mapProp.PropertyNameAtomic +
                             "' for writing to property '" + propertyName + "'");
                    return(null);
                }

                var fastMethod = FastClass.GetMethod(methodInfo);
                return(new BeanEventPropertyWriterMapProp(UnderlyingType, fastMethod, mapProp.Key));
            }

            if (property is IndexedProperty)
            {
                var indexedProp = (IndexedProperty)property;
                var methodName  = string.Format("Set{0}", indexedProp.PropertyNameAtomic);
                var methodInfo  = UnderlyingType.GetMethod(
                    methodName, BindingFlags.Public | BindingFlags.Instance, null,
                    new Type[] { typeof(int), typeof(object) }, null);
                if (methodInfo == null)
                {
                    Log.Info("Failed to find mapped property '" + indexedProp.PropertyNameAtomic +
                             "' for writing to property '" + propertyName + "'");
                    return(null);
                }

                var fastMethod = FastClass.GetMethod(methodInfo);
                return(new BeanEventPropertyWriterIndexedProp(UnderlyingType, fastMethod, indexedProp.Index));
            }

            return(null);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType != typeof(string) || value == null)
            {
                return(base.ConvertTo(context, culture, value, destinationType));
            }

            FieldInfo fieldInfo = UnderlyingType.GetField(value.ToString());

            return(GetDisplayName(fieldInfo));
        }
Exemple #27
0
        // We could have used the default implementation of this on Type
        // if it handled special cases like generic type constraints
        // and interfaces->objec.
        public override bool IsSubclassOf(Type c)
        {
            ProjectingType?otherType = c as ProjectingType;

            if (otherType == null || Projector != otherType.Projector)
            {
                return(false);
            }

            return(UnderlyingType.IsSubclassOf(otherType.UnderlyingType));
        }
Exemple #28
0
        public override bool IsEquivalentTo([NotNullWhen(true)] Type?other)
        {
            ProjectingType?otherType = other as ProjectingType;

            if (otherType == null || Projector != otherType.Projector)
            {
                return(false);
            }

            return(UnderlyingType.IsEquivalentTo(otherType.UnderlyingType));
        }
Exemple #29
0
        public override bool IsAssignableFrom([NotNullWhen(true)] Type?c)
        {
            ProjectingType?otherType = c as ProjectingType;

            if (otherType == null || Projector != otherType.Projector)
            {
                return(false);
            }

            return(UnderlyingType.IsAssignableFrom(otherType.UnderlyingType));
        }
Exemple #30
0
        internal void LookupAllMembers(out ICollection <PropertyInfo> newProperties,
                                       out ICollection <EventInfo> newEvents, out List <XamlMember> knownMembers)
        {
            Debug.Assert(UnderlyingType != null, "Caller should check for UnderlyingType == null");
            Debug.Assert(_nonAttachableMemberCache != null, "Members property should have been invoked before this");

            PropertyInfo[] propList  = UnderlyingType.GetProperties(AllProperties_BF);
            EventInfo[]    eventList = UnderlyingType.GetEvents(AllProperties_BF);
            knownMembers  = new List <XamlMember>(propList.Length + eventList.Length);
            newProperties = FilterProperties(propList, knownMembers, true);
            newEvents     = FilterEvents(eventList, knownMembers);
        }