Search This Blog

Tuesday, July 30, 2019

Autofac

Example:

The basic pattern for integrating Autofac into your application is:
  • Structure your app with inversion of control (IoC) in mind.
  • Add Autofac references.
  • At application startup…
  • Create a ContainerBuilder.
  • Register components.
  • Build the container and store it for later use.
  • During application execution…
  • Create a lifetime scope from the container.
  • Use the lifetime scope to resolve instances of the components.

using Autofac;

using System;


namespace AutofacDemo
{
    class Program
    {
        private static IContainer Container { get; set; }
        static void Main(string[] args)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Output>().As<IOutput>();
            builder.RegisterType<DateWriter>().As<IDateWriter>();
            //New Date Class Register With Date Interface
            // Override Date Writer method with New Date Writer Method
            builder.RegisterType<NewDateWriter>().As<IDateWriter>();
            Container = builder.Build();

            WriteDate();

            Console.ReadLine();
        }

        private static void WriteDate()
        {
            using (var scope = Container.BeginLifetimeScope())
            {
                var writer = scope.Resolve<IDateWriter>();
                writer.WriteDate();
            }
        }
    }

    public interface IOutput
    {
        void Write(string content);
    }

    public class Output : IOutput
    {
        public void Write(string content)
        {
            Console.WriteLine(content);
        }
    }

    public interface IDateWriter
    {
        void WriteDate();
    }

    public class DateWriter : IDateWriter
    {
        private IOutput _output;
        public DateWriter(IOutput output)
        {
            _output = output;
        }
        public void WriteDate()
        {
            _output.Write(DateTime.Today.ToShortDateString());
        }
    }

    public class NewDateWriter : IDateWriter
    {
        private IOutput _output;
        public NewDateWriter(IOutput output)
        {
            _output = output;
        }
        public void WriteDate()
        {
            _output.Write(DateTime.Today.AddDays(1).ToShortDateString());
        }
    }
}


Add Autofac Reference from Nuget 







Thursday, June 20, 2019

Generics

Generics allow us to design classes and methods decoupled from the data type.
Name Space: System.Collections.Generic

Example: Generic Method

using System;

namespace CSharpPracktice
{
    public class Generics
    {
        public bool AreEqual<Type>(Type value1, Type value2)
        {
            return value1.Equals(value2);
        }
       
    }

    public class GenericsCaller
    {
        public void Demo()
        {
            Generics generics = new Generics();
            bool result = generics.AreEqual<string>("20", "20");

            if (result)
                Console.WriteLine("Equal");
            else
                Console.WriteLine("Not Equal");
        }
    }
}

Example: Generic Class

using System;

namespace CSharpPracktice
{
    public class Generics<Type>
    {
        public bool AreEqual(Type value1, Type value2)
        {
            return value1.Equals(value2);
        }
       
    }

    public class GenericsCaller
    {
        public void Demo()
        {
            Generics<string> generics = new Generics<string>();
            bool result = generics.AreEqual("20", "20");

            if (result)
                Console.WriteLine("Equal");
            else
                Console.WriteLine("Not Equal");
        }
    }
}

Friday, June 14, 2019

Publish Subscriber Pattern

Publish Subscriber Pattern (Observer Design Pattern)

  • The Publisher/Subscriber pattern is one of the variations of the Observer designer pattern
  • A publisher publishes a message and there are one or more Subscribers who capture the published message.
  • Publishers broadcast messages, with no knowledge of the subscribers.
  • Subscribers ‘listen’ out for messages regarding topic/categories that they are interested in without any knowledge of who the publishers are.
  • The event bus transfers the messages from the publishers to the subscribers.
  • Each subscriber only receives a subset of the messages that have been sent by the publisher, they only receive the message topics or categories they have subscribed to.

Event Bus knows what topic each subscriber is subscribed to. The event bus will filter messages based on topic and send the messages to subscribers that are subscribed to the topic of the message. The publishers are responsible for defining the topics of their messages.



To understand this consider a real-life scenario where Mobile operators are sending messages to their customers.
 

