The best visual studio code shortcuts

Basically, I’m a user who uses shortcuts a lot. In this post, I’m going to share some of my favourite shortcuts.

Earlier, we have shared Visual studio shortcuts in this site. Please do check if you are interested.

Lets jump into content directly.

Comment out selection or current line

  • Ctrl + /

Usually, I use the keystroke Ctrl +K, Ctrl + C for comment out a line.

And Ctrl +K, Ctrl + U for uncomment a selection or line.

This Ctrl + / does both the job in toggle way. Reduced keystrok and achieves the same. One of the productivity hack.

Zen mode

  • Ctrl + K, Z

Enables Zen mode. More focused mode of programming.

The command is basically toggle. You can use same shortcut to exit Zen mode.

Look at the difference between normal and Zen mode in below image.

Show command palette

  • Ctrl+Shift+P or F1

Open the command palette on editor. And we can perform various quick from there.

External terminal

  • Ctrl + Shift + C

It opens external terminal configured with the current project file path.

This is the one main shortcut I use daily with VS Code.

Even I made separate post on how to configure external terminal in VS Code.

Inline breakpoints

  • Shift+F9

Inline breakpoints will only be hit when the execution reaches the column associated with the inline breakpoint. This is particularly useful when debugging minified code which contains multiple statements on a single line.

An inline breakpoint can be set using Shift+F9 or through the context menu during a debug session. Inline breakpoints are shown inline in the editor.

Inline breakpoints can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.

Navigating to previous position or forward

  • Alt+ ← / →

To go back previous postition or go to forward postion of your navigation again.

Use Keyboards left side alt key.

Open Integrated terminal

  • Ctrl+`

This symbol key will present under the Esc key. This shortcut will open up the integrated terminal available within the VS Code.

Few more shortcuts used within intergrated terminal

  • Ctrl+Shift+` Create new terminal
  • Ctrl+C Copy selection
  • Ctrl+V Paste into active terminal
  • Ctrl+↑ / ↓ Scroll up/down
  • Shift+PgUp / PgDn Scroll page up/down
  • Ctrl+Home / End Scroll to top/bottom

Breadcrumbs

Sometimes we will be working with the small screen machines. Keeping the solution explorer always open isn’t an optimal solution when we are working on the small screen laptops. One of the solutions can be keeping the files hidden and opening whenever needed.

In that case, traversing between files or folders is a bit difficult.

To resolve this problem, we have an option called breadcrumbs in the VS Code.

Breadcrumb navigation lets you jump to symbols and files in your workspace.

Breadcrumbs show the current location and allow you to quickly navigate between symbols and files. To start using breadcrumbs, enable it with the View > Toggle Breadcrumbs command or via the breadcrumbs.enabled setting.

You can modify the user settings by visiting the settings page using shortcut CTRL + , or visiting the option File>Preferences>settings

In the search bar, search for the option breadcrumbs. You can find the following UI

I usually enable the breadcrumbs for File Path, because don’t use symbol path navigation. You can use the available options based on your needs.

How to expand Emmet abbreviations?

Emmet abbreviation and snippets are enabled by default for HTML, haml, jade, slim, jsx, XML, xsl, CSS, scss, sass, less and stylus files.

Mostly, the Tab key is used to complete the code abbreviation. We have to type the syntax and click the tab key to expand the abbreviations.

We expand the single HTML tag or even expand the hierarchy of HTML tag at the same time by clicking the tab key.

emmet-gif-01

An important change is that the Tab key is no longer the default way to expand Emmet abbreviations. Instead, Emmet abbreviations will now appear in the suggestion list. They can be selected like any other smart completion and on selection, the abbreviation will be expanded.

We can quickly view the Emmet abbreviation by clicking the info icon next to list shown. By typing text next to hash (#) will be taken as id and text next to the period(.) will be considered as a class name. Emmet basically works related to CSS selectors.

emmet-gif-02

And also we can create multiple lists of the same syntax with unique id as well.

emmet-gif-03

We can generate lorem ipsum text with the default number of words or a certain number of text by mentioning the word count.

emmet-gif-04

Let’s see some CSS abbreviation example as well

emmet-gif-05

To experience more HTML & CSS shortcode check this out link https://docs.emmet.io/cheat-sheet/ (The complete cheat sheet for HTML and CSS.)

Summary

I will be updating this same post regularly based on the new tips or tricks if I come across anything new.

Happy Coding!

Angular with Bootstrap

In this tutorial, we are going to use the angular and bootstrap to build an application.

We’ll be using angular to build the application and bootstrap to style the user interface.

You can get the source code of this tutorial from here.

Quick Access

You can get the source code of this tutorial from here.

To whom this tutorial?

If you are already familiar with the Angular framework. This tutorial will be a step by step process on how to add bootstrap style to your application.

If you are a beginner, this post will be an introduction session. – on how to create an angular application with angular CLI. And add bootstrap style to your application.

What is angular?

A framework for building client application in HTML, CSS and JavaScript/TypeScript.

Why Angular?

Why do we need to learn Angular? We can do the same in JavaScript or jQuery. Yes, we can complete most of the tasks using jQuery.

When the application becomes complex requirements, jQuery becomes hard to maintain the code.

We have lots of design patterns for JavaScript, but it’s hard for a beginner to start with design patterns.

When we create large complex applications using jQuery – it becomes hard to test. To make life easier a lot of frameworks arrived in the programming world to help the programmers.

Setting up the Environment

A quick start tool always helps the developer to save their valuable time.
And use those times in an efficient way of improving the quality of the application.

Angular provides us Angular CLI – which is a command-line interface tool.

Angular CLI can help to

  • create a project
  • add files
  • perform a variety of ongoing development tasks
  • testing
  • bundling
  • deployment

Using this CLI, we can create apps with a working condition that uses best practices suggested by Angular Team.

To create an Angular application using Angular CLI, all we need is to follow the below steps:

1. Install Node js and npm on your machine

Visit Node.js web page and download the installer. Once you’ve installed nodejs, the npm will get installed along with it.

2. Verify the compatible version

Angular CLI requires the minimal version of node and npm. But feel free to install the latest edition to explore the latest features.

We can check the version of the node and npm using the following commands.

node -v
npm -v

3. Install Angular CLI

Run the following command to install Angular CLI globally.

npm install -g @angular/cli

-g flag is used to install the package globally in the npm.

Once we installed CLI globally, we can confirm whether the tool installed by using the following command.

ng -v

Angular CLI

Angular CLI is one of the best tools available for angular.To set up the initial files or scaffolding structure of the application.

Setup

Once you have set up the basic software like node.js and npm. You can download CLI using the following command


npm install -g @angular/cli

Once installed we can check the version of angular CLI using the following command

ng version

One common argument every CLI has is help command. Here it is for you
ng help

Create a new Angular App

From your target empty folder, you need to run the following command to generate the basic files

ng new ng-bootstrap-demo

Make sure to replace ‘ng-bootstrap-demo’ with the name you prefer. This is will your application name.

Angular CLI - demo app

Angular CLI has lots of other options to help in setting the basic to advance files.

The CLI asks us to choose our required options based on our needs. Like routing and stylesheet type.

After installing the package, we are good to go with the debugging the new application.

You can check out some of our other posts related to angular CLI

Serving the project

Angular CLI provides a complete tool-chain for developing front-end apps.
As such, you don’t need to install a local server to serve your project.You can simply, use the ng serve command from your terminal to serve your project locally.

ng serve

The application will start serving in the root http://localhost:4200

ng serve

The default code provides following output

Adding Bootstrap to angular application

What is Bootstrap?

Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development.

It contains CSS- and JavaScript-based design templates for typography, forms, buttons, navigation, and other interface components.

We are going to use bootstrap in this tutorial but in a different way.

We’ll be using ng-bootstrap.

Angular widgets built from the ground up using only Bootstrap 4 CSS with APIs designed for the Angular ecosystem. No dependencies on 3rd party JavaScript.

Installation of ng-bootstrap

Before installing ng-bootstrap, let’s install bootstrap from npm.

Install bootstrap

npm install bootstrap

Add Bootstrap CSS or SCSS to your project

/* update your 'styles.css' with */
@import '~bootstrap/dist/css/bootstrap.css';


/* or your 'styles.scss' with */
@import "~bootstrap/scss/bootstrap";

The good news is we don’t have to add any bootstrap js to make an application now.

This is where ng-bootstrap comes into picture.

The goal of ng-bootstrap is to completely replace JavaScript implementation for components. Nor should you include other dependencies like jQuery or popper.js. It is not necessary and might interfere with ng-bootstrap code.

Add ng-bootstrap

Installing from npm 

npm install @ng-bootstrap/ng-bootstrap

Add ng-bootstrap module to main module

Once installed you need to import ng-bootstrap main module and you’re good to go

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { NgbModule } from "@ng-bootstrap/ng-bootstrap";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Alternatively you could only import modules with components you need, ex. pagination and alert. The resulting bundle will be smaller in this case.

import {NgbPaginationModule, NgbAlertModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  ...
  imports: [NgbPaginationModule, NgbAlertModule, ...],
  ...
})
export class YourAppModule {
}

