Skip to main content

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 that I have used and why that particular path has been taken.

The most dumbest yet the core part of any application is to save data. Whole application revolves around same. With growth of Object relational mapping(ORM), it is now a standard to map database tables as classes or we can say data models. In this particular architecture that we are going to create, data model will be playing central part of it.

It is always better to separate out data models rather then getting it associated with certain ORM. We might need to change ORM at any point as per need or certain things that used ORM provider does not provide. Also by keeping data models separate it could be used by other project in different way without hindering the current process. The approach could be called as Code first but these should be kept as a separate project.


As you see MyProject.Model is kept as separate project. There could be various models we are going to deal with. Like already told Data models, View models, Data Transfer Object or some internal business object model. All types of possible models meant to be kept over here.

So, now we know where to keep the different models associate with project. Before moving to DB layer let me introduce interface layer. The interfaces are like defining structure so that others can implement in there own way. Interfaces are great way to do Unit testing by mocking up object. The most important thing about interface is implementing dependency injection. In this way we won't be hard coding some specific class responsible to run application rather then dependent on interface. If the whole application is dependent on interface then we can change the definition of interfaces as per our different version of classes based on similar interface. Ex: Saving files, user can interact with cloud providers like Dropbox, OneDrive or any other. We can create our own interface and implement different version of classes as per available providers.

Again we will keep interface entirely in different layer so that we will be having the project specification at single place. This layer will also keep interfaces for any other features related to project like Business, services, factory or any core area like multiple caching, cloud access etc.

Let's move to DB layer, based on same I will be explaining related interfaces for MyProject.Interface.
In this one I will explaining all about Repositories, Unit of work.

Why repository pattern?
Repository pattern was created to have an abstraction from database so that people do not use Sql queries everywhere and other layers should not be aware of backend. With evolution of ORM and LINQ it make sense to avoid it but for me if anything is getting repeated then those should be kept as centralized place. Also sticking up with specific ORM does not sounds like good idea which may change in future.

The Repositories are created individually as per each data models. So, project can have lot of repository classes. To handle those multiple repositories Unit of work pattern is implement. For example, if multiple operations are done on database context then all of operation can be saved in a single transaction.

There are various ways to implement Repository and Unit of work. I will be giving walk through as per mine implementation with proper details why particular approach has been chosen.

Let's start with first stage where we need to create actual DbContext version for Entity Framework. I am keeping things less and simple for better clarity.

The simple DB context for just accepting connection string:

 internal sealed class MyProjectContext  
     : DbContext  
   {  
     public MyProjectContext()  
       : base("name=MyProjectEntities")  
     {  
     }  
     public MyProjectContext(string connectionString)  
       : base(connectionString)  
     {  
     }  
     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
     {  
       // Configure mappings  
       new FluentMapping.FluentMapping(modelBuilder);  
     }  
   }  

The next thing we need to have an interface for DbContext creation:

   /// <summary>  
   /// Context factory for creation of context  
   /// </summary>  
   /// <typeparam name="TContext">Database context</typeparam>  
   public interface IContextFactory<out TContext>  
     where TContext : DbContext  
   {  
     /// <summary>  
     /// Creates new database context  
     /// </summary>  
     /// <returns>New Database context</returns>  
     TContext Create();  
   }  


The implementation for context factory
   /// <summary>  
   /// Context Factory for project  
   /// </summary>  
   public sealed class MyProjectContextFactory  
     : IContextFactory<DbContext>  
   {  
     /// <summary>  
     /// The connection string  
     /// </summary>  
     private readonly string _connectionString;  
     /// <summary>  
     /// Initializes a new instance of the <see cref="MyProjectContextFactory"/> class.  
     /// </summary>  
     /// <param name="connectionStringOrName">Name of the connection string or actual connection string.</param>  
     public MyProjectContextFactory(string connectionStringOrName)  
     {  
       _connectionString = connectionStringOrName;  
     }  
     /// <summary>  
     /// Creates new database context.  
     /// </summary>  
     /// <returns>DbContext: <see cref="MyProjectContext"/></returns>  
     public DbContext Create()  
     {  
       return new MyProjectContext(_connectionString);  
     }  
   }  

These are all for context related stuff. If you check the MyProjectContext class it is being set as internal for access specifier to restrict calls outside of DB layer. The only way to get context is through MyProjectContextFactory class which will get injected later on through IContextFactory.

