Jul 3 2020

Blazor Controls Toolkit is out!

 Tree

Start with all comforts, save 70% of your development time: a few declarations are enough to generate the markup you need  and  the whole server interaction code: forget about input fields, the right input filed is generated automatically based on the property type and ViewModel attributes! Changes tracking, to compute changes for the server, query tools to query local and remote data (also server side query tools to power-up your API controllers are included) , advanced components that include grids, detail lists and trees. Basically all components can be Drag and Drop enabled, you don’t need to handle the Drag and Drop process, because you drag automatically the data that are bound to your markup!

Don’t worry about how to prevent the application you send to the client browser from being copied by hackers: you may rely on a double protection:

  1. Your code is protected by the best protector available on the market: Reactor, that is bundled with Blazor Controls Toolkit.
  2. Once Blazor Controls Toolkit is included as a dependency the whole application works properly only if it is validated by your server side Asp.net Core application with a complex cryptographic challenge. As a consequence your application is enabled to run properly only when it is connected with your web server!

Below more details about Blazor Controls Toolkit features, but you can try also all of them live:

  • The equivalent of all Bootstrap JavaScript components.
  • A complete set of input controls that includes all Html5 inputs or their fallback when they are not supported by user browser, dropdowns and autocompletes.
  • Validation attributes , and other metadata attributes that enable the developer to define how to render and edit data in a purely declarative way! You just put a generic edit or display component in your markup and the Blazor Controls Toolkit generate automatically for you the markup that implements the behavior declared with your model attributes: space to reserve for each field, the right Html5 input and / or auto-complete to use, and so on.
  • Default validation messages, and default button text/labels are already localized in various languages, and the develpèer can customize all of them. Moreover, each customer can require the localization kit to insert his language in the Blazor Controls Toolkit, in case it is not supported, yet. This demo application shows all localized default messages, and labels. However, with the only exception of this introduction page all other application-specific contents are not localized.
  • Changes tracking, tracking of invalid objects, and model transactions. All handled with uniform interfaces throghout all components. They prevent futher processing on invalid objects, enable the user to revert changes, and computes all changes to send to the server (additions, deletes and modifications).
  • Utility components, like modals, Tabs, pagers, and navigation tools
  • All components and html fragments can be drag-drop enabled, and bound to models. As a result of the drop operation list elements or grid rows are moved to different positions or modify the model bound to the drop target.
  • Behaviors that enrich existing Html element and other components with further features like collapsing, fading, input focus, visibility spy, anchor target spy.
  • Complex customizable components like DataGrids,TreeViews, Detail views, and Detail lists. Each component has its default row and column template that the developer can replace with custom ones.
  • Query tools for filtering, sorting, and aggregating data.These tools include components that enable the user to select the desired operations, attributes to declare how to build each filter view, and OData tools to translate the desired operations in OData format, to retrieve data from OData enabled servers, and to OData-enable your Asp.net controllers.
  • All components are accessible, and can be operated easily with just the keyboard. After each operation, the focus is moved where more appropriate for continuing keyboard processing. If possible accessibility is enforced also on developer provided custom templates

Tags: , ,

Oct 4 2017

Building Web applications with Knockout.js and ASP.NET core

Category: Asp.net | Asp.net core | MVC | TypeScript | WebApi | JavaScriptFrancesco @ 05:40

Amongst all the client side frameworks backed by big companies, React.js and Angular.js appear to be the most popular. However, Knockout.js still maintains a good market share, thanks to its interesting peculiarities.

Knockout is based on an MVVM paradigm similar to Angular.js, but unlike React.js. While it is adequate for modular complex applications, at the same time, it is very simple to mix with server side templating, similar to React.js, but unlike Angular.js….Read full article

Contact us if you want to learn more

aspnet-core-running-spa

Tags: , ,

Jun 26 2017

New 1.2.5 release of the Asp.net core Mvc Controls Toolkit

Category: Asp.net | Htnl5 fallback | MVCFrancesco @ 05:55

The new 1.2.5 release of the Asp.net core Mvc Controls Toolkit is ready for download. Play live with ajax sorting, filtering and grouping. Now, thanks to full ajax support, you may have several independent grids in the same page! Each grid may have an ajax “back button” to go back to its previous query.

Several Grid

Install in your project and follow Quickstart

Tags: ,

Jun 5 2017

New 1.2 release of the Asp.net core Mvc Controls Toolkit

Category: Htnl5 fallback | Asp.netFrancesco @ 23:38

The new 1.2 release of the Asp.net core Mvc Controls Toolkit is ready for download. Play live with sorting, filtering and grouping

Grouping

Install in your project and follow Quickstart

Tags: ,

May 7 2017

Asp.net core: Deserializing Json with Dependency Injection

Category: MVC | Asp.net core | Asp.netFrancesco @ 21:30

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

In a previous post I discussed how to model bind Interfaces/abstract classes with the help of Asp.net core dependency injection features. However, the technique discussed there doesn’t apply to Json data added to the request body, since request body is processed by the BodyModelBinder that, in turn, selects a formatter based on the request content-type header. The formatter for “application/json” is a wrapper for Json.net, so the code of our previous “interfaces model binder” is never called, and also if called it wouldn’t be able to process Json data in the request body.

The behavior of Json.net serializer/deserializer may be customized through an MvcJsonOptions options object.In this post I am going to show how to modify Json.net behavior so that it attempts to use Dependency Injection to create any .Net object before creating it through its constructor. This, will enable not only the deserialization of interfaces, but also the customization of object creation through Asp.net Core DI engine.

Preparing the project

As a first step let create a new asp.net core project named “JsonDI”:

Project

Select “no authentication” to simplify the code created by VS project template.