All set!

We have added all basic needs of using bootstrap with angular.

Now let’s add some bootstrap components into application.

You can view the sample component in this documentation page.

Let’s Experiment

Lets add carousel component from ng-bootstrap.

Carousel

The Carousel component allows you to a display a selection of rotating images with a title, brief description and link to an associated story, event, program or project page elsewhere in your site.

Right now, app component contains default code generated by the CLI.

We are going to replace that code with carousel code as follows

<div class="container-fluid">
  <ngb-carousel *ngIf="images">
    <ng-template ngbSlide>
      <div class="picsum-img-wrapper">
        <img [src]="images[0]" alt="Random first slide">
      </div>
      <div class="carousel-caption">
        <h3>First slide label</h3>
        <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
      </div>
    </ng-template>
    <ng-template ngbSlide>
      <div class="picsum-img-wrapper">
        <img [src]="images[1]" alt="Random second slide">
      </div>
      <div class="carousel-caption">
        <h3>Second slide label</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
      </div>
    </ng-template>
    <ng-template ngbSlide>
      <div class="picsum-img-wrapper">
        <img [src]="images[2]" alt="Random third slide">
      </div>
      <div class="carousel-caption">
        <h3>Third slide label</h3>
        <p>Praesent commodo cursus magna, nisl consectetur.</p>
      </div>
    </ng-template>
  </ngb-carousel>
</div>

Carousels needs some images to display.

So we are going to pass the image Urls from app.compnent.ts

export class AppComponent {
  images = [944, 1011, 984]
    .map(
      (n) => `https://picsum.photos/id/${n}/1366/600`
    );
}

You can see the demo here – https://parigygap.github.stackblitz.io/

The output will look like the above.

The carousel will have controls to switch to next image as show in diagram.

The main reason behind using ng-bootstrap is – we don’t have write any scripts to perform these operations.

Tabset

This is a default tabset.

We can swtich between content and even disable content based on needs.

<ngb-tabset [destroyOnHide]="false">
  <ngb-tab title="Simple">
    <ng-template ngbTabContent>
      <p>Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth
      master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh
      dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum
      iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.</p>
    </ng-template>
  </ngb-tab>
  <ngb-tab>
    <ng-template ngbTabTitle><b>Fancy</b> title</ng-template>
    <ng-template ngbTabContent>Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid.
      <p>Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table
      craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl
      cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia
      yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean
      shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero
      sint qui sapiente accusamus tattooed echo park.</p>
    </ng-template>
  </ngb-tab>
  <ngb-tab title="Disabled" [disabled]="true">
    <ng-template ngbTabContent>
      <p>Sed commodo, leo at suscipit dictum, quam est porttitor sapien, eget sodales nibh elit id diam. Nulla facilisi. Donec egestas ligula vitae odio interdum aliquet. Duis lectus turpis, luctus eget tincidunt eu, congue et odio. Duis pharetra et nisl at faucibus. Quisque luctus pulvinar arcu, et molestie lectus ultrices et. Sed diam urna, egestas ut ipsum vel, volutpat volutpat neque. Praesent fringilla tortor arcu. Vivamus faucibus nisl enim, nec tristique ipsum euismod facilisis. Morbi ut bibendum est, eu tincidunt odio. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris aliquet odio ac lorem aliquet ultricies in eget neque. Phasellus nec tortor vel tellus pulvinar feugiat.</p>
    </ng-template>
  </ngb-tab>
</ngb-tabset>

Tabset Output

Date Picker

A simple picker requires lots of code when we are using basic HTML and Javscript.

Modern frameworks reduces a lots of code by introducing reusable components.

<h3>Date picker</h3>

  <p>Simple datepicker</p>

  <ngb-datepicker #dp
    [(ngModel)]="model"
    (navigate)="date = $event.next"></ngb-datepicker>

  <hr />

  <button class="btn btn-sm btn-outline-primary mr-2"
    (click)="selectToday()">
    Select Today
  </button>
  <button class="btn btn-sm btn-outline-primary mr-2"
    (click)="dp.navigateTo()">To current month</button>
  <button class="btn btn-sm btn-outline-primary mr-2"
    (click)="dp.navigateTo({year: 2013, month: 2})">To Feb
    2013</button>

  <hr />

  <pre>Month: {{ date.month }}.{{ date.year }}</pre>
  <pre>Model: {{ model | json }}</pre>

import { Component } from '@angular/core';
import { NgbDateStruct, NgbCalendar } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {

  model: NgbDateStruct;
  date: { year: number, month: number };

  constructor(private calendar: NgbCalendar) {
  }

  selectToday() {
    this.model = this.calendar.getToday();
  }
}

Date picker demo

Thanks for reading.

Happy Coding!

Angular 9 Tutorial for Beginners: Action Plan

What is Angular?

A framework for building client application in HTML, CSS and JavaScript/TypeScript.

Why Angular?

Why we need to learn Angular? We can do the same in JavaScript or jQuery. Yes, we can complete our most of the task using jQuery.

When the application becomes complex in terms of requirements, jQuery becomes hard to maintain the code. Even though we have lots of design patterns for JavaScript, its hard for beginner to start with design patterns.

When we create large complex application using jQuery – it becomes hard to test. To make life easier a lots of frameworks arrived in programming world to help the programmers.

Benefits of Angular

  • Its a component based framework which gives a clean structure for our application
  • It has Declarative templates which Includes lots of re-usable code
  • More testable code – supports to build lots of automated test
  • Dependency Injection – loads dependent objects (called the dependencies) when it creates an instance of an object.
  • We can write our code in either JavaScript or TypeScript – Angular Framework itself developed using TypeScript

Action Plan

In this tutorial, we are going to explore the basic concepts of angular first – step by step. And then we can move on to the advanced topics later on.

The plan is to help someone who are really new to angular. Beginners needs some simple step by step tutorial at the early stage. So we will discuss the basic concepts with code at first.

We are going to cover following topics in entire course. And I’m planning to add videos tutorial as well simultaneously. The action plan skeleton is

Introduction to the course

What is Angular?

Architecture of Angular

We have two main sections in Architecture

  • Front-end
  • Back-end

Front-end

In the front-end, we have built our UI using HTML, CSS, JavaScript or TypeScript. It contains HTML templates, Graphical representation, application presentation logic.

Back-end

Back-end Architecture contains the Business Logic, Data from Database or APIs.

In angular, we are not going to store any data in client side because once the session or cookies cleared everything will deleted.

We will use local storage or cookies in client side to store temporary data. The business logic or data are stored in database or APIs.

angular architecture
Angular skeleton

The key parts available in angular architecture are

  • Modules
  • Components
  • Templates
  • Directives
  • Data Binding
  • Services
  • Dependency Injection

We can discuss on each topic in upcoming posts.

overview
Angular over view

Setting up the Environment

In this post, we are going to discuss how to setup development environment and create an initial angular app using CLI.

A quick start tool is always helps the developer to save their valuable time and use those time in efficient way on improving the quality of the application.

Angular provides us Angular CLI which is a command line interface tool that can help to create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.

Using this CLI, we can create apps with a working condition which uses best practices suggested by Angular Team.

To create an Angular application using Angular CLI, all we need is to follow the below steps:

1. Install Node js and npm on your machine

Visit Node.js web page and download installer. Once you’ve installed nodejs, the npm will get installed along with it.

2. Verify the compatible version

Angular CLI requires the minimal version of node and npm. But feel free to install the latest edition to explore the latest features.

We can check the version of node and npm using following commands.

node -v

npm -v

3. Install Angular CLI

Run the following command to install Angular CLI globally.

npm install -g @angular/cli

