Wednesday, November 4, 2015

Anonymous Methods

A Anonymous method is a code block assigned to some delegate.
This concept is introduced in .Net Framework 2.0, before it only named methods could be used with delegates

Scenarios to use:
  1. When want to use delegate in same method
  2. When code is small
  3. Performance wise anonymous methods are faster than named method

    class Program
    {
        delegate void delAnonymousMethods(int i, int j);
        static void Main(string[] args)
        {
            //anonymous method
            delAnonymousMethods delAM = delegate(int i, int j)
            {
                Console.WriteLine((i + j).ToString());
            };

            delAM(10, 20);
            Console.ReadLine();
        }
    }


Some examples of Anonymous functions


delegate (int x) { return x + 1; }      // Anonymous method expression
delegate { return 1 + 1; }              // Parameter list omitted
x => x + 1                              // Implicitly typed, expression body
x => { return x + 1; }                  // Implicitly typed, statement body
(int x) => x + 1                        // Explicitly typed, expression body
(int x) => { return x + 1; }            // Explicitly typed, statement body
(x, y) => x * y                         // Multiple parameters
() => Console.WriteLine()               // No parameters
async (t1,t2) => await t1 + await t2    // Async



Asynchronous Method Calls using Delegate

Asynchronous method call means main execution goes continue and method executed parallel, when method execution gets completed it notifies back to main execution program / caller (client).

Example
namespace AsyncCallBack
{
    class Program
    {
        public delegate string delTask();
        public static string results;
        static void Main(string[] args)
        {
            clsBigTask objclsTask = new clsBigTask();
            delTask del = objclsTask.BigTask;
          
            AsyncCallback asyncCall = new AsyncCallback(CallBackMethod);
            del.BeginInvoke(asyncCall, del);
          
            Console.WriteLine("Main task completed @" + DateTime.Now.ToString());
            Console.ReadLine();
        }

        public static void CallBackMethod(IAsyncResult result)
        {
            delTask mydel = (delTask)result.AsyncState;
            results = mydel.EndInvoke(result);
            Console.WriteLine(results);
        }
    }

    public class clsBigTask
    {
        public string BigTask()
        {
            Thread.Sleep(6000);
            return "Big Task completed";
        }
    }
}

Output

Events

An event is a mechanism to notify all clients of the class about something happened, and clients executed the required operation on triggering of the event.
An event is a variable of type of a delegate with keyword 'event'.

Steps to create & use events:
  1. Create a delegate
  2. Create an event in your class (for that you want event tracking)
  3. Call event
  4. Hookup event with delegate
Example


    public class MyEventClass
    {
        public delegate void Mydelegate(object sender, MyEventArgsClass e); //step 1
        public event Mydelegate myEvent; //step 2

        public class MyEventArgsClass : EventArgs
        {
            public readonly string _message;
            public MyEventArgsClass(string message)
            {
                this._message = message;
            }
        }

        public void RaiseEvent(string message)
        {
            if(myEvent != null)
                myEvent(this, new MyEventArgsClass(message));  //step 3
        }
    }

    class Program
    {
       public static void Main(string[] args)
       {
        MyEventClass objEventClass = new MyEventClass();
        objEventClass.myEvent += objEventClass_myEvent;  //Step 4

       }
        //Client Method to Execute on Event
       static void objEventClass_myEvent(object sender, MyEventClass.MyEventArgsClass e)
       {
           if (sender is MyEventClass)
           {
               MyEventClass objClass = (MyEventClass)sender;
               Console.WriteLine("This is message : " + e._message);
           }
       }
    }

Sunday, October 25, 2015

SQL - Concurrent operations | Problems | Solutions

Concurrent Operations: When more than one user(s) / application(s) attempt operation (select / insert / update) on same data row(s), this is called Concurrent operation.

Concurrent operations may cause below given issues -

1. Dirty Reads: If session 2 executed during the 15 second delay. Session 2 will get updated data by session 1, but then session 1 get rolled back, so session 2 got wrong data its called Dirty Read.

Session 1
Begin tran
update tb_city set regionid = 2 where id between 11 and 20
waitfor delay '00:00:15'
--Commit
Rollback

Session 2
select * from tb_city where id = 15

2. Unrepeatable Reads:  If all these session executing parallel then 4 select statements of session 1 will get different values every time.

Session 1
select * from tb_city where id between 100 and 200
select * from tb_city where id between 100 and 200
select * from tb_city where id between 100 and 200
select * from tb_city where id between 100 and 200


