Skip to main content

jQuery Datatable generic implementation on .Net/dotnet Core for any entity server filtering or sorting through EF/EF Core

jQuery Datatable is one of the popular freely available grid for the developers. It works really great on the client side but there is always need to write a lot of codes on the server side for filtering and sorting for each individual entities.

In this article, we would address this by creating a generic implementation of server code which can work on any entity without writing any further piece of code for filtering and sorting. Just by calling a generic extension method it would resolve sorting and filtering.

The key points to achieve it are as follows:
- Model binding and provider to transform client side request to strongly typed item on the server.
- Once we get strongly typed items to read values, we can apply a dynamic approach to generate queries and filters through LINQ expression.
- At final part, just consumption of created mechanism by creating endpoints for each entity. Also, we can easily select required columns through LINQ projection.

Model Binding

As per DataTable server request, it passes a lot of information to the server to filter out things which are really difficult to parse on the server to get exact value and the do filter on the server. The image was generated through https://datatables.net/examples/server_side/post.html post request. To simplify things we need a model binder to get structured data. On .net code, we need to do four things for same.
1. Model to hold passed values.
2. Model Binder.
3. Model Provider
4. Registration of model Provider on startup.cs.

Since it has a huge number of parameters, I am not going to go into details for each section but based on codes it would make sense and anyway that's an abstraction 😊.

Request Models

This section contains all the request models that are required.

 /// <summary>  
 /// Grid data request.  
 /// </summary>  
 public sealed class GridDataRequest  
 {  
   /// <summary>  
   /// Gets or sets the draw.  
   /// </summary>  
   /// <value>  
   /// The draw.  
   /// </value>  
   public int Draw { get; set; }  
   /// <summary>  
   /// Gets or sets the start index.  
   /// </summary>  
   /// <value>  
   /// The start index.  
   /// </value>  
   public int Start { get; set; }  
   /// <summary>  
   /// Gets or sets the length of page size.  
   /// </summary>  
   /// <value>  
   /// The length of page size.  
   /// </value>  
   public int Length { get; set; }  
   /// <summary>  
   /// Gets or sets the search.  
   /// </summary>  
   /// <value>  
   /// The search.  
   /// </value>  
   public DataTableSearch Search { get; set; }  
   /// <summary>  
   /// Gets or sets the order for columns.  
   /// </summary>  
   /// <value>  
   /// The order for columns.  
   /// </value>  
   public IEnumerable<DataTableOrder> Order { get; set; }  
   /// <summary>  
   /// Gets or sets the data table columns.  
   /// </summary>  
   /// <value>  
   /// The data table columns.  
   /// </value>  
   public IEnumerable<DataTableColumn> Columns { get; set; }  
 }  

 /// <summary>  
 /// The data table column search.  
 /// </summary>  
 public sealed class DataTableSearch  
 {  
   /// <summary>  
   /// Gets or sets the value.  
   /// </summary>  
   /// <value>  
   /// The value.  
   /// </value>  
   public string Value { get; set; }  
   /// <summary>  
   /// Gets or sets a value indicating whether this <see cref="DataTableSearch"/> is regex.  
   /// </summary>  
   /// <value>  
   ///  <c>true</c> if regex; otherwise, <c>false</c>.  
   /// </value>  
   public bool Regex { get; set; }  
 }  

 /// <summary>  
 /// The data table order of columns.  
 /// </summary>  
 public sealed class DataTableOrder  
 {  
   /// <summary>  
   /// Gets or sets the column.  
   /// </summary>  
   /// <value>  
   /// The column.  
   /// </value>  
   public string Column { get; set; }  
   /// <summary>  
   /// Gets or sets the direction of order.  
   /// </summary>  
   /// <value>  
   /// The direction of order.  
   /// </value>  
   public string Dir { get; set; }  
 }  

 /// <summary>  
 /// DataTable column  
 /// </summary>  
 public sealed class DataTableColumn  
 {  
   /// <summary>  
   /// Gets or sets the data.  
   /// </summary>  
   /// <value>  
   /// The data.  
   /// </value>  
   public string Data { get; set; }  
   /// <summary>  
   /// Gets or sets the name.  
   /// </summary>  
   /// <value>  
   /// The name.  
   /// </value>  
   public string Name { get; set; }  
   /// <summary>  
   /// Gets or sets a value indicating whether this <see cref="DataTableColumn"/> is orderable.  
   /// </summary>  
   /// <value>  
   ///  <c>true</c> if orderable; otherwise, <c>false</c>.  
   /// </value>  
   public bool Orderable { get; set; }  
   /// <summary>  
   /// Gets or sets a value indicating whether this <see cref="DataTableColumn"/> is searchable.  
   /// </summary>  
   /// <value>  
   ///  <c>true</c> if searchable; otherwise, <c>false</c>.  
   /// </value>  
   public bool Searchable { get; set; }  
   /// <summary>  
   /// Gets or sets the search request.  
   /// </summary>  
   /// <value>  
   /// The search request.  
   /// </value>  
   public DataTableSearch Search { get; set; }  
 }  

