Skip to main content

Consuming built MVC project under other MVC app

The idea is to reuse build application on multiple child application as a lot of Views and Codes need to be same on all children application. This approach can be a good candidate for a multitenant application, some sort of pluggable architecture or reusing MVC app as parent project.

There are three things need to be done to achieve.
  1. Project built event to copy Views from the parent application.
  2. Area registration on child application.
  3. Custom View path through customized Razor view engine.
Project built event to copy Views from the parent application.

This has to be configured on child application to copy from application build event. It can be done by going into project property => Build Events => Edit Post Built (Post-built event command line).
Ex:
xcopy "$(SolutionDir)"..\“App.Common\App.Common.Web\Views” “$(ProjectDir)\CommonAppLoc\Views\” /s /i /y /f

xcopy "$(SolutionDir)"..\“App.common\App.Common\App.Common.Web\Areas” “$(ProjectDir)\CommonAppLoc\Areas\” /s /i /y /f

xcopy "$(SolutionDir)"..\“\App.Common\App.Common.Web\Content” “$(ProjectDir)\CommonAppLoc\Content\” /s /i /y /f

There are several macros which can help out to get the desired path. In this one, $(SolutionDir) is used to get solution path and then put the relative path for the application. It can be customized based on a need basis.

In above example, I am trying to copy View, Areas and Content to child application to get physical files.

Area registration on child application.

To consume some other controller, Area registration needs to be done in a different manner with namespace parameter to refer codes of the parent controller from somewhere else.


 public override void RegisterArea(AreaRegistrationContext context)  
 {  
   context.MapRoute(  
     name: "User_default",  
     url: "User/{controller}/{action}/{id}",  
     defaults: new { action = "Index", id = UrlParameter.Optional },  
     namespaces: new[] { "App.Common.Web.Areas.User,Controllers" }  
   );  
 }  


NOTE: If want to have the same path as parent application then Area registration on parent application can be and consumed on child application to have paths


Custom View path through customized Razor view engine.

Since the other app Views are copied to the local project, we need to set up our View Engine to look into the newly copied paths. To do that the default view engine needs to override to have those paths.

If we look into the source code of MVC then can have a better idea https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/RazorViewEngine.cs.

So, we can inherit the same RazorViewEngine and customize the paths based on desired locations.

 public class AppCommonRazor  
 : RazorViewEngine  
 {  
   /// <summary>  
   /// Initializes a new instance of the <see cref="AppCommonRazor"/> class.  
   /// </summary>  
   public AppCommonRazor()  
   {  
     ViewLocationFormats = ViewLocationFormats.Concat(new string[]  
     {  
       "~/CommonApp/Views/CustomViewLoc/{1}/{0}.cshtml",  
       "~/CommonApp/Views/CustomViewLoc/{0}.cshtml",  
       "~/CommonApp/Views/{1}/{0}.cshtml",  
       "~/CommonApp/Views/{0}.cshtml",  
     }).ToArray();  
     PartialViewLocationFormats = PartialViewLocationFormats.Concat(new string[]  
     {  
       "~/CommonApp/Views/CustomViewLoc/{1}/{0}.cshtml",  
       "~/CommonApp/Views/CustomViewLoc/Shared/{0}.cshtml",  
       "~/CommonApp/Views/{1}/{0}.cshtml",  
       "~/CommonApp/Views/Shared/{0}.cshtml",  
     }).ToArray();  
     AreaViewLocationFormats = AreaViewLocationFormats.Concat(new string[]  
     {  
       "~/CommonApp/Areas/{2}/Views/CustomViewLoc/{1}/{0}.cshtml",  
       "~/CommonApp/Areas/{2}/Views/CustomViewLoc/Shared/{0}.cshtml",  
       "~/CommonApp/Areas/{2}/Views/{1}/{0}.cshtml",  
       "~/CommonApp/Areas/{2}/Views/Shared/{0}.cshtml",  
     }).ToArray();  
     AreaPartialViewLocationFormats = AreaPartialViewLocationFormats.Concat(new string[]  
     {  
       "~/CommonApp/Areas/{2}/Views/CustomViewLoc/{1}/{0}.cshtml",  
       "~/CommonApp/Areas/{2}/Views/CustomViewLoc/Shared/{0}.cshtml",  
       "~/CommonApp/Areas/{2}/Views/{1}/{0}.cshtml",  
       "~/CommonApp/Areas/{2}/Views/Shared/{0}.cshtml",  
     }).ToArray();  
   }  
 }  

The above code is just registering CommonApp path for the application to get the views. The CustomViewLoc path is used to add precedence for views. If any view need further customization then it can be just placed under CustomViewLoc, if it is not present then it picks from original view.

Finally, the View engine registration
This above view engine needs to be registered under Global.asax

 ViewEngines.Engines.Clear();  
 ViewEngines.Engines.Add(new MasterAppCommonRazor());  

Comments

Popular posts from this blog

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) { ...

Centralized model validation both for MVC/WebApi and SPA client-side validation using FluentValidation

Validation is one of the crucial parts of any application. It has to validate on both client side and server side requests. What are target features or implementation from this article? Model validation for any given model. Centralized/One code for validation on both server-side and client-side. Automatic validation of model without writing any extra codes on/under actions for validation.  NO EXTRA/ANY codes on client-side to validate any form. Compatible with SPA. Can be compatible with any client-side validation framework/library. Like Angular Reactive form validation or any jquery validation libraries. Tools used in the implementation? FluentValidation : I feel DataAnnotation validation are excellent and simple to use, but in case of complex validation or writing any custom validations are always tricker and need to write a lot of codes to achieve whereas FluentValidations are simple even in case of complex validation. Generally, we need to validate inc...

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 ...

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 ...

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...

Custom authorization on class, action/function, code, area level under Asp.Net MVC application

With evolution of ASP.Net MVC there are lot of inbuilt feature came and evolved with time. One of those is Authorization and Custom Authorization. The in-built function is sufficient enough to handle anonymous user restriction, user based on there name, specific roles for user with just single class AuthorizeAttribute . To implement we need to decorate attribute on any given class, action based on need. Example: [Authorize] public ActionResult Test() { } By just providing  Authorize  attribute anonymous user are restricted. It has Roles  and Users  property parameters to restrict access based on certain role or user which can accept multiple values by comma separated as string format. In one of the situation, I got chance to built an authorization where roles keep changing. Administrator can add new role, delete any role or modify existing role. In that situation we cannot map roles with codes. So, there were two way to achieve by creating group ...

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> ...

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...

main method return value

Mainly we used to write "static void main" for entry point in console application. Placement of void denotes return type. In main function we could have "int" too but what does it really mean. "int main" signifies return type as integer. The return type of main function tells about execution status of application. Even if we have specified void as return type then it would be marked as successful program execution. If we mark int as return type then we are able to control the execution status. Now, what is the benefit of making main function as int. Windows OS saves result in  %ERRORLEVEL% environment variable of OS. If we create batch file and execute application through it then we will able to get status and based on result we can trigger something else through batch file. Let's suppose we have created program called TEST.EXE. Batch file script: @echo off REM Execute main program REM TEST.EXE @if  "%ERRORLEVEL%" == "0...