Tuesday, 5 February 2019

Factory Design Pattern in C#

Factory Design Pattern

In Factory pattern, we create the object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to sub classes.

In short, factory method design pattern abstract the process of object creation and allows the object to be created at run-time when it is required.

Example :- Employee

A) Class Library :- Test.Employee


1) EmployeeFactory

using System;
using System.Configuration;

namespace Test.Employee
{
    public class EmployeeFactory
    {
        private static Type _empType;

        private static string GetTypeName(string factoryName)
        {
            var nameSpace = ConfigurationManager.AppSettings["EmployeeFactory"];
            return String.Format("{0}.{1}, {0}", nameSpace, factoryName);
        }

        public static IEmployeeManager GetManager()
        {
            if (_empType == null)
            {
                var empTypeName = GetTypeName("EmployeeManager");
                if (!string.IsNullOrEmpty(empTypeName))
                    _empType = Type.GetType(empTypeName);
                else
                    throw new NullReferenceException("EmployeeManagerType");
                if (_empType == null)
                    throw new ArgumentException(string.Format("Type {0} could not be found", empTypeName));
            }
            return (IEmployeeManager)Activator.CreateInstance(_empType);
        }
    }
}

2) IEmployee (Interface)

namespace Test.Employee
{
    public interface IEmployee
    {
        string Name { get; set; }

        int GetSalary();
    }
}

3) IEmployeeManager (Interface)

using System;

namespace Test.Employee
{
    public interface IEmployeeManager : IDisposable
    {
        string Data { get; set; }

        T GetProvider<T>() where T : class;
    }
}

B) Class Library :- Test.Employee.Parmanent

1) Employee (Class)

namespace Test.Employee.Parmanent
{
    public class Employee : IEmployee
    {
        public string Name { get; set; } = "Permanent";
        public int InHandSalary { get; set; }
        public int PF { get; set; }

        public int GetSalary()
        {
            return InHandSalary + PF;
        }
    }
}

2) EmployeeManager 

using System;

namespace Test.Employee.Parmanent
{
    public class EmployeeManager : IEmployeeManager
    {
        private static string _typeMask = typeof(EmployeeManager).FullName.Replace("EmployeeManager", @"{0}");

        private object _NewInstance = null;

        public string Data { get; set; }

        public T GetProvider<T>() where T : class
        {
            var typeName = string.Format(_typeMask, typeof(T).Name.Substring(1));
            var type = Type.GetType(typeName);
            if (type != null)
            {
                _NewInstance = Activator.CreateInstance(type);
                return _NewInstance as T;
            }
            else
                throw new NotImplementedException(typeName);
        }

        public void Dispose()
        {
            if (_NewInstance is IDisposable)
            {
                ((IDisposable)_NewInstance).Dispose();
            }
            _NewInstance = null;
        }
    }
}

C) Class Library :- Test.Employee.Temporary

1) Employee  (Class)

namespace Test.Employee.Temporary
{
    public class Employee : IEmployee
    {
        public string Name { get; set; } = "Temporary";

        public int InHandSalary { get; set; }

        public int PF { get; set; }

        public int GetSalary()
        {
            return InHandSalary + PF;
        }
    }
}

2)EmployeeManager  (Class) 

using System;

namespace Test.Employee.Temporary
{
    public class EmployeeManager : IEmployeeManager
    {
        private static string _typeMask = typeof(EmployeeManager).FullName.Replace("EmployeeManager", @"{0}");

        private object _NewInstance = null;

        public string Data { get; set; }

        public T GetProvider<T>() where T : class
        {
            var typeName = string.Format(_typeMask, typeof(T).Name.Substring(1));
            var type = Type.GetType(typeName);
            if (type != null)
            {
                _NewInstance = Activator.CreateInstance(type);
                return _NewInstance as T;
            }
            else
                throw new NotImplementedException(typeName);
        }

        public void Dispose()
        {
            if (_NewInstance is IDisposable)
            {
                ((IDisposable)_NewInstance).Dispose();
            }
            _NewInstance = null;
        }
    }
}

4) Console Application :- TestFactoryPattern

1) Program (Class)

using System;
using Test.Employee;

namespace TestFactoryPattern
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            try
            {
                using (var empManager = EmployeeFactory.GetManager())
                {
                    var employee = empManager.GetProvider<IEmployee>();
                    Console.WriteLine(employee.Name);
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}

2) App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <appSettings>
    <add key="EmployeeFactory" value="Test.Employee.Parmanent" />
    <!--<add key="EmployeeFactory" value="Test.Employee.Temporary" />-->
  </appSettings>
</configuration>

Note :- 
        a) Pass the reference Test.Employee To All Project 
        b) Test.Employee.Permanent & Test.Employee.Temporary in Console App
        c) Configure any one at Run time by using config file

Result :- if you set "Test.Employee.Parmanent" in config then result will shown of Permanent 



