Thursday, February 27, 2020

How to update User Multi-Factor Authentication in Azure Active Directory?

first step you log into the azure portal


second click on the Azure Acitve Directory to launch AAD blade, then click on the Users on the blade.








third click on the Multi-Factor Authentication icon on the menu bar to launch Multi-Factor Authentication Services page











fourth click on the service setting tab to access the notification setting





 

Python 101

i joined a Harvard Online Introduction course using Python for Research.

it is really good to get to know a new programming language. here is some 101 fact for Python

1. [:]  is for Array slice which is a shadow copy of the array content

for example a=[1 , 2 , 3 , 4]

b=a   #a and b reference to the same object. however
b=a[:]   #a and b have same content. but reference to two different object due to shadow copy of array a.

2. global value vs local variable

  x=1 # which is a global value

   def printx();
     x=2  # x is a local variable which different from the global value above
    print(x) # print function will output 2 since the print function execute inside the printx fucntion.

print(x) # output will be 1 since global x is 1

another example shows that global and local variable do not interference each other

x=1
while x<5:
 x *=2

the final value of x is 4

3. # is the inline comment character, use Ctrl + / to comment out or uncomment highlight rows or multi line delimiter (""")


4. len([]) will only count distinct value only
len[1, 1, 2, 3, 3, 4] =4

5. a=["Hello, World"]
a[5:] will be equal to a.slice(5) which will be result in ", World"

6. the function block is identified the indentation
for example
def myFunc():
      #line 1
      #line 2
      #line 3 the function is end here

#this line is  out of function. same applies to for loop and while loop.
python use indentation for to indicate a block of code

Happy programming. enjoy the fun on learning a new language.





Monday, February 24, 2020

A cool tool to validate the yaml content on building the docker-compose.yml file.

after i added a docker-compose project the asp.net solution, then i try to build the docker-compose file to generate all the images.

however i always encounter error without specific message. the root of cause this issue is that
YAML follows indentation structure very strictly. one extra space or tab will cause this issue.

this online tool will be a great help on validation your content in YAML.

https://onlineyamltools.com/validate-yaml

here is my sample docker-compose file, after i pasted it in the yaml box, the line causes the issue highlights immediately in the errors box

version: '3.7'

services:
  webapi_dotnetcore:
    image: ${DOCKER_REGISTRY-}webapidotnetcore
    build:
      context: .
      dockerfile: WebAPI_DotNetCore/Dockerfile

  db:
    image: mcr.microsoft.com/mssql/server
    environment:
         - ACCEPT_EULA=Y
         - SA_PASSWORD=Password_01
  ports:
   - '1433:1433'


Sunday, February 23, 2020

How to fix COPY failed COPY failed: stat /var/lib/docker/tmp/docker-builder/appFolder/App.csproj: no such file or directory issue in Docker Build command to create a docker image in Microservice project?

I am playing with the Microservices application with docker enable in my local development.

after i completely setup my project. i try to manipulate the project with docker building command.

since the dockerfile had been automatically generated by visual studio, when i create a dotnet core web api project with docker support.







how ever when i run this command to create a docker image

docker build . -t myimage -f dockerfile

it encountered an error on the copy step. i put the step with error in bold.

FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build
WORKDIR /src
COPY ["simplemicroservicesApp/simplemicroservicesApp.csproj", "simplemicroservicesApp/"]
RUN dotnet restore "simplemicroservicesApp/simplemicroservicesApp.csproj"
COPY . .
WORKDIR "/src/simplemicroservicesApp"
RUN dotnet build "simplemicroservicesApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "simplemicroservicesApp.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "simplemicroservicesApp.dll"]

here is the error message

Step 7/17 : COPY ["simplemicroservicesApp/simplemicroservicesApp.csproj", "simplemicroservicesApp/"]
COPY failed: stat /var/lib/docker/tmp/docker-builder663072116/simplemicroservicesApp/simplemicroservicesApp.csproj: no such file or directory

the root of cause of this issue is that Visual Studio generated the dockerfile inside the project folder. actually it should be in the solution folder.

by default the dockerfile was generated inside the project folder