-g flag is used to install the package globally in the npm.

Once we installed CLI globally, we can confirm whether the tool installed successfully by using the following command.

ng -v

StackBlitz

StackBlitz is an online IDE where you can create Angular & React projects that are immediately online & shareable via link… in just one click. It automatically takes care of installing dependencies, compiling, bundling, and hot reloading as you type.

StackBlitz is a tool in the Cloud IDE category of a tech stack.

Read more here for StackBlitz docs.

Additional Reading

Just read this if you really want to get deep insight about npm

As a part of learning angular, I would suggest everyone learn and understand the basic concept of npm

Maybe by finding answers for few of questions listed below

  • What is npm?
  • What is the role of npm?
  • How to use it?
  • Why we are going to use it?

So, what is npm?

npm – node package manager

Let’s split the sentence and understand the meaning present in the abbreviation.

Node

Here node.js is mentioned as the node. Node.js is a server-side JavaScript environment. It uses an asynchronous event-driven model and is designed for writing scalable Internet applications, notably web servers.

Package

Modules of code grouped up into a component which can be used in various project or application.

Manager

Managing the dependencies with the various operation like install, uninstall, update and so on.

Now, we can frame our own definition for npm from above split up an explanation. So using npm, we can manage (install, uninstall, organize) the node.js packages in our project.

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js.

npm has CLI terminal and website to search for packages.

What is the role of npm?

npm does N number of roles in various projects. I’m just mentioning the various steps which we are going to use in our upcoming posts in the end user developer point of view

  • install packages
  • uninstall packages
  • version maintenance of packages across the team
  • maintaining the dependencies

How to use it?

Simple, install Node.js

npm is distributed with Node.js- which means that when we download and install Node.js, we automatically get npm installed on our computer.

Using following command in terminal, we can check whether our toolset get installed successfully,

// to check node.js version
node -v

// to check npm version
npm -v

packages.json

What is this packages.json? this is one of the important things we should get familiar if we are going for use npm in our projects.

  • packages.json file is like the registry of packages in our project.
  • it lists the packages that our project depends on.
  • allows us to specify the versions of a package that our project can use using semantic versioning rules.

How to create packages.json file?

Open terminal with your target folder location.

Type npm init and Enter, now you’ll be caught up with few questions. After you have answered most of the question, your file will get created.

name and version fields are mandatory fields.

npm_cmd
npm init

If you are afraid of questions, we have another quick option.

Enter command npm init –yes

npm_cmd_2
npm init –yes

Using –yes argument option, the npm will create packages.json file with default values.

Install a package

npm install (in the package directory, no arguments) – Install the dependencies in the local node_modules folder.

In global mode (ie, with -g or --global appended to the command), it installs the current package context (ie, the current working directory) as a global package.

You can find detailed details of npm install options in this link

A package can be downloaded with the command:

npm install <package_name>

The --save and --save-dev install flags

The easier (and more awesome) way to add dependencies to your package.json is to do from the command line, flagging the npm install command with either --save or --save-dev, depending on how you’d like to use that dependency.

To add an entry to your package.json‘s dependencies:

npm install <package_name> --save

To add an entry to your package.json‘s devDependencies:

npm install <package_name> --save-dev

That’s it. Few lines have been copied from official documentation. :p

Let’s conclude, using npm we can manage number of packages in our projects easily.

Angular CLI

Angular CLI is one of the best tool available for angular to setup the initial files or scaffolding structure of the application.

Setup

Once you have setup the basic software like node.js and npm. You can download CLI using the following command

npm install -g @angular/cli

Once installed we can check the version of angular CLI using the following command

ng version

One common arguments every CLI has is help command. Here it is for you

ng help

Create new Angular App

From your target empty folder, you need to run the following command to generate the basic files/

ng new my-first-project

Make sure to replace ‘my-first-project’ with name you prefer. This is will your application name.

Angular CLI have lots of others option to help in setting the basic to advance files.

Available angular CLI commands

Available angular CLI commands By using command ng help, I’m getting the following information

ng help
ng help
  • add – Adds support for an external library to your project.
  • analytics – Configures the gathering of Angular CLI usage metrics. See https://v8.angular.io/cli/usage-analytics-gathering.
  • build (b) – Compiles an Angular app into an output directory named dist/ at the given output path. Must be executed from within a workspace directory.
  • deploy – Invokes the deploy builder for a specified project or for the default project in the workspace.
  • config – Retrieves or sets Angular configuration values in the angular.json file for the workspace.
  • doc (d) – Opens the official Angular documentation (angular.io) in a browser, and searches for a given keyword.
  • e2e (e) – Builds and serves an Angular app, then runs end-to-end tests using Protractor.
  • generate (g) – Generates and/or modifies files based on a schematic.
  • help – Lists available commands and their short descriptions.
  • lint (l) – Runs linting tools on Angular app code in a given project folder.
  • new (n) – Creates a new workspace and an initial Angular app.
  • run – Runs an Architect target with an optional custom builder configuration defined in your project.
  • serve (s) – Builds and serves your app, rebuilding on file changes.
  • test (t) – Runs unit tests in a project.
  • update – Updates your application and its dependencies. See https://update.angular.io/
  • version (v) – Outputs Angular CLI version.
  • xi18n (i18n-extract) – Extracts i18n messages from source code.

Creating new angular project

ng new timer-project
ng new
ng new

timer-project is name of project we chose.

The CLI asks us choose our required options based on our needs. Like routing and stylesheet type.

After installing package, we are good to go with debugging of the newly generated application. We can discuss about the project structure in our upcoming post.

You can checkout some of our other posts related to angular CLI

Serving the project

Angular CLI provides a complete tool-chain for developing front-end apps on your local machine. As such, you don’t need to install a local server to serve your project — you can simply, use the ng serve command from your terminal to serve your project locally.

ng serve

The application will start serving in the root http://localhost:4200

Generating angular schematic

Generates and/or modifies files based on a schematic.

ng generate <schematic> [options]
ng g <schematic> [options]

schematic can be replaced with following sets

  • appShell
  • application
  • class
  • component
  • directive
  • enum
  • guard
  • interceptor
  • interface
  • library
  • module
  • pipe
  • service
  • serviceWorker
  • webWorker

These commands is fair to start using angular CLI in beginner mode.

Your First Angular App

Structure of Angular Project

In the previous post, we have discussed how to create hello world application in angular. Using Angular CLI, we have generated basic files needed to run a hello world application.

Now, let’s have a quick look at the files and folders in our new Angular project.

The generated projects have the following files and folders structure

The top level of the workspace contains workspace-wide configuration files, configuration files for the root-level application, and subfolders for the root-level application source and test files.

Folder structure
Folder structure
WORKSPACE CONFIG FILESPURPOSE
.editorconfigConfiguration for code editors. See EditorConfig.
.gitignoreSpecifies intentionally untracked files that Git should ignore.
README.mdIntroductory documentation for the root app.
angular.jsonCLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses, such as TSLintKarma, and Protractor. For details, see Angular Workspace Configuration.
package.jsonConfigures npm package dependencies that are available to all projects in the workspace. See npm documentation for the specific format and contents of this file.
package-lock.jsonProvides version information for all packages installed into node_modules by the npm client. See npm documentation for details. If you use the yarn client, this file will be yarn.lock instead.
src/Source files for the root-level application project.
node_modules/Provides npm packages to the entire workspace. Workspace-wide node_modules dependencies are visible to all projects.
tsconfig.jsonDefault TypeScript configuration for projects in the workspace.
tslint.jsonDefault TSLint configuration for projects in the workspace.
Folder Details

Application source files

Files at the top level of src/ support testing and running your application. Subfolders contain the application source and application-specific configuration.

APP SUPPORT FILESPURPOSE
app/Contains the component files in which your application logic and data are defined. See details below.
assets/Contains image and other asset files to be copied as-is when you build your application.
environments/Contains build configuration options for particular target environments. By default there is an unnamed standard development environment and a production (“prod”) environment. You can define additional target environment configurations.
favicon.icoAn icon to use for this application in the bookmark bar.
index.htmlThe main HTML page that is served when someone visits your site. The CLI automatically adds all JavaScript and CSS files when building your app, so you typically don’t need to add any <script> or<link> tags here manually.
main.tsThe main entry point for your application. Compiles the application with the JIT compiler and bootstraps the application’s root module (AppModule) to run in the browser. You can also use the AOT compiler without changing any code by appending the --aot flag to the CLI build and serve commands.
polyfills.tsProvides polyfill scripts for browser support.
styles.sassLists CSS files that supply styles for a project. The extension reflects the style preprocessor you have configured for the project.
test.tsThe main entry point for your unit tests, with some Angular-specific configuration. You don’t typically need to edit this file.
Source Files

