SortOrder.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. MemberExpression mexp = null;
  94. if (CoreUtils.TryFindMemberExpression(Expression, out mexp))
  95. prop = CoreUtils.GetFullPropertyName(mexp, "/");
  96. else
  97. prop = Expression.ToString();
  98. var result = string.Format("{0} {1}", prop, orderby[Direction]);
  99. if (Thens != null && Thens.Count > 0)
  100. foreach (var then in Thens)
  101. {
  102. var ThenResult = then.AsOData();
  103. if (!string.IsNullOrEmpty(ThenResult))
  104. result = string.Format("{0}, {1}", result, ThenResult);
  105. }
  106. return result;
  107. }
  108. public override string ToString()
  109. {
  110. return AsOData();
  111. }
  112. public IEnumerable<string> ColumnNames()
  113. {
  114. List<String> result = new List<string>();
  115. result.Add(CoreUtils.ExpressionToString(typeof(T), Expression));
  116. foreach (var then in Thens)
  117. result.AddRange(then.ColumnNames());
  118. return result;
  119. }
  120. #endregion
  121. //public Expression<Func<T,Object>> AsExpression()
  122. //{
  123. // var param = Expression.Parameter(typeof(T), "x");
  124. // var result = Expression.Lambda<Func<T,Object>>(Expression,param);
  125. // return result;
  126. //}
  127. #region Serialization
  128. public override void Serialize(SerializationInfo info, StreamingContext context)
  129. {
  130. info.AddValue("Direction", Direction.ToString());
  131. if (Thens.Count > 0)
  132. info.AddValue("Thens", Thens, typeof(List<SortOrder<T>>));
  133. }
  134. public override void Deserialize(SerializationInfo info, StreamingContext context)
  135. {
  136. Direction = (SortDirection)Enum.Parse(typeof(SortDirection), (string)info.GetValue("Direction", typeof(string)));
  137. try
  138. {
  139. Thens = (List<SortOrder<T>>)info.GetValue("Thens", typeof(List<SortOrder<T>>));
  140. }
  141. catch
  142. {
  143. Thens = new List<SortOrder<T>>();
  144. }
  145. }
  146. #endregion
  147. }
  148. public class SortOrderJsonConverter : JsonConverter
  149. {
  150. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  151. {
  152. var property = CoreUtils.GetPropertyValue(value, "Expression") as MemberExpression;
  153. //MethodInfo mi = value.GetType().GetTypeInfo().GetMethod("ExpressionToString");
  154. //String prop = mi.Invoke(value, new object[] { property, true }) as String;
  155. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  156. var dir = CoreUtils.GetPropertyValue(value, "Direction");
  157. writer.WriteStartObject();
  158. writer.WritePropertyName("Expression");
  159. writer.WriteValue(prop);
  160. writer.WritePropertyName("Direction");
  161. writer.WriteValue(dir);
  162. var thens = CoreUtils.GetPropertyValue(value, "Thens") as IList;
  163. if (thens != null && thens.Count > 0)
  164. {
  165. writer.WritePropertyName("Thens");
  166. serializer.Serialize(writer, thens);
  167. }
  168. writer.WriteEndObject();
  169. }
  170. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  171. {
  172. if (reader.TokenType == JsonToken.Null)
  173. return null;
  174. var data = new Dictionary<string, object>();
  175. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  176. if (reader.Value != null)
  177. {
  178. var key = reader.Value.ToString();
  179. reader.Read();
  180. if (string.Equals(key, "Thens"))
  181. {
  182. var array = JArray.Load(reader);
  183. var thens = new List<object>();
  184. foreach (var item in array)
  185. {
  186. var then = ReadJson(item.CreateReader(), objectType, existingValue, serializer);
  187. thens.Add(then);
  188. //String jexp = item["Expression"].Value<String>();
  189. //MemberExpression exp = CoreUtils.StringToExpression(jexp) as MemberExpression;
  190. //var then = CreateSortOrder(
  191. // objectType,
  192. // exp.Member.Name,
  193. // (SortDirection)item["Direction"].Value<Int64>()
  194. //);
  195. //thens.Add(then);
  196. }
  197. data[key] = thens;
  198. }
  199. else
  200. {
  201. data[key] = reader.Value;
  202. }
  203. }
  204. var jprop = data["Expression"].ToString();
  205. var prop = CoreUtils.StringToExpression(jprop) as MemberExpression;
  206. var direction = (SortDirection)int.Parse(data["Direction"].ToString());
  207. var result = Activator.CreateInstance(objectType, CoreUtils.GetFullPropertyName(prop, "."), direction);
  208. if (data.ContainsKey("Thens"))
  209. {
  210. var source = data["Thens"] as List<object>;
  211. var target = CoreUtils.GetPropertyValue(result, "Thens") as IList;
  212. foreach (var srcitem in source)
  213. target.Add(srcitem);
  214. }
  215. return result;
  216. }
  217. public override bool CanConvert(Type objectType)
  218. {
  219. if (objectType.IsConstructedGenericType)
  220. {
  221. var ot = objectType.GetGenericTypeDefinition();
  222. var tt = typeof(SortOrder<>);
  223. if (ot == tt)
  224. return true;
  225. }
  226. return false;
  227. }
  228. }
  229. }