actually it should be in the solution level in order to build a docker image properly.





after i cut and paste the file into the solution folder, then navigate to the solution folder in window CMD, and execute the following line to create a docker image.

docker build . -t myimage -f dockerfile



Saturday, February 22, 2020

how to build a link list tree in C#?

i had completed a hackerrank challenge a week ago.. it is quite interesting topic. since C# already provide the LinkList object in the .net framework.

i need to use c# to build my own LinkList class. the recursion is the key to solve this challenge.

here is the sample code. Happy programming


using System;
class Node
{
public int data;
public Node next;
    public Node(int d){
        data=d;
        next=null;
    }
}
class Solution {
public static  Node insert(Node head,int data)
{
      //Complete this method
      Node newNode=new Node(data);
      if(head==null){
         // Console.WriteLine($"{newNode.data} ,{data}");
          return newNode;
        }
      else if(head.next ==null){
          //Console.WriteLine($"{newNode.data} ,{data}");
            head.next=newNode;
       }
       else insert(head.next, data);
      return head;
      //Console.WriteLine($"{head.data} ,{data}");
      //return head;
    }
public static void display(Node head)
{
Node start=head;
while(start!=null)
{
Console.Write(start.data+" ");
start=start.next;
}
}
    static void Main(String[] args) {
Node head=null;
        int T=Int32.Parse(Console.ReadLine());
        while(T-->0){
            int data=Int32.Parse(Console.ReadLine());
            head=insert(head,data);
        }
display(head);
}
}


how to remove duplicate records in the linked list?

the hackerrank post today challenge is to remove duplicate record from integer linklist.

i use hashset to store the unique integer from the linklist, if the current node data already exist in the hashset. i simply pointing the previous node to the current node next pointer. if not found, i add the current node data to the hashset and move to the next node.


here is the sample code in C#

using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node next;
    public Node(int d){
        data=d;
        next=null;
    }
}
class Solution {
  public static Node removeDuplicates(Node head){
    //Write your code here
    if (head==null){
        return null;
    }
    HashSet<int> hashset =new HashSet<int>();
    Node prevNode = head;
    Node currentNode =prevNode.next;
    if(currentNode==null){
        return head;
    }
    hashset.Add(prevNode.data);
    while(currentNode!=null)
        {
        if(hashset.Contains(currentNode.data))
            {
            prevNode.next=currentNode.next;
            currentNode=currentNode.next;
        }
        else{
            hashset.Add(currentNode.data);
              prevNode=currentNode;
            currentNode=currentNode.next;
        }
    }
    return head;
  }
public static  Node insert(Node head,int data)
{
        Node p=new Node(data);
if(head==null)
head=p;
else if(head.next==null)
head.next=p;
else
{
Node start=head;
while(start.next!=null)
start=start.next;
start.next=p;
}
return head;
    }
public static void display(Node head)
{
Node start=head;
while(start!=null)
{
Console.Write(start.data+" ");
start=start.next;
}
}
    static void Main(String[] args) {
Node head=null;
        int T=Int32.Parse(Console.ReadLine());
        while(T-->0){
            int data=Int32.Parse(Console.ReadLine());
            head=insert(head,data);
        }
      head=removeDuplicates(head);
display(head);
}
}

Friday, February 21, 2020

how to get an access token and use the token to access key vault to load secret from Azure CLI (Bash)?

first i create an azure key vault with the following az command

az keyvault create --resource-group myResource-rg --name mykeyvault 

second i can store the secret(for example password) in the key vault

az keyvault secrete create --name dbpassword --vault-name mykeyvault --description "database password" --value "mysecretpassord"


third step is generate the access token to access the key vault

