KarthikTechBlog https://karthiktechblog.com/ Everyone can code! Wed, 05 Jan 2022 01:50:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 https://karthiktechblog.com/wp-content/uploads/2022/08/cropped-lsc-logo-png-new-3-32x32.png KarthikTechBlog https://karthiktechblog.com/ 32 32 How to implement time-based caching in Angular using HTTP Interceptor https://karthiktechblog.com/angular/how-to-implement-time-based-caching-in-angular-using-http-interceptor/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-implement-time-based-caching-in-angular-using-http-interceptor https://karthiktechblog.com/angular/how-to-implement-time-based-caching-in-angular-using-http-interceptor/#comments Wed, 05 Jan 2022 01:50:49 +0000 https://karthiktechblog.com/?p=1013 Introduction Implementing time-based caching in Angular using HTTP Interceptor is simple and easy. This post shows step by step process of creating simple caching logic for all outgoing HTTP GET API calls. Why implement caching? Angular is used to develop SPA applications. Most of the pages in an application will call external HTTP APIs (GET) […]

The post How to implement time-based caching in Angular using HTTP Interceptor appeared first on KarthikTechBlog.

]]>
Introduction

Implementing time-based caching in Angular using HTTP Interceptor is simple and easy. This post shows step by step process of creating simple caching logic for all outgoing HTTP GET API calls.

How to implement time-based caching in Angular using HTTP Interceptor

Why implement caching?

Angular is used to develop SPA applications. Most of the pages in an application will call external HTTP APIs (GET) to retrieve data in order to display it on the screen. Let’s say, a user navigates to the same page multiple times which is normal.

This will lead to calling the same GET API multiple times though the data is not changed. A typical example is to get a list of product categories on a page which won’t change so often or even if doesn’t change at all.

By implementing caching in the front end or we can say as client-side, we will avoid calling the same API often. This will save some network calls and since data is served from the local cache, the application will be faster and give a rich user experience.

Short video tutorial

What is HTTP Interceptor?

In simple words, HTTP Interceptor in Angular is used to intercept the outgoing HTTP API calls and perform some action. E.g. we can intercept the outgoing call and add or modify the request/response. HTTP Interceptors transform the outgoing request before passing it to the next interceptor in the chain, by calling next.handle(transformedReq).

To know more about HTTP Interceptor, refer here.

Implementation of Caching

First, we will create a service named “HttpCacheService” which does the below actions.

  1. Used to retrieve saved response of a particular URL.
  2. For any new outgoing request, used to save the URL and its response.
  3. Invalidate a particular URL response.
  4. Invalidate the entire cache.
import { Injectable } from '@angular/core';
import { HttpResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpCacheService {

  private requests: any = { };

  constructor() { }

  get(url: string): HttpResponse | undefined {
    return this.requests[url];
  }

  put(url: string, response: HttpResponse): void {
    this.requests[url] = response;
  }

  invalidateUrl(url: string): void {
    this.requests[url] = undefined;
  }

  invalidateCache(): void {
    this.requests = { };
  }

}

Implementing HTTP Interceptor

We will implement an HTTP interceptor named “CacheInterceptor

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { HttpCacheService } from '../services/http-cache.service';


@Injectable()
export class CacheInterceptor implements HttpInterceptor {
  constructor(
  private cacheService: HttpCacheService
  ) {}

  intercept(
    req: HttpRequest,
    next: HttpHandler
  ): Observable> {
    

    //check if the outgoing calls are GET and MRDH APIs
    if (req.method === 'GET' ) { 
      // attempt to retrieve a cached response
      const cachedResponse:
        | HttpResponse
        | undefined = this.cacheService.get(req.url);

      // return cached response
      if (cachedResponse) {
        console.log(`Returning a cached response: ${cachedResponse.url}`);
        console.log(cachedResponse);
        return of(cachedResponse);
      }

      // send request to server and add response to cache
      return next.handle(req).pipe(
        tap((event) => {
          if (event instanceof HttpResponse) {
            console.log(`Adding item to cache: ${req.url}`);
            this.cacheService.put(req.url, event);
          }
        })
      );
    }
    else {
        // pass along non-cacheable requests 
        return next.handle(req);
    }
  }
}

This interceptor will intercept all outgoing HTTP API calls. The Cache Interceptor will save the URL and its response detecting upon a GET API call. If we don’t find any saved response, we will let the call continue and save the response and its URL in our HttpCacheService.

To make this work we need to register this in the main NgModule provider.

Use this code to place it in the NgModule of the application.

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }
  ]
.... other codes ignored

Great, that’s it. it’s as simple as that.

Wait wait. The title says time-based cache implementation. Right, let’s implement that next.

TimerService is used to start the timer when the first response is cached. After which the interceptor checks for a particular amount of time and invalidates the cache.

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({ providedIn: 'root' })
export class TimerService {
  private isTimerStarted = false;
  public dateNow = new Date();
  public dDay = new Date();
  milliSecondsInASecond = 1000;
  hoursInADay = 24;
  minutesInAnHour = 60;
  SecondsInAMinute = 60;

  public timeDifference: any;

  constructor() {}

  private getTimeDifference() {
    this.timeDifference = this.dDay.getTime() - new Date().getTime();    
  }
  
  startTimer() {
    if (!this.isTimerStarted) {
   
      this.dDay.setMinutes(
        this.dDay.getMinutes() + 30 //+environment.cacheTimeInMinutes // you can put this time in environment file to make it configurable.
      );
      this.getTimeDifference();
      this.isTimerStarted = true;
    }
  }

  resetTimer() {
    this.isTimerStarted = false;
    this.getTimeDifference();
  }

  getRemainingTime(): number {
    this.getTimeDifference();
    return this.timeDifference;
  }
}

Updated CacheInterceptor code which uses time service to track down the timing and invalidate the cache after a particular time.

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { HttpCacheService } from '../services/http-cache.service';
import { TimerService } from '../services/timer.service';


@Injectable()
export class CacheInterceptor implements HttpInterceptor {
  constructor(
  private cacheService: HttpCacheService,
  private timerService: TimerService
  ) {}

  intercept(
    req: HttpRequest,
    next: HttpHandler
  ): Observable> {
    
    this.timerService.startTimer();
    let remainingTimeInMilliseconds = this.timerService.getRemainingTime();
    
    if (remainingTimeInMilliseconds <= 0) {
      
      this.timerService.resetTimer();
      console.log(
        `Invalidating cache due to cache time limit: ${req.method} ${req.url}`
      );
      this.cacheService.invalidateCache();
    } 


    //check if the outgoing calls are GET and MRDH APIs
    if (req.method === 'GET' ) { 
      // attempt to retrieve a cached response
      const cachedResponse:
        | HttpResponse
        | undefined = this.cacheService.get(req.url);

      // return cached response
      if (cachedResponse) {
        console.log(`Returning a cached response: ${cachedResponse.url}`);
        console.log(cachedResponse);
        return of(cachedResponse);
      }

      // send request to server and add response to cache
      return next.handle(req).pipe(
        tap((event) => {
          if (event instanceof HttpResponse) {
            console.log(`Adding item to cache: ${req.url}`);
            this.cacheService.put(req.url, event);
          }
        })
      );
    }
    else {
        // pass along non-cacheable requests 
        return next.handle(req);
    }
  }
}