After context we can jump into Repository creation. There are few steps which are implemented to reduce extra codes. Those are base class of repositories and interface for same. Each repositories are get accessed via interface that is why Repository's base class is created along with the interface for same.

Repository interface:

 /// <summary>  
   /// Base repository interface for interaction with DB model  
   /// </summary>  
   /// <typeparam name="TModel">Entity Type</typeparam>  
   public interface IRepository<TModel>  
     where TModel : class  
   {  
     /// <summary>  
     /// Gets the count.  
     /// </summary>  
     /// <value>Total rows count.</value>  
     int Count { get; }  
     /// <summary>  
     /// Alls this instance.  
     /// </summary>  
     /// <returns>All records from model</returns>  
     IQueryable<TModel> All();  
     /// <summary>  
     /// Gets model by id.  
     /// </summary>  
     /// <param name="id">The id.</param>  
     /// <returns>Entity</returns>  
     TModel GetById(object id);  
     /// <summary>  
     /// Gets objects via optional filter, sort order, and includes.  
     /// </summary>  
     /// <param name="filter">The filter.</param>  
     /// <param name="orderBy">The order by.</param>  
     /// <returns>IQueryable for model entity</returns>  
     IQueryable<TModel> Get(Expression<Func<TModel, bool>> filter = null, Func<IQueryable<TModel>,  
       IOrderedQueryable<TModel>> orderBy = null);  
     /// <summary>  
     /// Gets objects from database by filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter</param>  
     /// <returns>IQueryable for model entity</returns>  
     IQueryable<TModel> Filter(Expression<Func<TModel, bool>> predicate);  
     /// <summary>  
     /// Gets objects from database with filtering and paging.  
     /// </summary>  
     /// <param name="filter">Specified filter.</param>  
     /// <param name="total">Returns the total records count of the filter.</param>  
     /// <param name="index">Page index.</param>  
     /// <param name="size">Page size.</param>  
     /// <returns>IQueryable for model entity</returns>  
     IQueryable<TModel> Filter(Expression<Func<TModel, bool>> filter, out int total, int index = 0, int size = 50);  
     /// <summary>  
     /// Gets the object(s) is exists in database by specified filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter expression</param>  
     /// <returns><c>true</c> if contains the specified filter; otherwise, /c>.</returns>  
     bool Contains(Expression<Func<TModel, bool>> predicate);  
     /// <summary>  
     /// Find object by specified expression.  
     /// </summary>  
     /// <param name="predicate">Specified filter.</param>  
     /// <returns>Search result</returns>  
     TModel Find(Expression<Func<TModel, bool>> predicate);  
     /// <summary>  
     /// Create a new object to database.  
     /// </summary>  
     /// <param name="entity">A new object to create.</param>  
     /// <returns>Created object</returns>  
     void Create(TModel entity);  
     /// <summary>  
     /// Deletes the object by primary key  
     /// </summary>  
     /// <param name="id">Object key</param>  
     void Delete(object id);  
     /// <summary>  
     /// Delete the object from database.  
     /// </summary>  
     /// <param name="entity">Specified a existing object to delete.</param>  
     void Delete(TModel entity);  
     /// <summary>  
     /// Delete objects from database by specified filter expression.  
     /// </summary>  
     /// <param name="predicate">Specify filter.</param>  
     void Delete(Expression<Func<TModel, bool>> predicate);  
   }  

