Sunday, September 20, 2020

Basic Concepts of JavaScript

Syntax Parsers

A program that reads your code and determines what it does and if it's grammar is valid. 

The code we written can not understand by the computer. So the code needed to be read character by character and convert it to the set of instructions that the computer can understand. To do that ,there is a compiler/ interpreter and Syntax Parser is part of it. 


Lexical Environment

Lexical environment is where something sits physically in the code we write. 

Lexical environment stores the variable defined in the function during the execution of that function.

Execution Context

Execution context is a wrapper to help manage the code that is running. There are lot of lexical environments and which one is currently running is managed via execution contexts. 

When ever we run the JavaScript code, it runs inside the execution context.

Name Value Pair

Name value pair is a name which maps to unique value. 

The name may be defined more than once, but only can have one value in a given context.

In below example, Name is "Address" and Value is "Main 100".

Address =  'Main 100'

Objects

Object is a collection of Name Value pairs. 

In below example, Address and Apartment are objects. 


Global Execution Context

Base execution context is the global execution context. When we say Global, it means the things where accessible in everywhere in our code. Global Execution creates two things which are Global Object and  special variable 'this'. 

eg : Inside the browser, the global object is 'window'. 

If there is any variables or functions which are not in the inside of the functions are attached to the global object (window). 
// Below code is not in the inside of the function. So that is global. 	
var a = 'Hello World';

function b(){  
}


Hoisting

Hoisting is setting up memory space for variables and functions. 

Before our code executing line by line, Java Script engine sets up the memory space for variables and functions created in entire code. So those functions and variables exists in the memory. When the code begins to execute line by line, it can access them. However when it comes to variables little bit different. When Java Script engine sets up the memory for a variable, it does not any assigned value for that.  That's why, it returns "undefined'.

See below Example. Even though, 'b' function call  is in top of the code, it will still executing not like other programming languages. And instead of error , 'a' is undefined. 






Undefined

When Java Scripts sets up the memory space for the variables or method,  automatically "undefined"  value will be set to them as the initial value . 

Single Threaded and Synchronous

Single threaded means one command one at a time. 

Synchronous means one line of code is executed at a time in the order it appears. 

Function Invocation

Function invocation means running a function. In Java Script we can use parenthesis '( )'.

Every time function is called a new execution context will be created. 


Variable Environment

Variable environment is the place where the variables lives and how they are related to each other.

When we have declare variable with the same name in different methods, it will be executed their own scope and in their own execution context. Even though they have same name , they are unique, distinct and they don't touch each other.  See the below example. 


Scope Chain

When a variable is used in JavaScript, the JavaScript engine will try to find the variable’s value in the current execution context. If it could not find the variable, it will look into the outer reference somewhere down below in the execution stack until it finds the variable or reaches global scope.  Outer Reference depends on where the function sits lexically. 



In below code, b() function physically sits inside a(). 


Scope

Scope in JavaScript refers to the accessibility or visibility of variables. That is, which parts of a program have access to the variable or where the variable is visible.

  •  Global Scope
Any variable that’s not inside any function or block (a pair of curly braces), is inside the global scope. The variables in global scope can be accessed from anywhere in the program.

  •   Local Scope or Function Scope 
Variables declared inside a function is inside the local scope. They can only be accessed from within that function, that means they can’t be accessed from the outside code. For example:
function a() {
  var greeting = 'Hello World!';
  console.log(greeting);
}

// Prints 'Hello World!'
a();

// Uncaught ReferenceError: greeting is not defined
console.log(greeting);

  • Block Scope
ES6(ECMAScript 6) introduced let variable, unlike var variables, they can be scoped to the nearest pair of curly braces. That means, they can’t be accessed from outside that pair of curly braces. For example:
function a() {
  var age = 100;
  if (age > 12){
    let dogYears = age * 7; //using let
    var noOfYears = age * 7; //using var
    console.log(`You are ${dogYears} dog years old!`);
  }
 
// Prints '700'
console.log(noOfYears);
    
// Uncaught Reference Error: dogYears is not defined
console.log(dogYears);
}

a();

References: Udemy.com

Saturday, September 19, 2020

