Facade Pattern C#

This is a structural design pattern that only exposes a simplified interface to the outside world while hiding the complex subsystems. The facade keeps the unwanted dependencies to one place. Its own behaviour takes care of the internal complexities of the subsystems.

A car acts like a facade to the outside world which exposes it’s own behaviour like on, accelerate, brake, off etc. But you are not aware of how it all works internally.

Let’s take a small example of an online Shopping cart where you add an item to a cart which is the only behaviour exposed for the Client. Once you add the item to the cart, a few things happen internally which are not directly controlled by the user action like checking availability of item, calculation of tax, locking the item for availability and calculating the cost etc.

Create a Console Application which is the Client in this example that will only add the Item to cart. Also, add a class library Shopping that will do all of the above described operations but only expose the Cart to the Client.

public interface IShoppingCart
    {
        bool addItemToCart(int itemid, int qty);
    }

internal interface IStock
    {
        bool checkStockItemsByID(int itemID);
        bool lockItemsTemp(int itemID, int qty);
    }

internal interface IItemCost
    {
        string getItemCostByID(int itemid);
    }

internal interface ITaxes
    {
        string getStateTax(string statecode);
    }

Now, implement the above behaviours while keeping only the ShoppingCart class public:

internal class Stock : IStock
    {
        public bool checkStockItemsByID(int itemID)
        {
            Console.WriteLine($"Item Id: {itemID} is available");
            return true;
        }

        public bool lockItemsTemp(int itemID, int qty)
        {
            Console.WriteLine($"Item Id: {itemID}, quantity: {qty} is locked");
            return true;
        }
    }


internal class ItemCost : IItemCost
    {
        public string getItemCostByID(int itemid)
        {
            Console.WriteLine($"Item Id: {itemid} cost is $25");
            return "25";
        }
    }


internal class Taxes : ITaxes
    {
        public string getStateTax(string statecode)
        {
            Console.WriteLine($"{statecode} state tax is 3.5%");
            return string.Empty;
        }
    }

//Exposed class
public class ShoppingCart : IShoppingCart
    {
        public bool addItemToCart(int itemid, int qty)
        {
            IStock stock = new Stock();
            stock.checkStockItemsByID(itemid);
            stock.lockItemsTemp(itemid, qty);

            IItemCost itemCost = new ItemCost();
            itemCost.getItemCostByID(itemid);

            ITaxes taxes = new Taxes();
            taxes.getStateTax("NY");

            return true;
        }
    }

The console Application only performs the action to add the Item to the cart:

class Program
    {
        static void Main(string[] args)
        {
            IShoppingCart item = new ShoppingCart();
            item.addItemToCart(123, 2);
            Console.ReadKey();
        }
    }


Output:
Item Id: 123 is available
Item Id: 123, quantity: 2 is locked
Item Id: 123 cost is $25
NY state tax is 3.5%

Singleton pattern C#

A Singleton class in OOP allows only one instance of itself to be created. While a conventional class can have any number of instances created. Below is the thread-safe implementation of Singleton class.

using System;
namespace SingletonPattern
{
    // thread-safe way.
    public sealed class Singleton
    {
        private static Singleton obj = null;
        // mutex lock used for thread-safety.
        private static readonly object mutex = new object();
        private int var = 0;

        private Singleton()
        {
        }

        public static Singleton getObj
        {
            get
            {
                lock (mutex)
                {
                    //lazy loading..
                    if (obj == null)
                    {
                        obj = new Singleton();
                    }
                    return obj;
                }
            }
        }

        public void doSomething()
        {
            var += 1;
            Console.WriteLine($"Current Value: {var}");
        }
    }
}

Now, when we call the Singleton class object using getObj from anywhere, it’ll return the same instance of obj.

using System;

namespace SingletonPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton instance = Singleton.getObj;
            instance.doSomething();
            instance.doSomething();
        }
    }
}

Output:

Current Value: 1
Current Value: 2

An example of a Singleton class can be a Database which returns only 1 instance of itself from wherever we connect to it.

How is it different from a Static class?

  1. A Singleton class can inherit other classes and can also implement interfaces.
  2. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .NET Framework CLR when the program or namespace containing the class is loaded. While a static class is generally initialized when it is first loaded.

Abstract Factory pattern C#

Let’s begin with a story of 2 brothers Bill and Steve. Both love Pizza and Ice Cream. They go to a Food Court which has Pizza outlets like Pizza Hut and Dominos Pizza and Ice Cream Parlours like Baskin Robbins and Mikey.

Taking this real world pattern into our Software design by creating classes. In this context, Food Court will be our FoodFactory abstract class that creates 2 abstract Products Pizza and Ice Cream. The Food Court has 2 sections Fun and Frolic. Bill goes for Fun and Steve goes to Frolic.

public abstract class FoodFactory
{
    public abstract Pizza BakePizza();
    public abstract IceCream MakeIceCream();
}

Create an Abstract Products folder and add the following 2 classes:

public class Pizza {

}

public class IceCream {

}

Create a Products Folder and add the following classes:

