Saturday, 22 April 2017

Replace Conditional with Polymorphism

Replace Conditional with Polymorphism

Problem Code

foreach(Employee in _emp)
{
    if(emp.IsManager)
    {
        emp.bonus = totalFreight/10m;
    }
    else
    {
        emp.bonus = totalFreight/10m;
    }
}

Solution Code

public class Employee
{
    public string Name;
    public bool IsManager;
    protected decimal bonus;
    public decimal Bonus { get{ return bonus;}}
    public virtual void SetBonus(decimal freightUsedForBonus)
    {
        bonus = freightUsedForBonus/1000;
    }
}
public class Manager : Employee
{
    public override void SetBonus(decimal freightUsedForBonus)
    {
        bonus = freightUsedForBonus/10;
    }
}

Benefits

  • Tell-Don't-Ask Principal instead of asking an object about its state and then performing actions based on this, it is much easier to simply tell the object what it needs to do and let it decide for itself how to do that.
  • Do Not Repeat (DRY) Principal we get rid of many almost identical conditionals.
  • Open/Closed Principle If we need to add a new variant, all you need to do is add a new subclass without touching the existing code

Tuesday, 11 April 2017

Some inheritance Cases in Objected Oriented Programming in CSharp

Inheritance by using Virtual and Override Keyword

Parameterized Constructor Inheritance

Common Errors while Inheritance

Friday, 17 March 2017

Priceless SOLID Principal Posters

SOLID

Software development is not a Jenga game.

Single responsibility principle (SIP)

Open closed principle (OCP)

Liskov substitution principle (LSP)

Interface segregation principle (ISP)

Dependency inversion principle (DIP)

Thursday, 16 March 2017

Top 3 thing of interest introduced in Angular 4 RC

if...else syntax in component HTML templates

 <ng-template #fetching>
   <p>Fetching...

</ng-template> <p *ngIf="auth | async; else fetching; let user"> {{user.username }} </p>

Saperate library for Animation

In Angular 2 Animation were in library @angular/core since angular 4 it separately maintained in @angular/animations

Strict Null check in Typescript

 let x = String | null
 let y = Number | undefined
 let z = Array<String> | null | undefined

Friday, 10 March 2017

Types of Grant Workflows

Resource Owner Password Grant

The User Credential are stored at client and sent to the token service which returns the token. Collecting and storing credential is the job of the token service doing it in client is consider not safe.The User Credential are stored at client and sent to the token service which returns the token. Collecting and storing credential is the job of the token service doing it in client is consider not safe.

This grant is only used in legacy scenario.

Implicit Grant

Implicit flow is commonly user when a client is javascript application a browser.

Here browser issue for Token to Token Service without explicitly providing client credential then a redirection occurs to a login page that is served by Token Service.

This approaches often has a security issue

Authorization Code

Authorization Code solves the security problem. It needs a web server Application i.e. the client.

Hear browser get a code back from Token Service and that browser send that code to Client(Web Server) Then client sends the code to Token Service and get the Token back.

Hybrid

Thursday, 16 February 2017

Improving Angular 2 Performance while using ngFor

When you iterate over an array or collection most probably you use ngFor directive to bind the data of collection into your DOM elements.

Problem !

Here the big problem is, If at some point of time you wish to change the data in the collection, for example maybe as a result of an API request, Then the Angular can’t keep track of items in the collection and has no knowledge of which items have been removed or added as a results it creates the DOM again. That means this has a lot of DOM manipulations.

Solution ..

Here comes the solution, ngFor directive has a property called track by.

So what do these do? They help Angular to associate key with the DOM elements and tracks which items are added or removed.

Angular’s ngFor defaults tracks object identity for you, which is fast, but it can be more faster if we use track by unique object ID in ngFor. Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the things that changed.

   <li *ngFor="let student of students; trackBy: student.id;">
    ...
   </li>

Optionally, we can use track by index but that is not advisable as the index may be subject to change if you reorder your collection. Using a unique identifier allows Angular to locate that DOM node associated with the object much faster

Toggle String Lower to Upper and Upper to Lower

You have been given a String S consisting of uppercase and lowercase English alphabets. You need to change the case of each alphabet in this String. That is, all the uppercase letters should be converted to lowercase and all the lowercase letters should be converted to uppercase. You need to then print the resultant String to output.

using System; 
using System.Numerics;
public static class InvertStringExtension
{
    public static string Invert(this string s)
    {
        char[] chars = s.ToCharArray();
        for (int i = 0; i < chars.Length; i++)
            chars[i] = chars[i].Invert();
            
        return new string(chars);
    }
    public static char Invert(this char c)
    {
        if (!char.IsLetter(c))
            return c;
 
        return char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
    }
}
class MyClass {
    static void Main(string[] args) {
        var line1 = System.Console.ReadLine().Trim();
        System.Console.WriteLine(line1.Invert());
    }
}

Tuesday, 14 February 2017

Maintaining Relationship in NoSQL

The decision "What database to use" is a bit difficult. Most Startup rely on NoSQL Database. MongoDB is the most popular NoSQL DataBase. NoSQL Database has grown in popularity due to it's open source, flexible in nature and ease to use.

But what about relationship

As Database is mostly representation of real world entities relationship is very important to be maintain among database. While MongoDB is not a relational database, there are two recommended approaches to representing relationships between entities.

Modeling Embedded Relationships