Repository base class:

 /// <summary>  
   /// Base repository implementation to interacting with database through ORM  
   /// </summary>  
   /// <typeparam name="TModel">The type of the model.</typeparam>  
   public class Repository<TModel>  
     : IRepository<TModel> where TModel : class  
   {  
     /// <summary>  
     /// DB context  
     /// </summary>  
     protected readonly DbContext DbContext;  
     /// <summary>  
     /// Gets the context.  
     /// </summary>  
     /// <typeparam name="T">Db Model</typeparam>  
     /// <returns></returns>  
     protected T GetContext<T>() where T  
       : class  
     {  
       return (T)Convert.ChangeType(DbContext, Type.GetTypeCode(typeof(T)));  
     }  
     /// <summary>  
     /// Initializes a new instance of the <see cref="Repository{TModel}"/> class.  
     /// </summary>  
     /// <param name="dbContext">The DB context.</param>  
     protected Repository(DbContext dbContext)  
     {  
       DbContext = dbContext;  
     }  
     /// <summary>  
     /// Gets the count.  
     /// </summary>  
     /// <value>Total rows count.</value>  
     public virtual int Count  
     {  
       get { return DbContext.Set<TModel>().Count(); }  
     }  
     /// <summary>  
     /// Alls this instance.  
     /// </summary>  
     /// <returns>All records from model</returns>  
     public virtual IQueryable<TModel> All()  
     {  
       return DbContext.Set<TModel>();  
     }  
     /// <summary>  
     /// Gets model by id.  
     /// </summary>  
     /// <param name="id">The id.</param>  
     /// <returns>DB Model</returns>  
     public virtual TModel GetById(object id)  
     {  
       return DbContext.Set<TModel>().Find(id);  
     }  
     /// <summary>  
     /// Gets objects via optional filter, sort order, and includes.  
     /// </summary>  
     /// <param name="filter">The filter.</param>  
     /// <param name="orderBy">The order by.</param>  
     /// <returns>IQueryable for model entity</returns>  
     public virtual IQueryable<TModel> Get(Expression<Func<TModel, bool>> filter = null,  
       Func<IQueryable<TModel>, IOrderedQueryable<TModel>> orderBy = null)  
     {  
       IQueryable<TModel> query = DbContext.Set<TModel>();  
       if (filter != null)  
       {  
         query = query.Where(filter);  
       }  
       return orderBy != null ? orderBy(query).AsQueryable() : query.AsQueryable();  
     }  
     /// <summary>  
     /// Gets objects from database by filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter</param>  
     /// <returns>IQueryable for model entity</returns>  
     public virtual IQueryable<TModel> Filter(Expression<Func<TModel, bool>> predicate)  
     {  
       return DbContext.Set<TModel>().Where(predicate).AsQueryable();  
     }  
     /// <summary>  
     /// Gets objects from database with filtering and paging.  
     /// </summary>  
     /// <param name="filter">Specified filter.</param>  
     /// <param name="total">Returns the total records count of the filter.</param>  
     /// <param name="index">Page index.</param>  
     /// <param name="size">Page size.</param>  
     /// <returns>IQueryable for model entity</returns>  
     public virtual IQueryable<TModel> Filter(Expression<Func<TModel, bool>> filter, out int total, int index = 0, int size = 50)  
     {  
       var skipCount = index * size;  
       var resetSet = filter != null ? DbContext.Set<TModel>().Where(filter).AsQueryable()  
         : DbContext.Set<TModel>().AsQueryable();  
       resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);  
       total = resetSet.Count();  
       return resetSet.AsQueryable();  
     }  
     /// <summary>  
     /// Gets the object(s) is exists in database by specified filter.  
     /// </summary>  
     /// <param name="predicate">Specified filter expression</param>  
     /// <returns><c>true</c> if contains the specified filter; otherwise, /c>.</returns>  
     public bool Contains(Expression<Func<TModel, bool>> predicate)  
     {  
       return DbContext.Set<TModel>().Any(predicate);  
     }  
     /// <summary>  
     /// Find object by specified expression.  
     /// </summary>  
     /// <param name="predicate">Specified filter.</param>  
     /// <returns>Search result</returns>  
     public virtual TModel Find(Expression<Func<TModel, bool>> predicate)  
     {  
       return DbContext.Set<TModel>().FirstOrDefault(predicate);  
     }  
     /// <summary>  
     /// Create a new object to database.  
     /// </summary>  
     /// <param name="entity">A new object to create.</param>  
     /// <returns>Created object</returns>  
     public virtual void Create(TModel entity)  
     {  
       DbContext.Set<TModel>().Add(entity);  
     }  
     /// <summary>  
     /// Deletes the object by primary key  
     /// </summary>  
     /// <param name="id">Object key</param>  
     public virtual void Delete(object id)  
     {  
       var entityToDelete = GetById(id);  
       Delete(entityToDelete);  
     }  
     /// <summary>  
     /// Delete the object from database.  
     /// </summary>  
     /// <param name="entity">Specified a existing object to delete.</param>  
     public virtual void Delete(TModel entity)  
     {  
       DbContext.Set<TModel>().Remove(entity);  
     }  
     /// <summary>  
     /// Delete objects from database by specified filter expression.  
     /// </summary>  
     /// <param name="predicate">Specify filter.</param>  
     public virtual void Delete(Expression<Func<TModel, bool>> predicate)  
     {  
       var entitiesToDelete = Filter(predicate);  
       foreach (var entity in entitiesToDelete)  
       {  
         DbContext.Set<TModel>().Remove(entity);  
       }  
     }  
   }  