Then let create a new folder called “Models” and add it the following “IPerson.cs” file, that contains both an interface definition and its default implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JsonDI.Models
{
    public interface IPerson
    {
       string Name { get; set; }
       string Surname { get; set; }
    }
    public class DefaultPerson: IPerson
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

Now let modify the code of the Home controller to add an HttpPost for the Index action:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using JsonDI.Models;

namespace JsonDI.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index([FromBody] IPerson model)
        {
            return Json(model);
        }
        ....
        ....

We need an Ajax call to send Json data to our newly created HttpPost action method. Go to the Index.cshtml file in the Views/Home folder and substitute its code with the code below:

@{
    ViewData["Title"] = "Deserialization with DI";
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home">
    
    <button data-url="@Url.Action("Index", "Home")" type="button" class="test btn btn-default">Submit</button>
</form>
@section Scripts
{
    <script type="text/javascript">
        $(".test").click(function (evt) {
            var url = $(evt.target).attr("data-url");
            $.ajax(url,
                {
                type: 'POST',
                data: JSON.stringify({
                    name: "Francesco",
                    surname: "Abbruzzese"
                }),
                success: function () { alert("message received"); },
                contentType: "application/json",
                dataType: 'json'
            });
        });
    </script>
}

Now place a breakpoint here:

Breakpoint

…and run the project.

When we click the “Submit” button an Ajax request is issued to our HomeController that contains an IPerson interface in the request body. However, when the breakpoint is hit, we may verify that the model parameter is null! In fact Json.net is not able to deserialize the IPerson interface because it doesn’t know how to create an instance of it.

Enriching Asp.net Core Dependency Injection.

Pieces of code that need Asp.net Core Dependency Injection engine creates type instances do it through the IServiceProvider interface that contains the unique method “GetService(Type t)”. Accordingly, we may create a type instance calling GetService or some other extension method that, in turn, calls it, but we are not able to ask if a type has been registered with the DI engine. This problem may be solved using a third party DI engine, such as Autofac. In this section we will show how to add this capability without using third party DI engines.

Let add an “Extensions” folder to the project. We will place there all extensions we need to have Json.net use DI. As a first step let define an interface containing all features we need and that are not exposed by IServiceProvider:

using System;

namespace JsonDI.Extensions
{
    public interface IDIMeta
    {
        bool IsRegistred(Type t);
        Type RegistredTypeFor(Type t);
    }
}

I called it IDIMeta because it provides meta-information about the content of the the DI container. The first method returns if a type has been registered with the DI engine, and the second returns the type that will be actually created when requiring an instance of the registered type.

The actual implementation of the above interface uses the IServiceCollection available in the ConfigureServices method of the Startup.cs class to collect all information needed to implement the interface methods in a dictionary :

using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;

namespace JsonDI.Extensions
{
    public class DIMetaDefault: IDIMeta
    {
        IDictionary<Type, Type> register = new Dictionary<Type, Type>();
        public DIMetaDefault(IServiceCollection services)
        {
            foreach (var s in services)
            {
                register[s.ServiceType] = s.ImplementationType;
            }
        }
        public bool IsRegistred(Type t)
        {
            return register.ContainsKey(t);
        }

        public Type RegistredTypeFor(Type t)
        {
            return register[t];
        }
    }
}

As a final step we need to register IDIMeta itself in the DI engine, by adding the code below to the ConfigureServices method of the Startup.cs class:

services.TryAddSingleton<IDIMeta>(s =>
{
    return new DIMetaDefault(services);
});

Later on we will show the whole code to be added to the ConfigureServices method of the Startup.cs class.

Customizing Json.net behavior

Now we are ready to customize Json.net behavior! The way Json.net serializes/deserializes types is specified by ContractResolvers. ContractResolvers return a “contract” for each type that contains all information on how to deal with that type. In particular each contract specifies how to create an instance of the type and how to fill its properties. The way to fill type properties may be customized by passing a custom converter in the “Converter” property of the contract. However, we don’t need custom converters since we must customize just the way types are created.

Our custom ContractResolver inherits form the built-in “CamelCasePropertyNamesContractResolver” that is the one used as a default by Asp.net Core:

using System;
using Newtonsoft.Json.Serialization;

namespace JsonDI.Extensions
{
    public class DIContractResolver: CamelCasePropertyNamesContractResolver
    {
        IDIMeta diMeta;
        IServiceProvider sp;
        public DIContractResolver(IDIMeta diMeta, IServiceProvider sp)
        {
            this.diMeta = diMeta;
            this.sp = sp;
        }
        protected override JsonObjectContract CreateObjectContract(Type objectType)
        {

            if (diMeta.IsRegistred(objectType))
            {
                JsonObjectContract contract = DIResolveContract(objectType);
                contract.DefaultCreator = () => sp.GetService(objectType);

                return contract;
            }

            return base.CreateObjectContract(objectType);
        }
        private JsonObjectContract DIResolveContract(Type objectType)
        {
            var fType = diMeta.RegistredTypeFor(objectType);
            if (fType != null) return base.CreateObjectContract(fType);
            else return CreateObjectContract(objectType);
        }
    }
}

We override the CreateObjectContract method to modify the custom contract. If the type our ContractResolver has been invoked on is registered in the DI container we call DIResolveContract that, if available, returns a contract for the type that will be actually created by the DI engine. If no type is specified DIResolveContract falls back on a contract for the original type (which might have less properties than the actual type created). After that CreateObjectContract changes the contract DefaultCreator property to use DI.

Our ContractResolver needs both IServiceProvider and IDIMeta to do its job, so we passed them in its constructor.

Installing our DIContractResolver

Our DIContractResolver may be installed by configuring the MvcJsonOptions options object. In my previous posts of the custom model binding series I showed how to configure options by passing a lambda function to various extension methods in the ConfigureServices method of the Startup.cs class. We may also factor out the configuration code for each specific option object in a class by writing a class that inherits from IOption<MyOptionObject>:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace JsonDI.Extensions
{
    public class JsonOptionsSetup: IConfigureOptions<MvcJsonOptions>
    {
        IServiceProvider serviceProvider;
        public JsonOptionsSetup(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }
        public void Configure(MvcJsonOptions o)
        {
            o.SerializerSettings.ContractResolver =
                new DIContractResolver(serviceProvider.GetService<IDIMeta>(), serviceProvider);
        }
    }
}

After that, it is enough to call “services.AddTransient<IConfigureOptions<MvcJsonOptions>, JsonOptionsSetup>();” in the ConfigureServices method of the Startup.cs class. Summing up the whole code of the ConfigureServices method of the Startup.cs class is:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            
            services.AddTransient<IPerson, DefaultPerson>();
            services.TryAddSingleton<IDIMeta>(s =>
            {
                return new DIMetaDefault(services);
            });
            services.AddTransient<IConfigureOptions<MvcJsonOptions>, JsonOptionsSetup>();
        }

For the above to compile properly we need the “usings” below:

using JsonDI.Extensions;
using JsonDI.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

 

That’s all! Run the project, click the submit button and wait on our previous breakpoint. This time the IPerson model contains the right data sent by the client!

Stay Tuned!

Francesco

Tags: , , , ,

Apr 5 2017

Model binding interfaces: fixing server side validation

Category: Asp.net | Asp.net core | MVCFrancesco @ 20:55

 

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

This is a follow-up of my previous post on model binding interfaces, so please read it before going on with this post. I suppose also you have available the VS solution built in the previous post.

The problem

We use interfaces when we don’t want dependencies on how a “surface behavior” is implemented. As a matter of fact the same class may implement several interfaces and when we access it through one of these interfaces we want that each effect of the computation depends just on the way the interface is defined and not on the specific class peculiarities. In particular, we want that object validation performed through that interface depends only on the way the interface is defined.

That is why in my previous post I defined all validation attributes in the interface, instead of the interface implementation:

public interface ITestInterface
{
    [Range(1, 10)]
    int TestProperty { get; set; }
}

Unluckily, this doesn’t ensure model binder uses that validation rule. As a matter of fact the model binder has a “strange” behavior, namely if the interface is the root model received by the action method, it uses the validation attributes defined in the class that implements the interface,while if the interface is nested inside the root ViewModel received by the action method it do uses the validation attributes defined on the interface.

The reason of this behavior is quite simple: during validation the type of the root ViewModel is inferred by calling ‘GetType()’ on the model returned by the model binder, while the type of nested objects is inferred by the type of the property they are in.

About client side validation, it always uses the attributes defined in the interface.

 

In my previous post I suggested using the ‘ModelMetadataTypeAttribute’ to force usage of validation attributes defined in the interface:

[ModelMetadataType(typeof(ITestInterface))]
public class TestViewModel : ITestInterface
{
    public int TestProperty { get; set; }
}

Unluckily, this solution suffers of several problems:

  1. All validation attributes defined in the interfaces doesn’t substitute the ones defined in the class but they are simply added to them.
  2. A class may have just a single ‘ModelMetadataTypeAttribute’ so if a class implements several interfaces this technique can’t be used
  3. We cant make the class that implements the interface depends on peculiarities of the presentation layer since this would break separation of concerns between layers, thus adding the ‘ModelMetadataTypeAttribute’  just to solve a technical problem we have in the presentation layer is not a good practice.

Therefore, we are forced to modify the default behavior of the built-in validation system.

The solution

In all previous versions of Asp.net Mvc validation were performed during the model-binding recursive steps. In asp.net core, validation is performed after model binding has returned an objects tree, with a recursive visit of the whole tree. This way, the same validation process may be applied also to models that have been built by formatters (such as, for instance, the Json formatter that processes Json objects). Namely, as soon as model binding returns an objects tree an implementation of the “IObjectModelValidator” interface is retrieved through dependency injection and its “Validate” model is called passing it the model returned by the model binder and other parameters we will analyze later on in this section.

The “IObjectModelValidator” default implementation performs some preparation steps, then calls GetTipe on the model passed to its Validate method to get the root type to validate, and finally it calls a recursive visitor that traverses the whole tree for validation.

We need to substitute the default implementation with an implementation that instead of calling GetType to get the root type uses the type declared in the action method. This way instead of validating the interface implementation we might validate the interface. No modification is needed to the recursive visitor since it doesn’t use GetType but the types declared in the type properties.

Unluckily the “Validate” method is not passed the type declared in the action method but just the overall ActionContext.

The method below is able to extract the type declared in the action method from the model type extracted with GetType, the ActionContext, and initial prefix passed to the validate method. This initial prefix is either the empty string or the name of the parameter of the action method that is being processed (more details on this, later on):

private Type referenceType(string prefix, Type modelType, ActionContext actionContext)
{
    var parameterDescriptors = actionContext.ActionDescriptor.Parameters;
    ParameterDescriptor parameter;
    if (string.IsNullOrWhiteSpace(prefix))
        parameter = parameterDescriptors
            .Where(m => m.ParameterType.GetTypeInfo().IsAssignableFrom(modelType))
            .FirstOrDefault();
    else
    {
        parameter = parameterDescriptors
            .Where(m => m.Name == prefix && m.ParameterType.GetTypeInfo().IsAssignableFrom(modelType))
            .FirstOrDefault();
    }
    if (parameter != null && parameter.ParameterType.GetTypeInfo().IsInterface)
        return parameter.ParameterType;
    else return modelType;
}

We look for the parameter we need the type of in the list of all parameter descriptors.If the initial prefix is the empty string we don’t have the name of the parameter we are looking the type of, so we try to find it through the type of the model (model type must be “assignable” to the parameter type), otherwise we try a match for both name and type.

Finally if the parameter is an interface we use its type otherwise we revert to the default behavior an use the model type obtained with GetType.

The whole code of our custom implementation is :

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System.Linq;
using System.Reflection;

namespace ModelBindingInterfaces.Validation
{
    public class EnhancedObjectValidator: IObjectModelValidator
    {
        private readonly IModelMetadataProvider _modelMetadataProvider;
        private readonly ValidatorCache _validatorCache;
        private readonly IModelValidatorProvider _validatorProvider;


        public EnhancedObjectValidator(
            IModelMetadataProvider modelMetadataProvider,
            IList<IModelValidatorProvider> validatorProviders)
        {
            if (modelMetadataProvider == null)
            {
                throw new ArgumentNullException(nameof(modelMetadataProvider));
            }

            if (validatorProviders == null)
            {
                throw new ArgumentNullException(nameof(validatorProviders));
            }

            _modelMetadataProvider = modelMetadataProvider;
            _validatorCache = new ValidatorCache();

            _validatorProvider = new CompositeModelValidatorProvider(validatorProviders);
        }

        private Type referenceType(string prefix, Type modelType, ActionContext actionContext)
        {
            var parameterDescriptors = actionContext.ActionDescriptor.Parameters;
            ParameterDescriptor parameter;
            if (string.IsNullOrWhiteSpace(prefix))
                parameter = parameterDescriptors
                    .Where(m => m.ParameterType
                        .GetTypeInfo().IsAssignableFrom(modelType))
                    .FirstOrDefault();
            else
            {
                parameter = parameterDescriptors
                    .Where(m => m.Name == prefix && m.ParameterType.GetTypeInfo()
                        .IsAssignableFrom(modelType))
                    .FirstOrDefault();
            }
            if (parameter != null && parameter.ParameterType.GetTypeInfo().IsInterface)
                return parameter.ParameterType;
            else return modelType;
        }
        public void Validate(
            ActionContext actionContext,
            ValidationStateDictionary validationState,
            string prefix,
            object model)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            var visitor = new ValidationVisitor(
                actionContext,
                _validatorProvider,
                _validatorCache,
                _modelMetadataProvider,
                validationState);

            var metadata = model == null ? null :
                _modelMetadataProvider
                    .GetMetadataForType(referenceType(prefix, model.GetType(),
                        actionContext));
            visitor.Validate(metadata, prefix, model);
        }
    }
}