public class DominosPizza: Pizza
{
    public DominosPizza()
    {
    }
}
public class PizzaHut: Pizza
{
    public PizzaHut()
    {
    }
}
public class Mikey: IceCream
{
    public Mikey()
    {
    }
}
public class BaskinRobbins: IceCream
{
    public BaskinRobbins()
    {
    }
}

Now, suppose Fun section has Pizza Hut and Mikey and Frolic has Dominos Pizza and Baskin Robbins. Create a folder Factories and under that add the following classes:

class FunFoodFactory : FoodFactory
{
    public override Pizza BakePizza()
    {
        return new PizzaHut();
    }

    public override IceCream MakeIceCream()
    {
        return new Mikey();
    }
}
public class FrolicFoodFactory : FoodFactory
{
    public override Pizza BakePizza()
    {
        return new DominosPizza();
    }

    public override IceCream MakeIceCream()
    {
        return new BaskinRobbins();
    }
}

Now the 2 Good brothers start having fun. Create a class called GoodBrothers as below:

public class GoodBrothers
{
    private readonly Pizza _pizza;
    private readonly IceCream _icecream;

    public GoodBrothers(FoodFactory factory)
    {
        _pizza = factory.BakePizza();
        _icecream = factory.MakeIceCream();
    }

    public string WhatDidYouHaveToday()
    {
        return $"Today I ate at {_pizza.GetType().Name} and {_icecream.GetType().Name}";
    }
}

From the main class we ask them What did you have today?

class Program
{
    static void Main(string[] args)
    {
        GoodBrothers Bill = new GoodBrothers(new FunFoodFactory());
        Console.WriteLine($"Bill: {Bill.WhatDidYouHaveToday()}");

        GoodBrothers Steve = new GoodBrothers(new FrolicFoodFactory());
        Console.WriteLine($"Steve: {Steve.WhatDidYouHaveToday()}");

        Console.ReadKey();
    }
}

Output:

Bill: Today I ate at PizzaHut and Mikey
Steve: Today I ate at DominosPizza and BaskinRobbins

A similar example for Abstract Factory pattern can be for a Clothes Factory abstract class which creates abstract Products like Shirts and Trousers. A Businessman may buy from ElegantFactory and a student may buy from CasualFactory. Shirts can be of types Formal and PoloTs and Trousers can be of type Suit and Jeans.

The ElegantFactory will return types Formal Shirt and Suit Trousers. CasualFactory will return types PoloTs and Jeans. We can create a Client class like GoodBrothers that receives the ClothesFactory reference in it’s constructor to create a Shirt and Trouser for the Businessman and Student and so on.

Run ReactJS App in Docker on Mac

This post explains how you can run your ReactJS App using Docker containers on your MacBook. Containers let your Application run in an environment isolated from the rest of your machine. It includes all the necessary files and resources to run your Application as is by creating an image that can be run anywhere as a container.

First you need to download and install the latest version of Docker for Desktop on your machine here. You can check whether your Mac has Intel chip or Apple chip from About This Mac menu option. Follow the installation steps and it should be available to open under Applications.

I’m using VS Code to create the basic ReactJS App. Open VS Code and install create-react-app command if not already installed using Terminal:

npm install -g create-react-app

Use sudo with above command if it gives permission denied error.

Switch to an empty folder and run the following command:

create-react-app reactondocker

Once the App is created, open the folder in VS Code and in the terminal install the required packages using and then build:

npm install
npm run-script build

Now, run the App as below to check it works normally on your machine without Docker:

npm start

Your Application should open fine in a browser. Url would like http://localhost:3000. We need to make sure this port is exposed from the container to your machine to run the Application without issues. This will be done in a Dockerfile.

From the Extensions menu, install Docker extension in your VS Code. Then, open the Command Palette under View menu, search for Dockerfile and select Add Dockerfiles to workspace -> Node.js -> package.json -> confirm port to be exposed, in this case it is 3000.

Dockerfile will look something like this:

FROM node:12.18-alpine
ENV NODE_ENV=production
WORKDIR /usr/src/app
COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./"]
RUN npm install --production --silent
COPY . .
EXPOSE 3000
CMD ["npm", "start"]

In short, this configuration is using a base alpine image (linux distribution) with node, sets your working directory to app. Copies the required files, installs packages and exposes the port 3000. The last line is running your Application in the container like you did from VS Code on your machine. You can optionally add a compose file for multi-container Application.

You can create a .dockerignore file to prevent items from getting copied to your image that you don’t want but it is optional.


/node_modules

/build

.git

*.md

.gitignore

Now, time to build the image which can be run as a container. Again, open the command palette and search for Docker Images: build image. It’ll ask for your Dockerfile, select it and observe the command it runs automatically in your VS Code Terminal as below:

docker build --rm --pull -f "/Users/username/Documents/Apps/ReactOnDocker/reactondocker/Dockerfile" --label "com.microsoft.created-by=visual-studio-code" -t "reactondocker:latest" "/Users/username/Documents/Apps/ReactOnDocker/reactondocker"

The above docker build command will create the image which can be found under the Docker menu on the left of your VS Code below extensions.

