// Change this to provide different name for the member.
        private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
        {
            JsonPropertyAttribute jsonProperty = member.GetCustomAttribute <JsonPropertyAttribute>();

            if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
            {
                return(jsonProperty.PropertyName);
            }

            if (hasDataContractAttribute)
            {
                DataMemberAttribute dataMember = member.GetCustomAttribute <DataMemberAttribute>();
                if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
                {
                    return(dataMember.Name);
                }
            }

            return(member.Name);
        }
Ejemplo n.º 2
0
        private Dictionary <string, string> GetTableMap()
        {
            Type type = GetType();

            if (!tableMaps.ContainsKey(type))
            {
                Dictionary <string, string> map = new Dictionary <string, string>();
                string value;
                foreach (PropertyInfo property in type.GetProperties())
                {
                    if (property.GetCustomAttribute <RestIgnoreColumnAttribute>() != null)
                    {
                        continue;
                    }

                    RestColumnAttribute columnAttribute = property.GetCustomAttribute <RestColumnAttribute>();
                    if (columnAttribute != null)
                    {
                        value = columnAttribute.Name;
                    }
                    else
                    {
                        DataMemberAttribute dataMemberAttribute = property.GetCustomAttribute <DataMemberAttribute>();
                        if (dataMemberAttribute != null)
                        {
                            value = dataMemberAttribute.Name;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    map[property.Name] = value;
                }

                tableMaps[type] = map;
            }

            return(tableMaps[type]);
        }
Ejemplo n.º 3
0
        public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo)
        {
            if (memberInfo.MemberType() == MemberTypes.Field)
            {
                return(CachedAttributeGetter <DataMemberAttribute> .GetAttribute(memberInfo));
            }
            PropertyInfo        propertyInfo = (PropertyInfo)memberInfo;
            DataMemberAttribute attribute    = CachedAttributeGetter <DataMemberAttribute> .GetAttribute(propertyInfo);

            if (attribute == null && propertyInfo.IsVirtual())
            {
                for (Type i = propertyInfo.DeclaringType; attribute == null && i != null; i = i.BaseType())
                {
                    PropertyInfo memberInfoFromType = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(i, propertyInfo);
                    if (memberInfoFromType != null && memberInfoFromType.IsVirtual())
                    {
                        attribute = CachedAttributeGetter <DataMemberAttribute> .GetAttribute(memberInfoFromType);
                    }
                }
            }
            return(attribute);
        }
Ejemplo n.º 4
0
        public static string GetMemberName(this MemberInfo memberInfo)
        {
            // Json.Net honors JsonPropertyAttribute more than DataMemberAttribute
            // So we check for JsonPropertyAttribute first.
            JsonPropertyAttribute jsonPropertyAttribute = memberInfo.GetCustomAttribute <JsonPropertyAttribute>(true);

            if (jsonPropertyAttribute != null && !string.IsNullOrEmpty(jsonPropertyAttribute.PropertyName))
            {
                return(jsonPropertyAttribute.PropertyName);
            }

            DataContractAttribute dataContractAttribute = memberInfo.DeclaringType.GetCustomAttribute <DataContractAttribute>(true);

            if (dataContractAttribute != null)
            {
                DataMemberAttribute dataMemberAttribute = memberInfo.GetCustomAttribute <DataMemberAttribute>(true);
                if (dataMemberAttribute != null && !string.IsNullOrEmpty(dataMemberAttribute.Name))
                {
                    return(dataMemberAttribute.Name);
                }
            }

            return(memberInfo.Name);
        }
        public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo)
        {
            if (memberInfo.MemberType == MemberTypes.Field)
            {
                return(CachedAttributeGetter <DataMemberAttribute> .GetAttribute(memberInfo));
            }
            PropertyInfo        propertyInfo = (PropertyInfo)memberInfo;
            DataMemberAttribute attribute    = CachedAttributeGetter <DataMemberAttribute> .GetAttribute(propertyInfo);

            if (attribute == null && propertyInfo.IsVirtual())
            {
                Type type = propertyInfo.DeclaringType;
                while (attribute == null && type != null)
                {
                    PropertyInfo propertyInfo2 = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(type, propertyInfo);
                    if (propertyInfo2 != null && propertyInfo2.IsVirtual())
                    {
                        attribute = CachedAttributeGetter <DataMemberAttribute> .GetAttribute(propertyInfo2);
                    }
                    type = type.BaseType;
                }
            }
            return(attribute);
        }