In this approach we embed the related document inside its parent document.

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   ...
   "address": [
      {
         "building": "22 A, Indiana Apt",
         ...
      },
      {
         "building": "ABC Apart",
         ...
      }
   ]
} 

This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. But The drawback is it is not Consistent. And if the embedded document keeps on growing too much in size, it can impact the read/write performance.

Modeling Referenced Relationships

In this approach the two related table are maintained saperatly and the reference of one table is maintained in another table by its document id

{
   ...
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
}

The benefit of this approach is whenever a document is updated, there is no overhead of managing other document because the reference ids does not change and the problem of Consistency is solved.

Monday, 23 January 2017

Setting and getting Session values in Asp.NET Core 1.0

Session is accessed through the Session property on HttpContext. Session is an ISession implementation.

Simple Get Set Session in Core 1.0

The following extension methods, we can set and get serializable session objects:

Session Extensions Method

Implementing Session Extensions Method

Sunday, 15 January 2017

Detect a Loop in Singly Linked List and Remove Loop

using System;
namespace ConsoleApplication1
{
    class Program
    {

        public class LinkedListNode
        {
            public LinkedListNode() { }
            public LinkedListNode(T value)
            {
                Value = value;
            }
            public T Value { get; set; }
            public LinkedListNode Next { get; set; }
        }

        static void Main(string[] args)
        {
            LinkedListNode Llist = new LinkedListNode();
            Llist.Next = new LinkedListNode(1);
            Llist.Next.Next = new LinkedListNode(2);
            Llist.Next.Next.Next = new LinkedListNode(3);
            Llist.Next.Next.Next.Next = new LinkedListNode(4);
            Llist.Next.Next.Next.Next.Next = new LinkedListNode(5);
            Llist.Next.Next.Next.Next.Next.Next = new LinkedListNode(6);

            Llist.Next.Next.Next.Next.Next.Next.Next = Llist.Next.Next.Next.Next;
            Console.WriteLine(FloydCycleDedection(Llist).ToString());
            Console.WriteLine(FloydCycleDedection(Llist).ToString());
            Console.Read();
        }

        public static bool FloydCycleDedection(LinkedListNode node)
        {
            LinkedListNode slow = node, fast = node;
            while (slow != null && fast != null && fast.Next != null)
            {
                slow = slow.Next;
                fast = fast.Next.Next;
                if (slow == fast)
                {
                    removeLoop(node, slow, fast);
                    return true;
                }
            }
            return false;
        }

        public static void removeLoop(LinkedListNode node, LinkedListNode slow, LinkedListNode fast)
        {
            /* If loop exists */
            if (slow == fast)
            {
                slow = node;
                while (slow != fast.Next)
                {
                    slow = slow.Next;
                }
                fast.Next = null; // remove loop
            }
        }
    }
}

Thursday, 12 January 2017

Kadane's algorithm to find subarray with the maximum sum 2D array in C#

using System;
using System.Linq;

namespace test2
{
    class Program
    {

        static void Main(string[] args)
        {
            int[][] int1 = new int[][] {
                new int[] {1, 2, -1, -4, -20},
                new int[] {-8, -3, 4, 2, 1},
                new int[] {3, 8, 10, 1, 3},
                new int[] {-4, -1, 1, 7, -6}
            };
            findMaxSubMatrix(int1);

            //int[] kk = kadane(new int[] { -3,-2,-1 });
            //foreach(var item in kk)
            //{
            //    Console.WriteLine(item);
            //}
            Console.Read();
        }

        public static int[] kadane(int[] a)
        {
            //result[0] == maxSum, result[1] == start, result[2] == end;
            int[] result = new int[] { int.MinValue, 0, -1 };
            int currentSum = 0;
            int localStart = 0;

            for (int i = 0; i < a.Length; i++)
            {
                currentSum += a[i];
                if (currentSum < 0)
                {
                    currentSum = 0;
                    localStart = i + 1;
                }
                else if (currentSum > result[0])
                {
                    result[0] = currentSum;
                    result[1] = localStart;
                    result[2] = i;
                }
            }

            // all numbers in a are negative
            if (result[2] == -1)
            {
                for (int i = 0; i < a.Length; i++)
                {
                    if (a[i] > result[0])
                    {
                        result[0] = a[i];
                        result[1] = i;
                        result[2] = i;
                    }
                }
            }

            return result;
        }

        /**
        * To find and print maxSum, (left, top),(right, bottom)
        */
        public static void findMaxSubMatrix(int[][] a)
        {
            int cols = a[0].Length;
            int rows = a.Length;
            int[] currentResult;
            int maxSum = int.MinValue;
            int left = 0;
            int top = 0;
            int right = 0;
            int bottom = 0;

            for (int leftCol = 0; leftCol < cols; leftCol++)
            {
                int[] tmp = new int[rows];

                for (int rightCol = leftCol; rightCol < cols; rightCol++)
                {

                    for (int i = 0; i < rows; i++)
                    {
                        tmp[i] += a[i][rightCol];
                    }
                    currentResult = kadane(tmp);
                    if (currentResult[0] > maxSum)
                    {
                        maxSum = currentResult[0];
                        left = leftCol;
                        top = currentResult[1];
                        right = rightCol;
                        bottom = currentResult[2];
                    }
                }
            }
            Console.WriteLine("MaxSum: " + maxSum +
            ", range: [(" + left + ", " + top +
            ")(" + right + ", " + bottom + ")]");
        }
    }
}