Ejemplo n.º 1
0
        /// <summary>
        /// Converts string to camel-case formatted string
        /// </summary>
        /// <param name="str"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static string ToCamelCase(this string str, Action <CamelCasePropertyNamesContractResolver> config = null)
        {
            var camelCase = new CamelCasePropertyNamesContractResolver();

            config?.Invoke(camelCase);
            return(camelCase.GetResolvedPropertyName(str));
        }
        public static IEnumerable <string> GetPaths <T>(bool camelCase = false)
            where T : class
        {
            var resolver = new CamelCasePropertyNamesContractResolver();

            return(typeof(T).GetProperties()
                   .Where(p => p.GetCustomAttribute <UniqueKeyAttribute>() != null)
                   .Select(p => $"/{(camelCase ? resolver.GetResolvedPropertyName(p.Name) : p.Name)}"));
        }
Ejemplo n.º 3
0
        public static IEnumerable <string> GetPaths(Type type, bool camelCase = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var resolver = new CamelCasePropertyNamesContractResolver();

            return(type.GetProperties()
                   .Where(p => p.GetCustomAttribute <UniqueKeyAttribute>() != null)
                   .Select(p => $"/{(camelCase ? resolver.GetResolvedPropertyName(p.Name) : p.Name)}"));
        }
Ejemplo n.º 4
0
        public void ToLowerCamelCase_LowerCamelCaser_HasSameBehaviorAsJsonNet(string propertyName, string expectName)
        {
            // Arrange
            var lowerCamelCaser = new LowerCamelCaser();
            var camelCasePropertyNamesContractResolver = new CamelCasePropertyNamesContractResolver();

            // Act
            string nameResolvedByLowerCamelCaser = lowerCamelCaser.ToLowerCamelCase(propertyName);
            string nameResolveByJsonNet          = camelCasePropertyNamesContractResolver.GetResolvedPropertyName(propertyName);

            // Assert
            Assert.Equal(nameResolveByJsonNet, nameResolvedByLowerCamelCaser);
            Assert.Equal(expectName, nameResolvedByLowerCamelCaser);
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var objectType = value.GetType();
            var fieldList  = new List <string>();

            foreach (var fieldInfo in objectType.GetProperties())
            {
                var attribute = fieldInfo.GetCustomAttribute <JsonConverterAttribute>();
                if (attribute != null)
                {
                    var converter = (JsonConverter)Activator.CreateInstance(attribute.ConverterType);
                    fieldList.Add($"\"{camelCaseConverter.GetResolvedPropertyName(fieldInfo.Name)}\":{JsonConvert.SerializeObject(fieldInfo.GetValue(value), converter)}");
                }
                else
                {
                    fieldList.Add($"\"{camelCaseConverter.GetResolvedPropertyName(fieldInfo.Name)}\":{JsonConvert.SerializeObject(fieldInfo.GetValue(value), new JsonSerializerSettings { ContractResolver = this.camelCaseConverter })}");
                }
            }

            var serialized = "{" + $"{string.Join(",", fieldList)}" + "}";
            var t          = JToken.FromObject(JsonConvert.DeserializeObject <dynamic>(serialized));

            t.WriteTo(writer);
        }
        /// <summary>
        /// Gets the <see cref="SupportedPropertyMeta"/> based on property features
        /// and common attributes.
        /// </summary>
        public virtual SupportedPropertyMeta GetMeta(PropertyInfo property)
        {
            var isReadonly  = property.SetMethod == null || property.SetMethod.IsPrivate || HasReadonlyAttribute(property);
            var title       = _propertyNames.GetResolvedPropertyName(property.Name);
            var description = property.GetDescription() ?? string.Format(DefaultDescription, title);
            var isWriteOnly = property.GetMethod == null ||
                              property.GetMethod.IsPrivate ||
                              property.GetCustomAttribute <WriteOnlyAttribute>() != null;

            return(new SupportedPropertyMeta
            {
                Title = title,
                Description = description,
                Writeable = isReadonly == false,
                Readable = isWriteOnly == false
            });
        }
Ejemplo n.º 7
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var type    = value.GetType().GetCustomAttribute <TypeNameAttribute>().Type;
            var jObject = new JObject();

            jObject.Add("type", new JValue(type));
            foreach (var prop in value.GetType().GetProperties())
            {
                var propValue = prop.GetValue(value);
                var name      = prop.GetCustomAttribute <JsonPropertyAttribute>()?.PropertyName ?? prop.Name;
                if (propValue != null)
                {
                    jObject.Add(camelCaseContractResolver.GetResolvedPropertyName(name), JToken.FromObject(propValue, serializer));
                }
            }
            jObject.WriteTo(writer);
        }
Ejemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        /// <param name="destMember"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public List <Dictionary <string, object> > Resolve(SurveyResponse source,
                                                           SurveyResponseViewModel destination, List <Dictionary <string, object> > destMember, ResolutionContext context)
        {
            List <Dictionary <string, object> > responseValues = new List <Dictionary <string, object> >();

            foreach (var response in source.ResponseValues)
            {
                var obj = response.GetType()
                          .GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(f =>
                {
                    return(f.PropertyType != typeof(SurveyResponse) && f.Name != "Id");
                })
                          .ToDictionary(prop => NamesContractResolver.GetResolvedPropertyName(prop.Name), prop => prop.GetValue(response, null));

                responseValues.Add(obj);
            }

            return(responseValues);
        }