Thursday, June 13, 2019

Callback

Callback: (Opposite to synchronous process)

Function that will be called when a process is done executing a specific task.
Usage is usually in asynchronous logic.

Example in simple term

Synchronous Process:

Customer go to shopkeeper and order to customize a boot. Shopkeeper takes some time to customize it and rerun it back to the customer. Customer wait till the process and when customer get back the customized shoes it gifted to his neighbor. This complete process is the simple example of synchronous process as customer has to wait till the process of shoe customization not done by the shopkeeper.

Asynchronous Process (Callback):

Customer go to shopkeeper and order to customize a boot. Shopkeeper told to the customer that it will takes some time to customize it. Customer said that I do not want to wait for the process. Take your time and when process for customization will be done then please handover the shoes to my neighbor, I do not want to wait for the process to accomplished. Shopkeeper said OK sure. Customer go back. Shopkeeper customized the shoe which takes some time and once done shopkeeper handover the shoes to the neighbor. This process is the example of asynchronous process as customer do not have to wait till the process was executing and this is also example of callback as once process of customization has been done, shoes was handover to the neighbor by the shopkeeper, which was to be done by customer in the synchronized process.

Example:


    public class CallbackDemo1
    {
        public delegate void DelegateSumOfNumbers(int x);

        public void PrintSumOfNumbers(int num)
        {
            Console.WriteLine("Sum of numbers is " + num);
        }

        public void Demo()
        {
            int num = 5;

            DelegateSumOfNumbers callBackSum = new DelegateSumOfNumbers(PrintSumOfNumbers);
            InnerClassForSum innerClassForSum = new InnerClassForSum(num, callBackSum);

            innerClassForSum.computeSum();
        }

        public class InnerClassForSum
        {
            private int number;
            private DelegateSumOfNumbers _callBackSum;
            public InnerClassForSum(int num, DelegateSumOfNumbers callBackSum)
            {
                number = num;
                _callBackSum = callBackSum;
            }
            public void computeSum()
            {
                int sum = 0;
                for (int i = 0; i <= number; i++)
                {
                    sum += i;
                }

                _callBackSum(sum);
            }
        }
    }

Wednesday, June 12, 2019

Delegate

Prerequisite:

  1. Type Safe: Can not move one data type to other data type. Type safety means preventing type errors. Type error happens when unknowingly developer assigns one data type to other causing bugs. In C# you can not assign one type value to another type value. C# is type safe, JavaScript is not type safe.
  2. Conversion: Converts from one data type to other data type using the convert class.
  3. Casting: Converts from one data type to other data type by defining the data type.
  4. Implicit Casting: No need to define to cast from where to where. No data loss.
  5. Explicit Casting: Need to define to cast from where to where. Data loss can happen.
  6. Reference Type: Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.
Delegate:

  • Type safe function pointer.
  • Just like class and string, Delegate is also reference type.
  • Representative for the communication between two parties.
  • Real world use is to callback and do the data communication.


Example-1:

 public class DelegateDemo
    {

        public delegate void DelegateName1();
        public delegate int DelegateName2();
        public delegate bool DelegateName3();
        public delegate bool DelegateName4(int x);

        public void method1()
        {
            Console.WriteLine("Method1 called.");
        }

        public int method2()
        {
            Console.WriteLine("Method2 called.");
            return 0;
        }

        private bool method3()
        {
            Console.WriteLine("Method3 called.");
            return false;
        }

        private bool method4(int x)
        {
            Console.WriteLine("Method4 called.");
            return false;
        }

        public void method5()
        {
            Console.WriteLine("Method5 called.");
        }

        public void Demo()
        {
            // calling methods directly
            method1();
            method2();
            method3();
            method5();

            // calling methods using reference i.e. delegate
            Console.WriteLine("Calling from delegate");
            DelegateName1 delegateName1 = new DelegateName1(method1);
            delegateName1();
            delegateName1.Invoke();

            delegateName1 += method5;
            delegateName1();

            DelegateName2 delegateName2 = new DelegateName2(method2);
            DelegateName3 delegateName3 = new DelegateName3(method3);
            DelegateName4 delegateName4 = new DelegateName4(method4);

            delegateName2();
            delegateName3();
            delegateName4(0);
        }

    }