Our custom implementation may be installed easily in the DI section of our project Startup.cs.

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddTransient<ITestInterface, TestViewModel>();

            services.AddMvc(o =>
            {
                o.ModelBinderProviders.Insert(0,
                    new ModelBinders.InterfacesModelBinderProvider());
            });
            services.TryAddSingleton<IObjectModelValidator>(s =>
            {
                var options = s.GetRequiredService<IOptions<MvcOptions>>().Value;
                var metadataProvider = s.GetRequiredService<IModelMetadataProvider>();
                return new EnhancedObjectValidator(metadataProvider,
                    options.ModelValidatorProviders);
            });
        }

We use the possibility offered by DI to get an instance through a Lambda, since, in the constructor of our implementation, we need the current model metadata provider that is contained in the MvcOptions object.

Proof of correctness of parameter type extraction algorithm

If you are not interested in the details of why the parameter extraction algorithm I propose always works, that is,why  it never guesses the wrong parameter you may jump this section.

In case the algorithm receives the exact parameter name, no error is possible, but what happens when it receives the empty string? There might be several parameters that are assignable from the model type, how are we sure to select the right one?

The answer is very simple: when when the algorithm receives the empty string there can’t be several parameters compatible with the model type! In fact, we receives the empty string instead of the parameter name when the name of the action method parameter is not used as a prefix in the name of any input field submitted. In fact the model binder always attempts matching field names with and without the parameter names as prefixes. Usually, we don’t add the parameter name prefix to the field names when the action method has an unique parameter, but this is not compulsory.

However, for sure, when we omit parameter names in field names we can’t have several parameters whose types share properties with the same names, otherwise the model binding process would be ambiguous. Therefore, when parameter names do not prefix field names we can’t have several parameters compatible with the same type (otherwise the properties of the model compatible with both parameters would create ambiguities).

Cautions!

Our algorithm guesses the right correctly interface type when the model binding process is invoked directly by the framework during action method parameters instantiation. However, it doesn’t work if you invoke manually model binding by calling helper functions like “TryUpdateModelAsync” from within an action method, so please, in this case do not use interfaces as parameter types.

Moreover, pay attention when using Interfaces! Validation attributes defined on interfaces are not inherited by derived interfaces or classes implementing them, since interfaces are just prescriptions and can’t furnish any “code” to the types that implement them.

 

That’s all for now

Stay tuned!

Francesco

Tags: , ,

Mar 17 2017

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

Category: MVC | Asp.net core | Asp.netFrancesco @ 01:53


Custom Model Binding in Asp.net Core Mvc, 1

Custom Model Binding in Asp.net Core, 2: Getting Time + Client Time Zone Offset

Model binding interfaces: fixing server side validation

Asp.net core: Deserializing Json with Dependency Injection

 

In this last post of the model binding series I will discuss model binders that are not specific for a single type. That is, model binders able to handle generic types, and/or categories of types. Typical examples of these model binders are the built-in model binders for all complex types, all IEnumerables, and all dictionaries. If we give a look at all these model binders, we see that they recursively call the binding process itself to bind child elements and/or properties. They do this after having created a child binding context with a call to bindingContext.EnterNestedScope that loads the newly created child binding context in the same bindingContext variable. The call is enclosed within an using block, so that the original bindingContext is restored after exiting the block.

As an example we will build a custom model binder for interfaces, that is, a model binder that binds interfaces by looking for a an implementation in the Asp.net core Dependency Injection framework, and then by calling back the binding process itself on that implementation. Interfaces model binding is not only a good example of recursive model binding but also an useful programming tool for the following reasons:

  1. Using interfaces instead of concrete ViewModels allows a better separation between business layer and user interface layer.
  2. ViewModels inheritance allows a better reuse of views and metadata (validation attributes, DisplayAttributes, etc.), and interfaces overcome the limitation of inheriting from a single father class, since each interface may inherit from multiple other interfaces.

Asp.net core Mvc already has a model binder that is able to inject objects from the Dependency Injection engine into action methods. Its usage is triggered by the FromServicesAttribute, and it just injects object instances as they are returned by the DI engine without binding their properties to the input received by the client. Our custom model binder, instead, will be invoked only on interfaces or abstract classes and only when no FromServicesAttribute is provided. Moreover, once invoked it will bind all interface/abstract class properties against the input received by the client.

Preparing the project

As a first step let create a new asp.net core project named “ModelBindingInterfaces” and let select “no authentication”. Then let create a new folder called “ViewModels”.

