SortOrder.cs 12 KB

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