private JsonMemberSerializationInfo(FieldInfo field, PropertyInfo property, Type memberType, JsonPropertyAttribute jsonProperty)
 {
     Field = field;
     Property = property;
     MemberType = memberType;
     JsonProperty = jsonProperty;
     Serializer = (jsonProperty != null ? JsonSerializer.CreateSerializer(memberType, jsonProperty.SerializeAs) : JsonSerializer.CreateSerializer(memberType));
     Name = (jsonProperty != null && !string.IsNullOrEmpty(jsonProperty.Name) ? jsonProperty.Name : (property != null ? property.Name : field.Name));
 }
    public void NullValueHandlingTest()
    {
      JsonPropertyAttribute attribute = new JsonPropertyAttribute();
      Assert.AreEqual(null, attribute._nullValueHandling);
      Assert.AreEqual(NullValueHandling.Include, attribute.NullValueHandling);

      attribute.NullValueHandling = NullValueHandling.Ignore;
      Assert.AreEqual(NullValueHandling.Ignore, attribute._nullValueHandling);
      Assert.AreEqual(NullValueHandling.Ignore, attribute.NullValueHandling);
    }
    public void DefaultValueHandlingTest()
    {
      JsonPropertyAttribute attribute = new JsonPropertyAttribute();
      Assert.AreEqual(null, attribute._defaultValueHandling);
      Assert.AreEqual(DefaultValueHandling.Include, attribute.DefaultValueHandling);

      attribute.DefaultValueHandling = DefaultValueHandling.Ignore;
      Assert.AreEqual(DefaultValueHandling.Ignore, attribute._defaultValueHandling);
      Assert.AreEqual(DefaultValueHandling.Ignore, attribute.DefaultValueHandling);
    }
    public void ReferenceLoopHandlingTest()
    {
      JsonPropertyAttribute attribute = new JsonPropertyAttribute();
      Assert.AreEqual(null, attribute._defaultValueHandling);
      Assert.AreEqual(ReferenceLoopHandling.Error, attribute.ReferenceLoopHandling);

      attribute.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
      Assert.AreEqual(ReferenceLoopHandling.Ignore, attribute._referenceLoopHandling);
      Assert.AreEqual(ReferenceLoopHandling.Ignore, attribute.ReferenceLoopHandling);
    }
    public void IsReferenceTest()
    {
      JsonPropertyAttribute attribute = new JsonPropertyAttribute();
      Assert.AreEqual(null, attribute._isReference);
      Assert.AreEqual(false, attribute.IsReference);

      attribute.IsReference = false;
      Assert.AreEqual(false, attribute._isReference);
      Assert.AreEqual(false, attribute.IsReference);

      attribute.IsReference = true;
      Assert.AreEqual(true, attribute._isReference);
      Assert.AreEqual(true, attribute.IsReference);
    }
        // 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);
        }
        private static List <ElasticExpressionPropertyInfo> GetProperties(Type T, string Parameter)
        {
            List <ElasticExpressionPropertyInfo> Props = new List <ElasticExpressionPropertyInfo>();

            try
            {
                T.GetProperties()
                .ToList()
                .ForEach(x =>
                {
                    JsonPropertyAttribute attr2 = x.GetCustomAttributes(true).Where(y => y is JsonPropertyAttribute).FirstOrDefault() as JsonPropertyAttribute;
                    if (attr2 != null)
                    {
                        if (!string.IsNullOrEmpty(attr2.PropertyName))
                        {
                            attr2.PropertyName = attr2.PropertyName.Replace("-raw", "");
                        }
                        Props.Add(new ElasticExpressionPropertyInfo()
                        {
                            PropertyName        = Parameter + "." + x.Name,
                            ElasticPropertyName = attr2.PropertyName,
                            PropertyType        = x.PropertyType
                        });
                    }
                    else
                    {
                        Props.Add(new ElasticExpressionPropertyInfo()
                        {
                            PropertyName        = Parameter + "." + x.Name,
                            ElasticPropertyName = x.Name.Length > 1 ? x.Name.Substring(0, 2).ToLower() + x.Name.Substring(2) : x.Name.ToLower(),
                            PropertyType        = x.PropertyType
                        });
                    }
                });
            }
            catch (Exception)
            {
            }

            return(Props);
        }
Пример #8
0
    /// <inheritdoc />
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var     properties = value.GetType().GetRuntimeProperties().Where(p => p.CanRead && p.CanWrite);
        JObject main       = new JObject();

        foreach (PropertyInfo prop in properties)
        {
            JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                                        .OfType <JsonPropertyAttribute>()
                                        .FirstOrDefault();

            string jsonPath = att != null ? att.PropertyName : prop.Name;
            if (serializer.ContractResolver is DefaultContractResolver)
            {
                var resolver = (DefaultContractResolver)serializer.ContractResolver;
                jsonPath = resolver.GetResolvedPropertyName(jsonPath);
            }

            var     nesting   = jsonPath.Split('.');
            JObject lastLevel = main;

            for (int i = 0; i < nesting.Length; i++)
            {
                if (i == nesting.Length - 1)
                {
                    lastLevel[nesting[i]] = new JValue(prop.GetValue(value));
                }
                else
                {
                    if (lastLevel[nesting[i]] == null)
                    {
                        lastLevel[nesting[i]] = new JObject();
                    }

                    lastLevel = (JObject)lastLevel[nesting[i]];
                }
            }
        }

        serializer.Serialize(writer, main);
    }
Пример #9
0
        public bool Parse(ref string requestString, JsonPropertyAttribute attribute, PropertyInfo property, object propertyValue, object propertyParent)
        {
            if (!attribute.PropertyName.Contains("metadata") && !attribute.PropertyName.Contains("fraud_details"))
            {
                return(false);
            }

            var dictionary = (Dictionary <string, string>)propertyValue;

            if (dictionary == null)
            {
                return(true);
            }

            foreach (var key in dictionary.Keys)
            {
                RequestStringBuilder.ApplyParameterToRequestString(ref requestString, $"{attribute.PropertyName}[{key}]", dictionary[key]);
            }

            return(true);
        }
        public bool Parse(ref string requestString, JsonPropertyAttribute attribute, PropertyInfo property, object propertyValue, object propertyParent)
        {
            if (attribute.PropertyName != "subscription_items_array_invoice")
            {
                return(false);
            }

            var items = ((List <StripeInvoiceSubscriptionItemOptions>)property.GetValue(propertyParent, null));

            var itemIndex = 0;

            foreach (var item in items)
            {
                var properties = item.GetType().GetRuntimeProperties();

                foreach (var prop in properties)
                {
                    var value = prop.GetValue(item, null);
                    if (value == null)
                    {
                        continue;
                    }

                    // it must have a json attribute matching stripe's key, and only one
                    var attr = prop.GetCustomAttributes <JsonPropertyAttribute>().SingleOrDefault();
                    if (attr == null)
                    {
                        continue;
                    }

                    RequestStringBuilder.ApplyParameterToRequestString(ref requestString,
                                                                       $"subscription_items[{itemIndex}][{attr.PropertyName}]", value.ToString());
                }

                itemIndex++;
            }

            return(true);
        }
    public override object ReadJson(JsonReader reader, Type objectType,
                                    object existingValue, JsonSerializer serializer)
    {
        JObject jo        = JObject.Load(reader);
        object  targetObj = Activator.CreateInstance(objectType);

        foreach (PropertyInfo prop in objectType.GetProperties()
                 .Where(p => p.CanRead && p.CanWrite))
        {
            JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                                        .OfType <JsonPropertyAttribute>()
                                        .FirstOrDefault();
            string jsonPath = (att != null ? att.PropertyName : prop.Name);
            JToken token    = jo.SelectToken(jsonPath);
            if (token != null && token.Type != JTokenType.Null)
            {
                object value = token.ToObject(prop.PropertyType, serializer);
                prop.SetValue(targetObj, value, null);
            }
        }
        return(targetObj);
    }