Now let add an Interface called “ITestInterface”  to this folder :

using System.ComponentModel.DataAnnotations;

namespace ModelBindingInterfaces.ViewModels
{
    public interface ITestInterface
    {
        [Range(1, 10)]
        int TestProperty { get; set; }
    }
}

and a class implementing this interface, called “TestViewModel”:

using Microsoft.AspNetCore.Mvc;

namespace ModelBindingInterfaces.ViewModels
{
    [ModelMetadataType(typeof(ITestInterface))]
    public class TestViewModel : ITestInterface
    {
        public int TestProperty { get; set; }
    }
}

All metadata are added to the interface, so, to be sure they are used also by its implementation, we define the interface as a “ModelMetaDataType” for its implementation.

Now let register the above pair in the dependency injection engine, by adding the last line of the code below to the “startup.cs” file:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddTransient<ITestInterface, TestViewModel>();

Finally, we need a controller and a test view. Let modify the “Index” action method of the HomeController in “HomeController.cs” as follows:

public IActionResult Index()
{
    return View();
}
[HttpPost]
public IActionResult Index(ITestInterface model)
{
    return View(model);
}

 

And also its “Views\Home\Index.cshtml” associated view:

@model ModelBindingInterfaces.ViewModels.ITestInterface

@{
    ViewData["Title"] = "Model Binding Interfaces";
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home">
    <div class="form-group">
        <label asp-for="TestProperty" class="control-label"></label>
        <input asp-for="TestProperty" class="form-control">
        <span asp-validation-for="TestProperty" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

 

As you can see both controller and view reference only the interface. The only chunk of code that mentions its actual implementation is the DI container definition.

If you run the project as it is now, and try to submit the Index form, you get the following error:

“ModelBindingInterfaces.ViewModels.ITestInterface' does not have a default constructor”

In fact, all default model binders are not able to create automatically an instance of the  “ITestInterface'” interface.

Implementing the custom model binder

Our model binder should perform a job similar to the one of the built-in ComplexTypeModelBinder. The only difference being that instead of attempting to create an interface it should invoke the the DI engine to get an instance of a class that implements the interface. The code of the ComplexTypeModelBinder is quite complex, but its kernel is the invocation of “bindingContext.EnterNestedScope” on each type property. EnterNestedScope is passed an updated "ModelName" obtained by appending ".<property name>" to the current ModelName. ModelName is used to retrieve data from the input received by the client once a leaf property is reached, as we have seen in the previous post of this series. Inside the using block associated to EnterNestedScope there is a call to the “BindProperty” method, that in turn, retrieves the right binder for the property by looking in the dictionary of all property binders that is passed in the ComplexTypeModelBinder constructor. Once the right binder is found it is invoked on the child binding context created by “bindingContext.EnterNestedScope”. The result is finally stored in a variable defined outside the using block.

All results returned by the recursive calls on all  properties are then used to populate an instance of the type created by the “CreateModel” method.

We need just to modify “CreateModel” so that it uses the DI engine to get an instance of the type. Thus, we may inherit from the ComplexTypeModelBinder  and override its CreateModel method.

Let add the new “ModelBinders” folder to our project, and then add our “InterfacesModelBinder” class to this folder:

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace ModelBindingInterfaces.ModelBinders
{
    public class InterfacesModelBinder : ComplexTypeModelBinder
    {

        public InterfacesModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinder)
            : base(propertyBinder)
        {

        }
        protected override object CreateModel(ModelBindingContext bindingContext)
        {
            return bindingContext.HttpContext
                .RequestServices.GetService(bindingContext.ModelType);
        }
    }
}

 

Implementing the provider

In the previous post of the series we have seen that model binders are selected and created by model binder providers, so now it is time to write a provider for our custom model binder. Before start coding we need an answer to two questions:

  1. When the provider must return a not null result, meaning when we are in the right situation when our custom model binder must be used.
  2. Which parameters to pass in the constructor of the model binder.

The right conditions for using our “InterfacesModelBinder” are:

  • we are going to bind either an interface or an abstract class
  • the interface is not an IEnumerable, otherwise the built-in CollectionModelBinder/DictionaryModelBinder would be more appropriate
  • no FromServicesAttribute is in place, since this attribute is used when the user needs just the injection of a type with no subsequent binding of the type against the input provided by the client.

Finally, the constructor of our “InterfacesModelBinder” needs a dictionary whose entries associate the right binder to each type property.

Now we have all information to add our InterfacesModelBinderProvider class to the ModelBinders folder:

using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace ModelBindingInterfaces.ModelBinders
{
    public class InterfacesModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!context.Metadata.IsCollectionType &&
                (context.Metadata.ModelType.GetTypeInfo().IsInterface ||
                 context.Metadata.ModelType.GetTypeInfo().IsAbstract)  &&
                (context.BindingInfo.BindingSource == null ||
                !context.BindingInfo.BindingSource
                .CanAcceptDataFrom(BindingSource.Services)))
            {
                var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
                for (var i = 0; i < context.Metadata.Properties.Count; i++)
                {
                    var property = context.Metadata.Properties[i];
                    propertyBinders.Add(property, context.CreateBinder(property));
                }
                return new InterfacesModelBinder(propertyBinders);
            }

            return null;
        }
    }
}

The metadata of each property are taken from the MetaData.Properties array contained in the context object passed to the GetBinder method of the provider. Then, a binder for the property is created by invoking the CreateBinder method of the same context object on the property metadata.The remainder of the code is self-explicative.

The provider is installed with the same procedure of our previous post. Go to the startup.cs file and modify the ConfigureServices method as shown below:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddTransient<ITestInterface, TestViewModel>();
            services.AddMvc(o =>
            {
                o.ModelBinderProviders.Insert(0,
                    new ModelBinders.InterfacesModelBinderProvider());
            });

As in our previous post, our provider is inserted at the top of the list of all providers to avoid that some other built-in provider might return a different model binder also when all conditions for the application of our InterfacesModelBinder are satisfied.

We have Finished! Run the project and verify how the interface is bound properly, and also how validation errors work properly.

Our series on model binding ended

but stay tuned!

We are preparing new enjoying adventures!

Francesco

Tags: , ,

Feb 22 2017

Custom Model Binding in Asp.net Core, 2: Getting Time + Client Time Zone Offset

Category: MVC | Asp.net core | Asp.netFrancesco @ 05:51


Custom Model Binding in Asp.net Core Mvc, 1

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

The second post of the “Custom Model Binding” series is dedicated to “fixed representation” complex types, that is to types that for some reason cannot be handled as “simple types” but that are rendered with some pre-defined input fields. For a general discussion, on Custom Model Binding, please refer to the first post of the series. As an example of the general technique we will design and install a custom model binder for the DateTimeOffset .Net type. The DateTimeOffset is a generalization of the Datetime that contains also the Time Zone offset associated to the DateTime value. We can’t use the simple technique described in the first post of the series for two reasons:

  1. The DateTimeOffset is a system type so we can’t apply a custom TypeConverterAttribute to its definition.
  2. We need the DateTime and Time Zone offset be rendered into separate fields so that the user may edit date and time with a datetime-local Html5 input type. The Time Zone offset part will be stored in an hidden input field that will be handled automatically by some JavaScript. The hidden field must be updated each time the datetime-local input value changes because the Time Zone Offset is not constant but depends on the selected date (Daylight saving time on/off). On the server side we need a custom model binder that is able to combine both inputs into a DateTimeOffset instance.

More specifically, a DateTimeOffset that is rendered and then posted to the server again passes through the following transformations:

  1. DateTime and Time Zone offset are rendered in the two dedicated input fields described above.
  2. Once on the client side some JavaScript converts the DateTime/Time Zone offset pair into the client time zone, so that user may edit it in a datetime-local input field (we suppose the browser supports datetime-local)
  3. Each time the user changes the datetime value the associated Time Offset field is updated by some JavaScript
  4. Once the form is posted a custom model binder combines both the DateTime and the client Time Zone Offset into an unique DateTimeOffset.
  5. During the business processing the DateTimeOffset may be converted in other Time Zones, and possibly is rendered again, thus returning to step 1.