Output:



Example-2:

Business Class

public class DelegateDemoBusinessClass
    {
        public delegate void DelGetCalculatedValue(int x, int y);

        private int _x, _y;
        private DelGetCalculatedValue _delegateObject;// = new DelGetCalculatedValue(getCalculatedValue);

        public DelegateDemoBusinessClass(int x, int y, DelGetCalculatedValue getCalculatedValue)
        {
            _x = x;
            _y = y;
            _delegateObject = this.getCalculatedValue;
        }
        public void getCalculatedValue(int x, int y)
        {
            _delegateObject(x, y);
        }
    }

User (Caller) Class

public class DelegateDemoCallerClass
    {
        enum typeOperation { Addition = 0, Substraction = 1, Multiplication = 2, Division = 3 };
        public static void Demo()
        {
            int x = 20, y = 10, operationChoice = 3;
            DelegateDemoBusinessClass.DelGetCalculatedValue getCalculated;

            if (operationChoice == Convert.ToInt32(typeOperation.Addition))
            {
                getCalculated = myAdd;
            }
            else if (operationChoice == Convert.ToInt32(typeOperation.Substraction))
            {
                getCalculated = mySub;
            }
            else if (operationChoice == Convert.ToInt32(typeOperation.Multiplication))
            {
                getCalculated = myMul;
            }
            else
            {
                getCalculated = myDiv;
            }

            DelegateDemoBusinessClass demobusinessclass = new DelegateDemoBusinessClass(x, y, getCalculated);

            getCalculated(x, y);

        }

        public static void myAdd(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public static void mySub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
        public static void myMul(int x, int y)
        {
            Console.WriteLine(x * y);
        }
        public static void myDiv(int x, int y)
        {
            Console.WriteLine(x / y);
        }
    }


Multicast Delegate:

  • That has references to more than one function.
  • Two approaches to create multicast delegate.
  • + or += to register a method with the delegate
  • - or -= to un-register a method with the delete
  • Invokes the methods in the invocation list, the the same order in which they are added.
  • If the delegate has a return type other than void and if the delegate is a multicast delegate, only the value of the last invoked method will be returned.
  • If the delegate has an out parameter, the value of the output parameter, will be the value assigned by the last method.
  • Usage: Observer design pattern.

Monday, February 11, 2019

JavaScript

Window Popup

alert("Hello! I am an alert box!")


Get Element By ID

document.getElementById('demo')// demo is the id of element
// Assign some value
document.getElementById('demo').innerHTML = Date();
document.getElementById('demo1').innerHTML = 'Magic'
// Change Font Size
document.getElementById('demo2').style.fontSize='35px'

Stop execution of debugging at certain point

debugger;

Hide 

document.getElementById('demo1').style.display = 'none'

Display

document.getElementById('demo1').style.display = 'block'

Write in various form

document.write("This is document.write");
document.write("<br>");
document.write(10 * 5);
window.alert("This is window.alert");
console.log("this message is coming from console.log");

Function

//Accessing a function without () will return the function definition instead of the function result:

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;

Calling function

<input type="button" value="button1" onClick="myFunction()"/>
var text = "The temperature is " + toCelsius(77) + " Celsius";

Object

var car = {type:"Fiat", model:"500", color:"white"};

var person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

//The name:values pairs in JavaScript objects are called properties:


Accessing Object Properties

objectName.propertyName
//or
objectName["propertyName"]


Variable Declaration
// Simple string
var car = "Fiat"


The this Keyword

In a function definition, this refers to the "owner" of the function.
In other words, this.firstName means the firstName property of this object.

fullName : function() {
    return this.firstName + " " + this.lastName;
  }
 
<button onclick="this.innerHTML = Date()">The time is?</button>

 
//A method is a function stored as a property.

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};


String Operations

Length

txt.length;

Escape character

The backslash (\) escape character turns special characters into string characters
var x = "We are the so-called \"Vikings\" from the north.";

