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";

Circular Progress bar svg javascript

In this post, I’ll give the code to create a Circular progress bar which I tried with a Start button and it resets every time you click on the start button and ticks every second for 60 seconds. The start button is shown using media control html code. The start button will re-appear once timer is reset.

If you’re using Asp.net Core MVC template, I’ve put the below code in index.cshtml file.

The HTML is as below:

< div >
            < svg class="progress-ring"
                 width="120"
                 height="120" >
                < circle class="progress-ring__circle"
                        stroke="orange"
                        stroke-width="4"
                        fill="transparent"
                        r="58"
                        cx="60"
                        cy="60" / >
                < text id="play" x="40" y="70" onclick="startTimer()" >▶< /text >
            < /svg >
< /div >

Css is as follows in the site.css file:

.progress-ring {
}

.progress-ring__circle {
    transition: 0.35s stroke-dashoffset;
    transform-origin: 50% 50%;
}

#play {
    cursor: pointer;
    font-size: xx-large;
}

The below Javascript code is going to modify the svg stroke-dashoffset attribute as below in the site.js file:

var i = 0;
var interval;
var circle = document.querySelector('circle');
var radius = circle.r.baseVal.value;
var circumference = radius * 2 * Math.PI;
console.log('radius', radius);
console.log('circumference', circumference);
circle.style.strokeDasharray = `${circumference} ${circumference}`;
circle.style.strokeDashoffset = `${circumference}`;

function setProgress(percent) {
    const offset = circumference - percent / 100 * circumference;
    circle.style.strokeDashoffset = offset;
}

function startTimer() {
    console.log('circumference', circumference);
    circle.style.strokeDashoffset = `${circumference}`;
    document.getElementById("play").textContent = "ok";
    interval = setInterval(increment, 1000);
}

function increment() {
    i = i % 360 + 1;
    var perc = (i / 60) * 100;
    console.log(i);
    if (i === 60) {
        clearInterval(interval);
        document.getElementById("play").textContent = "\u25B6";
        i = 0;
    }
    setProgress(perc);
}

The stroke-dashoffset value is reduced every time to increase the progress with stroke-dasharray. You can play around with the radius to increase the circle size.

Binary Search with C#

It is a divide and conquer approach to search an element in the Array. At each step, the search space is reduced to half.

The first part of the program is a recursive approach to write the Binary Search algorithm. The second approach focuses on the iterative model. The code will spit out the index of the element if found.

public class BinarySearch
    {
        //space complexity: O(log2 (n)).
        public int? fnRecursiveBinarySearch(int[] Arr, int k, int low, int high)
        {
            int mid = 0;
            if (low > high)
            {
                return null;
            }
            else
            {
                mid = (high + low) / 2;
                if (k==Arr[mid])
                {
                    return mid;
 //return position of found.
                }
                else if (k < Arr[mid])
                {
                    return fnRecursiveBinarySearch(Arr, k, low, mid - 1);
 //search in first half.
                }
                else
                {
                    return fnRecursiveBinarySearch(Arr, k, mid + 1, high);
 //search in second half.
                }
            }
        }

        //space complexity: O(n)
        public int? fnIterativeBinarySearch(int[] Arr, int k, int low, int high)
        {
            int mid = 0;
            do
            {
                mid = (low + high) / 2;
                if(k==Arr[mid]) { return mid; //return position of found. }
                else if(k<Arr[mid]) {
                    high = mid - 1;
 //search in first half.
                }
                else
                {
                    low = mid + 1;
 //search in second half.
                }
            } while (low <= high);
            return null;
        }

    }

To test the above 2 approaches, we use a simple call to both the functions:

class Program
    {
        static void Main(string[] args)
        {
            BinarySearch bs = new BinarySearch();
            int[] Arr = { 5, 6, 3, 1, 8, 10 };

            Console.WriteLine("Recursively Found element at index: {0}", bs.fnRecursiveBinarySearch(Arr, 8, 0, Arr.Length - 1));
            Console.WriteLine("Iteratively Found element at index: {0}", bs.fnIterativeBinarySearch(Arr, 8, 0, Arr.Length - 1));
        }
    }

Time complexity is log2 (n), for both approaches. For the space complexity,
Recursive may reach to log2 (n) space because of the stack, but in the iterative approach, it should be O(1) space complexity.