Summing up we need:

  • A custom TagHelper to render DateTimeOffset into the 2 input fields format described above
  • Some JavaScript for the conversion in the client Time Zone, and for updating automatically the hidden field
  • A Custom Model for DateTimeOffset types
  • Some wire up code to “connect” our custom model binder.

The above steps are a kind of standard, since custom model binders are always designed together with their compatible rendering counterparts.

A Custom TagHelper for DateTimeOffset

As a first step let create a new asp.net core project named “FixedRepresentationModelBinding” and let select “no authentication”.

Then create a new Folder called “TagHelpers”, and add a new DateTimeOffsetInputTagHelper class.

Our TagHelper should execute before the Asp.net Mvc standard input  TagHelper and should intercept all DateTimeOffset rendering:

 

using System;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace FixedRepresentationModelBinding.TagHelpers
{
    [HtmlTargetElement("input", Attributes = ForAttributeName,
        TagStructure = TagStructure.WithoutEndTag)]
    public class DateTimeOffsetInputTagHelper : TagHelper
    {
        public override int Order
        {
            get
            {
                return int.MinValue;
            }
        }
        private const string ForAttributeName = "asp-for";
        [HtmlAttributeName("type")]
        public string InputTypeName { get; set; }
        [HtmlAttributeName("value")]
        public string Value { get; set; }

        [HtmlAttributeName(ForAttributeName)]
        public ModelExpression For { get; set; }

        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if(For.Metadata.UnderlyingOrModelType == typeof(DateTimeOffset))
            {
                var fullName = ViewContext.ViewData
                    .TemplateInfo.GetFullHtmlFieldName(For.Name);
                var dvalue = (DateTimeOffset?)For.Model;
                var offset = dvalue.HasValue ?
                    Convert.ToInt32(dvalue.Value.Offset.TotalMinutes) :
                    0;
                if (String.IsNullOrEmpty(InputTypeName))
                    InputTypeName = "datetime-local";
                if (!output.Attributes.ContainsName("type"))
                    output.Attributes.Add("type", InputTypeName);

                if (String.IsNullOrEmpty(Value))
                {
                    Value= dvalue.HasValue ?
                        string.Format("{0:00}-{1:00}-{2:00}T{3:00}:{4:00}:{5:00}",
                        dvalue.Value.Year, dvalue.Value.Month, dvalue.Value.Day,
                        dvalue.Value.Hour, dvalue.Value.Minute, dvalue.Value.Second) :
                        string.Empty;
                }
                if (!output.Attributes.ContainsName("value"))
                    output.Attributes.Add("value", Value);
                output.Attributes.Add("data-has-offset", "true");

                fullName = fullName.Length > 0 ? fullName + ".O" : "O";
                output.PostElement.AppendHtml("<input name='" +
                    fullName + "' type='hidden' value='"+offset+"' />");
            }
        }
    }
}

The Order property returning int.MinValue ensures that out TagHelper is the first to be executed.

The InputTypeName property is filled with the   input “type” if any is specified. If no type is specified it is automatically set to “datetime-local” and copied into the output attributes dictionary

Similarly, if no input “value” is specified, value is taken from the model contained in the For property, serialized with the yyyy-MM-ddTHH:mm:ss format (the format required by a datetime-local input field) and copied to the output dictionary.

The input field itself is not rendered by our TagHelper since its rendering is left to the standard input TagHelper that is executed immediately after our custom TagHelper. However,

the standard TagHelper will use the value and type we have set in the output attributes.

We add the attribute “data-has-offset=’true’” to the output attributes in order to retrieve all DateTimeOffset/rendering input fields from JavaScript.

The last instruction adds further Html to the Html rendered by the standard TagHelper, with the help of PostElement.AppendHtml. This way we add the input type hidden containing the Time Zone offset. The offset is expressed in minutes, since some time zones have an hours+minutes format. Finally, hidden input name is the same as the main input name but with a “.O” postfix.

For more information about custom TagHelpers, please refer to the official documentation.

Now we need to register all TagHelpers contained in the web site dll. Open the _ViewImports.cshtml file contained in the Views folder and add the following line:

@addTagHelper *, FixedRepresentationModelBinding

Now we can test our TagHelper.

Go to “Views\Home\Index.cshtm” and replace the whole content with:

@model Nullable<DateTimeOffset>

@{
    ViewData["Title"] = "Fixed representation Model Binding Test";
    var datetimeTest = Model;
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home">
    <div class="form-group">
        <label asp-for="@datetimeTest">Local date/time:</label>
        <input asp-for="@datetimeTest" class="form-control">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

Model must be assigned to the variable datetimeTest otherwise the input field would have empty name and id.

This problem arises because in our very simple test the DateTimeOffset struct is not a property of a bigger model. With our trick the input field is named “datetimeTest” that must match the name of the parameter of the Home controller Index method, that we are going to substitute in the Home controller:

public IActionResult Index(DateTimeOffset? datetimeTest)
        {
            //datetimeTest = new DateTimeOffset(2000, 12, 2, 20, 0, 0,
            //    new TimeSpan(0, 5, 0, 0));
            return View(datetimeTest);
        }

In order to verify that our TagHelper is actually able to render a DateTimeOffset just un-comment the commented lines and run the project. If the selected browser supports datetime-local Httml5 inputs you should see a well formatted date+time. Moreover, looking at the Html sources the hidden input should contain 300 (5 hours times 60 minutes)

If everything is ok, comment again the un-commented lines.

Now is time to add the needed JavaScript. For simplicity, we may add it with an in-line script:

@section scripts{
    <script type="text/javascript">
        (function ($) {
            function dateFromISO8601(isoDateString) {
                var parts = isoDateString.match(/\d+/g);
                var isoTime = Date.UTC(parts[0], parts[1] - 1,
                    parts[2], parts[3], parts[4], parts[5]);
                var isoDate = new Date(isoTime);
                return isoDate;
            }
            function localDateFromISO8601(isoDateString) {
                var parts = isoDateString.match(/\d+/g);
                var isoDate = new Date(parts[0], parts[1] - 1,
                    parts[2], parts[3] || 0, parts[4] || 0, parts[5] || 0);
                

                return isoDate;
            }
            $("[data-has-offset]").each(function () {
                var jThis = $(this);
                var val = $.trim(jThis.val())
                var date = val ? dateFromISO8601(val) : null;
                //now we date have UTC + Server offset
                //since val is interpreted as UTC date but is not
                if (date) {
                    var offset = parseInt(this.nextElementSibling.value);
                    
                    date = new Date(date.getTime()
                        - offset * 1000 * 60);
                    //after subtracting server offset we have right date
                    var clientOffset = -date.getTimezoneOffset();
                    //we change sign because getTimezoneOffset returns UTC-local time
                    //while we need local time - UTC
                    this.nextElementSibling.value = clientOffset;
                    date = new Date(date.getTime()
                        + clientOffset * 1000 * 60);
                    //We add client offset because toISOString
                    //serialize UTD date not local date so we need to increase
                    //UTC date + clientOffset
                    jThis.val(date.toISOString().substr(0, 19));
                }
            })
            .change(function(evt){
                var target=evt.target;
                var val = target.value.trim();
                if (val) {
                    target.nextElementSibling.value =
                       -localDateFromISO8601(val).getTimezoneOffset();
                    //We must call localDateFromISO8601 because date is in local time
                    
                }
            });
        })(jQuery)
    </script>
}

We select all input fields with the “data-has-offset” attribute, that are the ones to process. First of all we convert the DateTime/Time-Zone-Offset pairs into the client time zone. Dates math is done by converting everything in milliseconds: the date with get Time, and the offset by multiplying it times 60*1000. Then we apply a change event handler to all selected inputs, in order to update the Time Zone offset each time the date+time changes.

A Custom Model Binder for DateTimeOffset

Custom model binders for “fixed representations” usually mimic the standard Mvc SimpleTypeModelBinder, the only difference being that the SimpleTypeModelBinder processes just one input field while “fixed representations” model binders process several input fields. As you can see in the source code the SimpleTypeModelBinder uses TypeConverters to deserialize types; for our simple model binder, instead, a DateTime and an integer parsers will be enough.

Let add a new “ModelBinding” folder and create a DateTimeOffsetModelBinder class. Our model binder must implement the interface IModelBinder that contains the single method BindModelAsync:

using System;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace FixedRepresentationModelBinding.ModelBinding
{
    public class DateTimeOffsetModelBinder: IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);
            var auxValueProviderResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName+".O");
            if (valueProviderResult == ValueProviderResult.None ||
                auxValueProviderResult == ValueProviderResult.None)
            {
                // no entry found for some of the two needed input fields
                //return without setting result, that is, return a failure
                return TaskCache.CompletedTask;
            }
            //store value retrieved for Date+Time in model state
            //this way, in case of format errors user may
            //correct input. No need to store also time zone offset,
            //since it cannot be edited by the user
            bindingContext.ModelState
                .SetModelValue(bindingContext.ModelName, valueProviderResult);

            try
            {
                var value = valueProviderResult.FirstValue;
                var auxValue = auxValueProviderResult.FirstValue;
                object model;
                if (string.IsNullOrWhiteSpace(value) ||
                    string.IsNullOrWhiteSpace(auxValue))
                {
                    //empty fields, means null model
                    model = null;
                }
                else
                {
                    int offset = int.Parse(auxValue, CultureInfo.InvariantCulture);
                    DateTime dt = DateTime.Parse(value, CultureInfo.InvariantCulture);
                    model = new DateTimeOffset(dt, new TimeSpan(0, offset, 0));
                }
                //if model is null and type is not nullable
                //return a required field error
                if (model == null &&
                    !bindingContext.ModelMetadata
                        .IsReferenceOrNullableType)
                {
                    bindingContext.ModelState.TryAddModelError(
                        bindingContext.ModelName,
                        bindingContext.ModelMetadata
                        .ModelBindingMessageProvider.ValueMustNotBeNullAccessor(
                            valueProviderResult.ToString()));

                    return TaskCache.CompletedTask;
                }
                else
                {
                    bindingContext.Result =
                        ModelBindingResult.Success(model);
                    return TaskCache.CompletedTask;
                }
            }
            catch (Exception exception)
            {
                //in case parsers throw a FormatException
                //add error to the model state.

                bindingContext.ModelState.TryAddModelError(
                    bindingContext.ModelName,
                    exception,
                    bindingContext.ModelMetadata);

                
                return TaskCache.CompletedTask;
            }
        }
    }
}

