/// <summary> /// Used for flattening a collection of objects into a string /// </summary> /// <param name="array">Array of elements to flatten</param> /// <param name="fmt">Format string to use for array flattening</param> /// <param name="separator">Separator to use for string concat</param> /// <returns>Representative string made up of array elements</returns> private static string flattenCollection(ICollection array, ArrayDeserialization fmt, char separator, bool urlEncode, string key = "") { StringBuilder builder = new StringBuilder(); string format = string.Empty; if (fmt == ArrayDeserialization.UnIndexed) format = String.Format("{0}[]={{0}}{{1}}", key); else if (fmt == ArrayDeserialization.Indexed) format = String.Format("{0}[{{2}}]={{0}}{{1}}", key); else if (fmt == ArrayDeserialization.Plain) format = String.Format("{0}={{0}}{{1}}", key); else if (fmt == ArrayDeserialization.Csv || fmt == ArrayDeserialization.Psv || fmt == ArrayDeserialization.Tsv) { builder.Append(String.Format("{0}=", key)); format = "{0}{1}"; } else format = "{0}{1}"; //append all elements in the array into a string int index = 0; foreach (object element in array) builder.AppendFormat(format, getElementValue(element, urlEncode), separator, index++); //remove the last separator, if appended if ((builder.Length > 1) && (builder[builder.Length - 1] == separator)) builder.Length -= 1; return builder.ToString(); }
/// <summary> /// Used for flattening a collection of objects into a string /// </summary> /// <param name="array">Array of elements to flatten</param> /// <param name="fmt">Format string to use for array flattening</param> /// <param name="separator">Separator to use for string concat</param> /// <param name="urlEncode">Whether to Url encode</param> /// <param name="key">The key</param> /// <returns>Representative string made up of array elements</returns> private static string FlattenCollection(ICollection array, ArrayDeserialization fmt, char separator, bool urlEncode, string key = "") { var builder = new StringBuilder(); string format; switch (fmt) { case ArrayDeserialization.UnIndexed: format = $"{key}[]={{0}}{{1}}"; break; case ArrayDeserialization.Indexed: format = $"{key}[{{2}}]={{0}}{{1}}"; break; case ArrayDeserialization.Plain: format = $"{key}={{0}}{{1}}"; break; case ArrayDeserialization.Csv: case ArrayDeserialization.Psv: case ArrayDeserialization.Tsv: builder.Append($"{key}="); format = "{0}{1}"; break; default: format = "{0}{1}"; break; } //append all elements in the array into a string var index = 0; foreach (var element in array) { builder.AppendFormat(format, GetElementValue(element, urlEncode), separator, index++); } //remove the last separator, if appended if ((builder.Length > 1) && (builder[builder.Length - 1] == separator)) { builder.Length -= 1; } return(builder.ToString()); }
/// <summary> /// Used for flattening a collection of objects into a string /// </summary> /// <param name="array">Array of elements to flatten</param> /// <param name="fmt">Format string to use for array flattening</param> /// <param name="separator">Separator to use for string concat</param> /// <returns>Representative string made up of array elements</returns> private static string flattenCollection(ICollection array, ArrayDeserialization fmt, char separator, bool urlEncode, string key = "") { var builder = new StringBuilder(); var format = string.Empty; if (fmt == ArrayDeserialization.UN_INDEXED) { format = $"{key}[]={{0}}{{1}}"; } else if (fmt == ArrayDeserialization.INDEXED) { format = $"{key}[{{2}}]={{0}}{{1}}"; } else if (fmt == ArrayDeserialization.PLAIN) { format = $"{key}={{0}}{{1}}"; } else if (fmt == ArrayDeserialization.CSV || fmt == ArrayDeserialization.PSV || fmt == ArrayDeserialization.TSV) { builder.Append($"{key}="); format = "{0}{1}"; } else { format = "{0}{1}"; } //append all elements in the array into a string var index = 0; foreach (var element in array) { builder.AppendFormat(format, getElementValue(element, urlEncode), separator, index++); } //remove the last separator, if appended if ((builder.Length > 1) && (builder[builder.Length - 1] == separator)) { builder.Length -= 1; } return(builder.ToString()); }
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); }
/// <summary> /// Appends the given set of parameters to the given query string /// </summary> /// <param name="queryUrl">The query url string to append the parameters</param> /// <param name="parameters">The parameters to append</param> public static void AppendUrlWithQueryParameters (StringBuilder queryBuilder, IEnumerable <KeyValuePair <string, object> > parameters, ArrayDeserialization arrayDeserializationFormat = ArrayDeserialization.UnIndexed, char separator = '&') { //perform parameter validation if (null == queryBuilder) { throw new ArgumentNullException("queryBuilder"); } if (null == parameters) { return; } //does the query string already has parameters bool hasParams = (indexOf(queryBuilder, "?") > 0); //iterate and append parameters foreach (KeyValuePair <string, object> pair in parameters) { //ignore null values if (pair.Value == null) { continue; } //if already has parameters, use the & to append new parameters queryBuilder.Append((hasParams) ? '&' : '?'); //indicate that now the query has some params hasParams = true; string paramKeyValPair; //load element value as string if (pair.Value is ICollection) { paramKeyValPair = flattenCollection(pair.Value as ICollection, arrayDeserializationFormat, separator, true, pair.Key); } else if (pair.Value is DateTime) { paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), ((DateTime)pair.Value).ToString(DateTimeFormat)); } else if (pair.Value is DateTimeOffset) { paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), ((DateTimeOffset)pair.Value).ToString(DateTimeFormat)); } else { paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value.ToString())); } //append keyval pair for current parameter queryBuilder.Append(paramKeyValPair); } }
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); } if (value is Stream) { keys.Add(new KeyValuePair <string, object>(name, value)); return(keys); } if (value is JObject jObject) { var valueAccept = jObject; foreach (var property in valueAccept.Properties()) { var pKey = property.Name; object pValue = property.Value; var fullSubName = name + '[' + pKey + ']'; PrepareFormFieldsFromObject(fullSubName, pValue, keys, propInfo, arrayDeserializationFormat); } } else if (value is IList list) { var enumerator = list.GetEnumerator(); var hasNested = false; while (enumerator.MoveNext()) { var subValue = enumerator.Current; var ns = subValue.GetType().Namespace; if (ns != null && (subValue != null && (subValue is JObject || subValue is IList || subValue is IDictionary || !(ns.StartsWith("System"))))) { hasNested = true; break; } } var 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) { var thisAssembly = typeof(APIHelper).GetTypeInfo().Assembly; var enumTypeName = value.GetType().FullName; var enumHelperType = thisAssembly.GetType($"{enumTypeName}Helper"); object enumValue = (int)value; if (enumHelperType != null) { //this enum has an associated helper, use that to load the value var enumHelperMethod = enumHelperType.GetRuntimeMethod("ToValue", new[] { value.GetType() }); if (enumHelperMethod != null) { enumValue = enumHelperMethod.Invoke(null, new[] { value }); } } keys.Add(new KeyValuePair <string, object>(name, enumValue)); } else if (value is IDictionary obj) { foreach (var sName in obj.Keys) { var subName = sName.ToString(); var subValue = obj[subName]; var fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo, arrayDeserializationFormat); } } else { var ns = value.GetType().Namespace; if (ns != null && !(ns.StartsWith("System"))) { //Custom object Iterate through its properties using (var enumerator = value.GetType().GetRuntimeProperties().GetEnumerator()) { var t = new JsonPropertyAttribute().GetType(); while (enumerator.MoveNext()) { var pInfo = enumerator.Current; var jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(t, true).FirstOrDefault(); var subName = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name; var fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; var subValue = pInfo.GetValue(value, null); PrepareFormFieldsFromObject(fullSubName, subValue, keys, pInfo, arrayDeserializationFormat); } } } else if (value is DateTime time) { string convertedValue = null; object[] pInfo = null; if (propInfo != null) { pInfo = propInfo.GetCustomAttributes(true); } if (pInfo != null) { foreach (var attr in pInfo) { if (attr is JsonConverterAttribute converterAttr) { convertedValue = JsonSerialize(time, (JsonConverter) Activator.CreateInstance(converterAttr.ConverterType, converterAttr.ConverterParameters)).Replace("\"", ""); } } } keys.Add(new KeyValuePair <string, object>(name, (convertedValue) ?? time.ToString(DateTimeFormat))); } else { keys.Add(new KeyValuePair <string, object>(name, value)); } } return(keys); }
/// <summary> /// Appends the given set of parameters to the given query string /// </summary> /// <param name="queryBuilder">The query url string to append the parameters</param> /// <param name="parameters">The parameters to append</param> /// <param name="arrayDeserializationFormat">Array deserialization format</param> /// <param name="separator">The separator</param> public static void AppendUrlWithQueryParameters (StringBuilder queryBuilder, IEnumerable <KeyValuePair <string, object> > parameters, ArrayDeserialization arrayDeserializationFormat = ArrayDeserialization.UnIndexed, char separator = '&') { //perform parameter validation if (null == queryBuilder) { throw new ArgumentNullException(nameof(queryBuilder)); } if (null == parameters) { return; } //does the query string already has parameters var hasParams = (IndexOf(queryBuilder, "?") > 0); //iterate and append parameters foreach (var pair in parameters) { //ignore null values if (pair.Value == null) { continue; } //if already has parameters, use the & to append new parameters queryBuilder.Append((hasParams) ? '&' : '?'); //indicate that now the query has some params hasParams = true; string paramKeyValPair; switch (pair.Value) { //load element value as string case ICollection value: paramKeyValPair = FlattenCollection(value, arrayDeserializationFormat, separator, true, pair.Key); break; case DateTime time: paramKeyValPair = $"{Uri.EscapeDataString(pair.Key)}={time.ToString(DateTimeFormat)}"; break; case DateTimeOffset offset: paramKeyValPair = $"{Uri.EscapeDataString(pair.Key)}={offset.ToString(DateTimeFormat)}"; break; default: paramKeyValPair = $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value.ToString())}"; break; } //append keyval pair for current parameter queryBuilder.Append(paramKeyValPair); } }
public static void AppendUrlWithQueryParameters (StringBuilder queryBuilder, IEnumerable <KeyValuePair <string, object> > parameters, ArrayDeserialization arrayDeserializationFormat = ArrayDeserialization.UnIndexed, char separator = '&') { if (null == queryBuilder) { throw new ArgumentNullException("queryBuilder"); } if (null == parameters) { return; } bool hasParams = (indexOf(queryBuilder, "?") > 0); foreach (KeyValuePair <string, object> pair in parameters) { if (pair.Value == null) { continue; } queryBuilder.Append((hasParams) ? '&' : '?'); hasParams = true; string paramKeyValPair; if (pair.Value is ICollection) { paramKeyValPair = flattenCollection(pair.Value as ICollection, arrayDeserializationFormat, separator, true, pair.Key); } else if (pair.Value is DateTime) { paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), ((DateTime)pair.Value).ToString(DateTimeFormat)); } else if (pair.Value is DateTimeOffset) { paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), ((DateTimeOffset)pair.Value).ToString(DateTimeFormat)); } else { paramKeyValPair = string.Format("{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value.ToString())); } queryBuilder.Append(paramKeyValPair); } }