Inside the src/ folder, the app/ folder contains your project’s logic and data. Angular components, templates, and styles go here.

App folder
App Folder
SRC/APP/ FILESPURPOSE
app/app.component.tsDefines the logic for the app’s root component, named AppComponent. The view associated with this root component becomes the root of the view hierarchy as you add components and services to your application.
app/app.component.htmlDefines the HTML template associated with the root AppComponent.
app/app.component.cssDefines the base CSS stylesheet for the root AppComponent.
app/app.component.spec.tsDefines a unit test for the root AppComponent.
app/app.module.tsDefines the root module, named AppModule, that tells Angular how to assemble the application. Initially declares only the AppComponent. As you add more components to the app, they must be declared here.

Application configuration files

The application-specific configuration files for the root application reside at the workspace root level. For a multi-project workspace, project-specific configuration files are in the project root, under projects/project-name/.

Project-specific TypeScript configuration files inherit from the workspace-wide tsconfig.json, and project-specific TSLint configuration files inherit from the workspace-wide tslint.json.

APPLICATION-SPECIFIC CONFIG FILESPURPOSE
browserslistConfigures sharing of target browsers and Node.js versions among various front-end tools. See Browserslist on GitHub for more information.
karma.conf.jsApplication-specific Karma configuration.
tsconfig.app.jsonApplication-specific TypeScript configuration, including TypeScript and Angular template compiler options. See TypeScript Configuration and Angular Compiler Options.
tsconfig.spec.jsonTypeScript configuration for the application tests. See TypeScript Configuration.
tslint.jsonApplication-specific TSLint configuration.
Config files

Reference

https://angular.io/guide/file-structure


Yet to be added….!

Decorators

Life-cycle

Components

Templates

Directives

Services

Dependency Injection


Learning Approach

When you are following this course, try the top down approach to learn the concepts.

Once you are confident with the concepts, you can go to any topics to brush your knowledge.

Each and every topic will be covered in upcoming posts and hyperlinked will be added in the above topics.

What about Intermediate or Experts?

If you are already familiar with angular, these sessions can act as brush up session for you to revisit the technology.

We are planning to add more tutorials on angular later on to cover intermediate and expert audience.

Our plan is to build

  • CRUD application tutorial in angular
  • Full stack application in angular
  • Performance optimization sessions.

How to reach?

If you have doubts while trying out the concepts or any errors in your code. Feel free to add comments in respective post or tweet me in the twitter.

If you are learning angular using this post, please let me that you are here.

Its kind of sending virtual HI to me! Add a comment in comments section below or send me a tweet.

Hey, @pandiyan_cool I’m just checking out your angular tutorial course. So thought to send you a virtual hi 🙂

Happy Coding!

25+ Blogging Tools for 2020 (SEO, Traffic, Optimisation)

Even the simplest tool can empower the people to do great things.

If you are a blogger, then this post will definitely help you to prepare and enhance your content & it’s quality. (Pro Tip: bookmark it after reading).

This post is not limited to any particular niche of the blog. Whether you are a travel blogger, tech blogger or in any other niche – at least one of the tools mentioned below will help you to groom your content and traffic in your site.

I have used almost every tool listed, with minimum 1 week of time to explore key features.

I built this ultimate list or cheer sheet based on my personal experience.

Note that the order of tools doesn’t based on any rating or popularity and not doing this post to market any tool. The aim to help the fellow blogger to improve their content and strategy.

I will keep on updating this post whenever I explore new tools and think it is worth to be placed here. Make sure you comment on your favorite in the comments section to grow list into a massive cheat sheet for bloggers.

Cheat sheet of blogging tools

Editors

Notion One of my favorite tools which helps me to maintain my blog drafts, blog ideas, and various blog management task. It helps me to share the draft with my friends quickly with a quick magic link.

OneNote If you are working as a team, collaborating with the same document by a number of people is possible. OneNote is mainly a content management tool.

Grammarly – proof reading tool to check the spelling and grammar, mistake-free, and effective.

Images for blogs

Canva got plenty of templates that can be used as a featured image, blog illustration, and social media stories, etc.

Unsplash – The internet’s source of freely usable images. Powered by creators everywhere. And remember to give credit to the creator.

Pixabay – Find your perfect free image or video to download and use for anything. Free for commercial use.

Blog Reading

Use the following tools to follow fellow blogger as well as to research the content.

Feedly – It compiles news feeds from a variety of online sources for the user to customize and share with others.

Pocket – is an application and web service for managing a reading list of articles and videos from the Internet.

Reddit – Big database network which got plenty good user data and real-time users.

Content creation

GifCam – simple tool to convert the screen capture into GIFs

Make Web video – is a powerful web video production website which allows you to make Promotional Videos

Camtasia – simple to record and create professional-looking videos on Windows and Mac.

Analytics tool

Google analytics – lets you measure your advertising ROI as well as track your Flash, video, and social networking sites and applications.

Jetpack plugin – when you WordPress as your hosting platform jetpack is the right tool to check stats and analytics.

Social media marketing tools

Tweet Deck – simple tool to schedule tweets, but can used in browser only

Buffer – one of the favourite social media marketing tools to schedule posts. Supports Facebook, Twitter, Instagram and provides better time to post content on various mediums.

Clicktotweet – Whoever clicks on the link will have the message automatically added to their Twitter status box–they simply click to tweet!

Bit.ly – helps to shorten the long urls.

SEO & Research tool

Ubersuggest easy to use tool to research the keywords and traffic analysis. Ubersuggest provides an option to perform a site analysis as well, and also connecting with google console is available.

Yoast – is a search-optimization plug-in for WordPress. It has 5+ million active installations and has been downloaded more than 202 million times.

KWfinder – Find hundreds of hidden keywords with low SEO difficulty in seconds.

SEO Extension – Chrome extension to quickly check the page SEO – metrics, backlinks, on-page.

TubeBuddy – the must-have app for any YouTuber, this tool brings a good quality of analytics details and keywords details.

Google Webmaster – Track your site’s search performance with Google Search Console and our additional webmaster resources.

Email Marketing

MailChimp – a marketing automation platform and an email marketing service. Easy to deploy and collect the email of visitors to your site. We can run a campaign and Ads with help of MailChimp.

Time Tracking

TimeDoser – Chrome extension or timer to do the Pomodoro session effectively. (I love this tool, must try)

RescueTime – a time-management tool that provides intelligent insights into how you spend your days.

I will keep on updating this post whenever I explore new tools and think it is worth to be placed here. Make sure you comment on your favorite in the comments section to grow list into a massive cheat sheet for bloggers.

To get latest updates you can follow or subscribe! #peace

Feature image credit: Photo by Andrew Neel on Unsplash

Why build a Progressive Web Apps?

Want to know what is Progressive Web Apps(PWA)? Take a look here!

Building a high-quality Progressive Web App has incredible benefits, making it easy to delight your users, grow engagement and increase conversions.

  • Worthy of being on the home screen
  • Work reliably, no matter the network conditions
  • Increased engagement
  • Improved conversions

Worthy of being on the home screen

Is an app worthy to present in our home screen?

We need following qualities to answer YES for this question.

  • Reliable
  • Fast
  • Engaging

When the Progressive Web App criteria are met, Chrome prompts users to add the Progressive Web App to their home screen.

Actually, we use service workers to trigger installable shortcut based on our needs. Lets say, we are targeting only the mobile based users to install our PWA in their devices. We can detect the device based on browser and then we can prompt the user to install PWA apps.

Work reliably, no matter the network conditions

We have to handle various network conditions in PWA to meet the reliability.

The various connection modes are

  • Perfect
  • Slow
  • Lie-Fi
  • Offline

Increased Engagement

Web push notification helping a lot to provide the feel of native apps to keep the user engaged. And keeping the user more engaged once they visited the PWA application.

Improved conversions

The ability to deliver amazing experience without any distraction. Once the user started to use the application in dedicated window, it feels like native apps and there is less chance to jump to between other application similar to switching tabs in browser.

Lighthouse