Пример #12
0
        /// <summary>
        /// 获取请求类的keyValue
        /// </summary>
        /// <param name="request"></param>
        /// <param name="notDeal"></param>
        /// <returns></returns>
        private string GetRequestKeyValue(BaseRequest request)
        {
            List <string> keyVals  = new List <string>();
            Type          type     = request.GetType();
            var           propList = type.GetProperties().OrderBy(x => x.Name.ToLower()).ToList();

            propList.ForEach(p =>
            {
                JsonPropertyAttribute attr = (JsonPropertyAttribute)p.GetCustomAttributes(typeof(JsonPropertyAttribute), true).FirstOrDefault();
                if (attr != null)
                {
                    string key   = attr.PropertyName;
                    string value = string.Empty;
                    if (p.PropertyType.IsClass && p.PropertyType != typeof(String))
                    {
                        value = JsonConvert.SerializeObject(p.GetValue(request));
                    }
                    else
                    {
                        value = p.GetValue(request) != null ? p.GetValue(request).ToString() : string.Empty;
                    }
                    switch (key)
                    {
                    case "client_key":
                        value = Client_key;
                        break;

                    case "client_secret":
                        value = Client_secret;
                        break;
                    }
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        keyVals.Add(key + "=" + HttpUtility.UrlEncode(value));
                    }
                }
            });
            return(string.Join("&", keyVals));
        }
Пример #13
0
        public bool Parse(ref string requestString, JsonPropertyAttribute attribute, PropertyInfo property, object propertyValue, object propertyParent)
        {
            if (attribute.PropertyName != "subscription_items_array_updated")
            {
                return(false);
            }

            var items = ((List <StripeSubscriptionItemUpdateOption>)property.GetValue(propertyParent, null));

            var itemIndex = 0;

            foreach (var item in items)
            {
                var properties = item.GetType().GetRuntimeProperties();

                foreach (var prop in properties)
                {
                    var value = prop.GetValue(item, null);
                    if (value == null)
                    {
                        continue;
                    }

                    // it must have a json attribute matching stripe's key, and only one
                    var attr = prop.GetCustomAttributes <JsonPropertyAttribute>().SingleOrDefault();
                    if (attr == null)
                    {
                        continue;
                    }
                    // a JsonPropertyAttribute is required to supply a property name to parser plugins.
                    var indexedItemAttribute = new JsonPropertyAttribute($"items[{itemIndex}][{attr.PropertyName}]");
                    RequestStringBuilder.ProcessPlugins(ref requestString, indexedItemAttribute, prop, value, propertyParent);
                }

                itemIndex++;
            }

            return(true);
        }
Пример #14
0
        private string GetConcateFieldsStr(string[] duplicateFieldList, IList <PropertyInfo> props, object entity)
        {
            string concatedString = string.Empty;

            foreach (string field in duplicateFieldList)
            {
                foreach (PropertyInfo p in props)
                {
                    JsonPropertyAttribute attr = p.GetCustomAttributes <JsonPropertyAttribute>().FirstOrDefault(m => m.PropertyName.ToLower() == field.ToLower());
                    if (attr != null)
                    {
                        object value = p.GetValue(entity, null);
                        if (value != null)
                        {
                            concatedString += value.ToString();
                        }
                        break;
                    }
                }
            }
            return(concatedString);
        }
        /// <summary>
        ///     Get the JSON property name corresponding to the specified model property.
        /// </summary>
        /// <param name="modelType">
        ///     The model <see cref="Type"/>.
        /// </param>
        /// <param name="propertyName">
        ///     The name of the target property.
        /// </param>
        /// <returns>
        ///     The JSON property name.
        /// </returns>
        static string GetJsonPropertyName(Type modelType, string propertyName)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException(nameof(modelType));
            }

            if (String.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'propertyName'.", nameof(propertyName));
            }

            PropertyInfo targetProperty = modelType.GetProperty(propertyName);

            Assert.NotNull(targetProperty);

            JsonPropertyAttribute jsonPropertyAttribute = targetProperty.GetCustomAttribute <JsonPropertyAttribute>();

            Assert.NotNull(jsonPropertyAttribute);

            return(jsonPropertyAttribute.PropertyName);
        }
Пример #16
0
    /// <inheritdoc />
    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        JObject jo        = JObject.Load(reader);
        object  targetObj = Activator.CreateInstance(objectType);

        foreach (PropertyInfo prop in objectType.GetProperties().Where(p => p.CanRead && p.CanWrite))
        {
            JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                                        .OfType <JsonPropertyAttribute>()
                                        .FirstOrDefault();

            string jsonPath = att != null ? att.PropertyName : prop.Name;

            if (serializer.ContractResolver is DefaultContractResolver)
            {
                var resolver = (DefaultContractResolver)serializer.ContractResolver;
                jsonPath = resolver.GetResolvedPropertyName(jsonPath);
            }

            if (!Regex.IsMatch(jsonPath, @"^[a-zA-Z0-9_.-]+$"))
            {
                throw new InvalidOperationException($"JProperties of JsonPathConverter can have only letters, numbers, underscores, hiffens and dots but name was ${jsonPath}.");         // Array operations not permitted
            }

            JToken token = jo.SelectToken(jsonPath);
            if (token != null && token.Type != JTokenType.Null)
            {
                object value = token.ToObject(prop.PropertyType, serializer);
                prop.SetValue(targetObj, value, null);
            }
        }

        return(targetObj);
    }
Пример #17
0
        /// <summary>
        /// Determines whether the given property corresponds with a given field.
        /// </summary>
        /// <param name="modelProperty">CLR property to be compared with <paramref name="fieldName"/>.</param>
        /// <param name="fieldName">Name of the field in <paramref name="contentType"/>.</param>
        /// <param name="contentType">Content type containing <paramref name="fieldName"/>.</param>
        /// <returns>TRUE if <paramref name="modelProperty"/> is a CLR representation of <paramref name="fieldName"/> in <paramref name="contentType"/>.</returns>
        public bool IsMatch(PropertyInfo modelProperty, string fieldName, string contentType)
        {
            var ignoreAttribute = modelProperty.GetCustomAttribute <JsonIgnoreAttribute>();

            if (ignoreAttribute != null)
            {
                // If JsonIgnore is set, do not match
                return(false);
            }
            else
            {
                JsonPropertyAttribute propertyAttr = modelProperty.GetCustomAttribute <JsonPropertyAttribute>();
                if (propertyAttr != null)
                {
                    // Try to get the name of the field from the JSON serialization property
                    return(fieldName.Equals(propertyAttr.PropertyName, StringComparison.Ordinal));
                }
                else
                {
                    // Default mapping
                    return(fieldName.Replace("_", "").Equals(modelProperty.Name, StringComparison.OrdinalIgnoreCase));
                }
            }
        }