LINQ

  • LINQ stands for Language Integrated Query. LINQ gives to capability to query objects.
  • We can query, 
    • Objects in memory eg :Collections)(LINQ to Objects), 
    • Databases (LINQ to SQL), 
    • XML(LINQ to XML) 
    • ADO.NET Data Sets (LINQ to Data Sets). 
    •  class Book
          {
              public string Name { get; set; }
              public decimal Price { get; set; }
          }
      
      class BookRepository
          {
      
              public IEnumerable GetBooks()
              {
                  var boooks = new List()
                  {
                      new Book() { Name="Fundamentals of C#" , Price = 20 },
                      new Book() { Name="ASP.NET MVC" , Price = 30},
                      new Book() { Name="Entity Framework" , Price = 12 },
                      new Book() { Name ="Java" , Price = 10 },
                      new Book() { Name = "Web API" , Price = 15 },
                      new Book() { Name="Java Script Basics" , Price= 25 }
                  };
      
                  return boooks;
              }
          }
      
      class Program
          {
              static void Main(string[] args)
              {
                  var books = new BookRepository().GetBooks();
                  var cheapbooks = new List();
                  
                  if(books != null)
                  {
                      cheapbooks = books.Where(book=>book.Price >12).ToList();
                  }
      
                  foreach (var book in cheapbooks)
                  {
                      Console.WriteLine(book.Name);
                  }
      
                  Console.Read();
              }
          }
      
      
Some of the more frequently used standard query methods and keywords

Method/Keywords Syntax Description
Where
Where(Predicate) Filters a sequence of values based on a predicate.
OrderBy OrderBy(Predicate) Sorts the elements of a sequence in ascending order.
ThenBy ThenBy(Predicate) Performs a subsequent ordering of the elements in a sequence in ascending order.
Select Select(Predicate) Projects each element of a sequence into a new form.
Take Take(int) Returns a specified number of contiguous elements from the start of a collection/sequence.
Skip Skip(int) Bypasses a specified number of elements in a sequence and then returns the remaining elements.
FirstOrDefault FirstOrDefault(Predicate) Returns the first element of a sequence, or a default value if no element is found.
First First(Predicate) Returns the first element of a sequence.
Single Single(Predicate) Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.

Thursday, September 17, 2020

Extension Methods

  • Extension methods allow us to add new methods to an existing class without changing its source code or creating a new class that inherits from it. 
As an example , suppose we need a shorten version of a very long post. In that case, there is no instance method in String class to get it done. Also we can not inherit the String class as it is sealed class and can not change or modify. In that situation, we can use extension methods to add new methods to an existing class.  
  • Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.
  • namespace ExtentionMethods
    {
        public static class StringExtention
        {
            //numofwords is 5 means we need first 5 words of the str
            public static string Shorten(this string str, int numofwords)
            {
                if (numofwords == 0)
                    return " ";
    
                var words = str.Split(' ');
    
                if (words.Length <= numofwords)
                    return str;
    
                return string.Join(" ", words.Take(numofwords));
            }
        }
    }
    
    
  • Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. The "Shorten" extension method can be brought into scope with this "using ExtensionMethods;".
  • using ExtentionMethods;
    using System;
    
    namespace Example_ExtentionMethods
    {
        class Program
        {
            static void Main(string[] args)
            {
                string post = "This is supposed to be a very long post...";
                var shortenpost = post.Shorten(5);
                Console.WriteLine(shortenpost);
                Console.Read();
            }
        }
    }
    
    
  • At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if String class has an instance method "Shorten(int count)" and we have an extension method with the same signature for System namespace, the compiler will always bind to the instance method. In that case, our method will never be called.  

  • For those occasions when the original source isn't under our control, when a derived object is inappropriate or impossible, or when the functionality shouldn't be exposed beyond its applicable scope, Extension methods are an excellent choice.

  • When implement extension methods for a given type, should remember below points, 
    • An extension method will never be called if it has the same signature as a method defined in the type.
    • Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they'll all be brought into scope by the using Extensions; directive.
References : udemy.com , docs.microsoft.com

Saturday, September 12, 2020

