SortOrder.cs 9.3 KB

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