Lighthouse, an open-source, automated tool for improving the quality of your Progressive Web Apps, eliminates much of the manual testing that was previously required. You can even use Lighthouse in continuous integration systems to catch regressions.

PWA Checklist

Lighthouse provides an chrome extension which provide helpful checklist that can be used to track of features of PWA.

Advantage of PWA over Native Apps

In the native application, the upgrade process is tedious or complex based on structure.

We need think of migration and data integrity, and we don’t have control at certain extent.

But in a PWA, we have control to all updates or upgrades to application. We can provide wide range of security fixes, bug fixes without any hesitation.

When we have SaaS platform application, PWA is the right combination of website with native application feel. User won’t have to worry about the upgrade scenarios. The developers will take of everything.

Popular Realtime Progressive Web Apps

There are plenty of popular websites converted their website into PWA to engaged more with their audience.

Dev.to

Dev.to is blogging or social forum where programmers share ideas and help each other grow.

They are displaying following canvas to users whenever the internet goes down. The user can paint in the meantime when the internet is trying to reconnect.

This has been achieved with the power of Progressive Web Apps.

Spotify

The popular music giant application which has large number of user base.

With all these things going on, it looked like Spotify was unable to resist the temptation and joined the race with their own version of Spotify PWA, despite having their own desktop app.

Your background colors are now adaptable to your needs as you progress through the PWA, making your experience more personalized and unique—as a music player should be.

Ola cabs

In the competitive ola cabs did the trick and leads the market over Uber by using PWA.

During installation time native apps (Apps from play store or Apple store), you can just open Ola cabs PWA and book your ride within.

You can save your mobile data and works well in unstable 3G network as well.

Sounds like a master plan.

Swiggy

Swiggy is an online food ordering app. It leads the market over Zomato by having adaptive screen in mobile devices.

Even though you have poor mobile network, the PWA works out of box and serves you the perfect needs of the user.

Can you spot difference between native app and Progressive Web App?


And lazy loading and service workers helps the website to load only required content instead downloading whole assets files.

Even though Swiggy and Zomato is popular in India. User feels Zomato is providing more offers than Swiggy.

Because they didn’t proper user engagement and mobile app user retention.

That’s the place Zomato losing the market with Swiggy (Based on my personal experience, I’m mentioning these point; not to offend anyone)

As a user of 2+ years in both apps, I prefer PWA app whenever I needed.

Pinterest

Pinterest – Infinite scrolling – never ending image social media

The design of this application itself makes the application user to stay for long time.

You would feel the difference between native app and web app (and also PWA)

Twitter

The popular social media which lets the people to write shorter and makes PWA to use the mobile data also shorter.

The following figure shows the application of Twitter client in various medium.

Take Away

We have seen various aspects of Progressive Web Apps. And the popular web application which uses the power of PWA to engage more with the user base. Do you think its worth to give a try and convert your web application into PWA?

Leave your replies in comment section below.

In the next blog, we can see the approaches to turn the Web Application into Progressive Web Apps (PWA).

Related Post

Why Progressive Web Apps is next big thing?

Progressive Web Apps – Web App Manifest

To get latest updates you can follow or subscribe! #peace

Why Progressive Web Apps is next big thing

A Progressive Web App (PWA) is a web app that uses modern web capabilities to deliver an app-like experience to users. These apps meet certain requirements, are deployed to servers, accessible through URLs, and indexed by search engines.

Progressive Web Apps are user experiences that have the reach of the web, and are:

  • Reliable
  • Fast
  • Engaging

Lets discuss the basic first.

Apps

Technically, apps got two categories

  • Native Apps
  • Web Apps

Native Apps are the apps which we used to download from play store or apple store or windows store. Native Apps are the apps which have developed to do operation of particular company or product.

Web Apps are the apps which we browse using the browser. Basically its a website, we browse and use it based on our needs.

PWA or Progressive Web Apps fills the gap between these techniques to provide more accessibility to end user and make engaging withing the product.

Target Audience

The world is moving towards portable devices. If we are building a application which basically serves via web browser, that can be build as PWA.

The above shows the Global User (Millions) of Internet. And we can clearly see the rise of mobile users drastically.

If we want to stay in the market, we need to support the latest technologies and adapt the same thing in our product.

PWA – FIRE

A Web Application should meet the FIRE to become Progressive Web Apps. And the FIRE is

  • F – Fast
  • I – Integrated
  • R – Reliable
  • E – Engaging

Fast

  • Respond quickly to user interactions with silky smooth animations and no janky scrolling.
  • So how fast a web app should load a page?
    • ~ < 3 seconds
  • 53% of users will abandon a site if it takes longer than 3 seconds to load! And once loaded, users expect them to be fast—no janky scrolling or slow-to-respond interfaces.

Bounce rate is 20% if your website takes more than 3.3 seconds to load.

And if your website takes more than 9.9 secs, the user have already started to leave your site.

Now, tell me how fast the websites we are developing/developed is loading?

Integrated Experience

