Monday, March 26, 2018

Abstract Factory Pattern Using C# - Real World Example

While learning about design patterns, I came to understand the most frequently used term, Factory Pattern as well as Abstract factory pattern. I searched the internet and came across numerous learning points. After a lot of search and study, I endeavored to find an actual need for the abstract design pattern.

In this article, I will explore this pattern in an easy way so that everyone can have a better understanding of it. Down the level, I'm using a Car (Vehicle) example to demonstrate abstract factory pattern.

An important aspect of software design is the manner in which objects are created. Thus, it is not only important what an object does or what it models, but also in what manner it was created.

Reference: http://www.dofactory.com/
Definition
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Definition

C#

I'd keep the structure in such a way as depicted below.
Participants

The classes and objects participating in this pattern are:

  • AbstractFactory (IVehicleFactory)
    • declares an interface for operations that create abstract products.
  • ConcreteFactory (MarutiFactory, TataFactory)
    • implements the operations to create concrete product objects.
  • AbstractProduct (ICarEngine, ICarLight)
    • declares an interface for a type of product object.
  • Product (DDis, LED, Revtron, Helogan)
    • defines a product object to be created by the corresponding concrete factory.
    • implements the AbstractProduct interface.
  • Client (Clinet)
    • uses interfaces declared by AbstractFactory and AbstractProduct classes.

Implementation

  1. using System; 
  2. namespace AbstractFactoryPattern 
  3. interface IVehicleFactory 
  4.     { 
  5.         ICarEngine GetCarEngine(); 
  6.         ICarLight GetCarLight(); 
  7.     } 
  8. class MarutiFactory : IVehicleFactory 
  9.     { 
  10. public ICarEngine GetCarEngine() 
  11.         { 
  12. return new DDiS(); 
  13.         } 
  14. public ICarLight GetCarLight() 
  15.         { 
  16. return new LED(); 
  17.         } 
  18.     } 
  19. class TataFactory : IVehicleFactory 
  20.     { 
  21. public ICarEngine GetCarEngine() 
  22.         { 
  23. return new Revtron(); 
  24.         } 
  25. public ICarLight GetCarLight() 
  26.         { 
  27. return new Helogen(); 
  28.         } 
  29.     } 
  30. class LED : ICarLight 
  31.     { 
  32. public string GetLightInfo() 
  33.         { 
  34. return "Led lights"; 
  35.         } 
  36.     } 
  37. class DDiS : ICarEngine 
  38.     { 
  39. public string GetEngineInfo() 
  40.         { 
  41. return "DDis engine for their diesal cars..."; 
  42.         } 
  43.     } 
  44.     internal class Helogen : ICarLight 
  45.     { 
  46. public string GetLightInfo() 
  47.         { 
  48. return "Helogan Light..."; 
  49.         } 
  50.     } 
  51.     internal class Revtron : ICarEngine 
  52.     { 
  53. public string GetEngineInfo() 
  54.         { 
  55. return "Revtron engine for their diesal/petrol cars..."; 
  56.         } 
  57.     } 
  58.     internal interface ICarLight 
  59.     { 
  60.         string GetLightInfo(); 
  61.     } 
  62.     internal interface ICarEngine 
  63.     { 
  64.         string GetEngineInfo(); 
  65.     } 
  66. class Client 
  67.     { 
  68. private IVehicleFactory vehicleFactory = null; 
  69. public void CreateCarWithLight(string carName) 
  70.         { 
  71. if (carName.ToLower() == "maruti") 
  72.             { 
  73.                 vehicleFactory = new MarutiFactory(); 
  74.                 Console.Write( 
  75.                     $"{carName} uses {vehicleFactory.GetCarEngine().GetEngineInfo()} with {vehicleFactory.GetCarLight().GetLightInfo()} as headlight"); 
  76.             } 
  77. else if (carName.ToLower() == "tata") 
  78.             { 
  79.                 vehicleFactory = new TataFactory(); 
  80.                 Console.Write( 
  81.                     $"{carName} uses {vehicleFactory.GetCarEngine().GetEngineInfo()} with {vehicleFactory.GetCarLight().GetLightInfo()} as headlight"); 
  82.             } 
  83.         } 
  84.     } 
  85. class Program 
  86.     { 
  87. static void Main(string[] args) 
  88.         { 
  89.             Console.Write("**** Welcome to Abstract Factory pattern By DotnetPiper.com *******\n Kinldy enter your car name..."); 
  90.             Client client = new Client(); 
  91.             string carName = Console.ReadLine(); 
  92.             client.CreateCarWithLight(carName); 
  93.             Console.ReadLine(); 
  94.         } 
  95.     } 
  96. }