The above interface and base class creates common logic to interact with data models so that basic functions can be avoided on each single repositories.

To access any data models respective repository with interface need to be created. Through these we can interact with domain models. Also any new function need to be added into these respective repository.

Ex:
IBookRepository.cs:

   /// <summary>  
   /// Interface to interact with <see cref="MyProject.Model.DataModel.Book"/> domain model.  
   /// </summary>  
   public partial interface IBookRepository  
        : IRepository<Book>  
   {  
   }  

BookRepository.cs

   /// <summary>  
   /// Interface for interacting with <see cref="MyProject.Model.DataModel.BookRepository"/>  
   /// </summary>  
      public partial class BookRepository  
           : Repository<MyProject.Model.DataModel.Book>,  
            MyProject.Interface.Repository.IBookRepository  
      {  
     /// <summary>  
     /// Initializes a new instance of the <see cref="BookRepository"/> class.  
     /// </summary>  
     /// <param name="dbContext">The database context.</param>  
     public BookRepository(DbContext dbContext)  
       : base(dbContext)  
     {  
     }  
      }  

As per each model these similar repository and interfaces need to be created. It becomes little cumbersome to keep adding these interfaces and respective classes for each models. I have created a T4 which generates basic class and interface according to models.

This is it as per repository. Now we are going to create Unit of work to handle to create instance of these repository interface and classes.

There would be a generic Unit of work interface and class which need to derived by project specific Unit of work. This creates another abstraction to implement Unit of work as repositories are project specific. This can be extended if we have more the one repository system.

IUnitOfWork.cs

   /// <summary>  
   /// Generic version of Unit Of Work.  
   /// </summary>  
   public interface IUnitOfWork : IDisposable  
   {  
     /// <summary>  
     /// Regenerates the context.  
     /// </summary>  
     void RegenerateContext();  
     /// <summary>  
     /// Saves Context changes.  
     /// </summary>  
     void Save();  
   }  

The above can be extended to specific transaction classes. The dispose function is written over here to handle context and also this is the key to share context among all repositories. The other thing need to noted out is the context is getting initialized by passing IContextFactory which will be passed and initialized on later stage.

 /// <summary>  
   /// Unit of work implementation for having single instance of context and doing DB operation as transaction  
   /// </summary>  
   /// <typeparam name="TContext">The type of the context.</typeparam>  
   public abstract class UnitOfWork<TContext> : IUnitOfWork  
     where TContext : DbContext  
   {  
     /// <summary>  
     /// DB context  
     /// </summary>  
     private TContext _dbContext;  
     /// <summary>  
     /// The DB context factory  
     /// </summary>  
     private readonly IContextFactory<TContext> _dbContextFactory;  
     /// <summary>  
     /// Initializes a new instance of the <see cref="UnitOfWork{TContext}"/> class.  
     /// </summary>  
     /// <param name="dbContextFactory">The db context factory.</param>  
     protected UnitOfWork(IContextFactory<TContext> dbContextFactory)  
       : this(dbContextFactory.Create())  
     {  
       _dbContextFactory = dbContextFactory;  
     }  
     /// <summary>  
     /// Initializes a new instance of the <see cref="UnitOfWork{TContext}"/> class.  
     /// </summary>  
     /// <param name="context">The context.</param>  
     protected UnitOfWork(TContext context)  
     {  
       _dbContext = context;  
     }  
     /// <summary>  
     /// Gets the context.  
     /// </summary>  
     /// <value>The context.</value>  
     public virtual TContext Context  
     {  
       get  
       {  
         return _dbContext;  
       }  
     }  
     /// <summary>  
     /// Regenerates the context.  
     /// </summary>  
     /// <remarks>WARNING: Calling with dirty context will save changes automatically</remarks>  
     public void RegenerateContext()  
     {  
       if (_dbContext != null)  
       {  
         Save();  
       }  
       _dbContext = _dbContextFactory.Create();  
     }  
     /// <summary>  
     /// Saves Context changes.  
     /// </summary>  
     public void Save()  
     {  
       Context.SaveChanges();  
     }  
     #region " Dispose "  
     /// <summary>  
     /// To detect redundant calls  
     /// </summary>  
     private bool _disposedValue;  
     /// <summary>  
     /// Dispose the object  
     /// </summary>  
     /// <param name="disposing">IsDisposing</param>  
     protected virtual void Dispose(bool disposing)  
     {  
       if (!_disposedValue)  
       {  
         if (disposing)  
         {  
           if (_dbContext != null)  
           {  
             _dbContext.Dispose();  
           }  
         }  
       }  
       _disposedValue = true;  
     }  
     #region " IDisposable Support "  
     /// <summary>  
     /// Dispose the object  
     /// </summary>  
     public void Dispose()  
     {  
       Dispose(true);  
       GC.SuppressFinalize(this);  
     }  
     #endregion " IDisposable Support "  
     #endregion " Dispose "  
   }  

