<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[dotnetbees]]></title><description><![CDATA[dotnetbees]]></description><link>https://dotnetbees.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1632649433645/PLqduFGCV.png</url><title>dotnetbees</title><link>https://dotnetbees.com</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 30 Aug 2026 18:16:41 GMT</lastBuildDate><atom:link href="https://dotnetbees.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Builder Design Pattern From Intent to Implementation]]></title><description><![CDATA[Introduction
The Builder Pattern is among the Creational Patterns of the Gang Of Four (GOF). To understand this pattern, we first need to understand its intent.
Intent
“Separate the construction of a complex object from its representation so that the...]]></description><link>https://dotnetbees.com/builder-design-pattern-from-intent-to-implementation</link><guid isPermaLink="true">https://dotnetbees.com/builder-design-pattern-from-intent-to-implementation</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Sat, 01 Jan 2022 10:21:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649140759573/C3VMIWxAA.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>The Builder Pattern is among the Creational Patterns of the Gang Of Four (GOF). To understand this pattern, we first need to understand its intent.</p>
<p><strong>Intent</strong></p>
<p>“Separate the construction of a complex object from its representation so that the same construction process can create different representations.” –GOF</p>
<p>The preceding definition of the Builder Design Pattern is given by the GOF. It might be difficult to understand by reading the definition, so let us understand it by dividing it up.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632304999351/NcAkcACoV.png" alt="image.png" /></p>
<p>So the moral of the story is <strong>"Separate object construction from its representation".</strong></p>
<p>Now let's understand the implementation of this pattern using a real-world scenario.</p>
<p><strong>Scenario</strong></p>
<p>On one fine day a Pizza vendor has placed an order to a software company. His requirement was to get the list of contents to make a Pizza based on the requested Pizza type. The company has accepted the order and has provided this definition to his Project Manager Mr. X. Then Mr. X has explained all the requirements to his developer Mr. Y and asked him to develop a program for that.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305078344/Or5SZS6QU.png" alt="image.png" /></p>
<p><strong>Approach 1</strong></p>
<p>Mr. Y has begun thinking of the definition. He thought that there are many possible contents in a Pizza, like size, dough type, cheese type and so on. So first he created enumerations for all these selections. Then he created one class called "Pizza". In this class he has created a parameterized constructor with all required contents to create the Pizza. This constructor accepts the contents and sets the values in private variables. Now Mr. X has accept the functionality for the contents from the client, so he created a method called "PizzaContent" to print the entire list of contents to generate the Pizza. </p>
<pre><code><span class="hljs-keyword">public</span> class Pizza  
    {  
        <span class="hljs-keyword">private</span> readonly DoughType doughType;  
        <span class="hljs-keyword">private</span> readonly <span class="hljs-keyword">bool</span> isRedPepper;  
        <span class="hljs-keyword">private</span> readonly Size size;  
        <span class="hljs-keyword">private</span> readonly CheeseType cheeseType;  
        <span class="hljs-keyword">private</span> readonly List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> vegetables;  

        <span class="hljs-keyword">public</span> Pizza(DoughType doughType, <span class="hljs-keyword">bool</span> isRedPepper, Size size,CheeseType cheeseType,List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> vegetables)  
        {  
            <span class="hljs-built_in">this</span>.doughType <span class="hljs-operator">=</span> doughType;  
            <span class="hljs-built_in">this</span>.isRedPepper <span class="hljs-operator">=</span> isRedPepper;  
            <span class="hljs-built_in">this</span>.size=size;  
            <span class="hljs-built_in">this</span>.cheeseType=cheeseType;  
            <span class="hljs-built_in">this</span>.vegetables=vegetables;  
        }  

        <span class="hljs-keyword">public</span> void PizzaContent()  
        {  
            Console.WriteLine(<span class="hljs-string">"Pizza with {0}"</span>, doughType);  

            <span class="hljs-keyword">if</span> (isRedPepper)  
                Console.WriteLine(<span class="hljs-string">"Red Pepper"</span>);  

            Console.WriteLine(<span class="hljs-string">"Size: {0}"</span>, size);  
            Console.WriteLine(<span class="hljs-string">"Cheese Type: {0}"</span>, cheeseType);  
            Console.WriteLine(<span class="hljs-string">"Vegetables:"</span>);  

            foreach (<span class="hljs-keyword">var</span> item in vegetables)  
            {  
                Console.WriteLine(<span class="hljs-string">" {0}"</span>, item);  
            }  
        }  
    }  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">DoughType</span>  
    {  
        Neapolitan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
        NewYorkStyle_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
        SquarePan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
    }  

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">CheeseType</span>  
    {  
        American <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
        Swiss <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
    }  

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">Size</span>  
    {  
        Small <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
        Medium <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
        Large <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
    }
</code></pre><p><strong>Client-Side Code</strong></p>
<p>Mr. Y has created an object of the Pizza class where he has provided the contents of his choice to create a Pizza and called the method to get the contents.</p>
<pre><code>    static void Main(<span class="hljs-keyword">string</span>[] args)  
            {  
                <span class="hljs-keyword">new</span> Pizza(DoughType.Neapolitan_Pizza_Dough, <span class="hljs-literal">true</span>, Size.Medium, CheeseType.Swiss, <span class="hljs-keyword">new</span> List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> { <span class="hljs-string">"Tomato"</span>, <span class="hljs-string">"Capsicum"</span>,<span class="hljs-string">"Corn"</span> }).PizzaContent();  
                Console.ReadKey();  
            }
</code></pre><p><strong>Output</strong></p>
<p>Mr. Y has checked the application and it was built and run successfully.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305197300/01yZ69Dqw.png" alt="image.png" /></p>
<p>Mr. Y was very happy that he has completed the given task successfully. He has provided the demo to his Project Manager Mr. X. Mr. X has gone through the application and has discovered a problem. The constructor is very large, in other words the constructor has many parameters. He asked Mr. Y to solve that problem.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305215477/xXcPRPfoES.png" alt="image.png" /></p>
<p><strong>Huge Constructor / Too many parameters</strong></p>
<p><strong>Approach 2</strong></p>
<p>Again Mr. Y has started working on it. He has made some changes in the Pizza class. He has converted a variable into properties and removed the parameterized constructor. </p>
<pre><code> <span class="hljs-keyword">public</span> class Pizza  
        {  
           <span class="hljs-keyword">public</span> DoughType doughType {get; set;}  
           <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> isRedPepper { get; set; }  
           <span class="hljs-keyword">public</span> Size size { get; set; }  
           <span class="hljs-keyword">public</span> CheeseType cheeseType { get; set; }  
           <span class="hljs-keyword">public</span> List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> vegetables { get; set; }  

            <span class="hljs-keyword">public</span> void PizzaContent()  
            {  
                Console.WriteLine(<span class="hljs-string">"Pizza with {0}"</span>, doughType);  
                <span class="hljs-keyword">if</span> (isRedPepper)  
                    Console.WriteLine(<span class="hljs-string">"Red Pepper"</span>);  
                Console.WriteLine(<span class="hljs-string">"Size: {0}"</span>, size);  
                Console.WriteLine(<span class="hljs-string">"Cheese Type: {0}"</span>, cheeseType);  
                Console.WriteLine(<span class="hljs-string">"Vegetables:"</span>);  
                foreach (<span class="hljs-keyword">var</span> item in vegetables)  
                {  
                    Console.WriteLine(<span class="hljs-string">" {0}"</span>, item);  
                }  
            }  
        }  

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">DoughType</span>  
        {  
            Neapolitan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
            NewYorkStyle_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
            SquarePan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
        }  

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">CheeseType</span>  
        {  
            American <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
            Swiss <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
        }  

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">Size</span>  
        {  
            Small <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
            Medium <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
            Large <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
        }
</code></pre><p><strong>Client-Side Code</strong></p>
<p>Mr. Y has created an object of the Pizza class and has set all the properties for that object and called the method.</p>
<pre><code>static void Main(<span class="hljs-keyword">string</span>[] args)  
      {  
          <span class="hljs-keyword">var</span> pizza <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Pizza();  
          pizza.doughType <span class="hljs-operator">=</span> DoughType.Neapolitan_Pizza_Dough;  
          pizza.isRedPepper <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;  
          pizza.size <span class="hljs-operator">=</span> Size.Large;  
          pizza.cheeseType <span class="hljs-operator">=</span> CheeseType.American;  
          pizza.vegetables <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> { <span class="hljs-string">"Tomato"</span>, <span class="hljs-string">"Corn"</span> };  

          pizza.PizzaContent();  

          Console.ReadKey();  
      }
</code></pre><p><strong>Output</strong></p>
<p>Mr. Y has built and run the application again.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305396353/ZTQjy2y6q.png" alt="image.png" /></p>
<p>This time Mr. Y thought that he has solved the problem. He has shown the application to his Project Manager Mr. X. Mr. X was a little happy but explained that the client needs to remember all the properties, so you need to figure out some solution.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305421370/aJKk4PROS.png" alt="image.png" /></p>
<p><strong>Need to remember all the properties</strong></p>
<p><strong>Approach 3</strong></p>
<p>Mr. Y has again started working on that and he got the solution for not remembering the properties. This time he didn't change anything in the Pizza class.</p>
<pre><code>
    <span class="hljs-keyword">public</span> class Pizza  
        {  
           <span class="hljs-keyword">public</span> DoughType doughType {get; set;}  
           <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> isRedPepper { get; set; }  
           <span class="hljs-keyword">public</span> Size size { get; set; }  
           <span class="hljs-keyword">public</span> CheeseType cheeseType { get; set; }  
           <span class="hljs-keyword">public</span> List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> vegetables { get; set; }  

            <span class="hljs-keyword">public</span> void PizzaContent()  
            {  
                Console.WriteLine(<span class="hljs-string">"Pizza with {0}"</span>, doughType);  
                <span class="hljs-keyword">if</span> (isRedPepper)  
                    Console.WriteLine(<span class="hljs-string">"Red Pepper"</span>);  
                Console.WriteLine(<span class="hljs-string">"Size: {0}"</span>, size);  
                Console.WriteLine(<span class="hljs-string">"Cheese Type: {0}"</span>, cheeseType);  
                Console.WriteLine(<span class="hljs-string">"Vegetables:"</span>);  
                foreach (<span class="hljs-keyword">var</span> item in vegetables)  
                {  
                    Console.WriteLine(<span class="hljs-string">" {0}"</span>, item);  
                }  
            }  
        }  
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">DoughType</span>  
        {  
            Neapolitan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
            NewYorkStyle_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
            SquarePan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
        }  

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">CheeseType</span>  
        {  
            American <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
            Swiss <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
        }  

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">Size</span>  
        {  
            Small <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
            Medium <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
            Large <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
        }
</code></pre><p>Mr. Y has created a new class "MyPizzaBuilder". In this class he has implemented the following three major things:</p>
<ol>
<li>Create one method "GetPizza" that returns an instance of a Pizza class</li>
<li>Create methods ("PrepareDough", "AppyVegetables", "AppyCheese", "AddCondiments") to set properties</li>
<li>Create one more method "CreatePizza" that initializes an object of the Pizza class and calls the preceding methods</li>
</ol>
<pre><code>    <span class="hljs-keyword">public</span> class MyPizzaBuilder  
        {  
            Pizza pizza;  

            <span class="hljs-keyword">public</span> Pizza GetPizza()  
            {  
                <span class="hljs-keyword">return</span> pizza;  
            }  

            <span class="hljs-keyword">public</span> void CreatePizza()  
            {  
                pizza <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Pizza();  

                PrepareDough();  
                ApplyVegetables();  
                ApplyCheese();  
                AddCondiments();  
            }  

            <span class="hljs-keyword">private</span> void AddCondiments()  
            {  
                pizza.isRedPepper <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;  
            }  

            <span class="hljs-keyword">private</span> void ApplyCheese()  
            {  
                pizza.cheeseType <span class="hljs-operator">=</span> CheeseType.American;  
            }  

            <span class="hljs-keyword">private</span> void ApplyVegetables()  
            {  
                pizza.vegetables <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> { <span class="hljs-string">"Tomato"</span>, <span class="hljs-string">"Corn"</span> };  
            }  

            <span class="hljs-keyword">private</span> void PrepareDough()  
            {  
                pizza.doughType <span class="hljs-operator">=</span> DoughType.Neapolitan_Pizza_Dough;  
                pizza.size <span class="hljs-operator">=</span> Size.Large;  
            }  
        }
</code></pre><p><strong>Client-Side Code</strong></p>
<p>In the client side Mr. Y has created an object of the "MyPizzaBuilder" class and called the "CreatePizza" method. As we have seen the "CreatePizza" method calls all the methods that are required to set the properties. So in this way the client does not need to remember all the properties.</p>
<pre><code>static void Main(<span class="hljs-keyword">string</span>[] args)  
        {  
            <span class="hljs-keyword">var</span> builder <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MyPizzaBuilder();  
            builder.CreatePizza();  
           <span class="hljs-keyword">var</span> pizza <span class="hljs-operator">=</span> builder.GetPizza();  
            pizza.PizzaContent();  

            Console.ReadKey();  
        }
</code></pre><p><strong>Output</strong></p>
<p>Again Mr. Y has built and run the application and was very happy. He just explained the solution to his Project Manager. The Project Manager appreciated his efforts and asked one question "What if we want to create another type of Pizza?" Mr. Y was realized that he must copy "MyPizzaBuilder" and then change the definition of creating a Pizza. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305688515/HJOZGT9iUY8.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305696241/si6s07zA4.png" alt="image.png" /></p>
<p>If you want to create another type of Pizza then you need to create another class and copy from MyPizzaBuilder and change the definition of creating a Pizza. This is not a good practice.</p>
<p><strong>Approach 4</strong></p>
<p>Mr. Y has become fed up with the situation and this time he just wants a concrete solution. So he has thought about it and came up with the solution. In this approach he also didn't change anything in the "Pizza" class.</p>
<pre><code><span class="hljs-keyword">public</span> class Pizza  
    {  
       <span class="hljs-keyword">public</span> DoughType doughType {get; set;}  
       <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> isRedPeeper { get; set; }  
       <span class="hljs-keyword">public</span> Size size { get; set; }  
       <span class="hljs-keyword">public</span> CheeseType cheeseType { get; set; }  
       <span class="hljs-keyword">public</span> List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> vegetables { get; set; }  

        <span class="hljs-keyword">public</span> void PizzaContent()  
        {  
            Console.WriteLine(<span class="hljs-string">"Pizza with {0}"</span>, doughType);  
            <span class="hljs-keyword">if</span> (isRedPeeper)  
                Console.WriteLine(<span class="hljs-string">"Red Peeper"</span>);  
            Console.WriteLine(<span class="hljs-string">"Size: {0}"</span>, size);  
            Console.WriteLine(<span class="hljs-string">"Cheese Type: {0}"</span>, cheeseType);  
            Console.WriteLine(<span class="hljs-string">"Vegetables:"</span>);  
            foreach (<span class="hljs-keyword">var</span> item in vegetables)  
            {  
                Console.WriteLine(<span class="hljs-string">" {0}"</span>, item);  
            }  
        }  
    }  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">DoughType</span>  
    {  
        Neapolitan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
        NewYorkStyle_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
        SquarePan_Pizza_Dough <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
    }  

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">CheeseType</span>  
    {  
        American <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
        Swiss <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
    }  

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title">Size</span>  
    {  
        Small <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
        Medium <span class="hljs-operator">=</span> <span class="hljs-number">2</span>,  
        Large <span class="hljs-operator">=</span> <span class="hljs-number">3</span>  
    }
</code></pre><p>This time he has created an abstract class "PizzaBuilder" and declared all the methods that were used to set the properties as abstract. </p>
<pre><code>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">PizzaBuilder</span>  
        {  
            <span class="hljs-keyword">protected</span> Pizza pizza;  

            <span class="hljs-function"><span class="hljs-keyword">public</span> Pizza <span class="hljs-title">GetPizza</span>(<span class="hljs-params"></span>)</span>  
            {  
                <span class="hljs-keyword">return</span> pizza;  
            }  

            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CreateNewPizza</span>(<span class="hljs-params"></span>)</span>  
            {  
                pizza = <span class="hljs-keyword">new</span> Pizza();  
            }  

            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">PrepareDough</span>(<span class="hljs-params"></span>)</span>;  
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ApplyVegetables</span>(<span class="hljs-params"></span>)</span>;  
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ApplyCheese</span>(<span class="hljs-params"></span>)</span>;  
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddCondiments</span>(<span class="hljs-params"></span>)</span>;  
        }