The main entry class over here is GridDataRequest model which would collect all information from client AJAX request.

We need one more model to return values once we are done with query filter. So, I have created a generic class which can contain IQuerable of data. We would see how it is being used later.

 /// <summary>  
 /// Grid data result.  
 /// </summary>  
 /// <typeparam name="T">The type of grid result.</typeparam>  
 public class GridDataResult<T>  
 {  
   /// <summary>  
   /// Gets or sets the draw.  
   /// </summary>  
   /// <value>  
   /// The draw.  
   /// </value>  
   [JsonProperty(PropertyName = "draw")]  
   public int Draw { get; set; }  
   /// <summary>  
   /// Gets or sets the records total.  
   /// </summary>  
   /// <value>  
   /// The records total.  
   /// </value>  
   [JsonProperty(PropertyName = "recordsTotal")]  
   public int RecordsTotal { get; set; }  
   /// <summary>  
   /// Gets or sets the records filtered.  
   /// </summary>  
   /// <value>  
   /// The records filtered.  
   /// </value>  
   [JsonProperty(PropertyName = "recordsFiltered")]  
   public int RecordsFiltered { get; set; }  
   /// <summary>  
   /// Gets or sets the data from result.  
   /// </summary>  
   /// <value>  
   /// The result data.  
   /// </value>  
   [JsonProperty(PropertyName = "data")]  
   public IQueryable<T> Data { get; set; }  
 }  

These were all POCO items needed. Now, we can have a look on implementation.

Model Binder

This would be having main logic to collect information from client request and transform into above classes.

 /// <summary>  
 /// <see cref="GridDataRequest"/> model binder.  
 /// </summary>  
 /// <seealso cref="IModelBinder" />  
 public sealed class GridDataRequestBinder  
   : IModelBinder  
 {  
   public Task BindModelAsync(ModelBindingContext bindingContext)  
   {  
     if (bindingContext == null)  
     {  
       throw new ArgumentNullException(nameof(bindingContext));  
     }  
     var request = bindingContext.HttpContext.Request;  
     var search = new DataTableSearch  
     {  
       Value = request.Form["search[value]"],  
       Regex = Convert.ToBoolean(request.Form["search[regex]"])  
     };  
     var ordByColCounter = 0;  
     var order = new List<DataTableOrder>();  
     while (!string.IsNullOrEmpty(request.Form["order[" + ordByColCounter + "][column]"]))  
     {  
       var column = request.Form["order[" + ordByColCounter + "][column]"];  
       order.Add(new DataTableOrder  
       {  
         Column = request.Form["columns[" + column + "][data]"],  
         Dir = request.Form["order[" + ordByColCounter + "][dir]"]  
       });  
       ordByColCounter++;  
     }  
     var colCounter = 0;  
     var columns = new List<DataTableColumn>();  
     while (!string.IsNullOrEmpty(request.Form["columns[" + colCounter + "][name]"]))  
     {  
       columns.Add(new DataTableColumn  
       {  
         Data = request.Form["columns[" + colCounter + "][data]"],  
         Name = request.Form["columns[" + colCounter + "][name]"],  
         Orderable = Convert.ToBoolean(request.Form["columns[" + colCounter + "][orderable]"]),  
         Searchable = Convert.ToBoolean(request.Form["columns[" + colCounter + "][searchable]"]),  
         Search = new DataTableSearch  
         {  
           Value = request.Form["columns[" + colCounter + "][search][value]"],  
           Regex = Convert.ToBoolean(request.Form["columns[" + colCounter + "][search][regex]"])  
         }  
       });  
       colCounter++;  
     }  
     var model = new GridDataRequest  
     {  
       Draw = Convert.ToInt32(request.Form["draw"]),  
       Start = Convert.ToInt32(request.Form["start"]),  
       Length = Convert.ToInt32(request.Form["length"]),  
       Search = search,  
       Order = order,  
       Columns = columns  
     };  
     model.Length = model.Length == 0 ? 10 : model.Length;  
     bindingContext.Result = ModelBindingResult.Success(model);  
     return TaskCache.CompletedTask;  
   }  
 }  