As a first step we use the value provider passed in the bindingContext to get the string values of our two input fields. If provided we use them to build a DateTimeOffset structure with the help of DateTime and int parse methods. In case of errors an error message is added to the ModelState. If the model binder returns TaskCache.CompleteTask without setting bindingContext.Result the framework assumes that model binding failed.

Installing Our Model Binder

There are various options to inform the framework on when to use our model binder:

  1. Decorate a ViewModel property or an Action Method parameter with a ModelBinderAttribute specifying the type of our model binder. In this case just that property or parameter will be bound with our model binder.
  2. Decorate the class or struct to bind with our model binder with the ModelBinderAttribute. In this case the model binder is used for each occurrence of the target type. Unluckily, we can’t follow this path since DateTimeOffset is a system type, so we can’t apply any attribute to it.
  3. Installing the model binder in the standard model binding pipeline. Also in this case the model binder is used for each occurrence of our target type.

Since we want our model binder be used on each occurrence of DateTimeOffset structures, and since option 2 is not viable we are forced to adopt option 3. Since in option 3 the model binder is not attached to any type or property we must instruct explicitly the standard model binding pipeline on when to use our model binder. This is done by defining an implementation of the IModelBinderProvider interface that exposes the single GetBinder method. Let call DateTimeOffsetModelBinderProvider our implementation, and place it in the already defined “ModelBinding” folder:

using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace FixedRepresentationModelBinding.ModelBinding
{
    public class DateTimeOffsetModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Metadata.UnderlyingOrModelType == typeof(DateTimeOffset))
            {
                return new DateTimeOffsetModelBinder();
            }

            return null;
        }
    }
}

The implementation is straightforward, if the current type to bind is either a DateTimeOffset or a DateTimeOffset? our provider returns an instance of our model binder, otherwise it returns null. A null result informs the model binding pipeline to try the next IModelBinderProvider implementation.

In fact all installed IModelBinderProvider implementations are placed into an IList contained in the ModelBinderProviders property of the MvcOptions object. Accordingly, we may have our model binder working by adding its associated provider to this IList.

The MvcOptions default object may be modified in several ways, The easiest way being to substitute:

services.AddMvc()

in the Startup.cs class, with:

services.AddMvc(o =>
{
    o.ModelBinderProviders.Insert(0, new DateTimeOffsetModelBinderProvider());
});

 

 

We added our provider on top of the list so it is tried first, to avoid that some other “standard” provider might select a different model binder.

Done!

Run the application, and when the home page appears, place a breakpoint in the Index method of Home controller that will receive our submitted data. Now select select a date+time, submit and verify what is received by the Index method: a DateTimeOffset containing the date and time selected in the browser, an the right client Time Zone offset!

That’s all for now

In a short time the last episode of our series: model binding interfaces!

Stay tuned!

Francesco

Tags: , ,

Jan 29 2017

Custom Model Binding in Asp.net Core Mvc, 1

Category: Asp.net core | Asp.net | MVCFrancesco @ 06:48


Custom Model Binding in Asp.net Core, 2: Getting Time + Client Time Zone Offset

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

This is the first of a series of 3 posts on how to write custom model binders in Asp.net core Mvc. Three posts on three different ways to customize model binding in three different scenarios.

The concept of “simple type” plays a key role in model binding. A Simple type is not just a string, numbers, dates, or any other.net basic type but any type we decide to render as a string in a single input field. Below three examples of types that’s worth to render as “simple types”:

  1. An YouTube Url type, that contains the id of the you tube Url, but is rendered as an actual Url according to some format settings (it might implement IFormattable, for instance), and that “Model Binds” any correct YouTube Url.
  2. A Month type that contains month and year information and that is rendered in Month ISO format (YYYY-MM) into an HTML5 Month input.
  3. A Week type that contains week and year information and that is rendered in Week ISO format (YYYY-Www)  into an HTML5 Week input.

However, we may represent as “simple types” arbitrarily complex data structures by converting them from/to single strings in JSON format. Thus, they are “simple” just because they fit an a single input field.

Types that are not simple are “complex”. In turns, complex types may be split into 2 categories: fixed representation types, and variable representation types. Fixed representation types are rendered with a constant number of input fields whose names do not depend on the value of each instance. Roughly, they are always rendered with the “same input fields”.

For instance, we may represent the Month type mentioned above also as a fixed representation complex type using an input field for the year and another input field for the month.

IEnumerables and generic types must be considered variable representation types if their properties are rendered in different input fields. However, they may always be worked as simple types by using a single input field and JSON serialization.

Simple types, fixed representation types and variable representation types need different model binding techniques.

Variable representation types are the more difficult to deal with and will be analyzed in the last post of the series, since, in general, they require the model binder be invoked recursively to bind their sub-parts.

Simple types are the easier to model bind since it is enough to specify how they must be serialized and de-serialized. The remainder of this post is dedicated to them. We use the Month type example.

As a first step let create a new asp.net core project named “SimpleModelBinding” and let select “no authentication”.

Then create a new Folder called “Types”, and add a new Month structure:

public struct Month
{
    public uint YearNumber { get; private set; }
    public uint MonthNumber { get; private set; }
   