CacheInterceptor will monitor all the outgoing calls and start the triggers timer. After 30 minutes of time, the cache service will be ready to invalidate the cache. Interceptor invalidates the cache after 30 minutes of time. This is what will happen when the app initiates the first call.

Are you a beginner? Interested in learning Angular? check out this link

Summary

In this post, I showed you how to implement time-based caching in Angular using HTTP Interceptor. I hope you enjoyed this post and it is useful for you.

The post How to implement time-based caching in Angular using HTTP Interceptor appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/angular/how-to-implement-time-based-caching-in-angular-using-http-interceptor/feed/ 1 1013
Entity Framework Core commands explained with examples https://karthiktechblog.com/aspnetcore/efcore/entity-framework-core-commands-explained-with-examples/?utm_source=rss&utm_medium=rss&utm_campaign=entity-framework-core-commands-explained-with-examples https://karthiktechblog.com/aspnetcore/efcore/entity-framework-core-commands-explained-with-examples/#respond Wed, 22 Dec 2021 16:08:04 +0000 https://karthiktechblog.com/?p=999 Introduction Entity Framework Core commands are useful and make our life a bit easy to execute a few tasks. EF Core is popular Entity Framework data access technology. Entity Framework (EF) Core is a lightweight, extensible and open source. EF Core can serve as an object-relational mapper (O/RM) and it supports many database engines. I […]

The post Entity Framework Core commands explained with examples appeared first on KarthikTechBlog.

]]>
Introduction

Entity Framework Core commands are useful and make our life a bit easy to execute a few tasks. EF Core is popular Entity Framework data access technology. Entity Framework (EF) Core is a lightweight, extensible and open source. EF Core can serve as an object-relational mapper (O/RM) and it supports many database engines.

Entity Framework Core commands explained with examples

I will cover all the options from the three commands.

Commands:

  • database Commands to manage the database.
  • dbcontext Commands to manage DbContext types.
  • migrations Commands to manage migrations.

Short video tutorial

Installation

.NET Core CLI

Use the following .NET Core CLI command from the operating system’s command line to install or update the EF Core SQL Server provider

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Visual Studio NuGet Package Manager Console

Install-Package Microsoft.EntityFrameworkCore.SqlServer


Get the .NET Core CLI tools

dotnet ef must be installed as a global or local tool.

Also, Install the latest Microsoft.EntityFrameworkCore.Design package

dotnet tool install --global dotnet-ef

dotnet add package Microsoft.EntityFrameworkCore.Design

Refer to how to install Entity Framework Core for more information.

Demo App Explained

For the purpose of the demo, I have a sample restaurant app created using DOTNET CORE. Using the app, we will learn how to use all the dotnet ef commands.

Project structure:

The sample app project has five projects in it. Each serves its purpose and it satisfies the separation of concerns. In the real world, the project has more than one layer hence I choose to demo in a similar structure.

Entity Framework Core commands project structure

Entity Classes

 FoodMenus { get; set; }
    }

    public class FoodImages
    {
        public int Id { get; set; }
        public byte[] Image { get; set; }
        public string Mime { get; set; }
        public string ImageName { get; set; }
        public bool IsActive { get; set; }
        public int? FoodMenusId { get; set; }
        public virtual FoodMenus FoodMenus { get; set; }
    }

    public class FoodMenus
    {
        public int Id { get; set; }
        [Required]
        [MinLength(5), MaxLength(100)]
        public string Name { get; set; }
        [Required]
        [MinLength(100), MaxLength(5000)]
        public string Description { get; set; }
        public decimal Price { get; set; }        
        public bool IsActive { get; set; }
        public short? CategoryId { get; set; }
        public virtual Category Category { get; set; }
        public int? CuisineId { get; set; }
        public virtual Cuisine Cuisine { get; set; }
        public virtual List FoodImages { get; set; }
    }

Now, Let’s get started in exploring each command from dotnet ef command.

Using .NET CORE CLI : Command Prompt

  1. I have opened the database layer project’s location in the command prompt. E.g. “KarthikTechBlog.Restaurant.Data”.

2. To check entity framework core is installed and ready to use, type “dotnet ef” in the command prompt and you will see similar or same details as shown in the image.

dotnet entity framework core

EF Core Commands in Action

migrations : add

dotnet ef migrations add InitialCreate -s ../KarthikTechBlog.Restaurant.API/KarthikTechBlog.Restaurant.API.csproj

To create migrations from the application, we use the command migration add followed by name of the migration. -s “location of the startup project” is to specify the startup project. This is required for the project to build and generate the migration.

dotnet ef migrations add

To generate SQL script for the Entity models, use the below command. Remember the script can be generated only when migrations are created.

migrations : script

dotnet ef migrations script  -s ../KarthikTechBlog.Restaurant.API/KarthikTechBlog.Restaurant.API.csproj
dotnet ef migrations script

migrations: list

This lists all the migrations present in the project.

dotnet ef migrations list  -s ../KarthikTechBlog.Restaurant.API/KarthikTechBlog.Restaurant.API.csproj

migrations: remove

Rollbacks the latest migration.

dotnet ef migrations remove-s ../KarthikTechBlog.Restaurant.API/KarthikTechBlog.Restaurant.API.csproj

database: bundle

Creates an executable to update the database.

dotnet ef migrations bundle -s ../KarthikTechBlog.Restaurant.API/KarthikTechBlog.Restaurant.API.csproj

database : update

This command updates the database with the details present in the migration. If the database is not present, it will create one for us.

dotnet ef database update -s ../KarthikTechBlog.Restaurant.API/KarthikTechBlog.Restaurant.API.csproj

database: drop

Deletes the database. some of the options are

  1. --force or -f which is used to just delete without confirmation.
  2. --dry-run option show which database would be dropped, but don’t drop it.
dotnet ef database drop

dbcontext: scaffold

Generates code for a DbContext and entity types for a database. In order for this command to generate an entity type, the database table must have a primary key.

To scaffold all schemas and tables and puts the new files in the Models folder.

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Shopping;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models


For more options, visit MSDN

dbcontext: optimize

Generates a compiled version of the model used by the DbContext. Added in EF Core 6.

dotnet ef dbcontext optimize

dbcontext: script

Generates a SQL script from the DbContext. Bypasses any migrations.

dotnet ef dbcontext script

Summary

This post covers Entity Framework Core commands and their usage with examples. I hope you enjoyed and learned something new today.

The post Entity Framework Core commands explained with examples appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/aspnetcore/efcore/entity-framework-core-commands-explained-with-examples/feed/ 0 999
Angular Getting Started | Software Installation and App Setup | Part 2 https://karthiktechblog.com/angular/angular-getting-started-software-installation-and-app-setup-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=angular-getting-started-software-installation-and-app-setup-part-2 https://karthiktechblog.com/angular/angular-getting-started-software-installation-and-app-setup-part-2/#respond Sat, 18 Dec 2021 18:29:14 +0000 https://karthiktechblog.com/?p=994 Overview In this post, I will cover software installation steps and app setup from scratch. Software Installations In this course, I introduce TypeScript, which is the programming language we’ll use. TypeScript is the language we use when working with Angular. Let me take a moment to tell you what is TypeScript. “TypeScript is JavaScript with […]

