SortOrder.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq.Expressions;
  5. using System.Runtime.Serialization;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. namespace InABox.Core
  9. {
  10. public enum SortDirection
  11. {
  12. Ascending,
  13. Descending
  14. }
  15. public interface ISortOrder
  16. {
  17. SortDirection Direction { get; set; }
  18. Expression Expression { get; set; }
  19. IEnumerable<ISortOrder> Thens { get; }
  20. IEnumerable<String> ColumnNames();
  21. }
  22. public static class SortOrder
  23. {
  24. public static ISortOrder Create<T>(Type concrete, Expression<Func<T,object>> expression, SortDirection direction = SortDirection.Ascending)
  25. {
  26. if (!typeof(T).IsAssignableFrom(concrete))
  27. throw new Exception($"Columns: {concrete.EntityName()} does not implement {typeof(T).EntityName()}");
  28. var type = typeof(SortOrder<>).MakeGenericType(concrete);
  29. var property = CoreUtils.GetFullPropertyName(expression,".");
  30. var result = Activator.CreateInstance(type, property, direction );
  31. return (result as ISortOrder)!;
  32. }
  33. }
  34. public class SortOrder<T> : SerializableExpression<T>, ISortOrder // where T : Entity
  35. {
  36. public SortDirection Direction { get; set; }
  37. public List<SortOrder<T>> Thens { get; private set; }
  38. IEnumerable<ISortOrder> ISortOrder.Thens => Thens;
  39. //public SortOrder<T> Ascending()
  40. //{
  41. // Direction = SortOrder.Ascending;
  42. // return this;
  43. //}
  44. //public SortOrder<T> Descending()
  45. //{
  46. // Direction = SortOrder.Descending;
  47. // return this;
  48. //}
  49. public SortOrder<T> ThenBy(Expression<Func<T, object?>> expression, SortDirection direction = SortDirection.Ascending)
  50. {
  51. var thenby = new SortOrder<T>(expression, direction);
  52. Thens.Add(thenby);
  53. return this;
  54. }
  55. #region Constructors
  56. public SortOrder()
  57. {
  58. Thens = new List<SortOrder<T>>();
  59. Direction = SortDirection.Ascending;
  60. }
  61. public SortOrder(Expression<Func<T, object?>> expression, SortDirection direction = SortDirection.Ascending)
  62. : base(expression)
  63. {
  64. Thens = new List<SortOrder<T>>();
  65. Direction = direction;
  66. }
  67. public SortOrder(string property, SortDirection direction = SortDirection.Ascending)
  68. {
  69. Thens = new List<SortOrder<T>>();
  70. Direction = direction;
  71. var iprop = DatabaseSchema.Property(typeof(T), property);
  72. Expression = iprop.Expression();
  73. }
  74. public SortOrder(SerializationInfo info, StreamingContext context)
  75. {
  76. Deserialize(info, context);
  77. }
  78. public static explicit operator SortOrder<T>(SortOrder<Entity> v)
  79. {
  80. if (v == null)
  81. return null;
  82. var json = Serialization.Serialize(v);
  83. json = json.Replace(typeof(Entity).EntityName(), typeof(T).EntityName());
  84. var result = Serialization.Deserialize<SortOrder<T>>(json);
  85. return result;
  86. }
  87. #endregion
  88. #region Display Functions
  89. public string AsOData()
  90. {
  91. var orderby = new Dictionary<SortDirection, string>
  92. {
  93. { SortDirection.Ascending, "asc" },
  94. { SortDirection.Descending, "desc" }
  95. };
  96. var prop = "";
  97. if (CoreUtils.TryFindMemberExpression(Expression, out var mexp))
  98. prop = CoreUtils.GetFullPropertyName(mexp, "/");
  99. else
  100. prop = Expression.ToString();
  101. var result = string.Format("{0} {1}", prop, orderby[Direction]);
  102. if (Thens != null && Thens.Count > 0)
  103. foreach (var then in Thens)
  104. {
  105. var ThenResult = then.AsOData();
  106. if (!string.IsNullOrEmpty(ThenResult))
  107. result = string.Format("{0}, {1}", result, ThenResult);
  108. }
  109. return result;
  110. }
  111. public override string ToString()
  112. {
  113. return AsOData();
  114. }
  115. public IEnumerable<string> ColumnNames()
  116. {
  117. List<String> result = new List<string>();
  118. result.Add(CoreUtils.ExpressionToString(typeof(T), Expression));
  119. foreach (var then in Thens)
  120. result.AddRange(then.ColumnNames());
  121. return result;
  122. }
  123. #endregion
  124. //public Expression<Func<T,Object>> AsExpression()
  125. //{
  126. // var param = Expression.Parameter(typeof(T), "x");
  127. // var result = Expression.Lambda<Func<T,Object>>(Expression,param);
  128. // return result;
  129. //}
  130. #region Serialization
  131. public override void Serialize(SerializationInfo info, StreamingContext context)
  132. {
  133. info.AddValue("Direction", Direction.ToString());
  134. if (Thens.Count > 0)
  135. info.AddValue("Thens", Thens, typeof(List<SortOrder<T>>));
  136. }
  137. public override void Deserialize(SerializationInfo info, StreamingContext context)
  138. {
  139. Direction = (SortDirection)Enum.Parse(typeof(SortDirection), (string)info.GetValue("Direction", typeof(string)));
  140. try
  141. {
  142. Thens = (List<SortOrder<T>>)info.GetValue("Thens", typeof(List<SortOrder<T>>));
  143. }
  144. catch
  145. {
  146. Thens = new List<SortOrder<T>>();
  147. }
  148. }
  149. #endregion
  150. }
  151. public class SortOrderJsonConverter : JsonConverter
  152. {
  153. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
  154. {
  155. if(value is null)
  156. {
  157. writer.WriteNull();
  158. return;
  159. }
  160. var property = CoreUtils.GetPropertyValue(value, "Expression") as MemberExpression;
  161. //MethodInfo mi = value.GetType().GetTypeInfo().GetMethod("ExpressionToString");
  162. //String prop = mi.Invoke(value, new object[] { property, true }) as String;
  163. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  164. var dir = CoreUtils.GetPropertyValue(value, "Direction");
  165. writer.WriteStartObject();
  166. writer.WritePropertyName("Expression");
  167. writer.WriteValue(prop);
  168. writer.WritePropertyName("Direction");
  169. writer.WriteValue(dir);
  170. var thens = CoreUtils.GetPropertyValue(value, "Thens") as IList;
  171. if (thens != null && thens.Count > 0)
  172. {
  173. writer.WritePropertyName("Thens");
  174. serializer.Serialize(writer, thens);
  175. }
  176. writer.WriteEndObject();
  177. }
  178. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  179. {
  180. if (reader.TokenType == JsonToken.Null)
  181. return null;
  182. var data = new Dictionary<string, object>();
  183. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  184. if (reader.Value != null)
  185. {
  186. var key = reader.Value.ToString();
  187. reader.Read();
  188. if (string.Equals(key, "Thens"))
  189. {
  190. var array = JArray.Load(reader);
  191. var thens = new List<object>();
  192. foreach (var item in array)
  193. {
  194. var then = ReadJson(item.CreateReader(), objectType, existingValue, serializer);
  195. if(then != null)
  196. thens.Add(then);
  197. //String jexp = item["Expression"].Value<String>();
  198. //MemberExpression exp = CoreUtils.StringToExpression(jexp) as MemberExpression;
  199. //var then = CreateSortOrder(
  200. // objectType,
  201. // exp.Member.Name,
  202. // (SortDirection)item["Direction"].Value<Int64>()
  203. //);
  204. //thens.Add(then);
  205. }
  206. data[key] = thens;
  207. }
  208. else
  209. {
  210. data[key] = reader.Value;
  211. }
  212. }
  213. var jprop = data["Expression"].ToString();
  214. var prop = CoreUtils.StringToExpression(jprop) as MemberExpression;
  215. var direction = (SortDirection)int.Parse(data["Direction"].ToString());
  216. var result = Activator.CreateInstance(objectType, CoreUtils.GetFullPropertyName(prop, "."), direction);
  217. if (data.ContainsKey("Thens"))
  218. {
  219. var source = (data["Thens"] as List<object>)!;
  220. var target = (CoreUtils.GetPropertyValue(result, "Thens") as IList)!;
  221. foreach (var srcitem in source)
  222. target.Add(srcitem);
  223. }
  224. return result;
  225. }
  226. public override bool CanConvert(Type objectType)
  227. {
  228. if (objectType.IsConstructedGenericType)
  229. {
  230. var ot = objectType.GetGenericTypeDefinition();
  231. var tt = typeof(SortOrder<>);
  232. if (ot == tt)
  233. return true;
  234. }
  235. return false;
  236. }
  237. }
  238. }