Airhorner (https://airhorner.com/) is my favorite website which i used to show in demo whenever I go to public talks about PWA.

Any PWA should be really integrated in any platforms. Once it developed well adapted and integrated, the application will open in the dedicated window and let end users stays within the application without any distraction.

The integrated experience can be achieved with the help of Manifest. We already discussed about this earlier.

Reliable

Load instantly and never show the downasaur, even in uncertain network conditions.
When launched from the user’s home screen, service workers enable a Progressive Web App to load instantly, regardless of the network state.

Connection mode

Basically, we have following connection mode in Application

  • Perfect
  • Slow
  • Lie-fi
  • Offline

Perfect

When you are Perfect connection, everything happens as expected and you don’t have to worry about anything.

Slow

Slow is the one of the connection mode which suffers the user a lot. Everything will happen but not at the right time.

Lie-Fi

Lie-Fi is the connection mode which we usually experience in travel mode. There will be lots fluctuation in the connection type. Suddenly it goes to high and suddenly it goes very low.

Offline

When we are offline, we go mad.

A successful PWA should handle all kind of connection mode and keep the users engaged.

A user should get notified whenever connection is slow or unstable.

Engaging

A PWA should Feel like a natural app on the device, with an immersive user experience.

Progressive Web Apps are installable and live on the user’s home screen, without the need for an app store.

They offer an immersive full screen experience with help from a web app manifest file and can even re-engage users with web push notifications.

The Web App Manifest allows you to control how your app appears and how it’s launched. You can specify home screen icons, the page to load when the app is launched, screen orientation, and even whether or not to show the browser chrome.

Why build a Progressive Web App?

Building a high-quality Progressive Web App has incredible benefits, making it easy to delight your users, grow engagement and increase conversions.

  • Worthy of being on the home screen
  • Work reliably, no matter the network conditions
  • Increased engagement
  • Improved conversions

PWA of Twitter is just 0.6 MB.

What’s Next?

Approaches to making an web app into PWA

  • Offline first
  • Service workers
  • Indexed db and caching
  • Web App Manifest
  • Push notifications

We will discuss about these things in detail in upcoming posts.

Further Reading

Why build a Progressive Web Apps?

Progressive Web Apps – Web App Manifest

To get latest updates you can follow or subscribe! #peace

Technical Debt

Sometimes you might have came across the word Over-Engineering. The good programmer do that intentionally to avoid the technical debt.

Technical debt is a concept in software development that reflects the implied cost of additional rework caused by choosing an easy (limited) solution now instead of using a better approach that would take longer.

Boxing yourself with bad code.

Technical debt keep on raising when you are boxing with the bad code base. The main reason of technical debt is – we are attempting to solve a particular problem in our software with some shortcuts or some quick fix.

Refactoring is the key.

Source: Internet

Boxing with bad code will end up making the code base complex to do further changes or maintenance. Refactoring the code time to time will help to make the code more adaptive.

Quick Fix – No longer works

When we are doing a quick fix to any problem, we should aware that we have to accept technical debt we are making. Doing the similar stuff regularly will end up the code base into a worst place to visit.

At some point your code does not allow you to change anything. And you will break something when you attempt to create something or change something.

The increase in technical debt in the software will make the system more fragile. If you attempt to made any crucial fix which urgently needed, you can’t do that without breaking something. That’s the cost we will be paying as interest to the debt we were creating from the beginning time.

The common mistakes which leads to increase the technical debt

  • Urging into deadline without creating core components
  • Delivering MVP (Minimum Viable Product)
  • Working for Now moment
  • Bringing unaccomplished POC (Proof of Concept) into production

Hard Coding

You started killing your code when you started Hard-Coding.

It might sound crazy, hard-coding will make you to do multiple iteration when you are attempt to change something in the software.

Lets consider, you have a warning message throughout the application as “This request has been submitted successfully”. And you have used it in throughout the application in multiple places.

Suddenly, we need to change all the occurrence of warning message into something else. Lets say – “submitted successfully to server.”

Since it is a simple text, you have hard-coded throughout application. And also you have decided that it is going to straight-forward when it needs a change.

Actually it isn’t. So, what would be approach here. How you will be doing the text change in 100 places in your application?

  • Find and replace?
  • Regex to match text and replace?
  • Or by using some magic refactor tool?

Most of the above best cases would have failed if text is split in two lines or didn’t caught during the search. Earlier, I had used language translate service in my angular app.

The application would support multiple language or variant like US English, UK English, or some other language. So all the text which has been used in the application will be stored in the a particular json file.

If a Warning message has been used in 100 places in the application, this particular variable in the json file would serve as the source for all the messages in the entire application.

If I want to do a text change, I don’t have worry about much in changing as well as testing. Just think of just a text change would have cost this much time, how about touching core functionalities in the code base. So avoid hard-coding whenever possible.

Mi Smart Band 4 (Black)

Adaptive Code

Don’t do temporary solutions which will work only today and save your application from current bug which shows up.

Working for a temporary solution will increase the technical debt in code base.

Technically debt makes your code base easily breakable and you have to work harder to achieve even simple results or changes in the software.

Technical debts brings too much bugs which slows down building new features which dependent of existing code.

Think of all the important cases how the code can change in future. And Refactor the code if it going to accept massive change or new feature on top of it.

Source: Internet

Most of time, you can’t justify the code base needs Refactoring.

Every single time, we will get a question like

It works great, why should touch it? And you can justify your answer all the time.

As a architect or developer, one should think of the all possibilities how the code base might change in future. The one of the possible way to handle it is Adaptive Code.

Don’t Fit yourself inside user story

Think of adaptive code instead of just fulfilling or satisfying the current user story.

If your code doesn’t have any future purpose, never worry about it. Just build a adaptive which help you to improve yourself as well as improve the code base standard.

Earlier, we had discussed about the minimalist approaches which will help to build a quality code.

Building faster is pointless, when it isn’t build right. The art of saying No or YAGNI – “You Aren’t Gonna Need It” is an important skill in the software world. The software should not overflow with the features requested by everyone.

DRY – Instead of duplicating or repeating, just replace with abstraction – function or class

Keep your technical debt down, and deliver the deliverable on time.

We should decide which is emergency, if there is a bug in production which needs attention and a bug fix. That time we need to accept the debt and handle it in future. But we should make sure we should not consider a simple text change or minor new feature as technical debt.

Happy Coding!

To get latest updates you can follow or subscribe! #peace

References

Code Review best practices

Everyone has there own set of best practices. Here are the few points which I would like to share with you regarding the code review.

The aim of the code review is to build the team spirit, improve the code quality and collaborative learn the best practices.

One feature at a time

Make sure your CRR or commits are based on single feature or story or bug fix. Keeping multiple feature or bug fixes in a single code review request will create more confusion. So keep it simple.

Add members to review

Add everyone from team into in your code review request. At least 2 reviewers should review your code before it has been merged to the remote repository.

Information about what has been changed

Add information about what has been changed in the CRR. Add the related tickets/story/bug link in the CRR (in most of the cases). This will help the peer reviewers to get an insight or information about the task.

Notify the team

Send an Instant message to your team when the CRR request is sent or when the individual completes reviewing a particular request.

If you have any automated system like web hook or slack notification, thats fine. Otherwise, it’s OK to maintain a seperate channel or group to discuss about CRR.

Write it simple and clean

Keep the commit message concise & clear (if it is a bug fix mention it clearly).

When you are reviewing, look into the code and make sure you understand what code does actually; if there is any doubts/clarification needed highlight the code and add comments for clarification.

The aim is to have a readable code, so that remaining team members can also understand.

Be a advisor

If you find the code is difficult to understand or it could be even simpler feel free to suggest the better way to do that.

It’s a good habit to suggest something good instead of just mentioning that particular piece of code can be improved.

Maintain patience

Don’t urge to get your code get reviewed; Give some time to the reviewer and add a gentle reminder if it takes too long.

Be gentle

Stay humble, all these processes are to improve ourselves in a better way.

Code review process is to improve the code quality and build the team spirit in a better way. Collaboratively we can learn more from Code Reviews.

Happy Coding!

What’s new in Angular CLI 8.1?

Angular CLI 8.1 is released with lot of interesting changes.

This release includes brand new options for the various commands.

The official Node.js version that is supported for Angular CLI 8.0+ is 10.9 or greater.

Flag !

Lets look into the latest updates related to flags.

ng doc

It helps to open the official documentation in browser from CLI and also searched for given keyword.

For example, if you need to search for pipes relates documentation by passing pipes as keyword in ng doc command.

ng doc pipes

This will help us to open the related documentation in browser.

ng doc <keyword> –search

we additionally have the following options to this command

ng doc pipes --search=true|false

When search option is true, searches all of angular.io. Otherwise, searches only API reference documentation. Default: false

The similar option can simplified with alias -s as following

ng doc pipes --s=true

The command needs to be ran inside a angular project definition. Otherwise, we will get following error message in CLI

The doc command requires to be run in an Angular project, but a project definition could not be found.

ng doc pipes -s=false

ng doc pipes -s=true

You can compare difference search option flag values in above couple of images.

The command now also allows us to search for particular version of documents.

For example, we can search for documents related forms in angular version 6 using following command

ng doc form -s=false --version 6

If we didn’t specify any version during search, the command will search angular version you are using in your project.

ng generate component – -skip-selector

CLI version 8.1 brings an option to generate a component without any selectors.

--skip-selector

For example, the following command generates a component with selector

ng generate component sidebar

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

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

whereas, the following command with skip selector generates a component without selector

ng generate component sidebar-ws –skip-selector

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

@Component({
  templateUrl: './sidebar-ws.component.html',
  styleUrls: ['./sidebar-ws.component.css']
})
export class SidebarWsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

This new flag will be helpful when we are dealing with situation to create a component which doesn’t actually required a component.

Simple example, consider we need to redirect to error page when something went wrong in application. In that case, we simply redirect the page to specific component with help routing.

Thanks for reading. Please feel free to subscribe, share and support this blog.

Join 866 other followers

angular – copy to clipboard feature

We all came across this kind of feature – copy to clipboard.

Basically, the aim of this feature is to help the end user to quickly copy some text to clipboard. Instead of selecting particular text and clicking keyboard shortcut for copying text, some websites will provide us a icon to simplify the task.

Once we click that icon or button, the required text will get copy into the clipboard.

Pro Tip: Angular 9 brings separate module for clipboard feature. You can checkout it here.

I used copy to clipboard option most of the time in Github,

And that’s the base story.

Why?

Few months back, I was supposed to implement the same feature in one of my angular application.

I’m aware that how to do this feature in plain JavaScript. The typical copy function will look like the below snippet

But I hesitated to follow the same structure.

Analyzed existing npm packages

I have gone through various npm packages for copy clipboard with following features expectation in mind

  • Copy icon should get automatically created
  • Selection & Copy function should be generic
  • The code should reused and light weight
  • Minimal effort to implement

Most of the npm plugins available didn’t fulfilled my expectation.

The popular plugin expected the developer to create and pass the text which needs to copied to the copy to clipboard function.

For me, this looks weird!

If a paragraph is having 100 lines, sending those entire text to a plugin doesn’t make sense to me. So I decided to create a angular directive based on my expectation.

Later, I published it as a separate npm package. And the package name is

angular-clipboard-auto

How it works?

Installation

To install this library, run:

$ npm install angular-clipboard-auto --save

Consuming your library

Once you have published your library to npm, you can import your library in any Angular application by running:

$ npm install angular-clipboard-auto

and then from your Angular AppModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
 
// Import your library
import { ClipboardModule } from 'angular-clipboard-auto';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
 
    // Specify your library as an import
    ClipboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Once your library is imported, you can use its components, directives and pipes in your Angular application:

<!-- You can now use your library component in app.component.html -->
  
<!-- Add attribute appCopy in your html code -->
  
<input appCopy type="text" #text1 value="hello world">
  
<!-- And refer font awesome in your index.html to view copy symbol -->
  
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" crossorigin="anonymous">

That’s it!

TLTR;

All we have to do is

  • Add appCopy as attribute in text field HTML
  • Import fontawesome css

The copy icon will automatically get created next to your input field and you can use the feature right away.

The npm package will take care of all the background task seamlessly.

And also you can find the working copy of angular application in following path

https://stackblitz.com/edit/angular-clipboard

Sample snippet of HTML block

If you feel the implementation looks like, feel free to star ⭐️ the repository in GitHub and share with your friends.

Angular Clipboard Auto - Create a copy icon to your text element with one attribute. | Product Hunt Embed

Happy Coding!

What’s new in ASP.NET Core 2.2 – Web API improvements – API Analyzer

In the past post, we discussed the Web Improvements that have been released in the ASP.NET Core 2.2 preview. We have discussed how the creation, testing, and documentation of API has been improved in the ASP.NET Core release. Using Swagger gen, we created API documentation and also able to test our API application from the UI itself. On successful HTTP action, we usually get 200 status code and response from the API.
ASP.NET Core provides custom error response by default from 2.2 release. The error response includes TraceId to correlate to other response easily,
In the earlier post, we use SwashBuckle to generate swagger UI, but it isn’t able to determine all the possible response type of an HTTP method. For example, a post method can return 200, 400, 500 kinds of responses based on different input. Our documentation should cover most of the possible response type available in our API.
[ProducesResponseType(StatusCodes.Status400BadRequest)]
We shall specify the possible response type of each method in our Controller which will generate related documentation in the Swagger UI. But it will be a tedious process to analyze and add all the methods in our API. For this, ASP.NET Core 2.2 shipped an API Analyzer that will analyze the API actions and provide code fix that can be added in the code. We shall the package “Microsoft.AspNetCore.Mvc.Api.Analyzers” from Nuget Package manager
Once added API analyzer in our project, the analyzer starts showing the possible response type suggestion in warning window.
Instead of providing mentioning each response type on every action, we shall globally enable the API convention type with default conventions like below

[assembly: ApiConventionType(typeof(DefaultApiConventions))]
namespace APITest.Controllers
{
  ....
}
These DefaultApiConventions can also be extended and defined separately based on our needs. DefaultApiConventions covers some basic commonly used convention types in APIs.
using Microsoft.AspNetCore.Mvc.ApiExplorer;
namespace Microsoft.AspNetCore.Mvc
{
public static class DefaultApiConventions
{
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
public static void Create([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Any)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object model);
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ProducesResponseType(400)]
public static void Delete([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object id);
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(204)]
[ProducesResponseType(404)]
[ProducesResponseType(400)]
public static void Edit([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object id, [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Any)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object model);
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public static void Find([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object id);
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public static void Get([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object id);
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
public static void Post([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Any)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object model);
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(204)]
[ProducesResponseType(404)]
[ProducesResponseType(400)]
public static void Put([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object id, [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Any)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object model);
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
[ProducesDefaultResponseType]
[ProducesResponseType(204)]
[ProducesResponseType(404)]
[ProducesResponseType(400)]
public static void Update([ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object id, [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Any)][ApiConventionTypeMatch(ApiConventionTypeMatchBehavior.Any)] object model);
}
}
Based API conventions, now the swagger UI generates documentation of various response types and its sample inputs.
Documentation and testing become simpler in ASP.Net Core 2.2. Please try out for your API code, and leave your feedback in comment section. Happy Coding!

What’s new in ASP.NET Core 2.2 – Web API improvements – HTTP-REPL

On September 2018, .NET Core preview 2 has been released. Dot Net team keeping the Web API improvements as a major theme for this release.

The aim of web API improvements is to make API

  • Easier to create
  • Easier test and debug
  • Easier to document
  • Easier to consume
  • Easier to secure
  • Easier to monitor

API becomes part of a major software application, this release got major improvements to develop APIs and services.

In this post, we shall discuss the improvements made to APIs in terms of creating, debugging and testing.

We can build an API from scratch and let’s view what’s new in this release.

For doing these activities, I’m using Visual studio 2017 preview 2 in my machine. So make sure you are having the similar version to experiment the same.

Create an API Project

Let’s create a new project called “APITest” using the following steps

  • File -> New Project -> Choose ASP.NET Core Web Application under Web Category

http-repl-1

  • And in the next prompt select ASP.NET Core 2.2 in the topmost drop-down and click.

http-repl-2

Now, our API gets created with the default template. We will be having a controller called ValuesController.

Additionally to that, we shall create a new controller called EventController to perform our experiments.

Model

Before creating that controller, let’s create Event model and we can generate our Controller code based on the model we create.

Our Event model will look like below,

public class Event
{
public int Id { get; set; }
public string Organiser { get; set; }
public DateTime EventDate { get; set; }
}

view raw
Event.cs
hosted with ❤ by GitHub

So, we have our Model ready now. Let’s generate our Controller based on this Model.

Controller

  • Right click on Controller folder in solution explorer
  • Select Add
  • Click Controller
  • Choose Option “API Controller with actions, using Entity Framework”
  • Select Model class and DataContext using the plus symbol and Click Add

http-repl-3

http-repl-4

Once we have clicked the Visual studio will start scaffolding our new controller in a few seconds. And our controller will look like below

namespace APITest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{
private readonly EventContext _context;
public EventsController(EventContext context)
{
_context = context;
}
// GET: api/Events
[HttpGet]
public async Task<ActionResult<IEnumerable<Event>>> GetEvent()
{
return await _context.Event.ToListAsync();
}
// GET: api/Events/5
[HttpGet("{id}")]
public async Task<ActionResult<Event>> GetEvent(int id)
{
var @event = await _context.Event.FindAsync(id);
if (@event == null)
{
return NotFound();
}
return @event;
}
// PUT: api/Events/5
[HttpPut("{id}")]
public async Task<IActionResult> PutEvent(int id, Event @event)
{
if (id != @event.Id)
{
return BadRequest();
}
_context.Entry(@event).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EventExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Events
[HttpPost]
public async Task<ActionResult<Event>> PostEvent(Event @event)
{
_context.Event.Add(@event);
await _context.SaveChangesAsync();
return CreatedAtAction("GetEvent", new { id = @event.Id }, @event);
}
// DELETE: api/Events/5
[HttpDelete("{id}")]
public async Task<ActionResult<Event>> DeleteEvent(int id)
{
var @event = await _context.Event.FindAsync(id);
if (@event == null)
{
return NotFound();
}
_context.Event.Remove(@event);
await _context.SaveChangesAsync();
return @event;
}
private bool EventExists(int id)
{
return _context.Event.Any(e => e.Id == id);
}
}
}

view raw
EventsController.cs
hosted with ❤ by GitHub

So, all set with API setup. Whenever we create an API, we will run the application and open the API link in the browser window.

If it is a GET call its fine, but when we need to make POST call or something we need another set of tools to perform testing. In that case, the browser is not the best tool to perform testing in the API.

In .NET Core 2.2, a new tool called HTTP-REPL has been introduced. It’s a .NET Core global which we can install using the dotnet CLI.

HTTP-REPL is a command line tool to interact with API.

Right now, the tool is not shipped with this release. However, we install using the following steps.

How to install HTTP-REPL

Run the following command in command prompt to install in global level in your machine

dotnet tool install -g dotnet-httprepl --version 2.2.0-* --add-source https://dotnet.myget.org/F/dotnet-core/api/v3/index.json

Once installed, we can verify the installation using the following command

http-repl-5

we can run http-repl using the command

dotnet httprepl

And we can point to any API which has swagger enabled to try out by setting the base URL.

Let’s not do that now, we can experiment the tool with the API which we created.

Add HTTP-REPL in Web browser list

Instead of opening the command and traversing to the API URL, we can launch our application into Repl right from our Visual Studio IDE.

For that, we need to add the Repl in the Web browser list.

http-repl-6

To Add in web browser list, click browse with the option and click Add and fill the required as follows.

http-repl-7

http-repl exe will present in the following path

C:\Users\<>\.dotnet\tools\dotnet-httprepl.exe

Once added, set it as default web browser.

And update your default launchUrl as empty or remove that settings from launchSettings.json

{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:32022",
"sslPort": 44384
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"APITest": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

view raw
launchSettings.json
hosted with ❤ by GitHub

Launch the application

As we have added EF in our API, let’s add migration before launching the application.

Run the following command in Package Manager Console (Tools->Nuget Package Manger->Package Manager Console)

Add-Migration Initial
Update-Database

Click F5 or click IIS express in the toolbar to launch

http-repl-8.png

After launching the application, we can test our API endpoint right from our Repl command prompt.

Let’s add Open API spec

To make HTTP Repl more accessible, we can add swagger Open API Spec. So that Repl will get to know the available HTTP methods and info in the application.

Let’s add swagger generation with the help open source project Swashbuckle.AspNetCore

Right click on the project and click Manage Nuget package and install Swashbuckle

http-repl-9.PNG

Once installed

In the ConfigureServices method of Startup.cs, register the Swagger generator, defining one or more Swagger documents.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Events API", Version = "v1" });
});

In the Configure method, insert middleware to expose the generated Swagger as JSON endpoint(s)

app.UseSwagger();

At this point, you can spin up your application and view the generated Swagger JSON at “/swagger/v1/swagger.json.”

Optionally insert the swagger-ui middleware if you want to expose interactive documentation, specifying the Swagger JSON endpoint(s) to power it from.

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Events API V1");
});