The post Angular Getting Started | Software Installation and App Setup | Part 2 appeared first on KarthikTechBlog.

]]>
Overview

In this post, I will cover software installation steps and app setup from scratch.

Angular Getting Started | Software Installation and App Setup

Software Installations

In this course, I introduce TypeScript, which is the programming language we’ll use.

TypeScript is the language we use when working with Angular. Let me take a moment to tell you what is TypeScript.

TypeScript is JavaScript with syntax for types.” TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.

check out more here

What is TypeScript?

1. TypeScript adds additional syntax to JavaScript to support a tighter integration with your editor. Catch errors early in your editor.

2. TypeScript code converts to JavaScript, which runs anywhere JavaScript runs: In a browser, on Node.js or Deno and in your apps.

3. TypeScript understands JavaScript and uses type inference to give you great tooling without additional code.

typescriptlang.org

JavaScript:

JavaScript is the language for the web and is executed by all browsers. The JavaScript language specification standard is officially called ECMAScript, or ES.


Most modern browsers support ES5. ES 2015 is renamed from ES6 specification. It introduced many key new features, such as classes and arrow functions.

Any newer JavaScript features that we use but a browser doesn’t support must first be transpiles. Newer JavaScript features in our code must be compiled by a tool that converts the newer JavaScript syntax to comparable older syntax before the browser executes it.

Microsoft developed TypeScript which is open-source. It is a superset of JavaScript, meaning all JavaScript is valid TypeScript. TypeScript code transpiles to plain JavaScript.

Installing IDE Editor:

There are many editors that support TypeScript, either out of the box or with a plugin. We’ll select one of the most common editors used by Angular developers, Visual Studio Code, often just called VS Code.

Download Visual Studio Code

Installing NPM:

We need to install npm (Node Package Manager) before we begin. Npm has become the package manager for JavaScript applications. With npm, we can install libraries, packages, and applications, along with their dependencies. We’ll need npm to install all the libraries for Angular.

Download and install Node.JS here

Install the Angular CLI

To install the Angular CLI, open a terminal window and run the following command:

npm install -g @angular/cli

Create a workspace and initial application

Run the CLI command ng new and provide the name my-app, as shown here

ng new my-app

Run the application

The Angular CLI includes a server, for you to build and serve your app locally.

  1. Navigate to the workspace folder, such as my-app.
  2. Run the following command
cd my-app
ng serve --open

The ng serve command launches the server watches your files and rebuilds the app as you make changes to those files.

The –open (or just -o) option automatically opens your browser to http://localhost:4200/. In case you need to run on a different port, use –port <port number> E.g. –port 4300

If your installation and setup were successful, you should see a page similar to the following.

Angular Getting Started | default app setup

Short video tutorial

Summary

Hope you enjoyed learning this part of the course. This post explained the software required to be installed in our system to get started with angular application development.

The post Angular Getting Started | Software Installation and App Setup | Part 2 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/angular/angular-getting-started-software-installation-and-app-setup-part-2/feed/ 0 994
Angular Getting Started | Course overview and Introduction | Part 1 https://karthiktechblog.com/angular/angular-getting-started-course-overview-and-introduction-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=angular-getting-started-course-overview-and-introduction-part-1 https://karthiktechblog.com/angular/angular-getting-started-course-overview-and-introduction-part-1/#respond Sat, 18 Dec 2021 14:48:29 +0000 https://karthiktechblog.com/?p=989 Overview Angular Getting Started is a beginner-level course that takes you on a journey through the basic features of Angular. The course will guide you through the right path and make you feel more pleasant and productive. In this course, we build a sample application E.g. Restaurant. so you can code along or use it […]

The post Angular Getting Started | Course overview and Introduction | Part 1 appeared first on KarthikTechBlog.

]]>
Overview

Angular Getting Started is a beginner-level course that takes you on a journey through the basic features of Angular. The course will guide you through the right path and make you feel more pleasant and productive.

Angular Getting Started | Course overview and Introduction


In this course, we build a sample application E.g. Restaurant. so you can code along or use it as a reference for your own development. Also, you will see how Angular provides a consistent set of patterns for building components, templates, modules, and services which will help come up to speed quickly.

This course covers the following

  1. Setup local development environment starting from stratch.
  2. How to build components
  3. How to create the user interface for your application in a template, and power it up with data binding and directives.
  4. Build services for logic needed across components and inject those services where they are needed.
  5. Learn how to send requests to a web server using HTTP and observables.
  6. Set up routing to navigate between the views of your application
  7. Last but not least, during the course you will learn Angular command line interface, or CLI, to generate, execute, test, and at the end how to deploy your Angular application.

At the end of the course, you will know the basics you need to get started building your own Angular applications.

Introduction

Angular is a framework for building both small and large web applications. With Angular, you can build a simple, small website in a few hours or build rich full-featured enterprise-level product management and inventory application.


Angular is a JavaScript framework for building client-side applications. These are applications that run entirely in the user’s browser. We use techniques we already know including HTML and CSS to build the user interface, and we write our code in TypeScript, which is an enhanced version of JavaScript.

Why Angular and not some other JavaScript framework?

There are a lot of other JavaScript frameworks out there however, Angular makes our HTML more expressive.


We can embed features, such as if conditions, for loops, and local variables, directly into our HTML. Angular has powerful data binding that lets us connect data directly to our UI. Angular promotes modularity.

We build our applications as a set of building blocks, making it easier to create and reuse content. And Angular has built‑in support for communication with a back‑end server.


This makes it easy for our web applications to get and post data or execute server‑side business logic.

Angular Getting Started

This is a beginner-level course/tutorial. However, this course assumes you have some basic knowledge of JavaScript for code, HTML for building a user interface, and Cascading Style Sheets, or CSS for styling.


You do not need any prior knowledge of Angular or TypeScript. We’ll cover what you need in this course. If you have a working knowledge of each of these will help you learn this course faster.

Whats Next?

In the next chapter/post, I will cover all the steps that are required to set up a local environment and run the initial application.

Short video tutorial

Summary

This Angular Getting Started post covered the overview of the course. Also, we looked at what is Angular, the JavaScript framework, and why Angular framework is. I hope you enjoyed it and are excited to learn the next module.

The post Angular Getting Started | Course overview and Introduction | Part 1 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/angular/angular-getting-started-course-overview-and-introduction-part-1/feed/ 0 989
JavaScript Getting Started | Variables var, let, and const | Part 2 https://karthiktechblog.com/javascript/javascript-getting-started-variables-var-let-and-const-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=javascript-getting-started-variables-var-let-and-const-part-2 https://karthiktechblog.com/javascript/javascript-getting-started-variables-var-let-and-const-part-2/#respond Fri, 10 Dec 2021 19:55:20 +0000 https://karthiktechblog.com/?p=973 Introduction In this JavaScript Getting Started, you will learn about JavaScript Variables var, let, and const along with their usage. Join me in learning variables and start using them in your work. What is a variable ? Any application that we write is going to be based on data. If we’re selling fruits, we need […]