Пример #18
0
    public override IDictionary <string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Type type = obj.GetType();
        List <MemberInfo> members = new List <MemberInfo>();

        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        Dictionary <string, object> values = new Dictionary <string, object>();

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));
            if (jsonProperty != null)
            {
                values[jsonProperty.Name] = GetMemberValue(member, obj);
            }
            else
            {
                values[member.Name] = GetMemberValue(member, obj);
            }
        }
        return(values);
    }
        private static CustomAttributes GetCustomAttributes(MemberInfo property)
        {
            JsonIgnoreAttribute   jsonIgnoreAttribute   = null;
            JsonPropertyAttribute jsonPropertyAttribute = null;
            Attribute             dataMemberAttribute   = null;

            foreach (var attribute in property.GetCustomAttributes(true).OfType <Attribute>())
            {
                if (attribute is JsonIgnoreAttribute)
                {
                    jsonIgnoreAttribute = attribute as JsonIgnoreAttribute;
                }
                else if (attribute is JsonPropertyAttribute)
                {
                    jsonPropertyAttribute = attribute as JsonPropertyAttribute;
                }
                else if (attribute.GetType().Name == "DataMemberAttribute")
                {
                    dataMemberAttribute = attribute;
                }
            }

            return(new CustomAttributes(jsonIgnoreAttribute, jsonPropertyAttribute, GetDataContractAttribute(property.DeclaringType), dataMemberAttribute));
        }
Пример #20
0
        public bool Parse(ref string requestString, JsonPropertyAttribute attribute, PropertyInfo property, object propertyValue, object propertyParent)
        {
            if (property.PropertyType != typeof(StripeDateFilter))
            {
                return(false);
            }

            var filter = (StripeDateFilter)propertyValue;

            if (filter.EqualTo.HasValue)
            {
                RequestStringBuilder.ApplyParameterToRequestString(ref requestString, attribute.PropertyName, filter.EqualTo.Value.ToUniversalTime().ConvertDateTimeToEpoch().ToString());
            }

            if (filter.LessThan.HasValue)
            {
                RequestStringBuilder.ApplyParameterToRequestString(ref requestString, attribute.PropertyName + "[lt]", filter.LessThan.Value.ToUniversalTime().ConvertDateTimeToEpoch().ToString());
            }

            if (filter.LessThanOrEqual.HasValue)
            {
                RequestStringBuilder.ApplyParameterToRequestString(ref requestString, attribute.PropertyName + "[lte]", filter.LessThanOrEqual.Value.ToUniversalTime().ConvertDateTimeToEpoch().ToString());
            }

            if (filter.GreaterThan.HasValue)
            {
                RequestStringBuilder.ApplyParameterToRequestString(ref requestString, attribute.PropertyName + "[gt]", filter.GreaterThan.Value.ToUniversalTime().ConvertDateTimeToEpoch().ToString());
            }

            if (filter.GreaterThanOrEqual.HasValue)
            {
                RequestStringBuilder.ApplyParameterToRequestString(ref requestString, attribute.PropertyName + "[gte]", filter.GreaterThanOrEqual.Value.ToUniversalTime().ConvertDateTimeToEpoch().ToString());
            }

            return(true);
        }
Пример #21
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);
        }
Пример #22
0
        public static List <KeyValuePair <string, object> > PrepareFormFieldsFromObject(
            string name, object value, List <KeyValuePair <string, object> > keys = null, PropertyInfo propInfo = null, ArrayDeserialization arrayDeserializationFormat = ArrayDeserialization.UnIndexed)
        {
            keys = keys ?? new List <KeyValuePair <string, object> >();

            if (value == null)
            {
                return(keys);
            }
            else if (value is Stream)
            {
                keys.Add(new KeyValuePair <string, object>(name, value));
                return(keys);
            }
            else if (value is JObject)
            {
                var valueAccept = (value as JObject);
                foreach (var property in valueAccept.Properties())
                {
                    string pKey        = property.Name;
                    object pValue      = property.Value;
                    var    fullSubName = name + '[' + pKey + ']';
                    PrepareFormFieldsFromObject(fullSubName, pValue, keys, propInfo, arrayDeserializationFormat);
                }
            }
            else if (value is IList)
            {
                var enumerator = ((IEnumerable)value).GetEnumerator();

                var hasNested = false;
                while (enumerator.MoveNext())
                {
                    var subValue = enumerator.Current;
                    if (subValue != null && (subValue is JObject || subValue is IList || subValue is IDictionary || !(subValue.GetType().Namespace.StartsWith("System"))))
                    {
                        hasNested = true;
                        break;
                    }
                }

                int i = 0;
                enumerator.Reset();
                while (enumerator.MoveNext())
                {
                    var fullSubName = name + '[' + i + ']';
                    if (!hasNested && arrayDeserializationFormat == ArrayDeserialization.UnIndexed)
                    {
                        fullSubName = name + "[]";
                    }
                    else if (!hasNested && arrayDeserializationFormat == ArrayDeserialization.Plain)
                    {
                        fullSubName = name;
                    }

                    var subValue = enumerator.Current;
                    if (subValue == null)
                    {
                        continue;
                    }
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo, arrayDeserializationFormat);
                    i++;
                }
            }
            else if (value is JToken)
            {
                keys.Add(new KeyValuePair <string, object>(name, value.ToString()));
            }
            else if (value is Enum)
            {
#if WINDOWS_UWP || NETSTANDARD1_3
                Assembly thisAssembly = typeof(APIHelper).GetTypeInfo().Assembly;
#else
                Assembly thisAssembly = Assembly.GetExecutingAssembly();
#endif
                string enumTypeName   = value.GetType().FullName;
                Type   enumHelperType = thisAssembly.GetType(string.Format("{0}Helper", enumTypeName));
                object enumValue      = (int)value;

                if (enumHelperType != null)
                {
                    //this enum has an associated helper, use that to load the value
#if NETSTANDARD1_3
                    MethodInfo enumHelperMethod = enumHelperType.GetRuntimeMethod("ToValue", new[] { value.GetType() });
#else
                    MethodInfo enumHelperMethod = enumHelperType.GetMethod("ToValue", new[] { value.GetType() });
#endif
                    if (enumHelperMethod != null)
                    {
                        enumValue = enumHelperMethod.Invoke(null, new object[] { value });
                    }
                }

                keys.Add(new KeyValuePair <string, object>(name, enumValue));
            }
            else if (value is IDictionary)
            {
                var obj = (IDictionary)value;
                foreach (var sName in obj.Keys)
                {
                    var    subName     = sName.ToString();
                    var    subValue    = obj[subName];
                    string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']';
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo, arrayDeserializationFormat);
                }
            }
            else if (!(value.GetType().Namespace.StartsWith("System")))
            {
                //Custom object Iterate through its properties
#if NETSTANDARD1_3
                var enumerator = value.GetType().GetRuntimeProperties().GetEnumerator();
#else
                var enumerator = value.GetType().GetProperties().GetEnumerator();;
#endif
                PropertyInfo pInfo = null;
                var          t     = new JsonPropertyAttribute().GetType();
                while (enumerator.MoveNext())
                {
                    pInfo = enumerator.Current as PropertyInfo;

                    var    jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(t, true).FirstOrDefault();
                    var    subName      = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name;
                    string fullSubName  = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']';
                    var    subValue     = pInfo.GetValue(value, null);
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys, pInfo, arrayDeserializationFormat);
                }
            }
            else if (value is DateTime)
            {
                string convertedValue = null;
#if NETSTANDARD1_3
                IEnumerable <Attribute> pInfo = null;
#else
                object[] pInfo = null;
#endif
                if (propInfo != null)
                {
                    pInfo = propInfo.GetCustomAttributes(true);
                }
                if (pInfo != null)
                {
                    foreach (object attr in pInfo)
                    {
                        JsonConverterAttribute converterAttr = attr as JsonConverterAttribute;
                        if (converterAttr != null)
                        {
                            convertedValue =
                                JsonSerialize(value,
                                              (JsonConverter)
                                              Activator.CreateInstance(converterAttr.ConverterType,
                                                                       converterAttr.ConverterParameters)).Replace("\"", "");
                        }
                    }
                }
                keys.Add(new KeyValuePair <string, object>(name, (convertedValue) ?? ((DateTime)value).ToString(DateTimeFormat)));
            }
            else
            {
                keys.Add(new KeyValuePair <string, object>(name, value));
            }
            return(keys);
        }