All Set!!!

The command ls will list the routes API as well the HTTP methods available in that particular.

http-repl-10

The command UI will launch the swagger UI page and open in the browser.

https://localhost:44384/api/Events~ ui

http-repl-11

POST call

Let’s post some values using Repl. For making post calls we need to register some text or code editor.

For example, using the following command we can set a default editor

pref set editor.command.default "C:\Windows\System32\notepad.exe"

Once we have set the default editor, we can make post call as follows by typing command POST

http-repl-12

 

The target editor will default placeholder to fill the data, we can fill up the JSON data, save the file and close it. And also we set header with command line argument -h, the tool got some nice autocomplete feature.

Once closed, the POST call gets called with the data we submit.

http-repl-13

 

Get call

We can make GET call as follows,

http-repl-14

Cool! That’s it for now. we can discuss API Analyzer in the next post.

Happy Coding!

ASP.NET Core 2.2.0-preview1 – Web templates update

The first preview of the next minor release of ASP.NET Core and .NET Core is available from Aug 21, 2018. The new .NET Core SDK of 2.2.0-preview1 can be downloaded from here.

We need Preview of Visual Studio 2017 – 15.9 Preview 1 to work with .NET Core 2.2 projects.

Whats new in 2.2?

.NET Core listed the following features in their documentation. Now, there is no much information regarding the features in details. They will be publishing detailed information about features soon and hyperlinking that documentation in the same release page.

