SortOrder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Runtime.Serialization;
  7. using System.Text.Json;
  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. List<ISortOrder> Thens { get; }
  20. IEnumerable<String> ColumnNames();
  21. string AsOData();
  22. void SerializeBinary(CoreBinaryWriter writer);
  23. void DeserializeBinary(CoreBinaryReader reader);
  24. }
  25. public static class SortOrder
  26. {
  27. public static ISortOrder Create<T>(Type concrete, Expression<Func<T,object>> expression, SortDirection direction = SortDirection.Ascending)
  28. {
  29. if (!typeof(T).IsAssignableFrom(concrete))
  30. throw new Exception($"Columns: {concrete.EntityName()} does not implement {typeof(T).EntityName()}");
  31. var type = typeof(SortOrder<>).MakeGenericType(concrete);
  32. var property = CoreUtils.GetFullPropertyName(expression,".");
  33. var result = Activator.CreateInstance(type, property, direction );
  34. return (result as ISortOrder)!;
  35. }
  36. }
  37. public class SortOrder<T> : SerializableExpression<T>, ISortOrder // where T : Entity
  38. {
  39. public SortDirection Direction { get; set; }
  40. public List<SortOrder<T>> Thens { get; private set; }
  41. List<ISortOrder> ISortOrder.Thens => Thens.OfType<ISortOrder>().ToList();
  42. //public SortOrder<T> Ascending()
  43. //{
  44. // Direction = SortOrder.Ascending;
  45. // return this;
  46. //}
  47. //public SortOrder<T> Descending()
  48. //{
  49. // Direction = SortOrder.Descending;
  50. // return this;
  51. //}
  52. public SortOrder<T> ThenBy(Expression<Func<T, object?>> expression, SortDirection direction = SortDirection.Ascending)
  53. {
  54. var thenby = new SortOrder<T>(expression, direction);
  55. Thens.Add(thenby);
  56. return this;
  57. }
  58. #region Constructors
  59. public SortOrder()
  60. {
  61. Thens = new List<SortOrder<T>>();
  62. Direction = SortDirection.Ascending;
  63. }
  64. public SortOrder(Expression<Func<T, object?>> expression, SortDirection direction = SortDirection.Ascending)
  65. : base(expression)
  66. {
  67. Thens = new List<SortOrder<T>>();
  68. Direction = direction;
  69. }
  70. public SortOrder(string property, SortDirection direction = SortDirection.Ascending)
  71. {
  72. Thens = new List<SortOrder<T>>();
  73. Direction = direction;
  74. var iprop = DatabaseSchema.Property(typeof(T), property);
  75. Expression = iprop.Expression();
  76. }
  77. public SortOrder(SerializationInfo info, StreamingContext context)
  78. {
  79. Deserialize(info, context);
  80. }
  81. public static explicit operator SortOrder<T>(SortOrder<Entity> v)
  82. {
  83. if (v == null)
  84. return null;
  85. var json = Serialization.Serialize(v);
  86. json = json.Replace(typeof(Entity).EntityName(), typeof(T).EntityName());
  87. var result = Serialization.Deserialize<SortOrder<T>>(json);
  88. return result;
  89. }
  90. #endregion
  91. #region Display Functions
  92. public string AsOData()
  93. {
  94. var orderby = new Dictionary<SortDirection, string>
  95. {
  96. { SortDirection.Ascending, "asc" },
  97. { SortDirection.Descending, "desc" }
  98. };
  99. var prop = "";
  100. if (CoreUtils.TryFindMemberExpression(Expression, out var mexp))
  101. prop = CoreUtils.GetFullPropertyName(mexp, "/");
  102. else
  103. prop = Expression.ToString();
  104. var result = string.Format("{0} {1}", prop, orderby[Direction]);
  105. if (Thens != null && Thens.Count > 0)
  106. foreach (var then in Thens)
  107. {
  108. var ThenResult = then.AsOData();
  109. if (!string.IsNullOrEmpty(ThenResult))
  110. result = string.Format("{0}, {1}", result, ThenResult);
  111. }
  112. return result;
  113. }
  114. public override string ToString()
  115. {
  116. return AsOData();
  117. }
  118. public IEnumerable<string> ColumnNames()
  119. {
  120. yield return CoreUtils.ExpressionToString(typeof(T), Expression);
  121. foreach (var then in Thens)
  122. foreach (var x in then.ColumnNames())
  123. yield return x;
  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 : CustomJsonConverter<ISortOrder>
  214. {
  215. public override bool CanConvert(Type objectType)
  216. {
  217. if (objectType.IsConstructedGenericType)
  218. {
  219. var ot = objectType.GetGenericTypeDefinition();
  220. var tt = typeof(SortOrder<>);
  221. if (ot == tt)
  222. return true;
  223. }
  224. return false;
  225. }
  226. public override ISortOrder? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  227. {
  228. if (reader.TokenType == JsonTokenType.Null)
  229. return null;
  230. ISortOrder? result = null;
  231. var sType = "";
  232. var sExpr = "";
  233. var sDir = "";
  234. while (reader.TokenType != JsonTokenType.EndObject && reader.Read())
  235. {
  236. var tag = reader.GetString();
  237. reader.Read();
  238. if (string.Equals(tag, "$type"))
  239. {
  240. sType = reader.GetString();
  241. if (!string.IsNullOrWhiteSpace(sType))
  242. {
  243. var tType = Type.GetType(sType);
  244. if (tType != null)
  245. {
  246. var gType = typeof(SortOrder<>).MakeGenericType(tType);
  247. result = Activator.CreateInstance(gType) as ISortOrder;
  248. }
  249. }
  250. }
  251. else if (string.Equals(tag, "Expression") && result != null)
  252. sExpr = reader.GetString();
  253. else if (string.Equals(tag, "Direction") && result != null)
  254. sDir = reader.GetString();
  255. else if (string.Equals(tag, "Thens") && result != null)
  256. {
  257. reader.Read();
  258. while (reader.TokenType != JsonTokenType.EndObject)
  259. {
  260. var then = Read(ref reader, typeof(ISortOrder), options);
  261. if (then != null)
  262. result.Thens.Add(then);
  263. }
  264. }
  265. }
  266. return result;
  267. }
  268. public override void Write(Utf8JsonWriter writer, ISortOrder value, JsonSerializerOptions options)
  269. {
  270. var type = value.GetType().GenericTypeArguments[0];
  271. var property = CoreUtils.GetPropertyValue(value, "Expression") as MemberExpression;
  272. var prop = CoreUtils.ExpressionToString(type, property, true);
  273. var dir = CoreUtils.GetPropertyValue(value, "Direction")?.ToString() ?? nameof(SortDirection.Ascending);
  274. writer.WriteStartObject();
  275. writer.WriteString("$type",value.GetType().FullName);
  276. writer.WriteString("Expression",prop);
  277. writer.WriteString("Direction",dir);
  278. if (CoreUtils.GetPropertyValue(value, "Thens") is IEnumerable<ISortOrder> thens)
  279. {
  280. writer.WritePropertyName("Thens");
  281. writer.WriteStartArray();
  282. foreach (var then in thens)
  283. Write(writer,then,options);
  284. writer.WriteEndArray();
  285. }
  286. writer.WriteEndObject();
  287. }
  288. }
  289. }