-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDataTableHelper.cs
197 lines (186 loc) · 8.46 KB
/
DataTableHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using DataTable_ServerSide__Implementation_Sample.Data.Requests;
using DataTable_ServerSide__Implementation_Sample.Data.Responses;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace DataTable_ServerSide__Implementation_Sample.Extensions
{
public static class DataTableHelper
{
/// <summary>
/// Use this function to invoke selector in your options,
/// this might be good for performance when dealing with large tables.
/// </summary>
/// <typeparam name="T">Object Type</typeparam>
/// <param name="data">IQuerable of the data</param>
/// <param name="option">Datatable Options</param>
/// <param name="selector">Selector of type X => new object {...} </param>
/// <returns>Datatable Response for provided DBSet</returns>
public static async Task<DataTableResponse> GetOptionResponseAsync<T>(this IQueryable<T> data, DataTableOptions option, Expression<Func<T, object>> selector) where T : class
{
var countTotal = await data.CountAsync();
var searchedEntities = SearchEntity<T>(option, data);
var countFiltered = await searchedEntities.CountAsync();
var theData = await searchedEntities
.Skip(option.Start)
.Take(option.Length)
.Select(selector)
.ToListAsync();
return new DataTableResponse
{
Draw = Int32.Parse(option.Draw),
Data = theData.ToList(),
RecordsTotal = countTotal,
RecordsFiltered = countFiltered,
};
}
/// <summary>
/// Returns DataTable Response, done asynchronously
/// </summary>
/// <typeparam name="T">Object Type</typeparam>
/// <param name="data">IQuerable of the data</param>
/// <param name="option">Datatable Options</param>
/// <returns>Datatable Response for provided DBSet</returns>
public static async Task<DataTableResponse> GetOptionResponseAsync<T>(this IQueryable<T> data, DataTableOptions option) where T : class
{
var countTotal = await data.CountAsync();
var searchedEntities = SearchEntity<T>(option, data);
var countFiltered = await searchedEntities.CountAsync();
var theData = await searchedEntities
.Skip(option.Start)
.Take(option.Length)
.ToListAsync();
return new DataTableResponse
{
Draw = Int32.Parse(option.Draw),
Data = theData.ToList<object>(),
RecordsTotal = countTotal,
RecordsFiltered = countFiltered,
};
}
/// <summary>
/// Returns DataTable Response
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <param name="option"></param>
/// <returns>Datatable Response for provided DBSet</returns>
public static DataTableResponse GetOptionResponse<T>(this IQueryable<T> data, DataTableOptions option) where T : class
{
var countTotal = data.Count();
var searchedEntities = SearchEntity<T>(option, data);
var countFiltered = searchedEntities.Count();
var theData = searchedEntities
.Skip(option.Start)
.Take(option.Length)
.ToList();
return new DataTableResponse
{
Draw = Int32.Parse(option.Draw),
Data = theData.ToList<object>(),
RecordsTotal = countTotal,
RecordsFiltered = countFiltered,
};
}
/// <summary>
/// Returns Iquerable after applying dynamically all search and orders provided by the datatable options.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dtOptions"></param>
/// <param name="data"></param>
/// <returns></returns>
public static IQueryable<T> SearchEntity<T>(DataTableOptions dtOptions, IQueryable<T> data) where T : class
{
if (dtOptions.Search != null)
{
//Perform search filter on all Searchable Coloumns
if (!string.IsNullOrEmpty(dtOptions.Search.Value))
{
List<Expression<Func<T, bool>>> predicatesSearh = new List<Expression<Func<T, bool>>>();
foreach (var col in dtOptions.Columns.Where(t => t.Searchable))
{
string filterTarget = col.Data;
//If Property Not Found, upper the First char, other people might not need this if you explicitly use camel case serializing.
if (!typeof(T).GetProperties().Any(t => t.Name == filterTarget))
{
filterTarget = filterTarget[0].ToString().ToUpper() + filterTarget.Substring(1);
}
var colPredicate = ExpressionBuilder.BuildPredicate<T>(dtOptions.Search.Value, OperatorComparer.Contains, filterTarget);
if (colPredicate != null)
predicatesSearh.Add(colPredicate);
}
if (predicatesSearh.Any())
{
//Init Expression of type T return bool (search filter)
Expression<Func<T, bool>> predicateCompiled = null;
//Combine all search conditions
foreach (var pre in predicatesSearh)
predicateCompiled = predicateCompiled == null ? pre : predicateCompiled.Or(pre);
data = data.Where<T>(predicateCompiled);
}
}
}
//Perform column sorting
IOrderedQueryable<T> dataOrder = null;
if (dtOptions.Order != null)
{
var sortQuery = new List<string>();
foreach (var order in dtOptions.Order)
{
var col = dtOptions.Columns[order.Column];
if (col.Orderable)
{
var filterData = col.Data;
sortQuery.Add(filterData + " " + (order.Dir.ToLower().Equals("asc") ? "ASC" : "DESC"));
}
}
if (sortQuery.Any())
data = data.OrderBy(string.Join(",", sortQuery));
}
if (dataOrder != null)
return dataOrder;
else
return data;
}
/// <summary>
/// Used to build Expression for the specifications
/// </summary>
/// <typeparam name="T"> The Type </typeparam>
/// <param name="name"> (the name of the colomn to be filtered)</param>
/// <param name="value">(the value to be used for the comparision)</param>
/// <param name="comparer">type of comparer (Equal,Contains, NotEqual)</param>
/// <returns></returns>
public static Expression<Func<T, bool>> BuildPredicate<T>(string name, string value, OperatorComparer comparer)
{
if (typeof(T).GetProperties().Any(t => t.Name == name))
{
Expression<Func<T, bool>> predicateCompiled =
ExpressionBuilder.BuildPredicate<T>(value, comparer, name);
return predicateCompiled;
}
else
throw new Exception("Property Not Found, Please check property name used");
}
/// <summary>
/// Serialize Data Table Response.
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static string ToJsonString(this DataTableResponse response)
{
return JsonConvert.SerializeObject(response, Formatting.None, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver(),
DateTimeZoneHandling = DateTimeZoneHandling.Local,
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
});
}
}
}