Session 2 update tb_city set regionid = 2 where id between 100 and 200
Session 3 update tb_city set regionid = 4 where id between 100 and 200
Session 4 update tb_city set regionid = 9 where id between 100 and 200
Session 5 update tb_city set regionid = 3 where id between 100 and 200

3. Phantom Rows: User looking to set 20 for all active records. Session 2 is running parallel added new active values. These new rows are Phantom Rows.

Session 1
update tb_city set regionid = 20 where IsActive = 1

Session 2
insert into tb_city values (201, 1)
insert into tb_city values (202, 1)
insert into tb_city values (203, 1)

4. Lost Update: user is looking to set region id to 200, but parallel session 2 set it to 100. so user 1 lost his updates.

Session 1
update tb_city set regionid = 200 where IsActive = 1

Session 2
update tb_city set regionid = 100 where IsActive = 1
--------------------------------------------------------------------------
Solutions for these problems
  1. Optimistic Lock
  2. Pessimistic Lock

out Vs ref

Both are used to pass variable(s) as a reference from one function to another function.
out: It does not carry existing value of variable and ask to initialize it in function 2, but returns the new out put value. so its one way communication.

ref: It carries existing value of variable in function 1, and after operations on existing value returns the out put value, so its two way communication.

    static void Method(out int i, ref int j)
    {
        i = 50; //initialization required for out but not for ref

  i = i + 10;
  j = j + 10;
 
    }
    static void Main()
    {
        int value1 = 20, value2 = 20;
        Method(out value1, ref value2);
        // value1 is now 60
        // value2 is now 30

    }

Saturday, October 24, 2015

Keywords - checked & unchecked

First understand scenarios where we can use checked & unchecked keywords

C# compiler does not throws any error at compile or run time for arithmetic overflow.
j has assigned wrong value.
checked:  Used to check arithmetic overflow, it throws arithmetic overflow exception in case of overflow.



C# compiler checks for arithmetic overflow if constant(s) involved in operation and gives compile time error.
unchecked: unchecked is used to suppress checking for arithmetic overflow by compiler

Delegate in .Net

A delegate is a type that defines a method signature. When you create an instance of the delegate, you can associate a method to the instance of compatible signature, now you can call or invoke that method by the delegate instance.
  1. Delegates are used to pass a method as argument to other method. 
  2. A delegate instance can be assigned a method of any accessible class or struct that matches signature of delegate, method can be static or instance method.
  3. Delegate types are sealed they can not be derived from. (Sealed restricts inheritance of any class, like struct can't be inherited as they are sealed)
  4. Instance of delegate is an object so it can be assign to a property or can be pass to a method as parameter.
  5. Delegate can be multicast.
Using delegate is 4 step process 
  1. Declare delegate 
  2. Create instance / object of delegate (Create delegate pointer)
  3. Reference delegate instance to one or more methods with same signature
  4. Call delegate 

Example
namespace ClassLibrary1
{
    public class Class1
    {
        //-1-Declare delegate
        public delegate string DelSaveData(string msg);

        public DelSaveData SaveClientData()
        {
            //-2-Create delegate pointer (object)
            DelSaveData delObj = null;
           
            //-3-Point method(s) / reference to method(s)
            delObj += SaveData;
            delObj += SendMailtoClient;
            delObj += SendSMStoClient;

            return delObj;           
        }
       
        private string SaveData(string msg)
        {
            return "Data saved at : " + DateTime.Now.ToString();
        }
        private string SendMailtoClient(string msg)
        {
            return "Email sent to client at : " + DateTime.Now.ToString();
        }
        private string SendSMStoClient(string msg)
        {
            return "SMS sent to "+ msg +" at : " + DateTime.Now.ToString();
        }

    }
}

Client Code
private void button1_Click(object sender, EventArgs e)
{
   Class1 objclass1 = new Class1();
   Class1.DelSaveData objDelSaveData = objclass1.SaveClientData();
           
   //-4-Execute/call the delegate
   string s = objDelSaveData.Invoke("Client1");
}

Point to be noted in delegate multi casting : 
  1. Passed parameter(s) is available inside all assigned methods. Here "Client1" will be available to all three assigned method in msg variable.
  2. Delegate returns output returned by last called method. Here delegate invoke will return output returned by SendSMStoClient.
string s = objDelSaveData.Invoke("Client1");

Node | Cluster Vs Worker Threads

Cluster: Multiple processes (scale app across CPU cores) Worker Threads: Multiple threads (handle CPU-heavy work inside one process) Cluster...