</code></pre><p>Mr. Y has inherited the preceding abstract class into "MyPizzaBuilder" and implemented all the abstract methods. So in this way he has a solution and implemented it. Now if the client wants to create another type of pizza then he must inherit the same abstract class and implement the properties.</p>
<pre><code>
    <span class="hljs-keyword">public</span> class MyPizzaBuilder : PizzaBuilder  
        {  
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> void AddCondiments()  
            {  
                pizza.isRedPeeper <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;  
            }  

            <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> void ApplyCheese()  
            {  
                pizza.cheeseType <span class="hljs-operator">=</span> CheeseType.American;  
            }  

            <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> void ApplyVegetables()  
            {  
                pizza.vegetables <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> List<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span><span class="hljs-operator">&gt;</span> { <span class="hljs-string">"Tomato"</span>, <span class="hljs-string">"Corn"</span> };  
            }  

            <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> void PrepareDough()  
            {  
                pizza.doughType <span class="hljs-operator">=</span> DoughType.Neapolitan_Pizza_Dough;  
                pizza.size <span class="hljs-operator">=</span> Size.Large;  
            }  
        }
</code></pre><p>Mr. Y has created one more class, "PizzaMaker", to construct an object using the builder abstract class. So in this class the client must pass a builder and the methods are called of that specific concrete builder.</p>
<pre><code>
    <span class="hljs-keyword">public</span> class PizzaMaker  
    {  
        <span class="hljs-keyword">private</span> readonly PizzaBuilder builder;  

        <span class="hljs-keyword">public</span> PizzaMaker(PizzaBuilder builder)  
        {  
            <span class="hljs-built_in">this</span>.builder <span class="hljs-operator">=</span> builder;  
        }  

        <span class="hljs-keyword">public</span> void BuildPizza()   
        {  
            builder.CreateNewPizza();  
            builder.PrepareDough();  
            builder.ApplyVegetables();  
            builder.ApplyCheese();  
            builder.AddCondiments();  
        }  

        <span class="hljs-keyword">public</span> Pizza GetPizza()   
        {  
            <span class="hljs-keyword">return</span> builder.GetPizza();  
        }  
    }
</code></pre><p>Let's check what Mr. Y has done so far using a Class Diagram. Mr. Y has created the "Pizza" class that was our product. Then he created a "PizzaBuilder" abstract class that was our builder. Then he has created two concrete builders, in other words "MyPizzaBuilder" and "TomatoPizzaBuilder". In the future the client can also add more concrete builders, in other words more types of Pizzas. Finally he has created the "PizzaMaker" class that was our director.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632305887208/i1b61Io3b9.png" alt="image.png" /></p>
<p><strong>Participants</strong></p>
<ul>
<li><p>Builder (PizzaBuilder): Specifies an abstract interface for creating parts of a Product object.</p>
</li>
<li><p>ConcreteBuilder (MyPizzaBuilder, TomatoPizzaBuilder): Constructs and assembles parts of the product by implementing the Builder interface and defines and keeps track of the representation it creates. Provides an interface for retrieving the product.</p>
</li>
<li><p>Director (PizzaMaker): Constructs an object using the Builder interface.</p>
</li>
<li><p>Product (Pizza): Represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.</p>
</li>
</ul>
<p><strong>Client-Side Code</strong></p>
<p>In the client-side code Mr. Y has created an object of the "PizzaMaker" class and passed a "MyPizzaBuilder" object. Then he called the BuildPizza method that calls all the necessary methods to create a Pizza for that builder. In the third step he called the GetPizza method followed by the PizzaContent method. The same was done for "TomatoPizzaBuilder" also.</p>
<pre><code>
    static void Main(<span class="hljs-keyword">string</span>[] args)  
            {  
                <span class="hljs-keyword">var</span> pizzaMaker <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> PizzaMaker(<span class="hljs-keyword">new</span> MyPizzaBuilder());  
                pizzaMaker.BuildPizza();  
                <span class="hljs-keyword">var</span> pizza1 <span class="hljs-operator">=</span> pizzaMaker.GetPizza();  

                pizza1.PizzaContent();  

                pizzaMaker <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> PizzaMaker(<span class="hljs-keyword">new</span> TomatoPizzaBuilder());  
                pizzaMaker.BuildPizza();  
                <span class="hljs-keyword">var</span> pizza2 <span class="hljs-operator">=</span> pizzaMaker.GetPizza();  

                pizza2.PizzaContent();  

                Console.ReadKey();  
            }
</code></pre><p><strong>Output</strong></p>
<p>Mr. Y has built and run the application and gave the demo to Mr. X. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632306020876/7JiePbN1N.png" alt="image.png" /></p>
<p>This time Mr. X has gone through the application and was very happy as Mr Y. has implemented "The Builder Design Pattern".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632306038430/Rn0SwQoR0.png" alt="image.png" /></p>
<p><strong>Summary</strong></p>
<p>When we have multiple parameters, the order of those parameters are important and when we have different constructions, we should need to separate the construction of an object from its representation.</p>
]]></content:encoded></item><item><title><![CDATA[Dependency Injection In .NET Core]]></title><description><![CDATA[Consider a scenario where you want to fetch all the categories from the database and want to show that in the UI layer. So, you will create a service, i.e., a Web API which will be called by the UI layer. Now, in API, we need to create one GET method...]]></description><link>https://dotnetbees.com/dependency-injection-in-net-core</link><guid isPermaLink="true">https://dotnetbees.com/dependency-injection-in-net-core</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Sat, 01 Jan 2022 07:01:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637058404103/H9LNVfJbJ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Consider a scenario where you want to fetch all the categories from the database and want to show that in the UI layer. So, you will create a service, i.e., a Web API which will be called by the UI layer. Now, in API, we need to create one GET method which will call the repository and the repository talks with the database. In order to call the repository, we need to create an instance of the same in API GET method, which means, it’s mandatory to create an instance of the repository for API. We can say the instance of the repository is the dependency of API. Now, let’s see how we can inject this dependency in our core Web API.</p>
<p>Open Visual Studio and create a new project</p>
<p>Select API as template and press OK.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632380258505/z5WJ2LZQGv.png" alt="image.png" /></p>
<p>As we are going to fetch the categories, let’s create a category model which has two fields - CategoryId and CategoryName.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">DIinCore</span>  
{  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Category</span>  
    {  
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> CategoryId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }  
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> CategoryName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }  
    }  
}
</code></pre><p>Create an interface of repository having GetCategories method which returns the list of category object.</p>
<pre><code><span class="hljs-keyword">using</span> System.Collections.Generic;  

<span class="hljs-keyword">namespace</span> <span class="hljs-title">DIinCore</span>  
{  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ICategoryRepository</span>  
    {  
        <span class="hljs-function">List&lt;Category&gt; <span class="hljs-title">GetCategories</span>(<span class="hljs-params"></span>)</span>;  
    }  
}
</code></pre><p>Implement the preceding interface and return some sample data. As our target is to understand dependency injection, here, we are not going to fetch the data from database rather returning hard coded ones.</p>
<pre><code><span class="hljs-keyword">using</span> <span class="hljs-title">System</span>.<span class="hljs-title">Collections</span>.<span class="hljs-title">Generic</span>;  
namespace DIinCore  
{  
    <span class="hljs-keyword">public</span> class CategoryRepository : ICategoryRepository  
    {  
        <span class="hljs-keyword">public</span> List<span class="hljs-operator">&lt;</span>Category<span class="hljs-operator">&gt;</span> GetCategories()  
        {  
            List<span class="hljs-operator">&lt;</span>Category<span class="hljs-operator">&gt;</span> categories <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> List<span class="hljs-operator">&lt;</span>Category<span class="hljs-operator">&gt;</span>();  

            Category category <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Category() { CategoryId <span class="hljs-operator">=</span> <span class="hljs-number">1</span>, CategoryName <span class="hljs-operator">=</span> <span class="hljs-string">"Category1"</span> };  
            categories.Add(category);  

            category <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Category() { CategoryId <span class="hljs-operator">=</span> <span class="hljs-number">2</span>, CategoryName <span class="hljs-operator">=</span> <span class="hljs-string">"Category2"</span> };  
            categories.Add(category);  

            <span class="hljs-keyword">return</span> categories;  
        }  
    }  
}
</code></pre><p>Assume that we are not aware of the dependency injection. Then, how will we expose the GET method from API? We used to create an instance of CategoryRepository and call the GetCategories method using that instance. So tomorrow, if there is a change in CategoryRepository it will directly affect the GET method of API as it is tightly coupled with that.</p>
<pre><code>[HttpGet]  
        <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IActionResult<span class="hljs-operator">&gt;</span> Get()  
        {  
            CategoryRepository categoryRepository <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> CategoryRepository();  
            List<span class="hljs-operator">&lt;</span>Category<span class="hljs-operator">&gt;</span> categories <span class="hljs-operator">=</span> categoryRepository.GetCategories();  

            <span class="hljs-keyword">return</span> Ok(categories);  
        }
</code></pre><p>With the .NET Framework, we used to use containers like LightInject, NInject, Unity etc. But in .NET Core, Microsoft has provided an in-built container. We need to add the namespace, i.e., Microsoft.Extension.DependencyInjection.</p>
<p>So, in the startup class, inside the ConfigureServices method, we need to add our dependency into the service collection which will dynamically inject whenever and wherever we want in the project. Also, we can mention which kind of instance we want to inject - the lifetime of our instance.</p>
<p><strong>Transient</strong></p>
<p>It creates an instance each time they are requested and are never shared. It is used mainly for lightweight stateless services.</p>
<p><strong>Singleton</strong></p>
<p>This creates only single instances which are shared among all components that require it.</p>
<p><strong>Scoped</strong></p>
<p>It creates an instance once per scope which is created on every request to the application.</p>
<pre><code><span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">AspNetCore</span>.<span class="hljs-title">Builder</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">AspNetCore</span>.<span class="hljs-title">Hosting</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">Extensions</span>.<span class="hljs-title">Configuration</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">Extensions</span>.<span class="hljs-title">DependencyInjection</span>;  

namespace DIinCore  
{  
    <span class="hljs-keyword">public</span> class Startup  
    {  
        <span class="hljs-keyword">public</span> Startup(IConfiguration configuration)  
        {  
            Configuration <span class="hljs-operator">=</span> configuration;  
        }  

        <span class="hljs-keyword">public</span> IConfiguration Configuration { get; }  

        <span class="hljs-keyword">public</span> void ConfigureServices(IServiceCollection services)  
        {  
            <span class="hljs-comment">//services.AddTransient&lt;ICategoryRepository, CategoryRepository&gt;();  </span>

            services.AddSingleton&lt;ICategoryRepository, CategoryRepository<span class="hljs-operator">&gt;</span>();  

            <span class="hljs-comment">//services.AddScoped&lt;ICategoryRepository, CategoryRepository&gt;();  </span>

            services.AddMvc();  
        }  

        <span class="hljs-keyword">public</span> void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            <span class="hljs-keyword">if</span> (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  

            app.UseMvc();  
        }  
    }  
}
</code></pre><p>So far, we have added our dependency to the collection. Now, it’s time to inject where we need it, i.e., in the Web API. Our GET method is inside the CategoryController and we want an instance of categoryrepository. So, let’s create a constructor of CategoryController which expects the type of ICategoryRepository. From this parameterized constructor, set the private property of type ICategoryRepository which will be used to call GetCategories from the GET method.</p>
<pre><code><span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">AspNetCore</span>.<span class="hljs-title">Mvc</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">System</span>.<span class="hljs-title">Collections</span>.<span class="hljs-title">Generic</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">System</span>.<span class="hljs-title">Threading</span>.<span class="hljs-title">Tasks</span>;  

namespace DIinCore.Controllers  
{  
    [Route(<span class="hljs-string">"api/Category"</span>)]  
    <span class="hljs-keyword">public</span> class CategoryController : Controller  
    {  
        <span class="hljs-keyword">private</span> ICategoryRepository categoryRepository { get; set; }  
        <span class="hljs-keyword">public</span> CategoryController(ICategoryRepository categoryRepository)  
        {  
            <span class="hljs-built_in">this</span>.categoryRepository <span class="hljs-operator">=</span> categoryRepository;  
        }  

        [HttpGet]  
        <span class="hljs-keyword">public</span> async Task<span class="hljs-operator">&lt;</span>IActionResult<span class="hljs-operator">&gt;</span> Get()  
        {  
            List<span class="hljs-operator">&lt;</span>Category<span class="hljs-operator">&gt;</span> categories <span class="hljs-operator">=</span> categoryRepository.GetCategories();  
            <span class="hljs-keyword">return</span> Ok(categories);  
        }  
    }  
}
</code></pre><p>Run the application and we will be able to see the result of the GET method of CategoryController. Now, even though we haven’t created an instance of CategoryRepository which is expected by CategoryController, we are able to call the GET method successfully. The instance of CategoryRepository has been resolved dynamically, i.e., our Dependency Injection.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632380456996/6R1_Vy2qm.png" alt="image.png" /></p>
<p>You can download the sample code from <a target="_blank" href="https://github.com/akshayblevel/Core-DependencyInjection">here.</a></p>
]]></content:encoded></item><item><title><![CDATA[Host ASP.NET Core Web API On Linux Azure VM]]></title><description><![CDATA[We will create a Virtual Machine in Azure using the Ubuntu Operating System.
Let's see the step by step implementation,
Steps

Create ASP.NET Core Web API Application
Publish Web API Application
Create Virtual Machine in Azure
Install .NET Core and A...]]></description><link>https://dotnetbees.com/host-aspnet-core-web-api-on-linux-azure-vm</link><guid isPermaLink="true">https://dotnetbees.com/host-aspnet-core-web-api-on-linux-azure-vm</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Sat, 01 Jan 2022 06:47:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637058643989/ptScxMisZ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We will create a Virtual Machine in Azure using the Ubuntu Operating System.</p>
<p>Let's see the step by step implementation,</p>
<p><strong>Steps</strong></p>
<ol>
<li>Create ASP.NET Core Web API Application</li>
<li>Publish Web API Application</li>
<li>Create Virtual Machine in Azure</li>
<li>Install .NET Core and Apache in Virtual Machine</li>
<li>Host Web API Application in Virtual Machine</li>
</ol>
<p><strong>Create ASP.NET Web API Application</strong></p>
<p>Create new project, select API as template and click on create button, which will create web API application with WeatherForcast Controller having get method.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632471710731/AdpSrctHX.png" alt="image.png" /></p>
<p>Configure Swagger in AspnetCoreWebApi, so that we can see exposed method in UI.</p>
<p>In order to enable swagger, add the below nuget packages</p>
<ul>
<li>AspNetCore</li>
<li>AspNetCore.Swagger</li>
</ul>
<p>Add the below code in startup.cs under ConfigureServices method</p>
<pre><code>services.AddSwaggerGen(c <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>  
            {  
                c.SwaggerDoc(<span class="hljs-string">"v1"</span>, <span class="hljs-keyword">new</span> Microsoft.OpenApi.Models.OpenApiInfo { Title <span class="hljs-operator">=</span> <span class="hljs-string">"Aspnet Core Web Api"</span>, Version <span class="hljs-operator">=</span> <span class="hljs-string">"v1"</span> });  
                <span class="hljs-keyword">var</span> xmlFile <span class="hljs-operator">=</span> $<span class="hljs-string">"{Assembly.GetExecutingAssembly().GetName().Name}.xml"</span>;  
                <span class="hljs-keyword">var</span> xmlPath <span class="hljs-operator">=</span> Path.Combine(AppContext.BaseDirectory, xmlFile);  
                c.IncludeXmlComments(xmlPath);  
            });
</code></pre><p>Add the below code in startup.cs under Configure method</p>
<pre><code>app.UseSwagger();  
           app.UseSwaggerUI(c <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>  
           {  
               c.SwaggerEndpoint(<span class="hljs-string">"/swagger/v1/swagger.json"</span>, <span class="hljs-string">"Aspnet Core Web Api"</span>);  
               c.InjectJavascript(<span class="hljs-string">"/swagger/custom.js"</span>);  

           });