Пример #23
0
        private void DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false)
        {
            if (!recordType.IsDynamicType())
            {
                Type pt = null;
                if (ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType<ChoJSONRecordFieldAttribute>().Any()).Any())
                {
                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        pt = pd.PropertyType.GetUnderlyingType();
                        bool optIn1 = ChoTypeDescriptor.GetProperties(pt).Where(pd1 => pd1.Attributes.OfType<ChoJSONRecordFieldAttribute>().Any()).Any();
                        if (optIn1 && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn1);
                        }
                        else if (pd.Attributes.OfType<ChoJSONRecordFieldAttribute>().Any())
                        {
                            var obj = new ChoJSONRecordFieldConfiguration(pd.Name, pd.Attributes.OfType<ChoJSONRecordFieldAttribute>().First(), pd.Attributes.OfType<Attribute>().ToArray());
                            obj.FieldType = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember = declaringMember == null ? null : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            if (!JSONRecordFieldConfigurations.Any(c => c.Name == pd.Name))
                                JSONRecordFieldConfigurations.Add(obj);
                        }
                    }
                }
                else
                {
                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        JsonIgnoreAttribute jiAttr = pd.Attributes.OfType<JsonIgnoreAttribute>().FirstOrDefault();
                        if (jiAttr != null)
                            continue;

                        pt = pd.PropertyType.GetUnderlyingType();
                        if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn);
                        }
                        else
                        {
                            var obj = new ChoJSONRecordFieldConfiguration(pd.Name, (string)null);
                            obj.FieldType = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember = declaringMember == null ? null : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            StringLengthAttribute slAttr = pd.Attributes.OfType<StringLengthAttribute>().FirstOrDefault();
                            if (slAttr != null && slAttr.MaximumLength > 0)
                                obj.Size = slAttr.MaximumLength;
                            ChoUseJSONSerializationAttribute sAttr = pd.Attributes.OfType<ChoUseJSONSerializationAttribute>().FirstOrDefault();
                            if (sAttr != null)
                                obj.UseJSONSerialization = true;

                            JsonPropertyAttribute jAttr = pd.Attributes.OfType<JsonPropertyAttribute>().FirstOrDefault();
                            if (jAttr != null && !jAttr.PropertyName.IsNullOrWhiteSpace())
                            {
                                obj.FieldName = jAttr.PropertyName;
                            }
                            else
                            {
                                DisplayAttribute dpAttr = pd.Attributes.OfType<DisplayAttribute>().FirstOrDefault();
                                if (dpAttr != null)
                                {
                                    if (!dpAttr.ShortName.IsNullOrWhiteSpace())
                                        obj.FieldName = dpAttr.ShortName;
                                    else if (!dpAttr.Name.IsNullOrWhiteSpace())
                                        obj.FieldName = dpAttr.Name;
                                }
                            }
                            DisplayFormatAttribute dfAttr = pd.Attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();
                            if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace())
                            {
                                obj.FormatText = dfAttr.DataFormatString;
                            }
                            if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace())
                            {
                                obj.NullValue = dfAttr.NullDisplayText;
                            }
                            if (!JSONRecordFieldConfigurations.Any(c => c.Name == pd.Name))
                                JSONRecordFieldConfigurations.Add(obj);
                        }
                    }
                }
            }
        }
Пример #24
0
        /// <summary>
        /// Validates, creates and compiles the property expression; whilst also determinig the property friendly <see cref="Text"/>.
        /// </summary>
        /// <param name="propertyExpression">The <see cref="Expression"/> to reference the entity property.</param>
        /// <param name="probeForJsonRefDataSidProperties">Indicates whether to probe for the <see cref="T:JsonPropertyAttribute"/> via alternate <c>Sid</c> or <c>Sids</c> properties as implemented for reference data.</param>
        /// <returns>A <see cref="PropertyExpression{TEntity, TProperty}"/> which contains (in order) the compiled <see cref="System.Func{TEntity, TProperty}"/>, member name and resulting property text.</returns>
        public static PropertyExpression <TEntity, TProperty> Create(Expression <Func <TEntity, TProperty> > propertyExpression, bool probeForJsonRefDataSidProperties = false)
        {
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }

            if (propertyExpression.Body.NodeType != ExpressionType.MemberAccess)
            {
                throw new InvalidOperationException("Only Member access expressions are supported.");
            }

            var me = (MemberExpression)propertyExpression.Body;

            // Check cache and reuse as this is an expensive operation.
            var key = new ExpressionKey {
                Type = me.Member.DeclaringType, Name = me.Member.Name, ProbeForJsonRefDataSidProperties = probeForJsonRefDataSidProperties
            };

            if (_expressions.ContainsKey(key))
            {
                return(_expressions[key]);
            }

            if (me.Member.MemberType != MemberTypes.Property)
            {
                throw new InvalidOperationException("Expression results in a Member that is not a Property.");
            }

            if (!me.Member.DeclaringType.GetTypeInfo().IsAssignableFrom(typeof(TEntity).GetTypeInfo()))
            {
                throw new InvalidOperationException("Expression results in a Member for a different Entity class.");
            }

            var pe = new PropertyExpression <TEntity, TProperty>()
            {
                Name = me.Member.Name
            };

            // Either get the friendly text from a corresponding DisplayTextAttribute or split the PascalCase member name into friendlier sentence case text.
            DisplayAttribute ca = me.Member.GetCustomAttribute <DisplayAttribute>(true);

            pe.Text = ca == null?Beef.CodeGen.CodeGenerator.ToSentenceCase(pe.Name) : ca.Name;

            // Get the JSON property name.
            JsonPropertyAttribute jpa = me.Member.GetCustomAttribute <JsonPropertyAttribute>(true);

            if (jpa == null && probeForJsonRefDataSidProperties)
            {
                // Probe corresponding Sid or Sids properties for value (using the standardised naming convention).
                var pi = me.Member.DeclaringType.GetProperty($"{pe.Name}Sid");
                if (pi == null)
                {
                    pi = me.Member.DeclaringType.GetProperty($"{pe.Name}Sids");
                }

                if (pi != null)
                {
                    jpa = pi.GetCustomAttribute <JsonPropertyAttribute>(true);
                }
            }

            pe.JsonPropertyAttribute = jpa;
            pe.JsonName = jpa == null ? pe.Name : jpa.PropertyName;

            // Compile the expression.
            pe._func = propertyExpression.Compile();

            // Recheck cache and use/update accordingly.
            lock (_lock)
            {
                if (_expressions.ContainsKey(key))
                {
                    return(_expressions[key]);
                }

                _expressions.Add(key, pe);
            }

            return(pe);
        }
