SortOrder.cs 12 KB

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