using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Retailcrm
{
///
/// QueryBuilder
///
public class QueryBuilder
{
private readonly List> _keyValuePairs
= new List>();
///
/// Build PHP like query string
///
///
///
///
public static string BuildQueryString(object queryData, string argSeperator = "&")
{
var encoder = new QueryBuilder();
encoder.AddEntry(null, queryData, allowObjects: true);
return encoder.GetUriString(argSeperator);
}
///
/// GetUriString
///
///
///
private string GetUriString(string argSeperator)
{
return String.Join(argSeperator,
_keyValuePairs.Select(kvp =>
{
var key = HttpUtility.UrlEncode(kvp.Key);
var value = HttpUtility.UrlEncode(kvp.Value.ToString());
return $"{key}={value}";
}));
}
///
/// AddEntry
///
///
///
///
private void AddEntry(string prefix, object instance, bool allowObjects)
{
var collection = instance as ICollection;
if (instance is IDictionary dictionary)
{
Add(prefix, GetDictionaryAdapter(dictionary));
}
else if (collection != null)
{
Add(prefix, GetArrayAdapter(collection));
}
else if (allowObjects)
{
Add(prefix, GetObjectAdapter(instance));
}
else
{
_keyValuePairs.Add(new KeyValuePair(prefix, instance));
}
}
///
/// Add
///
///
///
private void Add(string prefix, IEnumerable datas)
{
foreach (var item in datas)
{
var newPrefix = String.IsNullOrEmpty(prefix)
? item.Key
: $"{prefix}[{item.Key}]";
AddEntry(newPrefix, item.Value, allowObjects: false);
}
}
///
/// Entry
///
private struct Entry
{
public string Key;
public object Value;
}
///
/// GetObjectAdapter
///
///
///
private static IEnumerable GetObjectAdapter(object data)
{
var properties = data.GetType().GetProperties();
foreach (var property in properties)
{
yield return new Entry
{
Key = property.Name,
Value = property.GetValue(data)
};
}
}
///
/// GetArrayAdapter
///
///
///
private static IEnumerable GetArrayAdapter(ICollection collection)
{
int i = 0;
foreach (var item in collection)
{
yield return new Entry
{
Key = i.ToString(),
Value = item
};
i++;
}
}
///
/// GetDictionaryAdapter
///
///
///
private static IEnumerable GetDictionaryAdapter(IDictionary collection)
{
foreach (DictionaryEntry item in collection)
{
yield return new Entry
{
Key = item.Key.ToString(),
Value = item.Value
};
}
}
}
}