Model binder Provider

It has just simple logic to identify model and initiate the Grid binder

 /// <summary>  
 /// <see cref="Gems.Model.Dto.Grid.GridDataRequest"/> model binder provider.  
 /// </summary>  
 /// <seealso cref="Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinderProvider" />  
 public sealed class GridDataBinderProvider  
   : IModelBinderProvider  
 {  
   /// <summary>  
   /// Creates a <see cref="T:Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinder" /> based on <see cref="T:Microsoft.AspNetCore.Mvc.ModelBinding.ModelBinderProviderContext" />.  
   /// </summary>  
   /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.ModelBinding.ModelBinderProviderContext" />.</param>  
   /// <returns>  
   /// An <see cref="T:Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinder" />.  
   /// </returns>  
   /// <exception cref="ArgumentNullException">context</exception>  
   public IModelBinder GetBinder(ModelBinderProviderContext context)  
   {  
     if (context == null)  
     {  
       throw new ArgumentNullException(nameof(context));  
     }  
     if (context.Metadata.ModelType == typeof(GridDataRequest))  
     {  
       return new BinderTypeModelBinder(typeof(GridDataRequestBinder));  
     }  
     return null;  
   }  
 }  

Register Model Provider and setting JSON serializer

The final thing that needs to be done for this section is to register binder on MVC also register JSON serializer to return values in PascalCase to avoid parsing errors on the client while data binding.

 service.AddMvc(option =>  
 {  
   option.ModelBinderProviders.Insert(0, new GridDataBinderProvider());  
 })  
 .AddJsonOptions(options =>  
   options.SerializerSettings.ContractResolver = new DefaultContractResolver());  

LINQ query with expression

Now, we are done with the first section related to the model creation and binder. Next task is to compose the query by passing dynamic expression based on GridDataRequest.

Expression builders

The whole credits go to this post or any other originator of this.
https://stackoverflow.com/questions/35784736/linq-expression-building-get-property-and-convert-to-type#35785038. I have modified the source based on my need.

This is just expression model on which expression would be created.

 /// <summary>  
 /// Expression operators for creating expressions from enum.  
 /// </summary>  
 public enum ExpressionOperators  
 {  
   Equals,  
   GreaterThan,  
   LessThan,  
   GreaterThanOrEqual,  
   LessThanOrEqual,  
   Contains,  
   StartsWith,  
   EndsWith  
 }  
 /// <summary>  
 /// Expression model to apply expressions.  
 /// </summary>  
 public class ExpressionModel  
 {  
   /// <summary>  
   /// Gets or sets the name of the property.  
   /// </summary>  
   /// <value>  
   /// The name of the property.  
   /// </value>  
   public string PropertyName { get; set; }  
   /// <summary>  
   /// Gets or sets the expression operator.  
   /// </summary>  
   /// <value>  
   /// The expression operator.  
   /// </value>  
   public ExpressionOperators Operator { get; set; }  
   /// <summary>  
   /// Gets or sets the parameter value.  
   /// </summary>  
   /// <value>  
   /// The parameter value for the expression.  
   /// </value>  
   public object Value { get; set; }  
 }  