Ejemplo n.º 6
0
    // Token: 0x060009F5 RID: 2549 RVA: 0x00038614 File Offset: 0x00036814
    public static DataMemberAttribute smethod_3(object object_0)
    {
        if (object_0.smethod_1() == MemberTypes.Field)
        {
            return(Class102 <DataMemberAttribute> .smethod_0(object_0));
        }
        PropertyInfo        propertyInfo        = (PropertyInfo)object_0;
        DataMemberAttribute dataMemberAttribute = Class102 <DataMemberAttribute> .smethod_0(propertyInfo);

        if (dataMemberAttribute == null && propertyInfo.smethod_0())
        {
            Type type = propertyInfo.DeclaringType;
            while (dataMemberAttribute == null && type != null)
            {
                PropertyInfo propertyInfo2 = (PropertyInfo)Class90.smethod_37(type, propertyInfo);
                if (propertyInfo2 != null && propertyInfo2.smethod_0())
                {
                    dataMemberAttribute = Class102 <DataMemberAttribute> .smethod_0(propertyInfo2);
                }
                type = type.smethod_6();
            }
        }
        return(dataMemberAttribute);
    }
        internal static bool IsRequiredDataMember(
            Type containerType,
            IEnumerable <Attribute> attributes
            )
        {
            DataMemberAttribute dataMemberAttribute = attributes
                                                      .OfType <DataMemberAttribute>()
                                                      .FirstOrDefault();

            if (dataMemberAttribute != null)
            {
                // isDataContract == true iff the container type has at least one DataContractAttribute
                bool isDataContract = TypeDescriptorHelper
                                      .Get(containerType)
                                      .GetAttributes()
                                      .OfType <DataContractAttribute>()
                                      .Any();
                if (isDataContract && dataMemberAttribute.IsRequired)
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 8
0
        private static DefinitionProperty ProcessProperty(PropertyInfo propertyInfo, IList <string> hiddenTags,
                                                          Stack <Type> typesStack)
        {
            if (propertyInfo.GetCustomAttribute <DataMemberAttribute>() == null ||
                propertyInfo.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null ||
                propertyInfo.GetCustomAttributes <SwaggerWcfTagAttribute>()
                .Select(t => t.TagName)
                .Any(hiddenTags.Contains))
            {
                return(null);
            }

            TypeFormat typeFormat = Helpers.MapSwaggerType(propertyInfo.PropertyType, null);

            DefinitionProperty prop = new DefinitionProperty {
                Title = propertyInfo.Name
            };

            DataMemberAttribute dataMemberAttribute = propertyInfo.GetCustomAttribute <DataMemberAttribute>();

            if (dataMemberAttribute != null)
            {
                if (!string.IsNullOrEmpty(dataMemberAttribute.Name))
                {
                    prop.Title = dataMemberAttribute.Name;
                }

                prop.Required = dataMemberAttribute.IsRequired;
            }

            DescriptionAttribute descriptionAttribute = propertyInfo.GetCustomAttribute <DescriptionAttribute>();

            if (descriptionAttribute != null)
            {
                prop.Description = descriptionAttribute.Description;
            }

            prop.TypeFormat = typeFormat;

            if (prop.TypeFormat.Type == ParameterType.Object)
            {
                typesStack.Push(propertyInfo.PropertyType);

                prop.Ref = propertyInfo.PropertyType.FullName;

                return(prop);
            }

            if (prop.TypeFormat.Type == ParameterType.Array)
            {
                Type subType = propertyInfo.PropertyType.GetEnumerableType();
                if (subType != null)
                {
                    TypeFormat subTypeFormat = Helpers.MapSwaggerType(subType, null);

                    if (subTypeFormat.Type == ParameterType.Object)
                    {
                        typesStack.Push(subType);
                    }

                    prop.Items = new ParameterItems
                    {
                        TypeFormat = subTypeFormat
                    };
                }
            }

            if (prop.TypeFormat.Type == ParameterType.String && prop.TypeFormat.Format == "enum")
            {
                prop.Enum = new List <string>();
                List <string> listOfEnumNames = propertyInfo.PropertyType.GetEnumNames().ToList();
                foreach (string enumName in listOfEnumNames)
                {
                    prop.Enum.Add(GetEnumMemberValue(propertyInfo.PropertyType, enumName));
                }
            }

            return(prop);
        }
Ejemplo n.º 9
0
        private ParameterBase GetParameter(TypeFormat typeFormat, ParameterInfo parameter,
                                           SwaggerWcfParameterAttribute settings, string uriTemplate,
                                           IList <Type> definitionsTypesList)
        {
            string description = settings != null ? settings.Description : null;
            bool   required    = settings != null && settings.Required;
            string name        = parameter.Name;
            DataMemberAttribute dataMemberAttribute = parameter.GetCustomAttribute <DataMemberAttribute>();

            if (dataMemberAttribute != null && !string.IsNullOrEmpty(dataMemberAttribute.Name))
            {
                name = dataMemberAttribute.Name;
            }

            InType inType = GetInType(uriTemplate, parameter.Name);

            if (inType == InType.Path)
            {
                required = true;
            }

            if (!required && !parameter.HasDefaultValue)
            {
                required = true;
            }

            if (typeFormat.Type == ParameterType.Object)
            {
                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            if (inType == InType.Body)
            {
                if (typeFormat.Type == ParameterType.Array)
                {
                    Type t = parameter.ParameterType.GetElementType() ?? GetEnumerableType(parameter.ParameterType);
                    ParameterPrimitive arrayParam = new ParameterPrimitive
                    {
                        Name        = name,
                        Description = description,
                        In          = inType,
                        Required    = required,
                        TypeFormat  = typeFormat,
                        Items       = new ParameterItems
                        {
                            Items = new ParameterSchema
                            {
                                SchemaRef = t.FullName
                            }
                        },
                        CollectionFormat = CollectionFormat.Csv
                    };

                    //it's a complex type, so we'll need to map it later
                    if (definitionsTypesList != null && !definitionsTypesList.Contains(t))
                    {
                        definitionsTypesList.Add(t);
                    }

                    return(arrayParam);
                }

                //it's a complex type, so we'll need to map it later
                if (definitionsTypesList != null && !definitionsTypesList.Contains(parameter.ParameterType))
                {
                    definitionsTypesList.Add(parameter.ParameterType);
                }
                typeFormat = new TypeFormat(ParameterType.Object,
                                            HttpUtility.HtmlEncode(parameter.ParameterType.FullName));

                return(new ParameterSchema
                {
                    Name = name,
                    Description = description,
                    In = inType,
                    Required = required,
                    SchemaRef = typeFormat.Format
                });
            }

            ParameterPrimitive param = new ParameterPrimitive
            {
                Name        = name,
                Description = description,
                In          = inType,
                Required    = required,
                TypeFormat  = typeFormat
            };

            return(param);
        }
Ejemplo n.º 10
0
 public TypeMapField(FieldInfo fi, DataMemberAttribute dma)
     : base(fi, dma)
 {
     this.field = fi;
 }
        void ExtractAttributes(PropertyInfo pi, MessageDescription Message, OperationDescription Operation, MessagePartDescription MessagePartDescription)
        {
            object[] xmlElementAttributes   = pi.GetCustomAttributes(typeof(XmlElementAttribute), false);
            object[] stringLengthAttributes = pi.GetCustomAttributes(typeof(StringLengthAttribute), false);
            object[] regexAttributes        = pi.GetCustomAttributes(typeof(RegularExpressionAttribute), false);
            object[] rangeAttributes        = pi.GetCustomAttributes(typeof(RangeAttribute), false);
            object[] dataMemberAttributes   = pi.GetCustomAttributes(typeof(DataMemberAttribute), false);

            string ElemName = pi.Name;

            //pick up XmlElement's ElementName if used to match later
            if (xmlElementAttributes.Length > 0)
            {
                XmlElementAttribute xmlElementAttrib = xmlElementAttributes[0] as XmlElementAttribute;
                if (!string.IsNullOrWhiteSpace(xmlElementAttrib.ElementName))
                {
                    ElemName = xmlElementAttrib.ElementName;
                }
            }
            if (!_Namespaces.ContainsKey(MessagePartDescription.Namespace))
            {
                _Namespaces.Add(MessagePartDescription.Namespace, new XSDNamespace());
            }

            XSDNamespace Namespace = _Namespaces[MessagePartDescription.Namespace];

            if (!Namespace.ContainsKey(Operation.Name))
            {
                Namespace.Add(Operation.Name, new XSDMessage());
            }

            XSDMessage XsdMessage = Namespace[Operation.Name];

            for (int i = 0; i < stringLengthAttributes.Length; i++)
            {
                StringLengthAttribute sla = stringLengthAttributes[i] as StringLengthAttribute;

                XsdMessage.Add(ElemName, new StringLengthMessagePart()
                {
                    MinLength = sla.MinimumLength,
                    MaxLength = sla.MaximumLength
                });
            }

            for (int i = 0; i < regexAttributes.Length; i++)
            {
                RegularExpressionAttribute rea = regexAttributes[i] as RegularExpressionAttribute;

                XsdMessage.Add(ElemName, new RegexMessagePart()
                {
                    Regex = rea.Pattern
                });
            }

            for (int i = 0; i < rangeAttributes.Length; i++)
            {
                RangeAttribute raa = rangeAttributes[i] as RangeAttribute;

                XsdMessage.Add(ElemName, new RangeMessagePart()
                {
                    Min = raa.Minimum,
                    Max = raa.Maximum
                });
            }
            for (int i = 0; i < dataMemberAttributes.Length; i++)
            {
                DataMemberAttribute dma = dataMemberAttributes[i] as DataMemberAttribute;

                XsdMessage.Add(ElemName, new RequiredMessagePart()
                {
                    Required = dma.IsRequired
                });
            }

            //rough seach for properties that are "custom" classes: there isn't a better way of doing it that I can find.
            if (pi.PropertyType.IsClass && (pi.PropertyType.BaseType != pi.PropertyType) && !pi.PropertyType.Namespace.StartsWith("System.") && !pi.PropertyType.Namespace.StartsWith("Microsoft."))     //hopefully filter out base objects
            {
                //iterate nested properties, looking for more attributes
                foreach (PropertyInfo piNested in pi.PropertyType.GetProperties())
                {
                    ExtractAttributes(piNested, Message, Operation, MessagePartDescription);
                }
            }
        }
Ejemplo n.º 12
0
        void ImportDataMembers(Type type, bool hasDataContract)
        {
            members = new List <DataMember>();
            MemberInfo[] memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            for (int i = 0; i < memberInfos.Length; i++)
            {
                MemberInfo member = memberInfos[i];
                if (hasDataContract)
                {
                    object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false);
                    if (memberAttributes != null && memberAttributes.Length > 0)
                    {
                        if (memberAttributes.Length > 1)
                        {
                            throw new Exception(string.Format("member {1} in type {0} has too many DataMemberAttribute", member.DeclaringType.FullName, member.Name));
                        }
                        if (member.MemberType == MemberTypes.Property)
                        {
                            PropertyInfo property = (PropertyInfo)member;

                            MethodInfo getMethod = property.GetGetMethod(true);
                            if (getMethod != null && IsMethodOverriding(getMethod))
                            {
                                continue;
                            }
                            MethodInfo setMethod = property.GetSetMethod(true);
                            if (setMethod != null && IsMethodOverriding(setMethod))
                            {
                                continue;
                            }
                            if (getMethod == null)
                            {
                                throw new Exception(string.Format("member {1} in type {0} has no get method", property.DeclaringType, property.Name));
                            }

                            if (setMethod == null)
                            {
                                throw new Exception(string.Format("member {1} in type {0} has no set method", property.DeclaringType, property.Name));
                            }
                            if (getMethod.GetParameters().Length > 0)
                            {
                                throw new Exception("indexer is not supported");
                            }
                        }
                        else if (member.MemberType != MemberTypes.Field)
                        {
                            throw new Exception("only field or property is supported now");
                        }

                        DataMember          memberContract  = new DataMember(member);
                        DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0];
                        if (memberAttribute.Name == null)
                        {
                            memberContract.Name = member.Name;
                        }
                        else
                        {
                            memberContract.Name = memberAttribute.Name;
                        }
                        members.Add(memberContract);
                    }
                }
                else
                {
                    FieldInfo field = member as FieldInfo;
                    if (field != null && !field.IsNotSerialized)
                    {
                        DataMember memberContract = new DataMember(member);
                        memberContract.Name         = member.Name;
                        memberContract.VersionAdded = Globals.DefaultVersion;
                        //TODO, sowmys: Do Optionally Serialized here.
                        members.Add(memberContract);
                    }
                }
            }
            //TODO: need to update when introduce versions
            members.Sort(DataMemberComparer.Singleton);
        }
 public TypeMapField(FieldInfo fi, DataMemberAttribute dma)
     : base(fi, dma)
 {
     this.field = fi;
 }
        static TypeMap CreateTypeMap(Type type, DataContractAttribute dca)
        {
            if (dca != null && dca.Name != null && IsInvalidNCName(dca.Name))
            {
                throw new InvalidDataContractException(String.Format("DataContractAttribute for type '{0}' has an invalid name", type));
            }

            List <TypeMapMember> members = new List <TypeMapMember> ();

            foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (dca != null)
                {
                    object [] atts = fi.GetCustomAttributes(typeof(DataMemberAttribute), true);
                    if (atts.Length == 0)
                    {
                        continue;
                    }
                    DataMemberAttribute dma = (DataMemberAttribute)atts [0];
                    members.Add(new TypeMapField(fi, dma));
                }
                else
                {
                    if (fi.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).Length > 0)
                    {
                        continue;
                    }
                    members.Add(new TypeMapField(fi, null));
                }
            }

            if (dca != null)
            {
                foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    object [] atts = pi.GetCustomAttributes(typeof(DataMemberAttribute), true);
                    if (atts.Length == 0)
                    {
                        continue;
                    }
                    if (pi.GetIndexParameters().Length > 0)
                    {
                        continue;
                    }
                    if (IsCollection(pi.PropertyType))
                    {
                        if (!pi.CanRead)
                        {
                            throw new InvalidDataContractException(String.Format("Property {0} must have a getter", pi));
                        }
                    }
                    else if (!pi.CanRead || !pi.CanWrite)
                    {
                        throw new InvalidDataContractException(String.Format("Non-collection property {0} must have both getter and setter", pi));
                    }
                    DataMemberAttribute dma = (DataMemberAttribute)atts [0];
                    members.Add(new TypeMapProperty(pi, dma));
                }
            }

            members.Sort(delegate(TypeMapMember m1, TypeMapMember m2)
            {
                return(m1.Order != m2.Order ? m1.Order - m2.Order : String.CompareOrdinal(m1.Name, m2.Name));
            });
            return(new TypeMap(type, dca == null ? null : dca.Name, members.ToArray()));
        }