    public Month(uint yearNumber, uint monthNumber)
    {
        YearNumber = yearNumber;
        MonthNumber = monthNumber;
        if (MonthNumber < 1 || MonthNumber > 12) throw new FormatException();
        if (yearNumber < 1) throw new FormatException();
    }
    public static Month MinValue { get { return new Month(1, 1); } }
    public static Month MaxValue { get { return new Month(9999, 12); } }
}
Add conversion to/from DateTime:
public DateTime ToDateTime()
{
    return new DateTime((int)YearNumber, (int)MonthNumber, 1);
}

public static Month FromDateTime(DateTime t)
{
    return new Month((uint)t.Year, (uint)t.Month);
}

public static implicit operator Month(DateTime t)
{
    return FromDateTime(t);
}

public static implicit operator DateTime(Month m)
{
    return m.ToDateTime();
}

Finally add also ToString and Parse methods:

public override string ToString()
{
    return string.Format("{0:0000}-{1:00}", YearNumber, MonthNumber);
}

public static Month Parse(string s)
{
    return FromDateTime(DateTime.Parse(s));
}

public static bool TryParse(string s, out Month m)
{
    DateTime dt;
    var res = DateTime.TryParse(s, out dt);
    if (res) m = FromDateTime(dt);
    else m = new Month(1, 1);
    return res;
}

Add month and year may be useful too:

public Month AddMonths(int months)
{
    if (months == 0) return this;
    months = (int)MonthNumber + months;
    var years = months / 12;
    months = months % 12;
    if (months < 0)
    {
        months += 12;
        years--;
    }
    return new Month((uint)(years + YearNumber), (uint)(months));

}
public Month AddYears(int years)
{
    return new Month((uint)(YearNumber + years),
        MonthNumber);
}

If you want you may also define all comparison operators.

Since we already have adequate parsing and ToString methods we are very close to our goal.

We need just to inform Asp-net core Mvc model binding engine on which functions to call to serialize/de-serialize the Month type. This, doesn’t require the definition of a custom model binder but the definition of a TypeConverter that is able to convert between Month and string. In fact, Asp-net core Mvc model binding engine assumes that a type is “simple” exactly when a similar TypeConverter exists.

Let add a new class called MonthTypeConverter to our Types folder:

using System;
using System.ComponentModel;
using System.Globalization;

namespace SimpleModelBinding.Types
{
    public class MonthTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(
            ITypeDescriptorContext context,
            Type sourceType)
        {
            return sourceType == typeof(string) ||
                sourceType == typeof(DateTime);
        }
        public override object ConvertFrom(ITypeDescriptorContext context,
            CultureInfo culture, object value)
        {
            return value is string ? Month.Parse(value as string) :
                Month.FromDateTime((DateTime)value);
        }
        public override bool CanConvertTo(ITypeDescriptorContext context,
            Type destinationType)
        {
            return destinationType == typeof(string) ||
                destinationType == typeof(DateTime);
        }
        public override object ConvertTo(ITypeDescriptorContext context,
            CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
                return ((Month)value).ToString();
            return ((Month)value).ToDateTime();
        }
    }
}

The code is self explicative two bool functions that return true if the conversion from/to a type is possible and two functions that actually perform the conversion from/to. I enabled conversion from/to both DateTime and string but for the purpose of model binding conversion from strings is enough.

Now let declare that this type converter is associated with the Month struct by decorating the Month definition as shown below:

[System.ComponentModel
    .TypeConverter(typeof(MonthTypeConverter))]