The expression builder helper function.

 /// <summary>  
 /// Expression builder helper class.  
 /// </summary>  
 public static class ExpressionBuilder  
 {  
   private static MethodInfo containsMethod = typeof(string).GetMethod("Contains");  
   private static MethodInfo endsWithMethod = typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });  
   private static MethodInfo startsWithMethod = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });  
   /// <summary>  
   /// Makes the predicate as per expression model.  
   /// </summary>  
   /// <typeparam name="T">The type on which expression would be built.</typeparam>  
   /// <param name="filters">The filters that need to be applied.</param>  
   /// <returns>The expression based on passed filters.</returns>  
   public static Expression<Func<T, bool>> MakePredicate<T>(IEnumerable<ExpressionModel> filters)  
   {  
     if (filters == null)  
     {  
       return (model) => true;  
     }  
     filters = filters.Where(filter => filter != null);  
     if (!filters.Any())  
     {  
       return (model) => true;  
     }  
     var item = Expression.Parameter(typeof(T), "item");  
     var body = filters.Select(filter => MakePredicate(item, filter)).Aggregate(Expression.AndAlso);  
     var predicate = Expression.Lambda<Func<T, bool>>(body, item);  
     return predicate;  
   }  
   /// <summary>  
   /// Applies order by expression based on nested type.  
   /// </summary>  
   /// <typeparam name="T">The type of model on which order by would be applied.</typeparam>  
   /// <param name="source">The query source.</param>  
   /// <param name="ordering">The ordering column.</param>  
   /// <param name="ascending">if set to <c>true</c> ascending.</param>  
   /// <returns>Query composition after applying order by predicate.</returns>  
   public static IQueryable<T> OrderBy<T>(  
     this IQueryable<T> source,  
     string ordering,  
     bool ascending)  
   {  
     if (string.IsNullOrEmpty(ordering))  
     {  
       return source;  
     }  
     var type = typeof(T);  
     var parameter = Expression.Parameter(type, "p");  
     PropertyInfo property;  
     Expression propertyAccess;  
     if (ordering.Contains('.'))  
     {  
       // support to be sorted on child fields.  
       var childProperties = ordering.Split('.');  
       property = type.GetProperty(childProperties[0]);  
       propertyAccess = Expression.MakeMemberAccess(parameter, property);  
       for (int i = 1; i < childProperties.Length; i++)  
       {  
         property = property.PropertyType.GetProperty(childProperties[i]);  
         propertyAccess = Expression.MakeMemberAccess(propertyAccess, property);  
       }  
     }  
     else  
     {  
       property = typeof(T).GetProperty(ordering);  
       propertyAccess = Expression.MakeMemberAccess(parameter, property);  
     }  
     var orderByExp = Expression.Lambda(propertyAccess, parameter);  
     var resultExp = Expression.Call(  
       typeof(Queryable),  
       ascending ? "OrderBy" : "OrderByDescending",  
       new[] { type, property.PropertyType },  
       source.Expression,  
       Expression.Quote(orderByExp));  
     return source.Provider.CreateQuery<T>(resultExp);  
   }  
   /// <summary>  
   /// Makes the predicate.  
   /// </summary>  
   /// <param name="item">The parameter expression item.</param>  
   /// <param name="filter">The filter model.</param>  
   /// <returns>Predicate for the filter.</returns>  
   private static Expression MakePredicate(ParameterExpression item, ExpressionModel filter)  
   {  
     var member = Expression.Property(item, filter.PropertyName);  
     var constant = Expression.Constant(filter.Value);  
     switch (filter.Operator)  
     {  
       case ExpressionOperators.Equals:  
         return Expression.Equal(member, constant);  
       case ExpressionOperators.GreaterThan:  
         return Expression.GreaterThan(member, constant);  
       case ExpressionOperators.LessThan:  
         return Expression.LessThan(member, constant);  
       case ExpressionOperators.GreaterThanOrEqual:  
         return Expression.GreaterThanOrEqual(member, constant);  
       case ExpressionOperators.LessThanOrEqual:  
         return Expression.LessThanOrEqual(member, constant);  
       case ExpressionOperators.Contains:  
         return Expression.Call(member, containsMethod, constant);  
       case ExpressionOperators.StartsWith:  
         return Expression.Call(member, startsWithMethod, constant);  
       case ExpressionOperators.EndsWith:  
         return Expression.Call(member, endsWithMethod, constant);  
     }  
     return null;  
   }  
 }  

