Saturday 21 December 2019

Web API Basic Authentication Using MVC

Web API Basic Authentication Using MVC


Step :1 Create WEB  API Application

Step :2 Create Authorization Filter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Test.BussinessLayer;

namespace Test.Web.API
{
    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        private const string keyName = "TestName";
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic auth=\"{0}\"", keyName));
                }
            }
            else
            {
                string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
                string decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
                string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
                string username = usernamePasswordArray[0];
                string password = usernamePasswordArray[1];
                if (UserValidate.Login(username, password))
                {
                    var identity = new GenericIdentity(username);
                    IPrincipal principal = new GenericPrincipal(identity, null);
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null) { HttpContext.Current.User = principal; }
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }
    }

}


Step :3 Create Method For Validate User

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test.DataAccessLayer;

namespace Test.BussinessLayer
{
    public class UserValidate
    {
        //This method is used to check the user credentials
        public static bool Login(string username, string password)
        {
            return new UserFactory().UserValidate(username, password);
        }
    } 
}


Step :4 Create Method to check user exist into database

return TRUE when yes other wise FALSE.

Step :5 User the filter attribute

Use the "[BasicAuthentication]" filter attribute above controller action method. 


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 + " ");
            }
        }
    }
}



Monday 14 January 2019

Simple and Trick Question Answer SQL

Q.1 Below query will execute or give error.
     
       SELECT *,YEAR(CreatedOn) AS Yr FROM Customer WHERE YEAR(CreatedOn) > 2017;


Ans :-It will give records which year is greater than 2017.


Q.2 Below query will execute or give error.
 
SELECT CASE WHEN NULL=NULL THEN 'YES' ELSE 'NO' END

Ans :- Execute - NO

Q.3 What will be result?

    a)   SELECT COUNT(*);
    b)   SELECT SUM(NULL);

ANS :-  a) 1
             b) Operand data type NULL is invalid for sum operator.              

Q.4 Single query for update swap record?

       e.g  :- if customer table have one column i.e. Gender and some are Female & some Male then                update Female to Male & Male to Female.

ANS :-

     UPDATE Customer
     SET Gender = (CASE WHEN Gender='Female' THEN 'Male' ELSE 'Female' END);

Q.5 How to get nth salary in sql?

ANS :-
             WITH ResultCTE AS
              (
                 SELECT Salary,DENSE_RANK() OVER (ORDER BY Salary DESC) as DeskRank
                 FROM Employee
               )
              SELECT Salary FROM ResultCTE  WHERE ResultCTE .DeskRank=nth;

Q.6 How to delete duplicate record from table?

ANS :-
             WITH ResultCTE AS
              (
                 SELECT *,Row_Number() OVER (Partition by Id ORDER BY Id) as RowNumber
                 FROM Employee
               ) 
              DELETE From ResultCTE WHERE RowNumber > 1;


Factorial of a Number

Recently Viewed