The post JavaScript Getting Started | Variables var, let, and const | Part 2 appeared first on KarthikTechBlog.

]]>
Introduction

In this JavaScript Getting Started, you will learn about JavaScript Variables var, let, and const along with their usage. Join me in learning variables and start using them in your work.

JavaScript Getting Started | Variables var, let, and const | Part 2

What is a variable ?

Any application that we write is going to be based on data. If we’re selling fruits, we need data on the fruit name, the price, and all the data that belongs to an invoice or a purchase order. Likewise, if you consider your work is around car company then you need all car-related information such as engine, model, price, etc. I can talk about many such examples. All deals with data.

In JavaScript and most other programming languages, we use variables to hold this information. Data is stored in the computer memory. Let’s take an example. If you had to sell a car which is of price $20,000.                

That needs to be stored somewhere in the computer’s memory and typically, a memory address is a long,               complicated number. It would be very difficult if we had to use this long number to reference that value.

So instead we use a variable. In this case, we can use a variable called carPrice. So in this case we were using an English word to represent the number in the computer, and you can use words and characters from your own native language and name it in an understanding way.

There’s a special terminology we use in programming when you create a variable. It’s called declaring the variable.

Declaring Variables

 We declare variables to let Javascript know that we are going to work with variables. When we declare a variable, we use a keyword, let. A keyword is a special symbol that JavaScript knows about.

It performs some type of action. In this case, let allows us to declare a variable, and after the keyword let,  we have the variable name that we want to use and there are certain rules for creating variable names. we will talk about the variable naming shortly.

Keywords let and var

We have been using the var keyword in JavaScript. However, the var keyword has some limitations when it comes to scope. There are only two scopes for var which are the global scope and function scope. There is no block scope. This often becomes a bug for many developers.

what is scope then? The scope of the variable is the area of the program where it is legal to use. var has only two scopes as Global Scope and Function Scope. There is no block scope for var keyword.

javascript variable function scope
// var Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        var weather = '65F';
    }
    return weather;
};

let keyword solve this problem.

let is a new Keyword in JavaScript and allows us to define variables.

// var Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        var weather = '65F';
    }
    return weather;
};

// let Keyword scope example
var doSomeWork = function (raining) {
    if (raining) {
        let weather = '65F';
        return weather;
    }

    return '85F';
};

since variable “x” is available throughout the function there is no error. let the keyword makes the variable scoped to the condition and hence we got an error. Using such code through javascript runtime error stating no such variable exist.

All this confusion with the var keyword is because of the Hoisting. Hoisting is JavaScript’s default behavior of moving declarations to the top. You can read more here.

Another example is to use the let keyword in for loops.

JavaScript Getting Started | Variables let

Variable naming

  1. The name must contain only letters, digits, or the symbols $ and _
  2. The first character must not be a digit.

Try to provide a meaningful name and limit the length of the variable to a max of 15 characters.

example for variable naming

let $ = 20;
let _ = "John"
let _name$ = "name"

const Keyword

The const keyword is another addition in ECMA Script 6 (ES6). The idea of using this is to create and initialize a read-only variable. A variable that holds a constant value is something that you never change.

ES6 for const will have block scoping.

var constFuntion = function () {
    const max_size = 20;
    max_size = 20 + 20; // syntax error as you cannot assign value again;
}

Another difference with const and var keywords is you can define a variable more than once with the var keyword. However, you cannot do the same with the const keyword.

JavaScript Getting Started | Variables var, let, and const

JavaScript Getting Started: Table of contents

  1. Introduction and Setting up a local environment
  2. Variables and constants
  3. Types and Operators
  4. Program flow : conditions, comparision and different loops.
  5. Parameters : Default, Rest …Spread and templates
  6. Functions
  7. Objects and the DOM
  8. Arrarys
  9. Scope and Hoistings
  10. Classes (Advance)

Summary

This post JavaScript Getting Started covers Variables var, let, and const, how we declare variables, and the usage of var, let, and const keywords.

The post JavaScript Getting Started | Variables var, let, and const | Part 2 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/javascript/javascript-getting-started-variables-var-let-and-const-part-2/feed/ 0 973
JavaScript Getting Started | Introduction | Part 1 https://karthiktechblog.com/javascript/javascript-getting-started-introduction-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=javascript-getting-started-introduction-part-1 https://karthiktechblog.com/javascript/javascript-getting-started-introduction-part-1/#comments Fri, 10 Dec 2021 15:03:04 +0000 https://karthiktechblog.com/?p=966 Introduction JavaScript is one of the most popular programming languages. JS is the top programming language, and it’s more than twice as popular as Python. JavaScript the ubiquitous language for the web, it’s reached beyond the web.  It now runs inside of database engines, web servers, game consoles, and refrigerators. Backward compatibility is important when […]

The post JavaScript Getting Started | Introduction | Part 1 appeared first on KarthikTechBlog.

]]>
Introduction

JavaScript is one of the most popular programming languages. JS is the top programming language, and it’s more than twice as popular as Python.

JavaScript: Getting Started | Introduction | Part 1

JavaScript the ubiquitous language for the web, it’s reached beyond the web.  It now runs inside of database engines, web servers, game consoles, and refrigerators. Backward compatibility is important when there is so much code depending on a language. However, ES6 has come to take it forward to the next level.

In this Javascript: Getting Started tutorial, you’ll know the very basics of JavaScript and you’ll be able to build simple programs for the web. No prior knowledge of programming is required for this course.

This Javascript: Getting started is for those who are completely new to programming. Also valuable for programmers who are just new to the JavaScript language.

Installing Development Software for Demo/Practice

In order to start working with Javascript, there’s certain software that needs to be installed on our machines.

We need to have GIT, Node.js and an IDE, in our case it is Visual Studio Code.

Steps to check and install softwares

Step 1: To check GIT is installed, just type "git --version" in the command prompt if you are using a windows machine. On a Mac, you would go to a terminal window.

If you did not find GIT installed on your machine (when you see Error), install the download from https://git-scm.com/ both for windows and mac downloads are present (scroll down and check to your right side).

Step 2: Next is we need to install node package manager or npm package manager which comes with a . bundle in Node.js. To check node is installed, execute the command "npm --version“. visit https://nodejs.org/en/ and install the LTS version when you see the error. At the time of this post, 16.13.1 is the LTS version.

Step 3: I will be using Visual Studio Code as an editor for all the demo. You can download that at code.visualstudio.com

Setting up project from GitHub

I have set up a sample “Hello World” project and that will be good to start with. It has everything that you need to start developing.

js-starter is the repository name in GitHub. Go to https://github.com/karthiktechblog/js-starter and click on clone or download. you may also clone the project in Visual Studio Code by using this URL https://github.com/karthiktechblog/js-starter.git