It contains expressions for filters also order by expressions. We would see the query composition in next part.

Query composing through simplified extension methods

This is kind of entry point to create LINQ query. There are two overloaded functions one is to get a direct source of the data model and another one is to do through projection to select specific columns only.

 /// <summary>  
 /// Data source extension for querying Dynamic LINQ.  
 /// </summary>  
 public static class DataSourceQueryExtension  
 {  
   /// <summary>  
   /// To the data source.  
   /// </summary>  
   /// <typeparam name="T">Type of the request.</typeparam>  
   /// <param name="querySource">The query source.</param>  
   /// <param name="request">The request.</param>  
   /// <returns>The filtered result based on grid data request.</returns>  
   public static GridDataResult<T> ToDataSource<T>(  
     this IQueryable<T> querySource,  
     GridDataRequest request)  
   {  
     return new GridDataResult<T>  
     {  
       Draw = request.Draw,  
       RecordsTotal = querySource.Count(),  
       RecordsFiltered = 1,  
       Data = querySource.GetFilteredQuery(request)  
           .Skip(request.Start)  
           .Take(request.Length)  
     };  
   }  
   /// <summary>  
   /// To the data source.  
   /// </summary>  
   /// <typeparam name="T">The type of the model for query.</typeparam>  
   /// <typeparam name="TResult">The type of the result.</typeparam>  
   /// <param name="querySource">The query source.</param>  
   /// <param name="request">The request.</param>  
   /// <param name="expression">The expression.</param>  
   /// <returns>The filtered result based on grid data request.</returns>  
   /// <exception cref="ArgumentNullException">expression</exception>  
   public static GridDataResult<TResult> ToDataSource<T, TResult>(  
     this IQueryable<T> querySource,  
     GridDataRequest request,  
     Expression<Func<T, TResult>> expression)  
   {  
     if (expression == null)  
     {  
       throw new ArgumentNullException(nameof(expression));  
     }  
     return new GridDataResult<TResult>  
     {  
       Draw = request.Draw,  
       RecordsTotal = querySource.Count(),  
       RecordsFiltered = 1,  
       Data = querySource.GetFilteredQuery(request)  
           .Select(expression)  
           .Skip(request.Start)  
           .Take(request.Length)  
     };  
   }  
   /// <summary>  
   /// Gets the filtered query.  
   /// </summary>  
   /// <typeparam name="T">The type of the model for query.</typeparam>  
   /// <param name="querySource">The query source.</param>  
   /// <param name="request">The request.</param>  
   /// <returns>Filtered query based on <paramref name="request"/>.</returns>  
   private static IQueryable<T> GetFilteredQuery<T>(  
     this IQueryable<T> querySource,  
     GridDataRequest request)  
   {  
     var obj = new List<ExpressionModel>();  
     request.Columns.Where(col => !string.IsNullOrEmpty(col.Search.Value))  
       .ToList().ForEach((col) =>  
       {  
         obj.Add(new ExpressionModel  
         {  
           Operator = ExpressionOperators.Equals,  
           PropertyName = col.Data,  
           Value = col.Search.Value  
         });  
       });  
     querySource = querySource.Where(ExpressionBuilder.MakePredicate<T>(obj));  
     var column = request.Order.Select(v => v.Column).FirstOrDefault();  
     var direction = request.Order.Select(v => v.Dir).FirstOrDefault();  
     querySource = querySource.OrderBy(column, direction != "desc");  
     return querySource;  
   }  
 }  


