Wednesday 31 August 2016

IEnumerable VS ICollection

Enumerable

First of all, it is important to understand, that there are two different interfaces defined in the .NET base class library. There is a non-generic IEnumerable interface and there is a generic type-safe IEnumerable interface.

The IEnumerable interface is located in the System.Collections namespace and contains only a single method definition. The interface definition looks like this:


    public interface IEnumerable
    {
        IEnumerator GetEnumerator();
    }
    

It is important to know that the C# language foreach keyword works with all types that implement the IEnumerable interface.

IEnumerable

Let’s now take a look at the definition of the generic and type-safe version called IEnumerable which is located in the System.Collections.Generic namespace:


    public interface IEnumerable<out T> : IEnumerable
    {
        IEnumerator GetEnumerator();
    }
    

As you can see the IEnumerable interface inherits from the IEnumerable interface. Therefore a type which implements IEnumerable has also to implement the members of IEnumerable.

ICollection

As you can imagine, there are also two versions of ICollection which are System.Collections.ICollection and the generic version System.Collections.Generic.ICollection.

Let’s take a look at the definition of the ICollection interface type:


    public interface ICollection : IEnumerable
    {
        int Count { get; }  
        bool IsSynchronized { get; }
        Object SyncRoot { get; }
     
        void CopyTo(Array array, int index);
    }
    

ICollection inherits from IEnumerable. You therefore have all members from the IEnumerable interface implemented in all classes that implement the ICollection interface.

ICollection

When we look at the generic version of ICollection, you’ll recognize that it does not look exactly the same as the non-generic equivalent:


    public interface ICollection<T> : IEnumerable<T>, IEnumerable
    {
        int Count { get; }
        bool IsReadOnly { get; }
     
        void Add(T item);
        void Clear();
        bool Contains(T item);
        void CopyTo(T[] array, int arrayIndex);
        bool Remove(T item);
    }
    

Which type should you depend on?

Tuesday 30 August 2016

What is Yield in CSharp

Short Answer

Yield keyword helps us to do custom stateful iteration over .NET collections. There are two scenarios where yield keyword is useful:-

  • Customized iteration through a collection without creating a temporary collection.
  • Stateful iteration.

Long Answer

First Scenario:- Customized iteration through a collection

Let's try to understand what customized iteration means with an example. Consider the below code.

Let say we have a simple list called as "MyList" which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is iterated from console application from within static void main method.

For now let's visualize the "main()" method as a caller. So the caller i.e. "main()" method calls the list and displays the items inside it. Simple…till now".

  static List MyList = new List();
  static void Main(string[] args)
  {
    MyList.Add(1);
    MyList.Add(2);
    MyList.Add(3);
    MyList.Add(4);
    MyList.Add(5);
    foreach (int i in MyList) // Itterates through the list
    {
      Console.WriteLine(i);
    }
    Console.ReadLine();
  }

Now let me complicate this situation let's say the caller only wants values greater than "3" from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than "3" and return the same to the caller. The caller can then iterate through this collection.

  static IEnumerable FilterWithoutYield()
  {
    List temp = new List();
    foreach (int i in MyList)
    {
        if (i > 3)
        {
            temp.Add(i);
        }
    }
    return temp;
  } 

Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where "yield" keyword comes to help. Below is a simple code how we have used yield. "Yield" keyword will return back the control to the caller, the caller will do his work and re-enter the function from where he had left and continue iteration from that point onwards. In other words "yield" keyword moves control of the program to and fro between caller and the collection.

static IEnumerable FilterWithYield()
{
  foreach (int i in MyList)
  {
      if (i > 3) yield return i;
  }
}  

So for the above code following are details steps how the control will flow between caller and collection. You can also see the pictorial representation in the next diagram shown below.

  • Step 1:- Caller calls the function to iterate for number's greater than 3.
  • Step 2:- Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than "3" i.e. "4". As soon as the condition of value greater than 3 is met the "yield" keyword sends this data back to the caller.
  • Step 3:- Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from "5". The iteration continues further as usual.

Second Scenario:- Stateful iteration

Now let us add more complications to the above scenario. Let's say we want to display running total of the above collection. What do I mean?.

In other words we will browse from 1 to 5 and as we browse we would keep adding the total in variable. So we start with "1" the running total is "1", we move to value "2" the running total is previous value "1" plus current value "2" i.e. "3" and so on.

In other words we would like to iterate through the collection and as we iterate would like to maintain running total state and return the value to the caller ( i.e. console application). So the function now becomes something as shown below. The "runningtotal" variable will have the old value every time the caller re-enters the function.

Tipical implementation

  1. Caller calls the GetRunningTotal method.
  2. Running total of all items in Numbers list is calculated at returned to caller.
    Initital Sum = [0] [0] + {1} => [1] [1] + {2} => [3] [3] + {3} => [6] [6] + {4} => [10] [10] + {5} => [15] [15] + {6} => [21] [21] + {7} => [28] [28] + {8} => [36] [36] + {9} => [45]
  3. Caller iterates over each running total and prints it on console.
    Print [1];
    Print [3];
    Print [6];
    Print [10];
    Print [15];
    Print [21];
    Print [28];
    Print [36];
    Print [45];
    Where list items are in {} brackets and running total (at some point) is in [] bracket.
