lundi 24 juillet 2017

Dependency injection in ASP.NET Core [DI ASP.NET Core] Part 1


What is Dependency Injection?
Wikipedia says: "Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object (or client) and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior, which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles. It directly contrasts the service locator pattern, which allows clients to know about the system they use to find dependencies.".
So, from Wikipedia definition, we resume that Dependency Injection (DI) is a technique used to loose coupling between objects or dependencies.It is a sub-approach forming part of the global concepts of inversion of control. Its principle is such that a subroutine must express the dependencies it needs to function. The IoC container is then used to instantiate the subroutine; Taking into account these dependencies. The injection of dependencies can take several forms: via a constructor, via a property, via a private field, and so on. This depends on the library used and the conceptual choices used in the project.
This technique is used always when we would like to manage dependencies and to develop a modular and well-structured application.
Dependency Injection in MVC 
It is possible to easily transpose the principle of injection of dependencies in the following way.
The controller here expresses its dependencies via its constructor.
public class DIController : Controller
{
    private readonly IDependencyInjectionService _dependencyInjectionService;

    public MyController(IDependencyInjectionService dependencyInjectionService)
    {
        _dependencyInjectionService = dependencyInjectionService;
    }
}
static void Main(string[] args)
{
    var unityContainer = new UnityContainer();

    unityContainer.RegisterType<IDependencyInjectionService , DependencyInjectionService>();

    var instance = unityContainer.Resolve<DIController>();}
Before ASP.NET Core
The previous example is a bit special. Indeed, if you run it as is, at runtime, the program does not work.

Indeed, the default behavior of the controller factory is to expect that the default constructor (without arguments) is present on the controllers to be instantiated. The factory uses the Activator class of the .NET Framework and its CreateInstance method.
With ASP.NET MVC 4 and 5, the solution usually consists of replacing the dependency resolution mechanism of the library (the DependencyResolver class) with an implementation connected to the IoC container.
With ASP.NET Web API 1 and 2, it is also necessary to replace a service in the library with an implementation plugged into the IoC container. However, the differences in internal operation between the two libraries mean that the service to be replaced is not exactly the same.
Using a library such as Unity, it is possible to retrieve a Nuget package adapted to ASP.NET MVC which automatically downloads the Bootstrapper class below. Notice the call to the SetResolver method of the DependencyResolver class. It is this call that makes it possible to replace the mechanism of resolution and instantiation of the services for all the ASP.NET MVC part of an application. Let's start from an example :
public static class UnityConfig
{
  public static IUnityContainer Initialise()
  {
    var container = BuildUnityContainer();

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));

    return container;
  }

  private static IUnityContainer BuildUnityContainer()
  {
    var container = new UnityContainer();

    RegisterTypes(container);

    return container;
  }

  public static void RegisterTypes(IUnityContainer container)
  {
      container.RegisterType<IDependencyInjectionService , DependencyInjectionService>();
  }
}
The instance passed to SetResolver must simply implement an IDependencyResolver interface, which is present in the System.Web.Mvc namespace.
public interface IDependencyResolver
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}
ref : https://msdn.microsoft.com/en-us/library/system.web.mvc.idependencyresolver(v=vs.118).aspx

And it is at this level that the simple implementation by default and using the Activator class is defined. It is this class that we replace when we use the SetResolver method.
private class DefaultDependencyResolver : IDependencyResolver
{
    public object GetService(Type serviceType)
    {
        if (serviceType.IsInterface || serviceType.IsAbstract)
        {
            return null;
        }
        try
        {
            return Activator.CreateInstance(serviceType);
        }
        catch
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return Enumerable.Empty<object>();
    }
}
With ASP.NET Web API 2, implementation requires the creation of a class that meets the IDependencyResolver contract. The name space of the latter is System.Web.Http.Dependencies.
public interface IDependencyResolver : IDependencyScope, IDisposable
{
    IDependencyScope BeginScope();
}

public interface IDependencyScope : IDisposable
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}
The instantiation and definition of the Resolver so that it can be used with the Web API controllers is ultimately done in a totally different way.
public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    container.RegisterType<IDependencyInjectionService, DependencyInjectionService>();

    config.DependencyResolver = new UnityResolver(unityContainer);

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
Note that both technologies, ASP.NET MVC and ASP.NET Web API have the basics to enable injection of dependencies. The DependencyResolver mechanism is present as a base. However, by default, it is not plugged into an IoC container. In addition, each technology uses its own mechanism. For an application that mixes MVC and Web API controllers, it is therefore necessary to create two DependencyResolver homes and plug them into the same IoC container.
Note that SignalR, another ASP.NET brick also has its own mechanism, also different from those presented above.
ASP.NET Core and Injection Dependencies
==> Next Article Part 2






lundi 10 avril 2017

Multi-tenant Application using ASP.NET

Introduction 