Пример #25
0
        private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute)
        {
            hasExplicitAttribute = false;

            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType);

            DataMemberAttribute dataMemberAttribute;

            if (dataContractAttribute != null && attributeProvider is MemberInfo)
            {
                dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)attributeProvider);
            }
            else
            {
                dataMemberAttribute = null;
            }

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider);

            if (propertyAttribute != null)
            {
                hasExplicitAttribute = true;
            }

            bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null);

            string mappedName;

            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                mappedName = dataMemberAttribute.Name;
            }
            else
            {
                mappedName = name;
            }

            property.PropertyName   = ResolvePropertyName(mappedName);
            property.UnderlyingName = name;

            if (propertyAttribute != null)
            {
                property.Required = propertyAttribute.Required;
                property.Order    = propertyAttribute._order;
            }
            else if (dataMemberAttribute != null)
            {
                property.Required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
                property.Order    = (dataMemberAttribute.Order != -1) ? (int?)dataMemberAttribute.Order : null;
            }
            else
            {
                property.Required = Required.Default;
            }

            property.Ignored = (hasIgnoreAttribute ||
                                (memberSerialization == MemberSerialization.OptIn &&
                                 propertyAttribute == null &&
                                 dataMemberAttribute == null
                                ));

            // resolve converter for property
            // the class type might have a converter but the property converter takes presidence
            property.Converter       = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider);

            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling      = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling   = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling  = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
            property.TypeNameHandling       = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
            property.IsReference            = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            allowNonPublicAccess = false;
            if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (propertyAttribute != null)
            {
                allowNonPublicAccess = true;
            }
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess = true;
                hasExplicitAttribute = true;
            }
        }
Пример #26
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jo        = JObject.Load(reader);
            object  targetObj = Activator.CreateInstance(objectType);

            foreach (PropertyInfo prop in objectType.GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                                            .OfType <JsonPropertyAttribute>()
                                            .FirstOrDefault();

                string jsonPath = att != null ? att.PropertyName : prop.Name;

                if (serializer.ContractResolver is DefaultContractResolver)
                {
                    var resolver = (DefaultContractResolver)serializer.ContractResolver;
                    jsonPath = resolver.GetResolvedPropertyName(jsonPath);
                }

                //if (!Regex.IsMatch(jsonPath, @"^[a-zA-Z0-9_.-]+$"))
                //{
                //    throw new InvalidOperationException($"JProperties of JsonPathConverter can have only letters, numbers, underscores, hiffens and dots but name was ${jsonPath}."); // Array operations not permitted
                //}

                JToken token = jo.SelectToken(jsonPath);
                if (token != null && token.Type != JTokenType.Null)
                {
                    object value = token.ToObject(prop.PropertyType, serializer);
                    prop.SetValue(targetObj, value, null);
                }
            }

            return(targetObj);

            //var jo = JObject.Load(reader);
            //object targetObj = existingValue ?? Activator.CreateInstance(objectType);

            //foreach (var prop in objectType.GetProperties().Where(p => p.CanRead))
            //{
            //    var pathAttribute = prop.GetCustomAttributes(true).OfType<JsonPropertyAttribute>().FirstOrDefault();
            //    var converterAttribute = prop.GetCustomAttributes(true).OfType<JsonConverterAttribute>().FirstOrDefault();

            //    string jsonPath = pathAttribute?.PropertyName ?? prop.Name;
            //    var token = jo.SelectToken(jsonPath);

            //    if (token != null && token.Type != JTokenType.Null)
            //    {
            //        bool done = false;

            //        if (converterAttribute != null)
            //        {
            //            var args = converterAttribute.ConverterParameters ?? Array.Empty<object>();
            //            var converter = Activator.CreateInstance(converterAttribute.ConverterType, args) as JsonConverter;
            //            if (converter != null && converter.CanRead)
            //            {
            //                using (var sr = new StringReader(token.ToString()))
            //                using (var jr = new JsonTextReader(sr))
            //                {
            //                    var value = converter.ReadJson(jr, prop.PropertyType, prop.GetValue(targetObj), serializer);
            //                    if (prop.CanWrite)
            //                    {
            //                        prop.SetValue(targetObj, value);
            //                    }
            //                    done = true;
            //                }
            //            }
            //        }

            //        if (!done)
            //        {
            //            if (prop.CanWrite)
            //            {
            //                object value = token.ToObject(prop.PropertyType, serializer);
            //                prop.SetValue(targetObj, value);
            //            }
            //            else
            //            {
            //                using (var sr = new StringReader(token.ToString()))
            //                {
            //                    serializer.Populate(sr, prop.GetValue(targetObj));
            //                }
            //            }
            //        }
            //    }
            //}

            //return targetObj;
        }
Пример #27
0
        private void SetPropertySettingsFromAttributes(JsonProperty property, object attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess)
        {
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType);
            MemberInfo            memberInfo            = attributeProvider as MemberInfo;
            DataMemberAttribute   dataMemberAttribute;

            if (dataContractAttribute != null && memberInfo != null)
            {
                dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute(memberInfo);
            }
            else
            {
                dataMemberAttribute = null;
            }
            JsonPropertyAttribute attribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider);

            if (attribute != null)
            {
                property.HasMemberAttribute = true;
            }
            string propertyName;

            if (attribute != null && attribute.PropertyName != null)
            {
                propertyName = attribute.PropertyName;
            }
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                propertyName = dataMemberAttribute.Name;
            }
            else
            {
                propertyName = name;
            }
            property.PropertyName   = this.ResolvePropertyName(propertyName);
            property.UnderlyingName = name;
            bool flag = false;

            if (attribute != null)
            {
                property._required            = attribute._required;
                property.Order                = attribute._order;
                property.DefaultValueHandling = attribute._defaultValueHandling;
                flag = true;
            }
            else if (dataMemberAttribute != null)
            {
                property._required            = new Required?(dataMemberAttribute.IsRequired ? Required.AllowNull : Required.Default);
                property.Order                = ((dataMemberAttribute.Order != -1) ? new int?(dataMemberAttribute.Order) : null);
                property.DefaultValueHandling = ((!dataMemberAttribute.EmitDefaultValue) ? new DefaultValueHandling?(DefaultValueHandling.Ignore) : null);
                flag = true;
            }
            bool flag2 = JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null || JsonTypeReflector.GetAttribute <JsonExtensionDataAttribute>(attributeProvider) != null || JsonTypeReflector.GetAttribute <NonSerializedAttribute>(attributeProvider) != null;

            if (memberSerialization != MemberSerialization.OptIn)
            {
                bool flag3 = JsonTypeReflector.GetAttribute <IgnoreDataMemberAttribute>(attributeProvider) != null;
                property.Ignored = (flag2 || flag3);
            }
            else
            {
                property.Ignored = (flag2 || !flag);
            }
            property.Converter       = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            DefaultValueAttribute attribute2 = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider);

            if (attribute2 != null)
            {
                property.DefaultValue = attribute2.Value;
            }
            property.NullValueHandling         = ((attribute != null) ? attribute._nullValueHandling : null);
            property.ReferenceLoopHandling     = ((attribute != null) ? attribute._referenceLoopHandling : null);
            property.ObjectCreationHandling    = ((attribute != null) ? attribute._objectCreationHandling : null);
            property.TypeNameHandling          = ((attribute != null) ? attribute._typeNameHandling : null);
            property.IsReference               = ((attribute != null) ? attribute._isReference : null);
            property.ItemIsReference           = ((attribute != null) ? attribute._itemIsReference : null);
            property.ItemConverter             = ((attribute != null && attribute.ItemConverterType != null) ? JsonConverterAttribute.CreateJsonConverterInstance(attribute.ItemConverterType) : null);
            property.ItemReferenceLoopHandling = ((attribute != null) ? attribute._itemReferenceLoopHandling : null);
            property.ItemTypeNameHandling      = ((attribute != null) ? attribute._itemTypeNameHandling : null);
            allowNonPublicAccess               = false;
            if ((this.DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (attribute != null)
            {
                allowNonPublicAccess = true;
            }
            if (memberSerialization == MemberSerialization.Fields)
            {
                allowNonPublicAccess = true;
            }
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess        = true;
                property.HasMemberAttribute = true;
            }
        }
