Tuesday, November 10, 2015

yield keyword

yield keyword is used to define an iterator with maintaining state of data during iteration.

We use a yield return statement to return each element one at a time.
We consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

yield preserves returned variable value during iteration.

Limitation: yield can't be use in try-catch block

Source Code:
    class Program
    {
        static void Main(string[] args)
        {
            foreach (int res in power(3, 6))
            {
                Console.WriteLine("{0} ", res);
            }
            Console.ReadLine();
        }
       
        private static IEnumerable<int> power(int number, int exponent)
        {
            int result = 1;
            for (int i = 0; i < exponent; i++)
            {
                result = result * number;
                yield return result;
            }
        }


    }


Result:

Monday, November 9, 2015

Extension Methods

Extension method enables to add new method(s) into a class (type / library) without modifying, recompiling or creating derived type.

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

Scenario :
We've a class library 'Calculations' in which we have class 'Airithmatics' that contains method 'Add'.
Now we want to add 2 more methods 'Subtract' & 'Multiply' in this library without updating this library.

Limitation: Any extension method(s) with same signature to method(s) of main library / type will never be called

Steps to implement:
  1. Create new library named 'ArithmaticAddons'
  2. Add reference of main library 'Calculations'
  3. Create a static class 'ArthAddons' in new library
  4. Add new methods to this class as static method, you want to create as extension methods. Pass main library 'Airithmatics' in methods
  5. Add reference of both the libraries 'Calculations', 'ArithmaticAddons' in client code
  6. Create object of main library 'Airithmatics'
  7. With the object of main library 'Airithmatics', you can see methods of main library & extension methods
  8. Extension methods displays with a down arrow




















Custom Library Code:
using  Calculations;  //Main library contains ‘Add’ function

namespace ArithmaticAddons
{
    public static class ArthAddons
    {
        public static int Subtract(this Airithmatics obj, int num1, int num2)
        {
            return num1 - num2;
        }
 public static int Multiply(this Airithmatics obj, int num1, int num2)
        {
            return num1 * num2;
        }
    }

}

Client Code:
using Calculations; //Main library contains ‘Add’ function
using ArithmaticAddons; //Custom library contains subtract & Multiply extension methods
namespace ExtensionMethods
{
  class Program
  {
    static void Main(string[] args)
    {
      Airithmatics obj = new Airithmatics();
      Console.WriteLine(obj.Add(20, 215).ToString());
      Console.ReadLine();

      //Extension method Subtract & Multiply call
      Console.WriteLine(obj.Subtract(220, 215).ToString());
      Console.WriteLine(obj.Multiply(2, 20).ToString());
      Console.ReadLine();
    }
  }
}

Const Vs ReadOnly

Const Vs ReadOnly: Both type variables used to hold constant values. Once we initialize them values can't be changed.

Const : Constant variables are compile time constants it means we need to initialize them before compiling the program.

ex:
 public const string aa = "";

readonly : Read only variables are run time constants, it means not required to initialize for compilation, later we can initialize them on run time, like initialize with some value retrieve from database, after initialization it can't be reassigned.

Ex:
public class test
    {
        public readonly static string bb;
        public test()
        {
            bb = Session["user"].Tostring();
        }
   
    }

------------------------------------------------------------------------
Is Vs As
------------ Is : This keyword is used to check data type of variable
As: This keyword is used to convert data type of variable

ex
    object str = "";
    if (str is object)
    {
        string obj = str as string;
    }


-------------------------------------------------------------------------
Debug keyword
--------------------- If we want to execute some code when running application in debug mode but want to skip that code from execution when running in release mode, this keyword is useful.
Ex.

Debug mode
# if DEBUG
        Console.WriteLine("hello");

#endif

Release mode
# if DEBUG
        Console.WriteLine("hello");
#endif


-------------------------------------------------------------------------
typeof Vs GetType
------------------------
typeof: It is used to retrieve type from class name
GetType: It is used to retrieve type from instance

Source Code:
    public class employee
    {

    }
    public class Student
    {

    }
   
   
employee objEmp = new employee();
   
   
if (objEmp.GetType() == typeof(Student))
    {
      Console.WriteLine("Matched...");
    }
    else
    Console.WriteLine("Not Matched...");


-------------------------------------------------------------------------
null-coalescing operator (??)
------------------------
null-coalescing operator is used to get not null value from a group of variable.
It assigns first not null variable value from a variable or a group of variable.

string s1;
string s2;
string s3 = "ram";
string s4 = "raj";

string res1 = s2 ?? "krisna";  // res1 will assigned 'krishna'
string res2 = s2 ?? s3;  //  res2  will assigned 'ram'
string res3 = s1 ?? s2 ?? s3; // res3 will assigned 'ram'

-------------------------------------------------------------------------
Portable class library
------------------------
It is portable class library, compatible for any type .net project.

Thursday, November 5, 2015

Regex Timeout

Timeout is used to prevent DOS attack.
If some hacker puts long string as input on form that is validated with regular expression then application would be hanged. Preventing from this situation need to set timeout.
Timeout feature is provided in .net framework 4.5

Without below given timeout parameter, this IsMatch statement will get hanged.
TimeSpan.FromSeconds(2)

Example