Project specific Unit of work. If you check the class it is kind of hard coding the interface with related class which is not good. Instead of this service locator pattern or property dependency injection could be used but with this approach we have all repository instances at one place and also it is kind of lazy loading so that all instances does not get initialized at once. Also we are reducing a code much in this implementation.
Again, the instance creation of repository could be done with T4 which can be found in solution by using partial class.

 public sealed partial class MyProjectUnitOfWork  
     : UnitOfWork<DbContext>, IMyProjectUnitOfWork  
   {  
     public MyProjectUnitOfWork(IContextFactory<DbContext> contextFactory)  
       : base(contextFactory)  
     {  
     }  
     /// <summary>  
     /// BookRepository holder  
     /// </summary>  
     private MyProject.DB.Repository.BookRepository _bookRepository;  
     /// <summary>  
     /// Gets the BookRepository repository.  
     /// </summary>  
     /// <value>  
     /// The BookRepository repository.  
     /// </value>  
     MyProject.Interface.Repository.IBookRepository IMyProjectUnitOfWork.BookRepository  
     {  
       get  
       {  
         return _bookRepository =  
         _bookRepository ?? new MyProject.DB.Repository.BookRepository(Context);  
       }  
     }  
   }  

After all these, we are set with required architecture. Now, we just need to get it initialized with dependency injection under Web layer. Over here I am using Ninject for same. It can be installed via NuGet Ninject.MVC version package. It creates a NinjectWebCommon class under App_Start folder and under RegisterServices function we need to set dependency injection.

As you see, IContextFactory mapped with MyProjectContextFactory for context initialization and similarly UnitOfWork is initialized. Also this mapping will automatically create context and get disposed as per user request without taking overhead of initialization and disposing of object on our head.

       kernel.Bind<IContextFactory<DbContext>>()  
         .ToConstructor(ctxFac => new MyProjectContextFactory  
           (ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString));  
       kernel.Bind<IMyProjectUnitOfWork>().To<MyProjectUnitOfWork>();  

Before using them let's create a base class on MVC Controller to avoid variable creation every time.
If you see we just have created constructor  and having parameter of interface. This way we are avoiding any specific class and later on without changing entire application class definition can be simply changed by changing mapping that we did on Ninject Bind function.

BaseController:

  /// <summary>  
   /// Base controller for the application  
   /// </summary>  
   public abstract class BaseController  
     : Controller  
   {  
     /// <summary>  
     /// Gets my project unit of work.  
     /// </summary>  
     /// <value>  
     /// My project unit of work.  
     /// </value>  
     protected IMyProjectUnitOfWork MyProjectUnitOfWork { get; private set; }  
     /// <summary>  
     /// Initializes a new instance of the <see cref="BaseController"/> class.  
     /// </summary>  
     /// <param name="unitOfWork">The unit of work.</param>  
     public BaseController(IMyProjectUnitOfWork unitOfWork)  
     {  
       MyProjectUnitOfWork = unitOfWork;  
     }  
   }  

Final step, inherit any created controller with BaseController and create constructor with IMyProjectUnitOfWork which initializes property of base controller by initializing base class constructor.
Now if you see under Index action, repository and unit of work is used in simple and clean way without making much noise in code.

 public class HomeController : BaseController  
   {  
     public HomeController(IMyProjectUnitOfWork unitOfWork)  
       : base(unitOfWork)  
     {  
     }  
     public ActionResult Index()  
     {  
       MyProjectUnitOfWork.BookRepository.Create(new Model.DataModel.Book  
       {  
         BookTitle = "C#",  
         ISBN = "123",  
         PublisherName = "NA"  
       });  
       if (MyProjectUnitOfWork.BookRepository.Count == 0)  
       {  
         MyProjectUnitOfWork.Save();  
       }  
       return View();  
     }  
   }  