Ejemplo n.º 15
0
        public override T GetResponse()
        {
            //判断是否需要身份验证
            if (base.HttpMethodAttribute.IsToken)
            {
                base.HttpMethodAttribute.Url = base.HttpMethodAttribute.Url + WeiXinUtils.BuildGetUrl(base.HttpMethodAttribute.Url
                                                                                                      ) + "access_token=" + base.Token.AccessToken;
            }
            WebUtils webutils = new WebUtils();

            //上传文件返回json
            if (HttpMethodAttribute.Serialize == SerializeVerb.Json)
            {
                Type type = base.Request.GetType();
                //获得多媒体路径.
                PropertyInfo infoMedia = type.GetProperty("Media");
                object       objMedia  = infoMedia.FastGetValue(base.Request);
                // object objMedia = infoMedia.GetValue(Request, null);
                string strPath = string.Empty;
                if (objMedia is string)
                {
                    strPath = objMedia as string;
                }
                //获得多媒体类型.
                PropertyInfo     infoType  = type.GetProperty("Type");
                object           objType   = infoType.FastGetValue(base.Request);
                Domain.MediaType mediaType = new Domain.MediaType();
                if (objType is Domain.MediaType)
                {
                    mediaType = (Domain.MediaType)objType;
                }
                ///如果路径不为空
                if (File.Exists(strPath))
                {
                    //在url里面添加文件类型
                    HttpMethodAttribute.Url += "&type=" + mediaType.ToString().ToLower();
                    string strJson = webutils.DoPostFile(HttpMethodAttribute.Url, strPath);
                    return(strJson.jsonToObj <T>());
                }
                else
                {
                    throw new WeiXinException(string.Format("你要上传的:{0}路径非法", strPath));
                }
            }
            ///返回byte 执行下载逻辑
            if (HttpMethodAttribute.Serialize == SerializeVerb.Byte)
            {
                Type           type   = base.Request.GetType();
                PropertyInfo[] finfos = type.GetProperties();
                StringBuilder  sb     = new StringBuilder();
                foreach (PropertyInfo finfo in finfos)
                {
                    string fieldName  = finfo.Name;
                    string fieldValue = string.Empty;
                    object objValue   = finfo.FastGetValue(Request);
                    if (objValue is Int32 || objValue is string)
                    {
                        fieldValue = objValue.ToString();
                    }
                    FieldInfo           fieldInfo = type.GetField(fieldName);
                    DataMemberAttribute data      = (DataMemberAttribute)System.Attribute.GetCustomAttribute(finfo, typeof(DataMemberAttribute));
                    if (data != null)
                    {
                        //是否是必须参数
                        if (data.IsRequired)
                        {
                            if (string.IsNullOrEmpty(fieldValue))
                            {
                                throw new WeiXinException(string.Format("{0}属性值  不能为空", fieldName));
                            }
                            else
                            {
                                sb.Append(data.Name ?? fieldName);
                                sb.Append("=");
                                sb.Append(fieldValue);
                                sb.Append("&");
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(fieldValue))
                            {
                                sb.Append(fieldName);
                                sb.Append("=");
                                sb.Append(fieldValue);
                                sb.Append("&");
                            }
                        }
                    }
                }
                if (sb.ToString().EndsWith("&"))
                {
                    sb.Remove(sb.Length - 1, 1);
                }
                ///得到请求Url
                base.HttpMethodAttribute.Url = base.HttpMethodAttribute.Url + WeiXinUtils.BuildGetUrl(base.HttpMethodAttribute.Url
                                                                                                      ) + sb.ToString();
                string           path     = string.Empty;
                byte[]           stream   = webutils.Download(HttpMethodAttribute.Url, out path);
                GetMediaResponse response = new GetMediaResponse();
                response.Stream = BytesToStream(stream);
                response.Path   = path;
                return(response as T);
            }
            return(null);
        }
        private static void AddProperty(
            PropertyInfo propertyInfo,
            Type composedPropertyType,
            DataMemberAttribute dataMemberAttribute,
            TypeBuilder typeBuilder
        )
        {
            string propertyName = dataMemberAttribute.Name as string ?? propertyInfo.Name;

            // generating property
            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, composedPropertyType, null);

            Type dataMemberAttributeType = typeof(DataMemberAttribute);
            var dataMemberProps = new PropertyInfo[]
            {
                dataMemberAttributeType.GetProperty(nameof(DataMemberAttribute.Name)),
                dataMemberAttributeType.GetProperty(nameof(DataMemberAttribute.IsRequired)),
                dataMemberAttributeType.GetProperty(nameof(DataMemberAttribute.EmitDefaultValue))
            };

            var dataMemberPropValues = new object[] {
                propertyName,
                dataMemberAttribute.IsRequired,
                dataMemberAttribute.EmitDefaultValue
            };

            CustomAttributeBuilder dataMemberAttributeBuilder = new CustomAttributeBuilder(
                dataMemberAttributeType.GetConstructor(Type.EmptyTypes),
                new object[0],
                dataMemberProps,
                dataMemberPropValues
            );

            propertyBuilder.SetCustomAttribute(dataMemberAttributeBuilder);

            // generating private field
            FieldBuilder fieldBuilder = typeBuilder.DefineField("_" + propertyName, composedPropertyType, FieldAttributes.Private);
            CustomAttributeBuilder hideFieldAttributeBuilder = new CustomAttributeBuilder(
                typeof(DebuggerBrowsableAttribute).GetConstructor(new[] { typeof(DebuggerBrowsableState) }),
                new object[] { DebuggerBrowsableState.Never }
            );
            fieldBuilder.SetCustomAttribute(hideFieldAttributeBuilder);

            // generating public getter/setter
            MethodBuilder getPropMthdBldr = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, composedPropertyType, Type.EmptyTypes);
            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr = typeBuilder.DefineMethod("set_" + propertyName,
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.HideBySig,
                null, new[] { composedPropertyType });

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();
            Label modifyProperty = setIl.DefineLabel();
            Label exitSet = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