Events and Delegates

  • Events is a mechanism for communication between objects. When something happened to an object, It can notify other objects about that. 
  • Events are used to build a loosely couple application which classes and components are not tightly couple together. 
  • It helps to extend the application without breaking and changing the existing functionality. 
  • For an example, suppose we have a class  "VideoEncoder" which used to encode the video and send the email once video is encoded. In future, we might need to add another functionality  "send the text message" after the video is encoded. So then we have to add another functionality to send the messages. The problem is, we have to recompile the encoder class and all dependents of encoder class and redeploy. This is not a good idea. 

  • To solve this, we can use events. Here VideoEncoder is the publisher. mailService and messageService  are the subscribers. Video encoder does not know anything about the mailService and messageService. So in that case, in future if we need to add another subscriber , we can do it with minimal impact.  
       There are three main steps to implement above solution. 
  1. Define the delegate - Delegates works as a Agreement or contract between publisher and subscriber. It determines the signature of the event handler method in subscriber. 
  2. Define the Event based on that delegate.  
  3. Raise the event method which is protected ,virtual and void
    //By creating custom delegate and  EventArgs.Empty
        public class VideoEncoder
        {
            //1.Defines delegate
            //2.Defines a event based on event
            //3.raise the event
    
            public delegate void VideoEncodedEventHandler(object source, EventArgs args);
            public event VideoEncodedEventHandler VideoEncoded;
    
            public void Encode(Video video)
            {
                Console.WriteLine("Video Encoded");
                Thread.Sleep(3000);
    
                OnvideoEncoded();
            }
    
            protected virtual void OnvideoEncoded()
            {
                //VideoEncoded?.Invoke(this, EventArgs.Empty);
    
                if (VideoEncoded != null)
                {
                    VideoEncoded(this, EventArgs.Empty);
                }
    
            }
    
        }
    	
        class Program
        {
            static void Main(string[] args)
            {
                var video = new Video() { Name = "video1" };
                var videoEncoder = new VideoEncoder(); //publisher
                var mailService = new MailService();//Subscriber
                var messageService = new MessageService(); //Subscriber
    
                videoEncoder.VideoEncoded += mailService.OnVideoEncoded;
                videoEncoder.VideoEncoded += messageService.OnVideoEncoded;
                videoEncoder.Encode(video);
    	}
         }
    	
        public class MailService
        {
            public void OnVideoEncoded(object source, EventArgs args)
            {
                Console.WriteLine("Sending the email");
            }
        }
    	
    	public class MessageService
        {
            public void OnVideoEncoded(object source, EventArgs args)
            {
                Console.WriteLine("Sending the message");
            }
        }
        
        public class Video
        {
            public string Name { get; set; }
        }
    
  • Suppose we need to send addtional data (such as the video name which is encoded) to the subscriber. To do that, instead of EventsArgs we can use a custom class which derives from "EventArgs" class.
  •     //By creating custom  VideoEventArgs
        public class VideoEncoder
        {
            public delegate void VideoEncodedEventHandler(object source, VideoEventArgs args);
            public event VideoEncodedEventHandler VideoEncoded;
    
            public void Encode(Video video)
            {
                Console.WriteLine("Video Encoded");
                Thread.Sleep(3000);
    
                OnvideoEncoded(video);
            }
    
            protected virtual void OnvideoEncoded(Video video)
            {
                // VideoEncoded?.Invoke(this, new VideoEventArgs() { Video = video }); or
    
                if (VideoEncoded != null)
                {
                    VideoEncoded(this, new VideoEventArgs() { Video = video });
                }
    
            }
    
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var video = new Video() { Name = "PickUpLimes" };
                var videoEncoder = new VideoEncoder(); //publisher
                var mailService = new MailService();//Subscriber
                var messageService = new MessageService(); //Subcriber
    
                videoEncoder.VideoEncoded += mailService.OnVideoEncoded;
                videoEncoder.VideoEncoded += messageService.OnVideoEncoded;
                videoEncoder.Encode(video);
                Console.Read();
            }
        }
    
        public class VideoEventArgs : EventArgs
        {
            public Video Video { get; set; }
        }
    
        public class MailService
        {
            public void OnVideoEncoded(object source, VideoEventArgs args)
            {
                Console.WriteLine("Sending the email. Video name is " + args.Video.Name);
            }
        }
    
        public class MessageService
        {
            public void OnVideoEncoded(object source, VideoEventArgs args)
            {
                Console.WriteLine("Sending the message. Video name is " + args.Video.Name);
            }
        }
    
        public class Video
        {
            public string Name { get; set; }
        }
    
  • In .Net , same thing can be achieved using in-built EventHandler delegate instead of creating the custom delegate. EventHandler comes in two forms. One is normal form EventHandler  and other one is generic form EventHandler<T> . If we need to pass the data, we can use generic version. If not , can use the normal form.   
  •  	
        //using EventHandler delegate instead of custom delegate
        public class VideoEncoder
        {
            //Generic Form
            public event EventHandler<VideoEventArgs> VideoEncoded;
    
            //Normal Form
           // public event EventHandler VideoEncoded; 
    
            public void Encode(Video video)
            {
                Console.WriteLine("Video Encoded");
                Thread.Sleep(3000);
    
                OnvideoEncoded(video);
            }
    
            protected virtual void OnvideoEncoded(Video video)
            {
                //VideoEncoded?.Invoke(this, EventArgs.Empty);
    
                if (VideoEncoded != null)
                {
                    VideoEncoded(this, new VideoEventArgs() { Video = video });
                }
    
            }
    
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var video = new Video() { Name = "PickUpLimes" };
                var videoEncoder = new VideoEncoder(); //publisher
                var mailService = new MailService();//Subscriber
                var messageService = new MessageService(); //Subcriber
    
                videoEncoder.VideoEncoded += mailService.OnVideoEncoded;
                videoEncoder.VideoEncoded += messageService.OnVideoEncoded;
                videoEncoder.Encode(video);
                Console.Read();
            }
        }
    
        public class VideoEventArgs : EventArgs
        {
            public Video Video { get; set; }
        }
    
        public class MailService
        {
            public void OnVideoEncoded(object source, VideoEventArgs args)
            {
                Console.WriteLine("Sending the email. Video name is " + args.Video.Name);
            }
        }
    
        public class MessageService
        {
            public void OnVideoEncoded(object source, VideoEventArgs args)
            {
                Console.WriteLine("Sending the message. Video name is " + args.Video.Name);
            }
        }
    
        public class Video
        {
            public string Name { get; set; }
        }
    

 References : Udemy.com