Inside the sample project, there is a file named package.json which contains the required dependency software to run the project. Go to the terminal window by clicking Terminal => New Terminal from the top menu or using the shortcut “ctrl + shift +”.

Now, run “npm install” command which will install the lite server, version 2.5.4. Run "npm run start" in your terminal to start the server.

Now, we get Hello World, and you can see that the lite server is running on localhost port 3000.

JavaScript: Getting Started | Introduction sample app demo

JavaScript Getting Started: Table of contents

  1. Introduction and Setting up a local environment
  2. Variables and constants
  3. Types and Operators
  4. Program flow : conditions, comparision and different loops.
  5. Parameters : Default, Rest …Spread and templates
  6. Functions
  7. Objects and the DOM
  8. Arrarys
  9. Scope and Hoistings
  10. Classes (Advance)

Summary

In this post, you learned JavaScript and how to kick start your learning journey along with me. Thanks for reading and in the next post, you will learn about variables and how to declare and use them.

The post JavaScript Getting Started | Introduction | Part 1 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/javascript/javascript-getting-started-introduction-part-1/feed/ 1 966
Provision virtual machines using ARM Templates | Implement IaaS solutions | Part 4 https://karthiktechblog.com/azure/provision-virtual-machines-using-arm-templates-implement-iaas-solutions-part-4/?utm_source=rss&utm_medium=rss&utm_campaign=provision-virtual-machines-using-arm-templates-implement-iaas-solutions-part-4 https://karthiktechblog.com/azure/provision-virtual-machines-using-arm-templates-implement-iaas-solutions-part-4/#respond Sat, 27 Nov 2021 14:52:43 +0000 https://karthiktechblog.com/?p=923 This post covers how to provision virtual machines using ARM Templates that is part 4 of Implement Iaas Solutions. We have been learning how to provision virtual machines using various methods like Azure Portal, CLI, Powershell. Let’s learn about ARM Templates. An ARM template is a JSON‑formatted file that is a configuration document that defines […]

The post Provision virtual machines using ARM Templates | Implement IaaS solutions | Part 4 appeared first on KarthikTechBlog.

]]>
This post covers how to provision virtual machines using ARM Templates that is part 4 of Implement Iaas Solutions. We have been learning how to provision virtual machines using various methods like Azure Portal, CLI, Powershell. Let’s learn about ARM Templates.

An ARM template is a JSON‑formatted file that is a configuration document that defines what resources you want to be deployed in Azure with their configurations. You can create any resource with an ARM template.

Provision virtual machines using ARM Templates | Implement IaaS solutions | Part 4

Understanding ARM Templates

I will be focusing on Virtual Machine in this ARM Template topic. ARM templates are a building block for deployment automation. Using ARM templates, you can parameterize the configuration elements for resources defined in an ARM template.

You can use parameters for commonly changed configuration elements such as virtual machine names and many more. Other elements are image names, network security, storage account name, and many more.

After that, you can then use that same ARM template repeatedly to deploy the environment defined in the template. However, use different parameters to customize each environment at deployment time.

For example, you can have each set of parameters for Dev, QA, Stage, and one for Production that will provide consistency to your deployments. 

How ARM Template works?

 You create an ARM template and then an ARM template is submitted to Azure Resource Manager for deployment. The tools used are Azure CLI, Powershell, Azure Portal.

Once the ARM Template is deployed, it reads the details inside the ARM Template like creating resources, depleting resources modifying existing properties or creating new properties.

Creating ARM Templates

  1. You can build and export an ARM template from the Azure portal.
  2. Write your own manually.
  3. Also, you can start from the Quickstart library, which is a collection of community templates available in the Azure portal in the Custom deployment blade.

In order to focus on the higher-level process of how ARM templates work, we will mainly cover the building and exporting of an ARM template in the Azure portal.

How it works?

After you deploy an ARM template, Resource Manager receives that template, formatted as JSON, and then converts the template into REST API operations. This means you can use ARM Templates using many tools that include Azure Portal, CLI, Powershell.

ARM Template Structure

Let’s go through the structure of the ARM Template.

{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
	"apiProfile":"",
    "parameters": { },
    "variables": {},
	"functions": [],
    "resources": [],
    "outputs": {}
}

First, we have some header information. Schema is the location of the JSON schema file that describes the template’s language.

Content version is the version of the template, which is defined by you so that you can version control your templates.

apiProfile, which allows for versioning of the resource types that are defined in the template.

Parameters, which are used to provide values during deployment so that the same template can be reused for multiple deployments. This is where you’ll define deployment‑specific configuration parameters, and this is very useful when you want to be able to use that same template over and over again, but change out the parameters for specific deployments. Common parameters are resource groups, regions, resource names, and network configurations.

Variables define values that are reused in your templates and are often constructed from parameter values.

Functions allow you to create customized functions that simplify your templates and help enable reuse of templates. A common use for functions is generating a resource name based on the environment that it’s being deployed into.
To create your own functions, see User-defined functions.

The commonly used function is concat which combines multiple string values and returns the concatenated string, or combines multiple arrays and returns the concatenated array.

Example

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "prefix": {
      "type": "string",
      "defaultValue": "prefix"
    }
  },
  "resources": [],
  "outputs": {
    "concatOutput": {
      "type": "string",
      "value": "[concat(parameters('prefix'), '-', uniqueString(resourceGroup().id))]"
    }
  }
}

for more information read it from string functions

DEMO

It is time for the demo, to get started we will log in to Azure Portal and create an ARM Template. Follow the instructions in detail of how to Provision virtual machines using the Azure portal | Implement IaaS solutions | Part 1

Once you are on the final page as shown in the image below.

Provision virtual machines using ARM Templates

Instead of clicking on create which we normally do, we will click on “Download a template for automation” to view the template. This creates the template and parameters JSON files needed for an ARM template‑based deployment for the virtual machine that we just configured.

From this screen at the top, we can click Download to download the template and parameters files, we can click Add to add them to a library for further deployments inside of Azure, or we can deploy them right from here.

Examining an ARM Template

Examining an ARM Template

In this template, we can see that we have three sections defined, Parameters, Variables, and Resources. It is important to note that not all the sections are mandated to fill, many are optional. If we don’t provide them, the default values will be taken.

In this template, we have 19 different parameters defined, 3 variables, and 5 resources.

Parameter section | ARM Template

The template starts with parameters, you can see that these are the parameters used to provide values for unique deployments allowing us to change them at runtime. In this section of a template, it’s just the declaration of the parameters. The actual parameters of values for this particular deployment are going to be in the parameters file.

Some of the exposed parameters in this template are location, networkInterfaceName, enableAcceleratedNetworking, networkSecurityGroupName, virtualNetworkName, networkSecurityGroupRules, and so on.

A collection of parameters are exposed in this template. The values are going to come from the parameters.json file. clicking on the parameter tab will present you with the following parameter values.

arm template parameter values

All the sections that we filled in the Azure portal to create a virtual machine are included in the parameter values.

Decoupling these values from the template allows us to use that template file over and over again, setting unique values for each deployment in this parameters file.