"Software Multitenancy refers to a software architecture in which a single instance of a software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant with a dedicated share of the instance including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants" (Wikipedia)
==> It's simple: build one central web application (single instance) that will house multiple websites able to serve multiple users.

Our goal from this article and video is to build create SaaS (Software-as-Service) applications that support multiple domains (or tenants) applying best practices from both a server-side and client-side perspective.

In Multi-tenant Application, we have many approaches in the deployment, database design, and structure. 
1- Many Deployment  in different database: 
 If we run one instance of the application for each tenant with the different database we can let many tenants able to work on a single server. 
Having many instances should not conflict with each other in the same server environment.
==> Security and maintenance problems.
2- One Deployment - many Database:
we have to run a single instance of the application in a server. We have a master (host) database to save tenant metadata (for example the tenant name and its subdomain) in a separated database for every tenant. Once we identify the current tenant (for example; from a subdomain or from a user login form), then we can switch to that tenant's database to perform operations.
==>Seperated database, separate backup separately from other tenants.
3- One Deployment - one  Database:
This the best multi-tenancy architecture. We just deploy a single instance of the application with a single database into the same server.
We use an Id field for the Tenant in each table (for a RDBMS) which is used to identify a tenant's data from others.
==>Easy to setup and maintain
4-Single Deployment - Hybrid Databases:
We would like to store tenants in one database, but we want to create separate databases for every tenant. For example, we can store tenants with big data in their own databases, but we can store all other tenants in a single database.
5-Many Deployment - One to more/Hybrid Database
It's like a combination of previous cases, we can deploy our web application to more than one server.This is independent from the database approach.

Summary
 We have 3 choices: 
1-Scale a single multi-tenant site by increasing the dedicated hardware. 
==>Offer increased flexibility.
2-Scale by adding multiple servers in a web form configuration.
==>Define the software architecture to an abstract common shareable functionality of each tenant across the multi-tenant application.  
3- Call by adding multiple virtual machines or adding cloud pass resources.
==>Develop a plan for isolation and security of each tenant in a multi-tenant solution. In this module, we reviewed all those considerations.

Let's start a project and choose the right way to work.

AlloTabib is a cloud platform, actually was used by only Tunisian doctors, we will work in this example to let all doctors in the world use it without any impact on its performance.
We will together build one website that supports multiple countries. 
The common interests of each tenant, or in our case country, is the country itself.
The group of users (patients) of each tenant are those users interested in that particular Country to get the convenient doctors.
Our goal is to build a robust, scalable, multi-tenant or single tenant web application.
We will use the following frameworks:

  • ASP.NET MVC and ASP.NET Web API as Web Frameworks.
  • Entity Framework as ORM.
  • Angularjs as SPA framework.
  • Bootstrap as HTML/CSS framework.
Will show you the way to include ASP.NET custom routing with MVC Razor, building AngularJS with Node.js in Gulp, deploying to on-premise Azure and AWS, and using Redis in server memory for cache. 

SEE IN NEXT EPISODE:


- Building the Core Components of Multi-tenancy
- Publishing Sites on Premise Azure and AWS Including Redis Cache

Next article is a video ! Keep Tuned !!

jeudi 16 mars 2017

Celebrating three years in ARDIA. A year for creating Microsoft - Tunisian .NET Community

18 March 2014 was my first day in ARDIA, another new experience for me after more than 4 years in a previous company.
Three years is considered a significant experience with ARDIA, where I learned a lot.
16 March 2016 I create Tunisian.NET Community to mount skills beginners.NET developers (Microsoft Technologies).
Some advice:
Don’t be afraid of being yourself! Believe in your ability whatever they said!
If you love what you're doing no matter what comes your way, or what problems you run into, you're going to be resilient and get through it.
Let your passion drive your career map direction. If you just started your career, do something that inspires you and gives you a sense of purpose.
As women, particularly if you have children that are on the cards, you have to expect that your career will take unexpected turns, and your priorities may shift.
I'm a mother of a wonderful kid called Rayen and an inspired husband. It's about the legacy I leave my kid, I hope to make him and her father proud and to be an example to them of what can be achieved with passion, support, tenacity, a lot of work and some luck for a unique goal is to make the world a better.
LOT OF “INSPIRATION. MOTIVATION and PASSION.”
Mastering a skill or technology is not as easy as we thought especially in a fast-changing industry.
I'm proud to be a woman, wife, and mother, face these challenges, sometimes I'm asking myself why I love programming? The answer is simple, I'm able to learn every day new technologies, I can directly impact someone's life by providing a solution, and the puzzles we solve translated into problems solved for others, I'm able to create beautiful products, solve problems and learn new tricks keeps. It is simply exciting!
A personal project reference for me that I created alone piece by piece: http://www.allotabib.net/
Writing blogs, recording some videos inspires me to be a better programmer and a better communicator, for this reason, I created my blog: http://hamidarebai.blogspot.it/ and a YouTube Channel: https://www.youtube.com/channel/UC31YxrncpmMma2_UuaWxkKw
I believe that designing, technology, and programming is almost like art and as creative not up to all. When I create components, modules, classes, entities, layers, then slowly build them up to come together and play well together.
I’m always in the phase of "The growth mindset" because I believe that my ability and intelligence can be developed and refined."
Next days, I have a lot of changes in my career with not only with ARDIA but with Microsoft.
I Say thank you for all peoples that believed in me as a technical woman involving year after year, and I said thank you to people that they tried to breaking my wing and decrease my technical value, this let me always be strong and confident.