Bubble Shorting Program

Bubble Shorting Program


using System;
using System.Linq;

namespace BubbleShortingProg
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Bubble Shorting");
            Console.WriteLine("Enter values with space");

            string inputLine = System.Console.ReadLine();
            string[] inputLine_arr = inputLine.Split(' ').ToArray();

            int[] inputArr = Array.ConvertAll(inputLine_arr, Int32.Parse);

            int tempValue = 0;

            for (int node = 0; node < inputArr.Length; node++)
            {
                for (int sort = 0; sort < inputArr.Length - 1; sort++)
                {
                    if (inputArr[sort] > inputArr[sort + 1])
                    {
                        tempValue = inputArr[sort + 1];
                        inputArr[sort + 1] = inputArr[sort];
                        inputArr[sort] = tempValue;
                    }
                }
            }
            
            for (int i = 0; i < inputArr.Length; i++)
                Console.Write(inputArr[i] + " ");
           
            Console.ReadKey();
        }
    }
}



Monday, 4 February 2019

Extension methods in C#

Extension methods in C#


public static void AllowWholeNumberOnly(this KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true;
if (e.KeyChar == (char)8) e.Handled = false;
}

public static void AllowNumbericValueOnly(this KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true;
if (e.KeyChar == (char)8) e.Handled = false;
if (e.KeyChar == (char)46) e.Handled = false;
}

public static bool AllowDecimalValueOnly(object sender, KeyPressEventArgs e)
{
var IsValid = false;
IsValid = (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46)) ? true : false;

// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
IsValid = ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1) ? true : false;
}

return IsValid;
}

public static void AllowAlphabeticalValueOnly(this KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar)) e.Handled = true;
if (e.KeyChar == (char)8) e.Handled = false;
if (e.KeyChar == (char)46) e.Handled = false;
}

Reverse the string

Reverse the string


Reverse the string by for Loop


using System;

namespace ConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string inputString = Console.ReadLine();
            string reverse = ReverseString(inputString);
            Console.WriteLine(string.Format("Reverse string of {0} is {1}", inputString, reverse));
            Console.ReadLine();
        }

        public static string ReverseString(string inputString)
        {
           string reveseString = "";
            char[] inputStringArr = inputString.ToCharArray();
            for (int i = inputStringArr.Length - 1; i <= inputStringArr.Length && i >= 0; i--)
            {
                reveseString += inputStringArr[i];
            }
            return reveseString;
        }
    }
}

Reverse the string by While Loop

using System;

namespace ConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string inputString = Console.ReadLine();
            string reverse = ReverseString(inputString);
            Console.WriteLine(string.Format("Reverse string of {0} is {1}", inputString, reverse));
            Console.ReadLine();
        }

        public static string ReverseString(string inputString)
        {
            string reveseString = "";
            char[] inputStringArr = inputString.ToCharArray();
            int j = inputStringArr.Length - 1;
            while (j >= 0)
            {
                reveseString += inputStringArr[j];
                j--;
            }
            return reveseString;
        }
    }

}



Minimum in SubArrays

Minimum in Sub Arrays


You are given an array A[] of size N and an integer K.
Your task is to print the Minimum element for each subarray of size 'k'.
In other words, for Each Valid Index i (1 <= i <= N - K)
You have to print min(A[i], A[i + 1], A[i + 2] .... A[i + k]).

Input Format
The First line will contain two Integers N and K.
The Second Line will contain N Integers denoting the elements of Array A[].

Constraints
1 <= N <= 10^5
1 <= K <= N
1 <= A[i] <= 10^6

Output Format
Print the Minimum elements for each subarray of Size K separated by space.


Sample TestCase 1

Input
5 2
10 0 3 2 5

Output
0 0 2 2

Code:

using System;
using System.Linq;

namespace ConsoleApp
{
    internal class DonNetTest
    {
        private static void Main(string[] args)
        {
            string inputFirstLine = System.Console.ReadLine();
            string[] firstLine_arr = inputFirstLine.Split(' ').ToArray();

            int n = Int32.Parse(firstLine_arr[0]);
            int k = Int32.Parse(firstLine_arr[1]);

            int[] arr = new int[k];

            string inputSecondLine = System.Console.ReadLine();
            string[] secondLine_arr = inputSecondLine.Split(' ').ToArray();
            arr = Array.ConvertAll(secondLine_arr, Int32.Parse);

            printMinimumArray(n, k, arr);
        }

        private static void printMinimumArray(int n, int k, int[] arr)
        {
            int j, min;

            for (int i = 0; i <= n - k; i++)
            {
                min = arr[i];

                for (j = 1; j < k; j++)
                {
                    if (arr[i + j] < min )
                        min = arr[i + j];
                }
                Console.Write(min + " ");
            }
        }
    }
}



Factorial of a Number

Recently Viewed