You can run this image using Docker for Desktop, the image named reactondocker will be available to run. Or right-click on the image name in VS Code and select run interactive. Notice the docker run command as below:

docker run --rm -it  -p 3000:3000/tcp reactondocker:latest

Now you can try running the Application using the same URL http://localhost:3000 this time running inside a container. You can see the running image in the Docker for Desktop as well.

Factory Pattern C#

Factory Design Pattern falls under the category of creational design pattern. It deals with the problem of creating objects without specifying the exact class of object that will be created. It is abstracting the process of object generation which is determined at run-time.

The behavior of a PizzaFactory class is to Bake a Pizza. So, the PizzaFactory class will create the object based on the choice provided by the customer of whether it is a Dominos Pizza or Pizza Hut.

interface IBake
{
    void Pizza();
}

public class DominosPizza: IBake
{
    public void Pizza()
    {
        Console.WriteLine("Dominos Pizza is Served!");
    }
}


public class PizzaHut: IBake
{
    public void Pizza()
    {
        Console.WriteLine("Pizza Hut is Served!");
    }
}

//The type of object created is determined at run-time.
class PizzaFactory
{
    public static IBake makePizza(int choice)
    {
        IBake objPizza = null;

        switch (choice)
        {
            case 1:
                objPizza = new DominosPizza();
                break;
            case 2:
                objPizza = new PizzaHut();
                break;
            default:
                objPizza = new DominosPizza();
                break;
        }
        return objPizza;
    }
}

Now suppose your Client is a Console Application in this case. The code will be as below:

class Program
{
    static void Main(string[] args)
    {
        IBake objPizza = null;
        Console.WriteLine("Enter your choice of Pizza!");
        int choice = Convert.ToInt32(Console.ReadLine());

        objPizza = PizzaFactory.makePizza(choice);
        objPizza.Pizza();
    }
}

Sort By Day of Week PowerBI

It’s a common scenario where you’d want to display data in a chart based on Day of the Week and it obviously will look good if sorted by the Day of Week starting say Monday.

In this scenario, my Model has sample Incidents data used by a team for the number of Incidents raised over a period of time. I’ve created a Measure for the Total Count of Incidents as below:

Total Count = COUNT(IncidentsData[Incident #])

I’m using a Stacked Column chart for the display purpose, so I need to create a column Weekday that will be calculated from the Created Date of the Incident.

WEEKDAY = FORMAT('IncidentsData'[Created Date & Time],"DDDD")

Create another column that shows the default number of the Weekday as below:

WEEKDAY-NR = WEEKDAY(IncidentsData[Created Date & Time], 2)

Now select the column Weekday column in the Model, Go to Sort by Column menu and Select the column Weekday-NR as the Sort order. This tells Power BI to sort Weekday Column by Weekday-NR.

Make sure to select Weekday as your sort column in the Stacked Column chart.

Create New Project TFS 2015

To proceed further, you must have Visual Studio 2015 or higher and TFS 2015 configured in your environment. Your account must have project creation privileges.

To configure a New Team Project under TFS 2015 from your Visual Studio, follow the below steps:

  1. From your Visual Studio, access the Team Explorer window (View -> Team Explorer), click Home and hover over Projects and My Teams and click New Team Project.

2. When New Team Project wizard appears, provide a name for your Project:

3. Select a Process Template:

4. Select Source Control Settings:

Review the Settings and Finish.

public, src and scripts folder not created with create-react-app

While creating a new ReactJS App on my Windows 10 machine, I faced the issue as described in the title even though I didn’t update any packages recently.

To resolve this, I tried updating node to the latest version from here. But that didn’t work. So I had to uninstall create-react-app package globally using the following command:

npm rm -g create-react-app

Install it again with:

npm install -g create-react-app

Then it worked fine with creating the App again:

npx create-react-app my-app

Docker desktop requires the server service to be enabled Windows 10

While trying to install Docker Desktop through the installer on my Windows 10 machine I kept got the error as mentioned in the title of this post. The installer can be downloaded from here which is the Community version since we’re working on the development environment.

To resolve this, we need to take care of some prerequisites as mentioned below:

  1. Install Hyper-V and enable it. If not already done, run the following commands in PowerShell in Admin mode:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
Enable-WindowsOptionalFeature -Online -FeatureName Containers -All

2. Once the above 2 commands are successfully completed. Open Services.msc in Admin mode and look for Server service. Enable this Service as per requirement to Automatic/Manual and set it to Running.

Restart your machine to complete the installation.

Show multiline text svg circle

For creating a circle using svg, you can follow this post. Then add the below code within the svg view box.

Normally you can use text tag to show some text in a svg component. But in order to show multiline text, we need to use HTML inside foreignObject tag as shown below:

< foreignObject id="content" x="20" y="25" width="100" height="100" >
                    < div >
                        < p id="txt1" style="font-size: 12px;">Text 1< /p >
                        < p id="txt2" style="font-size: 12px;">Text 2< /p >
                    < /div >
                < /foreignObject >

The x, y values should be set according to the svg view box. You can also use normal Javascript to modify the text using innerText property as below:

document.getElementById("txt1").innerText = "New Text 1";