Sunday, 29 March 2020

How To Create JavaScript Function

How To Create JavaScript Function 



Use Keyword "function" to create function with parameter or parameter less.

see the example as below.

e.g.:- 1 - Parameter Less Function

function sum(){
let a =5;
let b=10;
let c=a+b;
console.log(c);
}


e.g.:- 2 - Parameter Function

function sum(a,b){
let c=a+b;
console.log(c);
}

e.g :- 3 - Function As Expression

var sum = function(a,b){
let c= a+b;
return c;
}

let  output =sum(5,10);
console.log(output );

e.g :- 4 - Arrow Function

let sum = (a,b) => a+b;
let  output =sum(5,10);
console.log(output);

Tuesday, 3 March 2020

Logging using log4net

Logging using log4net


Step : 1 

Create Demo application like console application.

Step : 2

Add log4Net library from nuget manager.

Step : 3

Add config file for log4net


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender"
                    type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="E:\Test Application\Log\log.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="2" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern"
             value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
        <conversionPattern
             value="%newline%newline%date %newline%logger 
                       [%property{NDC}] %newline>> %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
</configuration>  


Step : 5

Add one class for logging method

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

namespace LoggingTest
{
    public static class Logger
    {
        private static log4net.ILog Log { get; set; }

        static Logger()
        {
            Log = log4net.LogManager.GetLogger(typeof(Logger));
        }

        public static void Error(object msg)
        {
            Log.Error(msg);
        }

        public static void Error(object msg, Exception ex)
        {
            Log.Error(msg, ex);
        }

        public static void Error(Exception ex)
        {
            Log.Error(ex.Message, ex);
        }

        public static void Info(object msg)
        {
            Log.Info(msg);
        }
    }
}


Step : 6

Register config file into application assembly (Properties >> AssemblyInfo.cs).


[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]





Step : 7

Use logger method as like uses.

class Program
    {
        static void Main(string[] args)
        {
           
            try
            {
                throw new Exception("Test Logging  by dot net by vickypedia");
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            Console.WriteLine("Test Logging  by dot net by vickypedia");
            Console.ReadKey();

        }
    }



Step :8 

See the log file as mention into config "E:\Test Application\Log\log.txt"











Sunday, 19 January 2020

Create Custom Primary Key SQL

Create Custom Primary Key SQL


Step 1: Create a function to get custom value

e.g. : EMP-0001, EMP-0002

CREATE FUNCTION Empcode (@id INT)
returns CHAR(10)
AS
  BEGIN
      RETURN 'EMP-'+ RIGHT('0000' + CONVERT(VARCHAR(10), @id), 4)
  END 

Step 2: Create table "tbl_Emloyee"

Note :-Add EmploeeId column , datatype as function name and parameter will be id

CREATE TABLE tbl_Employee
(
Id int primary key identity(1,1),
EmployeeId as dbo.Empcode(Id),
EmployeeName VARCHAR(50) NOT NULL,
EmployeeDOB DateTime ,
Gender int,
Address VARCHAR(500),
State int,
Hobbies VARCHAR(200)
)


Step 3:- Insert Values 

INSERT INTO [dbo].[tbl_Employee]
            ([EmployeeName],
             [EmployeeDOB],
             [Gender],
             [Address],
             [State],
             [Hobbies])
VALUES      ('Test User',
             Getdate(),
             1,
             'Address delhi',
             1,
             'Writing Blog') 


Step 4 :- To Check

SELECT * FROM tbl_Employee;


See Custom value as primary key

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

Factorial of a Number

Recently Viewed