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 368 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.

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 --&gt;
 
<!-- Add attribute appCopy in your html code --&gt;
 
<input appCopy type="text" #text1 value="hello world"&gt;
 
<!-- And refer font awesome in your index.html to view copy symbol --&gt;
 
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"&gt;

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.

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.
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,

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

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

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!

 

Quick steps to import and debug angular GitHub repository in StackBlitz

StackBlitz is an online IDE where you can create Angular & React projects that are immediately online & shareable via link.

It provides option to open any public repo into it and debug immediately.

You can run any public repo on GitHub by providing the username + repo name like so:

stackblitz.com/github/{GH_USERNAME}/{REPO_NAME}

And you can also optionally specify a branch, tag, or commit:

…/github/{GH_USERNAME}/{REPO_NAME}/tree/{TAG|BRANCH|COMMIT}

Automatically stays in sync with your repo

Whenever you push commits to Github, the corresponding StackBlitz project automatically updates with the latest changes — ensuring Github remains your code’s source of truth.

For example,

If we have angular repo like below

https://github.com/PandiyanCool/thirukural

This can be framed as following URL

https://stackblitz.com/github/PandiyanCool/thirukural

Advertisements
Advertisements