Variables section | ARM Template

Variables are used to define values for reuse in a template. And there are three variables in this template, we will look into those.

The first variable is nsgId. A system function being used, resourceId. This will return the resource ID of a defined resource. The value that is returned from that function is stored in the variable nsgId.

nsgId is reused within the ARM template so frequently.

Provision virtual machines using ARM Templates

We then see the virtual network name as the second variable that was passed in via a parameter. And then for the final variable, we see subnetRef. It’s going to use another system function, concat, to concatenate together the values of the vnetId variable, the string subnets, and a template parameter named subnetName. That’s going to combine those strings all together to set the value for subnetRef.

Resources section | ARM Template

The last part is resources. There are 5 resources defined in this template. These are the actual resources being deployed in Azure by this ARM template.

In the resources section, we have an important section called the dependsOn section, which is a list of resources that this resource depends on before it gets deployed. And so this is a way for us to define some ordering and how resources in this template are created. This network interface won’t be created until these three other resources defined are deployed.

Similarly, all the other sections are defined in this way and the ARM template will deploy the dependent resources first before any other resources are deployed.

Deploying ARM Template

Provision virtual machines using ARM Templates | Implement IaaS solutions | Part 4

This downloads a zip file containing parameter.json and template.json files. If I wanted to deploy this template as is, I can click Deploy and that will take me to the custom deployment page to start a deployment. Clicking Deploy, you can see that it has prepopulated the parameters that we entered when we created the ARM template.

Deploy a custom template

Let me show you how to build this template from scratch. In the search box, search with “Deploy a custom template” and choosing this will present a screen to get started with our own template.

Provision virtual machines using ARM Templates | Implement IaaS solutions | Part 4

You need to provide an Admin password that was not in the downloaded template. You can edit the parameter file and update the admin password there or provide it in the Azure portal.

Now, it’s a regular step to click on create a virtual machine.

Deploying ARM Template using Powershell

#Let's login, may launch a browser to authenticate the session.
Connect-AzAccount -SubscriptionName 'Demo Account'


#Ensure you're pointed at your correct subscription
Set-AzContext -SubscriptionName 'Demo Account'


#If you resources already exist, you can use this to remove the resource group
Remove-AzResourceGroup -Name 'lscdemo-rg'


#Recreate the Resource Group
New-AzResourceGroup -Name 'lscdemo-rg' -Location 'EastUS'


#We can deploy ARM Templates using the Portal, Azure CLI or PowerShell
#Make sure to set the adminPassword parameter in parameters.json around line 80 "adminPassword" prior to deployment.
#Once finished, look for ProvisioningState Succeeded.
New-AzResourceGroupDeployment `
    -Name mydeployment -ResourceGroupName 'lscdemo-rg' `
    -TemplateFile './template/template.json' `
    -TemplateParameterFile './template/parameters.json' 

Using this template we can now deploy the virtual machine in Azure.

Clean up resource

Now the Demo is complete for creating a virtual machine. It is time to clean up the resources we used.

When no longer needed, you can delete the resource group, virtual machine, and all related resources.

Go to the resource group for the virtual machine, then select Delete resource group. Confirm the name of the resource group to finish deleting the resources.

Related resources

Conclusion

In this post, I have covered the topic of the Provision of virtual machines using ARM Templates. This is part of implementing IaaS solutions, part 4. Happy learning!.

The post Provision virtual machines using ARM Templates | Implement IaaS solutions | Part 4 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/azure/provision-virtual-machines-using-arm-templates-implement-iaas-solutions-part-4/feed/ 0 923
Provision virtual machines using PowerShell | Implement IaaS solutions | Part 3 https://karthiktechblog.com/azure/provision-virtual-machines-using-powershell-implement-iaas-solutions-part-3/?utm_source=rss&utm_medium=rss&utm_campaign=provision-virtual-machines-using-powershell-implement-iaas-solutions-part-3 https://karthiktechblog.com/azure/provision-virtual-machines-using-powershell-implement-iaas-solutions-part-3/#comments Wed, 03 Nov 2021 21:40:35 +0000 https://karthiktechblog.com/?p=881 Introduction This post covers how to provision virtual machines using PowerShell. This is part of implementing the IaaS solutions topic (AZ-204 Certification). This is a continuation of the previous post Provision virtual machines using Azure CLI. PowerShell scripts can be executed in various ways. You can use PowerShell from Azure Portal (Cloud Shell), PowerShell software, […]

The post Provision virtual machines using PowerShell | Implement IaaS solutions | Part 3 appeared first on KarthikTechBlog.

]]>
Introduction

This post covers how to provision virtual machines using PowerShell. This is part of implementing the IaaS solutions topic (AZ-204 Certification). This is a continuation of the previous post Provision virtual machines using Azure CLI.

Provision virtual machines using PowerShell | Implement IaaS solutions | Part 3

PowerShell scripts can be executed in various ways. You can use PowerShell from Azure Portal (Cloud Shell), PowerShell software, or using Visual Studio Code. I showed you how to use the PowerShell window in my previous demo. To install PowerShell in Visual Studio Code follow the instructions below.

The advantage of using Visual Studio Code IDE is that the syntax is nicely highlighted for the PowerShell commands. This helps in finding the issue upfront.

How to use PowerShell in Visual Studio Code IDE

Install Visual Studio Code IDE that is an open-source and free software from Microsoft.

Install PowerShell plugin from the extension. Refer to the below image.

PowerShell using Visual Studio Code editor

Install PowerShell on Windows, Linux, and macOS

Choose the right installation from this link. As of this writing, PowerShell 7 is the latest. To install the Azure Az module, use this link Install the Azure Az PowerShell module.

How to run PowerShell using Azure Cloud Shell – Azure Portal

Provision virtual machines using PowerShell | Implement IaaS solutions | Part 3

Log in to the Azure portal and on the top right side, click on “Cloud Shell”, which opens a prompt to choose either Bash or PowerShell.

Choose Bash to run Azure CLI commands. In our current demo, we will choose PowerShell. After choosing the PowerShell/Bash, it will prompt to install a Storage which will cost a small amount. This is really a small amount.

Provision virtual machines using PowerShell

Creating a virtual machine in Azure with Azure PowerShell using the Az module. Logically the process is the same as creating a virtual machine with Azure CLI.

The first step to creating a virtual machine in PowerShell is to create a PSCredential object which will hold the username and password.

This is used for the credential for the local administrator account on the virtual machine that is deployed.

To create that PSCredential, you define a username and password. Password should match the password requirement from Azure. E.g. combination of Capital letter, lower case letter, number, special characters and it should be 8 and 123 characters long.

Now, you need to convert the string password defined here into a secure string, and you can do that with the cmdlet ConvertTo‑SecureString

Once you have the username and password variables defined, you can create a new PSCredential object with New‑Object, specifying the PSCredential object type, and then passing in the username and password variables as parameters into New‑Object.

Complete PowerShell Commands to provision virtual machines

#This command is required only when you use PowerShell other than Azure Portal as Portal is signed i already we dont need this to run.
Connect-AzAccount -SubscriptionName 'Demo Account'
#Ensure you're pointed at your correct subscription (if you have more than one subscription)
Set-AzContext -SubscriptionName 'Demo Account'


#Create a Resource Group
New-AzResourceGroup -Name "LSCDemo-rg" -Location "EastUS"


#Create a credential to use in the VM creation
$username = 'demoadmin'
$password = ConvertTo-SecureString 'Strongpassword$%^&*' -AsPlainText -Force
$WindowsCred = New-Object System.Management.Automation.PSCredential ($username, $password)


#Create a Windows Virtual Machine, can be used for both Windows and Linux.
#Note, you can create Windows or Linux VMs with PowerShell by specifying the correct Image parameter.
New-AzVM `
    -ResourceGroupName 'LSCDemo-rg' `
    -Name 'LSCDemo-win-az' `
    -Image 'Win2019Datacenter' `
    -Credential $WindowsCred `
    -OpenPorts 3389