Пример #28
0
        private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess)
        {
            JsonPropertyAttribute attribute1 = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider);

            if (attribute1 != null)
            {
                property.HasMemberAttribute = true;
            }
            string propertyName = attribute1 == null || attribute1.PropertyName == null ? name : attribute1.PropertyName;

            property.PropertyName   = this.ResolvePropertyName(propertyName);
            property.UnderlyingName = name;
            bool flag1 = false;

            if (attribute1 != null)
            {
                property._required            = attribute1._required;
                property.Order                = attribute1._order;
                property.DefaultValueHandling = attribute1._defaultValueHandling;
                flag1 = true;
            }
            bool flag2 = JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null || JsonTypeReflector.GetAttribute <NonSerializedAttribute>(attributeProvider) != null;

            if (memberSerialization != MemberSerialization.OptIn)
            {
                bool flag3 = false;
                property.Ignored = flag2 || flag3;
            }
            else
            {
                property.Ignored = flag2 || !flag1;
            }
            property.Converter       = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            DefaultValueAttribute attribute2 = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider);

            if (attribute2 != null)
            {
                property.DefaultValue = attribute2.Value;
            }
            property.NullValueHandling         = attribute1 != null ? attribute1._nullValueHandling : new NullValueHandling?();
            property.ReferenceLoopHandling     = attribute1 != null ? attribute1._referenceLoopHandling : new ReferenceLoopHandling?();
            property.ObjectCreationHandling    = attribute1 != null ? attribute1._objectCreationHandling : new ObjectCreationHandling?();
            property.TypeNameHandling          = attribute1 != null ? attribute1._typeNameHandling : new TypeNameHandling?();
            property.IsReference               = attribute1 != null ? attribute1._isReference : new bool?();
            property.ItemIsReference           = attribute1 != null ? attribute1._itemIsReference : new bool?();
            property.ItemConverter             = attribute1 == null || attribute1.ItemConverterType == null ? (JsonConverter)null : JsonConverterAttribute.CreateJsonConverterInstance(attribute1.ItemConverterType);
            property.ItemReferenceLoopHandling = attribute1 != null ? attribute1._itemReferenceLoopHandling : new ReferenceLoopHandling?();
            property.ItemTypeNameHandling      = attribute1 != null ? attribute1._itemTypeNameHandling : new TypeNameHandling?();
            allowNonPublicAccess               = false;
            if ((this.DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (attribute1 != null)
            {
                allowNonPublicAccess = true;
            }
            if (memberSerialization != MemberSerialization.Fields)
            {
                return;
            }
            allowNonPublicAccess = true;
        }
        private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute)
        {
            hasExplicitAttribute = false;
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType);
            DataMemberAttribute   dataMemberAttribute;

            if (dataContractAttribute != null && attributeProvider is MemberInfo)
            {
                dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)attributeProvider);
            }
            else
            {
                dataMemberAttribute = null;
            }
            JsonPropertyAttribute attribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider);

            if (attribute != null)
            {
                hasExplicitAttribute = true;
            }
            bool   flag = JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null;
            string propertyName;

            if (attribute != null && attribute.PropertyName != null)
            {
                propertyName = attribute.PropertyName;
            }
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                propertyName = dataMemberAttribute.Name;
            }
            else
            {
                propertyName = name;
            }
            property.PropertyName   = this.ResolvePropertyName(propertyName);
            property.UnderlyingName = name;
            if (attribute != null)
            {
                property.Required = attribute.Required;
                property.Order    = attribute._order;
            }
            else if (dataMemberAttribute != null)
            {
                property.Required = ((!dataMemberAttribute.IsRequired) ? Required.Default : Required.AllowNull);
                property.Order    = ((dataMemberAttribute.Order == -1) ? null : new int?(dataMemberAttribute.Order));
            }
            else
            {
                property.Required = Required.Default;
            }
            property.Ignored         = (flag || (memberSerialization == MemberSerialization.OptIn && attribute == null && dataMemberAttribute == null));
            property.Converter       = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            DefaultValueAttribute attribute2 = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider);

            property.DefaultValue           = ((attribute2 == null) ? null : attribute2.Value);
            property.NullValueHandling      = ((attribute == null) ? null : attribute._nullValueHandling);
            property.DefaultValueHandling   = ((attribute == null) ? null : attribute._defaultValueHandling);
            property.ReferenceLoopHandling  = ((attribute == null) ? null : attribute._referenceLoopHandling);
            property.ObjectCreationHandling = ((attribute == null) ? null : attribute._objectCreationHandling);
            property.TypeNameHandling       = ((attribute == null) ? null : attribute._typeNameHandling);
            property.IsReference            = ((attribute == null) ? null : attribute._isReference);
            allowNonPublicAccess            = false;
            if ((this.DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (attribute != null)
            {
                allowNonPublicAccess = true;
            }
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess = true;
                hasExplicitAttribute = true;
            }
        }
        /// <summary>
        /// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
        /// </summary>
        /// <param name="contract">The member's declaring types <see cref="JsonObjectContract"/>.</param>
        /// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
        /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
        protected virtual JsonProperty CreateProperty(JsonObjectContract contract, MemberInfo member)
        {
            JsonProperty property = new JsonProperty();

            property.PropertyType  = ReflectionUtils.GetMemberUnderlyingType(member);
            property.ValueProvider = CreateMemberValueProvider(member);

            // resolve converter for property
            // the class type might have a converter but the property converter takes presidence
            property.Converter = JsonTypeReflector.GetJsonConverter(member, property.PropertyType);

#if !PocketPC && !NET20
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(member.DeclaringType);

            DataMemberAttribute dataMemberAttribute;
            if (dataContractAttribute != null)
            {
                dataMemberAttribute = JsonTypeReflector.GetAttribute <DataMemberAttribute>(member);
            }
            else
            {
                dataMemberAttribute = null;
            }
#endif

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(member);
            bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(member) != null);

            string mappedName;
            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                mappedName = dataMemberAttribute.Name;
            }
#endif
            else
            {
                mappedName = member.Name;
            }

            property.PropertyName = ResolvePropertyName(mappedName);

            if (propertyAttribute != null)
            {
                property.Required = propertyAttribute.Required;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null)
            {
                property.Required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
            }
#endif
            else
            {
                property.Required = Required.Default;
            }

            property.Ignored = (hasIgnoreAttribute ||
                                (contract.MemberSerialization == MemberSerialization.OptIn &&
                                 propertyAttribute == null
#if !PocketPC && !NET20
                                 && dataMemberAttribute == null
#endif
                                ));

            bool allowNonPublicAccess = false;
            if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (propertyAttribute != null)
            {
                allowNonPublicAccess = true;
            }