Endpoints to consume above mechanism

Now, the easiest part is to use the whole implementation in a cleaner manner. This support any kind of sorting and filtering based on a string. Filtering plugin can be used for same https://datatables.net/examples/api/multi_filter.html.

There aren't any codes written here, also it can work on any entities without writing codes to do filters and sorting.

 [HttpPost]  
 public JsonResult List(GridDataRequest request)  
 {  
   return Json(UnitOfWork.EmployeeRepository.All()  
           .ToDataSource(request, model => new { model.Id, model.Name }));  
 }  
 [HttpPost]  
 public JsonResult List(GridDataRequest request)  
 {  
   return Json(UnitOfWork.EmployeeRepository.All()  
           .ToDataSource(request);  
 }  

NOTE: This is been created as a concept, need to see how it progress with various requirements. It may have issues with certain data types on filters but this gives an idea to extend and fulfill requirements. I would try to release as a nuget package later.



Popular posts from this blog

Handling JSON DateTime format on Asp.Net Core

This is a very simple trick to handle JSON date format on AspNet Core by global settings. This can be applicable for the older version as well.

In a newer version by default, .Net depends upon Newtonsoft to process any JSON data. Newtonsoft depends upon Newtonsoft.Json.Converters.IsoDateTimeConverter class for processing date which in turns adds timezone for JSON data format.

There is a global setting available for same that can be adjusted according to requirement. So, for example, we want to set default formatting to US format, we just need this code.


services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.DateTimeZoneHandling = "MM/dd/yyyy HH:mm:ss"; });



Elegantly dealing with TimeZones in MVC Core / WebApi

In any new application handling TimeZone/DateTime is mostly least priority and generally, if someone is concerned then it would be handled by using DateTime.UtcNow on codes while creating current dates and converting incoming Date to UTC to save on servers.
Basically, the process is followed by saving DateTime to UTC format in a database and keep converting data to native format based on user region or single region in the application's presentation layer.
The above is tedious work and have to be followed religiously. If any developer misses out the manual conversion, then that area of code/view would not work.
With newer frameworks, there are flexible ways to deal/intercept incoming or outgoing calls to simplify conversion of TimeZones.
These are steps/process to achieve it. 1. Central code for storing user's state about TimeZone. Also, central code for conversion logic based on TimeZones. 2. Dependency injection for the above class to be able to use globally. 3. Creating Mo…

LDAP with ASP.Net Identity Core in MVC with project.json

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functionality.

It is always better to have an abstraction for irrelevant items in consuming part. For an example, the application does not need to know about PrincipalContext or any other dependent items from those two references to make it extensible. So, we can begin with some bas…

Trim text in MVC Core through Model Binder

Trimming text can be done on client side codes, but I believe it is most suitable on MVC Model Binder since it would be at one place on infrastructure level which would be free from any manual intervention of developer. This would allow every post request to be processed and converted to a trimmed string.

Let us start by creating Model binder