The new features have been discussed in the ASP.NET Community Standup call.

 

In this post, I would like to discuss updated web templates. Even though we need Visual Studio Preview to work with ASP.NET Core Projects. I have used VS Code to discuss the web templates in this post.

Current Version

Before upgrading the SDK, I wanted to check the current version of the .NET Core with the command.


dotnet --version

version

We can download the .NET Core 2.2 SDK from the link,

https://www.microsoft.com/net/download/dotnet-core/2.2

We can download and start Installation based on our system environment.

SDK

Once installed we can check whether the latest version is available or not with the same command which we have earlier in this post.

SDK2

Now, dotnet version is updated the 2.2.1 preview 🙂

Let’s create a web application

Using dotnet CLI, we can create the application from the command prompt right away. Following is the syntax to create an application


dotnet new  [--force] [-i|--install] [-lang|--language] [-n|--name] [--nuget-source] [-o|--output]
[-u|--uninstall] [Template options]
dotnet new  [-l|--list] [--type]
dotnet new [-h|--help]

 

If we have any doubts in the arguments we can use flag –help to list the available arguments to that particular command. dotnet template engine will display the commands.

For example,

dotnet new --help

The above command lists the available templates in this version

args.png

Using the help of commands, we can create n number of application with the various application with different themes.

MVC web templates

For now, let’s explore whats new in MVC and angular web templates.

To explore MVC web templates, we can go ahead and create an MVC application using dotnet CLI from the and prompt with the owing command.


dotnet new mvc

Once the command executed, the CLI will create the required files for the MVC application and it will start to restore the dependencies as the post-creation actions.

mvc

The files have been generated with the following structure,

mvc-2.png

DotNet completed optimized this folder and file structure, and they have placed an only minimal code in the starter template. The main aim of this optimization is to provide a quick starter template for the user to get started with the project.

Even though we have a separate template to create an empty project, its always good to have a very minimal set of code with some working example in the project.

So the team has provided the very small set of code in this latest version templates if the user wants to override or delete the existing pages and getting started with the new project. That can be achieved with less number of deleting the existing code.

Let’s run the application and see how the new UI has been designed with command

dotnet run

 

mvc-3

The latest UI looks so clean, there are no such components – Jumbotron in the first half of page, 4 or 5 pages with user login feature. We are having only 2-page links here.

And as you see there is a default option to place the cookie accept policy details. Once the user clicks the Accept button, the message gets hidden and a flag is getting added in the browser cache. Until the user clears the browser for this particular web page, the message won’t show to the user again. That’s a helpful feature IMHO.

We 2 links called page 1, page 2 here, but those are not working in this preview release. In the standup call, the team provided the news that it will be fixed in the main release. And the team is looking for the feedback from the community to improve the templates.

I think we should add sidebar as an optional flag, we can let the user decide whether they need it or not. We don’t have to put it in the default templates page.

 

Angular web templates

Now, let’s explore the angular application web template.

We can follow the same approach

dotnet new angular
dotnet run

 

The angular web templates come up with following folder structure

spa.png

When we run the latest angular application template, we have got following UI pages,

angularangular1angular2

In the Home page, we have information about the single page application on what are all the UI framework and technology used in the application like –

In the counter page, we have a button and counter whenever we click the button the counter provides the number of clicks information.

In the Fetch date page, we have a table with bootstrap styles.

 

Bootstrap is fine here, but I wish the angular material design should get included as an optional flag. It will be great if have the material design support in the dotnet CLI itself.

That’s for now, thanks for reading.

Happy Coding!

 

7 common mistakes by newbie bloggers

Choosing the domain

Choosing the wrong domain name or free domain. Picking the right domain name based on niche will help Visitors to remember easily & relate with content.

Mixing up niche

Don’t mix up the blog topics too much. Decide your niche clearly. If your blog is focused on programming, food or lifestyle. Mixing up niche will discourage recurring visitors. If you really want to cover multiple niche – maintain proper category.

Write consistently

Consistency is the key. Make proper plan, write and schedule the Content. If you can write one post in a week or two week. Just go with it and schedule post accordingly. One of my favorite blogger posts Content on every Tuesday and Friday.

Copying content without giving credits

If you are referring and copying a part of sentence from another site. Give proper credits in your post. And also never copy paste entire content. Respect others work.

Never to hesitate to write small post

Never hesitate to write “How To” kind of post. If it solves a rare problem, even if it is a small post. It will get more traction. Even my blog have such kind of posts which gains me more traffic and tops at Google search.

Avoid grammatical mistakes

N number of online free tools available to check the spelling mistakes and grammatical mistakes. I myself did these kind of mistakes at start of my blogging journey. Sometimes my friends read it and message me to correct it.

Have your own style of writing

Prepare your own way of presentation. Design your own content delivery technique and the social media sharing schedules.

Happy blogging!

Credits

Photo by Andrew Neel on Unsplash

Photo by Markus Winkler on Unsplash

Photo by Bench Accounting on Unsplash

Photo by NeONBRAND on Unsplash

Photo by Daniela Holzer on Unsplash

Create a CSK Jersey with your name

Are you a fan of CSK? Ok this post is for us. Its time to support our CSK team in this IPL season.

I’m great fan of CSK as well as THALA Dhoni. So I created this CSK Jersey image with the help of MovieFontsMaker website.

Looks great! Don’t it?

Here is another one with super talented Raina image.

How to do it?

Here is the quick steps to generate your CSK Jersey.

1. Goto to MovieFontsMaker website

Click here to go to CSK homepage.

2.Select your favourite template

3. Fillup your details

4. Download the image

What’ Next?

Time to cheer up our team and enjoy the match.

#CSK #WhistlePodu

One more

https://linksind.net/dhonicustomizeddp/

Credits

http://www.moviefontsmaker.com/ for providing us this great template. Thanks!