European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting UK - HostForLIFE.eu :: How to Use Automapper with ASP.NET MVC Application

clock November 8, 2019 11:20 by author Peter

At this moment, I will show you How to Use Automapper with ASP.NET MVC Application. Automapper could be a convention primarily based object - object mapper. it's offered in GitHub. Here I make a case for about a way to use Automapper to map between domain model objects and think about model objects in ASP.NET MVC applications.  Install Automapper to the project through Nuget.

Consider there's a powerfully typed view that expects a model object of type EmployeeViewModel. thus after querying with the Emplyee model object, we want to map this to EmployeeViewModel object.
public class Employee
   {
      public int EmployeeId { get; set; }
      public string EmployeeName { get; set; }
    }

And my employee view model
public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }

    }

The use of AutoMapper
AutoMapper is designed within the web project. to form this more maintainable, create a folder (say Mappings) within the solution. Here we will produce 2 profile classes.  One for mapping from domain model object to look at model object and another one for reverse mapping.

public class DomainToViewModelMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "DomainToViewModelMappings"; }
        }
        protected override void Configure()
        {
            Mapper.CreateMap<Employee, EmployeeViewModel>();
        }
    }
public class ViewModelToDomainMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "ViewModelToDomainMappings"; }
        }
        protected override void Configure()
        {
            Mapper.CreateMap<EmployeeViewModel, Employee>();
        }
    }

Now create a configuration class within Mappings folder.
public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<DomainToViewModelMappingProfile>();
                x.AddProfile<ViewModelToDomainMappingProfile>();
            });
        }
    }

And then call this configuration from global.asax.
AutoMapperConfiguration.Configure();

And from the controller simply map the employeeObject (domain model object) to employeeViewModelObject (view model object).
var employeeViewModelObject = Mapper.Map<Employee, EmployeeViewModel>(employeeObject);

In advanced situation we will even customise the configuration. for instance we will map a specific property from source to destination.
Mapper.CreateMap<X, XViewModel>()
.ForMember(x => x.Property1, opt => opt.MapFrom(source => source.PropertyXYZ));

Automapper provides extremely an improved and straightforward way to map between objects.



ASP.NET MVC Hosting UK - HostForLIFE.eu :: Session Handling for Synchronous/Asynchronous Requests in ASP.NET MVC Hosting with jQuery

clock September 6, 2019 12:18 by author Peter

Basic use of session in ASP.NET MVC is as follows:

  • Check user is logged in or not
  • to carry authorization data of user logged in
  • to carry temporary alternative data
  • Check session Timeout on user action for every controller

Using asynchronous (AJAX) request it's a very common state of affairs to use jquery AJAX or unobtrusive AJAX API of ASP.NET MVC 5 to create asynchronous request in MVC 5. Each jquery AJAX and unobtrusive AJAX square measure very powerful to handle asynchronous mechanism. however in most things, we like better to use jquery AJAX to possess fine tuned control over the application. And currently suppose we wish to see the session timeout for every asynchronous call in our application. we are using JSON to grab an information on form and send it with asynchronous request. Therefore we dropped in situation where:

1. Normal direct won’t work well
RedirectToAction("LoginView", "LoginController");

2. We need to ascertain session timeout in action technique. A repetitive code in every action method therefore reduced code reusability and maintainability.

if (session.IsNewSession || Session["LoginUser"] == null) { //redirection logic 

We can use base controller class or take advantage of action filters of ASP.NET MVC 5. using base controller class and preponderant OnActionExecuting methodology of Controller class:
public class MyBaseController : Controller

{

    protected override void OnActionExecuting(ActionExecutingContext filterContext)

   {

        HttpSessionStateBase session = filterContext.HttpContext.Session;
        if (session.IsNewSession || Session["LoginUser"] == null)

        {

            filterContext.Result = Json("Session Timeout", "text/html");

        }

   }

}

And inheriting Base Class:

public class MyController : BaseController

{

//your action methods…

}

Limitation of this approach is that it covers up every action method.Using action filter attribute class of ASP.NET MVC 5. Therefore we will fine tune every controller action as needed.
      [AttributeUsage(AttributeTargets.Class |

    AttributeTargets.Method, Inherited = true, AllowMultiple = true)]

     public class SessionTimeoutFilterAttribute : ActionFilterAttribute

     {
   
       public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

       HttpSessionStateBase session = filterContext.HttpContext.Session;

        // If the browser session or authentication session has expired

        if (session.IsNewSession || Session["LoginUser"] == null)

        {

            if (filterContext.HttpContext.Request.IsAjaxRequest())

            {

                
JsonResult result = Json("SessionTimeout", "text/html");
                filterContext.Result = result;

            }

            else

            {

                // For round-trip requests,

               filterContext.Result = new RedirectToRouteResult(

                new RouteValueDictionary {

                { "Controller", "Accounts" },

                { "Action", "Login" }

                });

            }

        }

        base.OnActionExecuting(filterContext);

    }

}


Jquery code at client side

$.ajax({

    type: "POST",

    url: "controller/action",

    contentType: "application/json; charset=utf-8",

    dataType: "json",

    data: JSON.stringify(data),

    async: true,

    complete: function (xhr, status) {

            if (xhr.responseJSON == CONST_SESSIONTIMEOUT) {

                RedirectToLogin(true);

                return false;

            }

            if (status == 'error' || !xhr.responseText) {

                alert(xhr.statusText);

            }

       }

    });




About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in