</code></pre><p>Create AspnetCoreWebApi.xml file with the below content:</p>
<pre><code><span class="hljs-meta">&lt;?xml version="1.0"?&gt;</span>  
<span class="hljs-tag">&lt;<span class="hljs-name">doc</span>&gt;</span>  
<span class="hljs-tag">&lt;/<span class="hljs-name">doc</span>&gt;</span>
</code></pre><p>Copy AspnetCoreWebApi.xml to D:\AspnetCoreWebApi\AspnetCoreWebApi\bin\Debug\netcoreapp3.0</p>
<p>Now run the application and see the result in UI.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632478262110/N4lI0_ZgN.png" alt="image.png" /></p>
<p>Our application is running under localhost in our system.</p>
<p><strong>Publish Web API Application</strong></p>
<p>Right click on project and click on Publish</p>
<p>Click on Folder from left panel and select the path where you would like to save publish copy</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550007195/HPX_inYmn.png" alt="image.png" /></p>
<p>Click on Advanced link, which will open below window</p>
<p>Select Release as Configuration, netcoreapp3.0 as Target Framework and Framework-Dependent as Deployment Mode</p>
<p>Select linux-x64 as Target Runtime, as we want to host our application in Linux environment</p>
<p>Click on Save button</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550038405/SQ3Twl2Qo.png" alt="image.png" /></p>
<p>Click on CreateProfile which will create a profile for us and will be useful for further releases</p>
<p>Click on Publish button which will publish our application and save in predefined path</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550065571/cqjU5mJz-.png" alt="image.png" /></p>
<p>Explore our selected path i.e. D:\AspnetCoreWebApi\AspnetCoreWebApi\bin\Release\netcoreapp3.0\publish and we can see the published data</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550095182/C-7pI7OpR.png" alt="image.png" /></p>
<p><strong>Create Virtual Machine in Azure</strong></p>
<p>Log into portal.azure.com and click on "Virtual machines".</p>
<p>Click on 'Add', which will open the "Create a virtual machine" wizard. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550139616/qqDTPVh5o.png" alt="image.png" /></p>
<ol>
<li>Select your Azure subscription. Duly note that all resources in an Azure subscription are billed together.</li>
<li>Select existing or create a new resource group. It is a collection of resources that share the same lifecycle, permissions, and policies.</li>
<li>Provide your virtual machine a name. For demo purpose, I have given it a name like 'AspNetCoreLinuxVM'.</li>
<li>Select the region that is right for you and your customers. Not all VM sizes are available in all regions.</li>
<li>Azure offers a range of options for managing the availability and resiliency of your application. We can select 'Availability Set' also but as of now, select 'No infrastructure redundancy required'.</li>
<li>Choose the base operating system or application for your VM.</li>
<li>Change the size as per your requirement and the price will be calculated accordingly.</li>
<li>Provide Username and Password which will be used later on to connect your VM.</li>
<li>Select SSH and HTTP as inbound ports</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550529054/WtBemCaIP.png" alt="image.png" /></p>
<p>Select your disk option.</p>
<ol>
<li><p>Premium SSD
Offers high-performance, low-latency disk support for I/O-intensive applications and production workloads. </p>
</li>
<li><p>Standard SSD
Cost effective storage option optimized for workloads that needs consistent performance at lower IOPS (Input/Output Operations Per Second) levels.</p>
</li>
<li><p>Standard HDD
For dev/test scenarios and less critical workloads at the lowest cost.</p>
</li>
</ol>
<p>For best performance, reliability, scalability, and access control, it is recommended to select Managed Disk for most of the virtual machine configuration. Use unmanaged disks if you need to support certain classic scenarios or want to manage Disk VHDs in your own storage account.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550825429/Jb5j0gxq4.png" alt="image.png" /></p>
<p>Keep the networking option as it is and move to Management.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550900765/2IGT3Gre7.png" alt="image.png" /></p>
<p>Boot the diagnostics capture serial console output and screenshots of the virtual machine running on a host to help diagnose startup issues.</p>
<p>OS guest diagnostics gets metrics every minute for our virtual machine. We can use them to create alerts and stay informed on our applications.</p>
<p>Metrics are written on a storage account.</p>
<p>If Identity is enabled, all necessary permissions can be granted via Azure Role-based access control.</p>
<p>Enable auto-shutdown configures our virtual machine to automatically shut down daily.</p>
<p>Provide the time when we want to shutdown VM</p>
<p>Provide the time zone in which shutdown time is given</p>
<p>Subscribe for notification before the VM is shutdown</p>
<p>To guard our VM against accidental deletion and corruption, enable backup.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550948184/ms3TbM7p3.png" alt="image.png" /></p>
<p>Keep Advanced option as it is and move to the Tags</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632550984365/En2OpazCk.png" alt="image.png" /></p>
<p>A tag is not required as of now. Skip this stage and move to Review + Create.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632551013550/Lugby-xXp.png" alt="image.png" /></p>
<p>It will validate all the inputs and show the status message.</p>
<p>Click on the 'Create' button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632551050985/KExSfPaFW.png" alt="image.png" /></p>
<p>Once the VM is created, you will be able to see the deployment details as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632551071793/tvhoVwHK5.png" alt="image.png" /></p>
<p>Now, in the next step, let's try to connect our recently created VM. For this, we need a public IP Address and port.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632551105220/w0KY7L6D6.png" alt="image.png" /></p>
<p>Install .NET Core and Apache in Virtual Machine</p>
<p>Open command prompt to connect virtual machine</p>
<p>Execute below command with username and IpAddress</p>
<p><em>&gt;ssh akshayblevel@13.82.17.110</em></p>
<p>It will ask for the password</p>
<p><em>&gt;akshayblevel@13.82.17.110's password:xxxxxxxxxx</em></p>
<p>Once it is connected, execute below command to point to the root</p>
<p><em>&gt;akshayblevel@AspNetCoreLinuxVM:~$ sudo -i
root@AspNetCoreLinuxVM:~# </em></p>
<p>Execute below commands to register microsoftkey, product repository and required dependencies. Need to execute once per machine.</p>
<p><em>&gt;wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb</em></p>
<p><em>&gt;sudo dpkg -i packages-microsoft-prod.deb</em></p>
<p>Execute below commands in sequence in order to install .Net Core SDK,</p>
<pre><code><span class="hljs-operator">&gt;</span>sudo add<span class="hljs-operator">-</span>apt<span class="hljs-operator">-</span>repository universe
<span class="hljs-operator">&gt;</span>sudo apt<span class="hljs-operator">-</span>get update
<span class="hljs-operator">&gt;</span>sudo apt<span class="hljs-operator">-</span>get install apt<span class="hljs-operator">-</span>transport<span class="hljs-operator">-</span>https
<span class="hljs-operator">&gt;</span>sudo apt<span class="hljs-operator">-</span>get update
<span class="hljs-operator">&gt;</span>sudo apt<span class="hljs-operator">-</span>get install dotnet<span class="hljs-operator">-</span>sdk<span class="hljs-number">-3.1</span>
</code></pre><p>Install Asp.Net Core runtime</p>
<p><em>&gt;sudo apt-get install aspnetcore-runtime-3.1</em></p>
<p>Install .Net Core runtime</p>
<p><em>&gt;sudo apt-get install dotnet-runtime-3.1</em></p>
<p>In order to expose our application to the internet, we need IIS, Nginx or Apache as reverse proxy server that will accept HTTP request and forwards to Kestrel.</p>
<p>Execute below command to install Apache</p>
<p><em>&gt;sudo apt-get install apache2</em></p>
<p>Copy public ip and run in the browser, if apache is installed correctly then you can see the apache default page</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632551737537/cx1k5MuOX.png" alt="image.png" /></p>
<p>Enable modproxy modules in Apache server to make it work as a reverse proxy.</p>
<p>First we need to restart apache</p>
<p><em>&gt;systemctl restart apache2</em></p>
<p>Enable modproxy module</p>
<p><em>&gt;a2enmod proxy proxy_http proxy_html</em></p>
<p><strong>Host Web API Application in Virtual Machine</strong></p>
<p>All the configuration files in Apache are stored at /etc/apache2/conf-enabled directory. We need to create .conf file for our application.</p>
<p>Execute below command to create conf file</p>
<p><em>&gt;vi /etc/apache2/conf-enabled/aspnetcorewebapi.conf</em></p>
<p>Insert below text to add in the aspnetcorewebapi.conf</p>
<pre><code><span class="hljs-operator">&lt;</span>VirtualHost <span class="hljs-operator">*</span>:<span class="hljs-number">80</span><span class="hljs-operator">&gt;</span>  
   ProxyPreserveHost On  
   ProxyPass <span class="hljs-operator">/</span> http:<span class="hljs-comment">//127.0.0.1:5000/  </span>
   ProxyPassReverse <span class="hljs-operator">/</span> http:<span class="hljs-comment">//127.0.0.1:5000/  </span>
   ErrorLog <span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>log<span class="hljs-operator">/</span>apache2<span class="hljs-operator">/</span>aspnetcorewebapi<span class="hljs-operator">-</span><span class="hljs-keyword">error</span>.log  
   CustomLog <span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>log<span class="hljs-operator">/</span>apache2<span class="hljs-operator">/</span>aspnetcodewebapi<span class="hljs-operator">-</span>access.log common  
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>VirtualHost<span class="hljs-operator">&gt;</span>
</code></pre><p>Execute below command to save the file and return back to root</p>
<p><em>&gt;:x</em></p>
<p>Let's verify whether file is saved correctly or not by executing below command</p>
<p><em>&gt;cat /etc/apache2/conf-enabled/aspnetcorewebapi.conf</em></p>
<p>Restart apache</p>
<p><em>&gt;systemctl restart apache2</em></p>
<p>Create directory where we can transfer our published files.</p>
<p>Go to var directory</p>
<p><em>cd /var/</em></p>
<p>Create WebApi directory</p>
<p><em>mkdir WebApi</em></p>
<p>Go inside WebApi directory</p>
<p><em>cd WebApi</em></p>
<p>Now we need to transfer our published files to WebApi directory on server, for that we can use filezilla or winscp software.</p>
<p>Install winscp from below link</p>
<p>https://winscp.net/eng/download.php</p>
<p>Connect to server using publicip, username and password. Once it is connected we can see the folder with name as username.</p>
<p>Drag and drop Publish folder from left panel to right panel i.e. on server</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632551884845/KSL_M-ljd.png" alt="image.png" /></p>
<p>Explore publish folder from the right side and verify all the files are uploaded correctly.</p>
<p>Upload Transfer files including .xml into the same folder in order to support swagger.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632551910481/_yHmb-ner.png" alt="image.png" /></p>
<p>Now all the files are uploaded on server, in the next step we need to move files from akshayblevel directory to WebApi Directory.</p>
<p>Go to the akshayblevel directory</p>
<p><em>&gt;cd /home/akshayblevel</em></p>
<p>Verify if publish folder is there or not.</p>
<p><em>&gt;Ls</em></p>
<p>Go inside publish folder.</p>
<p><em>&gt;cd publish</em></p>
<p>Verify if all the files are there or not.</p>
<p><em>&gt;Ls</em></p>
<p>Copy all the files from publish folder to WebApi folder.</p>
<p><em>&gt;cp -R </em> /var/WebApi/*</p>
<p>Go to WebApi folder.</p>
<p><em>&gt;cd /var/WebApi</em></p>
<p>Verify if all the files are there or not.</p>
<p><em>&gt;Ls</em></p>
<p>Restart apache service and server.</p>
<p><em>systemctl restart apache2 </em></p>
<p><em>sudo service apache2 restart</em></p>
<p>Create service file to start and monitor web app.</p>
<p><em>&gt;vi /etc/systemd/system/kestrel-aspnetcorewebapi.service</em></p>
<p>Add the below content to the above service file, we need to provide working directory and which file should be executed.</p>
<pre><code>[Unit]  
Description<span class="hljs-operator">=</span>Aspnet Core Web Api running on Ubuntu <span class="hljs-number">18.04</span>  
[Service]  
WorkingDirectory<span class="hljs-operator">=</span><span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>WebApi  
ExecStart<span class="hljs-operator">=</span><span class="hljs-operator">/</span>usr<span class="hljs-operator">/</span>bin<span class="hljs-operator">/</span>dotnet <span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>WebApi<span class="hljs-operator">/</span>aspnetcorewebapi.dll  
Restart<span class="hljs-operator">=</span>always  
RestartSec<span class="hljs-operator">=</span><span class="hljs-number">10</span>  
SyslogIdentifier<span class="hljs-operator">=</span>dotnet<span class="hljs-operator">-</span>demo  
User<span class="hljs-operator">=</span>www<span class="hljs-operator">-</span>data  
Environment<span class="hljs-operator">=</span>ASPNETCORE_ENVIRONMENT<span class="hljs-operator">=</span>Production  
[Install]  
WantedBy<span class="hljs-operator">=</span>multi<span class="hljs-operator">-</span>user.target
</code></pre><p>Execute the below command to save the file and return back to root.</p>
<p><em>&gt;:x</em></p>
<p>Enable and start recently created service.</p>
<pre><code>sudo systemctl enable kestrel<span class="hljs-operator">-</span>aspnetcorewebapi.service  
sudo systemctl start kestrel<span class="hljs-operator">-</span>aspnetcorewebapi.service
</code></pre><p>Now hosting is done, let's verify in the browser using public ip and we can see that our Asp.Net Core Web Application is successfully running in Linux environment.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632552374740/eO4xfU_3t.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[GraphQL In .NET Core Web API With Entity Framework Core - Part Five]]></title><description><![CDATA[So far, we have seen GraphQL queries on a single table, multiple tables, and query with parameters in this article series.

GraphQL In .NET Core Web API With Entity Framework Core - Part One
GraphQL In .NET Core Web API With Entity Framework Core - P...]]></description><link>https://dotnetbees.com/graphql-in-net-core-web-api-with-entity-framework-core-part-five</link><guid isPermaLink="true">https://dotnetbees.com/graphql-in-net-core-web-api-with-entity-framework-core-part-five</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Sat, 01 Jan 2022 05:21:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637058254629/-xQ-hStLW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So far, we have seen GraphQL queries on a single table, multiple tables, and query with parameters in this article series.</p>
<ul>
<li><a target="_blank" href="https://dotnetbees.hashnode.dev/graphql-in-net-core-web-api-with-entity-framework-core-part-one">GraphQL In .NET Core Web API With Entity Framework Core - Part One</a></li>
<li><a target="_blank" href="https://dotnetbees.hashnode.dev/graphql-in-net-core-web-api-with-entity-framework-core-part-two">GraphQL In .NET Core Web API With Entity Framework Core - Part Two</a></li>
<li><a target="_blank" href="https://dotnetbees.hashnode.dev/graphql-in-net-core-web-api-with-entity-framework-core-part-three">GraphQL In .NET Core Web API With Entity Framework Core - Part Three</a></li>
<li><a target="_blank" href="https://dotnetbees.hashnode.dev/graphql-in-net-core-web-api-with-entity-framework-core-part-four">GraphQL In .NET Core Web API With Entity Framework Core - Part Four</a></li>
</ul>
<p>Today, we will discuss the below items in detail.</p>
<ol>
<li>Aliases</li>
<li>Multiple Queries</li>
<li>Fragment</li>
<li>Named Queries</li>
<li>Variables</li>
<li>Directive</li>
<li>Optional Parameter</li>
</ol>
<p><strong>Aliases</strong></p>
<p>Consider a scenario where you have exposed your APIs using GraphQL to multiple clients. Let’s take our existing example that we are going to expose - employee entity with certifications via API to multiple clients. Now each client wants their own naming convention for properties in an entity. One client may ask that I should get a certificate as a response; not the title. The other client may expect CertificationName as a response rather than a title, so we can’t create client specific APIs. In this situation, GraphQL alias feature will help. We need to ask the client to send alias along with the query, i.e., whatever the name they want, they just need to pass in the query and GraphQL will return the response accordingly.</p>
<p>In the below sample query, we have passed Employee as an alias for employee and CertificationName as the alias for title.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632398981048/h_yCqiYMp.png" alt="image.png" /></p>
<p>We can compare query and query response with alias and without alias for better understanding. </p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Query / Alias</td><td>Without Alias</td><td>With Alias</td></tr>
</thead>
<tbody>
<tr>
<td>Query</td><td>{                        employees{                          name                          certifications                          {                            title                          }                        }                      }</td><td>{                        Employee:employees{                          name                          certifications                          {                            CertificationName:title                          }                        }                      }</td></tr>
<tr>
<td>Query Response</td><td>{                        "data": {                          "employees": [                            {                              "name": "Akshay",                              "certifications": [                                {                                  "title": "MCSD"                                }                              ]                            },                            {                              "name": "Panth",                              "certifications": [                                {                                  "title": "Scrum Master"                                }                              ]                            }                          ]                        }                      }</td><td>{                        "data": {                          "Employee": [                            {                              "name": "Akshay",                              "certifications": [                                {                                  "CertificationName": "MCSD"                                }                              ]                            },                            {                              "name": "Panth",                              "certifications": [                                {                                  "CertificationName": "Scrum Master"                                }                              ]                            }                          ]                        }                      }</td></tr>
</tbody>
</table>
</div><p><strong>Multiple Queries</strong></p>
<p>In some scenarios, you want to execute more than one query and expect the result as single json, you can do the same by giving an alias. I have given aliases like E1 &amp; E2 and written two different queries, one to fetch employee1 and another to fetch employee2 and you can see in the response that both the employees are added in the single JSON file.  </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632454760502/eU1kJk3em.png" alt="image.png" /></p>
<p><strong>Query</strong></p>
<pre><code>{  
  <span class="hljs-attribute">E1</span>:employee(<span class="hljs-attribute">id</span>:<span class="hljs-number">1</span>){name certifications {title}}  
  <span class="hljs-attribute">E2</span>:employee(<span class="hljs-attribute">id</span>:<span class="hljs-number">2</span>){name certifications {title}}  
}
</code></pre><p><strong>Query Response</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"E1"</span>: {  
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
      <span class="hljs-attr">"certifications"</span>: [  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCSD"</span>  
        },  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Scrum Master"</span>  
        }  
      ]  
    },  
    <span class="hljs-attr">"E2"</span>: {  
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
      <span class="hljs-attr">"certifications"</span>: [  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCT"</span>  
        },  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"PMP"</span>  
        }  
      ]  
    }  
  }  
}
</code></pre><p><strong>Fragment</strong></p>
<p>In multiple queries, if you observe closely, we have added {name certifications {title}} which we want as a response, we have written multiple times. Now, assume that you want to write similar kinds of queries around 10 or 20 times, then you need to write the same in the query that many times. In order to avoid such repetitions, we can use fragment. You can write fragment on type; i.e., EmployeeType, and define what you want as a response once, and pass the same fragment in each query with three dots (…) as a prefix and you will get the same response. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632454905421/GV2O93l_Z.png" alt="image.png" /></p>
<p><strong>Query</strong></p>
<pre><code>{  
  <span class="hljs-attribute">E1</span>:employee(<span class="hljs-attribute">id</span>:<span class="hljs-number">1</span>){...employeeList}  
  <span class="hljs-attribute">E2</span>:employee(<span class="hljs-attribute">id</span>:<span class="hljs-number">2</span>){...employeeList}  
}  

<span class="hljs-selector-tag">fragment</span> <span class="hljs-selector-tag">employeeList</span> <span class="hljs-selector-tag">on</span> <span class="hljs-selector-tag">EmployeeType</span>{  
  <span class="hljs-selector-tag">name</span>, <span class="hljs-selector-tag">certifications</span> {<span class="hljs-selector-tag">title</span>}  
}
</code></pre><p><strong>Query Response</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"E1"</span>: {  
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
      <span class="hljs-attr">"certifications"</span>: [  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCSD"</span>  
        },  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Scrum Master"</span>  
        }  
      ]  
    },  
    <span class="hljs-attr">"E2"</span>: {  
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
      <span class="hljs-attr">"certifications"</span>: [  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCT"</span>  
        },  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"PMP"</span>  
        }  
      ]  
    }  
  }  
}
</code></pre><p><strong>Named Queries</strong></p>
<p>Now in the case where you want to write required queries and execute as and when it's required, you can write named queries, which  means give the name of each query so that while executing it will ask which one you want to execute. Refer to the the below screen shot for the reference. The syntax for this is query {queryName} followed by {Actual Query}</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632455007497/OOzkdeClSo.png" alt="image.png" /></p>
<p><strong>Query</strong></p>
<pre><code>query <span class="hljs-keyword">all</span>  
{  
  employees {<span class="hljs-type">name</span> certifications {title}}  
}  
query E1  
{  
  E1:employee(id:<span class="hljs-number">1</span>){<span class="hljs-type">name</span>, certifications {title}}  
}
</code></pre><p><strong>Query Response for ‘all’</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"employees"</span>: [  
      {  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
        <span class="hljs-attr">"certifications"</span>: [  
          {  
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCSD"</span>  
          },  
          {  
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Scrum Master"</span>  
          }  
        ]  
      },  
      {  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
        <span class="hljs-attr">"certifications"</span>: [  
          {  
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCT"</span>  
          },  
          {  
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"PMP"</span>  
          }  
        ]  
      }  
    ]  
  }  
}
</code></pre><p><strong>Query Response for ‘E1’</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"E1"</span>: {  
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
      <span class="hljs-attr">"certifications"</span>: [  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCSD"</span>  
        },  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Scrum Master"</span>  
        }  
      ]  
    }  
  }  
}
</code></pre><p>Syntax to call Named Queries from Postman</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>URL</td><td>https://localhost:44332/graphql</td></tr>
</thead>
<tbody>
<tr>
<td>Method</td><td>POST</td></tr>
<tr>
<td>Header</td><td>Application/json</td></tr>
</tbody>
</table>
</div><p>Request Body </p>
<pre><code>{  
"query":"query all  
                {  
                  employees {name certifications {title}}  
                }  
         query E1  
                {  
                  E1:employee(id:1){name, certifications {title}}  
                }",  
"OperationName":"all"  
}
</code></pre><p>Response</p>
<pre><code>{  
    <span class="hljs-attr">"data"</span>: {  
        <span class="hljs-attr">"employees"</span>: [  
            {  
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
                <span class="hljs-attr">"certifications"</span>: [  
                    {  
                        <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCSD"</span>  
                    },  
                    {  
                        <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Scrum Master"</span>  
                    }  
                ]  
            },  
            {  
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
                <span class="hljs-attr">"certifications"</span>: [  
                    {  
                        <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCT"</span>  
                    },  
                    {  
                        <span class="hljs-attr">"title"</span>: <span class="hljs-string">"PMP"</span>  
                    }  
                ]  
            }  
        ]  
    }  
}
</code></pre><p><strong>Variables</strong></p>
<p>So far we have written queries where we were passing hard coded values for the employeeid, here we can create a variable which can accept the value dynamically and return the response accordingly. </p>
<p>With the query name we need to mention variable; i.e., $employeeId and make it mandatory using the ! symbol. Replace hard coded employee id value with the variable; i.e., $employeeId. Before executing the query we need to pass employeeId value as Query Variables.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632457476100/ksLKwHm0t.png" alt="image.png" /></p>
<p><strong>Query</strong></p>
<pre><code><span class="hljs-selector-tag">query</span> <span class="hljs-selector-tag">E1</span>($<span class="hljs-attribute">EmployeeId </span>: ID!)  
{  
  <span class="hljs-selector-tag">employee</span>(<span class="hljs-attribute">id</span>:$EmployeeId){<span class="hljs-selector-tag">name</span>, <span class="hljs-selector-tag">certifications</span> {<span class="hljs-selector-tag">title</span>}}  
}
</code></pre><p><strong>Query Variables</strong></p>
<pre><code>{  
  <span class="hljs-attr">"EmployeeId"</span>: <span class="hljs-number">2</span>  
}
</code></pre><p><strong>Query Response</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"employee"</span>: {  
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
      <span class="hljs-attr">"certifications"</span>: [  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCT"</span>  
        },  
        {  
          <span class="hljs-attr">"title"</span>: <span class="hljs-string">"PMP"</span>  
        }  
      ]  
    }  
  }  
}
</code></pre><p>Syntax to call Named Queries from Postman</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>URL</td><td>https://localhost:44332/graphql</td></tr>
</thead>
<tbody>
<tr>
<td>Method</td><td>POST</td></tr>
<tr>
<td>Header</td><td>Application/json</td></tr>
</tbody>
</table>
</div><p><strong>Request Body</strong></p>
<pre><code>{  
<span class="hljs-string">"query"</span>:<span class="hljs-string">"query all  
                {  
                  employees {name certifications {title}}  
                }  

         query E1(<span class="hljs-subst">$EmployeeId</span>:ID!)  
                {  
                  employee(id:<span class="hljs-subst">$EmployeeId</span>){name, certifications {title}}  
                }"</span>,  
<span class="hljs-string">"OperationName"</span>:<span class="hljs-string">"E1"</span>,  
<span class="hljs-string">"variables"</span>:{<span class="hljs-string">"EmployeeId"</span>:<span class="hljs-number">2</span>}  
}
</code></pre><p><strong>Response</strong></p>
<pre><code>{  
    <span class="hljs-attr">"data"</span>: {  
        <span class="hljs-attr">"employee"</span>: {  
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
            <span class="hljs-attr">"certifications"</span>: [  
                {  
                    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"MCT"</span>  
                },  
                {  
                    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"PMP"</span>  
                }  
            ]  
        }  
    }  
}
</code></pre><p><strong>Directive</strong></p>
<p>Consider a scenario where your expectation is to get a response based on your query parameter, for example if value for Boolean parameter is passed as true then return a long description, or else don’t consider a long description in response. So declare a variable which expects true or false, which means a long description needs to be returned or not. And along with a long description in the query we can use inbuilt directive; i.e., @include(if: {condition}).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632460494578/So5-xp_xd.png" alt="image.png" /></p>
<p><strong>Query</strong></p>
<pre><code>   <span class="hljs-attribute">query</span> all(<span class="hljs-variable">$ShowLongDescription</span> : Boolean!)  
    {  
      <span class="hljs-section">employees</span>  
      {  
        <span class="hljs-attribute">id</span>  
        name  
        email  
        mobile  
        address  
        shortDescription  
        longDescription <span class="hljs-variable">@include</span>(if: <span class="hljs-variable">$ShowLongDescription</span>)  
    }  
    }
</code></pre><p><strong>Query Variables</strong></p>
<pre><code>{  
  <span class="hljs-attr">"ShowLongDescription"</span>:  <span class="hljs-literal">false</span>  
}
</code></pre><p><strong>Query Response</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"employees"</span>: [  
      {  
        <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
        <span class="hljs-attr">"email"</span>: <span class="hljs-string">"akshayblevel@gmail.com"</span>,  
        <span class="hljs-attr">"mobile"</span>: <span class="hljs-string">"9999999999"</span>,  
        <span class="hljs-attr">"address"</span>: <span class="hljs-string">"Hyderabad"</span>,  
        <span class="hljs-attr">"shortDescription"</span>: <span class="hljs-string">"Short Description"</span>  
      },  
      {  
        <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
        <span class="hljs-attr">"email"</span>: <span class="hljs-string">"panth@gmail.com"</span>,  
        <span class="hljs-attr">"mobile"</span>: <span class="hljs-string">"8888888888"</span>,  
        <span class="hljs-attr">"address"</span>: <span class="hljs-string">"Vadodara"</span>,  
        <span class="hljs-attr">"shortDescription"</span>: <span class="hljs-string">"SD"</span>  
      }  
    ]  
  }  
}
</code></pre><p><strong>Optional Parameter</strong></p>
<p>In the continuation of the above directive implementation, we can declare parameter as optional. For example, if someone doesn’t pass the expected value, in that case also it should work. So we have passed false as default parameter value. If you don’t pass value for showLongDescription it won’t return longDescription by default. If you want to get longDescription in your response, you need to pass parameter value as true.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632460629763/fAOJIC2a1.png" alt="image.png" /></p>
<p><strong>Query</strong></p>
<pre><code><span class="hljs-attribute">query</span> all(<span class="hljs-variable">$ShowLongDescription</span> : Boolean=<span class="hljs-literal">false</span>)  
{  
  <span class="hljs-section">employees</span>  
  {  
    <span class="hljs-attribute">id</span>  
    name  
    email  
    mobile  
    address  
    shortDescription  
    longDescription <span class="hljs-variable">@include</span>(if: <span class="hljs-variable">$ShowLongDescription</span>)  
}  
}
</code></pre><p><strong>Query Response</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"employees"</span>: [  
      {  
        <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
        <span class="hljs-attr">"email"</span>: <span class="hljs-string">"akshayblevel@gmail.com"</span>,  
        <span class="hljs-attr">"mobile"</span>: <span class="hljs-string">"9999999999"</span>,  
        <span class="hljs-attr">"address"</span>: <span class="hljs-string">"Hyderabad"</span>,  
        <span class="hljs-attr">"shortDescription"</span>: <span class="hljs-string">"Short Description"</span>,  
        <span class="hljs-attr">"longDescription"</span>: <span class="hljs-string">"Long Description"</span>  
      },  
      {  
        <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
        <span class="hljs-attr">"email"</span>: <span class="hljs-string">"panth@gmail.com"</span>,  
        <span class="hljs-attr">"mobile"</span>: <span class="hljs-string">"8888888888"</span>,  
        <span class="hljs-attr">"address"</span>: <span class="hljs-string">"Vadodara"</span>,  
        <span class="hljs-attr">"shortDescription"</span>: <span class="hljs-string">"SD"</span>,  
        <span class="hljs-attr">"longDescription"</span>: <span class="hljs-string">"LD"</span>  
      }  
    ]  
  }  
}
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632460720857/uRIGkHZVA.png" alt="image.png" /></p>
<p><strong>Query</strong></p>
<pre><code><span class="hljs-attribute">query</span> all(<span class="hljs-variable">$ShowLongDescription</span> : Boolean=<span class="hljs-literal">false</span>)  
{  
  <span class="hljs-section">employees</span>  
  {  
    <span class="hljs-attribute">id</span>  
    name  
    email  
    mobile  
    address  
    shortDescription  
    longDescription <span class="hljs-variable">@include</span>(if: <span class="hljs-variable">$ShowLongDescription</span>)  
}  
}
</code></pre><p><strong>Query Variables</strong></p>
<pre><code>{  
  <span class="hljs-attr">"ShowLongDescription"</span>:  <span class="hljs-literal">true</span>  
}
</code></pre><p><strong>Query Response</strong></p>
<pre><code>{  
  <span class="hljs-attr">"data"</span>: {  
    <span class="hljs-attr">"employees"</span>: [  
      {  
        <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Akshay"</span>,  
        <span class="hljs-attr">"email"</span>: <span class="hljs-string">"akshayblevel@gmail.com"</span>,  
        <span class="hljs-attr">"mobile"</span>: <span class="hljs-string">"9999999999"</span>,  
        <span class="hljs-attr">"address"</span>: <span class="hljs-string">"Hyderabad"</span>,  
        <span class="hljs-attr">"shortDescription"</span>: <span class="hljs-string">"Short Description"</span>,  
        <span class="hljs-attr">"longDescription"</span>: <span class="hljs-string">"Long Description"</span>  
      },  
      {  
        <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,  
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Panth"</span>,  
        <span class="hljs-attr">"email"</span>: <span class="hljs-string">"panth@gmail.com"</span>,  
        <span class="hljs-attr">"mobile"</span>: <span class="hljs-string">"8888888888"</span>,  
        <span class="hljs-attr">"address"</span>: <span class="hljs-string">"Vadodara"</span>,  
        <span class="hljs-attr">"shortDescription"</span>: <span class="hljs-string">"SD"</span>,  
        <span class="hljs-attr">"longDescription"</span>: <span class="hljs-string">"LD"</span>  
      }  
    ]  
  }  
}
</code></pre><p>I hope this will help you guys during your GraphQL implementation.</p>
]]></content:encoded></item><item><title><![CDATA[Overview Of Azure Service Bus - Relay]]></title><description><![CDATA[Azure Service Bus - Relay
This article explains about Azure Service Bus - Relay which has two entities - Hybrid Connection and WCF Relay. We will also see WCF Relay in detail.
A relay is used to communicate between on-premises applications and the ou...]]></description><link>https://dotnetbees.com/overview-of-azure-service-bus-relay</link><guid isPermaLink="true">https://dotnetbees.com/overview-of-azure-service-bus-relay</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 31 Dec 2021 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1646321448654/VBQqhwFc3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Azure Service Bus - Relay</strong></p>
<p>This article explains about Azure Service Bus - Relay which has two entities - Hybrid Connection and WCF Relay. We will also see WCF Relay in detail.</p>
<p>A relay is used to communicate between on-premises applications and the outside world application. We can expose on-premises service endpoints to the public so that the outside world can access on-premise services from anywhere. We can have more than one listener for a single on-premise service endpoint. The biggest advantage of using this is that we have no need to open any port or any kind of firewall configuration. It uses Azure's network security without exposing our on-premise application.</p>
<p>Before we start implementing WCF Relay, let's revise WCF once.</p>
<p><strong>Key points of WCF</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631535147379/6vKLzpyuP.png" alt="image.png" /></p>
<ol>
<li>WCF Service exposes one or more endpoints</li>
<li>An endpoint consists of ABC, i.e., Address, Binding, and Contract</li>
<li>Address is a unique Uniform Resource Locator (URI) that identifies the location of the service. It defines the network address for sending and receiving the messages.</li>
<li>Binding specifies which transport protocol to use, what message format and which any of the ws* protocols we want to use to a particular endpoint.</li>
<li>Contract provides the additional details of the structuring contents of the various messages that will be used by the various operations exposed to the particular endpoints.</li>
</ol>
<p>Now, let's see the step by step implementation,</p>
<ol>
<li>Create Relay Namespace</li>
<li>Create WCF Relay</li>
<li>Create WCF Service</li>
<li>Host WCF Service</li>
<li>WCF Client</li>
</ol>
<p><strong>Create Relay Namespace</strong></p>
<ul>
<li>Log in to the Azure portal via portal.azure.com</li>
<li>Click on '+Create a resource', expand Integration and click on 'Relay'.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631535356678/M4n6jhmZK.png" alt="image.png" /></p>
<p>Click on 'Create' button to create the relay namespace.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631535384428/oAvCPVBc-.png" alt="image.png" /></p>
<p>Give a proper name to the namespace and click on 'Create'.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631535407403/2gNaiDLPN.png" alt="image.png" /></p>
<p><strong>Create WCF Relay</strong></p>
<p>Here, we can see two entities, i.e., Hybrid Connections and WCF Relays. But we are going to create WCF Relay.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631535464257/3mteAV28S.png" alt="image.png" /></p>
<p>Click on '+WCF Relay' to create a new relay.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631536292253/euIaNtPSH.png" alt="image.png" /></p>
<ul>
<li>Give a proper name to the relay.</li>
<li>Select 'NetTcp' as Relay Type and click on 'Create'.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631536359825/_QYTo5IrZ.png" alt="image.png" /></p>
<p><strong>Create WCF Service (Library)</strong></p>
<ul>
<li>Create a WCF Service Library application.</li>
<li>Create an operation contract which expects a string parameter.</li>
<li>Implement the contract and return the string.</li>
</ul>
<pre><code>    <span class="hljs-keyword">namespace</span> <span class="hljs-title">WCFRelayLib</span>  
    {  
        [<span class="hljs-meta">ServiceContract(Namespace = <span class="hljs-meta-string">"https://recharge.servicebus.windows.net/rechargerelay"</span>)</span>]  
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IRecharge</span>  
        {  
            [<span class="hljs-meta">OperationContract</span>]  
            <span class="hljs-function"><span class="hljs-keyword">string</span> <span class="hljs-title">DoRecharge</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>;  
        }  

        <span class="hljs-keyword">interface</span> <span class="hljs-title">IRechargeChannel</span> : <span class="hljs-title">IRecharge</span>, <span class="hljs-title">IClientChannel</span> { }  
    }     
    <span class="hljs-keyword">namespace</span> <span class="hljs-title">WCFRelayLib</span>  
    {  
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Recharge</span> : <span class="hljs-title">IRecharge</span>  
        {  
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">DoRecharge</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>  
            {  
                <span class="hljs-keyword">return</span> <span class="hljs-string">"Recharge is done for: "</span> + message;  
            }  
        }  
    }
</code></pre><p><strong>Host WCF Service (Console Application)</strong></p>
<ul>
<li>Create a console application to host the previously created service.</li>
<li>Add a NuGet Pakage Microsoft.ServiceBus.</li>
</ul>
<pre><code><span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span>?<span class="hljs-operator">&gt;</span>  
<span class="hljs-operator">&lt;</span>packages<span class="hljs-operator">&gt;</span>  
  <span class="hljs-operator">&lt;</span>package id<span class="hljs-operator">=</span><span class="hljs-string">"Microsoft.WindowsAzure.ConfigurationManager"</span> version<span class="hljs-operator">=</span><span class="hljs-string">"2.0.0.0"</span> targetFramework<span class="hljs-operator">=</span><span class="hljs-string">"net461"</span> <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>  
  <span class="hljs-operator">&lt;</span>package id<span class="hljs-operator">=</span><span class="hljs-string">"ServiceBus.v1_1"</span> version<span class="hljs-operator">=</span><span class="hljs-string">"1.0.6"</span> targetFramework<span class="hljs-operator">=</span><span class="hljs-string">"net461"</span> <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>  
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>packages<span class="hljs-operator">&gt;</span>
</code></pre><ul>
<li>Expose NetTcpRelayBinding and host the service using ServiceHost.</li>
</ul>
<pre><code>    namespace WCFRelayHost  
    {  
        class Program  
        {  
            static void Main(<span class="hljs-keyword">string</span>[] args)  
            {  
                <span class="hljs-keyword">string</span> scheme <span class="hljs-operator">=</span> <span class="hljs-string">"sb"</span>;  
                <span class="hljs-keyword">string</span> serviceNamespace <span class="hljs-operator">=</span> <span class="hljs-string">"recharge"</span>;  
                <span class="hljs-keyword">string</span> servicePath <span class="hljs-operator">=</span> <span class="hljs-string">"https://recharge.servicebus.windows.net/rechargerelay"</span>;  
                <span class="hljs-keyword">string</span> policy <span class="hljs-operator">=</span> <span class="hljs-string">"RootManageSharedAccessKey"</span>;  
                <span class="hljs-keyword">string</span> accessKey <span class="hljs-operator">=</span> <span class="hljs-string">"Kn1GO+dihGWMbMLEe6DfsuxJd6ptgvfQVG6EF6GivdY="</span>;  

                Uri <span class="hljs-keyword">address</span> <span class="hljs-operator">=</span> ServiceBusEnvironment.CreateServiceUri(scheme, serviceNamespace, servicePath);  

                ServiceHost sh <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ServiceHost(typeof(Recharge),<span class="hljs-keyword">address</span>);  

                sh.AddServiceEndpoint(typeof(IRecharge), <span class="hljs-keyword">new</span> NetTcpRelayBinding(),<span class="hljs-keyword">address</span>)  
                    .Behaviors.Add(<span class="hljs-keyword">new</span> TransportClientEndpointBehavior  
                    {  
                        TokenProvider <span class="hljs-operator">=</span> TokenProvider.CreateSharedAccessSignatureTokenProvider(policy, accessKey)  
                    });  

                sh.Open();  

                Console.WriteLine(<span class="hljs-string">"Press ENTER to close"</span>);  
                Console.ReadLine();  

                sh.Close();  
            }  
        }  
    }
</code></pre><p><strong>WCF Client (Console Application)</strong></p>
<ul>
<li>Create a console application for WCF Client.</li>
<li>Add NuGet Pakage Microsoft.ServiceBus.</li>
</ul>
<pre><code>    <span class="hljs-operator">&lt;</span>?xml version<span class="hljs-operator">=</span><span class="hljs-string">"1.0"</span> encoding<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span>?<span class="hljs-operator">&gt;</span>  
    <span class="hljs-operator">&lt;</span>packages<span class="hljs-operator">&gt;</span>  
      <span class="hljs-operator">&lt;</span>package id<span class="hljs-operator">=</span><span class="hljs-string">"Microsoft.WindowsAzure.ConfigurationManager"</span> version<span class="hljs-operator">=</span><span class="hljs-string">"2.0.0.0"</span> targetFramework<span class="hljs-operator">=</span><span class="hljs-string">"net461"</span> <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>  
      <span class="hljs-operator">&lt;</span>package id<span class="hljs-operator">=</span><span class="hljs-string">"ServiceBus.v1_1"</span> version<span class="hljs-operator">=</span><span class="hljs-string">"1.0.6"</span> targetFramework<span class="hljs-operator">=</span><span class="hljs-string">"net461"</span> <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>  
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>packages<span class="hljs-operator">&gt;</span>
</code></pre><ul>
<li>Get the ServiceName, ServicePath, Policy, and Accesskey from the portal.</li>
<li>Implement the client code as below.</li>
</ul>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">WCFRelayLib</span>  
{  
    [<span class="hljs-meta">ServiceContract(Namespace = <span class="hljs-meta-string">"https://recharge.servicebus.windows.net/rechargerelay"</span>)</span>]  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IRecharge</span>  
    {  
        [<span class="hljs-meta">OperationContract</span>]  
        <span class="hljs-function"><span class="hljs-keyword">string</span> <span class="hljs-title">DoRecharge</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>;  
    }  

    <span class="hljs-keyword">interface</span> <span class="hljs-title">IRechargeChannel</span> : <span class="hljs-title">IRecharge</span>, <span class="hljs-title">IClientChannel</span> { }  
    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>  
    {  
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>  
        {  
            Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  
            Console.WriteLine(<span class="hljs-string">"Mobile Recharge"</span>);  
            Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  
            Console.WriteLine(<span class="hljs-string">"Operators"</span>);  
            Console.WriteLine(<span class="hljs-string">"1. Vodafone"</span>);  
            Console.WriteLine(<span class="hljs-string">"2. Airtel"</span>);  
            Console.WriteLine(<span class="hljs-string">"3. JIO"</span>);  
            Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  

            Console.WriteLine(<span class="hljs-string">"Operator:"</span>);  
            <span class="hljs-keyword">string</span> mobileOperator = Console.ReadLine();  
            Console.WriteLine(<span class="hljs-string">"Amount:"</span>);  
            <span class="hljs-keyword">string</span> amount = Console.ReadLine();  
            Console.WriteLine(<span class="hljs-string">"Mobile:"</span>);  
            <span class="hljs-keyword">string</span> mobile = Console.ReadLine();  

            Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  

            <span class="hljs-keyword">switch</span> (mobileOperator)  
            {  
                <span class="hljs-keyword">case</span> <span class="hljs-string">"1"</span>:  
                    mobileOperator = <span class="hljs-string">"Vodafone"</span>;  
                    <span class="hljs-keyword">break</span>;  
                <span class="hljs-keyword">case</span> <span class="hljs-string">"2"</span>:  
                    mobileOperator = <span class="hljs-string">"Airtel"</span>;  
                    <span class="hljs-keyword">break</span>;  
                <span class="hljs-keyword">case</span> <span class="hljs-string">"3"</span>:  
                    mobileOperator = <span class="hljs-string">"JIO"</span>;  
                    <span class="hljs-keyword">break</span>;  
                <span class="hljs-keyword">default</span>:  
                    <span class="hljs-keyword">break</span>;  
            }  

            <span class="hljs-keyword">string</span> message = mobileOperator + <span class="hljs-string">"*"</span> + mobile + <span class="hljs-string">"*"</span> + amount;  

            <span class="hljs-keyword">string</span> scheme = <span class="hljs-string">"sb"</span>;  
            <span class="hljs-keyword">string</span> serviceNamespace = <span class="hljs-string">"recharge"</span>;  
            <span class="hljs-keyword">string</span> servicePath = <span class="hljs-string">"https://recharge.servicebus.windows.net/rechargerelay"</span>;  
            <span class="hljs-keyword">string</span> policy = <span class="hljs-string">"RootManageSharedAccessKey"</span>;  
            <span class="hljs-keyword">string</span> accessKey = <span class="hljs-string">"Kn1GO+dihGWMbMLEe6DfsuxJd6pEF6GivdY="</span>;  

            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;  

            <span class="hljs-keyword">var</span> cf = <span class="hljs-keyword">new</span> ChannelFactory&lt;IRechargeChannel&gt;(<span class="hljs-keyword">new</span> NetTcpRelayBinding(),<span class="hljs-keyword">new</span> EndpointAddress(ServiceBusEnvironment.CreateServiceUri(scheme, serviceNamespace,servicePath)));  

            cf.Endpoint.Behaviors.Add(<span class="hljs-keyword">new</span> TransportClientEndpointBehavior { TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(policy, accessKey) });  

            <span class="hljs-keyword">using</span> (<span class="hljs-keyword">var</span> ch = cf.CreateChannel())  
            {  
                Console.WriteLine(ch.DoRecharge(message));  
            }  
        }  
    }  
}
</code></pre><ul>
<li>Run the WCF Client application.</li>
<li>Provide required inputs and you can see the response returned from the WCF service.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631536756390/jaQZWNgif.png" alt="image.png" /></p>
<p>We can find our WCF Client as listener under WCF Relays.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631536792215/lvpu8imU9Y.png" alt="image.png" /></p>
<p>For demo purposes, we have created all the applications under a single solution, but in the real world, we can put WCF Service and Client on two different servers and verify how an external application (WCFClient) uses on-premise service, i.e., WCF Service through Relay.</p>
<p>Download the complete sample code from  <a target="_blank" href="https://github.com/akshayblevel/Azure-ServiceBus-Relay">here</a> .</p>
]]></content:encoded></item><item><title><![CDATA[Azure Service Bus Topic And Subscription (Pub-Sub)]]></title><description><![CDATA[Azure Service Bus - Topic
This articles explains about Azure Service Bus Topic and Subscription which is commonly known as pub-sub with a real world scenario. 
Business Requirement
The business requirement is in my previous article,
 Azure Service Bu...]]></description><link>https://dotnetbees.com/azure-service-bus-topic-and-subscription-pub-sub</link><guid isPermaLink="true">https://dotnetbees.com/azure-service-bus-topic-and-subscription-pub-sub</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 31 Dec 2021 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1646321606212/Vgf8mdLk-.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Azure Service Bus - Topic</strong></p>
<p>This articles explains about Azure Service Bus Topic and Subscription which is commonly known as pub-sub with a real world scenario. </p>
<p><strong>Business Requirement</strong></p>
<p>The business requirement is in my previous article,</p>
<p> <a target="_blank" href="https://www.c-sharpcorner.com/article/azure-service-bus-queue-with-real-world-scenario/">Azure Service Bus - Working With Queue In A Real World Scenario</a> </p>
<p>So far we have seen about mobile recharge where we have used queuing mechanism. Now a company wants to provide some offers on regular recharge. But how will registered users come to know about these offers?</p>
<p>So again the company has started looking for some solution and finally it has come up with the solution of Azure Service Bus - Topic. Topic works like pub-sub model where one is the publisher and there can be many subscribers for the same publisher. In our scenario the publisher will publish offers and subscribed users will get the offers immediately.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537242760/PpeGRE3GW.png" alt="image.png" /></p>
<p>Now let's see the step by step implementation of the below to design a solution:</p>
<ul>
<li>Log in to the Azure portal via portal.azure.com</li>
<li>Explore previously created Service Namespace; i.e. Mobile Recharge</li>
<li>Click on '+Topic' under Topics to create a new topic</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537310239/TjbgFKJ0LT.png" alt="image.png" /></p>
<ul>
<li>Give appropriate name for Topic</li>
<li>Keep the rest of the input values as is and click on 'Create' button</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537351645/M7xLMzwFX.png" alt="image.png" /></p>
<p>We can see that Topic is created in it is shown under topics list.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537391261/SRPH3ua7e.png" alt="image.png" /></p>
<ul>
<li>Click on previously created topic; i.e. 'Offers', which will show the list of subscriptions. As of now it shows empty</li>
<li>Click on '+Subscription' under subscriptions to create subscription</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537422829/zjlYLuiCb.png" alt="image.png" /></p>
<ul>
<li>Give proper name of subscription</li>
<li>Change Lock duration to 5 minutes and click on 'Create' button, which will create subscription for topic</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537458155/K2V6c3GK1.png" alt="image.png" /></p>
<ul>
<li>Follow the preceding steps and create one more subscription</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537487342/dn7flXv-V.png" alt="image.png" /></p>
<p>We can see both the subscriptions in the list.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537520633/eNtBHhkky.png" alt="image.png" /></p>
<p><strong>Credentials</strong>
Click on 'Shared access policies' from the left panel, click on 'RootManageSharedAccessKey' to explore keys and connection strings which will be used further to connect.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537554577/QRSYjPBYG.png" alt="image.png" /></p>
<p><strong>Publish Message</strong></p>
<ul>
<li>Create a console application in Visual Studio</li>
<li>Set variables, one for connection string which you can copy from Shared access policies section and another is topic name; i.e. offers</li>
<li>In order to publish the offers, we need an offer from user</li>
<li>Add Microsoft.Azure.ServiceBus from a NuGet package manager</li>
<li>Create topic client using connection string and queue name</li>
<li>Convert string message to Azure Service Bus message</li>
<li>Using topic client, call SendAsync method to publish the message.</li>
<li>Call CloseAsync to close opened connection in finally block.</li>
</ul>
<pre><code> class Program  
        {  
            static ITopicClient topicClient;  
            static void Main(<span class="hljs-keyword">string</span>[] args)  
            {  
                <span class="hljs-keyword">string</span> sbConnectionString <span class="hljs-operator">=</span> <span class="hljs-string">"Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMjW9CzPWvA/JGvVvUZ64U21IBI="</span>;  
                <span class="hljs-keyword">string</span> sbTopic <span class="hljs-operator">=</span> <span class="hljs-string">"offers"</span>;  

                <span class="hljs-keyword">string</span> messageBody<span class="hljs-operator">=</span><span class="hljs-keyword">string</span>.Empty;  
                <span class="hljs-keyword">try</span>  
                {  
                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  
                    Console.WriteLine(<span class="hljs-string">"Publish Offer"</span>);  
                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  
                    Console.WriteLine(<span class="hljs-string">"Offers"</span>);  
                    Console.WriteLine(<span class="hljs-string">"1. Recharge with 100 and get talk time of 110"</span>);  
                    Console.WriteLine(<span class="hljs-string">"2. Get 5 GB data on recharge of 300. Validity 28 days"</span>);  
                    Console.WriteLine(<span class="hljs-string">"3. 1000 SMS in recharge of 100"</span>);  
                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  

                    Console.WriteLine(<span class="hljs-string">"Offer:"</span>);  
                    <span class="hljs-keyword">string</span> offer <span class="hljs-operator">=</span> Console.ReadLine();  

                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  

                    switch (offer)  
                    {  
                        case <span class="hljs-string">"1"</span>:  
                            offer <span class="hljs-operator">=</span> <span class="hljs-string">"Recharge with 100 and get talk time of 110"</span>;  
                            <span class="hljs-keyword">break</span>;  
                        case <span class="hljs-string">"2"</span>:  
                            offer <span class="hljs-operator">=</span> <span class="hljs-string">"Get 5 GB data on recharge of 300. Validity 28 days"</span>;  
                            <span class="hljs-keyword">break</span>;  
                        case <span class="hljs-string">"3"</span>:  
                            offer <span class="hljs-operator">=</span> <span class="hljs-string">"1000 SMS in recharge of 100"</span>;  
                            <span class="hljs-keyword">break</span>;  
                        default:  
                            <span class="hljs-keyword">break</span>;  
                    }  

                    messageBody <span class="hljs-operator">=</span> offer;  
                    topicClient <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> TopicClient(sbConnectionString, sbTopic);  

                    <span class="hljs-keyword">var</span> message <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Message(Encoding.UTF8.GetBytes(messageBody));  
                    Console.WriteLine($<span class="hljs-string">"Message Published: {messageBody}"</span>);  

                    topicClient.SendAsync(message);  

                }  
                <span class="hljs-keyword">catch</span> (Exception ex)  
                {  
                    Console.WriteLine(ex.Message);  
                }  
                finally  
                {  
                    Console.ReadKey();  
                    topicClient.CloseAsync();  
                }  
            }  
        }
</code></pre><ul>
<li>Run the application and select the offer which you would like to publish</li>
<li>You can see the published message 'Message Published…'</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537776322/6OFW55PNC.png" alt="image.png" /></p>
<p>We can see that published message is added in all available subscriptions.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537798624/SvmisxRgw.png" alt="image.png" /></p>
<p><strong>Read message from subscription</strong></p>
<ul>
<li>Create a console application in the Visual Studio</li>
<li>Set variables, one for connection string which you can copy from Shared access policies section and another is topic name; i.e. offers</li>
<li>Create topic client using connection string and queue name</li>
<li>Using topic client, call RegisterMessageHandler which is used to receive messages continuously from the entity. It registers a message handler and begins a new thread to receive messages. This handler is waited on every time a new message is received by the receiver.</li>
<li>Inside ReceiveMessageAsync, call CompleteAsync which completes a message using its lock token and deletes the message from the queue.</li>
</ul>
<pre><code>    class Program  
        {  
            static ISubscriptionClient subscriptionClient;  
            static void Main(<span class="hljs-keyword">string</span>[] args)  
            {  
                <span class="hljs-keyword">string</span> sbConnectionString <span class="hljs-operator">=</span> <span class="hljs-string">"Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMjW9CzPWvA/JGvVvUZ64U21IBI="</span>;  
                <span class="hljs-keyword">string</span> sbTopic <span class="hljs-operator">=</span> <span class="hljs-string">"offers"</span>;  
                <span class="hljs-keyword">string</span> sbSubscription <span class="hljs-operator">=</span> <span class="hljs-string">"akki5677"</span>;  
                <span class="hljs-keyword">try</span>  
                {  
                    subscriptionClient <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> SubscriptionClient(sbConnectionString, sbTopic, sbSubscription);  

                    <span class="hljs-keyword">var</span> messageHandlerOptions <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MessageHandlerOptions(ExceptionReceivedHandler)  
                    {  
                        MaxConcurrentCalls <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
                        AutoComplete <span class="hljs-operator">=</span> <span class="hljs-literal">false</span>  
                    };  
                    subscriptionClient.RegisterMessageHandler(ReceiveMessagesAsync, messageHandlerOptions);  
                }  
                <span class="hljs-keyword">catch</span> (Exception ex)  
                {  
                    Console.WriteLine(ex.Message);  
                }  
                finally  
                {  
                    Console.ReadKey();  
                    subscriptionClient.CloseAsync();  
                }  
            }  

            static async Task ReceiveMessagesAsync(Message message, CancellationToken token)  
            {  
                Console.WriteLine($<span class="hljs-string">"Subscribed message: {Encoding.UTF8.GetString(message.Body)}"</span>);  

                await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);  
            }  

            static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)  
            {  
                Console.WriteLine(exceptionReceivedEventArgs.Exception);  
                <span class="hljs-keyword">return</span> Task.CompletedTask;  
            }  
        }
</code></pre><ul>
<li>Run the application and you can see the previously added message in the subscription.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537929529/uVSZTVyib.png" alt="image.png" /></p>
<p>Now if you closely observe message count for all available subscriptions, one of the subscriptions has a zero message count as we have already read from that subscription and another subscription shows 1 as a message count means we need to publish once and it will be available for all subscriptions and whom so ever is read that only will be deleted and for rest it will be as it is.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631537953618/UAkHsD4g5.png" alt="image.png" /></p>
<ul>
<li>Now run both the applications simultaneously and select the offer which you would like to publish</li>
<li>You can observe that the message will be read by the second application immediately.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538001123/2yJHKD-tE.png" alt="image.png" /></p>
<p>Azure service bus topic is very similar to Azure service bus queue, the difference is queue works on one to one; i.e. one sender and one receiver whereas topic works on one to many; i.e. One publisher and many subscribers.</p>
<p><strong>Note:</strong>
Download complete sample code from  <a target="_blank" href="https://github.com/akshayblevel/Azure-ServiceBus-Topic">here</a> .</p>
]]></content:encoded></item><item><title><![CDATA[Azure Service Bus - Working With Queue In A Real World Scenario]]></title><description><![CDATA[This article explains a real-world business requirement and how Azure Service Bus Queue helps to fulfill the requirement.
Business Requirement
One of the utility bill payments company wants to build an application, which will do the mobile recharge f...]]></description><link>https://dotnetbees.com/azure-service-bus-working-with-queue-in-a-real-world-scenario</link><guid isPermaLink="true">https://dotnetbees.com/azure-service-bus-working-with-queue-in-a-real-world-scenario</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 31 Dec 2021 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1646321643546/l83ZkHRp7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article explains a real-world business requirement and how Azure Service Bus Queue helps to fulfill the requirement.</p>
<p><strong>Business Requirement</strong></p>
<p>One of the utility bill payments company wants to build an application, which will do the mobile recharge for end users. The application should support all the operators which are available in the market. The flow is, the user sends SMS in predefined format and application should parse the message and do the recharge accordingly.</p>
<p>Now, the biggest challenge is the application gets a huge number of recharge requests during the peak hours and is not able to process each request, so the company is looking for something like where all the requests are parked when they come and process one by one.</p>
<p><strong>Azure Service Bus</strong></p>
<p>The company came to know about the Azure Service Bus provided by Azure, so he started exploring Azure Service Bus.</p>
<p>Azure Service Bus supports cloud-based message-oriented middleware technologies like Queue, Topic, and Relay.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538257812/uPo1fHVKO.png" alt="image.png" /></p>
<p>Here in order to meet the business requirement, we will use the queue mechanism where all the requests will be added in the queue and another side queue listener will process the message by reading from the queue.</p>
<p><strong>Queue</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538286030/ARXFB1an6.png" alt="image.png" /></p>
<p>The sender sends the message, adds it into the queue and the receiver processes the message in a FIFO (First In First Out) manner. The benefit of using queue is, it creates decoupling between sender and receiver, means sender and receiver should not be available at the same time while sending the message as messages are stored in a queue. Another benefit is load leveling, which means sender sends messages at a different rate and the receiver can process messages at a different rate, as both are independent in sending and processing.</p>
<p>Now let's see the step by step implementation of the below to design a solution:</p>
<ol>
<li>Create Service Bus Namespace</li>
<li>Create Queue</li>
<li>Add a message in the queue</li>
<li>Read Message from the queue</li>
<li>Scheduled Message</li>
<li>Receive Mode</li>
<li>Abandoned Async</li>
<li>Dead-letter Queue</li>
</ol>
<p><strong>Create Service Bus Namespace</strong></p>
<p>Service bus namespace is a container for all messaging components. One namespace contains multiple queues and topics.</p>
<ul>
<li>Log in to the Azure portal via portal.azure.com</li>
<li>Click on 'Create a resource' from the left navigation pane, click on 'Integration' and then 'Service Bus'.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538459431/TxEYnL4-q.png" alt="image.png" /></p>
<ul>
<li>Enter the proper name for a namespace</li>
<li>Select pricing tier, for demo purpose we have selected Basic</li>
<li>Subscription and Resource group, keep it as it is</li>
<li>Select your desired location and click on 'Create' button</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538523821/66kZ5kN1n.png" alt="image.png" /></p>
<p>Once you create a namespace, you can explore the same from the dashboard where you can find all the details which you have provided while creating a namespace.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538548207/Mmibdzu0V.png" alt="image.png" /></p>
<p><strong>Credentials</strong></p>
<p>Click on 'Shared access policies' from the left panel, click on 'RootManageSharedAccessKey' to explore keys and connection strings which will be used further to connect.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538591150/COGkqED2g.png" alt="image.png" /></p>
<p><strong>Create Queue</strong></p>
<ul>
<li>Click on 'Mobile Recharge' namespace on Dashboard</li>
<li>Click on 'Queues' on the left pane and click on '+Queue' to create new Queue.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538645335/32B6TCGU-.png" alt="image.png" /></p>
<ul>
<li>Enter queue name and click on 'Create' button keeping the rest of the input as it is.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538691986/MaYqmv5lw.png" alt="image.png" /></p>
<ul>
<li>Click on 'Queues' and you will get a list of created queues. You can also find our recently created queue; i.e. recharge.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538718668/Tsl0MZEQvL.png" alt="image.png" /></p>
<p><strong>Add Message in the QUEUE</strong></p>
<ul>
<li>Create a console application in Visual Studio</li>
<li>Set variables, one for connection string which you can copy from Shared access policies section and another is queue name; i.e. recharge</li>
<li>In order to do the recharge, we need a mobile number, amount and operator from user</li>
<li>Concatenate preceding three values separated with a star(*) </li>
<li>Add Microsoft.Azure.ServiceBus from a NuGet package manager</li>
<li>Create queue client using connection string and queue name</li>
<li>Convert string message to Azure Service Bus message</li>
<li>Using queue client, call SendAsync method to add a message in the queue.</li>
<li>Call CloseAsync to close opened connection in finally block.</li>
</ul>
<pre><code>    class Program  
        {  
            static QueueClient queueClient;  
            static void Main(<span class="hljs-keyword">string</span>[] args)  
            {  
                <span class="hljs-keyword">string</span> sbConnectionString <span class="hljs-operator">=</span> <span class="hljs-string">"Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMj/JGvVvUZ64U21IBI="</span>;  
                <span class="hljs-keyword">string</span> sbQueueName <span class="hljs-operator">=</span> <span class="hljs-string">"Recharge"</span>;  

                <span class="hljs-keyword">string</span> messageBody<span class="hljs-operator">=</span><span class="hljs-keyword">string</span>.Empty;  
                <span class="hljs-keyword">try</span>  
                {  
                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  
                    Console.WriteLine(<span class="hljs-string">"Mobile Recharge"</span>);  
                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  
                    Console.WriteLine(<span class="hljs-string">"Operators"</span>);  
                    Console.WriteLine(<span class="hljs-string">"1. Vodafone"</span>);  
                    Console.WriteLine(<span class="hljs-string">"2. Airtel"</span>);  
                    Console.WriteLine(<span class="hljs-string">"3. JIO"</span>);  
                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  

                    Console.WriteLine(<span class="hljs-string">"Operator:"</span>);  
                    <span class="hljs-keyword">string</span> mobileOperator <span class="hljs-operator">=</span> Console.ReadLine();  
                    Console.WriteLine(<span class="hljs-string">"Amount:"</span>);  
                    <span class="hljs-keyword">string</span> amount <span class="hljs-operator">=</span> Console.ReadLine();  
                    Console.WriteLine(<span class="hljs-string">"Mobile:"</span>);  
                    <span class="hljs-keyword">string</span> mobile <span class="hljs-operator">=</span> Console.ReadLine();  

                    Console.WriteLine(<span class="hljs-string">"-------------------------------------------------------"</span>);  

                    switch (mobileOperator)  
                    {  
                        case <span class="hljs-string">"1"</span>:  
                            mobileOperator <span class="hljs-operator">=</span> <span class="hljs-string">"Vodafone"</span>;  
                            <span class="hljs-keyword">break</span>;  
                        case <span class="hljs-string">"2"</span>:  
                            mobileOperator <span class="hljs-operator">=</span> <span class="hljs-string">"Airtel"</span>;  
                            <span class="hljs-keyword">break</span>;  
                        case <span class="hljs-string">"3"</span>:  
                            mobileOperator <span class="hljs-operator">=</span> <span class="hljs-string">"JIO"</span>;  
                            <span class="hljs-keyword">break</span>;  
                        default:  
                            <span class="hljs-keyword">break</span>;  
                    }  

                    messageBody <span class="hljs-operator">=</span> mobileOperator <span class="hljs-operator">+</span> <span class="hljs-string">"*"</span> <span class="hljs-operator">+</span> mobile <span class="hljs-operator">+</span> <span class="hljs-string">"*"</span> <span class="hljs-operator">+</span> amount;  
                    queueClient <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> QueueClient(sbConnectionString, sbQueueName);  

                    <span class="hljs-keyword">var</span> message <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Message(Encoding.UTF8.GetBytes(messageBody));  
                    Console.WriteLine($<span class="hljs-string">"Message Added in Queue: {messageBody}"</span>);  
                    queueClient.SendAsync(message);  


                }  
                <span class="hljs-keyword">catch</span> (Exception ex)  
                {  
                    Console.WriteLine(ex.Message);  
                }  
                finally  
                {  
                    Console.ReadKey();  
                    queueClient.CloseAsync();  
                }  
            }  
        }
</code></pre><ul>
<li>Run the application and provide the required inputs</li>
<li>You can see the message 'Message Added in Queue…'</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538891567/w-7u31j3y.png" alt="image.png" /></p>
<ul>
<li>To check the added message in the portal, explore all the queues</li>
<li>Click on the queue in which we have added the message i.e. 'Recharge'</li>
<li>We can see 'Active message count' as 1</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631538946867/RKSIVW6GP.png" alt="image.png" /></p>
<p><strong>Read Message from QUEUE</strong></p>
<ul>
<li>Create a console application in the Visual Studio</li>
<li>Set variables, one for connection string which you can copy from Shared access policies section and another is queue name; i.e. recharge</li>
<li>Create queue client using connection string and queue name</li>
<li>Using queue client, call RegisterMessageHandler which is used to receive messages continuously from the entity. Registers a message handler and begins a new thread to receive messages. This handler has waited every time a new message is received by the receiver.</li>
<li>Inside ReceiveMessageAsync, call CompleteAsync which completes a message using its lock token and deletes the message from the queue.</li>
</ul>
<pre><code>class Program  
    {  
        static QueueClient queueClient;  
        static void Main(<span class="hljs-keyword">string</span>[] args)  
        {  
            <span class="hljs-keyword">string</span> sbConnectionString <span class="hljs-operator">=</span> <span class="hljs-string">"Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMj/JGvVvUZ64U21IBI="</span>;  
            <span class="hljs-keyword">string</span> sbQueueName <span class="hljs-operator">=</span> <span class="hljs-string">"Recharge"</span>;  

            <span class="hljs-keyword">try</span>  
            {  
                queueClient <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> QueueClient(sbConnectionString, sbQueueName);  

                <span class="hljs-keyword">var</span> messageHandlerOptions <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MessageHandlerOptions(ExceptionReceivedHandler)  
                {  
                    MaxConcurrentCalls <span class="hljs-operator">=</span> <span class="hljs-number">1</span>,  
                    AutoComplete <span class="hljs-operator">=</span> <span class="hljs-literal">false</span>  
                };  
                queueClient.RegisterMessageHandler(ReceiveMessagesAsync, messageHandlerOptions);  
            }  
            <span class="hljs-keyword">catch</span> (Exception ex)  
            {  
                Console.WriteLine(ex.Message);  
            }  
            finally  
            {  
                Console.ReadKey();  
                queueClient.CloseAsync();  
            }  
        }  

        static async Task ReceiveMessagesAsync(Message message, CancellationToken token)  
        {  
            Console.WriteLine($<span class="hljs-string">"Received message: {Encoding.UTF8.GetString(message.Body)}"</span>);  

            await queueClient.CompleteAsync(message.SystemProperties.LockToken);  
        }  

        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)  
        {  
            Console.WriteLine(exceptionReceivedEventArgs.Exception);  
            <span class="hljs-keyword">return</span> Task.CompletedTask;  
        }  
    }
</code></pre><ul>
<li>Run the application and you can see the previously added message in the queue.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539101326/B2fooF3Tw.png" alt="image.png" /></p>
<ul>
<li>Check the queue once again in the portal and you can see the 'Active message count' as zero(0) as it was deleted by CompleteAsync.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539147500/YGmRD6KenL.png" alt="image.png" /></p>
<ul>
<li>Now run both the applications simultaneously and provide the required inputs</li>
<li>You can observe that the message will be read by the second application immediately.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539194796/mp7OBdqjn.png" alt="image.png" /></p>
<p><strong>Scheduled Message</strong>
Now let's tweak the requirement, where we want to do recharge after a specific time, not now. So for this, we have scheduled message facility where you can schedule a message for a specific time. In the demo, we will set it after 5 minutes.</p>
<p>In order to implement this, we need to comment SendSync method and call ScheduleMessageAsync which expects a message and schedule time.</p>
<p>Modify your code as below,</p>
<pre><code>DateTimeOffset scheduleTime <span class="hljs-operator">=</span> DateTime.UtcNow.AddMinutes(<span class="hljs-number">5</span>);  
queueClient.ScheduleMessageAsync(message,scheduleTime);
</code></pre><ul>
<li>Run your application once again</li>
<li>Provide required inputs</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539311057/lCUABXWvh.png" alt="image.png" /></p>
<p>We can observe in the portal that the message is not added in the queue as 'Active message count' is zero (0) only.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539335777/UlE9O_LSF.png" alt="image.png" /></p>
<p>Now wait for 5 minutes and verify once again in a portal. We can see that it's added as 5 minutes have passed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539357814/11zBfz0_K.png" alt="image.png" /></p>
<p>Run the read application and you can get the scheduled message.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539383156/rbx0IJF9V.png" alt="image.png" /></p>
<p><strong>Receive Mode</strong>
In the next step after receiving the message, you need to process that message; i.e. need to do a recharge. Now assume that while processing the message some exception occurs, then we may lose the request completely. For this situation, we have a Receive Mode facility.</p>
<p>You can specify two different modes as Receive Mode:</p>
<ul>
<li>PeekLock</li>
<li>Receive and Delete</li>
</ul>
<p><strong>PeekLock</strong></p>
<p>In this mode, the message won't be deleted until you call CompleteAsync method, so while processing if any exception occurs, we don't lose the message.</p>
<ul>
<li>Run both the applications simultaneously in debug mode.</li>
<li>Provide the required input, and read application shows the added message.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539493423/VZD_gF0H6.png" alt="image.png" /></p>
<p>Let's check the message in the portal, ideally, it was read by read application, so it should not be there in the portal but as Receive Mode is Peeklock, the message will be there.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539516138/3Qk-jICGZ.png" alt="image.png" /></p>
<p>Execute CompleAsync method after processing the message. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539542006/jwkXrK8En.png" alt="image.png" /></p>
<p>We can see in the portal that the message is not available as we have already called CompleteAsync.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539564757/4AiJhOnGG.png" alt="image.png" /></p>
<p><strong>ReceiveAndDelete</strong></p>
<p>In Receive and Delete mode, as soon as the message is read, it will be deleted from the queue.</p>
<ul>
<li>Run both applications simultaneously in debug mode.</li>
<li>Provide the required input and read application shows the added message.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539627109/GMUGgynzt.png" alt="image.png" /></p>
<ul>
<li>Don't execute CompleAsync method, just hold the debug point there only.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539651764/bm70NhEu4-.png" alt="image.png" /></p>
<ul>
<li>Now, verify the message in the portal, ideally, CompleAsync is not called, so the message should be there but as we set ReceiveAndDelete mode, the message is deleted as soon as it was read.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539683438/R8pFp6mjdO.png" alt="image.png" /></p>
<p><strong>AbandonAsync</strong></p>
<p>Now in your application, whenever an exception occurs during processing you want to reprocess the message again. For this, we have the facility of AbandonAsync.</p>
<p>AbandonAsync abandons a Message using a lock token, this will make the message available again for processing.</p>
<p>To verify this we need to throw an exception explicitly from ReceiveMessageAsync and from the catch block call AbandonAsync method.</p>
<pre><code>    static async Task ReceiveMessagesAsync(Message message, CancellationToken token)  
            {  
                <span class="hljs-keyword">try</span>  
                {  
                    Console.WriteLine($<span class="hljs-string">"Received message: {Encoding.UTF8.GetString(message.Body)}"</span>);  

                    <span class="hljs-keyword">int</span> i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;  
                    i<span class="hljs-operator">=</span>i <span class="hljs-operator">/</span> Convert.ToInt32(message);  

                    await queueClient.CompleteAsync(message.SystemProperties.LockToken);  
                }  
                <span class="hljs-keyword">catch</span>(Exception ex)  
                {  
                   await queueClient.AbandonAsync(message.SystemProperties.LockToken);  
                }  
            }
</code></pre><p>Run the application once again and from the read application we can observe that the same message was read 10 times, this means whenever an exception occurs it was available once again to process.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539746584/1Zd8iN1F-.png" alt="image.png" /></p>
<p>You can configure the reprocess count from properties by setting Maximum Delivery Count. Previously it was read 10 times because, by default, Maximum Delivery Count is set to 10.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539771463/pTdL2dw6J.png" alt="image.png" /></p>
<p>Once the 10-time process is over, it is no longer available in the queue, and it will be added in the Dead-letter queue. We can verify the same thing in the portal. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631539797445/4c__QkT5w.png" alt="image.png" /></p>
<p><strong>Dead-letter Queue</strong></p>
<p>Now, in order to read the messages from the Dead-letter queue for analyzing purposes, the same application is used, you just need to change the queue name as below:</p>
<pre><code>  <span class="hljs-keyword">string</span> sbQueueName = <span class="hljs-string">"Recharge/<span class="hljs-subst">$DeadLetterQueue</span>"</span>;
</code></pre><p>Run the application and it will read all messages available in Dead-letter queue.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631540596466/qQC3unrRg3.png" alt="image.png" /></p>
<p>We don't find any messages in Dead-letter queue now.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631540618700/8A9dIom_s.png" alt="image.png" /></p>
<p>In the next article, we will discuss Azure Service Bus - Topic.</p>
<p><strong>Note:</strong>
You can download the complete sample code from  <a target="_blank" href="https://github.com/akshayblevel/Azure-ServiceBus-Queue">here</a> .</p>
]]></content:encoded></item><item><title><![CDATA[Multiple File Upload Sample Using HttpFileCollectionBase in MVC]]></title><description><![CDATA[Let's see the step-by-step implementation:
Create an MVC project from the "Empty" template.
Right-click on "Controllers" and select "Add" >> "Controller...".
Select "MVC 5 Controller - Empty" to add an empty controller.
Click on the "Add" button.
Nam...]]></description><link>https://dotnetbees.com/multiple-file-upload-sample-using-httpfilecollectionbase-in-mvc</link><guid isPermaLink="true">https://dotnetbees.com/multiple-file-upload-sample-using-httpfilecollectionbase-in-mvc</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 31 Dec 2021 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649321362260/uxFUDzbQR.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's see the step-by-step implementation:</p>
<p>Create an MVC project from the "Empty" template.</p>
<p>Right-click on "Controllers" and select "Add" &gt;&gt; "Controller...".</p>
<p>Select "MVC 5 Controller - Empty" to add an empty controller.</p>
<p>Click on the "Add" button.</p>
<p>Name the controller "HomeController".</p>
<p>The Index() action result method will be added.</p>
<p>To add a view, right-click on "Index" and select "Add View...".</p>
<p>Name the view and select "Empty (without model)" as the template. Click on the "Add" button.</p>
<p>We use the form attribute with the post method in our cshtml file. Inside the form attribute we have created a file upload and submit button. As our requirement is to upload multiple files, we need to set attribute multiple=multiple with file upload control.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632252891042/rV1O_D-w-.jpeg" alt="1.jpg" /></p>
<p>Here in the HTTP post method, the uploaded file will be available as an HttpPostedFileBase parameter. HttpPostedFileBase serves as the base class for classes that provide access to individual files that have been uploaded by the client. That means we get only one file in this parameter.</p>
<p>So we use a request object. Using Request.Files we get all the posted files and store them in HttpFileCollectionBase. HttpFileCollectionBase serves as the base class for classes that provide access to files that were uploaded by a client. Once we have a collection of files, we iterate the collection and get each file one by one and assign them to HttpPostedFileBase.</p>
<p>Using HttpPostedFileBase we can have properties like ContentLength, ContentType, FileName and so on. First we get the physical path of our application using Server.MapPath and then save the file inside the images folder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632252905947/mkIpu6wLT.jpeg" alt="2.jpg" /></p>
<p>Now run the project and click on the "Choose File" button. Select the multiple files that you want to upload from your directory structure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632252919741/iVJG4GpgX.jpeg" alt="3.jpg" /></p>
<p>It will show the number of selected files with the "Choose Files" button. Now press the "Upload" button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632252940454/fhDUxNApj.jpeg" alt="4.jpg" /></p>
<p>All the files are uploaded and you can see the files in the browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632252954296/uC4-hWrcg.jpeg" alt="5.jpg" /></p>
<p>We can also check the existence of these files in the images folder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632252968750/xg1Mahjoy.jpeg" alt="6.jpg" /></p>
]]></content:encoded></item><item><title><![CDATA[.NET Core Dependency Injection - One Interface, Multiple Implementations]]></title><description><![CDATA[Consider a scenario where you want to get shopping cart object and you have implemented IShoppingCart Interface. Now, you have multiple options to get the shopping cart like from Database, API, or Cache. Here, we need to implement all these three as ...]]></description><link>https://dotnetbees.com/net-core-dependency-injection-one-interface-multiple-implementations</link><guid isPermaLink="true">https://dotnetbees.com/net-core-dependency-injection-one-interface-multiple-implementations</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 31 Dec 2021 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637058425898/Z1DabGTwd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Consider a scenario where you want to get shopping cart object and you have implemented IShoppingCart Interface. Now, you have multiple options to get the shopping cart like from Database, API, or Cache. Here, we need to implement all these three as concrete implementations for an interface, IShoppingCart. Now, the question is how we can decide which instance is to be instantiated as generally we see one implementation for one interface and add it into service collection for dependency injection. So, let’s see the implementation step by step.</p>
<p>Open Visual Studio and create a new project.</p>
<p>Select the API as the template and click OK.</p>
<p>Create an IShoppingcart Interface having GetCart method.</p>
<pre><code>
    <span class="hljs-keyword">namespace</span> <span class="hljs-title">MultipleImplementation</span>  
    {  
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IShoppingCart</span>  
        {  
            <span class="hljs-function"><span class="hljs-keyword">object</span> <span class="hljs-title">GetCart</span>(<span class="hljs-params"></span>)</span>;  
        }  
    }
</code></pre><p>Implement the GetCart method of IShoppingCart interface in ShoppingCartCache.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">MultipleImplementation</span>  
{  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ShoppingCartCache</span> : <span class="hljs-title">IShoppingCart</span>  
    {  
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">object</span> <span class="hljs-title">GetCart</span>(<span class="hljs-params"></span>)</span>  
        {  
            <span class="hljs-keyword">return</span> <span class="hljs-string">"Cart loaded from cache."</span>;  
        }  
    }  
}
</code></pre><p>Implement the same interface in ShoppingCartDB.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">MultipleImplementation</span>  
{  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ShoppingCartDB</span> : <span class="hljs-title">IShoppingCart</span>  
    {  
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">object</span> <span class="hljs-title">GetCart</span>(<span class="hljs-params"></span>)</span>  
        {  
            <span class="hljs-keyword">return</span> <span class="hljs-string">"Cart loaded from DB"</span>;  
        }  
    }  
}
</code></pre><p>At last, implement the same interface in ShoppingCartAPI.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">MultipleImplementation</span>  
{  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ShoppingCartAPI</span> : <span class="hljs-title">IShoppingCart</span>  
    {  
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">object</span> <span class="hljs-title">GetCart</span>(<span class="hljs-params"></span>)</span>  
        {  
            <span class="hljs-keyword">return</span> <span class="hljs-string">"Cart loaded through API."</span>;  
        }  
    }  
}
</code></pre><p>Now, we need a repository which will internally decide which implementation should be instantiated and called to get the GetCart method from it. So, create IShoppingCartRepository having the GetCart method.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">MultipleImplementation</span>  
{  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IShoppingCartRepository</span>  
    {  
        <span class="hljs-function"><span class="hljs-keyword">object</span> <span class="hljs-title">GetCart</span>(<span class="hljs-params"></span>)</span>;  
    }  
}
</code></pre><p>Create an enum to select the concrete implementation type, i.e, Cache, DB, or API.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">MultipleImplementation</span>  
{  
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Constants</span>  
    {  
    }  

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> CartSource  
    {  
        Cache=<span class="hljs-number">1</span>,  
        DB=<span class="hljs-number">2</span>,  
        API=<span class="hljs-number">3</span>  
    }  
}
</code></pre><p>In the implementation of IShoppingCartRepository, we use constructor injection and we take Func delegate as a parameter. Func delegate expects a string as parameter and IShoppingCart as a return value. So in the GetCart method, you can see that we are using an enum to pass the parameter value which indicates the type of implementation we want to instantiate.</p>
<pre><code><span class="hljs-keyword">using</span> <span class="hljs-title">System</span>;  

namespace MultipleImplementation  
{  
    <span class="hljs-keyword">public</span> class ShoppingCartRepository : IShoppingCartRepository  
    {  
        <span class="hljs-keyword">private</span> readonly Func<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span>, IShoppingCart<span class="hljs-operator">&gt;</span> shoppingCart;  
        <span class="hljs-keyword">public</span> ShoppingCartRepository(Func<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span>, IShoppingCart<span class="hljs-operator">&gt;</span> shoppingCart)  
        {  
            <span class="hljs-built_in">this</span>.shoppingCart <span class="hljs-operator">=</span> shoppingCart;  
        }  

        <span class="hljs-keyword">public</span> object GetCart()  
        {  
            <span class="hljs-keyword">return</span> shoppingCart(CartSource.DB.ToString()).GetCart();  
        }  
    }  
}
</code></pre><p>In the same way, we need to add Func in startup class. First, we add the concrete implementation in service collection and on each request based on the parameter value, we used to get that concrete class.</p>
<pre><code><span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">AspNetCore</span>.<span class="hljs-title">Builder</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">AspNetCore</span>.<span class="hljs-title">Hosting</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">Extensions</span>.<span class="hljs-title">Configuration</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">Microsoft</span>.<span class="hljs-title">Extensions</span>.<span class="hljs-title">DependencyInjection</span>;  
<span class="hljs-keyword">using</span> <span class="hljs-title">System</span>;  

namespace MultipleImplementation  
{  
    <span class="hljs-keyword">public</span> class Startup  
    {  
        <span class="hljs-keyword">public</span> Startup(IConfiguration configuration)  
        {  
            Configuration <span class="hljs-operator">=</span> configuration;  
        }  

        <span class="hljs-keyword">public</span> IConfiguration Configuration { get; }  

        <span class="hljs-keyword">public</span> void ConfigureServices(IServiceCollection services)  
        {  

            services.AddScoped&lt;IShoppingCartRepository, ShoppingCartRepository<span class="hljs-operator">&gt;</span>();  

            services.AddSingleton&lt;ShoppingCartCache<span class="hljs-operator">&gt;</span>();  
            services.AddSingleton&lt;ShoppingCartDB<span class="hljs-operator">&gt;</span>();  
            services.AddSingleton&lt;ShoppingCartAPI<span class="hljs-operator">&gt;</span>();  

            services.AddTransient&lt;Func<span class="hljs-operator">&lt;</span><span class="hljs-keyword">string</span>, IShoppingCart<span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span>(serviceProvider <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> key <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>  
            {  
                switch (key)  
                {  
                    case <span class="hljs-string">"API"</span>:  
                        <span class="hljs-keyword">return</span> serviceProvider.GetService&lt;ShoppingCartAPI<span class="hljs-operator">&gt;</span>();  
                    case <span class="hljs-string">"DB"</span>:  
                        <span class="hljs-keyword">return</span> serviceProvider.GetService&lt;ShoppingCartDB<span class="hljs-operator">&gt;</span>();  
                    default:  
                        <span class="hljs-keyword">return</span> serviceProvider.GetService&lt;ShoppingCartCache<span class="hljs-operator">&gt;</span>();  
                }  
            });  

            services.AddMvc();  
        }  

        <span class="hljs-keyword">public</span> void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            <span class="hljs-keyword">if</span> (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  

            app.UseMvc();  
        }  
    }  
}
</code></pre><p>You can download the sample from <a target="_blank" href="https://github.com/akshayblevel/Core-DI-MultipleImplementation">here.</a></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Extension Method]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        String.prototype.getLength = function () {
            return this.length;
        }

        var str = "Akshay...]]></description><link>https://dotnetbees.com/javascript-extension-method</link><guid isPermaLink="true">https://dotnetbees.com/javascript-extension-method</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:46:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306432589/Kq10VjFwv.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        String.prototype.getLength <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.<span class="hljs-built_in">length</span>;
        }

        <span class="hljs-keyword">var</span> str <span class="hljs-operator">=</span> <span class="hljs-string">"Akshay Patel"</span>;

        alert(str.getLength());
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070743669/bF4ywJ09s.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Inheritance]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        function Computer(processor)
        {
            this.processor = processor;
        }

        Computer.prot...]]></description><link>https://dotnetbees.com/javascript-inheritance</link><guid isPermaLink="true">https://dotnetbees.com/javascript-inheritance</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:44:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306543404/yGZWWaZAB.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Computer</span>(<span class="hljs-params">processor</span>)
        </span>{
            <span class="hljs-built_in">this</span>.processor <span class="hljs-operator">=</span> processor;
        }

        Computer.prototype.assemble <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            alert(<span class="hljs-built_in">this</span>.processor <span class="hljs-operator">+</span> <span class="hljs-string">" - computer is assembled"</span>);
        };

        <span class="hljs-keyword">var</span> pc <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Computer(<span class="hljs-string">"i7"</span>);
        pc.assemble();

        <span class="hljs-keyword">var</span> pcTest <span class="hljs-operator">=</span> pc instanceof Computer;
        alert(pcTest);
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070641976/f2x4OewmX.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Static Member]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        function personalDetail(fname, lname) {
            this.fname = fname;
            this.lname = lname;
       ...]]></description><link>https://dotnetbees.com/javascript-static-member</link><guid isPermaLink="true">https://dotnetbees.com/javascript-static-member</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:42:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306557334/9uuE3IGoq.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">personalDetail</span>(<span class="hljs-params">fname, lname</span>) </span>{
            <span class="hljs-built_in">this</span>.fname <span class="hljs-operator">=</span> fname;
            <span class="hljs-built_in">this</span>.lname <span class="hljs-operator">=</span> lname;
        }

        personalDetail.email <span class="hljs-operator">=</span> <span class="hljs-string">"akshayblevel@gmail.com"</span>;

        <span class="hljs-keyword">var</span> pDetail <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> personalDetail();

        <span class="hljs-keyword">var</span> email <span class="hljs-operator">=</span> pDetail.email; <span class="hljs-comment">// Can't Access</span>
        email <span class="hljs-operator">=</span> personalDetail.email;

        alert(email);
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070525003/_ukUnsGCa.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Properties]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        function personalDetail(fname, lname) {
            var _fname = fname;
            var _lname = lname;

      ...]]></description><link>https://dotnetbees.com/javascript-properties</link><guid isPermaLink="true">https://dotnetbees.com/javascript-properties</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:40:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306611706/Eja1-SDRL.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">personalDetail</span>(<span class="hljs-params">fname, lname</span>) </span>{
            <span class="hljs-keyword">var</span> _fname <span class="hljs-operator">=</span> fname;
            <span class="hljs-keyword">var</span> _lname <span class="hljs-operator">=</span> lname;

            Object.defineProperty(<span class="hljs-built_in">this</span>, <span class="hljs-string">"fname"</span>,
                {
                    get: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> _fname; },
                    set: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{ _fname <span class="hljs-operator">=</span> value; }
                }
            );

            Object.defineProperty(<span class="hljs-built_in">this</span>,<span class="hljs-string">"lname"</span>,
                {
                    get: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> _lname; },
                    set: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{ _lname <span class="hljs-operator">=</span> value; }
                }
           );
        }


        <span class="hljs-keyword">var</span> pDetail <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> personalDetail(<span class="hljs-string">"Akshay"</span>, <span class="hljs-string">"Patel"</span>);

        <span class="hljs-keyword">var</span> fname <span class="hljs-operator">=</span> pDetail.fname;

        alert(fname);
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070402514/pVFld5UMZ.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Class]]></title><description><![CDATA[There is nothing like class in javascript but we can create something like that
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        function personalDetail(fname,l...]]></description><link>https://dotnetbees.com/javascript-class</link><guid isPermaLink="true">https://dotnetbees.com/javascript-class</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:38:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306622536/TrmygWwro.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There is nothing like class in javascript but we can create something like that</p>
<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">personalDetail</span>(<span class="hljs-params">fname,lname,email</span>)
        </span>{
            <span class="hljs-built_in">this</span>.fname <span class="hljs-operator">=</span> fname;
            <span class="hljs-built_in">this</span>.lname <span class="hljs-operator">=</span> lname;
            <span class="hljs-built_in">this</span>.email <span class="hljs-operator">=</span> email;
        }

        <span class="hljs-keyword">var</span> pDetail <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> personalDetail(<span class="hljs-string">"Akshay"</span>, <span class="hljs-string">"Patel"</span>, <span class="hljs-string">"akshayblevel@gmail.com"</span>);

        <span class="hljs-keyword">var</span> name <span class="hljs-operator">=</span> pDetail.fname <span class="hljs-operator">+</span> <span class="hljs-string">" "</span> <span class="hljs-operator">+</span> pDetail.lname;

        alert(name);
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070248688/P0sVkrXDa.png" alt="image.png" /></p>
<p><strong>Member Function</strong></p>
<pre><code>Add following code snippet inside <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">at</span> <span class="hljs-title">last</span>.
<span class="hljs-title"><span class="hljs-built_in">this</span></span>.<span class="hljs-title">printDetail</span> = <span class="hljs-title"><span class="hljs-keyword">function</span></span> (<span class="hljs-params">detail</span>) </span>{
                alert(detail);
            }
Add following line of code at last inside script 
pDetail.printDetail(name <span class="hljs-operator">+</span> <span class="hljs-string">"\n"</span> <span class="hljs-operator">+</span> pDetail.email);
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070296753/ZC1M4enhA.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Dynamic Objects]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">

        //Object Creation
        var personalDetail = {
            fname: "Akshay",
            lname: "Patel",
    ...]]></description><link>https://dotnetbees.com/javascript-dynamic-objects</link><guid isPermaLink="true">https://dotnetbees.com/javascript-dynamic-objects</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:35:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306761836/n2b9fRupf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>

        <span class="hljs-comment">//Object Creation</span>
        <span class="hljs-keyword">var</span> personalDetail <span class="hljs-operator">=</span> {
            fname: <span class="hljs-string">"Akshay"</span>,
            lname: <span class="hljs-string">"Patel"</span>,
            <span class="hljs-string">"registered email"</span>:<span class="hljs-string">"akshayblevel@gmail.com"</span>,
            <span class="hljs-keyword">address</span>:
                {
                    Add1: <span class="hljs-string">"Old Padra Road"</span>,
                    Add2: <span class="hljs-string">"Diwalipura"</span>,
                    City: <span class="hljs-string">"Vadodara"</span>,
                    State: <span class="hljs-string">"Gujarat"</span>,
                    Pin: <span class="hljs-string">"390020"</span>
                }
        };

        <span class="hljs-comment">//Object Access</span>

        <span class="hljs-comment">//Dot Pattern</span>
        <span class="hljs-keyword">var</span> fname <span class="hljs-operator">=</span> personalDetail.fname;

        <span class="hljs-comment">//Bracket Pattern</span>
        <span class="hljs-keyword">var</span> lname <span class="hljs-operator">=</span> personalDetail[<span class="hljs-string">"lname"</span>];

        <span class="hljs-keyword">var</span> registeredEmail <span class="hljs-operator">=</span> personalDetail[<span class="hljs-string">"registered email"</span>];

        <span class="hljs-comment">//Pattern 1</span>
        <span class="hljs-keyword">var</span> <span class="hljs-keyword">address</span> <span class="hljs-operator">=</span> personalDetail.<span class="hljs-built_in">address</span>;
        <span class="hljs-keyword">var</span> city <span class="hljs-operator">=</span> <span class="hljs-keyword">address</span>.City;

        <span class="hljs-comment">//Pattern 2</span>
        <span class="hljs-keyword">var</span> state <span class="hljs-operator">=</span> personalDetail.<span class="hljs-built_in">address</span>.State;

        alert(fname <span class="hljs-operator">+</span> <span class="hljs-string">" "</span> <span class="hljs-operator">+</span> lname <span class="hljs-operator">+</span> <span class="hljs-string">" \n"</span> <span class="hljs-operator">+</span> registeredEmail <span class="hljs-operator">+</span> <span class="hljs-string">" \n"</span> <span class="hljs-operator">+</span> city <span class="hljs-operator">+</span> <span class="hljs-string">" "</span> <span class="hljs-operator">+</span> state);
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069978322/P-cQ7jvGK.png" alt="image.png" /></p>
<p><strong>Add members on the fly in the preceding object</strong> </p>
<pre><code>personalDetail.mobile <span class="hljs-operator">=</span> <span class="hljs-string">"09769496026"</span>;

       alert(personalDetail.mobile);
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070023230/Qx-g83Dw1.png" alt="image.png" /></p>
<p><strong>Enumerating Members</strong></p>
<pre><code><span class="hljs-selector-tag">for</span>(var member in personalDetail)
        {
            <span class="hljs-selector-tag">alert</span>(member);                  <span class="hljs-comment">//Member Name</span>
            <span class="hljs-selector-tag">alert</span>(personalDetail[member]);  <span class="hljs-comment">//Member value</span>
        }
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070059186/dG1TStMKY.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070064079/O83HXJdgq.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070070622/U0-UpdoFd.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633070076986/F-FGeWiiP.png" alt="image.png" />
and so on…</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Arrays]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        var color = [];

        color[0] = "Red";
        color[1] = "Blue";
        color[2] = "Green";

        aler...]]></description><link>https://dotnetbees.com/javascript-arrays</link><guid isPermaLink="true">https://dotnetbees.com/javascript-arrays</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:31:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306769799/Z1sLZIgPq.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-keyword">var</span> color <span class="hljs-operator">=</span> [];

        color[<span class="hljs-number">0</span>] <span class="hljs-operator">=</span> <span class="hljs-string">"Red"</span>;
        color[<span class="hljs-number">1</span>] <span class="hljs-operator">=</span> <span class="hljs-string">"Blue"</span>;
        color[<span class="hljs-number">2</span>] <span class="hljs-operator">=</span> <span class="hljs-string">"Green"</span>;

        alert(<span class="hljs-string">"You choose :"</span> <span class="hljs-operator">+</span> color[<span class="hljs-number">1</span>]);
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069745069/zims428CN.png" alt="image.png" /></p>
<p><strong>Another Pattern</strong></p>
<pre><code><span class="hljs-keyword">var</span> color <span class="hljs-operator">=</span> [<span class="hljs-string">"Red"</span>, <span class="hljs-string">"Green"</span>, <span class="hljs-string">"Blue"</span>];

alert(<span class="hljs-string">"You choose :"</span> <span class="hljs-operator">+</span> color[<span class="hljs-number">1</span>]);
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069774129/lUfYqL6Wy.png" alt="image.png" /></p>
<p><strong>Another Example</strong></p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addColor</span>(<span class="hljs-params"></span>)
        </span>{
            <span class="hljs-keyword">var</span> temp <span class="hljs-operator">=</span> <span class="hljs-string">""</span>;

            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span> arguments.<span class="hljs-built_in">length</span>; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>) {
                temp <span class="hljs-operator">+</span><span class="hljs-operator">=</span> arguments[i] <span class="hljs-operator">+</span> <span class="hljs-string">" "</span>;
            }

            <span class="hljs-keyword">return</span> temp;
        }

        <span class="hljs-keyword">var</span> colorList <span class="hljs-operator">=</span> addColor(<span class="hljs-string">"Red"</span>, <span class="hljs-string">"Green"</span>, <span class="hljs-string">"Blue"</span>);

        alert(colorList);
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069820861/1HtDa_ODQ.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript For loop]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        for (var i = 0; i < 5; i++) 
        {
            alert("Akshay " + i);
        }
    </script>
</body>
</html...]]></description><link>https://dotnetbees.com/javascript-for-loop</link><guid isPermaLink="true">https://dotnetbees.com/javascript-for-loop</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:27:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306777376/95W542tdA.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069550807/sqoTOrCeV.png" alt="image.png" /></p>
<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span> <span class="hljs-number">5</span>; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>) 
        {
            alert(<span class="hljs-string">"Akshay "</span> <span class="hljs-operator">+</span> i);
        }
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069580230/392HdJGoK.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069586852/ojQfj-92s.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069594335/73Qd5g9Nh.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069606985/rvs1W81bt.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069616080/n3aaIkfTU.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Switch]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        var i = prompt("Enter Month Number","");

        switch (Number(i)) {
            case 1:
                aler...]]></description><link>https://dotnetbees.com/javascript-switch</link><guid isPermaLink="true">https://dotnetbees.com/javascript-switch</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:24:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306784549/NVIWg2-a9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.w3.org/1999/xhtml"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"javascript"</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">var</span> i = prompt(<span class="hljs-string">"Enter Month Number"</span>,<span class="hljs-string">""</span>);

        <span class="hljs-keyword">switch</span> (<span class="hljs-built_in">Number</span>(i)) {
            <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
                alert(<span class="hljs-string">"January"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
                alert(<span class="hljs-string">"February"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
                alert(<span class="hljs-string">"March"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">4</span>:
                alert(<span class="hljs-string">"April"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">5</span>:
                alert(<span class="hljs-string">"May"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">6</span>:
                alert(<span class="hljs-string">"June"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">7</span>:
                alert(<span class="hljs-string">"July"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">8</span>:
                alert(<span class="hljs-string">"August"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">9</span>:
                alert(<span class="hljs-string">"September"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">10</span>:
                alert(<span class="hljs-string">"October"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">11</span>:
                alert(<span class="hljs-string">"November"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-number">12</span>:
                alert(<span class="hljs-string">"December"</span>);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                alert(<span class="hljs-string">"Unknown"</span>);
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069454363/tkYTtBFqO.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069464821/p1wmRNSAC.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Confirm Box]]></title><description><![CDATA[Confirm box is used to get confirmation from the user.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        var input = confirm("Do you want to proceed?");
        ...]]></description><link>https://dotnetbees.com/javascript-confirm-box</link><guid isPermaLink="true">https://dotnetbees.com/javascript-confirm-box</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 06:22:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306882443/uODFNwMfl.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Confirm box is used to get confirmation from the user.</p>
<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-keyword">var</span> input <span class="hljs-operator">=</span> confirm(<span class="hljs-string">"Do you want to proceed?"</span>);
        <span class="hljs-keyword">if</span> (input <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-literal">true</span>)
        {
            alert(<span class="hljs-string">"You pressed OK!"</span>);
        }
        <span class="hljs-keyword">else</span>
        {
            alert(<span class="hljs-string">"You pressed Cancel!"</span>);
        }
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069325900/jUPvzBYoD.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633069346590/6RqPjL1v2.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript If Else]]></title><description><![CDATA[<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script id="javascript">
        var i = prompt("Enter Number","");

        if(Number(i)%2 === 0)
          {
            alert("Even");
      ...]]></description><link>https://dotnetbees.com/javascript-if-else</link><guid isPermaLink="true">https://dotnetbees.com/javascript-if-else</guid><dc:creator><![CDATA[Akshaykumar Patel]]></dc:creator><pubDate>Fri, 01 Oct 2021 04:19:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649306889871/zpxb8CGhC.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>title<span class="hljs-operator">&gt;</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>title<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>script id<span class="hljs-operator">=</span><span class="hljs-string">"javascript"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-keyword">var</span> i <span class="hljs-operator">=</span> prompt(<span class="hljs-string">"Enter Number"</span>,<span class="hljs-string">""</span>);

        <span class="hljs-keyword">if</span>(Number(i)<span class="hljs-operator">%</span><span class="hljs-number">2</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>)
          {
            alert(<span class="hljs-string">"Even"</span>);
          }
        <span class="hljs-keyword">else</span>
          {
            alert(<span class="hljs-string">"Odd"</span>);
          }
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633061911712/_c-WVtqwF.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633061924263/9EzQrwjdl.png" alt="image.png" /></p>
]]></content:encoded></item></channel></rss>