#Get the Public IP Address (select-object  is used to pick require property alone from entire JSON response)
Get-AzPublicIpAddress `
    -ResourceGroupName 'LSCDemo-rg' `
    -Name 'LSCDemo-win-az' | Select-Object IpAddress

In this demo, the screenshot shows how Azure rejects if the password does not match the requirements.

Provision virtual machines using PowerShell
Provision virtual machines using PowerShell

Now the VM is created and we have a public IP to remote login using RDP. You can check this post on how to log in to VM and install Web Server for application deployment.

Video tutorial

Clean up resource

Now the Demo is complete for creating a virtual machine. It is time to clean up the resources we used.

When no longer needed, you can delete the resource group, virtual machine, and all related resources.

Go to the resource group for the virtual machine, then select Delete resource group. Confirm the name of the resource group to finish deleting the resources.

Related resources

Conclusion

In this post, I have covered the topic of the Provision of virtual machines using Azure PowerShell that is part of implementing IaaS solutions. This post also covers various other PowerShell tools to use. For more, refer to AZ-204 Certification. Happy learning!.

The post Provision virtual machines using PowerShell | Implement IaaS solutions | Part 3 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/azure/provision-virtual-machines-using-powershell-implement-iaas-solutions-part-3/feed/ 1 881
Provision virtual machines using Azure CLI | Implement IaaS solutions | Part 2 https://karthiktechblog.com/azure/provision-virtual-machines-using-azure-cli-implement-iaas-solutions-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=provision-virtual-machines-using-azure-cli-implement-iaas-solutions-part-2 https://karthiktechblog.com/azure/provision-virtual-machines-using-azure-cli-implement-iaas-solutions-part-2/#respond Tue, 02 Nov 2021 19:10:35 +0000 https://karthiktechblog.com/?p=860 Introduction This post covers how to Provision virtual machines using Azure CLI. This is part of implementing the IaaS solutions topic. This is a continuation of the previous post Provision virtual machines using the Azure portal. This module’s topics are part of implementing IaaS solutions and I will cover “Provision Virtual Machine”. Provision virtual machines […]

The post Provision virtual machines using Azure CLI | Implement IaaS solutions | Part 2 appeared first on KarthikTechBlog.

]]>
Introduction

This post covers how to Provision virtual machines using Azure CLI. This is part of implementing the IaaS solutions topic. This is a continuation of the previous post Provision virtual machines using the Azure portal.

This module’s topics are part of implementing IaaS solutions and I will cover “Provision Virtual Machine”.

provision windows and linux virtual machine

Provision virtual machines using Azure CLI

In order to work with Azure CLI, first, we should download the Azure CLI and install it. I have a windows machine so I choose to download CLI for windows.

Install Azure CLI on Windows

The Azure CLI is available to install in Windows, macOS, and Linux environments. It can also be run in a Docker container and Azure Cloud Shell. View complete details here

Now, I have installed Azure CLI. Let’s get started with its usage.

How to use CLI

After CLI installation, you can use the windows command prompt or PowerShell.

I have used PowerShell for the demo.

Open PowerShell for CLI

Click on start or windows key => type “powershell” => open Windows PowerShell

On the PowerShell window, enter the script as below and log in interactively. Login interactively meaning, a browser will open and you need to sign in to Azure Portal with your Azure portal credentials.

az login

az stands for azure and will be recognized once Azure CLI is installed in your machine.

Provision virtual machines using Azure CLI

Azure CLI commands to provision windows virtual machines

There are a lot many az vm commands. the below commands are used to create a VM with minimum required configurations. to check the full command list check az vm commands.

#Login interactively and set a subscription to be the current active subscription. My subscription name is "Demo Account", chnage to your subscription name

az login
az account set --subscription "Demo Account"


#Create a Windows VM.

#check existing group listed in table format 
az group list --output table 


#Create a resource group.
az group create --name "LSCDemo-rg" --location "eastus"


#Creating a Windows Virtual Machine (for image, choose any avilable name)
az vm create 
    --resource-group "LSCDemo-rg" 
    --name "LSCDemo-win-cli" 
    --image "win2019datacenter" 
    --admin-username "demoadmin" 
    --admin-password "jsfdhsd$$Ddd$%^&*" 


#Open RDP for remote access, it may already be open
az vm open-port 
    --resource-group "LSCDemo-rg" 
    --name "LSCDemo-win-cli" 
    --port "3389"


#Get the IP Addresses for Remote Access
az vm list-ip-addresses 
    --resource-group "LSCDemo-rg" 
    --name "LSCDemo-win-cli" 
    --output table

Provision virtual machine using Azure CLI | Implement IaaS solutions | Part 2

Verify and Log into the Windows VM via RDP

This topic is already covered in my previous post, if you haven’t read the post, check here Provision virtual machines using the Azure portal | Implement IaaS solutions | Part 1

Azure CLI commands to provision linux virtual machines

Creating Linux virtual machines is almost the same as creating a Windows VM. There are only a few changes and the authentication mechanism needs to be changed. Let’s dive in and learn.

The authentication mechanism used for Linux is SSH. First, we need to generate a public/private RSA key pair, to do so you can use “ssh-keygen” available in your machine.

Steps

  1. Type “ssh-keygen” in run command. This opens up a terminal.
  2. “Enter file in which to save the key (C:\Users\karth/.ssh/id_rsa):” for this promt, leave it. Just press enter. This action will create a folder under current user name.
  3. Enter passphare. enter a password here and then enter again when asked.
  4. That’s it, the file is created.
ssh-keygen for rsa key
ssh-keygen to generate RSA key for Linux
#Creating a Linux Virtual Machine
az vm create 
    --resource-group "LSCDemo-rg" 
    --name "LSCDemo-linux-cli" 
    --image "UbuntuLTS" 
    --admin-username "demoadmin" 
    --authentication-type "ssh" 
    --ssh-key-value ~/.ssh/id_rsa.pub 


#OpenSSH for remote access, it may already be open
az vm open-port 
    --resource-group "LSCDemo-rg" 
    --name "LSCDemo-linux-cli" 
    --port "22"