#if !PocketPC && !NET20
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess = true;
            }
#endif

            property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
            property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess);

            property.MemberConverter = JsonTypeReflector.GetJsonConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(member);
            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling      = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling   = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling  = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
            property.TypeNameHandling       = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
            property.IsReference            = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            property.ShouldSerialize = CreateShouldSerializeTest(member);

            return(property);
        }
        private Type DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false,
                                          List <ChoJSONRecordFieldConfiguration> recordFieldConfigurations = null, bool isTop = false)
        {
            if (recordType == null)
            {
                return(recordType);
            }
            if (!recordType.IsDynamicType())
            {
                Type pt = null;
                if (ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any())
                {
                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        pt = pd.PropertyType.GetUnderlyingType();
                        bool optIn1 = ChoTypeDescriptor.GetProperties(pt).Where(pd1 => pd1.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any();
                        if (optIn1 && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn1, recordFieldConfigurations, false);
                        }
                        else if (pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any())
                        {
                            var obj = new ChoJSONRecordFieldConfiguration(pd.Name, pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().First(), pd.Attributes.OfType <Attribute>().ToArray());
                            obj.FieldType          = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember    = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            if (recordFieldConfigurations != null)
                            {
                                if (!recordFieldConfigurations.Any(c => c.Name == pd.Name))
                                {
                                    recordFieldConfigurations.Add(obj);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (isTop)
                    {
                        if (typeof(IList).IsAssignableFrom(recordType) || (recordType.IsGenericType && recordType.GetGenericTypeDefinition() == typeof(IList <>)))
                        {
                            throw new ChoParserException("Record type not supported.");
                        }
                        else if (typeof(IDictionary <string, object>).IsAssignableFrom(recordType))
                        {
                            recordType = typeof(ExpandoObject);
                            return(recordType);
                        }
                        else if (typeof(IDictionary).IsAssignableFrom(recordType))
                        {
                            recordType = typeof(ExpandoObject);
                            return(recordType);
                        }
                    }

                    if (recordType.IsSimple())
                    {
                        var obj = new ChoJSONRecordFieldConfiguration("Value", "$.Value");
                        obj.FieldType = recordType;

                        recordFieldConfigurations.Add(obj);
                        return(recordType);
                    }

                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        JsonIgnoreAttribute jiAttr = pd.Attributes.OfType <JsonIgnoreAttribute>().FirstOrDefault();
                        if (jiAttr != null)
                        {
                            continue;
                        }

                        pt = pd.PropertyType.GetUnderlyingType();
                        if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn, recordFieldConfigurations, false);
                        }
                        else
                        {
                            var obj = new ChoJSONRecordFieldConfiguration(pd.Name, ChoTypeDescriptor.GetPropetyAttribute <ChoJSONRecordFieldAttribute>(pd),
                                                                          pd.Attributes.OfType <Attribute>().ToArray());

                            obj.FieldType          = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember    = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault();
                            if (slAttr != null && slAttr.MaximumLength > 0)
                            {
                                obj.Size = slAttr.MaximumLength;
                            }
                            ChoUseJSONSerializationAttribute sAttr = pd.Attributes.OfType <ChoUseJSONSerializationAttribute>().FirstOrDefault();
                            if (sAttr != null)
                            {
                                obj.UseJSONSerialization = sAttr.Flag;
                            }
                            ChoJSONPathAttribute jpAttr = pd.Attributes.OfType <ChoJSONPathAttribute>().FirstOrDefault();
                            if (jpAttr != null)
                            {
                                obj.JSONPath = jpAttr.JSONPath;
                            }

                            JsonPropertyAttribute jAttr = pd.Attributes.OfType <JsonPropertyAttribute>().FirstOrDefault();
                            if (jAttr != null && !jAttr.PropertyName.IsNullOrWhiteSpace())
                            {
                                obj.FieldName = jAttr.PropertyName;
                                obj.JSONPath  = jAttr.PropertyName;
                                obj.Order     = jAttr.Order;
                            }
                            else
                            {
                                DisplayNameAttribute dnAttr = pd.Attributes.OfType <DisplayNameAttribute>().FirstOrDefault();
                                if (dnAttr != null && !dnAttr.DisplayName.IsNullOrWhiteSpace())
                                {
                                    obj.FieldName = dnAttr.DisplayName.Trim();
                                }
                                else
                                {
                                    DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault();
                                    if (dpAttr != null)
                                    {
                                        if (!dpAttr.ShortName.IsNullOrWhiteSpace())
                                        {
                                            obj.FieldName = dpAttr.ShortName;
                                        }
                                        else if (!dpAttr.Name.IsNullOrWhiteSpace())
                                        {
                                            obj.FieldName = dpAttr.Name;
                                        }

                                        obj.Order = dpAttr.Order;
                                    }
                                    else
                                    {
                                        ColumnAttribute clAttr = pd.Attributes.OfType <ColumnAttribute>().FirstOrDefault();
                                        if (clAttr != null)
                                        {
                                            obj.Order = clAttr.Order;
                                            if (!clAttr.Name.IsNullOrWhiteSpace())
                                            {
                                                obj.FieldName = clAttr.Name;
                                            }
                                        }
                                    }
                                }
                            }
                            DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault();
                            if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace())
                            {
                                obj.FormatText = dfAttr.DataFormatString;
                            }
                            if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace())
                            {
                                obj.NullValue = dfAttr.NullDisplayText;
                            }

                            if (recordFieldConfigurations != null)
                            {
                                if (!recordFieldConfigurations.Any(c => c.Name == pd.Name))
                                {
                                    recordFieldConfigurations.Add(obj);
                                }
                            }
                        }
                    }
                }
            }
            return(recordType);
        }
Пример #32
0
        public ActionResult <GenericResponse> TypeGet(string type)
        {
            if (string.IsNullOrEmpty(type))
            {
                ASF.ArchiLogger.LogNullError(nameof(type));

                return(BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(type)))));
            }

            Type targetType = WebUtilities.ParseType(type);

            if (targetType == null)
            {
                return(BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, type))));
            }

            string           baseType         = targetType.BaseType?.GetUnifiedName();
            HashSet <string> customAttributes = targetType.CustomAttributes.Select(attribute => attribute.AttributeType.GetUnifiedName()).ToHashSet(StringComparer.Ordinal);
            string           underlyingType   = null;

            Dictionary <string, string> body = new Dictionary <string, string>(StringComparer.Ordinal);

            if (targetType.IsClass)
            {
                foreach (FieldInfo field in targetType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(field => !field.IsPrivate))
                {
                    JsonPropertyAttribute jsonProperty = field.GetCustomAttribute <JsonPropertyAttribute>();

                    if (jsonProperty != null)
                    {
                        body[jsonProperty.PropertyName ?? field.Name] = field.FieldType.GetUnifiedName();
                    }
                }

                foreach (PropertyInfo property in targetType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(property => property.CanRead && (property.GetMethod?.IsPrivate == false)))
                {
                    JsonPropertyAttribute jsonProperty = property.GetCustomAttribute <JsonPropertyAttribute>();

                    if (jsonProperty != null)
                    {
                        body[jsonProperty.PropertyName ?? property.Name] = property.PropertyType.GetUnifiedName();
                    }
                }
            }
            else if (targetType.IsEnum)
            {
                Type enumType = Enum.GetUnderlyingType(targetType);
                underlyingType = enumType.GetUnifiedName();

                foreach (object value in Enum.GetValues(targetType))
                {
                    string valueText = value.ToString();

                    if (string.IsNullOrEmpty(valueText))
                    {
                        ASF.ArchiLogger.LogNullError(nameof(valueText));

                        return(BadRequest(new GenericResponse(false, string.Format(Strings.ErrorObjectIsNull, nameof(valueText)))));
                    }

                    body[valueText] = Convert.ChangeType(value, enumType).ToString();
                }
            }

            TypeResponse.TypeProperties properties = new TypeResponse.TypeProperties(baseType, customAttributes.Count > 0 ? customAttributes : null, underlyingType);

            TypeResponse response = new TypeResponse(body, properties);

            return(Ok(new GenericResponse <TypeResponse>(response)));
        }