class Program
{
static void Main(string[] args)
{
   if Validate("815640753863946969814609141061480419060941869400616086849408614610189x"))
   Console.WriteLine("Validated");           
}

 static bool Validate(string input)
 {
    try
    {
return Regex.IsMatch(input, @"^(\d+)+$", RegexOptions.Singleline,       TimeSpan.FromSeconds(2));
    }
    catch (RegexMatchTimeoutException ex)
    {
        Console.WriteLine("Big or bad data: " + ex.Message);
    }
    return false;
 }

}

Covariance & Contravariance

Covariance & Contravariance enables implicit reference conversion of parameters for arrays, delegates & generic types.
These concepts introduced in .Net framework 4.0, before it was not works

Covariance: Covariance allows more derived return type method than delegate's return type to be assigned.
Return type of method GetString is 'string' that is more derived type than return type of delegate Func that is 'object'.
1. Func<object> delFun = GetString; //See below code
2.  IEnumerable<string> strs = new List<string>();
   IEnumerable<object> objects = strs;

Contravariance: Contravariance allows less derived parameter types method than delegates parameters type to be assign.
Parameter of setobject method 'object' is less derived type than parameter of delegate Action that is 'string'.
Action<string> delAct = SetObject;

Examples 

class Program
{   
    static void Main(string[] args)
    {
       //Covariance
       Func<object> delFun = GetString;

       //Contravariance
       Action<string> delAct = SetObject;
    }

    static string GetString()
    {
        return string.Empty;
    }
    static void SetObject(object obj)
    {
   
    }
}

Predefined .net delegates Action, Func, Predicate

There are some predefined delegates provided by .net those makes code more simpler to write.

  1. Predicate: This delegate takes one input matches some condition and returns boolean value. This delegate is used to pass in functions of collection to match a condition, based on condition function returns collection items.
    ex.      Predicate<string> delPredicate = X => X.Length < 4;
    string
     myName = lstNames.Find(delPredicate);
  2. Action: This delegate takes one input and no output. This is used when out put not required and doing some operation with input inside as well.
    ex.  Action<string> delAction = G => Console.WriteLine(G);
  3. Func: This delegate has 17 overload methods, it returns 1 output and can take 1 to 16 inputs. This is used when we need output of some operation with providing 1 to 16 input parameters.
    Last parameter can be passed as output parameter if required.
    ex1     Func<intintint> delMulFunc = (x, y) => x * y;
    ex2     Func<intdouble> delTriangleArea = L => 3.14 * L * L;

Examples
class Program
{
    delegate int delAdd(int a, int b);

    static void Main(string[] args)
    {
    //Normal delegate
    delAdd delA = AddNum;
    int c = delA(50, 60);
    Console.WriteLine("Normal delegate: Value of c -" + c.ToString());

    //Lamda expression
    delAdd delLamda = (x,y) => x - y;
    int z = delLamda(70, 20);
    Console.WriteLine("Lamda expression: Value of z -" + z.ToString());

    //Ready made delegate Func
    Func<int, int, int> delMulFunc = (x, y) => x * y;
    int k = delMulFunc(20, 30);
    Console.WriteLine("Func: two input, Value of k -" + k.ToString());

    Func<int, double> delTriangleArea = L => 3.14 * L * L;
    double area = delTriangleArea(20);
    Console.WriteLine("Func: one input, Value of area :" + area.ToString());

    //Ready made delegate Action
    Action<string> delAction = G => Console.WriteLine(G);
    delAction("Action: Hello IT");

    //Ready made delegate Predicate
    Predicate<string> delPredicate = X => X.Length < 4;

    //use
    List<string> lstNames = new List<string> { "Ramu", "Raghu", "Raj", "Rajeev", "Ram" };
    string myName = lstNames.Find(delPredicate);
    Console.WriteLine("Predicate: Value of myName :" + myName);

    Console.ReadLine();
    }

    static int AddNum(int i, int j)
    {
        return i + j;
    }


}

Tuples Vs Anonymous Types

Tuples & Anonymous Types both are used to group related information, used when we look to group some information but avoid to create class.

Tuple Disadvantage 
Members are not strongly typed, we need to remember data contained in Item1, Item2...

Anonymous Type Disadvantage 
Type casting required

    class Program
    {
        static void Main(string[] args)
        {
            //Tuple call
            string Personnelinfo = "Ram Singh 39";
            var PI =  PersonalInfo(Personnelinfo);
            string FName = PI.Item1;
            string LName = PI.Item2;
            int Age = PI.Item3;

            //Anonymous Type call
            var objPI = Cast(PersInfo(Personnelinfo), new { FirstName = "", LastName = "",               Age = 0 });
            FName = objPI.FirstName;
            LName = objPI.LastName;
            Age = objPI.Age;

        }
        static Tuple<string, string, int> PersonalInfo(string PI)
        {
            string[] info = PI.Split(' ');
            // Tuple
            return Tuple.Create<string, string, int>(info[0], info[1], int.Parse(info[2])); 
        }       

        static object PersInfo(string PI)
        {
            string[] info = PI.Split(' ');
            //Anonymous type
            return new { FirstName = info[0], LastName = info[1], Age = info[2] }; 
        }
        static T Cast<T>(object obj, T type)
        {
            return (T)obj;
        }

    }


CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...