#Get the IP address for Remote Access
az vm list-ip-addresses 
    --resource-group "LSCDemo-rg" 
    --name "LSCDemo-linux-cli" 
    --output table


#Log into the Linux VM over SSH (paste the ip from above command, see image)
ssh demoadmin@PASTE_PUBLIC_IP_HERE

Provision virtual machines using Azure CLI

Connect to Linux VM

Once you attempt to connect to the VM, it will prompt for the passphrase that was used to create ssh file. Provide the same passphrase to connect to VM.

Provision virtual machine using Azure CLI | Implement IaaS solutions | Part 2

Video tutorial

Clean up resource

Now the Demo is complete for creating a virtual machine. It is time to clean up the resources we used.

When no longer needed, you can delete the resource group, virtual machine, and all related resources.

Go to the resource group for the virtual machine, then select Delete resource group. Confirm the name of the resource group to finish deleting the resources.

Related resources

Conclusion

In this post, I have covered the topic of the Provision of virtual machines using Azure CLI that is part of implementing IaaS solutions. This post covers CLI commands for creating both Windows and Linux VM. Other parts of this exam are covered in other posts. Happy learning!.

The post Provision virtual machines using Azure CLI | Implement IaaS solutions | Part 2 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/azure/provision-virtual-machines-using-azure-cli-implement-iaas-solutions-part-2/feed/ 0 860
Provision virtual machines using the Azure portal | Implement IaaS solutions | Part 1 https://karthiktechblog.com/azure/provision-virtual-machines-using-the-azure-portal-implement-iaas-solutions-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=provision-virtual-machines-using-the-azure-portal-implement-iaas-solutions-part-1 https://karthiktechblog.com/azure/provision-virtual-machines-using-the-azure-portal-implement-iaas-solutions-part-1/#respond Tue, 02 Nov 2021 13:07:23 +0000 https://karthiktechblog.com/?p=840 Introduction As part of Azure AZ-204 certification, this post will cover Provision virtual machines using the Azure portal that are part of Implement IaaS solutions. This module’s topics are part of implementing IaaS solutions and I will cover “Provision Virtual Machine”. What is infrastructure as a service (IaaS)? This is the foundational category of cloud […]

The post Provision virtual machines using the Azure portal | Implement IaaS solutions | Part 1 appeared first on KarthikTechBlog.

]]>
Introduction

As part of Azure AZ-204 certification, this post will cover Provision virtual machines using the Azure portal that are part of Implement IaaS solutions.

This module’s topics are part of implementing IaaS solutions and I will cover “Provision Virtual Machine”.

Provision virtual machines VM | Implement IaaS solutions

What is infrastructure as a service (IaaS)?

This is the foundational category of cloud computing services. With IaaS, you rent IT infrastructure—servers and virtual machines (VMs), storage, networks, and operating systems. You can use cloud providers such as Microsoft Azure on a pay-as-you-go basis.

What is Virtual Machine VM ?

A virtual machine, commonly shortened to just VM, is no different than any other physical computer like a laptop, smartphone, or server.

It has a CPU, memory, disks to store your files, and can connect to the internet if needed. While the parts that make up your computer (called hardware) are physical and tangible.

VMs are often thought of as virtual computers or software-defined computers within physical servers, existing only as code.

Virtual Machines used for the following

Building and deploying apps to the cloud

Trying out a new operating system (OS), including beta releases.

Backing up your existing OS

Spinning up a new environment to make it simpler and quicker for developers to run dev-test scenarios.

Accessing virus-infected data or running an old application by installing an older OS.

Running software or apps on operating systems that they weren’t originally intended for.

From Microsoft

Methods of Provision virtual machines VM.

Four ways you could create VM, Azure Portal, Azure CLI, Azure PowerShell, and Azure ARM Templates.

Video tutorial

Provision virtual machines VM using portal

Create Windows virtual machines in Azure

Azure VMs are an on-demand scalable cloud-computing resource. You can start and stop virtual machines anytime, and manage them from the Azure portal or with the Azure CLI.

You can also use a Remote Desktop Protocol (RDP) client to connect directly to the Windows desktop user interface (UI) and use the VM as if you were signed in to a local Windows computer.

Steps

Sign in to the Azure portal. If you do not have an account, don’t worry it is free to start with. Check out below for details.

Getting started with Azure
  • On the Azure portal, under Azure services, select Create a resource. The Create a resource pane appears.
  • In search services search box, search for “virtual” as you will see “Virtual machine”, click on it.
  • In the Basics tab, under Project details, make sure the correct subscription is selected and then choose to Create new resource group.
  • Choose an existing resource group or create a new one. I have named my new resource group as “LSCDemo-VM”.
  • Fill up the instance details as per the screenshot below. Here we have named “LSCVMDemo” as VM name and selected the region for our VM deployment.
  • pick up an image from the drop down, I picked “windows server 2016 datacenter” with standard power for this demo.
  • Chose a size of the VM as per the need.
Provision virtual machines using the Azure portal | Implement IaaS solutions  | Part 1
  • Provide Administarator account details like username and password.
  • Under Inbound port rules, choose Allow selected ports and then select RDP (3389) and HTTP (80) from the drop-down.
  • Leave the remaining defaults and then select the Review + create button at the bottom of the page.
  • After validation runs, select the Create button at the bottom of the page.
  • After deployment is complete, select Go to resource. Here you can see all the details of the newly created VM.
Provision virtual machines using the Azure portal RDP configuration

Deployment of VM completed.

Connect to virtual machine

VM dashboard

On the resource dashboard page, all the details of the virtual machine appear. select the Connect button then select RDP

Click on download RDP and open it. Depending on your machine be it MAC or Windows, the appropriate RDP file will be downloaded,

connect VM using RDP

Log into VM using username and password.

server configuration

Installation of web server in VM

Open a PowerShell prompt on the VM and run the following command:

Install-WindowsFeature -name Web-Server -IncludeManagementTools

To open PowerShell in windows, click on the start or run command, type “Powershell”. This will open the PowerShell window.

Installation of web server in VM

The webserver is now installed. To open Internet Information Service (IIS), go to Tools => Internet Information Service (IIS).

Now, we can deploy the applications to IIS.

Installation of web server in VM  open IIS

Clean up resource

Now the Demo is complete for creating a virtual machine. It is time to clean up the resources we used.

When no longer needed, you can delete the resource group, virtual machine, and all related resources.

Go to the resource group for the virtual machine, then select Delete resource group. Confirm the name of the resource group to finish deleting the resources.

Related resources

Resources

1. MSDN: Quickstart: Create a Windows virtual machine in the Azure portal

2. AZ-204 Developing Solutions for Microsoft Azure

Conclusion

In this post, I have covered the topic of the Provision of virtual machines using the Azure portal that is part of implementing IaaS solutions. Other parts of this exam are covered in other posts. Happy learning!.

The post Provision virtual machines using the Azure portal | Implement IaaS solutions | Part 1 appeared first on KarthikTechBlog.

]]>
https://karthiktechblog.com/azure/provision-virtual-machines-using-the-azure-portal-implement-iaas-solutions-part-1/feed/ 0 840