public struct Month
{
    ...
    ...

Done! Now we need just to test our Month struct.

Go to the HomeController and substitute the Index method with:

 

public IActionResult Index(Nullable<Month> monthTest)
{
    return View(monthTest);
}

Then go to “Views\Home\Index.cshtm” and replace the whole content with:

@model Nullable<SimpleModelBinding.Types.Month>
@{
    ViewData["Title"] = "Simple Type Model Binding Test";
    var monthTest = Model;
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home" >
    <div class="form-group">
        <label asp-for="@monthTest">Month:</label>
        <input asp-for="@monthTest" type="month" class="form-control">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

Model must be assigned to the variable monthTest otherwise the input field would have empty name and id.

This problem arises because in our very simple test the month struct is not a property of a bigger model. With our trick the input field is named “monthTest” that must match the name of the parameter of the Home controller Index method.

Now select a browser that supports input of type Month (last versions of Edge, Safari, Chrome, Firefox, will do) and run the project.

Select a month, and before submitting place a breakpoint in the Index action method. Once the breakpoint is hit you should see that the month parameter contains the month you have chosen in the browser:

SimpleModelBinderDebug

 

 

 

 

 

In a similar way you might define a Week type and a custom model binding for it.  The Asp.net core version of the Mvc Controls Toolkit, contains Week and Month types together with custom model binding, extensions of RangeAttribute and all validation rules, fallbacks for browsers that do not support any HTML5 and more…

 

That’s all for now

In a short time the second post of our series.

Stay tuned!

Francesco

Tags: , , ,

Dec 2 2016

Increasing productivity in your Asp.net core projects

Category: Asp.net | Asp.net core | MVCFrancesco @ 07:47

Often, during web development we complaint about the time we spend in “standard tasks” and dream of coding just our application peculiarities, thus concentrating just on our specific problem. For sure project templates and scaffolding save some “set up time” and avoid errors, but they do not save too much coding time.

In this post I’ll describe some good practices to increase web pages productivity at the price of some more set up time, and  how the new Asp.net core version of the Mvc Controls Toolkit  may help you with this. For the ones new to the Mvc Controls Toolkit, the Mvc Controls Toolkit is an open source project released with the same license of the whole Asp.net core project, so you may freely use it with no limitations and may also participate to its improvement.

The problem with most of “standard tasks” is that they are not “completely standard” so they cannot be completely automated. However, for each of them we may somehow define and automate a kind of “average task” where we can reach 90% of all actual tasks with small manual modifications. We increase further productivity if these manual modifications are achieved with name conventions, and declarations, such as, for instance, data annotations, options objects, and Tag-Helper attributes.

So for instance you might spend some set-up time to define a few “standard submit forms”, an automated procedure to create them given a few declarative information, and then use them to produce quickly, say 90%, of your views. That 90% is not a quite random number, but the result of statistics I carried out with the help of some of my customers. In fact, on the average 80-90% of all Views of a typical business application are quite standard and just 10-20% require a more complex design. In turn, among the last 10-20% just 3-7% are peculiar to the specific project since the remaining 7-13% consist of instances of general problems, so we may consider automating also part of them.

In the remainder of this post I’ll analyze different project areas that might benefit from this approach and that is worth to “attack”, pointing out the kind of automation to adopt and how the Mvc Control toolkit might help you in the task.

Business and DB Layer

The simplest optimization in this area is avoiding manual copies of DB model properties into ViewModel/DTO properties:

.Select(m => new InvoiceViewModelShow
                {
                    Id = m.Id,
                    Amount = m.Amount,
                    Reference = m.Reference,
                    FileName = m.FileName,
                    Date = m.Date,
                    Start = m.Start,
                    Stop = m.Stop,
                    ShipName = m.Ship.Name,
                    Paid = m.Paid,
                    Approved = m.Approved,
                    ....
                    ...,

                }).ToListAsync();

You might say that’s easy, with AutoMapper! Unluckily you can’t use AutoMapper since the above expression doesn’t perform a copy operation between two in-memory objects, but it is translated into an SQl query. Extracting the whole DB objects from the database and then copying them into DTO/ViewModels with AutoMapper would be unefficient, since you might extract a lot information you don’t need from the Data Base. So, the only solution is creating dynamically LinQ queries.

The MvcControlsToolkit.Core.Business Nuget package that is a completely independent part part of the Mvc Controls Toolkit contains a projection operator that do exactly this job. It uses a same name convention and nested objects like Ship.Name are mapped by concatenating all property names: Ship.Name ===> ShipName. User must specify just properties that doesn’t conform to the name convention. Expression content is not limited to a creation operator but may contain also nested conditions with several ViewModel creations in the various condition branches, like in the example below:

m => m.Maintenance == null ?
   new ProductViewModelDetail{}:
   new ProductMaintenanceViewModelDetail{
       MaintenanceYearlyRate = (decimal)m.Maintenance.YearlyRate
   }

Please notice that the ProductViewModelDetail constructor doesn’t contain any property since all properties may be inferred using the name convention.

Expressions are cached in various ways to avoid the performance cost of re-creating them each time they are used.

Please refer to the official documentation for more information.

Further speed-up may be achieved by defining generic CRUD Repositories that takes care of all main single-table operations: paged retrieval with projection on a ViewModel, detail retrieval, and all update operations that receive directly ViewModels/DTOs as parameters.

MvcControlsToolkit.Core.Business contains a DefaultCRUDRepository<Ctx, M> class where Ctx is the DB context type and M the DB model type, that is able to update automatically also entities related to M. It implements the not generic interface ICRUDRepository, so Ctx, and M may be hidden to the presentation layer. In fact all ICRUDRepository operations have the format: Add<T>, Delete<U>, Update<T>, UpdateList<T>. UpdateList<U>, etc. Where all generics are ViewModel/DTO types. Please refer to the documentation for more details, and further useful properties .

You may inherit from DefaultCRUDRepository<Ctx, M> or build your own generic class and then add also further operations that recur in several places, and with several types in your application.

Controllers

You may speed up Controller code implementation in several ways, namely:

  • By creating generics based abstract base controllers to inherit from.
  • By implementing ActionFilters for recurring controller pre/post processing.
  • By implementing MiddleWare that pre-processes all requests
  • By implementing controller utilities classes.

Base controller generics are usually ViewModels/DTOs types. In case of WebApi controllers their main purpose is handling client/server communication protocols. In fact for better modularity and reliability all application WebApi controllers should be based on well defined abstract protocols designed during your application preliminary analysis.

Also standard controllers may benefit of inheriting from base controllers with “standard action methods”, to handle recurrent “standard” Ajax update tasks , such as showing a detail show/edit modal, and updating a modified grid item.

Both type of controllers need a JavaScript library counterpart that interfaces them with the client side. So base controllers adoption factor out and “standardize” both server side and client side code.

Base controllers “standard” action methods may be connected with problem specific business logic either by calling protected virtual methods the inheriting controller may override, or by accepting implementations of "standard" repository interfaces as constructor arguments. Generic Repository interfaces may be instantiated by problem specific implementations passed by the inheriting controllers, which in turn receive them in their constructors through dependency injection.

At moment Mvc Controls toolkit contains just a single standard ServerCrudController<VMD, VMS, D> controller that offers Ajax assistance to Views showing item lists. More specifically, it offers automatic Ajax assistance to pages in-line Ajax item updates, and in showing detail Show/Edit modals. VMD is the item detail ViewModel type , VMS the in-line item ViewModel, and D the principal key type of both of them.

ServerCrudController<VMD, VMS, D> uses the ICRUDRepository interface to communicate with the business layer, but it has also various properties and methods the inheriting controller may override to customize further action methods behavior. For detail please refer to the official documentation.

In future versions we will add also WebApi controllers implementing useful protocols, as well as facilities to get easily filtering and sorting conditions passed in the query string in OData format.

SercerCrudController is a good example of how to use a standard controller, and how to connect it with business logics:

public class CGridsController :
    ServerCrudController<ProductViewModelDetail,
        ProductViewModel, int?>
{
    public CGridsController(ProductRepository repository,
        IStringLocalizerFactory factory, IHttpContextAccessor accessor)
        : base(factory, accessor)
    {
        Repository = repository;
    }
    public async Task<IActionResult> Products(int? page)
    {
        int pg = page.HasValue ? page.Value : 1;
        if (pg < 1) pg = 1;

        var model = new ProductlistViewModel
        {
            Products = await Repository.GetPage<ProductViewModel>(
            null,
            q => q.OrderBy(m => m.Name),
            pg, 5)
        };
        return View(model);
    }      
}

repository of type ProductRepository injected with DI in the inheriting controller constructor is assigned to the Repository base controller property of type ICRUDRepository. This is enough to connect ServerCrudController  ajax-assistance action methods to the application business logic. Then, we add the Action Method that prepares data for the View that is enhanced with Ajax assistance.

For sure base generic controllers are the most powerful tool to factor out controller code, but request pre/post processing with either MiddleWare  or per-controller ActionFilters may ensure further improvements and contribute to a cleaner modular design. If you have doubts about how to implement your pre/post processing consider that with the new Asp.net core 1.1 MiddlewareFilter you may use any MiddleWare also as an Action filter. Examples of how useful request pre/post processing code is factored-out by Middleware are: authentication cookies processing, culture selection processing, and in general user preferences processing discussed in the last section of this post. In the next version of the Mvc Controls Toolkit we will add Middleware for processing also filtering/sorting information contained in the query string in OData format.

Views

Usage of standard templates that render data according to ViewModel data annotations and/or parameters drastically reduces the development time, and contribute to Web Pages standardization. In turn, Web pages standardization reduce the time needed for a user to learn how to use the web application.  One may increase, the “scope” of a template by allowing the developer to customize part, of it, as for instance, how a single property is rendered.

Mvc Controls Toolkit templates rendering is organized around RowTypes and Columns. RowTypes contain overall infos and templates for rendering a whole data item while Columns contain infos and templates for rendering a single property. RowTypes templates call Column templates, so the developer may provide “standard” RowTypes and Column templates, and then on each page he/she may control how to display data items by providing adequate settings for RowType/Columns, and by providing some custom Column template. RowTypes, and Colum settings are automatically extracted from data annotations and property types but user my override them by providing supplementary infos in RowType/Column description TagHelpers.

Here an example of an edit form rendered with a standard bootstrap-based layout and whose settings are entirely extracted from data annotations and property types.Order, input are displayed is based on the Order property of the DisplayAttribute, while the number of Bootstrap grid system slots assigned to each input is based on percentage width specifications contained in ColumnLayoutAttributes. Developer may provide specifications for several screen widths. The kind of input is selected automatically by the standard Column template based on the property type/DataTypeAttribute. So, for instance,  enums are rendered with a selects and boolean with a checkboxes.The above detail-form TagHelper uses global templates defined with partial views inside the Mvc Controls Toolkit dlls. However, in general, user may specify the name of a different partial view, or the name of a ViewComponent  in the detail-form  tag itself. The developer may also override globally the standard template Partial Views by adding Partial Views with the same names in the Shared folder.

Here an example where rendering has been customized with the help of row-type and column TagHelpers. The exterrnal-key-remote tag specifies that the TypeId property contains an external key, and provides all needed information for the user to select the right key value with an autocomplete, by typing the display names associated to the various keys. Settings specified in the row-type tag are applied only if the ViewModel is the ProductMaintenanceViewModelDetail subclass of the  ProductViewModelDetail base ViewModel, otherwise settings specified directly in the detail-form tag are applied.

Here “standard templates” featuring a grid with edit in-line Ajax capabilities based on the Ajax assistance furnished by the ServerCrudController<VMD, VMS, D>.

User options

Another area where you may achieve further development-time optimizations is User option handling. Having, a centralized register containing all user options with the possibility to inject them where needed via dependency injection may help to factor out some code and simplify  your overall design. Basically you may have  user options sources and stores all attached to an unique global per-request register. Sources may be input fields, url parameters and cookies for unlogged user and User Claims or custom tables for logged users. Cookies, User Claims, and custom tables may work also as stores where to save user options received through input fields or url parameters.

The MvcControlsToolkit.Core.Options nuget package (that is a completely independent part of the Mvc Controls Toolkit) offers all services described above. You may collect user options provided through input forms or url parameters without writing controller code since they are automatically processed by MvcControlsToolkit.Core.Options middleware. Then you may save them in cookies, user claims and/or custom tables with no need to write any code. Developer may configure all above services with a few simple declarative options in the MvcControlsToolkit.Core.Options middleware. It is a typical example of how MiddleWare may speed up controllers development.

For more information please refer to the official documentation.

 

That’s all for now!

More examples and tutorials in posts to come!

Francesco

 

.

 

 

 

Tags: , , ,