More
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator

Break Line string

var txt = "Hello \
Dolly!";

var txt = "Hello " +
"Dolly!";

var x = "John";
var y = new String("John");

// typeof x will return string
// typeof y will return object

Don't create strings as objects. It slows down execution speed.

String Index

str.indexOf("locate");
str.lastIndexOf("locate");

Both indexOf(), and lastIndexOf() return -1 if the text is not found.
Both methods accept a second parameter as the starting position for the search:

str.indexOf("locate", 15);

String Search

The search() method searches a string for a specified value and returns the position of the match:
str.search("locate");

The search() method cannot take a second start position argument.
The indexOf() method cannot take powerful search values (regular expressions).

String other operations

slice(start, end)
substring(start, end)
substr(start, length)
substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12)
document.getElementById("demo").innerHTML = res;
</script>

output:
Banana, Kiwi

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(7);
document.getElementById("demo").innerHTML = res;
</script>

output:
Banana, Kiwi

var x = 100 / "Apple";
isNaN(x);

Output:
true

-----

String Equal

When using the == operator, equal strings are equal:

When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value.

var x = 500;           
var y = new Number(500);
// (x == y) is true because x and y have equal values
// (x === y) is false because x and y have different types


toFixed()

returns a string, with the number written with a specified number of decimals:

var x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000

toPrecision()

returns a string, with a number written with a specified length:

var x = 9.656;
x.toPrecision();        // returns 9.656
x.toPrecision(2);       // returns 9.7
x.toPrecision(4);       // returns 9.656
x.toPrecision(6);       // returns 9.65600

valueOf()

returns a number as a number.

var x = 123;
x.valueOf();            // returns 123 from variable x
(123).valueOf();        // returns 123 from literal 123
(100 + 23).valueOf();   // returns 123 from expression 100 + 23

Array

var cars = ["Saab", "Volvo", "BMW"];

var cars = [
  "Saab",
  "Volvo",
  "BMW"
];

var cars = new Array("Saab", "Volvo", "BMW");

Array Vs Object

Arrays use numbers to access its "elements". In this example, person[0] returns John
var person = ["John", "Doe", 46];

Objects use names to access its "members". In this example, person.firstName returns John
var person = {firstName:"John", lastName:"Doe", age:46};

In JavaScript, arrays use numbered indexes. 
In JavaScript, objects use named indexes.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;   // the length of fruits is 4

fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];//Accessing the First Array Element
var last = fruits[fruits.length - 1];//Accessing the Last Array Element

Looping Array Elements

var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];

text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
  text += "<li>" + value + "</li>";
}

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");    // adds a new element (Lemon) to fruits

JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes. 

----

var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
document.getElementById("demo1").innerHTML = fruits.join(" * ");

output:
Banana,Orange,Apple,Mango
Banana * Orange * Apple * Mango

The pop, push, shift, unshift

method removes the last element from an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();              // Removes the last element ("Mango") from fruits

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop();      // the value of x is "Mango"

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");       //  Adds a new element ("Kiwi") to fruits

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi");   //  the value of x is 5

The shift() method removes the first array element and "shifts" all other elements to a lower index.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();            // Removes the first element "Banana" from fruits

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift();    // the value of x is "Banana"

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");    // Adds a new element "Lemon" to fruits

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");    // Returns 5

----

The length property provides an easy way to append a new element to an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";          // Appends "Kiwi" to fruits


Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];           // Changes the first element in fruits to undefined

Using delete may leave undefined holes in the array. Use pop() or shift() instead.

The splice()

method can be used to add new items to an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");

The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
The splice() method returns an array with the deleted items:

String concat

var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys);   // Concatenates (joins) myGirls and myBoys

var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3);   // Concatenates arr1 with arr2 and arr3

var arr1 = ["Cecilie", "Lone"];
var myChildren = arr1.concat(["Emil", "Tobias", "Linus"]);


The slice, sort, referese()