Ejemplo n.º 17
0
        static List <PropertyConverter> GetPropertyConvertersForType(Type type)
        {
            var          propertyConverters = new List <PropertyConverter>();
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;

            // Loop through the type hierarchy to find all [DataMember] attributes which belong to [DataContract] classes.
            while (type != null && type.GetCustomAttribute <DataContractAttribute>() != null)
            {
                foreach (MemberInfo member in type.GetMembers(flags))
                {
                    DataMemberAttribute dataMember = member.GetCustomAttribute <DataMemberAttribute>();
                    if (dataMember == null)
                    {
                        continue;
                    }

                    PropertyInfo property = member as PropertyInfo;
                    FieldInfo    field    = member as FieldInfo;
                    if (property == null && field == null)
                    {
                        throw new InvalidDataContractException("Only fields and properties can be marked as [DataMember].");
                    }
                    else if (property != null && (!property.CanWrite || !property.CanRead))
                    {
                        throw new InvalidDataContractException("[DataMember] properties must be both readable and writeable.");
                    }

                    // Timestamp is a reserved property name in Table Storage, so the name needs to be changed.
                    string propertyName = dataMember.Name ?? member.Name;
                    if (string.Equals(propertyName, "Timestamp", StringComparison.OrdinalIgnoreCase))
                    {
                        propertyName = "_Timestamp";
                    }

                    Func <object, EntityProperty>   getEntityPropertyFunc;
                    Action <object, EntityProperty> setObjectPropertyFunc;

                    Type memberValueType = property != null ? property.PropertyType : field.FieldType;
                    if (typeof(string).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString((string)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.StringValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString((string)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.StringValue);
                        }
                    }
                    else if (memberValueType.IsEnum)
                    {
                        // Enums are serialized as strings for readability.
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString(property.GetValue(o).ToString());
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, Enum.Parse(memberValueType, e.StringValue));
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString(field.GetValue(o).ToString());
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, Enum.Parse(memberValueType, e.StringValue));
                        }
                    }
                    else if (typeof(int?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForInt((int?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.Int32Value);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForInt((int?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.Int32Value);
                        }
                    }
                    else if (typeof(long?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForLong((long?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.Int64Value);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForLong((long?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.Int64Value);
                        }
                    }
                    else if (typeof(bool?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForBool((bool?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.BooleanValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForBool((bool?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.BooleanValue);
                        }
                    }
                    else if (typeof(DateTime?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTime?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.DateTime);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTime?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.DateTime);
                        }
                    }
                    else if (typeof(DateTimeOffset?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTimeOffset?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.DateTimeOffsetValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTimeOffset?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.DateTimeOffsetValue);
                        }
                    }
                    else if (typeof(Guid?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForGuid((Guid?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.GuidValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForGuid((Guid?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.GuidValue);
                        }
                    }
                    else if (typeof(double?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDouble((double?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.DoubleValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDouble((double?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.DoubleValue);
                        }
                    }
                    else if (typeof(byte[]).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForByteArray((byte[])property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.BinaryValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForByteArray((byte[])field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.BinaryValue);
                        }
                    }
                    else // assume a serializeable object
                    {
                        getEntityPropertyFunc = o =>
                        {
                            object value = property != null?property.GetValue(o) : field.GetValue(o);

                            string json = value != null?JsonConvert.SerializeObject(value) : null;

                            return(EntityProperty.GeneratePropertyForString(json));
                        };

                        setObjectPropertyFunc = (o, e) =>
                        {
                            string json  = e.StringValue;
                            object value = json != null?JsonConvert.DeserializeObject(json, memberValueType) : null;

                            if (property != null)
                            {
                                property.SetValue(o, value);
                            }
                            else
                            {
                                field.SetValue(o, value);
                            }
                        };
                    }

                    propertyConverters.Add(new PropertyConverter(propertyName, getEntityPropertyFunc, setObjectPropertyFunc));
                }

                type = type.BaseType;
            }

            return(propertyConverters);
        }
Ejemplo n.º 18
0
 public TypeMapProperty(PropertyInfo pi, DataMemberAttribute dma)
     : base(pi, dma)
 {
     this.property = pi;
 }
Ejemplo n.º 19
0
 protected TypeMapMember(MemberInfo mi, DataMemberAttribute dma)
 {
     this.mi = mi;
     this.dma = dma;
 }
        private static DefinitionProperty ProcessProperty(PropertyInfo propertyInfo, IList <string> hiddenTags,
                                                          Stack <Type> typesStack)
        {
            if (propertyInfo.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null ||
                propertyInfo.GetCustomAttributes <SwaggerWcfTagAttribute>()
                .Select(t => t.TagName)
                .Any(hiddenTags.Contains))
            {
                return(null);
            }

            TypeFormat typeFormat = Helpers.MapSwaggerType(propertyInfo.PropertyType, null);

            DefinitionProperty prop = new DefinitionProperty {
                Title = propertyInfo.Name
            };

            DataMemberAttribute dataMemberAttribute = propertyInfo.GetCustomAttribute <DataMemberAttribute>();

            if (dataMemberAttribute != null)
            {
                if (!string.IsNullOrEmpty(dataMemberAttribute.Name))
                {
                    prop.Title = dataMemberAttribute.Name;
                }

                prop.Required = dataMemberAttribute.IsRequired;
            }

            // Special case - if it came out required, but we unwrapped a null-able type,
            // then it's necessarily not required.  Ideally this would only set the default,
            // but we can't tell the difference between an explicit declaration of
            // IsRequired =false on the DataMember attribute and no declaration at all.
            if (prop.Required && propertyInfo.PropertyType.IsGenericType &&
                propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                prop.Required = false;
            }

            DescriptionAttribute descriptionAttribute = propertyInfo.GetCustomAttribute <DescriptionAttribute>();

            if (descriptionAttribute != null)
            {
                prop.Description = descriptionAttribute.Description;
            }

            SwaggerWcfRegexAttribute regexAttr = propertyInfo.GetCustomAttribute <SwaggerWcfRegexAttribute>();

            if (regexAttr != null)
            {
                prop.Pattern = regexAttr.Regex;
            }

            prop.TypeFormat = typeFormat;

            if (prop.TypeFormat.Type == ParameterType.Object)
            {
                typesStack.Push(propertyInfo.PropertyType);

                prop.Ref = propertyInfo.PropertyType.GetModelName();

                return(prop);
            }

            if (prop.TypeFormat.Type == ParameterType.Array)
            {
                Type subType = DefinitionsBuilder.GetEnumerableType(propertyInfo.PropertyType);
                if (subType != null)
                {
                    TypeFormat subTypeFormat = Helpers.MapSwaggerType(subType, null);

                    if (subTypeFormat.Type == ParameterType.Object)
                    {
                        typesStack.Push(subType);
                    }

                    prop.Items = new ParameterItems
                    {
                        TypeFormat = subTypeFormat
                    };
                }
            }

            if ((prop.TypeFormat.Type == ParameterType.Integer && prop.TypeFormat.Format == "enum") || (prop.TypeFormat.Type == ParameterType.Array && prop.Items.TypeFormat.Format == "enum"))
            {
                prop.Enum = new List <int>();

                Type propType = propertyInfo.PropertyType;

                if (propType.IsGenericType && (propType.GetGenericTypeDefinition() == typeof(Nullable <>) || propType.GetGenericTypeDefinition() == typeof(IEnumerable <>)))
                {
                    propType = propType.GenericTypeArguments.FirstOrDefault() ?? propType.GetEnumerableType();
                }

                string        enumDescription = "";
                List <string> listOfEnumNames = propType.GetEnumNames().ToList();
                foreach (string enumName in listOfEnumNames)
                {
                    var    enumMemberItem        = Enum.Parse(propType, enumName, true);
                    string enumMemberDescription = DefinitionsBuilder.GetEnumDescription((Enum)enumMemberItem);
                    enumMemberDescription = (string.IsNullOrWhiteSpace(enumMemberDescription)) ? "" : $"({enumMemberDescription})";
                    int enumMemberValue = DefinitionsBuilder.GetEnumMemberValue(propType, enumName);
                    if (prop.Description != null)
                    {
                        prop.Enum.Add(enumMemberValue);
                    }
                    enumDescription += $"    {enumName}{System.Web.HttpUtility.HtmlEncode(" = ")}{enumMemberValue} {enumMemberDescription}\r\n";
                }

                if (enumDescription != "")
                {
                    prop.Description += $"\r\n\r\n{enumDescription}";
                }
            }

            // Apply any options set in a [SwaggerWcfProperty]
            DefinitionsBuilder.ApplyAttributeOptions(propertyInfo, prop);

            return(prop);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Update DB attribute values.
        /// </summary>
        /// <param name="attributes"></param>
        /// <param name="s"></param>
        private static void UpdateAttributes(Type type, object[] attributes, GXSerializedItem s)
        {
            int          value = 0;
            PropertyInfo pi    = s.Target as PropertyInfo;

            if (pi != null && pi.Name == "Id")
            {
                foreach (var i in type.GetInterfaces())
                {
                    if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IUnique <>))
                    {
                        value |= (int)(Attributes.Id | Attributes.PrimaryKey);
                        break;
                    }
                }
            }
            foreach (object att in attributes)
            {
                //If field is ignored.
                if (att is IgnoreAttribute && (((IgnoreAttribute)att).IgnoreType & IgnoreType.Db) != 0)
                {
                    value |= (int)Attributes.Ignored;
                }
                else
                {
                    if (att is DefaultValueAttribute)
                    {
                        DefaultValueAttribute def = att as DefaultValueAttribute;
                        s.DefaultValue = def.Value;
                    }
                    //Is property indexed.
                    if (att is IndexAttribute)
                    {
                        value |= (int)Attributes.Index;
                    }
                    //Is property auto indexed value.
                    if (att is AutoIncrementAttribute)
                    {
                        value |= (int)Attributes.AutoIncrement;
                    }
                    //Primary key value.
                    if (att is PrimaryKeyAttribute)
                    {
                        value |= (int)Attributes.PrimaryKey;
                    }
                    //Foreign key value.
                    if (att is ForeignKeyAttribute)
                    {
                        value |= (int)Attributes.ForeignKey;
                    }
                    //Relation field.
                    if (att is RelationAttribute)
                    {
                        value |= (int)Attributes.Relation;
                    }
                    if (att is StringLengthAttribute)
                    {
                        value |= (int)Attributes.StringLength;
                    }
                    if (att is DataMemberAttribute)
                    {
                        DataMemberAttribute n = att as DataMemberAttribute;
                        if (n.IsRequired)
                        {
                            value |= (int)Attributes.IsRequired;
                        }
                    }
                    if (att is DefaultValueAttribute)
                    {
                        value |= (int)Attributes.DefaultValue;
                    }
                }
            }
            s.Attributes = (Attributes)value;
        }
 protected TypeMapMember(MemberInfo mi, DataMemberAttribute dma)
 {
     this.mi  = mi;
     this.dma = dma;
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Creates a name resolution for a <see cref="DataMemberAttribute" />-annotated type.
 /// </summary>
 protected virtual IdentifierResolution CreateNameResolution(MemberInfo member, DataMemberAttribute attribute)
 {
     return(string.IsNullOrEmpty(attribute?.Name)
         ? new IdentifierResolution(member.Name)
         : new IdentifierResolution(attribute.Name, true));
 }
 public TypeMapProperty(PropertyInfo pi, DataMemberAttribute dma)
     : base(pi, dma)
 {
     this.property = pi;
 }
Ejemplo n.º 25
0
 protected virtual void Initialize(DataMemberAttribute attribute)
 {
     Name  = attribute.Name;
     Order = attribute.Order;
 }
Ejemplo n.º 26
0
        private static DefinitionProperty ProcessProperty(PropertyInfo propertyInfo, IList <string> hiddenTags,
                                                          Stack <Type> typesStack)
        {
            if (propertyInfo.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null ||
                propertyInfo.GetCustomAttributes <SwaggerWcfTagAttribute>()
                .Select(t => t.TagName)
                .Any(hiddenTags.Contains))
            {
                return(null);
            }

            TypeFormat typeFormat = Helpers.MapSwaggerType(propertyInfo.PropertyType, null);

            DefinitionProperty prop = new DefinitionProperty {
                Title = propertyInfo.Name
            };

            DataMemberAttribute dataMemberAttribute = propertyInfo.GetCustomAttribute <DataMemberAttribute>();

            if (dataMemberAttribute != null)
            {
                if (!string.IsNullOrEmpty(dataMemberAttribute.Name))
                {
                    prop.Title = dataMemberAttribute.Name;
                }

                prop.Required = dataMemberAttribute.IsRequired;
            }

            // Special case - if it came out required, but we unwrapped a null-able type,
            // then it's necessarily not required.  Ideally this would only set the default,
            // but we can't tell the difference between an explicit delaration of
            // IsRequired =false on the DataMember attribute and no declaration at all.
            if (prop.Required && propertyInfo.PropertyType.IsGenericType &&
                propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                prop.Required = false;
            }

            DescriptionAttribute descriptionAttribute = propertyInfo.GetCustomAttribute <DescriptionAttribute>();

            if (descriptionAttribute != null)
            {
                prop.Description = descriptionAttribute.Description;
            }

            prop.TypeFormat = typeFormat;

            if (prop.TypeFormat.Type == ParameterType.Object)
            {
                typesStack.Push(propertyInfo.PropertyType);

                prop.Ref = propertyInfo.PropertyType.FullName;

                return(prop);
            }

            if (prop.TypeFormat.Type == ParameterType.Array)
            {
                Type subType = GetEnumerableType(propertyInfo.PropertyType);
                if (subType != null)
                {
                    TypeFormat subTypeFormat = Helpers.MapSwaggerType(subType, null);

                    if (subTypeFormat.Type == ParameterType.Object)
                    {
                        typesStack.Push(subType);
                    }

                    prop.Items = new ParameterItems
                    {
                        TypeFormat = subTypeFormat
                    };
                }
            }

            if (prop.TypeFormat.Type == ParameterType.String && prop.TypeFormat.Format == "enum")
            {
                prop.Enum = new List <string>();

                Type propType = propertyInfo.PropertyType;

                if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    propType = propType.GetEnumerableType();
                }

                List <string> listOfEnumNames = propType.GetEnumNames().ToList();
                foreach (string enumName in listOfEnumNames)
                {
                    prop.Enum.Add(GetEnumMemberValue(propType, enumName));
                }
            }

            // Apply any options set in a [SwaggerWcfProperty]
            ApplyAttributeOptions(propertyInfo, prop);

            return(prop);
        }
Ejemplo n.º 27
0
		/// <summary>
		///		Initializes a new instance of the <see cref="DataMemberContract"/> struct from <see cref="DataMemberAttribute"/>.
		/// </summary>
		/// <param name="member">The target member.</param>
		/// <param name="attribute">The data contract member attribute. This value can be <c>null</c>.</param>
		public DataMemberContract( MemberInfo member, DataMemberAttribute attribute )
		{
			Contract.Requires( member != null );
			Contract.Requires( attribute != null );

			this._name = String.IsNullOrEmpty( attribute.Name ) ? member.Name : attribute.Name;
			this._nilImplication = Serialization.NilImplication.MemberDefault;
			this._id = attribute.Order;
		}
Ejemplo n.º 28
0
        /// <summary>
        /// Returns the string representation of the embededobject.
        /// </summary>
        /// <param name="format">(Unused). Leave this as null</param>
        /// <param name="formatProvider">The provider of a mechanism for retrieving an object to control formatting.</param>
        /// <returns>
        /// A <see cref="T:System.String"/> containing the value of the current embeded instance in the specified format.
        /// </returns>
        /// <exception cref="FormatException">Thrown if the <i>format</i> parameter is not null</exception>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (format == null)
            {
                if (m_body is byte[])
                {
                    return(String.Format(formatProvider, "Byte[{0}]", ((byte[])m_body).Length));
                }

                if (m_body is XmlElement)
                {
                    return(String.Format(formatProvider, "<{0}>", ((XmlElement)m_body).Name));
                }

                if (m_body is IFormattable)
                {
                    return(String.Format(formatProvider, "{0}", ((IFormattable)m_body).ToString(null, formatProvider)));
                }

                if (m_body is IEncodeable)
                {
                    StringBuilder body = new StringBuilder();

                    PropertyInfo[] properties = m_body.GetType().GetProperties(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);

                    foreach (PropertyInfo property in properties)
                    {
                        object[] attributes = property.GetCustomAttributes(typeof(DataMemberAttribute), true).ToArray();

                        for (int ii = 0; ii < attributes.Length; ii++)
                        {
                            DataMemberAttribute contract = attributes[ii] as DataMemberAttribute;

                            if (contract != null)
                            {
                                if (body.Length == 0)
                                {
                                    body.Append('{');
                                }
                                else
                                {
                                    body.Append(" | ");
                                }

                                body.AppendFormat("{0}", property.GetGetMethod().Invoke(m_body, null));
                            }
                        }
                    }

                    if (body.Length > 0)
                    {
                        body.Append('}');
                    }

                    return(String.Format(formatProvider, "{0}", body));
                }

                if (!NodeId.IsNull(this.m_typeId))
                {
                    return(String.Format(formatProvider, "{{{0}}}", this.m_typeId));
                }

                return("(null)");
            }

            throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format));
        }
Ejemplo n.º 29
0
        private void GeneratedControlByPropertyInfo(PropertyInfo property)
        {
            Type propertyType = property.PropertyType;

            if (propertyType == typeof(Guid))
            {
                return;
            }
            DataMemberAttribute dataMember = property.GetCustomAttributes(typeof(DataMemberAttribute), false)
                                             .FirstOrDefault() as DataMemberAttribute;

            if (dataMember == null)
            {
                return;
            }
            NotMappedAttribute notMapped = property.GetCustomAttributes(typeof(NotMappedAttribute), false)
                                           .FirstOrDefault() as NotMappedAttribute;

            if (notMapped != null)
            {
                return;
            }
            DisplayNameAttribute display = property.GetCustomAttributes(typeof(DisplayNameAttribute), false)
                                           .FirstOrDefault() as DisplayNameAttribute;
            MaxLengthAttribute maxLength = property.GetCustomAttributes(typeof(MaxLengthAttribute), false)
                                           .FirstOrDefault() as MaxLengthAttribute;

            if (display == null)
            {
                return;
            }
            //标签处理
            Label label = new Label();

            label.Width     = EditControlWidth / 2;
            label.Name      = label.GetType().Name + property.Name;
            label.Text      = display.DisplayName + ":";
            label.TextAlign = ContentAlignment.MiddleCenter;
            EditControls.Add(label);
            if (propertyType == typeof(string))
            {
                //字符串
                TextBox textBox = new TextBox();
                textBox.Name  = textBox.GetType().Name + property.Name;
                textBox.Width = EditControlWidth;
                //处理长度
                if (maxLength == null)
                {
                    textBox.MaxLength = 32;
                }
                else
                {
                    textBox.MaxLength = maxLength.Length / 2;
                }
                EditControls.Add(textBox);
            }
            //日期
            else if (propertyType == typeof(DateTime))
            {
                DateTimePicker dateTimePicker = new DateTimePicker();
                dateTimePicker.Name    = dateTimePicker.GetType().Name + property.Name;
                dateTimePicker.Value   = DateTime.Now;
                dateTimePicker.Width   = EditControlWidth;
                dateTimePicker.MaxDate = DateTime.Now.AddYears(100);
                dateTimePicker.MinDate = DateTime.Now.AddYears(-100);
                EditControls.Add(dateTimePicker);
            }
        }