SortOrder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. 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. IEnumerable<ISortOrder> ISortOrder.Thens => Thens;
  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. List<String> result = new List<string>();
  121. result.Add(CoreUtils.ExpressionToString(typeof(T), Expression));
  122. foreach (var then in Thens)
  123. result.AddRange(then.ColumnNames());
  124. return result;
  125. }
  126. #endregion
  127. //public Expression<Func<T,Object>> AsExpression()
  128. //{
  129. // var param = Expression.Parameter(typeof(T), "x");
  130. // var result = Expression.Lambda<Func<T,Object>>(Expression,param);
  131. // return result;
  132. //}
  133. #region Serialization
  134. public override void Serialize(SerializationInfo info, StreamingContext context)
  135. {
  136. info.AddValue("Direction", Direction.ToString());
  137. if (Thens.Count > 0)
  138. info.AddValue("Thens", Thens, typeof(List<SortOrder<T>>));
  139. }
  140. public override void Deserialize(SerializationInfo info, StreamingContext context)
  141. {
  142. Direction = (SortDirection)Enum.Parse(typeof(SortDirection), (string)info.GetValue("Direction", typeof(string)));
  143. try
  144. {
  145. Thens = (List<SortOrder<T>>)info.GetValue("Thens", typeof(List<SortOrder<T>>));
  146. }
  147. catch
  148. {
  149. Thens = new List<SortOrder<T>>();
  150. }
  151. }
  152. #endregion
  153. #region Binary Serialization
  154. public void SerializeBinary(CoreBinaryWriter writer)
  155. {
  156. writer.SerialiseExpression(typeof(T), Expression, false);
  157. writer.Write((byte)Direction);
  158. writer.Write(Thens.Count);
  159. foreach (var then in Thens)
  160. {
  161. then.SerializeBinary(writer);
  162. }
  163. }
  164. public void DeserializeBinary(CoreBinaryReader reader)
  165. {
  166. Expression = reader.DeserialiseExpression(typeof(T));
  167. Direction = (SortDirection)reader.ReadByte();
  168. Thens.Clear();
  169. var nThens = reader.ReadInt32();
  170. for(int i = 0; i < nThens; ++i)
  171. {
  172. var then = new SortOrder<T>();
  173. then.DeserializeBinary(reader);
  174. Thens.Add(then);
  175. }
  176. }
  177. #endregion
  178. }
  179. public static class SortOrderSerialization
  180. {
  181. /// <summary>
  182. /// Inverse of <see cref="Write{T}(CoreBinaryWriter, SortOrder{T}?)"/>.
  183. /// </summary>
  184. /// <param name="reader"></param>
  185. /// <returns></returns>
  186. public static SortOrder<T>? ReadSortOrder<T>(this CoreBinaryReader reader)
  187. {
  188. if (reader.ReadBoolean())
  189. {
  190. var sortOrder = new SortOrder<T>();
  191. sortOrder.DeserializeBinary(reader);
  192. return sortOrder;
  193. }
  194. return null;
  195. }
  196. /// <summary>
  197. /// Inverse of <see cref="ReadSortOrder{T}(CoreBinaryReader)"/>.
  198. /// </summary>
  199. /// <param name="filter"></param>
  200. /// <param name="writer"></param>
  201. public static void Write<T>(this CoreBinaryWriter writer, SortOrder<T>? sortOrder)
  202. {
  203. if (sortOrder is null)
  204. {
  205. writer.Write(false);
  206. }
  207. else
  208. {
  209. writer.Write(true);
  210. sortOrder.SerializeBinary(writer);
  211. }
  212. }
  213. }
  214. public class SortOrderJsonConverter : JsonConverter
  215. {
  216. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
  217. {
  218. if(value is null)
  219. {
  220. writer.WriteNull();
  221. return;
  222. }
  223. var property = CoreUtils.GetPropertyValue(value, "Expression") as MemberExpression;
  224. //MethodInfo mi = value.GetType().GetTypeInfo().GetMethod("ExpressionToString");
  225. //String prop = mi.Invoke(value, new object[] { property, true }) as String;
  226. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  227. var dir = CoreUtils.GetPropertyValue(value, "Direction");
  228. writer.WriteStartObject();
  229. writer.WritePropertyName("$type");
  230. writer.WriteValue(value.GetType().FullName);
  231. writer.WritePropertyName("Expression");
  232. writer.WriteValue(prop);
  233. writer.WritePropertyName("Direction");
  234. writer.WriteValue(dir);
  235. var thens = CoreUtils.GetPropertyValue(value, "Thens") as IList;
  236. if (thens != null && thens.Count > 0)
  237. {
  238. writer.WritePropertyName("Thens");
  239. serializer.Serialize(writer, thens);
  240. }
  241. writer.WriteEndObject();
  242. }
  243. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  244. {
  245. if (reader.TokenType == JsonToken.Null)
  246. return null;
  247. var data = new Dictionary<string, object>();
  248. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  249. if (reader.Value != null)
  250. {
  251. var key = reader.Value.ToString();
  252. reader.Read();
  253. if (String.Equals(key, "$type"))
  254. objectType = Type.GetType(reader.Value.ToString()) ?? objectType;
  255. else if (string.Equals(key, "Thens"))
  256. {
  257. var array = JArray.Load(reader);
  258. var thens = new List<object>();
  259. foreach (var item in array)
  260. {
  261. var then = ReadJson(item.CreateReader(), objectType, existingValue, serializer);
  262. if(then != null)
  263. thens.Add(then);
  264. //String jexp = item["Expression"].Value<String>();
  265. //MemberExpression exp = CoreUtils.StringToExpression(jexp) as MemberExpression;
  266. //var then = CreateSortOrder(
  267. // objectType,
  268. // exp.Member.Name,
  269. // (SortDirection)item["Direction"].Value<Int64>()
  270. //);
  271. //thens.Add(then);
  272. }
  273. data[key] = thens;
  274. }
  275. else
  276. {
  277. data[key] = reader.Value;
  278. }
  279. }
  280. var jprop = data["Expression"].ToString();
  281. var prop = CoreUtils.StringToExpression(jprop) as MemberExpression;
  282. var direction = (SortDirection)int.Parse(data["Direction"].ToString());
  283. var result = Activator.CreateInstance(objectType, CoreUtils.GetFullPropertyName(prop, "."), direction);
  284. if (data.ContainsKey("Thens"))
  285. {
  286. var source = (data["Thens"] as List<object>)!;
  287. var target = (CoreUtils.GetPropertyValue(result, "Thens") as IList)!;
  288. foreach (var srcitem in source)
  289. target.Add(srcitem);
  290. }
  291. return result;
  292. }
  293. public override bool CanConvert(Type objectType)
  294. {
  295. if (objectType.IsConstructedGenericType)
  296. {
  297. var ot = objectType.GetGenericTypeDefinition();
  298. var tt = typeof(SortOrder<>);
  299. if (ot == tt)
  300. return true;
  301. }
  302. return false;
  303. }
  304. }
  305. }