Run your application now. The following window will appear.
C#
Put the desired car name you would like to know the information about, like Maruti, Tata etc.

Kindly refer to the following window as a result after you put Maruti.
C#


Link to download sample application Abstract Factory Pattern Using C# - Real World Example

    Monday, February 19, 2018

    Workshop on #Microsoft #Azure

    Workshop on #Microsoft #Azure for the students of IIMT College of Engineering, Greater Noida by Sachin Kalia at C# Corner office, Noida.

    cc Mani Gautam Dinesh Kumar Beniwal Atul Gupta

    @dotnetpiper


    Image may contain: 1 person, sitting


    Image may contain: 1 person, indoor


    Warm Regards

    Sachin Kalia

    Thursday, January 4, 2018

    INTRODUCTION

    Custom Service Dependency Injection In .Net Core 1.1

    There are various ways to inject dependency in MVC. Dependency injection is a technique to pass the required Dependency so that the desired action can be performed.
    Dependency Injection In .Net Core
    In this article we will go through with one of the key features of .Net Core, Custom Service dependency injection in .Net core 1.1, particularly at controller’s action level .Here are some important points which will help you to understand the facts easily in the following excerpts:

    Dependency Injection

    Dependency Injection (DI) is a pattern that shows how we can create loosely coupled classes. It means Class A is not directly dependent on class B and an object injects the dependency of another object. A dependency is an object that can be used as service, which is a part of this article.

    Earlier in .Net there were some well-known dependency resolvers like Unity, Autofac and Ninject and so on.

    1. .Net Core allows you to inject dependency out-of-the-box, there is no need to add the reference of the above mentioned dependency resolver. As soon as you create a solution you will be able to configure services easily, .Net Core manages this operation at its level that indeed helps a developer to get rid of this matter.
    2. This article explains about how to configure custom service in .Net core and inject that service object in controller’s constructor as well as in action method. In the earlier versions of .Net it used to not inject the dependency at Action level. This is recently introduced with the release of .Net core. Action level injection of service makes an application lighter than controller level. Consider a scenario when you have a number of action methods defined in a single controller and you have injected the service at controller’s constructor. Though it’s being used at one action only, it looks like it’s not worth it.
    PREREQUISITES
    • Visual Studio 2017 Enterprise/Professional
    • .Net Core 1.1

    IMPLEMENTATION

    In order to understand the dependency injection in .Net core 1.1, kindly refer to the given below image which states how the client application needs an object to access the implementation of given methods.
    Dependency Injection In .Net Core

    Now create a custom service class file as depicted below in screen shot:

    Dependency Injection In .Net Core

    FirstService class file has the following code snippet.

    1. using Microsoft.Extensions.Configuration; 
    2. namespace DotnetPiper.Services 
    3. public interface IFirstService 
    4.     { 
    5.         string WelcomeEquinox(); 
    6.     } 
    7. public class FirstService : IFirstService 
    8.     { 
    9. public string welcomeEquinoxStr { get; set; } 
    10. public FirstService() 
    11.         { 
    12.             welcomeEquinoxStr = "Welcome Folks in .Net Core presentation!"; //Configuration["WelcomeEquinox"];
    13.         } 
    14. public string WelcomeEquinox() 
    15.         { 
    16. return welcomeEquinoxStr; 
    17.         } 
    18.     } 

    There is a startup class file which exists in solution and has two methods ConfigureServices and configure. Refer to the below image to know more about startup class file location under solution structure.

    Dependency Injection In .Net Core

    This method executes its functionality at runtime. Both operations have a different set of objectives as shown below,

    ConfigureServices

    This method gets called by the runtime. Use this method to add services to the container. And it takes one IServiceCollection object as an input. Refer to the given below screenshot.

    Dependency Injection In .Net Core

    Configure
    This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    Dependency Injection In .Net Core

    Register Your Custom Services

    To register your custom application services in ConfigureService method kindly put an interface definition object type that will be requested from the container. The second type represents the concrete type (class) thaFit will be instantiated by the container.

    1. services.AddSingleton<IFirstService, FirstService>(); 

    If you notice in figure4, it has an IServiceCollection object which registers IFirstService object as singleton. Though there are two more ways to register your dependency in .Net core, those are AddScoped and AddTrsnsient as shown below,

    1. services.AddScoped<ArticlesService>(); 
    2. services.AddTransient<ArticlesService>(); 

    Now create a product controller under controller’s folder and inject dependency in either of controller’s action, as shown below in screen shot,

    Dependency Injection In .Net Core

    Open Product Controller and inject IFirstService dependency in Details action method. Kindly refer to the below image for ref,

    1. public ActionResult Details([FromServices] IFirstService FirstService) 
    2.      {             
    3.          _FirstService = FirstService; 
    4. return Content(_FirstService.WelcomeEquinox()); 
    5.      } 

    Note

    [FromServices] attribute is newly introduced in .Net Core and brings an important role in order to inject abstract dependency at action method level.

    Let’s run an application and see how it works.

    Press F5 and application will open in browser just to ensure that application is up and running.

    Dependency Injection In .Net Core

    Kindly copy and paste the following url to ensure the IFirstService availability at action level.

    http://localhost:64686/product/details
    Dependency Injection In .Net Core

    This is the final outcome which brings information through Custom service
    Dependency Injection In .Net Core

      Wednesday, January 3, 2018

      Register A Chat Bot Using MS Bot Framework

      Recently, I created a Chabot for a purpose which I wanted to register within. After an implementation of Bot using MS Bot framework, it should be registered with https://dev.botframework.com/bots.

      These are a few steps which may help you to register and ready to use.

      Step 1
      Go to https://dev.botframework.com/bots. You will have the following section there as given in the below screenshot.

      Step 2
      Click on "My Bots" and further, click on "Create a bot".

      Chat Bot

      Step 3
      Click on "Create" button as shown in given image and the following window will appear.
      Chat Bot

      Step 4
      Choose the first option from the given screen and click OK.
      Chat Bot

      Step 5
      As soon as you create click ok, it generates AppId which might be essential at down the level during accessing the Bot which you have created.
      Chat Bot

      Step 6
      Click on "Generate an app password" to continue.

      Note
      Kindly save this password in Notepad for future purpose.


      Chat Bot
      Chat Bot

      Step 7:
      After performing all the above steps, it is time to set configuration as given below.
      Chat Bot

      It may prompt you to keep https instead of http,
      Chat Bot
      Step 8

      Once you are done, click on register and it will prompt to as Bot created in the given screenshot.
      Chat Bot

      Step 9
      As soon as you have created and registered your Bot, click on the recently registered Bot as depicted below in the screenshot.

      Chat Bot

      It will take you to the next level which advises you to test your Bot.
      Chat Bot
      Step 10

      Click on the Test button showing in right top corner. Click on that. It will prompt you another window and put "hi" in the chat window. As soon as you type something, it starts responding you which confirms that Bot has been register successfully.
      Chat Bot

      Short circuiting and branching in .NET Core are key concepts to make an application sequential and provide more control over the response.

      The term middleware is used in a .NET Core application either to delegate a request to the next component in the pipeline or short circuit it.

      Middleware has some important aspects as shown below:

      1. It delegates the request to the next component in the pipeline.
      2. Business logic can be written before and after the component is invoked in the pipeline.

      There are three extension methods Run, Map, and Use which can be configured as request delegates.

      Each request delegated can be written as a single line as an anonymous method (aka in-line middleware) or separately as a middleware component.

      These components are responsible for invoking the next delegate in the pipeline or to short circuit it.

      .NET Core request pipeline comprises request delegates, which call one after another as the image shown below:

      Reference: MSDN

      Each delegate can also decide not to pass a request to the next delegate, which is known as short circuiting. An advantage of short circuiting is, it doesn’t pass the request to the following delegate if it doesn’t meet specific criteria. For example, if a request doesn’t have a specific parameter in its URL, then it can short circuit the pipeline and returns the response directly from there.

      On the other hand, branching helps to map the request based on matches and executes the specific branch (can be a method).

      Map and MapWhen extensions are provided by .NET Core by default for branching the pipeline.

      Kindly refer to the image below for better understanding:

      Let’s practically see all this.

      PREREQUISITES

      • Visual Studio 2017 Enterprise/Professional
      • .Net Core 1.1

      IMPLEMENTATION

      To understand the short circuiting and branching in .NET Core 1.1, refer to the figure below for a solution structure:

      Open a startup.cs file and search for configure method; it comes out-of-box with .NET Core applications.

      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IFirstService FirstService)         { }
      
      

      CONFIGURE:

      This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

      Figure3.

      SHORT-CIRCUITING:

      To meet purpose I’ve written code using Use extension method and set a limitation so that if a specific request contains a query string in its URL, then it should not go further in pipeline otherwise it should go till the Run method.

      The code snippet for short-circuiting is shown below:

      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IFirstService FirstService)         {             app.Use(async (context, next) =>             {                 string agent = context.Request.Headers["user-agent"].ToString();                 if (!string.IsNullOrEmpty(context.Request.QueryString.Value))                 {                     context.Response.Headers.Add("X-Frame-Options", "localhost");                                        await context.Response.WriteAsync("Query string is not allowed in Middleware pipeline");                     return;                 }             });         }
      

      Press F5 and run an application.

      Now copy and paste the following URL into your browser: http://localhost:64687/Map3?CustomString

      Now as per the code (if it has a query string in URL) it should short circuit the request pipeline and return a response directly from Use method:

      RESPONSE

      As shown in the screen above it skips the remaining pipeline and responds from the use extension method only. Though Run method always executes if you don’t short circuit.

      The snippet for the run method within an application is given below:

      app.Run(async context =>         {             await context.Response.WriteAsync("Hello from sample application.");         });
      
      The complete code snippet for short-circuiting is given below:
      
      public class Startup
      
      {     public void Configure(IApplicationBuilder app)     {         app.Use(async (context, next) =>         {             // You can write logic that that doesn't write to the Response.             await next.Invoke();             // write logic that doesn't write to the Response.         });         app.Run(async context =>         {             await context.Response.WriteAsync("Hello from sample application.");         });     }
      
      }
      

      Note: If you use the above code segment, await next.Invoke(); which is being used to call next component or further delegate in the pipeline. In this case it is the app.Run() method.

      E.g., kindly copy and paste the following code snippet in your configure method and run an application.

      app.Use(async (context, next) =>             {                 string agent = context.Request.Headers["user-agent"].ToString();                 if (!string.IsNullOrEmpty(context.Request.QueryString.Value))                 {                     context.Response.Headers.Add("X-Frame-Options", "localhost");                     //context.Response.Headers.Add("X-Content-Type-Options", configuration["CustomMessage"]);                     await context.Response.WriteAsync("Query string is not allowed in Middleware pipeline");                     await next.Invoke();                 }             });
      
      app.Run(async (context) =>             {                               await context.Response.WriteAsync(" Welcome Folks in .Net Core presentation!");             });
      

      Output:

      Let’s run an application and see how it works.

      Press F5 and application will open in the browser to ensure that the application is up and running.

      BRANCHING:

      As the name implies, branching means a resembling of the branches of a tree. It’s somewhere same in .NET Core also.

      Map extension method exists in .NET Core which can be used a branching as given below:

      As defined in the screenshot above, map method branches the request pipeline based on the matches of the given request path. If the request path starts with the given path, the branch will execute.

      Code snippet: Keep the code segment in Configure() method of startup file.

      app.Map("/map1", HandleMapMiddlewareOne);
      
      private static void HandleMapMiddlewareOne(IApplicationBuilder app)         {             app.Run(async context =>             {                  await context.Response.WriteAsync("Map Middleware One Called...");                            });         }
      

      app.MapWhen works the same way, as shown in the image depicted below:

      Let’s see this in practice.

      Press F5 to run your application.

      Copy and paste the following URL in browser http://localhost:64687/map1?callingBranching

      Note: Kindly replace localhost port with your application’s one.

      As soon as you execute the URL, it verifies and matches the request and reaches to the branching delegate. In our case, its HandleMapMiddlewareOne and respond directly from there.

      The same way it should work for MapWhen with the bit different condition in the below code snippet.

      app.MapWhen(context => context.Request.Query.ContainsKey("branch"),HandleBranch);
      
      private static void HandleBranch(IApplicationBuilder app)         {             app.Run(async context =>             {                 var branchVer = context.Request.Query["branch"];                 await context.Response.WriteAsync($"Branch used = {branchVer}");             });         }
      

      Press F5 to run your application.

      Copy and paste the following URL in browser http://localhost:64687/custom?branch=dotnetCore

      OUTPUT:

      Hope this helps you to understand Short Circuiting and Branching in .NET Core.

      Happy Coding!

      Friday, December 15, 2017

      ASP. Net WebAPI With. Net Core & Micro Services

      Join Me in GuruGram(Gurgaon) in IKeva to learn

      ASP. Net WebAPI With. Net Core & Micro Services

      Image may contain: 3 people, people smiling, text

      Warm Regards

      Sachin Kalia

      Tuesday, June 6, 2017

      Can't bind to 'ngFor' since it isn't a known property of 'li'

      The usage of *ngFor within the li or div element has changed .like an example given below states that #contact of contacts where #contact defines as local variable.

      <li *ngFor="#contact of contacts"></li>

      Instead of using #contact,kindly replace your code snippet with the following structure in order to declare local variables inside of structural directives.

      <li *ngFor="let contact of contacts"

      (click)="onSelect(contact)"

      [class.clicked]="showDetail === true">

      {{contact.firstName}} {{contact.lastName}}

      </li>

      Hope it will help you someDay.

      Twitter @dotnetpiper

      Can't bind to 'ngModel' since it isn't a known property of 'input'

      This error may occur at your end during the Angular2 development, specially during creation of two way binding using [(ngModel)] with your Input type.

      To fix this error kindly use the following in app.module.js and import the namespace like given below:

      import { FormsModule } from '@angular/forms';

      @NgModule({

      declarations: [

      AppComponent,

      FirstComponent

      ],

      imports: [

      BrowserModule,FormsModule

      ],

      providers: [],

      bootstrap: [AppComponent]

      })

      As soon as you add this into the above given file.it should start work as anticipated.

      Thursday, May 4, 2017

      .Net Core Sample applications with examples

      Here is an attachment for .Net core application which has the following area’s and those implementation

      image

       

      .Net Core Sample applications with examples

      Regards

      Sachin Kalia

      Thursday, April 27, 2017

      mark or make job as durable in Quartz .net?

      Mark or make job as durable in Quartz .net?

       

      This is the code segment to mark Job as durable in case you are not trigging through ITrigger.

      public static ISchedulerFactory schedFact = new StdSchedulerFactory();
              IScheduler sched = schedFact.GetScheduler();

      IJobDetail jobEOD = JobBuilder.Create<Facilities>().WithIdentity("Facilities").StoreDurably(true).Build();
                                              JobKey jobKey = JobKey.Create("Facilities");
                                              sched.AddJob(jobEOD, false);
                                              sched.TriggerJob(jobKey);

       

      Categories: WCF and WebAPI