Search This Blog

Tuesday, July 13, 2021

Angular: Component Data Transfer

Scenario : Let say you want to populate the dropdown on component 2 when there is a change in value of dropdown present in component 1 

==============================================================================
First of all we have to check the relation between different components
1. Parent (component 1) > Child (Component 2) - Sharing data via @input
2. Child (component 1) > Parent (Component 2) -Sharing Data via Output() and EventEmitter
3. Siblings with common parent. Child 1(component 1) > Child 2 (Component 2) -- use of both @output and @input together
4. Totally unrelated components  -- Sharing data with service, Sharing data with Route, NgRX


==============================================================================

1. Parent > Child 
Sharing data via @input decorator. 
parent.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'parent-component',
  template: `
    <child-component [childProperty]="parentProperty"></child-component>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent{
  parentProperty = "I come from parent"
  constructor() { }
}

child.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `
      Hi {{ childProperty }}
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childProperty: string;

  constructor() { }

}


==============================================================================
2. Child > Parent
Sharing Data via Output() and EventEmitter
parent.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'parent-component',
  template: `
    Message: {{message}}
    <child-component (messageEvent)="receiveMessage($event)"></child-component>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message:string;

  receiveMessage($event) {
    this.message = $event
  }
}

 

child.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hello!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

==============================================================================
3. Siblings with common parent. Child 1(component 1) > Child 2 (Component 2)


parent.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'parent-component',
  template: `
    Message: {{message}}
    <child-one-component (messageEvent)="receiveMessage($event)"></child1-component>
    <child-two-component [childMessage]="message"></child2-component>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message: string;

  receiveMessage($event) {
    this.message = $event
  }
}

child-one.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-one-component',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child-one.component.css']
})
export class ChildOneComponent {

  message: string = "Hello!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

child-two.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'child-two-component',
  template: `
       {{ message }}
  `,
  styleUrls: ['./child-two.component.css']
})
export class ChildTwoComponent {

  @Input() childMessage: string;

  constructor() { }

}
==============================================================================
4. Totally unrelated components
Sharing Data with a Service

When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should be using a shared service. When you have data that should always be in sync, I find the RxJS BehaviorSubject very useful in this situation.

data.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

 

first.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'first-componennt',
  template: `
    {{message}}
  `,
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  message:string;

  constructor(private data: DataService) {
      // The approach in Angular 6 is to declare in constructor
      this.data.currentMessage.subscribe(message => this.message = message);
  }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

 

second.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'second-component',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("Hello from Second Component")
  }

}
==============================================================================







Wednesday, July 7, 2021

Azure: Devops

What is DevOPS:
It is a set of practices followed by development team and operations team from committing a change to taking it to the production. 

Azure Devops
  • It is a tool which gives us an integrated environment to use different tools. 
  • We have different stages for code to move into production
    • Development – Visual Studio, Visual Studio Code, Eclipse…
    • Code check in – TFS, GIT, …
    • Build code/ build servers – .net compilers, Maven, Gradle, pipelines  ..
    • Testing – Selenium, Junits….
    • Release – Jenkins, Bamboo
    • Deployment – Docker, AWS, Azure … 
    • Operations – Kubernetes, Redhat Openshift, 
    • Monitoring – Splunk..

Sunday, July 4, 2021

CSharp: JWT Authentication

Q: How we can do JWT Authentication in case of .net Core application?
------------------------------------------------------------------------------------------------------------------------------------------

Step 1:
Create a Login Controller and on top of that controller give attribute [authorize], this attribute will ensure that all actions inside this controller will be authenticated first. 

Step 2:
Create a action method "authenticate" in above controller and give attribute [AllowAnonymous] to it. This will make sure to bypass the authentication on it. 
>> We have two important input parameters to this method. username and password. 
>> This is the entry point to our application where we will check if entered username and password are correct or not. (usually database we use to check)
>> If username and password are correct we will use it to generate token and return the JWT token value. 
>> UI application can use this JWT token and send it with its further calls

Step 3:
Inside above authenticate method, create another method generateJWTToken(). Call this method on successfull validation of username and password. 

Step4:
>> Inside generateJWTToken method pass a secret key. This secret key can be maintained in config file or in database. 
>> In above method using secret key, algo type and some other thigns generate token. 
>> We might have to install few packages from nuget at thsi stage. 
>> Once the key is generated return it to the main function/ 

Step 5:
Startup.ConfigureService. Add service service.AddAuthentication in startup.ConfigureService method. We have to add few more properties here. 

Step 6:
Add app.UseAuthenticate in Startup.Configure method as a middleware. 

Now when we call any other method authentication logic will be in picture and it will check for jwt token is present in the call or not. if it is present that code will check for its validity. 



Saturday, July 3, 2021

Csharp: Factory Pattern


>> Main() method also known as client side method. So the tradational approach of calling a method of a particular class is to create an object of class with the help of new keyword and then call the required method of this class. 





============================================================================== Quick Revision

Below is the final version with factory pattern implemented. 

 interface Igetdetails
    {
        void getname();
        void getfathername();
    }

    class Teacher : Igetdetails
    {
        public void getname()
        {
            Console.WriteLine("Teacher name");
        }

        public void getfathername()
        {
            Console.WriteLine("Teacher Father name");
        }

    }

    class Student : Igetdetails
    {
        public void getname()
        {
            Console.WriteLine("Student name");
        }

        public void getfathername()
        {
            Console.WriteLine("Student Father name");
        }
    }

    class factory
    {
        public static Igetdetails createobject(string type)
        {
            Igetdetails obj = null;
            if (type.ToLower() == "teacher")
            {
                obj = new Teacher();
            }
            else
            {
                obj = new Student();
            }
            return obj;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var clientobj = factory.createobject("student");
            clientobj.getfathername();

            Console.ReadKey();
        }
    }