The entire code can be found on https://www.dropbox.com/s/41gakohw5r7030z/MyProject.zip?dl=0.

Comments

Popular posts from this blog

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 global

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"; });

Making FluentValidation compatible with Swagger including Enum or fixed List support

FluentValidation is not directly compatible with Swagger API to validate models. But they do provide an interface through which we can compose Swagger validation manually. That means we look under FluentValidation validators and compose Swagger validator properties to make it compatible. More of all mapping by reading information from FluentValidation and setting it to Swagger Model Schema. These can be done on any custom validation from FluentValidation too just that proper schema property has to be available from Swagger. Custom validation from Enum/List values on FluentValidation using FluentValidation.Validators; using System.Collections.Generic; using System.Linq; using static System.String; /// <summary> /// Validator as per list of items. /// </summary> /// <seealso cref="PropertyValidator" /> public class FixedListValidator : PropertyValidator { /// <summary> /// Gets the valid items /// <

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 ArgumentNullExce

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 wi

Using Redis distributed cache in dotnet core with helper extension methods

Redis cache is out process cache provider for a distributed environment. It is popular in Azure Cloud solution, but it also has a standalone application to operate upon in case of small enterprises application. How to install Redis Cache on a local machine? Redis can be used as a local cache server too on our local machines. At first install, Chocolatey https://chocolatey.org/ , to make installation of Redis easy. Also, the version under Chocolatey supports more commands and compatible with Official Cache package from Microsoft. After Chocolatey installation hit choco install redis-64 . Once the installation is done, we can start the server by running redis-server . Distributed Cache package and registration dotnet core provides IDistributedCache interface which can be overrided with our own implementation. That is one of the beauties of dotnet core, having DI implementation at heart of framework. There is already nuget package available to override IDistributedCache i

Data seed for the application with EF, MongoDB or any other ORM.

Most of ORMs has moved to Code first approach where everything is derived/initialized from codes rather than DB side. In this situation, it is better to set data through codes only. We would be looking through simple technique where we would be Seeding data through Codes. I would be using UnitOfWork and Repository pattern for implementing Data Seeding technique. This can be applied to any data source MongoDB, EF, or any other ORM or DB. Things we would be doing. - Creating a base class for easy usage. - Interface for Seed function for any future enhancements. - Individual seed classes. - Configuration to call all seeds. - AspNet core configuration to Seed data through Seed configuration. Creating a base class for easy usage public abstract class BaseSeed<TModel> where TModel : class { protected readonly IMyProjectUnitOfWork MyProjectUnitOfWork; public BaseSeed(IMyProjectUnitOfWork MyProjectUnitOfWork) { MyProject

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(bin

Storing and restoring Kendo Grid state from Database

There is no any built in way to store entire grid state into database and restore back again with all filters, groups, aggregates, page and page size. At first, I was trying to restore only filters by looking through DataSourceRequest. DataSourceRequest is kind of communication medium between client and server for the operation we do on grid. All the request comes via DataSourceRequest. In previous approach, I was trying to store IFileDescriptor interface which come with class FileDescriptor by looping through filters and serializing into string for saving into database but this IFileDescriptor can also contain CompositeFilterDescriptor which can be nested in nested object which are very tricky to handle. So, I had decompiled entire Kendo.MVC library and found out that all Kendo MVC controls are derived from “JsonObject”. It is there own implementation with ”Serialize” abstract function and “ToJson” function. In controls they are overriding “Serialize” method which depicts t

A wrapper implementation for Kendo Grid usage

A wrapper implementation for any heavily used item is always a good practice. Whatever is not written by us and used at a lot of places should be wrapped within specific functionality to keep it future proof and easily changeable. This also encourages DRY principle to keep our common setting at a central place. Kendo UI items are enormous in configuration, one of an issue I find people keep repeating codes for Kendo Grid configuration. They have built very flexible system to have any configuration, but in most of the cases, we do not need all of those complicated configuration. We would try to see a simpler configuration of same. The actual core implementation is bit complex, but we do not have to bother about it once done since the focus is just on usage only. I recommend doing this practice for as simple as jQuery events, form handling or as simple as any notification system. This just won't make things simple but makes codes much more manageable, easy understand, read or open f