mercredi 15 mars 2017

Convert from 1.x to Angular 2.0 - Part 2

SERVICES 

Angular 1.x

Angular 2


In Angular 1.x, if we want defining a service we have 5 different ways : Factory,Service, Provider,Constant and Values.

But in Angular 2, we use class that is the only way to define a service.
Example :

Angular 1.x

angular.module('app').service ('ClientService', ClientService);
function ClientService () {
this.getClients = function () { return
      [
        {id: 1, name: 'Hamida'},
        {id: 2, name: 'Mohamed'},
       {id: 3, name: 'Rayen'}
      ];
   }
}

Angular 2

import {Injectable} from '@angular/core';
@injectable()
export class ClientService {
getClients = () => [
      {id: 1, name: 'Hamida'},
      {id: 2, name: 'Mohamed'},
      {id: 3, name: 'Rayen'}
  ];
}
And once defined, you need to register it with your main component using provider.
Notice, @Injectable() is added to service class.

Dependency Injection

One of the advantage of Angular is Dependency Injection (DI). With Angular 2 DI is there but now there is a different way to inject dependencies. As everything is class in Angular, so DI is achieve via constructor.

Registering Services with the Injector

Angular 1.x

angular.module('app').service ('ClientService', ClientService);
function ClientService () {
this.getClients = function () { return
      [
        {id: 1, name: 'Hamida'},
        {id: 2, name: 'Mohamed'},
       {id: 3, name: 'Rayen'}
      ];
   }
}
ClientService ==> REGISTRATION

Angular 2

@NgModule({
imports: [BrowserModule, FormModule],
declarations : [ClientComponent],
providers : [ClientService],
bootstrap :   [ClientComponent],
})
export class AppModule {}

ClientService==> REGISTRATION

Dependency Injection

Angular 1.x

angular.module('app').controller('ClientController', ClientController);
ClientController.$inject = ['ClientService'];
function ClientController (ClientService) {
    var vm= this;
    vm.title = 'services';
    vm.clients = ClientService.getClients();
}

or angular.module('app').controller('ClientController', function (ClientService));

Angular 2

@Component ({
moduleId: module.id,
selector: 'my-clients',
templateUrl: 'client.component.html',
})
export class ClientComponent {
clients = this.clientService.getClients();
constructor(private clientService: ClientService) {}
}

ROUTES

In Angular 1.x, we use $routeProvider.when() to configuring routing. But in Angular 2, @RouteConfig{(...}) is used. ng-view present in Angular 1.x is replaced with <router-outlet>

Angular 1.x

var app = angular
        .module("MyModule", ["ngRoute"])
        .config(function ($routeProvider) { 
            $routeProvider 
              .when("/home", { templateUrl: "home.html", controller: "homeController" })
              .when("/client", { templateUrl: "client.html", controller: "clientController" }) 
        })
       .controller("homeController", function ($scope) {
            $scope.message = "Home Page"; 
        })    
       .controller("clientController", function ($scope) {
             $scope.clients = ["Hamida", "Mohamed", "Rayen"]; 
       }) 

Angular 2

import { Component } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import { ClientComponent } from './client/client.component';
import { ClientService } from './Client/Client.service';
 
@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html',
  directives: [ROUTER_DIRECTIVES],
  providers: [
    ROUTER_PROVIDERS,
    ClientService
  ]
})
@RouteConfig([
  { path: '/home', name: 'Home', component: HomeComponent, useAsDefault: true },
  { path: '/client', name: 'Client', component: ClientComponent },
])
export class AppComponent { }

We import Routing because it's a separate module.
 And we have more configurations to make routing work, one is adding [ROUTER_DIRECTIVES] as directive and other is to add ROUTER_DIRECTIVES in providers list.

HTML Page is like this :
<ul>
  <li><a [routerLink]="['Home']" href="">Home</a></li>
  <li><a [routerLink]="['Client']" href="">Client</a></li>
</ul>
ng-href is also replaced by [routerLink]
Angular 2 implements webstandards like components and it’s provide better performance than Angular 1.
To RECAP : we have 7 Keys to compare :

Next article will describe more Angular 2 Essentials: Modules, Components, Templates...