Ejemplo n.º 9
0
        public void ToLowerCamelCase_LowerCamelCaser_HasSameBehaviorAsJsonNet(string propertyName, string expectName)
        {
            // Arrange
            var lowerCamelCaser = new LowerCamelCaser();
            var camelCasePropertyNamesContractResolver = new CamelCasePropertyNamesContractResolver();

            // Act
            string nameResolvedByLowerCamelCaser = lowerCamelCaser.ToLowerCamelCase(propertyName);
            string nameResolveByJsonNet          = camelCasePropertyNamesContractResolver.GetResolvedPropertyName(propertyName);

            // Newtonsoft appears to have changed from v6 to v10 here. Some cases that used to pass
            // and were changed are:
            // [InlineData("MyPI", "mypi")] => [InlineData("MyPI", "myPI")]
            // [InlineData("U_ID", "u_id")] => [InlineData("U_ID", "u_ID")]
            //Assert.Equal(nameResolveByJsonNet, nameResolvedByLowerCamelCaser);

            // Assert
            Assert.Equal(expectName, nameResolvedByLowerCamelCaser);
        }
Ejemplo n.º 10
0
        public async Task PushAsync(string baseUrl, string accessToken, IDictionary <string, string> parameters)
        {
            var request = new Request("", baseUrl, HttpMethod.Post);

            if (!string.IsNullOrWhiteSpace(accessToken))
            {
                request.AddHeader("Access-Token", accessToken);
            }

            var body = parameters.ToDictionary(
                x => _nameResolver.GetResolvedPropertyName(x.Key),
                x => x.Value
                );

            request.ApplicationJsonContentType();
            request.AddJsonBody(body);

            await _api.Request(request);
        }
        /// <summary>
        /// This method creates the JsonProperty
        /// Note that we create a JsonProperty for ALL the properties, but determine whether to serialize based on
        /// the "ShouldSerialize" property
        /// Using the CamelCasePropertynamesContractResolver makes sure we get the correct naming for JavaScript
        /// </summary>
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var prop = base.CreateProperty(member, memberSerialization);

            prop.PropertyName = camelCasePropertyResolver.GetResolvedPropertyName(prop.PropertyName);

            if (propertyDeclarations.ContainsKey(member.DeclaringType))
            {
                // This property is what needs to be set in order to determine whether
                // the specific property should be serialized as part of the object or not
                prop.ShouldSerialize = instance =>
                {
                    var rules = propertyDeclarations[instance.GetType()];

                    return(rules.ShouldSerialize(prop.PropertyName));
                };
            }

            return(prop);
        }
Ejemplo n.º 12
0
 public string ResolvePropertyName(string propertyName)
 {
     return(CachedNames.GetOrAdd(propertyName, n => Resolver.GetResolvedPropertyName(n)));
 }
 public string GetModelName(Type modelType)
 {
     return(_propertyResolver.GetResolvedPropertyName(modelType.Name));
 }
Ejemplo n.º 14
0
        internal static string ToCamelCase(this string propertyName)
        {
            var resolver = new CamelCasePropertyNamesContractResolver();

            return(resolver.GetResolvedPropertyName(propertyName));
        }
 /// <summary>
 /// Returns the JSON property name for <paramref name="property"/>.
 /// </summary>
 /// <param name="property"></param>
 /// <returns></returns>
 private string PropertyName(PropertyInfo property)
 {
     return(_camelCaseContractResolver?.GetResolvedPropertyName(property.Name) ?? property.Name);
 }
Ejemplo n.º 16
0
        public static string BuildTsStr(this ClassAndLines classAndLines, List <string> allClassNames)
        {
            string tsClassStr = string.Empty;

            tsClassStr += "export class " + classAndLines.ClassName + " {\r\n";

            List <string> modifiedLines = new List <string>();

            //Remove get and set
            //Remove public
            //Remove virtual
            foreach (string l in classAndLines.Lines)
            {
                string        lineToAdd    = l;
                List <string> removeMeList = new List <string>()
                {
                    " { get; set; }", "virtual", "public"
                };
                foreach (string removeMe in removeMeList)
                {
                    lineToAdd = lineToAdd.RemoveThis(removeMe);
                }
                modifiedLines.Add(lineToAdd.Trim());
            }

            //Remove constructor if exists
            int endOfConstructorIndex = modifiedLines.FindLastIndex(l => l.Contains("}"));

            if (endOfConstructorIndex != -1)
            {
                modifiedLines = modifiedLines.GetRange(endOfConstructorIndex + 1, modifiedLines.Count() - (endOfConstructorIndex + 1));
            }

            List <string> importList = new List <string>();

            foreach (string line in modifiedLines)
            {
                string typeStr = line.Substring(0, line.IndexOf(" "));

                string propName = line.Substring(line.LastIndexOf(' ') + 1);

                //Convert to camelcase
                var cc = new CamelCasePropertyNamesContractResolver();
                propName = cc.GetResolvedPropertyName(propName);

                tsClassStr += $"   public {propName}: {typeStr.TypeConversion(allClassNames, importList)};\r\n";
            }

            tsClassStr += "}";

            //add imports
            string importStr = "\r\n";

            //Converting to hashset removes duplicates
            foreach (string import in importList.ToHashSet <string>())
            {
                //don't import self
                if (!(classAndLines.ClassName == import))
                {
                    importStr += "import { " + import + " } from './index';\r\n";
                }
            }

            tsClassStr = importStr + "\r\n" + tsClassStr;

            return(tsClassStr);
        }
Ejemplo n.º 17
0
 public static string GetResolvedPropertyName(string propertyName)
 {
     return(CamelCasePropertyNamesContractResolver.GetResolvedPropertyName(propertyName));
 }