Пример #33
0
 public PropertyWithJsonAttribute(PropertyInfo property, JsonPropertyAttribute attribute)
 {
     Property  = property;
     Attribute = attribute;
 }
Пример #34
0
        /// <summary>
        /// Prepares the object as form fields using the provided name.
        /// </summary>
        /// <param name="name">root name for the variable</param>
        /// <param name="value">form field value</param>
        /// <param name="keys">Contains a flattend and form friendly values</param>
        /// <returns>Contains a flattend and form friendly values</returns>
        public static Dictionary <string, object> PrepareFormFieldsFromObject(String name, Object value,
                                                                              Dictionary <String, Object> keys = null)
        {
            keys = keys ?? new Dictionary <string, object>();

            if (value == null)
            {
                return(keys);
            }
            if (value is Stream)
            {
                keys[name] = value;
                return(keys);
            }
            if (value is IList)
            {
                int index      = 0;
                var enumerator = ((IEnumerable)value).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var subValue = enumerator.Current;
                    if (subValue == null)
                    {
                        continue;
                    }
                    var fullSubName = string.Format("{0}[{1}]", name, index);
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys);
                    index++;
                }
            }
            else if (value is Enum)
            {
                var isStringEnum = value.GetType().GetCustomAttributes(false).FirstOrDefault(attrib => attrib is JsonConverterAttribute) != null;
                if (isStringEnum)
                {
                    value = JsonConvert.SerializeObject(value).Trim('"');
                }
                else
                {
                    value = (int)value;
                }
                keys[name] = value;
            }
            else if (value is IDictionary)
            {
                var obj = (IDictionary)value;
                foreach (var sName in obj.Keys)
                {
                    var    subName     = sName.ToString();
                    var    subValue    = obj[subName];
                    string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : string.Format("{0}[{1}]", name, subName);
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys);
                }
            }
            else if (!(value.GetType().Namespace.StartsWith("System")))
            {
                //Custom object Iterate through its properties
                var          enumerator = value.GetType().GetProperties().GetEnumerator();
                PropertyInfo pInfo      = null;
                var          attribType = new JsonPropertyAttribute().GetType();
                while (enumerator.MoveNext())
                {
                    pInfo = enumerator.Current as PropertyInfo;

                    var    jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(attribType, true).FirstOrDefault();
                    var    subName      = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name;
                    string fullSubName  = string.IsNullOrWhiteSpace(name) ? subName : string.Format("{0}[{1}]", name, subName);
                    var    subValue     = pInfo.GetValue(value, null);
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys);
                }
            }
            else
            {
                keys[name] = value;
            }
            return(keys);
        }
Пример #35
0
        /// <summary>
        /// Prepares the object as form fields using the provided name.
        /// </summary>
        /// <param name="name">root name for the variable</param>
        /// <param name="value">form field value</param>
        /// <param name="keys">Contains a flattend and form friendly values</param>
        /// <returns>Contains a flattend and form friendly values</returns>
        public static Dictionary <string, object> PrepareFormFieldsFromObject(
            string name, object value, Dictionary <string, object> keys = null, PropertyInfo propInfo = null)
        {
            keys = keys ?? new Dictionary <string, object>();

            if (value == null)
            {
                return(keys);
            }
            else if (value is Stream)
            {
                keys[name] = value;
                return(keys);
            }
            else if (value is JObject)
            {
                var valueAccept = (value as Newtonsoft.Json.Linq.JObject);
                foreach (var property in valueAccept.Properties())
                {
                    string pKey        = property.Name;
                    object pValue      = property.Value;
                    var    fullSubName = name + '[' + pKey + ']';
                    PrepareFormFieldsFromObject(fullSubName, pValue, keys, propInfo);
                }
            }
            else if (value is IList)
            {
                int i          = 0;
                var enumerator = ((IEnumerable)value).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var subValue = enumerator.Current;
                    if (subValue == null)
                    {
                        continue;
                    }
                    var fullSubName = name + '[' + i + ']';
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo);
                    i++;
                }
            }
            else if (value is JToken)
            {
                keys[name] = value.ToString();
            }
            else if (value is Enum)
            {
#if WINDOWS_UWP
                Assembly thisAssembly = typeof(APIHelper).GetTypeInfo().Assembly;
#else
                Assembly thisAssembly = Assembly.GetExecutingAssembly();
#endif
                string enumTypeName   = value.GetType().FullName;
                Type   enumHelperType = thisAssembly.GetType(string.Format("{0}Helper", enumTypeName));
                object enumValue      = (int)value;

                if (enumHelperType != null)
                {
                    //this enum has an associated helper, use that to load the value
                    MethodInfo enumHelperMethod = enumHelperType.GetMethod("ToValue", new[] { value.GetType() });
                    if (enumHelperMethod != null)
                    {
                        enumValue = enumHelperMethod.Invoke(null, new object[] { value });
                    }
                }

                keys[name] = enumValue;
            }
            else if (value is IDictionary)
            {
                var obj = (IDictionary)value;
                foreach (var sName in obj.Keys)
                {
                    var    subName     = sName.ToString();
                    var    subValue    = obj[subName];
                    string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']';
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo);
                }
            }
            else if (!(value.GetType().Namespace.StartsWith("System")))
            {
                //Custom object Iterate through its properties
                var          enumerator = value.GetType().GetProperties().GetEnumerator();
                PropertyInfo pInfo      = null;
                var          t          = new JsonPropertyAttribute().GetType();
                while (enumerator.MoveNext())
                {
                    pInfo = enumerator.Current as PropertyInfo;

                    var    jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(t, true).FirstOrDefault();
                    var    subName      = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name;
                    string fullSubName  = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']';
                    var    subValue     = pInfo.GetValue(value, null);
                    PrepareFormFieldsFromObject(fullSubName, subValue, keys, pInfo);
                }
            }
            else if (value is DateTime)
            {
                string convertedValue = null;
                var    pInfo          = propInfo?.GetCustomAttributes(true);
                if (pInfo != null)
                {
                    foreach (object attr in pInfo)
                    {
                        JsonConverterAttribute converterAttr = attr as JsonConverterAttribute;
                        if (converterAttr != null)
                        {
                            convertedValue = JsonSerialize(value, (JsonConverter)Activator.CreateInstance(converterAttr.ConverterType, converterAttr.ConverterParameters)).Replace("\"", "");
                        }
                    }
                }
                keys[name] = (convertedValue) ?? ((DateTime)value).ToString(DateTimeFormat);
            }
            else
            {
                keys[name] = value;
            }
            return(keys);
        }