access_token=(curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net' -H Metadata: true -r '.access_toekn')

final step is to use the token to load the password out of key vault
(dbpassword is name of the password set in the key vault secret, mykeyvault is the name of the key vault that i had setup in Azure)

 db_password=$(curl https://mykeyvault.vault.azure.net/secrets/dbpassword?api-version=2016-10-01 -H "Authorization: Bearer $access_token" --silent | jq -r '.value')

how to revoke the disk access in the Azure Replication?

after i complete a lab on  Site Recovery with Azure Replication, I encountered an error when i try clean up the resource.

 "There is an active shared access signature outstanding for disk molvm_disk1_6fd65a43abc14b58857b6beba271a17a-ASRReplica. Call EndGetAccess before attaching or deleting the disk. Learn more here: aka.ms/revokeaccessapi."


the error is stem from the disk had been enable the shared read access for replication

after i run the following command in Azure CLI, then i can successfully remove the resource.

az disk revoke-access --name MyManagedDisk --resource-group MyResourceGroup

for more information, please view the link below

https://docs.microsoft.com/de-de/cli/azure/disk?view=azure-cli-latest#az-disk-revoke-access


how to use Queue to implement a binary searh true Level Order algorithm?

Currently i had joined the Hackerrank challenag for 30 days

today i got a very interesting topic to use Queue to implement the level Order function

using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; class Node{ public Node left,right; public int data; public Node(int data){ this.data=data; left=right=null; } } class Solution{ static void levelOrder(Node root){ Queue<Node> nodeQueue=new Queue<Node>(); if(root !=null){ nodeQueue.Enqueue(root); } while(nodeQueue.Count>0){ Node current=nodeQueue.Dequeue(); Console.Write($"{current.data} "); if(current.left !=null){ nodeQueue.Enqueue(current.left); } if(current.right !=null){ nodeQueue.Enqueue(current.right); } } } static Node insert(Node root, int data){ if(root==null){ return new Node(data); } else{ Node cur; if(data<=root.data){ cur=insert(root.left,data); root.left=cur; } else{ cur=insert(root.right,data); root.right=cur; } return root; } } static void Main(String[] args){ Node root=null; int T=Int32.Parse(Console.ReadLine()); while(T-->0){ int data=Int32.Parse(Console.ReadLine()); root=insert(root,data); } levelOrder(root); } }

Thursday, February 20, 2020

how to fix commit issue "fatal: unable to auto-detect email address (got 'danny@cc-fe053af4-868f6d6c9-brgtr.(none)')" against the Github?

i have a simple action to make a commit against Github

git init -- to initialize the local repository

git add .  --to check in the change in the local

git commit -m "my comment"

then i got an error


*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'danny@cc-fe053af4-868f6d6c9-brgtr.(none)')


the easy and straightforward solution is manually add user section in the config file in .git folder.


[user]
name=github username
email=email for github login







Tuesday, February 11, 2020

How to solve "ERROR TypeError: Cannot read property 'subscribe' of undefined" in angular development?

after i completed my sample angular application, i ran it the result did show in the page.

however there was an error message in the console in the development tool.

"ERROR TypeError: Cannot read property 'subscribe' of undefined" 

core.js:5828 ERROR TypeError: Cannot read property 'subscribe' of undefined
    at AppComponent.ngOnInit (app.component.ts:24)
    at callHook (core.js:3892)
    at callHooks (core.js:3856)
    at executeInitAndCheckHooks (core.js:3797)
    at refreshView (core.js:11706)
    at renderComponentOrTemplate (core.js:11814)
    at tickRootContext (core.js:13290)
    at detectChangesInRootView (core.js:13324)
    at RootViewRef.detectChanges (core.js:15004)

    at ApplicationRef.tick (core.js:42192)


THE ROOT CAUSE OF THIS ERROR IS StocksService had been subscribed twice, one in the AppComponent, another one is in the DashBoard Component. after i comment out the code in the AppComponent. the error is gone. it is also a bad idea to call the service the AppComponent. since i had the routing enable.


export class AppComponent {
  stocksArray<StockInterface>;
  symbolsArray<string>;
  constructor(private serviceStocksService){
    //  this.service.load(['APPL']).subscribe(stocks=>{
    //    this.stocks=stocks;
    //  }
      // );
   }

   ngOnInit(){
     this.service.load(this.symbols).subscribe(stocks=>{
       this.stocks=stocks;
     });
   }
}



export class DashboardComponent implements OnInit {
  stocksArray<StockInterface>;
  symbolsArray<string>;
  constructor(private serviceStocksService) {
      this.symbols=service.get();
   }
  ngOnInit(): void {
    this.service.load(this.symbols).subscribe(
      stocks=>this.stocks=stocks);
  }
}

Monday, February 10, 2020

What is the normalization in the Database Design?

First normalization: to break down the cell into smallest unit. single value entry

second normalization: the repeat column should be abstract to a table with primary key reference.

third normalization: no transitional dependencies. such as salutation, or total


how to check a 2D point within the polygon?

in my recent interview, the interviewer gave a problem to solve

I implemented a program with  crossing number algorithm

using System;
using System.Collections.Generic;
using System.Linq;
namespace Polygon_Graph
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Point> polygon = new List<Point>();
            Console.WriteLine("please enter your points to build the polygon, enter exit to terminate the program");
            string input = Console.ReadLine();
            while (input != "0 0")
            {
                polygon.Add(GeneratePoint(input));
                input = Console.ReadLine();
            }
            Console.WriteLine("please enter your test point:");
            while (true)
            {
                input = Console.ReadLine();
                if (input == "exit")
                    break;
                Point testPoint = GeneratePoint(input);
                string resultMsg = string.Empty;
                if (IsPointOutOfBoundary(polygon, testPoint, ref resultMsg))
                {
                    Console.WriteLine("No, not inside");
                }
                else
                {
                    if (resultMsg == "Yes, inside")
                    {
                        Console.WriteLine("Yes, inside");
                    }
                    else
                    {
                        bool validateResult = ValidByCrossingNumber(polygon, testPoint);
                        if (validateResult)
                        {
                            Console.WriteLine("Yes, inside");
                        }
                        else
                        {
                            Console.WriteLine("No, not inside");
                        }
                    }
                }
            }
        }
        private static bool IsPointOutOfBoundary(List<Point> polygon, Point testPoint, ref string resultMsg) {
            var result = false;
            int minX = polygon[0].X;
            int maxX = polygon[0].X;
            int minY = polygon[0].Y;
            int maxY = polygon[0].Y;
            for (var i = 1; i < polygon.Count(); i++)
            {
                Point q = polygon[i];
                minX = Math.Min(q.X, minX);
                maxX = Math.Max(q.X, maxX);
                minY = Math.Min(q.Y, minY);
                maxY = Math.Max(q.Y, maxY);
            }
            //check for the boundary if the test point out of boundary return false
            if (testPoint.X < minX || testPoint.X > maxX || testPoint.Y < minY || testPoint.Y > maxY)
            {
                result = true;
            }
            else if (testPoint.X == minX && testPoint.Y < maxY || testPoint.X == maxX && testPoint.Y < maxY)
            {
                resultMsg = "Yes, inside";
            }
            return result;
        }
        private static bool ValidByCrossingNumber(List<Point> polygon, Point testPoint)
        {
            bool result = false;
            var j = polygon.Count() - 1;
            for (var i = 0; i < polygon.Count(); i++)
            {
                if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y)
                {
                    if (polygon[i].X + (testPoint.Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) / (polygon[j].Y - polygon[i].Y) > testPoint.X)
                    {
                        result = !result;
                    }
                }
                j = i;
            }
            return result;
        }
        private static Point GeneratePoint(string inputString)
        {
            string[] strArray = inputString.Split(' ');
            if (strArray.Length >= 2)
            {
                return new Point
                {
                    X = ConvertToInt(strArray[0]),
                    Y = ConvertToInt(strArray[1])
                };
            }
            return null;
        }
        private static int ConvertToInt(string str)
        {
            try
            {
                return Int32.Parse(str);
            }
            catch {
                return 0;
            }
        }
    }
        class Point {
            public int X { get; set; }
            public int Y { get; set; }
        }
}