method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();        // First sort the elements of fruits
fruits.reverse();     // Then reverse the order of the elements

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return a - b}); //Ascending
points.sort(function(a, b){return a - b}); //Descending

Saturday, January 26, 2019

Static

Static keyword has different role in different places for C#. When we declare static that means only single copy will be generate.

Static container can only contains static members


It is used in below places-
  • Class
  • Method
  • Field
  • Properties
  • Constructor


Static Class

  • Only contain all static members like static methods, static fields, static properties and static constructor.
  • Any instance or non-static member can not be there in the Static Class.
  • If we need to create all the members as static then we can create static class.
  • Can not create instance of such class.
  • Sealed.
  • Cannot contain Instance Constructors




Static Methods

  • Only contain all static fields
  • Non-static fields are not allowed in static methods
  • Method can be access using class only, no instance is needed or can access.
  • Single copy of static method will be shared among all the instances.



Static Fields


  • Single copy of fields/variables get created and shared among all the instances.
  • If static variable value has been change using one instance then all other instance will get that changed value.

Static Property

  • Can be access using class only.
  • Using instance it can not be access.

Static Constructor


  • Access modifier are not allowed.
  • Static Constructor as it(class constructor) execute prior to any other constructor (instance constructor).
  • Can instantiate value of static fields only.
  • Non-Static fields is not allowed within the scope.



More About Static:


  • Static methods are not allowed in the interface.
  • Access modifiers are not allowed in the interface and static constructor.
  • Static class can't be inherit from interface/class/static class.
  • Static class can only be inherit from object. ??
  • Inheritance from static class in not possible as static classes are sealed.
  • Inherited Static method can not be marked as override, virtual or abstract.
  • Inherited Static methods can be marked as new.



Friday, January 11, 2019

Structured/Imperative/Functional/Procedural Programming

Structured Programming 


  • Top-down analysis
    • Problem broken down into small piece (sub-problems) where each one has some significance.
    • Each small piece of problems are individually solved and steps are clearly stated.
  • Modular Programming
    • Code is broke down into small groups of instructions
    • These groups are knows as modules or subprograms or subroutines or methods.
    • Avoid jumps (unconditional GoTo) as non-traceable
  • Structured Code
    • Divide modules into further small units of code

  • Follow Top Down design model 
  • Maintainable Code
  • Systematic Organization
  • Reusable code block
  • Subdivision of program into functions
  • Hierarchy of task
  • Simple and easy to understand the code
  • Avoid unconditional Goto

Un-Structured code
  • Unconditional Goto 


Imperative languages


  • Imperative programming is a paradigm of computer programming in which the program describes a sequence of steps that change the state of the computer.
  • Unlike declarative programming, which describes "what" a program should accomplish, imperative programming explicitly tells the computer "how" to accomplish it.
  • To make programs simpler for a human to read and write, imperative statements can be grouped into sections known as code blocks.


Functional Programming


  • Functional programming (FP) is about passing data from function to function to get a result.
  • In FP, functions are treated as data, meaning you can use them as parameters, return them, build functions from other functions, and build custom functions.
  • A functional approach involves composing the problem as a set of functions to be executed.
  • In software, everything is a statement, unless it is a function. 


Procedural Programming


  • Procedural programming is a programming paradigm, derived from structured programming
  • Based upon the concept of the procedure call. Procedures
  • Also known as routines, subroutines, or functions, simply contain a series of computational steps to be carried out.
  • Any given procedure might be called at any point during a program's execution, including by other procedures or itself.
  • Procedural programming (PP), also known as inline programming takes a top-down approach.
  • It is about writing a list of instructions to tell the computer what to do step by step.
  • It relies on procedures or routines.
  • Procedural programming is a type of imperative programming in which the program is built from one or more procedures (also termed subroutines or functions).
  • Procedural programming could be considered a step towards declarative programming.
  • A programmer can often tell, simply by looking at the names, arguments, and return types of procedures (and related comments), what a particular procedure is supposed to do, without necessarily looking at the details of how it achieves its result.
  • At the same time, a complete program is still imperative since it fixes the statements to be executed and their order of execution to a large extent.