class Program
{
        static List Numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        static void Main(string[] args)
        {
            int itemsTraversed = 0;
            foreach (var item in GetRunningTotal())
            {
                Console.WriteLine("Running total of first {0} items is {1}", ++itemsTraversed, item);
            }
            Console.ReadKey();
        }

        static IEnumerable GetRunningTotal()
        {
            List runningTotals = new List();
            int runningTotal = 0;
            foreach (int number in Numbers)
            {
                Console.WriteLine("Adding {0} in running total", number);
                runningTotal += number;
                runningTotals.Add(runningTotal);

            }
            Console.WriteLine("\n\nReturn Running Total\n\n");
            return runningTotals;
        }
}

Please note that GetRunningTotal method is called only once and it returns all the subsequent running totals to the caller.

Yield Implementation

  1. Caller calls the GetRunningTotal method.
  2. Running total of first n items is calculated and returned to caller.
    [n-1]th running total + {n}th item => [n]th running total
  3. Caller prints it on console.
    Print [n]th running total;
  4. Control is given back to GetRunningTotal method which remembers it’s running state.
  5. Repeat step 2 , 3 and 4 untill all items are iterated.
class Program
{
        static List Numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        static void Main(string[] args)
        {
            int itemsTraversed = 0;
            foreach (var item in GetRunningTotal())
            {
                Console.WriteLine("Running total of last {0} items is {1}", ++itemsTraversed, item);
            }
            Console.ReadKey();
        }

        static IEnumerable GetRunningTotal()
        {
            int runningTotal = 0;
            foreach (int number in Numbers)
            {
                if (number > 1)
                    Console.WriteLine("Control is back and next item to be summed is {0}\n\n", number);
                runningTotal += number;
                yield return (runningTotal);

            }
        }
}

The above code will output the values 1,3,6,10,15,21,28,36,45. Because of the pause/resume behavior, the variable total will hold its value between iterations. So it can be very handy to do stateful calculations using yield keyword.

Monday 22 August 2016

Function Overloding, Polymorphism, Method Overloding in Javascript

I often do this...

C#

In CSharp

   public string CatStrings(string p1)                  {return p1;}
   public string CatStrings(string p1, int p2)          {return p1+p2.ToString();}
   public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}

   CatStrings("one");        // result = one
   CatStrings("one",2);      // result = one2
   CatStrings("one",2,true); // result = one2true
                

JS

In JavaScript

 function CatStrings(p1, p2, p3)
 {
   var s = p1;
   if(typeof p2 !== "undefined") {s += p2;}
   if(typeof p3 !== "undefined") {s += p3;}
   return s;
 };

 CatStrings("one");        // result = one
 CatStrings("one",2);      // result = one2
 CatStrings("one",2,true); // result = one2true
                

What most developers do is...

JS

JavaScript

The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

 function foo(a, b, opts) {

 }

 foo(1, 2, {"method":"add"});
 foo(3, 4, {"test":"equals", "bar":"tree"});
                

Then you can handle it anyway you want in your method. [Switch, if-else, etc.]

Friday 12 August 2016

Connect Mongodb on a Microsoft Azure VM from Remote Machine

Create Directory for MongoData

    C:\> mkdir \MongoData
    C:\> mkdir \MongoLogs

Install mongod.exe as a service

    C:\Program Files\MongoDB\Server\3.2\bin>mongod --dbpath C:\MongoData\ --logpath C:\MongoLogs\mongolog.log --logappend  --install

Start the Service

    start the service
Now that MongoDB is installed and running, you'll need to open a port in Windows Firewall so you can remotely connect to MongoDB. From the Start menu, select Administrative Tools and then Windows Firewall with Advanced Security.

Inbound Rules

Configure Endpoint for MongoDB in Azure

Test your Mongodb from Local Machine

Tuesday 9 August 2016

Javascript Reference Data Type and Primitive Data Types

One of the main differences between reference data type and primitive data types is reference data type’s value is stored as a reference, it is not stored directly on the variable, as a value, as the primitive data types are. For example:

 // The primitive data type String is stored as a value​
 ​var person = "Nisar";  
 ​var anotherPerson = person; // anotherPerson = the value of person​
 person = "Rahul"; // value of person changed​
 ​
 console.log(anotherPerson); // Nisar​
 console.log(person); // Rahul

It is worth noting that even though we changed person to “Rahul,” the anotherPerson variable still retains the value that person had.

Compare the primitive data saved-as-value demonstrated above with the save-as-reference for objects:

 var person = {name: "Nisar"};
 ​var anotherPerson = person;
 person.name = "Rahul";
 ​
 console.log(anotherPerson.name); // Rahul​
 console.log(person.name); // Rahul

In this example, we copied the person object to anotherPerson, but because the value in person was stored as a reference and not an actual value, when we changed the person.name property to “Rahul” the anotherPerson reflected the change because it never stored an actual copy of it’s own value of the person’s properties, it only had a reference to it.