Thursday, February 6, 2020

how to resolve the docker building issue "dial tcp: lookup auth.docker.io on 192.168.65.1:53: no such host"?

i try to play with a very simple script to build a docker from my local machine

the error came up immediately with following message

//Command to be execute to build a docker
λ docker build . -t hostname
Sending build context to Docker daemon  4.608kB
Step 1/5 : FROM nginx:latest
Get https://registry-1.docker.io/v2/library/nginx/manifests/latest: Get https://auth.docker.io/token?scope=repository%3Alibrary%2Fnginx%3Apull&service=registry.docker.io: dial tcp: lookup auth.docker.io on 192.168.65.1:53: no such host



The root cause of this issue is that though the Docker Desktop is running in my local, however i did not log into the docker hub.


after i log into the docker and run the command again. the result is succeed.

Sending build context to Docker daemon  4.608kB
Step 1/5 : FROM nginx:latest
latest: Pulling from library/nginx
bc51dd8edc1b: Pull complete
66ba67045f57: Pull complete
bf317aa10aa5: Pull complete
Digest: sha256:ad5552c786f128e389a0263104ae39f3d3c7895579d45ae716f528185b36bc6f
Status: Downloaded newer image for nginx:latest
 ---> 2073e0bcb60e
Step 2/5 : ARG VERSION
 ---> Running in 75e8c63f7258