using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Threading.Tasks; public class TrimmingModelBinder : IModelBinder { private readonly IModelBinder FallbackBinder; public TrimmingModelBinder(IModelBinder fallbackBinder) { FallbackBinder = fallbackBinder ?? throw new ArgumentNullException(nameof(fallbackBinder)); } public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingC…

Architecture solution composting Repository Pattern, Unit Of Work, Dependency Injection, Factory Pattern and others

Project architecture is like garden, we plant the things in certain order and eventually they grow in similar manner. If things are planted well then they will all look(work) great and easier to manage. If they grow as cumbersome it would difficult to maintain and with time more problems would be happening in maintenance.

There is no any fixed or known approach to decide project architecture and specially with Agile Methodology. In Agile Methodology, we cannot predict how our end products will look like similarly we cannot say a certain architecture will fit well for entire development lifespan for project. So, the best thing is to modify the architecture as per our application growth. I understand that it sounds good but will be far more problematic with actual development. If it is left as it is then more problems will arise with time. Just think about moving plant vs a full grown tree.

Coming to technical side, In this article, I will be explaining about the various techniques tha…

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager.

As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up:

[assembly: OwinStartup(typeof(MyProject.Web.Startup))]
Ninject configuration

Configuring Ninject kernel through method which would be used to register under Owin.

Startup.cs
public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); throw; }…

Kendo MVC Grid DataSourceRequest with AutoMapper - Advance

The actual process to make DataSourceRequest compatible with AutoMapper was explained in my previous post Kendo MVC Grid DataSourceRequest with AutoMapper, where we had created custom model binder attribute and in that property names were changed as data models.

In this post we will be looking into using AutoMapper's Queryable extension to retrieve the results based on selected columns. When Mapper.Map<RoleViewModel>(data) is called it retrieves all column values from table. The Queryable extension provides a way to retrieve only selected columns from table. In this particular case based on properties of RoleViewModel.
The previous approach that we implemented is perfect as far as this article (3 Tips for Using Telerik Data Access and AutoMapper) is concern about performance where it states: While this functionality allows you avoid writing explicit projection in to your LINQ query it has the same fatal flaw as doing so - it prevents the query result from being cached.
Since …

Kendo MVC Grid DataSourceRequest with AutoMapper

Kendo Grid does not work directly with AutoMapper but could be managed by simple trick using mapping through ToDataSourceResult. The solution works fine until different filters are applied.
The problems occurs because passed filters refer to view model properties where as database model properties are required after AutoMapper is implemented.
So, the plan is to intercept DataSourceRequest  and modify names based on database model. To do that we are going to create implementation of CustomModelBinderAttribute to catch calls and have our own implementation of DataSourceRequestAttribute from Kendo MVC. I will be using same source code from Kendo but will replace column names for different criteria for sort, filters, group etc.
Let's first look into how that will be implemented.
public ActionResult GetRoles([MyDataSourceRequest(GridId.RolesUserGrid)] DataSourceRequest request) { if (request == null) { throw new ArgumentNullException("reque…

Global exception handling and custom logging in AspNet Core with MongoDB

In this, we would be looking into logging and global exception handling in the AspNet Core application with proper registration of logger and global exception handling.

Custom logging
The first step is to create a data model that we want to save into DB.

Error log Data model
These are few properties to do logging which could be extended or reduced based on need.

public class ErrorLog { /// <summary> /// Gets or sets the Error log identifier. /// </summary> /// <value> /// The Error log identifier. /// </value> [BsonRepresentation(BsonType.ObjectId)] public ObjectId Id { get; set; /// <summary> /// Gets or sets the date. /// </summary> /// <value> /// The date. /// </value> public DateTime Date { get; set; } /// <summary> /// Gets or sets the thread. /// </summary> /// <v…

T4, Generating interface automatically based on provided classes

With new techniques and patterns interface plays a key role in application architecture. Interface makes application extendable like defining file upload interface and implementing based on file system, Azure Blob storage, Amazon S3. At starting we might be implementing based on Azure Blob but later we might move to Windows based file system and so on.

Ideally we create interface based on need and start implementing actual default implementation class. Many a times at starting of implementation there is one to one mapping between Interface and Class. Like from above example File upload interface and the initial or default class implementation that we design and with time it will get extended.
In this article, we will try to create interface based on default class implementation. This is not at all recommended in Test Driven Design (TDD) where we test the application before actual code implementation but I feel sometimes and in some situations it is okay do that and test straight afte…