==============================================================================

Wednesday, June 30, 2021

Csharp: Garbage Collector

Confusing Terms:
  1. IDispose -- unmanaged, user can call
  2. Difference between Close and Dispose
  3. GC.Collect -- managed, user can call
  4. Finalize -- unamanged, user can not call
  5. Destructor
  6. SupressFinalize
  7. Close
================================================================================
IDispose : 
  • Used for disposing unmanaged resources 
  • When we implement IDispose interface, Dispose is the method where we dispose the umanged resource. 
  • In some objects we have two options 1. dispose and 2. Close. For file streaming both options are same. 
Void dispose()
{
this.close();
Dispose(true);
GC.SupressFinalize(this);
}
===============================================================================
Difference between Close and Dispose

Close
1. Disconnected with DB
2. Release resources.
3. SQL Connection object not released, it is just close and can be open again. 

Dispose
1. Disconnected with DB
2. Release resources.
3. Release SQL connection object as well. 

Example: 
try 
    
        string constring = "Server=(local);Database=my; User Id=sa; Password=sa";                             SqlConnection sqlcon = new SqlConnection(constring); 
        sqlcon.Open(); // here connection is open 
        // some code here which will be execute 
    
catch // code will be execute when error occurred in try block } 
finally 
    
        sqlcon.Close(); // close the connection 
        sqlcon.Dispose(); // desroy the connection object 
    }

===============================================================================
GC.Collect:

1. this method is used to clear manged resources. 
2. Unlike Finalize which can not be called by user, GC.Collect can be called by user. 
3. Also GC.Collect is to work on managed resrouce while GC.Finalize is for unmanaged resources. 
4. It will force the GC generations to start. 

===============================================================================
Finalize():

1. This method is used to clear the unmanaged resource like IDispose. 
2. This method can only be called by GC as a part of destructor. 
3. We can not call it explicitly. We have to implemetn IDispose instead, if we want to take care of un managead resource. 

===============================================================================
Destructor:

1. Finalize also called as destructor of the class. Finalize()
2. It can not be explicitly called except for the destructor calling itself behind the scene. 
3. Finalize can be used to clean unmanged resource in C# with the help of GC. 

~myclass()
{
this.Dispose(); // behind the scene finalize would also be called
}

===============================================================================
SupressFinalize()

1. This method is to tell the CLR that we have already taken care of releasing unmanged resources and GC need not to act on it. 

===============================================================================

Tuesday, June 29, 2021

Ctor: Base class, Child class

  class baseclass
    {
        public baseclass()
        {
            Console.WriteLine("--base class ctor--");
        }
    }

    class childclass1 : baseclass
    {
        public childclass1()
        {
            Console.WriteLine("--Child class ctor--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            baseclass b = new childclass1();
            Console.ReadKey();
        }

    }

output of above both lines will be same. below o/p will be printed twice. 
--base class ctor--
--Child class ctor--

Base class Child Class relation

Case 1
    class baseclass
    {
        public void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.childmethod1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }

c.childmethod1() -- output would be "--Child Method1--"
c.basemethod(); -- No error, no warning, o/p would be "--base method--". Child class has access to its parent public and protected members. 

----------------------------------------------------------------------------------------------------------------------------------------
Case 2

    class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }

c.basemethod(); -- No error, no warning, o/p would be "--base method--" as nothing is override in child method. and code flow is from parent to child as waterfall. So parent method will be called. 
----------------------------------------------------------------------------------------------------------------------------------------
Case 3:

class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }

        public new / <<space>> / virtual / override void basemethod()
        {
            Console.WriteLine("--base method from child--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }
c.basemethod(); -- No error, no warning, o/p would be "--base method from child--" as object is pure form of child class.it wont simply look at parent method. 
----------------------------------------------------------------------------------------------------------------------------------------
Case 4:

class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }

        public new / <<space>> / virtual void basemethod()
        {
            Console.WriteLine("--base method from child--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            baseclass b = new childclass1();
            b.basemethod();

            Console.ReadKey();
        }

    }
c.basemethod(); -- o/p would be "--base method--" now method will be from parent to child as waterfall. Since there is no override keyword. basemethod of parent will be called in above case. 
Even if parent doent have virtual keyword then still only parent method would have called. 

----------------------------------------------------------------------------------------------------------------------------------------
Case 5:

 class baseclass
    {
        public virtual void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }

        public override void basemethod()
        {
            Console.WriteLine("--base method from child--");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            baseclass b = new childclass1();
            b.basemethod();

            Console.ReadKey();
        }

    }

c.basemethod(); -- o/p would be "--base method from child--" here method will be called from parent to child. since parent has virtual keyword and child has override keyword, method of child would be called. 

----------------------------------------------------------------------------------------------------------------------------------------
Case 6:

 class baseclass
    {
        public void basemethod()
        {
            Console.WriteLine("--base method--");
        }
    }

    class childclass1 : baseclass
    {
        public override void childmethod1()
        {
            Console.WriteLine("--Child Method1--");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            childclass1 c = new childclass1();
            c.basemethod(); // is this possible? error, warning, nothing?

            Console.ReadKey();
        }

    }

Compile time error: Override can not exists without virtual/abstract keyword. While virtual can exists without override. 

----------------------------------------------------------------------------------------------------------------------------------------





----------------------------------------------------------------------------------------------------------------------------------------





----------------------------------------------------------------------------------------------------------------------------------------