Removing intermediate container 75e8c63f7258
 ---> 74f3c847d731
Step 3/5 : ENV VERSION=$VERSION
 ---> Running in 6d1ef8500966
Removing intermediate container 6d1ef8500966
 ---> 3de0be6fa8a0
Step 4/5 : COPY hostname.sh .
 ---> 451b37ea6530
Step 5/5 : CMD ["/hostname.sh"]
 ---> Running in b71381f7ba23
Removing intermediate container b71381f7ba23
 ---> 47870a87b284
Successfully built 47870a87b284
Successfully tagged hostname:latest
















A simple and stupid PhoneBook in C#

I just completed a HackerRank Challenge today. the topic is about to write a program for a phonebook which allow the user to input contact information and support searching contact by name.

initial i finished it only support number of input search.Finally i have to use the while to support unlimited number of search..


here is the snippet of code. i hope you will enjoy it

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT.
Your class should be named Solution */
Dictionary<string, string> phoneBook=new Dictionary<string, string>();
int totalContact=Int32.Parse(Console.ReadLine());
for(var i=0; i<totalContact; i++){
string input=Console.ReadLine();
string[] strArray=input.Split(null);
if(strArray.Length>=2){
phoneBook.Add(strArray[0], strArray[1]);
}
}
//use the while loop to support unspecific number of search
while(true){
try{
string key=Console.ReadLine();
if (phoneBook.ContainsKey(key))
{
Console.WriteLine($"{key}={phoneBook[key]}");
}
else
{
Console.WriteLine("Not found");
}
}catch(System.Exception ex){
break;
}
}
}
}

cheer

Tuesday, February 4, 2020

Azure CLI helpful tips

1. use -h in the az group to show all available options for the command.

C:\Users>az group -h

Group
    az group : Manage resource groups and template deployments.

Subgroups:
    deployment : Manage Azure Resource Manager deployments.
    lock       : Manage Azure resource group locks.

Commands:
    create     : Create a new resource group.
    delete     : Delete a resource group.
    exists     : Check if a resource group exists.
    export     : Captures a resource group as a template.
    list       : List resource groups.
    show       : Gets a resource group.
    update     : Update a resource group.
    wait       : Place the CLI in a waiting state until a condition of the resource group is met.


2. use az interactive to work in the interactive mode.

it is very cool feature to use. even though it is in preview mode. it supports the intelli-sense, it shows the autocomplete during your typing








3. use --output flag to format the output display
when you try to list all account using az account list, the output will be in json format

we can use tsv to show the result in table format.

az account list --output tsv

Sunday, February 2, 2020

How to add Azure Logic App project template in Visual Studio?

1. Launch Visual Studio and click on the Extensions mean tab and select Manage Extensions.



2. Type Logic in the search box and hit enter, then select Azure Logic App Tools for Visual Studio 2019



3. double click on it to install the extension. close the visual studio in order to complete the modification.

4. now you can create a Azure Logic App project in Visual Studio 2019. please Note Azure Logic App Template resides in the Azure Resource Group Project Template. when you create a Azure Resource Group Project, you will direct to the windows to select a Azure Template