Friday, September 11, 2020

Lambda Expression

  • It is an anonymous method which has no access modifier, no name and  no return statement. 
(input-parameters) => expression
  • We can write lambda expression to achieve something with less code. Below example shows how we can write a code to get multiplication of two numbers with lambda expression and without lambda expression. 
  •     class Program
        {
            static void Main(string[] args)
            {
                //args => expression
    
                //Without Lambda Expression
                Console.WriteLine(Square(5));
    
                //With Lambda Expression and Func
                Func<int, int> multiplication = number => number * number;
                Console.WriteLine(multiplication(5));
    
                Console.Read();
            }
    		
    	private static int Square(int x)
            {
                return x * x;
            }
        }
    	
    
  • We can also use lambda expressions when we write LINQ in C#.
  • int[] numbers = { 2, 3, 4, 5 };
    var squaredNumbers = numbers.Select(x => x * x);
    Console.WriteLine(string.Join(" ", squaredNumbers));
    // Output:
    // 4 9 16 25
    
    //Consider new BookRepository().GetBooks() returns list of books
    var listofBooks = new BookRepository().GetBooks();
    List<Books> cheapBooks = listofBooks.FindAll(b => b.price < 20).ToList();
    	
    

Thursday, September 10, 2020

Delegates

  • Delegate is an object that knows how to call a method or a  group of methods which have the same signature. 
  • It is a reference to a function.
  • Of course, we can call methods directly, but we need delegates for designing extensible and flexible applications. (Ex: Frameworks).
  • Imagine that you are designing a framework which is use for processing the photos. In that framework, you have defined few photo processing ways such as "Apply Brightness" , "Apply Contrast" and etc. In future, may be a client who is using your framework need to add their own photo filter which we haven't defined. So in that case, we have to change our application , recompile and redeploy. It is not a good idea. If we use delegates in our frameworks, client can add any no of filters without relying on us. See below example. 
  •     public class Photo
        {
            public Photo Load(string path)
            {
                return new Photo();
            }
        }
    	
        public class Filter
        {
            public void Resize(Photo photo)
            {
                Console.WriteLine("Changed the Size");
            }
    
            public void ChangeBrightness(Photo photo)
            {
                Console.WriteLine("Changed the brightness");
            }
    
            public void ChangeContrast(Photo photo)
            {
                Console.WriteLine("Changed contrast of the photo");
            }
    
        }
    	
        public class PhotoMaker
        {
            // Define the delegate
            public delegate void PhotoFilterHandler(Photo photo);
            public void Process(string path, PhotoFilterHandler photofilterhandler )
            {
                var photoObject = new Photo();
                var photo = photoObject.Load(path);
                photofilterhandler(photo);
            }
        }
    	
        class Program
        {
            static void Main(string[] args)
            {
                var photomaker = new PhotoMaker();
                var filter = new Filter();
    			
    	    // Adding ChangeBrightness filter
                PhotoMaker.PhotoFilterHandler filterhandler = filter.ChangeBrightness;
    			
    	    //Adding ChangeContrast filter
    	    filterhandler += filter.ChangeContrast;
    			
    	    // Remove ChangeBrightness filter
                filterhandler -= filter.ChangeBrightness;
    			
    	    //Adding custom method  without changing the PhotoProcess class
                filterhandler+= RemoveRedEye;
               
    	    photomaker.Process("", filterhandler);	
    
                Console.Read();
            }
    
            static void RemoveRedEye(Photo photo)
            {
                Console.WriteLine("Remove Red Eye");
            }
        }
    	
    
  • In .Net, there are two delegates which are generic. They are Action and Func. Difference between Func and Action is Func point to a method that has a return value and Action point to a method that returns void (no return type). 

  • Below code uses in built Action delegate instead of creating a custom delegate. 
  •  	
    public class Photo
        {
            public Photo Load(string path)
            {
                return new Photo();
            }
        }
    	
        public class Filter
        {
            public void Resize(Photo photo)
            {
                Console.WriteLine("Changed the Size");
            }
    
            public void ChangeBrightness(Photo photo)
            {
                Console.WriteLine("Changed the brightness");
            }
    
            public void ChangeContrast(Photo photo)
            {
                Console.WriteLine("Changed contrast of the photo");
            }
        }
    	
        public class PhotoMaker
        {
            public void Process(string path, Action<Photo> photofilterhandler )
            {
                var photoObject = new Photo();
                var photo = photoObject.Load(path);
                photofilterhandler(photo);
            }
        }
    	
        class Program
        {
            static void Main(string[] args)
            {
                var photomaker = new PhotoMaker();
                var filter = new Filter();
    			
                // Adding ChangeBrightness filter
                Action<Photo> filterhandler = filter.ChangeBrightness;
    			
    	    //Adding ChangeContrast filter
    	    filterhandler += filter.ChangeContrast;
    			
    	    // Remove ChangeBrightness filter
                filterhandler -= filter.ChangeBrightness;
    			
    	    photomaker.Process("", filterhandler);	
    
                Console.Read();
            }
        }

  • Use a delegate in the following circumstances:
      • An eventing design pattern is used.
      • The caller has no need to access other properties, methods, or interfaces on the object implementing the method.

      Monday, September 7, 2020

      Generics

      • Generic classes and methods combine reusability, type safety, and efficiency in a way that their non-generic counterparts cannot.
      • Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
      • For example, by using a generic type parameter T, you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:
      •     public class GenericList<T>
            {
                public void Print(T key)
                {
                    Console.WriteLine(key);
                }
        
            }
        	
           class TestGenericList
           {
            static void Main()
            {
               // Type of T is int
                var genericnumbers = new GenericList<int> ();
                genericnumbers.Print(5);
        
        	// Type of T is strings
                var genericStrings = new GenericList<strings>();
                genericStrings.Print("Janaki");
            }
        }
        	
        
      • The System.Collections.Generic namespace contains several generic-based collection classes.We can also create custom generic types and methods to provide your own generalized solutions and design patterns that are type-safe and efficient.
      Constraints on Type Parameters

      • Constraints specify the capabilities and expectations of a type parameter.
      • Without any constraints, the type argument could be any type. The compiler can only assume the members of System.Object, which is the ultimate base class for any .NET type.
      • If client code uses a type that doesn't satisfy a constraint, the compiler issues an error. 
      • Constraints are specified by using the where contextual keyword. Below are some examples. 
        • where T : struct -  The type argument must be a non-nullable value type. 
        • where T : class -  T must be a non-nullable reference type.
        • where T: <any base class> :  T must be a non-nullable reference type derived from the specified base class.  
        •     public class CalculatePrice<T> where TProduct : Product
              {
                  public decimal getPrice(TProduct product)
                  {
                      return product.price;
                  }
              }
              public class Product
              {
                  public decimal price { get; set; }
              }
          	
          
        • where T : <interface name> - The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.  
        • where T : new() - T is an object type that has a default constructor. 
        •     public class CalculatePrice<T> where TProduct : new()
              {
                  public void DoSomeThing()
                  {
                      var Onj = new T();
                  }
               }
          

      • Type parameters that have no constraints can not use !=, > ,== operators because there's no guarantee that the concrete type argument will support these operators.
      •     public class Utilities<T> where T :IComparable
            {
                public int Max(int a, int b)
                {
                    return a > b ? a : b;
                }
        
                public T Max (T a, T b)
                {
                    //Can not compare by using operators a>b
                    return a.CompareTo(b)>0 ? a : b;
                }
        
            }
        	
        
      References :  docs.microsoft.com and udemy.com