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();
        }
    }

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